blob: 751c8c53f6b9f5b7c78e667dbf741fea4f017985 [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
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700603 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800604 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);
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700862 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800863
864 std::initializer_list<C2Param::Index> indices {
865 };
866 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700867 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800868 indices,
869 C2_DONT_BLOCK,
870 &params);
871 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
872 ALOGE("Failed to query component interface: %d", c2err);
873 return UNKNOWN_ERROR;
874 }
875 if (params.size() != indices.size()) {
876 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
877 indices.size(), params.size());
878 return UNKNOWN_ERROR;
879 }
880 if (usage && (usage.value & C2MemoryUsage::CPU_READ)) {
881 config->mInputFormat->setInt32("using-sw-read-often", true);
882 }
883
884 // NOTE: we don't blindly use client specified input size if specified as clients
885 // at times specify too small size. Instead, mimic the behavior from OMX, where the
886 // client specified size is only used to ask for bigger buffers than component suggested
887 // size.
888 int32_t clientInputSize = 0;
889 bool clientSpecifiedInputSize =
890 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
891 // TEMP: enforce minimum buffer size of 1MB for video decoders
892 // and 16K / 4K for audio encoders/decoders
893 if (maxInputSize.value == 0) {
894 if (config->mDomain & Config::IS_AUDIO) {
895 maxInputSize.value = encoder ? 16384 : 4096;
896 } else if (!encoder) {
897 maxInputSize.value = 1048576u;
898 }
899 }
900
901 // verify that CSD fits into this size (if defined)
902 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
903 sp<ABuffer> csd;
904 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
905 if (csd && csd->size() > maxInputSize.value) {
906 maxInputSize.value = csd->size();
907 }
908 }
909 }
910
911 // TODO: do this based on component requiring linear allocator for input
912 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
913 if (clientSpecifiedInputSize) {
914 // Warn that we're overriding client's max input size if necessary.
915 if ((uint32_t)clientInputSize < maxInputSize.value) {
916 ALOGD("client requested max input size %d, which is smaller than "
917 "what component recommended (%u); overriding with component "
918 "recommendation.", clientInputSize, maxInputSize.value);
919 ALOGW("This behavior is subject to change. It is recommended that "
920 "app developers double check whether the requested "
921 "max input size is in reasonable range.");
922 } else {
923 maxInputSize.value = clientInputSize;
924 }
925 }
926 // Pass max input size on input format to the buffer channel (if supplied by the
927 // component or by a default)
928 if (maxInputSize.value) {
929 config->mInputFormat->setInt32(
930 KEY_MAX_INPUT_SIZE,
931 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
932 }
933 }
934
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700935 int32_t clientPrepend;
936 if ((config->mDomain & Config::IS_VIDEO)
937 && (config->mDomain & Config::IS_ENCODER)
938 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
939 && clientPrepend
940 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
941 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
942 return BAD_VALUE;
943 }
944
Pawin Vongmasa36653902018-11-15 00:10:25 -0800945 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
946 // propagate HDR static info to output format for both encoders and decoders
947 // if component supports this info, we will update from component, but only the raw port,
948 // so don't propagate if component already filled it in.
949 sp<ABuffer> hdrInfo;
950 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
951 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
952 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
953 }
954
955 // Set desired color format from configuration parameter
956 int32_t format;
957 if (msg->findInt32("android._color-format", &format)) {
958 if (config->mDomain & Config::IS_ENCODER) {
959 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
960 } else {
961 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
962 }
963 }
964 }
965
966 // propagate encoder delay and padding to output format
967 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
968 int delay = 0;
969 if (msg->findInt32("encoder-delay", &delay)) {
970 config->mOutputFormat->setInt32("encoder-delay", delay);
971 }
972 int padding = 0;
973 if (msg->findInt32("encoder-padding", &padding)) {
974 config->mOutputFormat->setInt32("encoder-padding", padding);
975 }
976 }
977
978 // set channel-mask
979 if (config->mDomain & Config::IS_AUDIO) {
980 int32_t mask;
981 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
982 if (config->mDomain & Config::IS_ENCODER) {
983 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
984 } else {
985 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
986 }
987 }
988 }
989
990 ALOGD("setup formats input: %s and output: %s",
991 config->mInputFormat->debugString().c_str(),
992 config->mOutputFormat->debugString().c_str());
993 return OK;
994 };
995 if (tryAndReportOnError(doConfig) != OK) {
996 return;
997 }
998
999 Mutexed<Config>::Locked config(mConfig);
1000
1001 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1002}
1003
1004void CCodec::initiateCreateInputSurface() {
1005 status_t err = [this] {
1006 Mutexed<State>::Locked state(mState);
1007 if (state->get() != ALLOCATED) {
1008 return UNKNOWN_ERROR;
1009 }
1010 // TODO: read it from intf() properly.
1011 if (state->comp->getName().find("encoder") == std::string::npos) {
1012 return INVALID_OPERATION;
1013 }
1014 return OK;
1015 }();
1016 if (err != OK) {
1017 mCallback->onInputSurfaceCreationFailed(err);
1018 return;
1019 }
1020
1021 (new AMessage(kWhatCreateInputSurface, this))->post();
1022}
1023
Lajos Molnar47118272019-01-31 16:28:04 -08001024sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1025 using namespace android::hardware::media::omx::V1_0;
1026 using namespace android::hardware::media::omx::V1_0::utils;
1027 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1028 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1029 android::sp<IOmx> omx = IOmx::getService();
1030 typedef android::hardware::graphics::bufferqueue::V1_0::
1031 IGraphicBufferProducer HGraphicBufferProducer;
1032 typedef android::hardware::media::omx::V1_0::
1033 IGraphicBufferSource HGraphicBufferSource;
1034 OmxStatus s;
1035 android::sp<HGraphicBufferProducer> gbp;
1036 android::sp<HGraphicBufferSource> gbs;
1037 android::Return<void> transStatus = omx->createInputSurface(
1038 [&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