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