blob: b6262b7f964d7609f5712d7d2486570255b4197c [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodec"
19#include <utils/Log.h>
20
21#include <sstream>
22#include <thread>
23
24#include <C2Config.h>
25#include <C2Debug.h>
26#include <C2ParamInternal.h>
27#include <C2PlatformSupport.h>
28
Pawin Vongmasa36653902018-11-15 00:10:25 -080029#include <android/IOMXBufferSource.h>
Pawin Vongmasabf69de92019-10-29 06:21:27 -070030#include <android/hardware/media/c2/1.0/IInputSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
32#include <android/hardware/media/omx/1.0/IOmx.h>
33#include <android-base/stringprintf.h>
34#include <cutils/properties.h>
35#include <gui/IGraphicBufferProducer.h>
36#include <gui/Surface.h>
37#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070038#include <media/omx/1.0/WOmxNode.h>
39#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080040#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070041#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
42#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070043#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080044#include <media/stagefright/BufferProducerWrapper.h>
45#include <media/stagefright/MediaCodecConstants.h>
46#include <media/stagefright/PersistentSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080047
48#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080049#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070050#include "CCodecConfig.h"
Wonsik Kimfb7a7672019-12-27 17:13:33 -080051#include "Codec2Mapper.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080052#include "InputSurfaceWrapper.h"
53
54extern "C" android::PersistentSurface *CreateInputSurface();
55
56namespace android {
57
58using namespace std::chrono_literals;
59using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
60using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080061using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080062
Wonsik Kim9917d4a2019-10-24 12:56:38 -070063typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070064typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070065
Pawin Vongmasa36653902018-11-15 00:10:25 -080066namespace {
67
68class CCodecWatchdog : public AHandler {
69private:
70 enum {
71 kWhatWatch,
72 };
73 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
74
75public:
76 static sp<CCodecWatchdog> getInstance() {
77 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
78 static std::once_flag flag;
79 // Call Init() only once.
80 std::call_once(flag, Init, instance);
81 return instance;
82 }
83
84 ~CCodecWatchdog() = default;
85
86 void watch(sp<CCodec> codec) {
87 bool shouldPost = false;
88 {
89 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
90 // If a watch message is in flight, piggy-back this instance as well.
91 // Otherwise, post a new watch message.
92 shouldPost = codecs->empty();
93 codecs->emplace(codec);
94 }
95 if (shouldPost) {
96 ALOGV("posting watch message");
97 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
98 }
99 }
100
101protected:
102 void onMessageReceived(const sp<AMessage> &msg) {
103 switch (msg->what()) {
104 case kWhatWatch: {
105 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
106 ALOGV("watch for %zu codecs", codecs->size());
107 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
108 sp<CCodec> codec = it->promote();
109 if (codec == nullptr) {
110 continue;
111 }
112 codec->initiateReleaseIfStuck();
113 }
114 codecs->clear();
115 break;
116 }
117
118 default: {
119 TRESPASS("CCodecWatchdog: unrecognized message");
120 }
121 }
122 }
123
124private:
125 CCodecWatchdog() : mLooper(new ALooper) {}
126
127 static void Init(const sp<CCodecWatchdog> &thiz) {
128 ALOGV("Init");
129 thiz->mLooper->setName("CCodecWatchdog");
130 thiz->mLooper->registerHandler(thiz);
131 thiz->mLooper->start();
132 }
133
134 sp<ALooper> mLooper;
135
136 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
137};
138
139class C2InputSurfaceWrapper : public InputSurfaceWrapper {
140public:
141 explicit C2InputSurfaceWrapper(
142 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
143 mSurface(surface) {
144 }
145
146 ~C2InputSurfaceWrapper() override = default;
147
148 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
149 if (mConnection != nullptr) {
150 return ALREADY_EXISTS;
151 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800152 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800153 }
154
155 void disconnect() override {
156 if (mConnection != nullptr) {
157 mConnection->disconnect();
158 mConnection = nullptr;
159 }
160 }
161
162 status_t start() override {
163 // InputSurface does not distinguish started state
164 return OK;
165 }
166
167 status_t signalEndOfInputStream() override {
168 C2InputSurfaceEosTuning eos(true);
169 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800170 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800171 if (err != C2_OK) {
172 return UNKNOWN_ERROR;
173 }
174 return OK;
175 }
176
177 status_t configure(Config &config __unused) {
178 // TODO
179 return OK;
180 }
181
182private:
183 std::shared_ptr<Codec2Client::InputSurface> mSurface;
184 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
185};
186
187class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
188public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700189 typedef hardware::media::omx::V1_0::Status OmxStatus;
190
Pawin Vongmasa36653902018-11-15 00:10:25 -0800191 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700192 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800193 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700194 uint32_t height,
195 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800196 : mSource(source), mWidth(width), mHeight(height) {
197 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700198 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800199 }
200 ~GraphicBufferSourceWrapper() override = default;
201
202 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
203 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700204 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800205 mNode->setFrameSize(mWidth, mHeight);
206
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700207 // Usage is queried during configure(), so setting it beforehand.
208 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
209 (void)mNode->setParameter(
210 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
211 &usage, sizeof(usage));
212
Pawin Vongmasa36653902018-11-15 00:10:25 -0800213 // NOTE: we do not use/pass through color aspects from GraphicBufferSource as we
214 // communicate that directly to the component.
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;
251 // WORKAROUND: having more slots improve performance while consuming
252 // more memory. This is a temporary workaround to reduce memory for
253 // larger-than-4K scenario.
254 if (mWidth * mHeight > 4096 * 2340) {
255 constexpr OMX_U32 kPortIndexInput = 0;
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900256
Wonsik Kim0f6b61d2021-01-05 18:55:22 -0800257 OMX_PARAM_PORTDEFINITIONTYPE param;
258 param.nPortIndex = kPortIndexInput;
259 status_t err = mNode->getParameter(OMX_IndexParamPortDefinition,
260 &param, sizeof(param));
261 if (err == OK) {
262 numSlots = param.nBufferCountActual;
263 }
Taehwan Kim8b3bcdd2020-11-26 22:40:40 +0900264 }
265
266 for (size_t i = 0; i < numSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800267 source->onInputBufferAdded(i);
268 }
269
270 source->onOmxExecuting();
271 return OK;
272 }
273
274 status_t signalEndOfInputStream() override {
275 return GetStatus(mSource->signalEndOfInputStream());
276 }
277
278 status_t configure(Config &config) {
279 std::stringstream status;
280 status_t err = OK;
281
282 // handle each configuration granually, in case we need to handle part of the configuration
283 // elsewhere
284
285 // TRICKY: we do not unset frame delay repeating
286 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
287 int64_t us = 1e6 / config.mMinFps + 0.5;
288 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
289 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
290 if (res != OK) {
291 status << " (=> " << asString(res) << ")";
292 err = res;
293 }
294 mConfig.mMinFps = config.mMinFps;
295 }
296
297 // pts gap
298 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
299 if (mNode != nullptr) {
300 OMX_PARAM_U32TYPE ptrGapParam = {};
301 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700302 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800303 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
304 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700305 // float -> uint32_t is undefined if the value is negative.
306 // First convert to int32_t to ensure the expected behavior.
307 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800308 (void)mNode->setParameter(
309 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
310 &ptrGapParam, sizeof(ptrGapParam));
311 }
312 }
313
314 // max fps
315 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700316 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800317 && config.mMaxFps != mConfig.mMaxFps) {
318 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
319 status << " maxFps=" << config.mMaxFps;
320 if (res != OK) {
321 status << " (=> " << asString(res) << ")";
322 err = res;
323 }
324 mConfig.mMaxFps = config.mMaxFps;
325 }
326
327 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
328 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
329 status << " timeOffset " << config.mTimeOffsetUs << "us";
330 if (res != OK) {
331 status << " (=> " << asString(res) << ")";
332 err = res;
333 }
334 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
335 }
336
337 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
338 status_t res =
339 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
340 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
341 if (res != OK) {
342 status << " (=> " << asString(res) << ")";
343 err = res;
344 }
345 mConfig.mCaptureFps = config.mCaptureFps;
346 mConfig.mCodedFps = config.mCodedFps;
347 }
348
349 if (config.mStartAtUs != mConfig.mStartAtUs
350 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
351 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
352 status << " start at " << config.mStartAtUs << "us";
353 if (res != OK) {
354 status << " (=> " << asString(res) << ")";
355 err = res;
356 }
357 mConfig.mStartAtUs = config.mStartAtUs;
358 mConfig.mStopped = config.mStopped;
359 }
360
361 // suspend-resume
362 if (config.mSuspended != mConfig.mSuspended) {
363 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
364 status << " " << (config.mSuspended ? "suspend" : "resume")
365 << " at " << config.mSuspendAtUs << "us";
366 if (res != OK) {
367 status << " (=> " << asString(res) << ")";
368 err = res;
369 }
370 mConfig.mSuspended = config.mSuspended;
371 mConfig.mSuspendAtUs = config.mSuspendAtUs;
372 }
373
374 if (config.mStopped != mConfig.mStopped && config.mStopped) {
375 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
376 status << " stop at " << config.mStopAtUs << "us";
377 if (res != OK) {
378 status << " (=> " << asString(res) << ")";
379 err = res;
380 } else {
381 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700382 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
383 [&res, &delayUs = config.mInputDelayUs](
384 auto status, auto stopTimeOffsetUs) {
385 res = static_cast<status_t>(status);
386 delayUs = stopTimeOffsetUs;
387 });
388 if (!trans.isOk()) {
389 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
390 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800391 if (res != OK) {
392 status << " (=> " << asString(res) << ")";
393 } else {
394 status << "=" << config.mInputDelayUs << "us";
395 }
396 mConfig.mInputDelayUs = config.mInputDelayUs;
397 }
398 mConfig.mStopAtUs = config.mStopAtUs;
399 mConfig.mStopped = config.mStopped;
400 }
401
402 // color aspects (android._color-aspects)
403
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700404 // consumer usage is queried earlier.
405
Wonsik Kimbd557932019-07-02 15:51:20 -0700406 if (status.str().empty()) {
407 ALOGD("ISConfig not changed");
408 } else {
409 ALOGD("ISConfig%s", status.str().c_str());
410 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800411 return err;
412 }
413
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700414 void onInputBufferDone(c2_cntr64_t index) override {
415 mNode->onInputBufferDone(index);
416 }
417
Pawin Vongmasa36653902018-11-15 00:10:25 -0800418private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700419 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800420 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700421 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800422 uint32_t mWidth;
423 uint32_t mHeight;
424 Config mConfig;
425};
426
427class Codec2ClientInterfaceWrapper : public C2ComponentStore {
428 std::shared_ptr<Codec2Client> mClient;
429
430public:
431 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
432 : mClient(client) { }
433
434 virtual ~Codec2ClientInterfaceWrapper() = default;
435
436 virtual c2_status_t config_sm(
437 const std::vector<C2Param *> &params,
438 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
439 return mClient->config(params, C2_MAY_BLOCK, failures);
440 };
441
442 virtual c2_status_t copyBuffer(
443 std::shared_ptr<C2GraphicBuffer>,
444 std::shared_ptr<C2GraphicBuffer>) {
445 return C2_OMITTED;
446 }
447
448 virtual c2_status_t createComponent(
449 C2String, std::shared_ptr<C2Component> *const component) {
450 component->reset();
451 return C2_OMITTED;
452 }
453
454 virtual c2_status_t createInterface(
455 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
456 interface->reset();
457 return C2_OMITTED;
458 }
459
460 virtual c2_status_t query_sm(
461 const std::vector<C2Param *> &stackParams,
462 const std::vector<C2Param::Index> &heapParamIndices,
463 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
464 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
465 }
466
467 virtual c2_status_t querySupportedParams_nb(
468 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
469 return mClient->querySupportedParams(params);
470 }
471
472 virtual c2_status_t querySupportedValues_sm(
473 std::vector<C2FieldSupportedValuesQuery> &fields) const {
474 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
475 }
476
477 virtual C2String getName() const {
478 return mClient->getName();
479 }
480
481 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
482 return mClient->getParamReflector();
483 }
484
485 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
486 return std::vector<std::shared_ptr<const C2Component::Traits>>();
487 }
488};
489
490} // namespace
491
492// CCodec::ClientListener
493
494struct CCodec::ClientListener : public Codec2Client::Listener {
495
496 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
497
498 virtual void onWorkDone(
499 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800500 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800501 (void)component;
502 sp<CCodec> codec(mCodec.promote());
503 if (!codec) {
504 return;
505 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800506 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800507 }
508
509 virtual void onTripped(
510 const std::weak_ptr<Codec2Client::Component>& component,
511 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
512 ) override {
513 // TODO
514 (void)component;
515 (void)settingResult;
516 }
517
518 virtual void onError(
519 const std::weak_ptr<Codec2Client::Component>& component,
520 uint32_t errorCode) override {
521 // TODO
522 (void)component;
523 (void)errorCode;
524 }
525
526 virtual void onDeath(
527 const std::weak_ptr<Codec2Client::Component>& component) override {
528 { // Log the death of the component.
529 std::shared_ptr<Codec2Client::Component> comp = component.lock();
530 if (!comp) {
531 ALOGE("Codec2 component died.");
532 } else {
533 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
534 }
535 }
536
537 // Report to MediaCodec.
538 sp<CCodec> codec(mCodec.promote());
539 if (!codec || !codec->mCallback) {
540 return;
541 }
542 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
543 }
544
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800545 virtual void onFrameRendered(uint64_t bufferQueueId,
546 int32_t slotId,
547 int64_t timestampNs) override {
548 // TODO: implement
549 (void)bufferQueueId;
550 (void)slotId;
551 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800552 }
553
554 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800555 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800556 sp<CCodec> codec(mCodec.promote());
557 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800558 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800559 }
560 }
561
562private:
563 wp<CCodec> mCodec;
564};
565
566// CCodecCallbackImpl
567
568class CCodecCallbackImpl : public CCodecCallback {
569public:
570 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
571 ~CCodecCallbackImpl() override = default;
572
573 void onError(status_t err, enum ActionCode actionCode) override {
574 mCodec->mCallback->onError(err, actionCode);
575 }
576
577 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
578 mCodec->mCallback->onOutputFramesRendered(
579 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
580 }
581
Pawin Vongmasa36653902018-11-15 00:10:25 -0800582 void onOutputBuffersChanged() override {
583 mCodec->mCallback->onOutputBuffersChanged();
584 }
585
586private:
587 CCodec *mCodec;
588};
589
590// CCodec
591
592CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700593 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
594 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800595}
596
597CCodec::~CCodec() {
598}
599
600std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
601 return mChannel;
602}
603
604status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
605 status_t err = job();
606 if (err != C2_OK) {
607 mCallback->onError(err, ACTION_CODE_FATAL);
608 }
609 return err;
610}
611
612void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
613 auto setAllocating = [this] {
614 Mutexed<State>::Locked state(mState);
615 if (state->get() != RELEASED) {
616 return INVALID_OPERATION;
617 }
618 state->set(ALLOCATING);
619 return OK;
620 };
621 if (tryAndReportOnError(setAllocating) != OK) {
622 return;
623 }
624
625 sp<RefBase> codecInfo;
626 CHECK(msg->findObject("codecInfo", &codecInfo));
627 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
628
629 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
630 allocMsg->setObject("codecInfo", codecInfo);
631 allocMsg->post();
632}
633
634void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
635 if (codecInfo == nullptr) {
636 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
637 return;
638 }
639 ALOGD("allocate(%s)", codecInfo->getCodecName());
640 mClientListener.reset(new ClientListener(this));
641
642 AString componentName = codecInfo->getCodecName();
643 std::shared_ptr<Codec2Client> client;
644
645 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700646 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800647 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800648 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800649 SetPreferredCodec2ComponentStore(
650 std::make_shared<Codec2ClientInterfaceWrapper>(client));
651 }
652
653 std::shared_ptr<Codec2Client::Component> comp =
654 Codec2Client::CreateComponentByName(
655 componentName.c_str(),
656 mClientListener,
657 &client);
658 if (!comp) {
659 ALOGE("Failed Create component: %s", componentName.c_str());
660 Mutexed<State>::Locked state(mState);
661 state->set(RELEASED);
662 state.unlock();
663 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
664 state.lock();
665 return;
666 }
667 ALOGI("Created component [%s]", componentName.c_str());
668 mChannel->setComponent(comp);
669 auto setAllocated = [this, comp, client] {
670 Mutexed<State>::Locked state(mState);
671 if (state->get() != ALLOCATING) {
672 state->set(RELEASED);
673 return UNKNOWN_ERROR;
674 }
675 state->set(ALLOCATED);
676 state->comp = comp;
677 mClient = client;
678 return OK;
679 };
680 if (tryAndReportOnError(setAllocated) != OK) {
681 return;
682 }
683
684 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700685 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
686 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800687 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800688 if (err != OK) {
689 ALOGW("Failed to initialize configuration support");
690 // TODO: report error once we complete implementation.
691 }
692 config->queryConfiguration(comp);
693
694 mCallback->onComponentAllocated(componentName.c_str());
695}
696
697void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
698 auto checkAllocated = [this] {
699 Mutexed<State>::Locked state(mState);
700 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
701 };
702 if (tryAndReportOnError(checkAllocated) != OK) {
703 return;
704 }
705
706 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
707 msg->setMessage("format", format);
708 msg->post();
709}
710
711void CCodec::configure(const sp<AMessage> &msg) {
712 std::shared_ptr<Codec2Client::Component> comp;
713 auto checkAllocated = [this, &comp] {
714 Mutexed<State>::Locked state(mState);
715 if (state->get() != ALLOCATED) {
716 state->set(RELEASED);
717 return UNKNOWN_ERROR;
718 }
719 comp = state->comp;
720 return OK;
721 };
722 if (tryAndReportOnError(checkAllocated) != OK) {
723 return;
724 }
725
726 auto doConfig = [msg, comp, this]() -> status_t {
727 AString mime;
728 if (!msg->findString("mime", &mime)) {
729 return BAD_VALUE;
730 }
731
732 int32_t encoder;
733 if (!msg->findInt32("encoder", &encoder)) {
734 encoder = false;
735 }
736
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800737 int32_t flags;
738 if (!msg->findInt32("flags", &flags)) {
739 return BAD_VALUE;
740 }
741
Pawin Vongmasa36653902018-11-15 00:10:25 -0800742 // TODO: read from intf()
743 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
744 return UNKNOWN_ERROR;
745 }
746
747 int32_t storeMeta;
748 if (encoder
749 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
750 && storeMeta != kMetadataBufferTypeInvalid) {
751 if (storeMeta != kMetadataBufferTypeANWBuffer) {
752 ALOGD("Only ANW buffers are supported for legacy metadata mode");
753 return BAD_VALUE;
754 }
755 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
756 }
757
758 sp<RefBase> obj;
759 sp<Surface> surface;
760 if (msg->findObject("native-window", &obj)) {
761 surface = static_cast<Surface *>(obj.get());
762 setSurface(surface);
763 }
764
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700765 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
766 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800767 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800768 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
769 ALOGD("[%s] buffers are %sbound to CCodec for this session",
770 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800771
Wonsik Kim1114eea2019-02-25 14:35:24 -0800772 // Enforce required parameters
773 int32_t i32;
774 float flt;
775 if (config->mDomain & Config::IS_AUDIO) {
776 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
777 ALOGD("sample rate is missing, which is required for audio components.");
778 return BAD_VALUE;
779 }
780 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
781 ALOGD("channel count is missing, which is required for audio components.");
782 return BAD_VALUE;
783 }
784 if ((config->mDomain & Config::IS_ENCODER)
785 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
786 && !msg->findInt32(KEY_BIT_RATE, &i32)
787 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
788 ALOGD("bitrate is missing, which is required for audio encoders.");
789 return BAD_VALUE;
790 }
791 }
792 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
793 if (!msg->findInt32(KEY_WIDTH, &i32)) {
794 ALOGD("width is missing, which is required for image/video components.");
795 return BAD_VALUE;
796 }
797 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
798 ALOGD("height is missing, which is required for image/video components.");
799 return BAD_VALUE;
800 }
801 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700802 int32_t mode = BITRATE_MODE_VBR;
803 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700804 if (!msg->findInt32(KEY_QUALITY, &i32)) {
805 ALOGD("quality is missing, which is required for video encoders in CQ.");
806 return BAD_VALUE;
807 }
808 } else {
809 if (!msg->findInt32(KEY_BIT_RATE, &i32)
810 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
811 ALOGD("bitrate is missing, which is required for video encoders.");
812 return BAD_VALUE;
813 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800814 }
815 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
816 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
817 ALOGD("I frame interval is missing, which is required for video encoders.");
818 return BAD_VALUE;
819 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700820 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
821 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
822 ALOGD("frame rate is missing, which is required for video encoders.");
823 return BAD_VALUE;
824 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800825 }
826 }
827
Pawin Vongmasa36653902018-11-15 00:10:25 -0800828 /*
829 * Handle input surface configuration
830 */
831 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
832 && (config->mDomain & Config::IS_ENCODER)) {
833 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
834 {
835 config->mISConfig->mMinFps = 0;
836 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800837 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800838 config->mISConfig->mMinFps = 1e6 / value;
839 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700840 if (!msg->findFloat(
841 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
842 config->mISConfig->mMaxFps = -1;
843 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800844 config->mISConfig->mMinAdjustedFps = 0;
845 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800846 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800847 if (value < 0 && value >= INT32_MIN) {
848 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700849 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800850 } else if (value > 0 && value <= INT32_MAX) {
851 config->mISConfig->mMinAdjustedFps = 1e6 / value;
852 }
853 }
854 }
855
856 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700857 bool captureFpsFound = false;
858 double timeLapseFps;
859 float captureRate;
860 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
861 config->mISConfig->mCaptureFps = timeLapseFps;
862 captureFpsFound = true;
863 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
864 config->mISConfig->mCaptureFps = captureRate;
865 captureFpsFound = true;
866 }
867 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800868 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
869 }
870 }
871
872 {
873 config->mISConfig->mSuspended = false;
874 config->mISConfig->mSuspendAtUs = -1;
875 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800876 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800877 config->mISConfig->mSuspended = true;
878 }
879 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700880 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800881 }
882
883 /*
884 * Handle desired color format.
885 */
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700886 int32_t defaultColorFormat = COLOR_FormatYUV420Flexible;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800887 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700888 int32_t format = 0;
889 // Query vendor format for Flexible YUV
890 std::vector<std::unique_ptr<C2Param>> heapParams;
891 C2StoreFlexiblePixelFormatDescriptorsInfo *pixelFormatInfo = nullptr;
892 if (mClient->query(
893 {},
894 {C2StoreFlexiblePixelFormatDescriptorsInfo::PARAM_TYPE},
895 C2_MAY_BLOCK,
896 &heapParams) == C2_OK
897 && heapParams.size() == 1u) {
898 pixelFormatInfo = C2StoreFlexiblePixelFormatDescriptorsInfo::From(
899 heapParams[0].get());
900 } else {
901 pixelFormatInfo = nullptr;
902 }
903 std::optional<uint32_t> flexPixelFormat{};
904 std::optional<uint32_t> flexPlanarPixelFormat{};
905 std::optional<uint32_t> flexSemiPlanarPixelFormat{};
906 if (pixelFormatInfo && *pixelFormatInfo) {
907 for (size_t i = 0; i < pixelFormatInfo->flexCount(); ++i) {
908 const C2FlexiblePixelFormatDescriptorStruct &desc =
909 pixelFormatInfo->m.values[i];
910 if (desc.bitDepth != 8
911 || desc.subsampling != C2Color::YUV_420
912 // TODO(b/180076105): some device report wrong layout
913 // || desc.layout == C2Color::INTERLEAVED_PACKED
914 // || desc.layout == C2Color::INTERLEAVED_ALIGNED
915 || desc.layout == C2Color::UNKNOWN_LAYOUT) {
916 continue;
917 }
918 if (!flexPixelFormat) {
919 flexPixelFormat = desc.pixelFormat;
920 }
921 if (desc.layout == C2Color::PLANAR_PACKED && !flexPlanarPixelFormat) {
922 flexPlanarPixelFormat = desc.pixelFormat;
923 }
924 if (desc.layout == C2Color::SEMIPLANAR_PACKED && !flexSemiPlanarPixelFormat) {
925 flexSemiPlanarPixelFormat = desc.pixelFormat;
926 }
927 }
928 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800929 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700930 // Also handle default color format (encoders require color format, so this is only
931 // needed for decoders.
Pawin Vongmasa36653902018-11-15 00:10:25 -0800932 if (!(config->mDomain & Config::IS_ENCODER)) {
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700933 if (surface == nullptr) {
934 format = flexPixelFormat.value_or(COLOR_FormatYUV420Flexible);
935 } else {
936 format = COLOR_FormatSurface;
937 }
938 defaultColorFormat = format;
939 }
940 } else {
941 if ((config->mDomain & Config::IS_ENCODER) || !surface) {
942 switch (format) {
943 case COLOR_FormatYUV420Flexible:
944 format = flexPixelFormat.value_or(COLOR_FormatYUV420Planar);
945 break;
946 case COLOR_FormatYUV420Planar:
947 case COLOR_FormatYUV420PackedPlanar:
948 format = flexPlanarPixelFormat.value_or(
949 flexPixelFormat.value_or(format));
950 break;
951 case COLOR_FormatYUV420SemiPlanar:
952 case COLOR_FormatYUV420PackedSemiPlanar:
953 format = flexSemiPlanarPixelFormat.value_or(
954 flexPixelFormat.value_or(format));
955 break;
956 default:
957 // No-op
958 break;
959 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800960 }
961 }
962
Wonsik Kimd79ee1f2020-08-27 17:41:56 -0700963 if (format != 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800964 msg->setInt32("android._color-format", format);
965 }
966 }
967
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800968 int32_t subscribeToAllVendorParams;
969 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
970 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
971 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
972 }
973 }
974
Pawin Vongmasa36653902018-11-15 00:10:25 -0800975 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800976 // NOTE: We used to ignore "video-bitrate" at configure; replicate
977 // the behavior here.
978 sp<AMessage> sdkParams = msg;
979 int32_t videoBitrate;
980 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
981 sdkParams = msg->dup();
982 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
983 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800984 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800985 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800986 if (err != OK) {
987 ALOGW("failed to convert configuration to c2 params");
988 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700989
990 int32_t maxBframes = 0;
991 if ((config->mDomain & Config::IS_ENCODER)
992 && (config->mDomain & Config::IS_VIDEO)
993 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
994 && maxBframes > 0) {
995 std::unique_ptr<C2StreamGopTuning::output> gop =
996 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
997 gop->m.values[0] = { P_FRAME, UINT32_MAX };
998 gop->m.values[1] = {
999 C2Config::picture_type_t(P_FRAME | B_FRAME),
1000 uint32_t(maxBframes)
1001 };
1002 configUpdate.push_back(std::move(gop));
1003 }
1004
Pawin Vongmasa36653902018-11-15 00:10:25 -08001005 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
1006 if (err != OK) {
1007 ALOGW("failed to configure c2 params");
1008 return err;
1009 }
1010
1011 std::vector<std::unique_ptr<C2Param>> params;
1012 C2StreamUsageTuning::input usage(0u, 0u);
1013 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001014 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001015
1016 std::initializer_list<C2Param::Index> indices {
1017 };
1018 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001019 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -08001020 indices,
1021 C2_DONT_BLOCK,
1022 &params);
1023 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
1024 ALOGE("Failed to query component interface: %d", c2err);
1025 return UNKNOWN_ERROR;
1026 }
1027 if (params.size() != indices.size()) {
1028 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
1029 indices.size(), params.size());
1030 return UNKNOWN_ERROR;
1031 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001032 if (usage) {
1033 if (usage.value & C2MemoryUsage::CPU_READ) {
1034 config->mInputFormat->setInt32("using-sw-read-often", true);
1035 }
1036 if (config->mISConfig) {
1037 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
1038 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
1039 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001040 }
1041
1042 // NOTE: we don't blindly use client specified input size if specified as clients
1043 // at times specify too small size. Instead, mimic the behavior from OMX, where the
1044 // client specified size is only used to ask for bigger buffers than component suggested
1045 // size.
1046 int32_t clientInputSize = 0;
1047 bool clientSpecifiedInputSize =
1048 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
1049 // TEMP: enforce minimum buffer size of 1MB for video decoders
1050 // and 16K / 4K for audio encoders/decoders
1051 if (maxInputSize.value == 0) {
1052 if (config->mDomain & Config::IS_AUDIO) {
1053 maxInputSize.value = encoder ? 16384 : 4096;
1054 } else if (!encoder) {
1055 maxInputSize.value = 1048576u;
1056 }
1057 }
1058
1059 // verify that CSD fits into this size (if defined)
1060 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
1061 sp<ABuffer> csd;
1062 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
1063 if (csd && csd->size() > maxInputSize.value) {
1064 maxInputSize.value = csd->size();
1065 }
1066 }
1067 }
1068
1069 // TODO: do this based on component requiring linear allocator for input
1070 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
1071 if (clientSpecifiedInputSize) {
1072 // Warn that we're overriding client's max input size if necessary.
1073 if ((uint32_t)clientInputSize < maxInputSize.value) {
1074 ALOGD("client requested max input size %d, which is smaller than "
1075 "what component recommended (%u); overriding with component "
1076 "recommendation.", clientInputSize, maxInputSize.value);
1077 ALOGW("This behavior is subject to change. It is recommended that "
1078 "app developers double check whether the requested "
1079 "max input size is in reasonable range.");
1080 } else {
1081 maxInputSize.value = clientInputSize;
1082 }
1083 }
1084 // Pass max input size on input format to the buffer channel (if supplied by the
1085 // component or by a default)
1086 if (maxInputSize.value) {
1087 config->mInputFormat->setInt32(
1088 KEY_MAX_INPUT_SIZE,
1089 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1090 }
1091 }
1092
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001093 int32_t clientPrepend;
1094 if ((config->mDomain & Config::IS_VIDEO)
1095 && (config->mDomain & Config::IS_ENCODER)
1096 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1097 && clientPrepend
1098 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1099 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1100 return BAD_VALUE;
1101 }
1102
Pawin Vongmasa36653902018-11-15 00:10:25 -08001103 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1104 // propagate HDR static info to output format for both encoders and decoders
1105 // if component supports this info, we will update from component, but only the raw port,
1106 // so don't propagate if component already filled it in.
1107 sp<ABuffer> hdrInfo;
1108 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1109 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1110 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1111 }
1112
1113 // Set desired color format from configuration parameter
1114 int32_t format;
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001115 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
1116 format = defaultColorFormat;
1117 }
1118 if (config->mDomain & Config::IS_ENCODER) {
1119 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
1120 if (msg->findInt32("android._color-format", &format)) {
1121 config->mInputFormat->setInt32("android._color-format", format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001122 }
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001123 } else {
1124 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001125 }
1126 }
1127
1128 // propagate encoder delay and padding to output format
1129 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1130 int delay = 0;
1131 if (msg->findInt32("encoder-delay", &delay)) {
1132 config->mOutputFormat->setInt32("encoder-delay", delay);
1133 }
1134 int padding = 0;
1135 if (msg->findInt32("encoder-padding", &padding)) {
1136 config->mOutputFormat->setInt32("encoder-padding", padding);
1137 }
1138 }
1139
1140 // set channel-mask
1141 if (config->mDomain & Config::IS_AUDIO) {
1142 int32_t mask;
1143 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1144 if (config->mDomain & Config::IS_ENCODER) {
1145 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1146 } else {
1147 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1148 }
1149 }
1150 }
1151
1152 ALOGD("setup formats input: %s and output: %s",
1153 config->mInputFormat->debugString().c_str(),
1154 config->mOutputFormat->debugString().c_str());
1155 return OK;
1156 };
1157 if (tryAndReportOnError(doConfig) != OK) {
1158 return;
1159 }
1160
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001161 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1162 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001163
1164 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1165}
1166
1167void CCodec::initiateCreateInputSurface() {
1168 status_t err = [this] {
1169 Mutexed<State>::Locked state(mState);
1170 if (state->get() != ALLOCATED) {
1171 return UNKNOWN_ERROR;
1172 }
1173 // TODO: read it from intf() properly.
1174 if (state->comp->getName().find("encoder") == std::string::npos) {
1175 return INVALID_OPERATION;
1176 }
1177 return OK;
1178 }();
1179 if (err != OK) {
1180 mCallback->onInputSurfaceCreationFailed(err);
1181 return;
1182 }
1183
1184 (new AMessage(kWhatCreateInputSurface, this))->post();
1185}
1186
Lajos Molnar47118272019-01-31 16:28:04 -08001187sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1188 using namespace android::hardware::media::omx::V1_0;
1189 using namespace android::hardware::media::omx::V1_0::utils;
1190 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1191 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1192 android::sp<IOmx> omx = IOmx::getService();
1193 typedef android::hardware::graphics::bufferqueue::V1_0::
1194 IGraphicBufferProducer HGraphicBufferProducer;
1195 typedef android::hardware::media::omx::V1_0::
1196 IGraphicBufferSource HGraphicBufferSource;
1197 OmxStatus s;
1198 android::sp<HGraphicBufferProducer> gbp;
1199 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001200
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001201 using ::android::hardware::Return;
1202 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001203 [&s, &gbp, &gbs](
1204 OmxStatus status,
1205 const android::sp<HGraphicBufferProducer>& producer,
1206 const android::sp<HGraphicBufferSource>& source) {
1207 s = status;
1208 gbp = producer;
1209 gbs = source;
1210 });
1211 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001212 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001213 }
1214
1215 return nullptr;
1216}
1217
1218sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1219 sp<PersistentSurface> surface(CreateInputSurface());
1220
1221 if (surface == nullptr) {
1222 surface = CreateOmxInputSurface();
1223 }
1224
1225 return surface;
1226}
1227
Pawin Vongmasa36653902018-11-15 00:10:25 -08001228void CCodec::createInputSurface() {
1229 status_t err;
1230 sp<IGraphicBufferProducer> bufferProducer;
1231
1232 sp<AMessage> inputFormat;
1233 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001234 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001235 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001236 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1237 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001238 inputFormat = config->mInputFormat;
1239 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001240 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001241 }
1242
Lajos Molnar47118272019-01-31 16:28:04 -08001243 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001244 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1245 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1246 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001247
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001248 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001249 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1250 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001251 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001252 inputSurface));
1253 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001254 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001255 int32_t width = 0;
1256 (void)outputFormat->findInt32("width", &width);
1257 int32_t height = 0;
1258 (void)outputFormat->findInt32("height", &height);
1259 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001260 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001261 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001262 } else {
1263 ALOGE("Corrupted input surface");
1264 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1265 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001266 }
1267
1268 if (err != OK) {
1269 ALOGE("Failed to set up input surface: %d", err);
1270 mCallback->onInputSurfaceCreationFailed(err);
1271 return;
1272 }
1273
1274 mCallback->onInputSurfaceCreated(
1275 inputFormat,
1276 outputFormat,
1277 new BufferProducerWrapper(bufferProducer));
1278}
1279
1280status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001281 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1282 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001283 config->mUsingSurface = true;
1284
1285 // we are now using surface - apply default color aspects to input format - as well as
1286 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001287 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001288 ALOGD("input format %s to %s",
1289 inputFormatChanged ? "changed" : "unchanged",
1290 config->mInputFormat->debugString().c_str());
1291
1292 // configure dataspace
1293 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1294 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1295 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1296 surface->setDataSpace(dataSpace);
1297
1298 status_t err = mChannel->setInputSurface(surface);
1299 if (err != OK) {
1300 // undo input format update
1301 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001302 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001303 return err;
1304 }
1305 config->mInputSurface = surface;
1306
1307 if (config->mISConfig) {
1308 surface->configure(*config->mISConfig);
1309 } else {
1310 ALOGD("ISConfig: no configuration");
1311 }
1312
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001313 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001314}
1315
1316void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1317 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1318 msg->setObject("surface", surface);
1319 msg->post();
1320}
1321
1322void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1323 sp<AMessage> inputFormat;
1324 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001325 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001326 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001327 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1328 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001329 inputFormat = config->mInputFormat;
1330 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001331 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001332 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001333 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1334 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1335 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1336 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001337 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1338 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1339 if (err != OK) {
1340 ALOGE("Failed to set up input surface: %d", err);
1341 mCallback->onInputSurfaceDeclined(err);
1342 return;
1343 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001344 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001345 int32_t width = 0;
1346 (void)outputFormat->findInt32("width", &width);
1347 int32_t height = 0;
1348 (void)outputFormat->findInt32("height", &height);
1349 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001350 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001351 if (err != OK) {
1352 ALOGE("Failed to set up input surface: %d", err);
1353 mCallback->onInputSurfaceDeclined(err);
1354 return;
1355 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001356 } else {
1357 ALOGE("Failed to set input surface: Corrupted surface.");
1358 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1359 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001360 }
1361 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1362}
1363
1364void CCodec::initiateStart() {
1365 auto setStarting = [this] {
1366 Mutexed<State>::Locked state(mState);
1367 if (state->get() != ALLOCATED) {
1368 return UNKNOWN_ERROR;
1369 }
1370 state->set(STARTING);
1371 return OK;
1372 };
1373 if (tryAndReportOnError(setStarting) != OK) {
1374 return;
1375 }
1376
1377 (new AMessage(kWhatStart, this))->post();
1378}
1379
1380void CCodec::start() {
1381 std::shared_ptr<Codec2Client::Component> comp;
1382 auto checkStarting = [this, &comp] {
1383 Mutexed<State>::Locked state(mState);
1384 if (state->get() != STARTING) {
1385 return UNKNOWN_ERROR;
1386 }
1387 comp = state->comp;
1388 return OK;
1389 };
1390 if (tryAndReportOnError(checkStarting) != OK) {
1391 return;
1392 }
1393
1394 c2_status_t err = comp->start();
1395 if (err != C2_OK) {
1396 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1397 ACTION_CODE_FATAL);
1398 return;
1399 }
1400 sp<AMessage> inputFormat;
1401 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001402 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001403 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001404 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001405 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1406 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001408 // start triggers format dup
1409 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001410 if (config->mInputSurface) {
1411 err2 = config->mInputSurface->start();
1412 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001413 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001414 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001415 if (err2 != OK) {
1416 mCallback->onError(err2, ACTION_CODE_FATAL);
1417 return;
1418 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001419 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001420 if (err2 != OK) {
1421 mCallback->onError(err2, ACTION_CODE_FATAL);
1422 return;
1423 }
1424
1425 auto setRunning = [this] {
1426 Mutexed<State>::Locked state(mState);
1427 if (state->get() != STARTING) {
1428 return UNKNOWN_ERROR;
1429 }
1430 state->set(RUNNING);
1431 return OK;
1432 };
1433 if (tryAndReportOnError(setRunning) != OK) {
1434 return;
1435 }
1436 mCallback->onStartCompleted();
1437
1438 (void)mChannel->requestInitialInputBuffers();
1439}
1440
1441void CCodec::initiateShutdown(bool keepComponentAllocated) {
1442 if (keepComponentAllocated) {
1443 initiateStop();
1444 } else {
1445 initiateRelease();
1446 }
1447}
1448
1449void CCodec::initiateStop() {
1450 {
1451 Mutexed<State>::Locked state(mState);
1452 if (state->get() == ALLOCATED
1453 || state->get() == RELEASED
1454 || state->get() == STOPPING
1455 || state->get() == RELEASING) {
1456 // We're already stopped, released, or doing it right now.
1457 state.unlock();
1458 mCallback->onStopCompleted();
1459 state.lock();
1460 return;
1461 }
1462 state->set(STOPPING);
1463 }
1464
Wonsik Kim936a89c2020-05-08 16:07:50 -07001465 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001466 (new AMessage(kWhatStop, this))->post();
1467}
1468
1469void CCodec::stop() {
1470 std::shared_ptr<Codec2Client::Component> comp;
1471 {
1472 Mutexed<State>::Locked state(mState);
1473 if (state->get() == RELEASING) {
1474 state.unlock();
1475 // We're already stopped or release is in progress.
1476 mCallback->onStopCompleted();
1477 state.lock();
1478 return;
1479 } else if (state->get() != STOPPING) {
1480 state.unlock();
1481 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1482 state.lock();
1483 return;
1484 }
1485 comp = state->comp;
1486 }
1487 status_t err = comp->stop();
1488 if (err != C2_OK) {
1489 // TODO: convert err into status_t
1490 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1491 }
1492
1493 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001494 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1495 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001496 if (config->mInputSurface) {
1497 config->mInputSurface->disconnect();
1498 config->mInputSurface = nullptr;
1499 }
1500 }
1501 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001502 Mutexed<State>::Locked state(mState);
1503 if (state->get() == STOPPING) {
1504 state->set(ALLOCATED);
1505 }
1506 }
1507 mCallback->onStopCompleted();
1508}
1509
1510void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001511 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001512 {
1513 Mutexed<State>::Locked state(mState);
1514 if (state->get() == RELEASED || state->get() == RELEASING) {
1515 // We're already released or doing it right now.
1516 if (sendCallback) {
1517 state.unlock();
1518 mCallback->onReleaseCompleted();
1519 state.lock();
1520 }
1521 return;
1522 }
1523 if (state->get() == ALLOCATING) {
1524 state->set(RELEASING);
1525 // With the altered state allocate() would fail and clean up.
1526 if (sendCallback) {
1527 state.unlock();
1528 mCallback->onReleaseCompleted();
1529 state.lock();
1530 }
1531 return;
1532 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001533 if (state->get() == STARTING
1534 || state->get() == RUNNING
1535 || state->get() == STOPPING) {
1536 // Input surface may have been started, so clean up is needed.
1537 clearInputSurfaceIfNeeded = true;
1538 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001539 state->set(RELEASING);
1540 }
1541
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001542 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001543 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1544 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001545 if (config->mInputSurface) {
1546 config->mInputSurface->disconnect();
1547 config->mInputSurface = nullptr;
1548 }
1549 }
1550
Wonsik Kim936a89c2020-05-08 16:07:50 -07001551 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001552 // thiz holds strong ref to this while the thread is running.
1553 sp<CCodec> thiz(this);
1554 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1555}
1556
1557void CCodec::release(bool sendCallback) {
1558 std::shared_ptr<Codec2Client::Component> comp;
1559 {
1560 Mutexed<State>::Locked state(mState);
1561 if (state->get() == RELEASED) {
1562 if (sendCallback) {
1563 state.unlock();
1564 mCallback->onReleaseCompleted();
1565 state.lock();
1566 }
1567 return;
1568 }
1569 comp = state->comp;
1570 }
1571 comp->release();
1572
1573 {
1574 Mutexed<State>::Locked state(mState);
1575 state->set(RELEASED);
1576 state->comp.reset();
1577 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001578 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001579 if (sendCallback) {
1580 mCallback->onReleaseCompleted();
1581 }
1582}
1583
1584status_t CCodec::setSurface(const sp<Surface> &surface) {
1585 return mChannel->setSurface(surface);
1586}
1587
1588void CCodec::signalFlush() {
1589 status_t err = [this] {
1590 Mutexed<State>::Locked state(mState);
1591 if (state->get() == FLUSHED) {
1592 return ALREADY_EXISTS;
1593 }
1594 if (state->get() != RUNNING) {
1595 return UNKNOWN_ERROR;
1596 }
1597 state->set(FLUSHING);
1598 return OK;
1599 }();
1600 switch (err) {
1601 case ALREADY_EXISTS:
1602 mCallback->onFlushCompleted();
1603 return;
1604 case OK:
1605 break;
1606 default:
1607 mCallback->onError(err, ACTION_CODE_FATAL);
1608 return;
1609 }
1610
1611 mChannel->stop();
1612 (new AMessage(kWhatFlush, this))->post();
1613}
1614
1615void CCodec::flush() {
1616 std::shared_ptr<Codec2Client::Component> comp;
1617 auto checkFlushing = [this, &comp] {
1618 Mutexed<State>::Locked state(mState);
1619 if (state->get() != FLUSHING) {
1620 return UNKNOWN_ERROR;
1621 }
1622 comp = state->comp;
1623 return OK;
1624 };
1625 if (tryAndReportOnError(checkFlushing) != OK) {
1626 return;
1627 }
1628
1629 std::list<std::unique_ptr<C2Work>> flushedWork;
1630 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1631 {
1632 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1633 flushedWork.splice(flushedWork.end(), *queue);
1634 }
1635 if (err != C2_OK) {
1636 // TODO: convert err into status_t
1637 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1638 }
1639
1640 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001641
1642 {
1643 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001644 if (state->get() == FLUSHING) {
1645 state->set(FLUSHED);
1646 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001647 }
1648 mCallback->onFlushCompleted();
1649}
1650
1651void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001652 std::shared_ptr<Codec2Client::Component> comp;
1653 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001654 Mutexed<State>::Locked state(mState);
1655 if (state->get() != FLUSHED) {
1656 return UNKNOWN_ERROR;
1657 }
1658 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001659 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001660 return OK;
1661 };
1662 if (tryAndReportOnError(setResuming) != OK) {
1663 return;
1664 }
1665
Wonsik Kime75a5da2020-02-14 17:29:03 -08001666 {
1667 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1668 const std::unique_ptr<Config> &config = *configLocked;
1669 config->queryConfiguration(comp);
1670 }
1671
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001672 (void)mChannel->start(nullptr, nullptr, [&]{
1673 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1674 const std::unique_ptr<Config> &config = *configLocked;
1675 return config->mBuffersBoundToCodec;
1676 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001677
1678 {
1679 Mutexed<State>::Locked state(mState);
1680 if (state->get() != RESUMING) {
1681 state.unlock();
1682 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1683 state.lock();
1684 return;
1685 }
1686 state->set(RUNNING);
1687 }
1688
1689 (void)mChannel->requestInitialInputBuffers();
1690}
1691
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001692void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001693 std::shared_ptr<Codec2Client::Component> comp;
1694 auto checkState = [this, &comp] {
1695 Mutexed<State>::Locked state(mState);
1696 if (state->get() == RELEASED) {
1697 return INVALID_OPERATION;
1698 }
1699 comp = state->comp;
1700 return OK;
1701 };
1702 if (tryAndReportOnError(checkState) != OK) {
1703 return;
1704 }
1705
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001706 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1707 // the behavior here.
1708 sp<AMessage> params = msg;
1709 int32_t bitrate;
1710 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1711 params = msg->dup();
1712 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1713 }
1714
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001715 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1716 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001717
1718 /**
1719 * Handle input surface parameters
1720 */
1721 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001722 && (config->mDomain & Config::IS_ENCODER)
1723 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001724 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001725
1726 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1727 config->mISConfig->mStopped = false;
1728 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1729 config->mISConfig->mStopped = true;
1730 }
1731
1732 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001733 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001734 config->mISConfig->mSuspended = value;
1735 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001736 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001737 }
1738
1739 (void)config->mInputSurface->configure(*config->mISConfig);
1740 if (config->mISConfig->mStopped) {
1741 config->mInputFormat->setInt64(
1742 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1743 }
1744 }
1745
1746 std::vector<std::unique_ptr<C2Param>> configUpdate;
1747 (void)config->getConfigUpdateFromSdkParams(
1748 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1749 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1750 // Parameter synchronization is not defined when using input surface. For now, route
1751 // these directly to the component.
1752 if (config->mInputSurface == nullptr
1753 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1754 || comp->getName().find("c2.android.") == 0)) {
1755 mChannel->setParameters(configUpdate);
1756 } else {
1757 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1758 }
1759}
1760
1761void CCodec::signalEndOfInputStream() {
1762 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1763}
1764
1765void CCodec::signalRequestIDRFrame() {
1766 std::shared_ptr<Codec2Client::Component> comp;
1767 {
1768 Mutexed<State>::Locked state(mState);
1769 if (state->get() == RELEASED) {
1770 ALOGD("no IDR request sent since component is released");
1771 return;
1772 }
1773 comp = state->comp;
1774 }
1775 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001776 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1777 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001778 std::vector<std::unique_ptr<C2Param>> params;
1779 params.push_back(
1780 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1781 config->setParameters(comp, params, C2_MAY_BLOCK);
1782}
1783
Wonsik Kimab34ed62019-01-31 15:28:46 -08001784void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001785 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001786 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1787 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001788 }
1789 (new AMessage(kWhatWorkDone, this))->post();
1790}
1791
Wonsik Kimab34ed62019-01-31 15:28:46 -08001792void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1793 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001794 if (arrayIndex == 0) {
1795 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001796 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1797 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001798 if (config->mInputSurface) {
1799 config->mInputSurface->onInputBufferDone(frameIndex);
1800 }
1801 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001802}
1803
1804void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1805 TimePoint now = std::chrono::steady_clock::now();
1806 CCodecWatchdog::getInstance()->watch(this);
1807 switch (msg->what()) {
1808 case kWhatAllocate: {
1809 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001810 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001811 sp<RefBase> obj;
1812 CHECK(msg->findObject("codecInfo", &obj));
1813 allocate((MediaCodecInfo *)obj.get());
1814 break;
1815 }
1816 case kWhatConfigure: {
1817 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001818 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001819 sp<AMessage> format;
1820 CHECK(msg->findMessage("format", &format));
1821 configure(format);
1822 break;
1823 }
1824 case kWhatStart: {
1825 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001826 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001827 start();
1828 break;
1829 }
1830 case kWhatStop: {
1831 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001832 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001833 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001834 break;
1835 }
1836 case kWhatFlush: {
1837 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001838 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001839 flush();
1840 break;
1841 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001842 case kWhatRelease: {
1843 mChannel->release();
1844 mClient.reset();
1845 mClientListener.reset();
1846 break;
1847 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001848 case kWhatCreateInputSurface: {
1849 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001850 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001851 createInputSurface();
1852 break;
1853 }
1854 case kWhatSetInputSurface: {
1855 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001856 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001857 sp<RefBase> obj;
1858 CHECK(msg->findObject("surface", &obj));
1859 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1860 setInputSurface(surface);
1861 break;
1862 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001863 case kWhatWorkDone: {
1864 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001865 bool shouldPost = false;
1866 {
1867 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1868 if (queue->empty()) {
1869 break;
1870 }
1871 work.swap(queue->front());
1872 queue->pop_front();
1873 shouldPost = !queue->empty();
1874 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001875 if (shouldPost) {
1876 (new AMessage(kWhatWorkDone, this))->post();
1877 }
1878
Pawin Vongmasa36653902018-11-15 00:10:25 -08001879 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001880 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1881 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001882 bool changed = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001883 Config::Watcher<C2StreamInitDataInfo::output> initData =
1884 config->watch<C2StreamInitDataInfo::output>();
1885 if (!work->worklets.empty()
1886 && (work->worklets.front()->output.flags
1887 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1888
1889 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001890 std::vector<std::unique_ptr<C2Param>> updates;
1891 for (const std::unique_ptr<C2Param> &param
1892 : work->worklets.front()->output.configUpdate) {
1893 updates.push_back(C2Param::Copy(*param));
1894 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001895 unsigned stream = 0;
1896 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1897 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1898 // move all info into output-stream #0 domain
1899 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1900 }
George Burgess IVc813a592020-02-22 22:54:44 -08001901
1902 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
1903 // for now only do the first block
1904 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001905 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1906 // block.crop().left, block.crop().top,
1907 // block.crop().width, block.crop().height,
1908 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08001909 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08001910 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1911 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07001912 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001913 }
1914 ++stream;
1915 }
1916
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001917 if (config->updateConfiguration(updates, config->mOutputDomain)) {
1918 changed = true;
1919 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001920
1921 // copy standard infos to graphic buffers if not already present (otherwise, we
1922 // may overwrite the actual intermediate value with a final value)
1923 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07001924 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001925 C2StreamRotationInfo::output::PARAM_TYPE,
1926 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1927 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1928 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001929 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001930 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1931 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1932 };
1933 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1934 if (buf->data().graphicBlocks().size()) {
1935 for (C2Param::Index ix : stdGfxInfos) {
1936 if (!buf->hasInfo(ix)) {
1937 const C2Param *param =
1938 config->getConfigParameterValue(ix.withStream(stream));
1939 if (param) {
1940 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1941 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1942 }
1943 }
1944 }
1945 }
1946 ++stream;
1947 }
1948 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001949 if (config->mInputSurface) {
1950 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1951 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001952 mChannel->onWorkDone(
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001953 std::move(work), changed ? config->mOutputFormat->dup() : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001954 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001955 break;
1956 }
1957 case kWhatWatch: {
1958 // watch message already posted; no-op.
1959 break;
1960 }
1961 default: {
1962 ALOGE("unrecognized message");
1963 break;
1964 }
1965 }
1966 setDeadline(TimePoint::max(), 0ms, "none");
1967}
1968
1969void CCodec::setDeadline(
1970 const TimePoint &now,
1971 const std::chrono::milliseconds &timeout,
1972 const char *name) {
1973 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1974 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1975 deadline->set(now + (timeout * mult), name);
1976}
1977
1978void CCodec::initiateReleaseIfStuck() {
1979 std::string name;
1980 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001981 {
1982 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001983 if (deadline->get() < std::chrono::steady_clock::now()) {
1984 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001985 }
1986 if (deadline->get() != TimePoint::max()) {
1987 pendingDeadline = true;
1988 }
1989 }
1990 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001991 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1992 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1993 if (elapsed >= kWorkDurationThreshold) {
1994 name = "queue";
1995 }
1996 if (elapsed > 0s) {
1997 pendingDeadline = true;
1998 }
1999 }
2000 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002001 // We're not stuck.
2002 if (pendingDeadline) {
2003 // If we are not stuck yet but still has deadline coming up,
2004 // post watch message to check back later.
2005 (new AMessage(kWhatWatch, this))->post();
2006 }
2007 return;
2008 }
2009
2010 ALOGW("previous call to %s exceeded timeout", name.c_str());
2011 initiateRelease(false);
2012 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2013}
2014
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002015// static
2016PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002017 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002018 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002019 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07002020 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
2021 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08002022 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07002023 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
2024 sp<IGraphicBufferProducer> gbp;
2025 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
2026 status_t err = gbs->initCheck();
2027 if (err != OK) {
2028 ALOGE("Failed to create persistent input surface: error %d", err);
2029 return nullptr;
2030 }
2031 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07002032 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07002033 } else {
2034 return nullptr;
2035 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002036 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07002037 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08002038 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07002039 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08002040 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002041}
2042
Wonsik Kimffb889a2020-05-28 11:32:25 -07002043class IntfCache {
2044public:
2045 IntfCache() = default;
2046
2047 status_t init(const std::string &name) {
2048 std::shared_ptr<Codec2Client::Interface> intf{
2049 Codec2Client::CreateInterfaceByName(name.c_str())};
2050 if (!intf) {
2051 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
2052 mInitStatus = NO_INIT;
2053 return NO_INIT;
2054 }
2055 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2056 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
2057 C2ParamField{&sUsage, &sUsage.value}));
2058 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
2059 if (err != C2_OK) {
2060 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
2061 name.c_str(), err);
2062 mFields[0].status = err;
2063 }
2064 std::vector<std::unique_ptr<C2Param>> params;
2065 err = intf->query(
2066 {&mApiFeatures},
2067 {C2PortAllocatorsTuning::input::PARAM_TYPE},
2068 C2_MAY_BLOCK,
2069 &params);
2070 if (err != C2_OK && err != C2_BAD_INDEX) {
2071 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
2072 name.c_str(), err);
2073 }
2074 while (!params.empty()) {
2075 C2Param *param = params.back().release();
2076 params.pop_back();
2077 if (!param) {
2078 continue;
2079 }
2080 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
2081 mInputAllocators.reset(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07002082 C2PortAllocatorsTuning::input::From(param));
Wonsik Kimffb889a2020-05-28 11:32:25 -07002083 }
2084 }
2085 mInitStatus = OK;
2086 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002087 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002088
2089 status_t initCheck() const { return mInitStatus; }
2090
2091 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2092 CHECK_EQ(1u, mFields.size());
2093 return mFields[0];
2094 }
2095
2096 const C2ApiFeaturesSetting &getApiFeatures() const {
2097 return mApiFeatures;
2098 }
2099
2100 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2101 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2102 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2103 C2PortAllocatorsTuning::input::AllocUnique(0);
2104 param->invalidate();
2105 return param;
2106 }();
2107 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2108 }
2109
2110private:
2111 status_t mInitStatus{NO_INIT};
2112
2113 std::vector<C2FieldSupportedValuesQuery> mFields;
2114 C2ApiFeaturesSetting mApiFeatures;
2115 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2116};
2117
2118static const IntfCache &GetIntfCache(const std::string &name) {
2119 static IntfCache sNullIntfCache;
2120 static std::mutex sMutex;
2121 static std::map<std::string, IntfCache> sCache;
2122 std::unique_lock<std::mutex> lock{sMutex};
2123 auto it = sCache.find(name);
2124 if (it == sCache.end()) {
2125 lock.unlock();
2126 IntfCache intfCache;
2127 status_t err = intfCache.init(name);
2128 if (err != OK) {
2129 return sNullIntfCache;
2130 }
2131 lock.lock();
2132 it = sCache.insert({name, std::move(intfCache)}).first;
2133 }
2134 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002135}
2136
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002137static status_t GetCommonAllocatorIds(
2138 const std::vector<std::string> &names,
2139 C2Allocator::type_t type,
2140 std::set<C2Allocator::id_t> *ids) {
2141 int poolMask = GetCodec2PoolMask();
2142 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2143 C2Allocator::id_t defaultAllocatorId =
2144 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2145
2146 ids->clear();
2147 if (names.empty()) {
2148 return OK;
2149 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002150 bool firstIteration = true;
2151 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002152 const IntfCache &intfCache = GetIntfCache(name);
2153 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002154 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002155 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002156 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002157 if (firstIteration) {
2158 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002159 if (allocators && allocators.flexCount() > 0) {
2160 ids->insert(allocators.m.values,
2161 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002162 }
2163 if (ids->empty()) {
2164 // The component does not advertise allocators. Use default.
2165 ids->insert(defaultAllocatorId);
2166 }
2167 continue;
2168 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002169 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002170 if (allocators && allocators.flexCount() > 0) {
2171 filtered = true;
2172 for (auto it = ids->begin(); it != ids->end(); ) {
2173 bool found = false;
2174 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2175 if (allocators.m.values[j] == *it) {
2176 found = true;
2177 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002178 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002179 }
2180 if (found) {
2181 ++it;
2182 } else {
2183 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002184 }
2185 }
2186 }
2187 if (!filtered) {
2188 // The component does not advertise supported allocators. Use default.
2189 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2190 if (ids->size() != (containsDefault ? 1 : 0)) {
2191 ids->clear();
2192 if (containsDefault) {
2193 ids->insert(defaultAllocatorId);
2194 }
2195 }
2196 }
2197 }
2198 // Finally, filter with pool masks
2199 for (auto it = ids->begin(); it != ids->end(); ) {
2200 if ((poolMask >> *it) & 1) {
2201 ++it;
2202 } else {
2203 it = ids->erase(it);
2204 }
2205 }
2206 return OK;
2207}
2208
2209static status_t CalculateMinMaxUsage(
2210 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2211 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2212 *minUsage = 0;
2213 *maxUsage = ~0ull;
2214 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002215 const IntfCache &intfCache = GetIntfCache(name);
2216 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002217 continue;
2218 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002219 const C2FieldSupportedValuesQuery &usageSupportedValues =
2220 intfCache.getUsageSupportedValues();
2221 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002222 continue;
2223 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002224 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002225 if (supported.type != C2FieldSupportedValues::FLAGS) {
2226 continue;
2227 }
2228 if (supported.values.empty()) {
2229 *maxUsage = 0;
2230 continue;
2231 }
2232 *minUsage |= supported.values[0].u64;
2233 int64_t currentMaxUsage = 0;
2234 for (const C2Value::Primitive &flags : supported.values) {
2235 currentMaxUsage |= flags.u64;
2236 }
2237 *maxUsage &= currentMaxUsage;
2238 }
2239 return OK;
2240}
2241
2242// static
2243status_t CCodec::CanFetchLinearBlock(
2244 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002245 for (const std::string &name : names) {
2246 const IntfCache &intfCache = GetIntfCache(name);
2247 if (intfCache.initCheck() != OK) {
2248 continue;
2249 }
2250 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2251 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2252 *isCompatible = false;
2253 return OK;
2254 }
2255 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002256 uint64_t minUsage = usage.expected;
2257 uint64_t maxUsage = ~0ull;
2258 std::set<C2Allocator::id_t> allocators;
2259 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2260 if (allocators.empty()) {
2261 *isCompatible = false;
2262 return OK;
2263 }
2264 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2265 *isCompatible = ((maxUsage & minUsage) == minUsage);
2266 return OK;
2267}
2268
2269static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2270 static std::mutex sMutex{};
2271 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2272 std::unique_lock<std::mutex> lock{sMutex};
2273 std::shared_ptr<C2BlockPool> pool;
2274 auto it = sPools.find(allocId);
2275 if (it == sPools.end()) {
2276 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2277 if (err == OK) {
2278 sPools.emplace(allocId, pool);
2279 } else {
2280 pool.reset();
2281 }
2282 } else {
2283 pool = it->second;
2284 }
2285 return pool;
2286}
2287
2288// static
2289std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2290 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
2291 uint64_t minUsage = usage.expected;
2292 uint64_t maxUsage = ~0ull;
2293 std::set<C2Allocator::id_t> allocators;
2294 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2295 if (allocators.empty()) {
2296 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2297 }
2298 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2299 if ((maxUsage & minUsage) != minUsage) {
2300 allocators.clear();
2301 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2302 }
2303 std::shared_ptr<C2LinearBlock> block;
2304 for (C2Allocator::id_t allocId : allocators) {
2305 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2306 if (!pool) {
2307 continue;
2308 }
2309 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2310 if (err != C2_OK || !block) {
2311 block.reset();
2312 continue;
2313 }
2314 break;
2315 }
2316 return block;
2317}
2318
2319// static
2320status_t CCodec::CanFetchGraphicBlock(
2321 const std::vector<std::string> &names, bool *isCompatible) {
2322 uint64_t minUsage = 0;
2323 uint64_t maxUsage = ~0ull;
2324 std::set<C2Allocator::id_t> allocators;
2325 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2326 if (allocators.empty()) {
2327 *isCompatible = false;
2328 return OK;
2329 }
2330 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2331 *isCompatible = ((maxUsage & minUsage) == minUsage);
2332 return OK;
2333}
2334
2335// static
2336std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2337 int32_t width,
2338 int32_t height,
2339 int32_t format,
2340 uint64_t usage,
2341 const std::vector<std::string> &names) {
2342 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2343 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2344 ALOGD("Unrecognized pixel format: %d", format);
2345 return nullptr;
2346 }
2347 uint64_t minUsage = 0;
2348 uint64_t maxUsage = ~0ull;
2349 std::set<C2Allocator::id_t> allocators;
2350 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2351 if (allocators.empty()) {
2352 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2353 }
2354 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2355 minUsage |= usage;
2356 if ((maxUsage & minUsage) != minUsage) {
2357 allocators.clear();
2358 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2359 }
2360 std::shared_ptr<C2GraphicBlock> block;
2361 for (C2Allocator::id_t allocId : allocators) {
2362 std::shared_ptr<C2BlockPool> pool;
2363 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2364 if (err != C2_OK || !pool) {
2365 continue;
2366 }
2367 err = pool->fetchGraphicBlock(
2368 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2369 if (err != C2_OK || !block) {
2370 block.reset();
2371 continue;
2372 }
2373 break;
2374 }
2375 return block;
2376}
2377
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002378} // namespace android
2379