blob: f816778d9fc175f1baca82011423ee43a789df28 [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 }
249 constexpr size_t kNumSlots = 16;
250 for (size_t i = 0; i < kNumSlots; ++i) {
251 source->onInputBufferAdded(i);
252 }
253
254 source->onOmxExecuting();
255 return OK;
256 }
257
258 status_t signalEndOfInputStream() override {
259 return GetStatus(mSource->signalEndOfInputStream());
260 }
261
262 status_t configure(Config &config) {
263 std::stringstream status;
264 status_t err = OK;
265
266 // handle each configuration granually, in case we need to handle part of the configuration
267 // elsewhere
268
269 // TRICKY: we do not unset frame delay repeating
270 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
271 int64_t us = 1e6 / config.mMinFps + 0.5;
272 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
273 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
274 if (res != OK) {
275 status << " (=> " << asString(res) << ")";
276 err = res;
277 }
278 mConfig.mMinFps = config.mMinFps;
279 }
280
281 // pts gap
282 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
283 if (mNode != nullptr) {
284 OMX_PARAM_U32TYPE ptrGapParam = {};
285 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700286 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800287 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
288 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700289 // float -> uint32_t is undefined if the value is negative.
290 // First convert to int32_t to ensure the expected behavior.
291 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800292 (void)mNode->setParameter(
293 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
294 &ptrGapParam, sizeof(ptrGapParam));
295 }
296 }
297
298 // max fps
299 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700300 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800301 && config.mMaxFps != mConfig.mMaxFps) {
302 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
303 status << " maxFps=" << config.mMaxFps;
304 if (res != OK) {
305 status << " (=> " << asString(res) << ")";
306 err = res;
307 }
308 mConfig.mMaxFps = config.mMaxFps;
309 }
310
311 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
312 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
313 status << " timeOffset " << config.mTimeOffsetUs << "us";
314 if (res != OK) {
315 status << " (=> " << asString(res) << ")";
316 err = res;
317 }
318 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
319 }
320
321 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
322 status_t res =
323 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
324 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
325 if (res != OK) {
326 status << " (=> " << asString(res) << ")";
327 err = res;
328 }
329 mConfig.mCaptureFps = config.mCaptureFps;
330 mConfig.mCodedFps = config.mCodedFps;
331 }
332
333 if (config.mStartAtUs != mConfig.mStartAtUs
334 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
335 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
336 status << " start at " << config.mStartAtUs << "us";
337 if (res != OK) {
338 status << " (=> " << asString(res) << ")";
339 err = res;
340 }
341 mConfig.mStartAtUs = config.mStartAtUs;
342 mConfig.mStopped = config.mStopped;
343 }
344
345 // suspend-resume
346 if (config.mSuspended != mConfig.mSuspended) {
347 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
348 status << " " << (config.mSuspended ? "suspend" : "resume")
349 << " at " << config.mSuspendAtUs << "us";
350 if (res != OK) {
351 status << " (=> " << asString(res) << ")";
352 err = res;
353 }
354 mConfig.mSuspended = config.mSuspended;
355 mConfig.mSuspendAtUs = config.mSuspendAtUs;
356 }
357
358 if (config.mStopped != mConfig.mStopped && config.mStopped) {
359 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
360 status << " stop at " << config.mStopAtUs << "us";
361 if (res != OK) {
362 status << " (=> " << asString(res) << ")";
363 err = res;
364 } else {
365 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700366 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
367 [&res, &delayUs = config.mInputDelayUs](
368 auto status, auto stopTimeOffsetUs) {
369 res = static_cast<status_t>(status);
370 delayUs = stopTimeOffsetUs;
371 });
372 if (!trans.isOk()) {
373 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
374 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800375 if (res != OK) {
376 status << " (=> " << asString(res) << ")";
377 } else {
378 status << "=" << config.mInputDelayUs << "us";
379 }
380 mConfig.mInputDelayUs = config.mInputDelayUs;
381 }
382 mConfig.mStopAtUs = config.mStopAtUs;
383 mConfig.mStopped = config.mStopped;
384 }
385
386 // color aspects (android._color-aspects)
387
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700388 // consumer usage is queried earlier.
389
Wonsik Kimbd557932019-07-02 15:51:20 -0700390 if (status.str().empty()) {
391 ALOGD("ISConfig not changed");
392 } else {
393 ALOGD("ISConfig%s", status.str().c_str());
394 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800395 return err;
396 }
397
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700398 void onInputBufferDone(c2_cntr64_t index) override {
399 mNode->onInputBufferDone(index);
400 }
401
Pawin Vongmasa36653902018-11-15 00:10:25 -0800402private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700403 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800404 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700405 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800406 uint32_t mWidth;
407 uint32_t mHeight;
408 Config mConfig;
409};
410
411class Codec2ClientInterfaceWrapper : public C2ComponentStore {
412 std::shared_ptr<Codec2Client> mClient;
413
414public:
415 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
416 : mClient(client) { }
417
418 virtual ~Codec2ClientInterfaceWrapper() = default;
419
420 virtual c2_status_t config_sm(
421 const std::vector<C2Param *> &params,
422 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
423 return mClient->config(params, C2_MAY_BLOCK, failures);
424 };
425
426 virtual c2_status_t copyBuffer(
427 std::shared_ptr<C2GraphicBuffer>,
428 std::shared_ptr<C2GraphicBuffer>) {
429 return C2_OMITTED;
430 }
431
432 virtual c2_status_t createComponent(
433 C2String, std::shared_ptr<C2Component> *const component) {
434 component->reset();
435 return C2_OMITTED;
436 }
437
438 virtual c2_status_t createInterface(
439 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
440 interface->reset();
441 return C2_OMITTED;
442 }
443
444 virtual c2_status_t query_sm(
445 const std::vector<C2Param *> &stackParams,
446 const std::vector<C2Param::Index> &heapParamIndices,
447 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
448 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
449 }
450
451 virtual c2_status_t querySupportedParams_nb(
452 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
453 return mClient->querySupportedParams(params);
454 }
455
456 virtual c2_status_t querySupportedValues_sm(
457 std::vector<C2FieldSupportedValuesQuery> &fields) const {
458 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
459 }
460
461 virtual C2String getName() const {
462 return mClient->getName();
463 }
464
465 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
466 return mClient->getParamReflector();
467 }
468
469 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
470 return std::vector<std::shared_ptr<const C2Component::Traits>>();
471 }
472};
473
474} // namespace
475
476// CCodec::ClientListener
477
478struct CCodec::ClientListener : public Codec2Client::Listener {
479
480 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
481
482 virtual void onWorkDone(
483 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800484 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800485 (void)component;
486 sp<CCodec> codec(mCodec.promote());
487 if (!codec) {
488 return;
489 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800490 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800491 }
492
493 virtual void onTripped(
494 const std::weak_ptr<Codec2Client::Component>& component,
495 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
496 ) override {
497 // TODO
498 (void)component;
499 (void)settingResult;
500 }
501
502 virtual void onError(
503 const std::weak_ptr<Codec2Client::Component>& component,
504 uint32_t errorCode) override {
505 // TODO
506 (void)component;
507 (void)errorCode;
508 }
509
510 virtual void onDeath(
511 const std::weak_ptr<Codec2Client::Component>& component) override {
512 { // Log the death of the component.
513 std::shared_ptr<Codec2Client::Component> comp = component.lock();
514 if (!comp) {
515 ALOGE("Codec2 component died.");
516 } else {
517 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
518 }
519 }
520
521 // Report to MediaCodec.
522 sp<CCodec> codec(mCodec.promote());
523 if (!codec || !codec->mCallback) {
524 return;
525 }
526 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
527 }
528
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800529 virtual void onFrameRendered(uint64_t bufferQueueId,
530 int32_t slotId,
531 int64_t timestampNs) override {
532 // TODO: implement
533 (void)bufferQueueId;
534 (void)slotId;
535 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800536 }
537
538 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800539 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800540 sp<CCodec> codec(mCodec.promote());
541 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800542 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800543 }
544 }
545
546private:
547 wp<CCodec> mCodec;
548};
549
550// CCodecCallbackImpl
551
552class CCodecCallbackImpl : public CCodecCallback {
553public:
554 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
555 ~CCodecCallbackImpl() override = default;
556
557 void onError(status_t err, enum ActionCode actionCode) override {
558 mCodec->mCallback->onError(err, actionCode);
559 }
560
561 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
562 mCodec->mCallback->onOutputFramesRendered(
563 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
564 }
565
Pawin Vongmasa36653902018-11-15 00:10:25 -0800566 void onOutputBuffersChanged() override {
567 mCodec->mCallback->onOutputBuffersChanged();
568 }
569
570private:
571 CCodec *mCodec;
572};
573
574// CCodec
575
576CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700577 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
578 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800579}
580
581CCodec::~CCodec() {
582}
583
584std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
585 return mChannel;
586}
587
588status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
589 status_t err = job();
590 if (err != C2_OK) {
591 mCallback->onError(err, ACTION_CODE_FATAL);
592 }
593 return err;
594}
595
596void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
597 auto setAllocating = [this] {
598 Mutexed<State>::Locked state(mState);
599 if (state->get() != RELEASED) {
600 return INVALID_OPERATION;
601 }
602 state->set(ALLOCATING);
603 return OK;
604 };
605 if (tryAndReportOnError(setAllocating) != OK) {
606 return;
607 }
608
609 sp<RefBase> codecInfo;
610 CHECK(msg->findObject("codecInfo", &codecInfo));
611 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
612
613 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
614 allocMsg->setObject("codecInfo", codecInfo);
615 allocMsg->post();
616}
617
618void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
619 if (codecInfo == nullptr) {
620 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
621 return;
622 }
623 ALOGD("allocate(%s)", codecInfo->getCodecName());
624 mClientListener.reset(new ClientListener(this));
625
626 AString componentName = codecInfo->getCodecName();
627 std::shared_ptr<Codec2Client> client;
628
629 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700630 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800631 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800632 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800633 SetPreferredCodec2ComponentStore(
634 std::make_shared<Codec2ClientInterfaceWrapper>(client));
635 }
636
637 std::shared_ptr<Codec2Client::Component> comp =
638 Codec2Client::CreateComponentByName(
639 componentName.c_str(),
640 mClientListener,
641 &client);
642 if (!comp) {
643 ALOGE("Failed Create component: %s", componentName.c_str());
644 Mutexed<State>::Locked state(mState);
645 state->set(RELEASED);
646 state.unlock();
647 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
648 state.lock();
649 return;
650 }
651 ALOGI("Created component [%s]", componentName.c_str());
652 mChannel->setComponent(comp);
653 auto setAllocated = [this, comp, client] {
654 Mutexed<State>::Locked state(mState);
655 if (state->get() != ALLOCATING) {
656 state->set(RELEASED);
657 return UNKNOWN_ERROR;
658 }
659 state->set(ALLOCATED);
660 state->comp = comp;
661 mClient = client;
662 return OK;
663 };
664 if (tryAndReportOnError(setAllocated) != OK) {
665 return;
666 }
667
668 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700669 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
670 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800671 status_t err = config->initialize(mClient->getParamReflector(), comp);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800672 if (err != OK) {
673 ALOGW("Failed to initialize configuration support");
674 // TODO: report error once we complete implementation.
675 }
676 config->queryConfiguration(comp);
677
678 mCallback->onComponentAllocated(componentName.c_str());
679}
680
681void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
682 auto checkAllocated = [this] {
683 Mutexed<State>::Locked state(mState);
684 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
685 };
686 if (tryAndReportOnError(checkAllocated) != OK) {
687 return;
688 }
689
690 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
691 msg->setMessage("format", format);
692 msg->post();
693}
694
695void CCodec::configure(const sp<AMessage> &msg) {
696 std::shared_ptr<Codec2Client::Component> comp;
697 auto checkAllocated = [this, &comp] {
698 Mutexed<State>::Locked state(mState);
699 if (state->get() != ALLOCATED) {
700 state->set(RELEASED);
701 return UNKNOWN_ERROR;
702 }
703 comp = state->comp;
704 return OK;
705 };
706 if (tryAndReportOnError(checkAllocated) != OK) {
707 return;
708 }
709
710 auto doConfig = [msg, comp, this]() -> status_t {
711 AString mime;
712 if (!msg->findString("mime", &mime)) {
713 return BAD_VALUE;
714 }
715
716 int32_t encoder;
717 if (!msg->findInt32("encoder", &encoder)) {
718 encoder = false;
719 }
720
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800721 int32_t flags;
722 if (!msg->findInt32("flags", &flags)) {
723 return BAD_VALUE;
724 }
725
Pawin Vongmasa36653902018-11-15 00:10:25 -0800726 // TODO: read from intf()
727 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
728 return UNKNOWN_ERROR;
729 }
730
731 int32_t storeMeta;
732 if (encoder
733 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
734 && storeMeta != kMetadataBufferTypeInvalid) {
735 if (storeMeta != kMetadataBufferTypeANWBuffer) {
736 ALOGD("Only ANW buffers are supported for legacy metadata mode");
737 return BAD_VALUE;
738 }
739 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
740 }
741
742 sp<RefBase> obj;
743 sp<Surface> surface;
744 if (msg->findObject("native-window", &obj)) {
745 surface = static_cast<Surface *>(obj.get());
746 setSurface(surface);
747 }
748
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700749 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
750 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800751 config->mUsingSurface = surface != nullptr;
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800752 config->mBuffersBoundToCodec = ((flags & CONFIGURE_FLAG_USE_BLOCK_MODEL) == 0);
753 ALOGD("[%s] buffers are %sbound to CCodec for this session",
754 comp->getName().c_str(), config->mBuffersBoundToCodec ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800755
Wonsik Kim1114eea2019-02-25 14:35:24 -0800756 // Enforce required parameters
757 int32_t i32;
758 float flt;
759 if (config->mDomain & Config::IS_AUDIO) {
760 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
761 ALOGD("sample rate is missing, which is required for audio components.");
762 return BAD_VALUE;
763 }
764 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
765 ALOGD("channel count is missing, which is required for audio components.");
766 return BAD_VALUE;
767 }
768 if ((config->mDomain & Config::IS_ENCODER)
769 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
770 && !msg->findInt32(KEY_BIT_RATE, &i32)
771 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
772 ALOGD("bitrate is missing, which is required for audio encoders.");
773 return BAD_VALUE;
774 }
775 }
776 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
777 if (!msg->findInt32(KEY_WIDTH, &i32)) {
778 ALOGD("width is missing, which is required for image/video components.");
779 return BAD_VALUE;
780 }
781 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
782 ALOGD("height is missing, which is required for image/video components.");
783 return BAD_VALUE;
784 }
785 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700786 int32_t mode = BITRATE_MODE_VBR;
787 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700788 if (!msg->findInt32(KEY_QUALITY, &i32)) {
789 ALOGD("quality is missing, which is required for video encoders in CQ.");
790 return BAD_VALUE;
791 }
792 } else {
793 if (!msg->findInt32(KEY_BIT_RATE, &i32)
794 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
795 ALOGD("bitrate is missing, which is required for video encoders.");
796 return BAD_VALUE;
797 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800798 }
799 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
800 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
801 ALOGD("I frame interval is missing, which is required for video encoders.");
802 return BAD_VALUE;
803 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700804 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
805 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
806 ALOGD("frame rate is missing, which is required for video encoders.");
807 return BAD_VALUE;
808 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800809 }
810 }
811
Pawin Vongmasa36653902018-11-15 00:10:25 -0800812 /*
813 * Handle input surface configuration
814 */
815 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
816 && (config->mDomain & Config::IS_ENCODER)) {
817 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
818 {
819 config->mISConfig->mMinFps = 0;
820 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800821 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800822 config->mISConfig->mMinFps = 1e6 / value;
823 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700824 if (!msg->findFloat(
825 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
826 config->mISConfig->mMaxFps = -1;
827 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800828 config->mISConfig->mMinAdjustedFps = 0;
829 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800830 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800831 if (value < 0 && value >= INT32_MIN) {
832 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700833 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800834 } else if (value > 0 && value <= INT32_MAX) {
835 config->mISConfig->mMinAdjustedFps = 1e6 / value;
836 }
837 }
838 }
839
840 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700841 bool captureFpsFound = false;
842 double timeLapseFps;
843 float captureRate;
844 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
845 config->mISConfig->mCaptureFps = timeLapseFps;
846 captureFpsFound = true;
847 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
848 config->mISConfig->mCaptureFps = captureRate;
849 captureFpsFound = true;
850 }
851 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800852 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
853 }
854 }
855
856 {
857 config->mISConfig->mSuspended = false;
858 config->mISConfig->mSuspendAtUs = -1;
859 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800860 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800861 config->mISConfig->mSuspended = true;
862 }
863 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700864 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800865 }
866
867 /*
868 * Handle desired color format.
869 */
870 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
871 int32_t format = -1;
872 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
873 /*
874 * Also handle default color format (encoders require color format, so this is only
875 * needed for decoders.
876 */
877 if (!(config->mDomain & Config::IS_ENCODER)) {
878 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
879 }
880 }
881
882 if (format >= 0) {
883 msg->setInt32("android._color-format", format);
884 }
885 }
886
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800887 int32_t subscribeToAllVendorParams;
888 if (msg->findInt32("x-*", &subscribeToAllVendorParams) && subscribeToAllVendorParams) {
889 if (config->subscribeToAllVendorParams(comp, C2_MAY_BLOCK) != OK) {
890 ALOGD("[%s] Failed to subscribe to all vendor params", comp->getName().c_str());
891 }
892 }
893
Pawin Vongmasa36653902018-11-15 00:10:25 -0800894 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800895 // NOTE: We used to ignore "video-bitrate" at configure; replicate
896 // the behavior here.
897 sp<AMessage> sdkParams = msg;
898 int32_t videoBitrate;
899 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
900 sdkParams = msg->dup();
901 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
902 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800903 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800904 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905 if (err != OK) {
906 ALOGW("failed to convert configuration to c2 params");
907 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700908
909 int32_t maxBframes = 0;
910 if ((config->mDomain & Config::IS_ENCODER)
911 && (config->mDomain & Config::IS_VIDEO)
912 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
913 && maxBframes > 0) {
914 std::unique_ptr<C2StreamGopTuning::output> gop =
915 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
916 gop->m.values[0] = { P_FRAME, UINT32_MAX };
917 gop->m.values[1] = {
918 C2Config::picture_type_t(P_FRAME | B_FRAME),
919 uint32_t(maxBframes)
920 };
921 configUpdate.push_back(std::move(gop));
922 }
923
Pawin Vongmasa36653902018-11-15 00:10:25 -0800924 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
925 if (err != OK) {
926 ALOGW("failed to configure c2 params");
927 return err;
928 }
929
930 std::vector<std::unique_ptr<C2Param>> params;
931 C2StreamUsageTuning::input usage(0u, 0u);
932 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700933 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800934
935 std::initializer_list<C2Param::Index> indices {
936 };
937 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700938 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800939 indices,
940 C2_DONT_BLOCK,
941 &params);
942 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
943 ALOGE("Failed to query component interface: %d", c2err);
944 return UNKNOWN_ERROR;
945 }
946 if (params.size() != indices.size()) {
947 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
948 indices.size(), params.size());
949 return UNKNOWN_ERROR;
950 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700951 if (usage) {
952 if (usage.value & C2MemoryUsage::CPU_READ) {
953 config->mInputFormat->setInt32("using-sw-read-often", true);
954 }
955 if (config->mISConfig) {
956 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
957 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
958 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800959 }
960
961 // NOTE: we don't blindly use client specified input size if specified as clients
962 // at times specify too small size. Instead, mimic the behavior from OMX, where the
963 // client specified size is only used to ask for bigger buffers than component suggested
964 // size.
965 int32_t clientInputSize = 0;
966 bool clientSpecifiedInputSize =
967 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
968 // TEMP: enforce minimum buffer size of 1MB for video decoders
969 // and 16K / 4K for audio encoders/decoders
970 if (maxInputSize.value == 0) {
971 if (config->mDomain & Config::IS_AUDIO) {
972 maxInputSize.value = encoder ? 16384 : 4096;
973 } else if (!encoder) {
974 maxInputSize.value = 1048576u;
975 }
976 }
977
978 // verify that CSD fits into this size (if defined)
979 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
980 sp<ABuffer> csd;
981 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
982 if (csd && csd->size() > maxInputSize.value) {
983 maxInputSize.value = csd->size();
984 }
985 }
986 }
987
988 // TODO: do this based on component requiring linear allocator for input
989 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
990 if (clientSpecifiedInputSize) {
991 // Warn that we're overriding client's max input size if necessary.
992 if ((uint32_t)clientInputSize < maxInputSize.value) {
993 ALOGD("client requested max input size %d, which is smaller than "
994 "what component recommended (%u); overriding with component "
995 "recommendation.", clientInputSize, maxInputSize.value);
996 ALOGW("This behavior is subject to change. It is recommended that "
997 "app developers double check whether the requested "
998 "max input size is in reasonable range.");
999 } else {
1000 maxInputSize.value = clientInputSize;
1001 }
1002 }
1003 // Pass max input size on input format to the buffer channel (if supplied by the
1004 // component or by a default)
1005 if (maxInputSize.value) {
1006 config->mInputFormat->setInt32(
1007 KEY_MAX_INPUT_SIZE,
1008 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
1009 }
1010 }
1011
Wonsik Kim9ca01d32019-04-01 14:45:47 -07001012 int32_t clientPrepend;
1013 if ((config->mDomain & Config::IS_VIDEO)
1014 && (config->mDomain & Config::IS_ENCODER)
1015 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1016 && clientPrepend
1017 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1018 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1019 return BAD_VALUE;
1020 }
1021
Pawin Vongmasa36653902018-11-15 00:10:25 -08001022 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1023 // propagate HDR static info to output format for both encoders and decoders
1024 // if component supports this info, we will update from component, but only the raw port,
1025 // so don't propagate if component already filled it in.
1026 sp<ABuffer> hdrInfo;
1027 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1028 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1029 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1030 }
1031
1032 // Set desired color format from configuration parameter
1033 int32_t format;
1034 if (msg->findInt32("android._color-format", &format)) {
1035 if (config->mDomain & Config::IS_ENCODER) {
1036 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
1037 } else {
1038 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
1039 }
1040 }
1041 }
1042
1043 // propagate encoder delay and padding to output format
1044 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1045 int delay = 0;
1046 if (msg->findInt32("encoder-delay", &delay)) {
1047 config->mOutputFormat->setInt32("encoder-delay", delay);
1048 }
1049 int padding = 0;
1050 if (msg->findInt32("encoder-padding", &padding)) {
1051 config->mOutputFormat->setInt32("encoder-padding", padding);
1052 }
1053 }
1054
1055 // set channel-mask
1056 if (config->mDomain & Config::IS_AUDIO) {
1057 int32_t mask;
1058 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1059 if (config->mDomain & Config::IS_ENCODER) {
1060 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1061 } else {
1062 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1063 }
1064 }
1065 }
1066
1067 ALOGD("setup formats input: %s and output: %s",
1068 config->mInputFormat->debugString().c_str(),
1069 config->mOutputFormat->debugString().c_str());
1070 return OK;
1071 };
1072 if (tryAndReportOnError(doConfig) != OK) {
1073 return;
1074 }
1075
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001076 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1077 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001078
1079 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1080}
1081
1082void CCodec::initiateCreateInputSurface() {
1083 status_t err = [this] {
1084 Mutexed<State>::Locked state(mState);
1085 if (state->get() != ALLOCATED) {
1086 return UNKNOWN_ERROR;
1087 }
1088 // TODO: read it from intf() properly.
1089 if (state->comp->getName().find("encoder") == std::string::npos) {
1090 return INVALID_OPERATION;
1091 }
1092 return OK;
1093 }();
1094 if (err != OK) {
1095 mCallback->onInputSurfaceCreationFailed(err);
1096 return;
1097 }
1098
1099 (new AMessage(kWhatCreateInputSurface, this))->post();
1100}
1101
Lajos Molnar47118272019-01-31 16:28:04 -08001102sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1103 using namespace android::hardware::media::omx::V1_0;
1104 using namespace android::hardware::media::omx::V1_0::utils;
1105 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1106 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1107 android::sp<IOmx> omx = IOmx::getService();
1108 typedef android::hardware::graphics::bufferqueue::V1_0::
1109 IGraphicBufferProducer HGraphicBufferProducer;
1110 typedef android::hardware::media::omx::V1_0::
1111 IGraphicBufferSource HGraphicBufferSource;
1112 OmxStatus s;
1113 android::sp<HGraphicBufferProducer> gbp;
1114 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001115
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001116 using ::android::hardware::Return;
1117 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001118 [&s, &gbp, &gbs](
1119 OmxStatus status,
1120 const android::sp<HGraphicBufferProducer>& producer,
1121 const android::sp<HGraphicBufferSource>& source) {
1122 s = status;
1123 gbp = producer;
1124 gbs = source;
1125 });
1126 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001127 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001128 }
1129
1130 return nullptr;
1131}
1132
1133sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1134 sp<PersistentSurface> surface(CreateInputSurface());
1135
1136 if (surface == nullptr) {
1137 surface = CreateOmxInputSurface();
1138 }
1139
1140 return surface;
1141}
1142
Pawin Vongmasa36653902018-11-15 00:10:25 -08001143void CCodec::createInputSurface() {
1144 status_t err;
1145 sp<IGraphicBufferProducer> bufferProducer;
1146
1147 sp<AMessage> inputFormat;
1148 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001149 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001150 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001151 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1152 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001153 inputFormat = config->mInputFormat;
1154 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001155 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001156 }
1157
Lajos Molnar47118272019-01-31 16:28:04 -08001158 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001159 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1160 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1161 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001162
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001163 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001164 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1165 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001166 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001167 inputSurface));
1168 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001169 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001170 int32_t width = 0;
1171 (void)outputFormat->findInt32("width", &width);
1172 int32_t height = 0;
1173 (void)outputFormat->findInt32("height", &height);
1174 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001175 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001176 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001177 } else {
1178 ALOGE("Corrupted input surface");
1179 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1180 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001181 }
1182
1183 if (err != OK) {
1184 ALOGE("Failed to set up input surface: %d", err);
1185 mCallback->onInputSurfaceCreationFailed(err);
1186 return;
1187 }
1188
1189 mCallback->onInputSurfaceCreated(
1190 inputFormat,
1191 outputFormat,
1192 new BufferProducerWrapper(bufferProducer));
1193}
1194
1195status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001196 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1197 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001198 config->mUsingSurface = true;
1199
1200 // we are now using surface - apply default color aspects to input format - as well as
1201 // get dataspace
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001202 bool inputFormatChanged = config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001203 ALOGD("input format %s to %s",
1204 inputFormatChanged ? "changed" : "unchanged",
1205 config->mInputFormat->debugString().c_str());
1206
1207 // configure dataspace
1208 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1209 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1210 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1211 surface->setDataSpace(dataSpace);
1212
1213 status_t err = mChannel->setInputSurface(surface);
1214 if (err != OK) {
1215 // undo input format update
1216 config->mUsingSurface = false;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001217 (void)config->updateFormats(Config::IS_INPUT);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001218 return err;
1219 }
1220 config->mInputSurface = surface;
1221
1222 if (config->mISConfig) {
1223 surface->configure(*config->mISConfig);
1224 } else {
1225 ALOGD("ISConfig: no configuration");
1226 }
1227
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001228 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001229}
1230
1231void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1232 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1233 msg->setObject("surface", surface);
1234 msg->post();
1235}
1236
1237void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1238 sp<AMessage> inputFormat;
1239 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001240 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001241 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001242 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1243 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001244 inputFormat = config->mInputFormat;
1245 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001246 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001247 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001248 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1249 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1250 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1251 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001252 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1253 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1254 if (err != OK) {
1255 ALOGE("Failed to set up input surface: %d", err);
1256 mCallback->onInputSurfaceDeclined(err);
1257 return;
1258 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001259 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001260 int32_t width = 0;
1261 (void)outputFormat->findInt32("width", &width);
1262 int32_t height = 0;
1263 (void)outputFormat->findInt32("height", &height);
1264 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001265 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001266 if (err != OK) {
1267 ALOGE("Failed to set up input surface: %d", err);
1268 mCallback->onInputSurfaceDeclined(err);
1269 return;
1270 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001271 } else {
1272 ALOGE("Failed to set input surface: Corrupted surface.");
1273 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1274 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001275 }
1276 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1277}
1278
1279void CCodec::initiateStart() {
1280 auto setStarting = [this] {
1281 Mutexed<State>::Locked state(mState);
1282 if (state->get() != ALLOCATED) {
1283 return UNKNOWN_ERROR;
1284 }
1285 state->set(STARTING);
1286 return OK;
1287 };
1288 if (tryAndReportOnError(setStarting) != OK) {
1289 return;
1290 }
1291
1292 (new AMessage(kWhatStart, this))->post();
1293}
1294
1295void CCodec::start() {
1296 std::shared_ptr<Codec2Client::Component> comp;
1297 auto checkStarting = [this, &comp] {
1298 Mutexed<State>::Locked state(mState);
1299 if (state->get() != STARTING) {
1300 return UNKNOWN_ERROR;
1301 }
1302 comp = state->comp;
1303 return OK;
1304 };
1305 if (tryAndReportOnError(checkStarting) != OK) {
1306 return;
1307 }
1308
1309 c2_status_t err = comp->start();
1310 if (err != C2_OK) {
1311 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1312 ACTION_CODE_FATAL);
1313 return;
1314 }
1315 sp<AMessage> inputFormat;
1316 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001317 status_t err2 = OK;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001318 bool buffersBoundToCodec = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001319 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001320 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1321 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001322 inputFormat = config->mInputFormat;
Wonsik Kim274c8322020-02-28 10:42:21 -08001323 // start triggers format dup
1324 outputFormat = config->mOutputFormat = config->mOutputFormat->dup();
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001325 if (config->mInputSurface) {
1326 err2 = config->mInputSurface->start();
1327 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001328 buffersBoundToCodec = config->mBuffersBoundToCodec;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001329 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001330 if (err2 != OK) {
1331 mCallback->onError(err2, ACTION_CODE_FATAL);
1332 return;
1333 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001334 err2 = mChannel->start(inputFormat, outputFormat, buffersBoundToCodec);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001335 if (err2 != OK) {
1336 mCallback->onError(err2, ACTION_CODE_FATAL);
1337 return;
1338 }
1339
1340 auto setRunning = [this] {
1341 Mutexed<State>::Locked state(mState);
1342 if (state->get() != STARTING) {
1343 return UNKNOWN_ERROR;
1344 }
1345 state->set(RUNNING);
1346 return OK;
1347 };
1348 if (tryAndReportOnError(setRunning) != OK) {
1349 return;
1350 }
1351 mCallback->onStartCompleted();
1352
1353 (void)mChannel->requestInitialInputBuffers();
1354}
1355
1356void CCodec::initiateShutdown(bool keepComponentAllocated) {
1357 if (keepComponentAllocated) {
1358 initiateStop();
1359 } else {
1360 initiateRelease();
1361 }
1362}
1363
1364void CCodec::initiateStop() {
1365 {
1366 Mutexed<State>::Locked state(mState);
1367 if (state->get() == ALLOCATED
1368 || state->get() == RELEASED
1369 || state->get() == STOPPING
1370 || state->get() == RELEASING) {
1371 // We're already stopped, released, or doing it right now.
1372 state.unlock();
1373 mCallback->onStopCompleted();
1374 state.lock();
1375 return;
1376 }
1377 state->set(STOPPING);
1378 }
1379
Wonsik Kim936a89c2020-05-08 16:07:50 -07001380 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001381 (new AMessage(kWhatStop, this))->post();
1382}
1383
1384void CCodec::stop() {
1385 std::shared_ptr<Codec2Client::Component> comp;
1386 {
1387 Mutexed<State>::Locked state(mState);
1388 if (state->get() == RELEASING) {
1389 state.unlock();
1390 // We're already stopped or release is in progress.
1391 mCallback->onStopCompleted();
1392 state.lock();
1393 return;
1394 } else if (state->get() != STOPPING) {
1395 state.unlock();
1396 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1397 state.lock();
1398 return;
1399 }
1400 comp = state->comp;
1401 }
1402 status_t err = comp->stop();
1403 if (err != C2_OK) {
1404 // TODO: convert err into status_t
1405 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1406 }
1407
1408 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001409 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1410 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001411 if (config->mInputSurface) {
1412 config->mInputSurface->disconnect();
1413 config->mInputSurface = nullptr;
1414 }
1415 }
1416 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001417 Mutexed<State>::Locked state(mState);
1418 if (state->get() == STOPPING) {
1419 state->set(ALLOCATED);
1420 }
1421 }
1422 mCallback->onStopCompleted();
1423}
1424
1425void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001426 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001427 {
1428 Mutexed<State>::Locked state(mState);
1429 if (state->get() == RELEASED || state->get() == RELEASING) {
1430 // We're already released or doing it right now.
1431 if (sendCallback) {
1432 state.unlock();
1433 mCallback->onReleaseCompleted();
1434 state.lock();
1435 }
1436 return;
1437 }
1438 if (state->get() == ALLOCATING) {
1439 state->set(RELEASING);
1440 // With the altered state allocate() would fail and clean up.
1441 if (sendCallback) {
1442 state.unlock();
1443 mCallback->onReleaseCompleted();
1444 state.lock();
1445 }
1446 return;
1447 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001448 if (state->get() == STARTING
1449 || state->get() == RUNNING
1450 || state->get() == STOPPING) {
1451 // Input surface may have been started, so clean up is needed.
1452 clearInputSurfaceIfNeeded = true;
1453 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001454 state->set(RELEASING);
1455 }
1456
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001457 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001458 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1459 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001460 if (config->mInputSurface) {
1461 config->mInputSurface->disconnect();
1462 config->mInputSurface = nullptr;
1463 }
1464 }
1465
Wonsik Kim936a89c2020-05-08 16:07:50 -07001466 mChannel->reset();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001467 // thiz holds strong ref to this while the thread is running.
1468 sp<CCodec> thiz(this);
1469 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1470}
1471
1472void CCodec::release(bool sendCallback) {
1473 std::shared_ptr<Codec2Client::Component> comp;
1474 {
1475 Mutexed<State>::Locked state(mState);
1476 if (state->get() == RELEASED) {
1477 if (sendCallback) {
1478 state.unlock();
1479 mCallback->onReleaseCompleted();
1480 state.lock();
1481 }
1482 return;
1483 }
1484 comp = state->comp;
1485 }
1486 comp->release();
1487
1488 {
1489 Mutexed<State>::Locked state(mState);
1490 state->set(RELEASED);
1491 state->comp.reset();
1492 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001493 (new AMessage(kWhatRelease, this))->post();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001494 if (sendCallback) {
1495 mCallback->onReleaseCompleted();
1496 }
1497}
1498
1499status_t CCodec::setSurface(const sp<Surface> &surface) {
1500 return mChannel->setSurface(surface);
1501}
1502
1503void CCodec::signalFlush() {
1504 status_t err = [this] {
1505 Mutexed<State>::Locked state(mState);
1506 if (state->get() == FLUSHED) {
1507 return ALREADY_EXISTS;
1508 }
1509 if (state->get() != RUNNING) {
1510 return UNKNOWN_ERROR;
1511 }
1512 state->set(FLUSHING);
1513 return OK;
1514 }();
1515 switch (err) {
1516 case ALREADY_EXISTS:
1517 mCallback->onFlushCompleted();
1518 return;
1519 case OK:
1520 break;
1521 default:
1522 mCallback->onError(err, ACTION_CODE_FATAL);
1523 return;
1524 }
1525
1526 mChannel->stop();
1527 (new AMessage(kWhatFlush, this))->post();
1528}
1529
1530void CCodec::flush() {
1531 std::shared_ptr<Codec2Client::Component> comp;
1532 auto checkFlushing = [this, &comp] {
1533 Mutexed<State>::Locked state(mState);
1534 if (state->get() != FLUSHING) {
1535 return UNKNOWN_ERROR;
1536 }
1537 comp = state->comp;
1538 return OK;
1539 };
1540 if (tryAndReportOnError(checkFlushing) != OK) {
1541 return;
1542 }
1543
1544 std::list<std::unique_ptr<C2Work>> flushedWork;
1545 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1546 {
1547 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1548 flushedWork.splice(flushedWork.end(), *queue);
1549 }
1550 if (err != C2_OK) {
1551 // TODO: convert err into status_t
1552 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1553 }
1554
1555 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001556
1557 {
1558 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001559 if (state->get() == FLUSHING) {
1560 state->set(FLUSHED);
1561 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001562 }
1563 mCallback->onFlushCompleted();
1564}
1565
1566void CCodec::signalResume() {
Wonsik Kime75a5da2020-02-14 17:29:03 -08001567 std::shared_ptr<Codec2Client::Component> comp;
1568 auto setResuming = [this, &comp] {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001569 Mutexed<State>::Locked state(mState);
1570 if (state->get() != FLUSHED) {
1571 return UNKNOWN_ERROR;
1572 }
1573 state->set(RESUMING);
Wonsik Kime75a5da2020-02-14 17:29:03 -08001574 comp = state->comp;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001575 return OK;
1576 };
1577 if (tryAndReportOnError(setResuming) != OK) {
1578 return;
1579 }
1580
Wonsik Kime75a5da2020-02-14 17:29:03 -08001581 {
1582 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1583 const std::unique_ptr<Config> &config = *configLocked;
1584 config->queryConfiguration(comp);
1585 }
1586
Wonsik Kimfb7a7672019-12-27 17:13:33 -08001587 (void)mChannel->start(nullptr, nullptr, [&]{
1588 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1589 const std::unique_ptr<Config> &config = *configLocked;
1590 return config->mBuffersBoundToCodec;
1591 }());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001592
1593 {
1594 Mutexed<State>::Locked state(mState);
1595 if (state->get() != RESUMING) {
1596 state.unlock();
1597 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1598 state.lock();
1599 return;
1600 }
1601 state->set(RUNNING);
1602 }
1603
1604 (void)mChannel->requestInitialInputBuffers();
1605}
1606
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001607void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001608 std::shared_ptr<Codec2Client::Component> comp;
1609 auto checkState = [this, &comp] {
1610 Mutexed<State>::Locked state(mState);
1611 if (state->get() == RELEASED) {
1612 return INVALID_OPERATION;
1613 }
1614 comp = state->comp;
1615 return OK;
1616 };
1617 if (tryAndReportOnError(checkState) != OK) {
1618 return;
1619 }
1620
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001621 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1622 // the behavior here.
1623 sp<AMessage> params = msg;
1624 int32_t bitrate;
1625 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1626 params = msg->dup();
1627 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1628 }
1629
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001630 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1631 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001632
1633 /**
1634 * Handle input surface parameters
1635 */
1636 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001637 && (config->mDomain & Config::IS_ENCODER)
1638 && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001639 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001640
1641 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1642 config->mISConfig->mStopped = false;
1643 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1644 config->mISConfig->mStopped = true;
1645 }
1646
1647 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001648 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001649 config->mISConfig->mSuspended = value;
1650 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001651 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001652 }
1653
1654 (void)config->mInputSurface->configure(*config->mISConfig);
1655 if (config->mISConfig->mStopped) {
1656 config->mInputFormat->setInt64(
1657 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1658 }
1659 }
1660
1661 std::vector<std::unique_ptr<C2Param>> configUpdate;
1662 (void)config->getConfigUpdateFromSdkParams(
1663 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1664 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1665 // Parameter synchronization is not defined when using input surface. For now, route
1666 // these directly to the component.
1667 if (config->mInputSurface == nullptr
1668 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1669 || comp->getName().find("c2.android.") == 0)) {
1670 mChannel->setParameters(configUpdate);
1671 } else {
1672 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1673 }
1674}
1675
1676void CCodec::signalEndOfInputStream() {
1677 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1678}
1679
1680void CCodec::signalRequestIDRFrame() {
1681 std::shared_ptr<Codec2Client::Component> comp;
1682 {
1683 Mutexed<State>::Locked state(mState);
1684 if (state->get() == RELEASED) {
1685 ALOGD("no IDR request sent since component is released");
1686 return;
1687 }
1688 comp = state->comp;
1689 }
1690 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001691 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1692 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001693 std::vector<std::unique_ptr<C2Param>> params;
1694 params.push_back(
1695 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1696 config->setParameters(comp, params, C2_MAY_BLOCK);
1697}
1698
Wonsik Kimab34ed62019-01-31 15:28:46 -08001699void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001700 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001701 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1702 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001703 }
1704 (new AMessage(kWhatWorkDone, this))->post();
1705}
1706
Wonsik Kimab34ed62019-01-31 15:28:46 -08001707void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1708 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001709 if (arrayIndex == 0) {
1710 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001711 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1712 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001713 if (config->mInputSurface) {
1714 config->mInputSurface->onInputBufferDone(frameIndex);
1715 }
1716 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001717}
1718
1719void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1720 TimePoint now = std::chrono::steady_clock::now();
1721 CCodecWatchdog::getInstance()->watch(this);
1722 switch (msg->what()) {
1723 case kWhatAllocate: {
1724 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001725 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001726 sp<RefBase> obj;
1727 CHECK(msg->findObject("codecInfo", &obj));
1728 allocate((MediaCodecInfo *)obj.get());
1729 break;
1730 }
1731 case kWhatConfigure: {
1732 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001733 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001734 sp<AMessage> format;
1735 CHECK(msg->findMessage("format", &format));
1736 configure(format);
1737 break;
1738 }
1739 case kWhatStart: {
1740 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001741 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001742 start();
1743 break;
1744 }
1745 case kWhatStop: {
1746 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001747 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001748 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001749 break;
1750 }
1751 case kWhatFlush: {
1752 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001753 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001754 flush();
1755 break;
1756 }
Wonsik Kim936a89c2020-05-08 16:07:50 -07001757 case kWhatRelease: {
1758 mChannel->release();
1759 mClient.reset();
1760 mClientListener.reset();
1761 break;
1762 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001763 case kWhatCreateInputSurface: {
1764 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001765 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001766 createInputSurface();
1767 break;
1768 }
1769 case kWhatSetInputSurface: {
1770 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001771 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001772 sp<RefBase> obj;
1773 CHECK(msg->findObject("surface", &obj));
1774 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1775 setInputSurface(surface);
1776 break;
1777 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001778 case kWhatWorkDone: {
1779 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001780 bool shouldPost = false;
1781 {
1782 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1783 if (queue->empty()) {
1784 break;
1785 }
1786 work.swap(queue->front());
1787 queue->pop_front();
1788 shouldPost = !queue->empty();
1789 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001790 if (shouldPost) {
1791 (new AMessage(kWhatWorkDone, this))->post();
1792 }
1793
Pawin Vongmasa36653902018-11-15 00:10:25 -08001794 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001795 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1796 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kimf6c41422020-09-03 11:48:41 -07001797 bool changed = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001798 Config::Watcher<C2StreamInitDataInfo::output> initData =
1799 config->watch<C2StreamInitDataInfo::output>();
1800 if (!work->worklets.empty()
1801 && (work->worklets.front()->output.flags
1802 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1803
1804 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001805 std::vector<std::unique_ptr<C2Param>> updates;
1806 for (const std::unique_ptr<C2Param> &param
1807 : work->worklets.front()->output.configUpdate) {
1808 updates.push_back(C2Param::Copy(*param));
1809 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001810 unsigned stream = 0;
1811 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1812 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1813 // move all info into output-stream #0 domain
1814 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1815 }
George Burgess IVc813a592020-02-22 22:54:44 -08001816
1817 const std::vector<C2ConstGraphicBlock> blocks = buf->data().graphicBlocks();
1818 // for now only do the first block
1819 if (!blocks.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001820 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1821 // block.crop().left, block.crop().top,
1822 // block.crop().width, block.crop().height,
1823 // block.width(), block.height());
George Burgess IVc813a592020-02-22 22:54:44 -08001824 const C2ConstGraphicBlock &block = blocks[0];
Pawin Vongmasa36653902018-11-15 00:10:25 -08001825 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1826 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07001827 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001828 }
1829 ++stream;
1830 }
1831
Wonsik Kime75a5da2020-02-14 17:29:03 -08001832 if (config->updateConfiguration(updates, config->mOutputDomain)) {
1833 changed = true;
1834 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001835
1836 // copy standard infos to graphic buffers if not already present (otherwise, we
1837 // may overwrite the actual intermediate value with a final value)
1838 stream = 0;
George Burgess IV3f1a0902020-03-18 12:58:32 -07001839 const static C2Param::Index stdGfxInfos[] = {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001840 C2StreamRotationInfo::output::PARAM_TYPE,
1841 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1842 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1843 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001844 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001845 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1846 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1847 };
1848 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1849 if (buf->data().graphicBlocks().size()) {
1850 for (C2Param::Index ix : stdGfxInfos) {
1851 if (!buf->hasInfo(ix)) {
1852 const C2Param *param =
1853 config->getConfigParameterValue(ix.withStream(stream));
1854 if (param) {
1855 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1856 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1857 }
1858 }
1859 }
1860 }
1861 ++stream;
1862 }
1863 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001864 if (config->mInputSurface) {
1865 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1866 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001867 mChannel->onWorkDone(
Pawin Vongmasad12500a2020-06-26 15:44:13 -07001868 std::move(work), changed ? config->mOutputFormat->dup() : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001869 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001870 break;
1871 }
1872 case kWhatWatch: {
1873 // watch message already posted; no-op.
1874 break;
1875 }
1876 default: {
1877 ALOGE("unrecognized message");
1878 break;
1879 }
1880 }
1881 setDeadline(TimePoint::max(), 0ms, "none");
1882}
1883
1884void CCodec::setDeadline(
1885 const TimePoint &now,
1886 const std::chrono::milliseconds &timeout,
1887 const char *name) {
1888 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1889 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1890 deadline->set(now + (timeout * mult), name);
1891}
1892
1893void CCodec::initiateReleaseIfStuck() {
1894 std::string name;
1895 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001896 {
1897 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001898 if (deadline->get() < std::chrono::steady_clock::now()) {
1899 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001900 }
1901 if (deadline->get() != TimePoint::max()) {
1902 pendingDeadline = true;
1903 }
1904 }
1905 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001906 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1907 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1908 if (elapsed >= kWorkDurationThreshold) {
1909 name = "queue";
1910 }
1911 if (elapsed > 0s) {
1912 pendingDeadline = true;
1913 }
1914 }
1915 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001916 // We're not stuck.
1917 if (pendingDeadline) {
1918 // If we are not stuck yet but still has deadline coming up,
1919 // post watch message to check back later.
1920 (new AMessage(kWhatWatch, this))->post();
1921 }
1922 return;
1923 }
1924
1925 ALOGW("previous call to %s exceeded timeout", name.c_str());
1926 initiateRelease(false);
1927 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1928}
1929
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001930// static
1931PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001932 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001933 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001934 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07001935 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1936 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001937 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001938 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
1939 sp<IGraphicBufferProducer> gbp;
1940 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
1941 status_t err = gbs->initCheck();
1942 if (err != OK) {
1943 ALOGE("Failed to create persistent input surface: error %d", err);
1944 return nullptr;
1945 }
1946 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001947 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07001948 } else {
1949 return nullptr;
1950 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001951 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07001952 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001953 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07001954 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08001955 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001956}
1957
Wonsik Kimffb889a2020-05-28 11:32:25 -07001958class IntfCache {
1959public:
1960 IntfCache() = default;
1961
1962 status_t init(const std::string &name) {
1963 std::shared_ptr<Codec2Client::Interface> intf{
1964 Codec2Client::CreateInterfaceByName(name.c_str())};
1965 if (!intf) {
1966 ALOGW("IntfCache [%s]: Unrecognized interface name", name.c_str());
1967 mInitStatus = NO_INIT;
1968 return NO_INIT;
1969 }
1970 const static C2StreamUsageTuning::input sUsage{0u /* stream id */};
1971 mFields.push_back(C2FieldSupportedValuesQuery::Possible(
1972 C2ParamField{&sUsage, &sUsage.value}));
1973 c2_status_t err = intf->querySupportedValues(mFields, C2_MAY_BLOCK);
1974 if (err != C2_OK) {
1975 ALOGW("IntfCache [%s]: failed to query usage supported value (err=%d)",
1976 name.c_str(), err);
1977 mFields[0].status = err;
1978 }
1979 std::vector<std::unique_ptr<C2Param>> params;
1980 err = intf->query(
1981 {&mApiFeatures},
1982 {C2PortAllocatorsTuning::input::PARAM_TYPE},
1983 C2_MAY_BLOCK,
1984 &params);
1985 if (err != C2_OK && err != C2_BAD_INDEX) {
1986 ALOGW("IntfCache [%s]: failed to query api features (err=%d)",
1987 name.c_str(), err);
1988 }
1989 while (!params.empty()) {
1990 C2Param *param = params.back().release();
1991 params.pop_back();
1992 if (!param) {
1993 continue;
1994 }
1995 if (param->type() == C2PortAllocatorsTuning::input::PARAM_TYPE) {
1996 mInputAllocators.reset(
1997 C2PortAllocatorsTuning::input::From(params[0].get()));
1998 }
1999 }
2000 mInitStatus = OK;
2001 return OK;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002002 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002003
2004 status_t initCheck() const { return mInitStatus; }
2005
2006 const C2FieldSupportedValuesQuery &getUsageSupportedValues() const {
2007 CHECK_EQ(1u, mFields.size());
2008 return mFields[0];
2009 }
2010
2011 const C2ApiFeaturesSetting &getApiFeatures() const {
2012 return mApiFeatures;
2013 }
2014
2015 const C2PortAllocatorsTuning::input &getInputAllocators() const {
2016 static std::unique_ptr<C2PortAllocatorsTuning::input> sInvalidated = []{
2017 std::unique_ptr<C2PortAllocatorsTuning::input> param =
2018 C2PortAllocatorsTuning::input::AllocUnique(0);
2019 param->invalidate();
2020 return param;
2021 }();
2022 return mInputAllocators ? *mInputAllocators : *sInvalidated;
2023 }
2024
2025private:
2026 status_t mInitStatus{NO_INIT};
2027
2028 std::vector<C2FieldSupportedValuesQuery> mFields;
2029 C2ApiFeaturesSetting mApiFeatures;
2030 std::unique_ptr<C2PortAllocatorsTuning::input> mInputAllocators;
2031};
2032
2033static const IntfCache &GetIntfCache(const std::string &name) {
2034 static IntfCache sNullIntfCache;
2035 static std::mutex sMutex;
2036 static std::map<std::string, IntfCache> sCache;
2037 std::unique_lock<std::mutex> lock{sMutex};
2038 auto it = sCache.find(name);
2039 if (it == sCache.end()) {
2040 lock.unlock();
2041 IntfCache intfCache;
2042 status_t err = intfCache.init(name);
2043 if (err != OK) {
2044 return sNullIntfCache;
2045 }
2046 lock.lock();
2047 it = sCache.insert({name, std::move(intfCache)}).first;
2048 }
2049 return it->second;
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002050}
2051
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002052static status_t GetCommonAllocatorIds(
2053 const std::vector<std::string> &names,
2054 C2Allocator::type_t type,
2055 std::set<C2Allocator::id_t> *ids) {
2056 int poolMask = GetCodec2PoolMask();
2057 C2PlatformAllocatorStore::id_t preferredLinearId = GetPreferredLinearAllocatorId(poolMask);
2058 C2Allocator::id_t defaultAllocatorId =
2059 (type == C2Allocator::LINEAR) ? preferredLinearId : C2PlatformAllocatorStore::GRALLOC;
2060
2061 ids->clear();
2062 if (names.empty()) {
2063 return OK;
2064 }
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002065 bool firstIteration = true;
2066 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002067 const IntfCache &intfCache = GetIntfCache(name);
2068 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002069 continue;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002070 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002071 const C2PortAllocatorsTuning::input &allocators = intfCache.getInputAllocators();
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002072 if (firstIteration) {
2073 firstIteration = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002074 if (allocators && allocators.flexCount() > 0) {
2075 ids->insert(allocators.m.values,
2076 allocators.m.values + allocators.flexCount());
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002077 }
2078 if (ids->empty()) {
2079 // The component does not advertise allocators. Use default.
2080 ids->insert(defaultAllocatorId);
2081 }
2082 continue;
2083 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002084 bool filtered = false;
Wonsik Kimffb889a2020-05-28 11:32:25 -07002085 if (allocators && allocators.flexCount() > 0) {
2086 filtered = true;
2087 for (auto it = ids->begin(); it != ids->end(); ) {
2088 bool found = false;
2089 for (size_t j = 0; j < allocators.flexCount(); ++j) {
2090 if (allocators.m.values[j] == *it) {
2091 found = true;
2092 break;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002093 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002094 }
2095 if (found) {
2096 ++it;
2097 } else {
2098 it = ids->erase(it);
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002099 }
2100 }
2101 }
2102 if (!filtered) {
2103 // The component does not advertise supported allocators. Use default.
2104 bool containsDefault = (ids->count(defaultAllocatorId) > 0u);
2105 if (ids->size() != (containsDefault ? 1 : 0)) {
2106 ids->clear();
2107 if (containsDefault) {
2108 ids->insert(defaultAllocatorId);
2109 }
2110 }
2111 }
2112 }
2113 // Finally, filter with pool masks
2114 for (auto it = ids->begin(); it != ids->end(); ) {
2115 if ((poolMask >> *it) & 1) {
2116 ++it;
2117 } else {
2118 it = ids->erase(it);
2119 }
2120 }
2121 return OK;
2122}
2123
2124static status_t CalculateMinMaxUsage(
2125 const std::vector<std::string> &names, uint64_t *minUsage, uint64_t *maxUsage) {
2126 static C2StreamUsageTuning::input sUsage{0u /* stream id */};
2127 *minUsage = 0;
2128 *maxUsage = ~0ull;
2129 for (const std::string &name : names) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002130 const IntfCache &intfCache = GetIntfCache(name);
2131 if (intfCache.initCheck() != OK) {
Wonsik Kimfcf46c32020-04-22 13:50:45 -07002132 continue;
2133 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002134 const C2FieldSupportedValuesQuery &usageSupportedValues =
2135 intfCache.getUsageSupportedValues();
2136 if (usageSupportedValues.status != C2_OK) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002137 continue;
2138 }
Wonsik Kimffb889a2020-05-28 11:32:25 -07002139 const C2FieldSupportedValues &supported = usageSupportedValues.values;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002140 if (supported.type != C2FieldSupportedValues::FLAGS) {
2141 continue;
2142 }
2143 if (supported.values.empty()) {
2144 *maxUsage = 0;
2145 continue;
2146 }
2147 *minUsage |= supported.values[0].u64;
2148 int64_t currentMaxUsage = 0;
2149 for (const C2Value::Primitive &flags : supported.values) {
2150 currentMaxUsage |= flags.u64;
2151 }
2152 *maxUsage &= currentMaxUsage;
2153 }
2154 return OK;
2155}
2156
2157// static
2158status_t CCodec::CanFetchLinearBlock(
2159 const std::vector<std::string> &names, const C2MemoryUsage &usage, bool *isCompatible) {
Wonsik Kimffb889a2020-05-28 11:32:25 -07002160 for (const std::string &name : names) {
2161 const IntfCache &intfCache = GetIntfCache(name);
2162 if (intfCache.initCheck() != OK) {
2163 continue;
2164 }
2165 const C2ApiFeaturesSetting &features = intfCache.getApiFeatures();
2166 if (features && !(features.value & API_SAME_INPUT_BUFFER)) {
2167 *isCompatible = false;
2168 return OK;
2169 }
2170 }
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002171 std::set<C2Allocator::id_t> allocators;
2172 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2173 if (allocators.empty()) {
2174 *isCompatible = false;
2175 return OK;
2176 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002177
2178 uint64_t minUsage = 0;
2179 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002180 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002181 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002182 *isCompatible = ((maxUsage & minUsage) == minUsage);
2183 return OK;
2184}
2185
2186static std::shared_ptr<C2BlockPool> GetPool(C2Allocator::id_t allocId) {
2187 static std::mutex sMutex{};
2188 static std::map<C2Allocator::id_t, std::shared_ptr<C2BlockPool>> sPools;
2189 std::unique_lock<std::mutex> lock{sMutex};
2190 std::shared_ptr<C2BlockPool> pool;
2191 auto it = sPools.find(allocId);
2192 if (it == sPools.end()) {
2193 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2194 if (err == OK) {
2195 sPools.emplace(allocId, pool);
2196 } else {
2197 pool.reset();
2198 }
2199 } else {
2200 pool = it->second;
2201 }
2202 return pool;
2203}
2204
2205// static
2206std::shared_ptr<C2LinearBlock> CCodec::FetchLinearBlock(
2207 size_t capacity, const C2MemoryUsage &usage, const std::vector<std::string> &names) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002208 std::set<C2Allocator::id_t> allocators;
2209 GetCommonAllocatorIds(names, C2Allocator::LINEAR, &allocators);
2210 if (allocators.empty()) {
2211 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2212 }
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002213
2214 uint64_t minUsage = 0;
2215 uint64_t maxUsage = ~0ull;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002216 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
Chih-Yu Huang990b5622020-10-13 14:53:37 +09002217 minUsage |= usage.expected;
Wonsik Kimfb7a7672019-12-27 17:13:33 -08002218 if ((maxUsage & minUsage) != minUsage) {
2219 allocators.clear();
2220 allocators.insert(C2PlatformAllocatorStore::DEFAULT_LINEAR);
2221 }
2222 std::shared_ptr<C2LinearBlock> block;
2223 for (C2Allocator::id_t allocId : allocators) {
2224 std::shared_ptr<C2BlockPool> pool = GetPool(allocId);
2225 if (!pool) {
2226 continue;
2227 }
2228 c2_status_t err = pool->fetchLinearBlock(capacity, C2MemoryUsage{minUsage}, &block);
2229 if (err != C2_OK || !block) {
2230 block.reset();
2231 continue;
2232 }
2233 break;
2234 }
2235 return block;
2236}
2237
2238// static
2239status_t CCodec::CanFetchGraphicBlock(
2240 const std::vector<std::string> &names, bool *isCompatible) {
2241 uint64_t minUsage = 0;
2242 uint64_t maxUsage = ~0ull;
2243 std::set<C2Allocator::id_t> allocators;
2244 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2245 if (allocators.empty()) {
2246 *isCompatible = false;
2247 return OK;
2248 }
2249 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2250 *isCompatible = ((maxUsage & minUsage) == minUsage);
2251 return OK;
2252}
2253
2254// static
2255std::shared_ptr<C2GraphicBlock> CCodec::FetchGraphicBlock(
2256 int32_t width,
2257 int32_t height,
2258 int32_t format,
2259 uint64_t usage,
2260 const std::vector<std::string> &names) {
2261 uint32_t halPixelFormat = HAL_PIXEL_FORMAT_YCBCR_420_888;
2262 if (!C2Mapper::mapPixelFormatFrameworkToCodec(format, &halPixelFormat)) {
2263 ALOGD("Unrecognized pixel format: %d", format);
2264 return nullptr;
2265 }
2266 uint64_t minUsage = 0;
2267 uint64_t maxUsage = ~0ull;
2268 std::set<C2Allocator::id_t> allocators;
2269 GetCommonAllocatorIds(names, C2Allocator::GRAPHIC, &allocators);
2270 if (allocators.empty()) {
2271 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2272 }
2273 CalculateMinMaxUsage(names, &minUsage, &maxUsage);
2274 minUsage |= usage;
2275 if ((maxUsage & minUsage) != minUsage) {
2276 allocators.clear();
2277 allocators.insert(C2PlatformAllocatorStore::DEFAULT_GRAPHIC);
2278 }
2279 std::shared_ptr<C2GraphicBlock> block;
2280 for (C2Allocator::id_t allocId : allocators) {
2281 std::shared_ptr<C2BlockPool> pool;
2282 c2_status_t err = CreateCodec2BlockPool(allocId, nullptr, &pool);
2283 if (err != C2_OK || !pool) {
2284 continue;
2285 }
2286 err = pool->fetchGraphicBlock(
2287 width, height, halPixelFormat, C2MemoryUsage{minUsage}, &block);
2288 if (err != C2_OK || !block) {
2289 block.reset();
2290 continue;
2291 }
2292 break;
2293 }
2294 return block;
2295}
2296
Wonsik Kim155d5cb2019-10-09 12:49:49 -07002297} // namespace android
2298