blob: 8474ce831ab740353b1a3f4e07fe2e25b3ed9271 [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
29#include <android/IGraphicBufferSource.h>
30#include <android/IOMXBufferSource.h>
31#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>
38#include <media/omx/1.0/WGraphicBufferSource.h>
39#include <media/openmax/OMX_IndexExt.h>
40#include <media/stagefright/BufferProducerWrapper.h>
41#include <media/stagefright/MediaCodecConstants.h>
42#include <media/stagefright/PersistentSurface.h>
43#include <media/stagefright/codec2/1.0/InputSurface.h>
44
45#include "C2OMXNode.h"
46#include "CCodec.h"
47#include "CCodecBufferChannel.h"
48#include "InputSurfaceWrapper.h"
49
50extern "C" android::PersistentSurface *CreateInputSurface();
51
52namespace android {
53
54using namespace std::chrono_literals;
55using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
56using android::base::StringPrintf;
57using BGraphicBufferSource = ::android::IGraphicBufferSource;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080058using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080059
60namespace {
61
62class CCodecWatchdog : public AHandler {
63private:
64 enum {
65 kWhatWatch,
66 };
67 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
68
69public:
70 static sp<CCodecWatchdog> getInstance() {
71 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
72 static std::once_flag flag;
73 // Call Init() only once.
74 std::call_once(flag, Init, instance);
75 return instance;
76 }
77
78 ~CCodecWatchdog() = default;
79
80 void watch(sp<CCodec> codec) {
81 bool shouldPost = false;
82 {
83 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
84 // If a watch message is in flight, piggy-back this instance as well.
85 // Otherwise, post a new watch message.
86 shouldPost = codecs->empty();
87 codecs->emplace(codec);
88 }
89 if (shouldPost) {
90 ALOGV("posting watch message");
91 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
92 }
93 }
94
95protected:
96 void onMessageReceived(const sp<AMessage> &msg) {
97 switch (msg->what()) {
98 case kWhatWatch: {
99 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
100 ALOGV("watch for %zu codecs", codecs->size());
101 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
102 sp<CCodec> codec = it->promote();
103 if (codec == nullptr) {
104 continue;
105 }
106 codec->initiateReleaseIfStuck();
107 }
108 codecs->clear();
109 break;
110 }
111
112 default: {
113 TRESPASS("CCodecWatchdog: unrecognized message");
114 }
115 }
116 }
117
118private:
119 CCodecWatchdog() : mLooper(new ALooper) {}
120
121 static void Init(const sp<CCodecWatchdog> &thiz) {
122 ALOGV("Init");
123 thiz->mLooper->setName("CCodecWatchdog");
124 thiz->mLooper->registerHandler(thiz);
125 thiz->mLooper->start();
126 }
127
128 sp<ALooper> mLooper;
129
130 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
131};
132
133class C2InputSurfaceWrapper : public InputSurfaceWrapper {
134public:
135 explicit C2InputSurfaceWrapper(
136 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
137 mSurface(surface) {
138 }
139
140 ~C2InputSurfaceWrapper() override = default;
141
142 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
143 if (mConnection != nullptr) {
144 return ALREADY_EXISTS;
145 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800146 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800147 }
148
149 void disconnect() override {
150 if (mConnection != nullptr) {
151 mConnection->disconnect();
152 mConnection = nullptr;
153 }
154 }
155
156 status_t start() override {
157 // InputSurface does not distinguish started state
158 return OK;
159 }
160
161 status_t signalEndOfInputStream() override {
162 C2InputSurfaceEosTuning eos(true);
163 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800164 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800165 if (err != C2_OK) {
166 return UNKNOWN_ERROR;
167 }
168 return OK;
169 }
170
171 status_t configure(Config &config __unused) {
172 // TODO
173 return OK;
174 }
175
176private:
177 std::shared_ptr<Codec2Client::InputSurface> mSurface;
178 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
179};
180
181class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
182public:
183// explicit GraphicBufferSourceWrapper(const sp<BGraphicBufferSource> &source) : mSource(source) {}
184 GraphicBufferSourceWrapper(
185 const sp<BGraphicBufferSource> &source,
186 uint32_t width,
187 uint32_t height)
188 : mSource(source), mWidth(width), mHeight(height) {
189 mDataSpace = HAL_DATASPACE_BT709;
190 }
191 ~GraphicBufferSourceWrapper() override = default;
192
193 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
194 mNode = new C2OMXNode(comp);
195 mNode->setFrameSize(mWidth, mHeight);
196
197 // NOTE: we do not use/pass through color aspects from GraphicBufferSource as we
198 // communicate that directly to the component.
199 mSource->configure(mNode, mDataSpace);
200 return OK;
201 }
202
203 void disconnect() override {
204 if (mNode == nullptr) {
205 return;
206 }
207 sp<IOMXBufferSource> source = mNode->getSource();
208 if (source == nullptr) {
209 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
210 return;
211 }
212 source->onOmxIdle();
213 source->onOmxLoaded();
214 mNode.clear();
215 }
216
217 status_t GetStatus(const binder::Status &status) {
218 status_t err = OK;
219 if (!status.isOk()) {
220 err = status.serviceSpecificErrorCode();
221 if (err == OK) {
222 err = status.transactionError();
223 if (err == OK) {
224 // binder status failed, but there is no servie or transaction error
225 err = UNKNOWN_ERROR;
226 }
227 }
228 }
229 return err;
230 }
231
232 status_t start() override {
233 sp<IOMXBufferSource> source = mNode->getSource();
234 if (source == nullptr) {
235 return NO_INIT;
236 }
237 constexpr size_t kNumSlots = 16;
238 for (size_t i = 0; i < kNumSlots; ++i) {
239 source->onInputBufferAdded(i);
240 }
241
242 source->onOmxExecuting();
243 return OK;
244 }
245
246 status_t signalEndOfInputStream() override {
247 return GetStatus(mSource->signalEndOfInputStream());
248 }
249
250 status_t configure(Config &config) {
251 std::stringstream status;
252 status_t err = OK;
253
254 // handle each configuration granually, in case we need to handle part of the configuration
255 // elsewhere
256
257 // TRICKY: we do not unset frame delay repeating
258 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
259 int64_t us = 1e6 / config.mMinFps + 0.5;
260 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
261 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
262 if (res != OK) {
263 status << " (=> " << asString(res) << ")";
264 err = res;
265 }
266 mConfig.mMinFps = config.mMinFps;
267 }
268
269 // pts gap
270 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
271 if (mNode != nullptr) {
272 OMX_PARAM_U32TYPE ptrGapParam = {};
273 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700274 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800275 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
276 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700277 // float -> uint32_t is undefined if the value is negative.
278 // First convert to int32_t to ensure the expected behavior.
279 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800280 (void)mNode->setParameter(
281 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
282 &ptrGapParam, sizeof(ptrGapParam));
283 }
284 }
285
286 // max fps
287 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700288 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800289 && config.mMaxFps != mConfig.mMaxFps) {
290 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
291 status << " maxFps=" << config.mMaxFps;
292 if (res != OK) {
293 status << " (=> " << asString(res) << ")";
294 err = res;
295 }
296 mConfig.mMaxFps = config.mMaxFps;
297 }
298
299 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
300 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
301 status << " timeOffset " << config.mTimeOffsetUs << "us";
302 if (res != OK) {
303 status << " (=> " << asString(res) << ")";
304 err = res;
305 }
306 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
307 }
308
309 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
310 status_t res =
311 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
312 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
313 if (res != OK) {
314 status << " (=> " << asString(res) << ")";
315 err = res;
316 }
317 mConfig.mCaptureFps = config.mCaptureFps;
318 mConfig.mCodedFps = config.mCodedFps;
319 }
320
321 if (config.mStartAtUs != mConfig.mStartAtUs
322 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
323 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
324 status << " start at " << config.mStartAtUs << "us";
325 if (res != OK) {
326 status << " (=> " << asString(res) << ")";
327 err = res;
328 }
329 mConfig.mStartAtUs = config.mStartAtUs;
330 mConfig.mStopped = config.mStopped;
331 }
332
333 // suspend-resume
334 if (config.mSuspended != mConfig.mSuspended) {
335 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
336 status << " " << (config.mSuspended ? "suspend" : "resume")
337 << " at " << config.mSuspendAtUs << "us";
338 if (res != OK) {
339 status << " (=> " << asString(res) << ")";
340 err = res;
341 }
342 mConfig.mSuspended = config.mSuspended;
343 mConfig.mSuspendAtUs = config.mSuspendAtUs;
344 }
345
346 if (config.mStopped != mConfig.mStopped && config.mStopped) {
347 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
348 status << " stop at " << config.mStopAtUs << "us";
349 if (res != OK) {
350 status << " (=> " << asString(res) << ")";
351 err = res;
352 } else {
353 status << " delayUs";
354 res = GetStatus(mSource->getStopTimeOffsetUs(&config.mInputDelayUs));
355 if (res != OK) {
356 status << " (=> " << asString(res) << ")";
357 } else {
358 status << "=" << config.mInputDelayUs << "us";
359 }
360 mConfig.mInputDelayUs = config.mInputDelayUs;
361 }
362 mConfig.mStopAtUs = config.mStopAtUs;
363 mConfig.mStopped = config.mStopped;
364 }
365
366 // color aspects (android._color-aspects)
367
368 // consumer usage
369 ALOGD("ISConfig%s", status.str().c_str());
370 return err;
371 }
372
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700373 void onInputBufferDone(c2_cntr64_t index) override {
374 mNode->onInputBufferDone(index);
375 }
376
Pawin Vongmasa36653902018-11-15 00:10:25 -0800377private:
378 sp<BGraphicBufferSource> mSource;
379 sp<C2OMXNode> mNode;
380 uint32_t mWidth;
381 uint32_t mHeight;
382 Config mConfig;
383};
384
385class Codec2ClientInterfaceWrapper : public C2ComponentStore {
386 std::shared_ptr<Codec2Client> mClient;
387
388public:
389 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
390 : mClient(client) { }
391
392 virtual ~Codec2ClientInterfaceWrapper() = default;
393
394 virtual c2_status_t config_sm(
395 const std::vector<C2Param *> &params,
396 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
397 return mClient->config(params, C2_MAY_BLOCK, failures);
398 };
399
400 virtual c2_status_t copyBuffer(
401 std::shared_ptr<C2GraphicBuffer>,
402 std::shared_ptr<C2GraphicBuffer>) {
403 return C2_OMITTED;
404 }
405
406 virtual c2_status_t createComponent(
407 C2String, std::shared_ptr<C2Component> *const component) {
408 component->reset();
409 return C2_OMITTED;
410 }
411
412 virtual c2_status_t createInterface(
413 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
414 interface->reset();
415 return C2_OMITTED;
416 }
417
418 virtual c2_status_t query_sm(
419 const std::vector<C2Param *> &stackParams,
420 const std::vector<C2Param::Index> &heapParamIndices,
421 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
422 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
423 }
424
425 virtual c2_status_t querySupportedParams_nb(
426 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
427 return mClient->querySupportedParams(params);
428 }
429
430 virtual c2_status_t querySupportedValues_sm(
431 std::vector<C2FieldSupportedValuesQuery> &fields) const {
432 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
433 }
434
435 virtual C2String getName() const {
436 return mClient->getName();
437 }
438
439 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
440 return mClient->getParamReflector();
441 }
442
443 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
444 return std::vector<std::shared_ptr<const C2Component::Traits>>();
445 }
446};
447
448} // namespace
449
450// CCodec::ClientListener
451
452struct CCodec::ClientListener : public Codec2Client::Listener {
453
454 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
455
456 virtual void onWorkDone(
457 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800458 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800459 (void)component;
460 sp<CCodec> codec(mCodec.promote());
461 if (!codec) {
462 return;
463 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800464 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800465 }
466
467 virtual void onTripped(
468 const std::weak_ptr<Codec2Client::Component>& component,
469 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
470 ) override {
471 // TODO
472 (void)component;
473 (void)settingResult;
474 }
475
476 virtual void onError(
477 const std::weak_ptr<Codec2Client::Component>& component,
478 uint32_t errorCode) override {
479 // TODO
480 (void)component;
481 (void)errorCode;
482 }
483
484 virtual void onDeath(
485 const std::weak_ptr<Codec2Client::Component>& component) override {
486 { // Log the death of the component.
487 std::shared_ptr<Codec2Client::Component> comp = component.lock();
488 if (!comp) {
489 ALOGE("Codec2 component died.");
490 } else {
491 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
492 }
493 }
494
495 // Report to MediaCodec.
496 sp<CCodec> codec(mCodec.promote());
497 if (!codec || !codec->mCallback) {
498 return;
499 }
500 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
501 }
502
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800503 virtual void onFrameRendered(uint64_t bufferQueueId,
504 int32_t slotId,
505 int64_t timestampNs) override {
506 // TODO: implement
507 (void)bufferQueueId;
508 (void)slotId;
509 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800510 }
511
512 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800513 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800514 sp<CCodec> codec(mCodec.promote());
515 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800516 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800517 }
518 }
519
520private:
521 wp<CCodec> mCodec;
522};
523
524// CCodecCallbackImpl
525
526class CCodecCallbackImpl : public CCodecCallback {
527public:
528 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
529 ~CCodecCallbackImpl() override = default;
530
531 void onError(status_t err, enum ActionCode actionCode) override {
532 mCodec->mCallback->onError(err, actionCode);
533 }
534
535 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
536 mCodec->mCallback->onOutputFramesRendered(
537 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
538 }
539
Pawin Vongmasa36653902018-11-15 00:10:25 -0800540 void onOutputBuffersChanged() override {
541 mCodec->mCallback->onOutputBuffersChanged();
542 }
543
544private:
545 CCodec *mCodec;
546};
547
548// CCodec
549
550CCodec::CCodec()
Wonsik Kimab34ed62019-01-31 15:28:46 -0800551 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800552}
553
554CCodec::~CCodec() {
555}
556
557std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
558 return mChannel;
559}
560
561status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
562 status_t err = job();
563 if (err != C2_OK) {
564 mCallback->onError(err, ACTION_CODE_FATAL);
565 }
566 return err;
567}
568
569void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
570 auto setAllocating = [this] {
571 Mutexed<State>::Locked state(mState);
572 if (state->get() != RELEASED) {
573 return INVALID_OPERATION;
574 }
575 state->set(ALLOCATING);
576 return OK;
577 };
578 if (tryAndReportOnError(setAllocating) != OK) {
579 return;
580 }
581
582 sp<RefBase> codecInfo;
583 CHECK(msg->findObject("codecInfo", &codecInfo));
584 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
585
586 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
587 allocMsg->setObject("codecInfo", codecInfo);
588 allocMsg->post();
589}
590
591void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
592 if (codecInfo == nullptr) {
593 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
594 return;
595 }
596 ALOGD("allocate(%s)", codecInfo->getCodecName());
597 mClientListener.reset(new ClientListener(this));
598
599 AString componentName = codecInfo->getCodecName();
600 std::shared_ptr<Codec2Client> client;
601
602 // set up preferred component store to access vendor store parameters
603 client = Codec2Client::CreateFromService("default", false);
604 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800605 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800606 SetPreferredCodec2ComponentStore(
607 std::make_shared<Codec2ClientInterfaceWrapper>(client));
608 }
609
610 std::shared_ptr<Codec2Client::Component> comp =
611 Codec2Client::CreateComponentByName(
612 componentName.c_str(),
613 mClientListener,
614 &client);
615 if (!comp) {
616 ALOGE("Failed Create component: %s", componentName.c_str());
617 Mutexed<State>::Locked state(mState);
618 state->set(RELEASED);
619 state.unlock();
620 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
621 state.lock();
622 return;
623 }
624 ALOGI("Created component [%s]", componentName.c_str());
625 mChannel->setComponent(comp);
626 auto setAllocated = [this, comp, client] {
627 Mutexed<State>::Locked state(mState);
628 if (state->get() != ALLOCATING) {
629 state->set(RELEASED);
630 return UNKNOWN_ERROR;
631 }
632 state->set(ALLOCATED);
633 state->comp = comp;
634 mClient = client;
635 return OK;
636 };
637 if (tryAndReportOnError(setAllocated) != OK) {
638 return;
639 }
640
641 // initialize config here in case setParameters is called prior to configure
642 Mutexed<Config>::Locked config(mConfig);
643 status_t err = config->initialize(mClient, comp);
644 if (err != OK) {
645 ALOGW("Failed to initialize configuration support");
646 // TODO: report error once we complete implementation.
647 }
648 config->queryConfiguration(comp);
649
650 mCallback->onComponentAllocated(componentName.c_str());
651}
652
653void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
654 auto checkAllocated = [this] {
655 Mutexed<State>::Locked state(mState);
656 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
657 };
658 if (tryAndReportOnError(checkAllocated) != OK) {
659 return;
660 }
661
662 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
663 msg->setMessage("format", format);
664 msg->post();
665}
666
667void CCodec::configure(const sp<AMessage> &msg) {
668 std::shared_ptr<Codec2Client::Component> comp;
669 auto checkAllocated = [this, &comp] {
670 Mutexed<State>::Locked state(mState);
671 if (state->get() != ALLOCATED) {
672 state->set(RELEASED);
673 return UNKNOWN_ERROR;
674 }
675 comp = state->comp;
676 return OK;
677 };
678 if (tryAndReportOnError(checkAllocated) != OK) {
679 return;
680 }
681
682 auto doConfig = [msg, comp, this]() -> status_t {
683 AString mime;
684 if (!msg->findString("mime", &mime)) {
685 return BAD_VALUE;
686 }
687
688 int32_t encoder;
689 if (!msg->findInt32("encoder", &encoder)) {
690 encoder = false;
691 }
692
693 // TODO: read from intf()
694 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
695 return UNKNOWN_ERROR;
696 }
697
698 int32_t storeMeta;
699 if (encoder
700 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
701 && storeMeta != kMetadataBufferTypeInvalid) {
702 if (storeMeta != kMetadataBufferTypeANWBuffer) {
703 ALOGD("Only ANW buffers are supported for legacy metadata mode");
704 return BAD_VALUE;
705 }
706 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
707 }
708
709 sp<RefBase> obj;
710 sp<Surface> surface;
711 if (msg->findObject("native-window", &obj)) {
712 surface = static_cast<Surface *>(obj.get());
713 setSurface(surface);
714 }
715
716 Mutexed<Config>::Locked config(mConfig);
717 config->mUsingSurface = surface != nullptr;
718
Wonsik Kim1114eea2019-02-25 14:35:24 -0800719 // Enforce required parameters
720 int32_t i32;
721 float flt;
722 if (config->mDomain & Config::IS_AUDIO) {
723 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
724 ALOGD("sample rate is missing, which is required for audio components.");
725 return BAD_VALUE;
726 }
727 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
728 ALOGD("channel count is missing, which is required for audio components.");
729 return BAD_VALUE;
730 }
731 if ((config->mDomain & Config::IS_ENCODER)
732 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
733 && !msg->findInt32(KEY_BIT_RATE, &i32)
734 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
735 ALOGD("bitrate is missing, which is required for audio encoders.");
736 return BAD_VALUE;
737 }
738 }
739 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
740 if (!msg->findInt32(KEY_WIDTH, &i32)) {
741 ALOGD("width is missing, which is required for image/video components.");
742 return BAD_VALUE;
743 }
744 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
745 ALOGD("height is missing, which is required for image/video components.");
746 return BAD_VALUE;
747 }
748 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700749 C2Config::bitrate_mode_t mode = C2Config::BITRATE_VARIABLE;
750 if (msg->findInt32(KEY_BITRATE_MODE, &i32)) {
751 mode = (C2Config::bitrate_mode_t) i32;
752 }
753 if (mode == BITRATE_MODE_CQ) {
754 if (!msg->findInt32(KEY_QUALITY, &i32)) {
755 ALOGD("quality is missing, which is required for video encoders in CQ.");
756 return BAD_VALUE;
757 }
758 } else {
759 if (!msg->findInt32(KEY_BIT_RATE, &i32)
760 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
761 ALOGD("bitrate is missing, which is required for video encoders.");
762 return BAD_VALUE;
763 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800764 }
765 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
766 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
767 ALOGD("I frame interval is missing, which is required for video encoders.");
768 return BAD_VALUE;
769 }
770 }
771 }
772
Pawin Vongmasa36653902018-11-15 00:10:25 -0800773 /*
774 * Handle input surface configuration
775 */
776 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
777 && (config->mDomain & Config::IS_ENCODER)) {
778 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
779 {
780 config->mISConfig->mMinFps = 0;
781 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800782 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800783 config->mISConfig->mMinFps = 1e6 / value;
784 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700785 if (!msg->findFloat(
786 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
787 config->mISConfig->mMaxFps = -1;
788 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800789 config->mISConfig->mMinAdjustedFps = 0;
790 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800791 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800792 if (value < 0 && value >= INT32_MIN) {
793 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700794 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800795 } else if (value > 0 && value <= INT32_MAX) {
796 config->mISConfig->mMinAdjustedFps = 1e6 / value;
797 }
798 }
799 }
800
801 {
802 double value;
803 if (msg->findDouble("time-lapse-fps", &value)) {
804 config->mISConfig->mCaptureFps = value;
805 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
806 }
807 }
808
809 {
810 config->mISConfig->mSuspended = false;
811 config->mISConfig->mSuspendAtUs = -1;
812 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800813 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800814 config->mISConfig->mSuspended = true;
815 }
816 }
817 }
818
819 /*
820 * Handle desired color format.
821 */
822 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
823 int32_t format = -1;
824 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
825 /*
826 * Also handle default color format (encoders require color format, so this is only
827 * needed for decoders.
828 */
829 if (!(config->mDomain & Config::IS_ENCODER)) {
830 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
831 }
832 }
833
834 if (format >= 0) {
835 msg->setInt32("android._color-format", format);
836 }
837 }
838
839 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800840 // NOTE: We used to ignore "video-bitrate" at configure; replicate
841 // the behavior here.
842 sp<AMessage> sdkParams = msg;
843 int32_t videoBitrate;
844 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
845 sdkParams = msg->dup();
846 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
847 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800848 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800849 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800850 if (err != OK) {
851 ALOGW("failed to convert configuration to c2 params");
852 }
853 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
854 if (err != OK) {
855 ALOGW("failed to configure c2 params");
856 return err;
857 }
858
859 std::vector<std::unique_ptr<C2Param>> params;
860 C2StreamUsageTuning::input usage(0u, 0u);
861 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
862
863 std::initializer_list<C2Param::Index> indices {
864 };
865 c2_status_t c2err = comp->query(
866 { &usage, &maxInputSize },
867 indices,
868 C2_DONT_BLOCK,
869 &params);
870 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
871 ALOGE("Failed to query component interface: %d", c2err);
872 return UNKNOWN_ERROR;
873 }
874 if (params.size() != indices.size()) {
875 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
876 indices.size(), params.size());
877 return UNKNOWN_ERROR;
878 }
879 if (usage && (usage.value & C2MemoryUsage::CPU_READ)) {
880 config->mInputFormat->setInt32("using-sw-read-often", true);
881 }
882
883 // NOTE: we don't blindly use client specified input size if specified as clients
884 // at times specify too small size. Instead, mimic the behavior from OMX, where the
885 // client specified size is only used to ask for bigger buffers than component suggested
886 // size.
887 int32_t clientInputSize = 0;
888 bool clientSpecifiedInputSize =
889 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
890 // TEMP: enforce minimum buffer size of 1MB for video decoders
891 // and 16K / 4K for audio encoders/decoders
892 if (maxInputSize.value == 0) {
893 if (config->mDomain & Config::IS_AUDIO) {
894 maxInputSize.value = encoder ? 16384 : 4096;
895 } else if (!encoder) {
896 maxInputSize.value = 1048576u;
897 }
898 }
899
900 // verify that CSD fits into this size (if defined)
901 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
902 sp<ABuffer> csd;
903 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
904 if (csd && csd->size() > maxInputSize.value) {
905 maxInputSize.value = csd->size();
906 }
907 }
908 }
909
910 // TODO: do this based on component requiring linear allocator for input
911 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
912 if (clientSpecifiedInputSize) {
913 // Warn that we're overriding client's max input size if necessary.
914 if ((uint32_t)clientInputSize < maxInputSize.value) {
915 ALOGD("client requested max input size %d, which is smaller than "
916 "what component recommended (%u); overriding with component "
917 "recommendation.", clientInputSize, maxInputSize.value);
918 ALOGW("This behavior is subject to change. It is recommended that "
919 "app developers double check whether the requested "
920 "max input size is in reasonable range.");
921 } else {
922 maxInputSize.value = clientInputSize;
923 }
924 }
925 // Pass max input size on input format to the buffer channel (if supplied by the
926 // component or by a default)
927 if (maxInputSize.value) {
928 config->mInputFormat->setInt32(
929 KEY_MAX_INPUT_SIZE,
930 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
931 }
932 }
933
934 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
935 // propagate HDR static info to output format for both encoders and decoders
936 // if component supports this info, we will update from component, but only the raw port,
937 // so don't propagate if component already filled it in.
938 sp<ABuffer> hdrInfo;
939 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
940 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
941 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
942 }
943
944 // Set desired color format from configuration parameter
945 int32_t format;
946 if (msg->findInt32("android._color-format", &format)) {
947 if (config->mDomain & Config::IS_ENCODER) {
948 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
949 } else {
950 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
951 }
952 }
953 }
954
955 // propagate encoder delay and padding to output format
956 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
957 int delay = 0;
958 if (msg->findInt32("encoder-delay", &delay)) {
959 config->mOutputFormat->setInt32("encoder-delay", delay);
960 }
961 int padding = 0;
962 if (msg->findInt32("encoder-padding", &padding)) {
963 config->mOutputFormat->setInt32("encoder-padding", padding);
964 }
965 }
966
967 // set channel-mask
968 if (config->mDomain & Config::IS_AUDIO) {
969 int32_t mask;
970 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
971 if (config->mDomain & Config::IS_ENCODER) {
972 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
973 } else {
974 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
975 }
976 }
977 }
978
979 ALOGD("setup formats input: %s and output: %s",
980 config->mInputFormat->debugString().c_str(),
981 config->mOutputFormat->debugString().c_str());
982 return OK;
983 };
984 if (tryAndReportOnError(doConfig) != OK) {
985 return;
986 }
987
988 Mutexed<Config>::Locked config(mConfig);
989
990 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
991}
992
993void CCodec::initiateCreateInputSurface() {
994 status_t err = [this] {
995 Mutexed<State>::Locked state(mState);
996 if (state->get() != ALLOCATED) {
997 return UNKNOWN_ERROR;
998 }
999 // TODO: read it from intf() properly.
1000 if (state->comp->getName().find("encoder") == std::string::npos) {
1001 return INVALID_OPERATION;
1002 }
1003 return OK;
1004 }();
1005 if (err != OK) {
1006 mCallback->onInputSurfaceCreationFailed(err);
1007 return;
1008 }
1009
1010 (new AMessage(kWhatCreateInputSurface, this))->post();
1011}
1012
Lajos Molnar47118272019-01-31 16:28:04 -08001013sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1014 using namespace android::hardware::media::omx::V1_0;
1015 using namespace android::hardware::media::omx::V1_0::utils;
1016 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1017 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1018 android::sp<IOmx> omx = IOmx::getService();
1019 typedef android::hardware::graphics::bufferqueue::V1_0::
1020 IGraphicBufferProducer HGraphicBufferProducer;
1021 typedef android::hardware::media::omx::V1_0::
1022 IGraphicBufferSource HGraphicBufferSource;
1023 OmxStatus s;
1024 android::sp<HGraphicBufferProducer> gbp;
1025 android::sp<HGraphicBufferSource> gbs;
1026 android::Return<void> transStatus = omx->createInputSurface(
1027 [&s, &gbp, &gbs](
1028 OmxStatus status,
1029 const android::sp<HGraphicBufferProducer>& producer,
1030 const android::sp<HGraphicBufferSource>& source) {
1031 s = status;
1032 gbp = producer;
1033 gbs = source;
1034 });
1035 if (transStatus.isOk() && s == OmxStatus::OK) {
1036 return new PersistentSurface(
1037 new H2BGraphicBufferProducer(gbp),
1038 sp<::android::IGraphicBufferSource>(new LWGraphicBufferSource(gbs)));
1039 }
1040
1041 return nullptr;
1042}
1043
1044sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1045 sp<PersistentSurface> surface(CreateInputSurface());
1046
1047 if (surface == nullptr) {
1048 surface = CreateOmxInputSurface();
1049 }
1050
1051 return surface;
1052}
1053
Pawin Vongmasa36653902018-11-15 00:10:25 -08001054void CCodec::createInputSurface() {
1055 status_t err;
1056 sp<IGraphicBufferProducer> bufferProducer;
1057
1058 sp<AMessage> inputFormat;
1059 sp<AMessage> outputFormat;
1060 {
1061 Mutexed<Config>::Locked config(mConfig);
1062 inputFormat = config->mInputFormat;
1063 outputFormat = config->mOutputFormat;
1064 }
1065
Lajos Molnar47118272019-01-31 16:28:04 -08001066 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001067
1068 if (persistentSurface->getHidlTarget()) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001069 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001070 persistentSurface->getHidlTarget());
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001071 if (!hidlInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001072 ALOGE("Corrupted input surface");
1073 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1074 return;
1075 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001076 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1077 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001078 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001079 inputSurface));
1080 bufferProducer = inputSurface->getGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001081 } else {
1082 int32_t width = 0;
1083 (void)outputFormat->findInt32("width", &width);
1084 int32_t height = 0;
1085 (void)outputFormat->findInt32("height", &height);
1086 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1087 persistentSurface->getBufferSource(), width, height));
1088 bufferProducer = persistentSurface->getBufferProducer();
1089 }
1090
1091 if (err != OK) {
1092 ALOGE("Failed to set up input surface: %d", err);
1093 mCallback->onInputSurfaceCreationFailed(err);
1094 return;
1095 }
1096
1097 mCallback->onInputSurfaceCreated(
1098 inputFormat,
1099 outputFormat,
1100 new BufferProducerWrapper(bufferProducer));
1101}
1102
1103status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
1104 Mutexed<Config>::Locked config(mConfig);
1105 config->mUsingSurface = true;
1106
1107 // we are now using surface - apply default color aspects to input format - as well as
1108 // get dataspace
1109 bool inputFormatChanged = config->updateFormats(config->IS_INPUT);
1110 ALOGD("input format %s to %s",
1111 inputFormatChanged ? "changed" : "unchanged",
1112 config->mInputFormat->debugString().c_str());
1113
1114 // configure dataspace
1115 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1116 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1117 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1118 surface->setDataSpace(dataSpace);
1119
1120 status_t err = mChannel->setInputSurface(surface);
1121 if (err != OK) {
1122 // undo input format update
1123 config->mUsingSurface = false;
1124 (void)config->updateFormats(config->IS_INPUT);
1125 return err;
1126 }
1127 config->mInputSurface = surface;
1128
1129 if (config->mISConfig) {
1130 surface->configure(*config->mISConfig);
1131 } else {
1132 ALOGD("ISConfig: no configuration");
1133 }
1134
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001135 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001136}
1137
1138void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1139 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1140 msg->setObject("surface", surface);
1141 msg->post();
1142}
1143
1144void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1145 sp<AMessage> inputFormat;
1146 sp<AMessage> outputFormat;
1147 {
1148 Mutexed<Config>::Locked config(mConfig);
1149 inputFormat = config->mInputFormat;
1150 outputFormat = config->mOutputFormat;
1151 }
1152 auto hidlTarget = surface->getHidlTarget();
1153 if (hidlTarget) {
1154 sp<IInputSurface> inputSurface =
1155 IInputSurface::castFrom(hidlTarget);
1156 if (!inputSurface) {
1157 ALOGE("Failed to set input surface: Corrupted surface.");
1158 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1159 return;
1160 }
1161 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1162 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1163 if (err != OK) {
1164 ALOGE("Failed to set up input surface: %d", err);
1165 mCallback->onInputSurfaceDeclined(err);
1166 return;
1167 }
1168 } else {
1169 int32_t width = 0;
1170 (void)outputFormat->findInt32("width", &width);
1171 int32_t height = 0;
1172 (void)outputFormat->findInt32("height", &height);
1173 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1174 surface->getBufferSource(), width, height));
1175 if (err != OK) {
1176 ALOGE("Failed to set up input surface: %d", err);
1177 mCallback->onInputSurfaceDeclined(err);
1178 return;
1179 }
1180 }
1181 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1182}
1183
1184void CCodec::initiateStart() {
1185 auto setStarting = [this] {
1186 Mutexed<State>::Locked state(mState);
1187 if (state->get() != ALLOCATED) {
1188 return UNKNOWN_ERROR;
1189 }
1190 state->set(STARTING);
1191 return OK;
1192 };
1193 if (tryAndReportOnError(setStarting) != OK) {
1194 return;
1195 }
1196
1197 (new AMessage(kWhatStart, this))->post();
1198}
1199
1200void CCodec::start() {
1201 std::shared_ptr<Codec2Client::Component> comp;
1202 auto checkStarting = [this, &comp] {
1203 Mutexed<State>::Locked state(mState);
1204 if (state->get() != STARTING) {
1205 return UNKNOWN_ERROR;
1206 }
1207 comp = state->comp;
1208 return OK;
1209 };
1210 if (tryAndReportOnError(checkStarting) != OK) {
1211 return;
1212 }
1213
1214 c2_status_t err = comp->start();
1215 if (err != C2_OK) {
1216 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1217 ACTION_CODE_FATAL);
1218 return;
1219 }
1220 sp<AMessage> inputFormat;
1221 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001222 status_t err2 = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001223 {
1224 Mutexed<Config>::Locked config(mConfig);
1225 inputFormat = config->mInputFormat;
1226 outputFormat = config->mOutputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001227 if (config->mInputSurface) {
1228 err2 = config->mInputSurface->start();
1229 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001230 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001231 if (err2 != OK) {
1232 mCallback->onError(err2, ACTION_CODE_FATAL);
1233 return;
1234 }
1235 err2 = mChannel->start(inputFormat, outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001236 if (err2 != OK) {
1237 mCallback->onError(err2, ACTION_CODE_FATAL);
1238 return;
1239 }
1240
1241 auto setRunning = [this] {
1242 Mutexed<State>::Locked state(mState);
1243 if (state->get() != STARTING) {
1244 return UNKNOWN_ERROR;
1245 }
1246 state->set(RUNNING);
1247 return OK;
1248 };
1249 if (tryAndReportOnError(setRunning) != OK) {
1250 return;
1251 }
1252 mCallback->onStartCompleted();
1253
1254 (void)mChannel->requestInitialInputBuffers();
1255}
1256
1257void CCodec::initiateShutdown(bool keepComponentAllocated) {
1258 if (keepComponentAllocated) {
1259 initiateStop();
1260 } else {
1261 initiateRelease();
1262 }
1263}
1264
1265void CCodec::initiateStop() {
1266 {
1267 Mutexed<State>::Locked state(mState);
1268 if (state->get() == ALLOCATED
1269 || state->get() == RELEASED
1270 || state->get() == STOPPING
1271 || state->get() == RELEASING) {
1272 // We're already stopped, released, or doing it right now.
1273 state.unlock();
1274 mCallback->onStopCompleted();
1275 state.lock();
1276 return;
1277 }
1278 state->set(STOPPING);
1279 }
1280
1281 mChannel->stop();
1282 (new AMessage(kWhatStop, this))->post();
1283}
1284
1285void CCodec::stop() {
1286 std::shared_ptr<Codec2Client::Component> comp;
1287 {
1288 Mutexed<State>::Locked state(mState);
1289 if (state->get() == RELEASING) {
1290 state.unlock();
1291 // We're already stopped or release is in progress.
1292 mCallback->onStopCompleted();
1293 state.lock();
1294 return;
1295 } else if (state->get() != STOPPING) {
1296 state.unlock();
1297 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1298 state.lock();
1299 return;
1300 }
1301 comp = state->comp;
1302 }
1303 status_t err = comp->stop();
1304 if (err != C2_OK) {
1305 // TODO: convert err into status_t
1306 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1307 }
1308
1309 {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001310 Mutexed<Config>::Locked config(mConfig);
1311 if (config->mInputSurface) {
1312 config->mInputSurface->disconnect();
1313 config->mInputSurface = nullptr;
1314 }
1315 }
1316 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001317 Mutexed<State>::Locked state(mState);
1318 if (state->get() == STOPPING) {
1319 state->set(ALLOCATED);
1320 }
1321 }
1322 mCallback->onStopCompleted();
1323}
1324
1325void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001326 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001327 {
1328 Mutexed<State>::Locked state(mState);
1329 if (state->get() == RELEASED || state->get() == RELEASING) {
1330 // We're already released or doing it right now.
1331 if (sendCallback) {
1332 state.unlock();
1333 mCallback->onReleaseCompleted();
1334 state.lock();
1335 }
1336 return;
1337 }
1338 if (state->get() == ALLOCATING) {
1339 state->set(RELEASING);
1340 // With the altered state allocate() would fail and clean up.
1341 if (sendCallback) {
1342 state.unlock();
1343 mCallback->onReleaseCompleted();
1344 state.lock();
1345 }
1346 return;
1347 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001348 if (state->get() == STARTING
1349 || state->get() == RUNNING
1350 || state->get() == STOPPING) {
1351 // Input surface may have been started, so clean up is needed.
1352 clearInputSurfaceIfNeeded = true;
1353 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001354 state->set(RELEASING);
1355 }
1356
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001357 if (clearInputSurfaceIfNeeded) {
1358 Mutexed<Config>::Locked config(mConfig);
1359 if (config->mInputSurface) {
1360 config->mInputSurface->disconnect();
1361 config->mInputSurface = nullptr;
1362 }
1363 }
1364
Pawin Vongmasa36653902018-11-15 00:10:25 -08001365 mChannel->stop();
1366 // thiz holds strong ref to this while the thread is running.
1367 sp<CCodec> thiz(this);
1368 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1369}
1370
1371void CCodec::release(bool sendCallback) {
1372 std::shared_ptr<Codec2Client::Component> comp;
1373 {
1374 Mutexed<State>::Locked state(mState);
1375 if (state->get() == RELEASED) {
1376 if (sendCallback) {
1377 state.unlock();
1378 mCallback->onReleaseCompleted();
1379 state.lock();
1380 }
1381 return;
1382 }
1383 comp = state->comp;
1384 }
1385 comp->release();
1386
1387 {
1388 Mutexed<State>::Locked state(mState);
1389 state->set(RELEASED);
1390 state->comp.reset();
1391 }
1392 if (sendCallback) {
1393 mCallback->onReleaseCompleted();
1394 }
1395}
1396
1397status_t CCodec::setSurface(const sp<Surface> &surface) {
1398 return mChannel->setSurface(surface);
1399}
1400
1401void CCodec::signalFlush() {
1402 status_t err = [this] {
1403 Mutexed<State>::Locked state(mState);
1404 if (state->get() == FLUSHED) {
1405 return ALREADY_EXISTS;
1406 }
1407 if (state->get() != RUNNING) {
1408 return UNKNOWN_ERROR;
1409 }
1410 state->set(FLUSHING);
1411 return OK;
1412 }();
1413 switch (err) {
1414 case ALREADY_EXISTS:
1415 mCallback->onFlushCompleted();
1416 return;
1417 case OK:
1418 break;
1419 default:
1420 mCallback->onError(err, ACTION_CODE_FATAL);
1421 return;
1422 }
1423
1424 mChannel->stop();
1425 (new AMessage(kWhatFlush, this))->post();
1426}
1427
1428void CCodec::flush() {
1429 std::shared_ptr<Codec2Client::Component> comp;
1430 auto checkFlushing = [this, &comp] {
1431 Mutexed<State>::Locked state(mState);
1432 if (state->get() != FLUSHING) {
1433 return UNKNOWN_ERROR;
1434 }
1435 comp = state->comp;
1436 return OK;
1437 };
1438 if (tryAndReportOnError(checkFlushing) != OK) {
1439 return;
1440 }
1441
1442 std::list<std::unique_ptr<C2Work>> flushedWork;
1443 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1444 {
1445 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1446 flushedWork.splice(flushedWork.end(), *queue);
1447 }
1448 if (err != C2_OK) {
1449 // TODO: convert err into status_t
1450 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1451 }
1452
1453 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001454
1455 {
1456 Mutexed<State>::Locked state(mState);
1457 state->set(FLUSHED);
1458 }
1459 mCallback->onFlushCompleted();
1460}
1461
1462void CCodec::signalResume() {
1463 auto setResuming = [this] {
1464 Mutexed<State>::Locked state(mState);
1465 if (state->get() != FLUSHED) {
1466 return UNKNOWN_ERROR;
1467 }
1468 state->set(RESUMING);
1469 return OK;
1470 };
1471 if (tryAndReportOnError(setResuming) != OK) {
1472 return;
1473 }
1474
1475 (void)mChannel->start(nullptr, nullptr);
1476
1477 {
1478 Mutexed<State>::Locked state(mState);
1479 if (state->get() != RESUMING) {
1480 state.unlock();
1481 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1482 state.lock();
1483 return;
1484 }
1485 state->set(RUNNING);
1486 }
1487
1488 (void)mChannel->requestInitialInputBuffers();
1489}
1490
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001491void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001492 std::shared_ptr<Codec2Client::Component> comp;
1493 auto checkState = [this, &comp] {
1494 Mutexed<State>::Locked state(mState);
1495 if (state->get() == RELEASED) {
1496 return INVALID_OPERATION;
1497 }
1498 comp = state->comp;
1499 return OK;
1500 };
1501 if (tryAndReportOnError(checkState) != OK) {
1502 return;
1503 }
1504
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001505 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1506 // the behavior here.
1507 sp<AMessage> params = msg;
1508 int32_t bitrate;
1509 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1510 params = msg->dup();
1511 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1512 }
1513
Pawin Vongmasa36653902018-11-15 00:10:25 -08001514 Mutexed<Config>::Locked config(mConfig);
1515
1516 /**
1517 * Handle input surface parameters
1518 */
1519 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1520 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001521 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522
1523 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1524 config->mISConfig->mStopped = false;
1525 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1526 config->mISConfig->mStopped = true;
1527 }
1528
1529 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001530 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001531 config->mISConfig->mSuspended = value;
1532 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001533 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001534 }
1535
1536 (void)config->mInputSurface->configure(*config->mISConfig);
1537 if (config->mISConfig->mStopped) {
1538 config->mInputFormat->setInt64(
1539 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1540 }
1541 }
1542
1543 std::vector<std::unique_ptr<C2Param>> configUpdate;
1544 (void)config->getConfigUpdateFromSdkParams(
1545 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1546 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1547 // Parameter synchronization is not defined when using input surface. For now, route
1548 // these directly to the component.
1549 if (config->mInputSurface == nullptr
1550 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1551 || comp->getName().find("c2.android.") == 0)) {
1552 mChannel->setParameters(configUpdate);
1553 } else {
1554 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1555 }
1556}
1557
1558void CCodec::signalEndOfInputStream() {
1559 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1560}
1561
1562void CCodec::signalRequestIDRFrame() {
1563 std::shared_ptr<Codec2Client::Component> comp;
1564 {
1565 Mutexed<State>::Locked state(mState);
1566 if (state->get() == RELEASED) {
1567 ALOGD("no IDR request sent since component is released");
1568 return;
1569 }
1570 comp = state->comp;
1571 }
1572 ALOGV("request IDR");
1573 Mutexed<Config>::Locked config(mConfig);
1574 std::vector<std::unique_ptr<C2Param>> params;
1575 params.push_back(
1576 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1577 config->setParameters(comp, params, C2_MAY_BLOCK);
1578}
1579
Wonsik Kimab34ed62019-01-31 15:28:46 -08001580void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001581 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001582 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1583 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584 }
1585 (new AMessage(kWhatWorkDone, this))->post();
1586}
1587
Wonsik Kimab34ed62019-01-31 15:28:46 -08001588void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1589 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001590 if (arrayIndex == 0) {
1591 // We always put no more than one buffer per work, if we use an input surface.
1592 Mutexed<Config>::Locked config(mConfig);
1593 if (config->mInputSurface) {
1594 config->mInputSurface->onInputBufferDone(frameIndex);
1595 }
1596 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001597}
1598
1599void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1600 TimePoint now = std::chrono::steady_clock::now();
1601 CCodecWatchdog::getInstance()->watch(this);
1602 switch (msg->what()) {
1603 case kWhatAllocate: {
1604 // C2ComponentStore::createComponent() should return within 100ms.
1605 setDeadline(now, 150ms, "allocate");
1606 sp<RefBase> obj;
1607 CHECK(msg->findObject("codecInfo", &obj));
1608 allocate((MediaCodecInfo *)obj.get());
1609 break;
1610 }
1611 case kWhatConfigure: {
1612 // C2Component::commit_sm() should return within 5ms.
1613 setDeadline(now, 250ms, "configure");
1614 sp<AMessage> format;
1615 CHECK(msg->findMessage("format", &format));
1616 configure(format);
1617 break;
1618 }
1619 case kWhatStart: {
1620 // C2Component::start() should return within 500ms.
1621 setDeadline(now, 550ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001622 start();
1623 break;
1624 }
1625 case kWhatStop: {
1626 // C2Component::stop() should return within 500ms.
1627 setDeadline(now, 550ms, "stop");
1628 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001629 break;
1630 }
1631 case kWhatFlush: {
1632 // C2Component::flush_sm() should return within 5ms.
1633 setDeadline(now, 50ms, "flush");
1634 flush();
1635 break;
1636 }
1637 case kWhatCreateInputSurface: {
1638 // Surface operations may be briefly blocking.
1639 setDeadline(now, 100ms, "createInputSurface");
1640 createInputSurface();
1641 break;
1642 }
1643 case kWhatSetInputSurface: {
1644 // Surface operations may be briefly blocking.
1645 setDeadline(now, 100ms, "setInputSurface");
1646 sp<RefBase> obj;
1647 CHECK(msg->findObject("surface", &obj));
1648 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1649 setInputSurface(surface);
1650 break;
1651 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001652 case kWhatWorkDone: {
1653 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001654 bool shouldPost = false;
1655 {
1656 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1657 if (queue->empty()) {
1658 break;
1659 }
1660 work.swap(queue->front());
1661 queue->pop_front();
1662 shouldPost = !queue->empty();
1663 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001664 if (shouldPost) {
1665 (new AMessage(kWhatWorkDone, this))->post();
1666 }
1667
Pawin Vongmasa36653902018-11-15 00:10:25 -08001668 // handle configuration changes in work done
1669 Mutexed<Config>::Locked config(mConfig);
1670 bool changed = false;
1671 Config::Watcher<C2StreamInitDataInfo::output> initData =
1672 config->watch<C2StreamInitDataInfo::output>();
1673 if (!work->worklets.empty()
1674 && (work->worklets.front()->output.flags
1675 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1676
1677 // copy buffer info to config
1678 std::vector<std::unique_ptr<C2Param>> updates =
1679 std::move(work->worklets.front()->output.configUpdate);
1680 unsigned stream = 0;
1681 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1682 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1683 // move all info into output-stream #0 domain
1684 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1685 }
1686 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1687 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1688 // block.crop().left, block.crop().top,
1689 // block.crop().width, block.crop().height,
1690 // block.width(), block.height());
1691 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1692 updates.emplace_back(new C2StreamPictureSizeInfo::output(
1693 stream, block.width(), block.height()));
1694 break; // for now only do the first block
1695 }
1696 ++stream;
1697 }
1698
1699 changed = config->updateConfiguration(updates, config->mOutputDomain);
1700
1701 // copy standard infos to graphic buffers if not already present (otherwise, we
1702 // may overwrite the actual intermediate value with a final value)
1703 stream = 0;
1704 const static std::vector<C2Param::Index> stdGfxInfos = {
1705 C2StreamRotationInfo::output::PARAM_TYPE,
1706 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1707 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1708 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001709 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001710 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1711 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1712 };
1713 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1714 if (buf->data().graphicBlocks().size()) {
1715 for (C2Param::Index ix : stdGfxInfos) {
1716 if (!buf->hasInfo(ix)) {
1717 const C2Param *param =
1718 config->getConfigParameterValue(ix.withStream(stream));
1719 if (param) {
1720 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1721 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1722 }
1723 }
1724 }
1725 }
1726 ++stream;
1727 }
1728 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001729 if (config->mInputSurface) {
1730 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1731 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001732 mChannel->onWorkDone(
1733 std::move(work), changed ? config->mOutputFormat : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001734 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001735 break;
1736 }
1737 case kWhatWatch: {
1738 // watch message already posted; no-op.
1739 break;
1740 }
1741 default: {
1742 ALOGE("unrecognized message");
1743 break;
1744 }
1745 }
1746 setDeadline(TimePoint::max(), 0ms, "none");
1747}
1748
1749void CCodec::setDeadline(
1750 const TimePoint &now,
1751 const std::chrono::milliseconds &timeout,
1752 const char *name) {
1753 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1754 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1755 deadline->set(now + (timeout * mult), name);
1756}
1757
1758void CCodec::initiateReleaseIfStuck() {
1759 std::string name;
1760 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001761 {
1762 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001763 if (deadline->get() < std::chrono::steady_clock::now()) {
1764 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001765 }
1766 if (deadline->get() != TimePoint::max()) {
1767 pendingDeadline = true;
1768 }
1769 }
1770 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001771 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1772 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1773 if (elapsed >= kWorkDurationThreshold) {
1774 name = "queue";
1775 }
1776 if (elapsed > 0s) {
1777 pendingDeadline = true;
1778 }
1779 }
1780 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001781 // We're not stuck.
1782 if (pendingDeadline) {
1783 // If we are not stuck yet but still has deadline coming up,
1784 // post watch message to check back later.
1785 (new AMessage(kWhatWatch, this))->post();
1786 }
1787 return;
1788 }
1789
1790 ALOGW("previous call to %s exceeded timeout", name.c_str());
1791 initiateRelease(false);
1792 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1793}
1794
Pawin Vongmasa36653902018-11-15 00:10:25 -08001795} // namespace android
1796
1797extern "C" android::CodecBase *CreateCodec() {
1798 return new android::CCodec;
1799}
1800
Lajos Molnar47118272019-01-31 16:28:04 -08001801// Create Codec 2.0 input surface
Pawin Vongmasa36653902018-11-15 00:10:25 -08001802extern "C" android::PersistentSurface *CreateInputSurface() {
1803 // Attempt to create a Codec2's input surface.
1804 std::shared_ptr<android::Codec2Client::InputSurface> inputSurface =
1805 android::Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001806 if (!inputSurface) {
1807 return nullptr;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001808 }
Lajos Molnar47118272019-01-31 16:28:04 -08001809 return new android::PersistentSurface(
1810 inputSurface->getGraphicBufferProducer(),
1811 static_cast<android::sp<android::hidl::base::V1_0::IBase>>(
1812 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001813}
1814