blob: 0f958c9674c93b0f7ed45f337d8155a4d7099242 [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 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700769 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
770 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
771 ALOGD("frame rate is missing, which is required for video encoders.");
772 return BAD_VALUE;
773 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800774 }
775 }
776
Pawin Vongmasa36653902018-11-15 00:10:25 -0800777 /*
778 * Handle input surface configuration
779 */
780 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
781 && (config->mDomain & Config::IS_ENCODER)) {
782 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
783 {
784 config->mISConfig->mMinFps = 0;
785 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800786 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800787 config->mISConfig->mMinFps = 1e6 / value;
788 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700789 if (!msg->findFloat(
790 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
791 config->mISConfig->mMaxFps = -1;
792 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800793 config->mISConfig->mMinAdjustedFps = 0;
794 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800795 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800796 if (value < 0 && value >= INT32_MIN) {
797 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700798 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800799 } else if (value > 0 && value <= INT32_MAX) {
800 config->mISConfig->mMinAdjustedFps = 1e6 / value;
801 }
802 }
803 }
804
805 {
806 double value;
807 if (msg->findDouble("time-lapse-fps", &value)) {
808 config->mISConfig->mCaptureFps = value;
809 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
810 }
811 }
812
813 {
814 config->mISConfig->mSuspended = false;
815 config->mISConfig->mSuspendAtUs = -1;
816 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800817 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800818 config->mISConfig->mSuspended = true;
819 }
820 }
821 }
822
823 /*
824 * Handle desired color format.
825 */
826 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
827 int32_t format = -1;
828 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
829 /*
830 * Also handle default color format (encoders require color format, so this is only
831 * needed for decoders.
832 */
833 if (!(config->mDomain & Config::IS_ENCODER)) {
834 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
835 }
836 }
837
838 if (format >= 0) {
839 msg->setInt32("android._color-format", format);
840 }
841 }
842
843 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800844 // NOTE: We used to ignore "video-bitrate" at configure; replicate
845 // the behavior here.
846 sp<AMessage> sdkParams = msg;
847 int32_t videoBitrate;
848 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
849 sdkParams = msg->dup();
850 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
851 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800852 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800853 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800854 if (err != OK) {
855 ALOGW("failed to convert configuration to c2 params");
856 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700857
858 int32_t maxBframes = 0;
859 if ((config->mDomain & Config::IS_ENCODER)
860 && (config->mDomain & Config::IS_VIDEO)
861 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
862 && maxBframes > 0) {
863 std::unique_ptr<C2StreamGopTuning::output> gop =
864 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
865 gop->m.values[0] = { P_FRAME, UINT32_MAX };
866 gop->m.values[1] = {
867 C2Config::picture_type_t(P_FRAME | B_FRAME),
868 uint32_t(maxBframes)
869 };
870 configUpdate.push_back(std::move(gop));
871 }
872
Pawin Vongmasa36653902018-11-15 00:10:25 -0800873 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
874 if (err != OK) {
875 ALOGW("failed to configure c2 params");
876 return err;
877 }
878
879 std::vector<std::unique_ptr<C2Param>> params;
880 C2StreamUsageTuning::input usage(0u, 0u);
881 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700882 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800883
884 std::initializer_list<C2Param::Index> indices {
885 };
886 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700887 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800888 indices,
889 C2_DONT_BLOCK,
890 &params);
891 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
892 ALOGE("Failed to query component interface: %d", c2err);
893 return UNKNOWN_ERROR;
894 }
895 if (params.size() != indices.size()) {
896 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
897 indices.size(), params.size());
898 return UNKNOWN_ERROR;
899 }
900 if (usage && (usage.value & C2MemoryUsage::CPU_READ)) {
901 config->mInputFormat->setInt32("using-sw-read-often", true);
902 }
903
904 // NOTE: we don't blindly use client specified input size if specified as clients
905 // at times specify too small size. Instead, mimic the behavior from OMX, where the
906 // client specified size is only used to ask for bigger buffers than component suggested
907 // size.
908 int32_t clientInputSize = 0;
909 bool clientSpecifiedInputSize =
910 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
911 // TEMP: enforce minimum buffer size of 1MB for video decoders
912 // and 16K / 4K for audio encoders/decoders
913 if (maxInputSize.value == 0) {
914 if (config->mDomain & Config::IS_AUDIO) {
915 maxInputSize.value = encoder ? 16384 : 4096;
916 } else if (!encoder) {
917 maxInputSize.value = 1048576u;
918 }
919 }
920
921 // verify that CSD fits into this size (if defined)
922 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
923 sp<ABuffer> csd;
924 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
925 if (csd && csd->size() > maxInputSize.value) {
926 maxInputSize.value = csd->size();
927 }
928 }
929 }
930
931 // TODO: do this based on component requiring linear allocator for input
932 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
933 if (clientSpecifiedInputSize) {
934 // Warn that we're overriding client's max input size if necessary.
935 if ((uint32_t)clientInputSize < maxInputSize.value) {
936 ALOGD("client requested max input size %d, which is smaller than "
937 "what component recommended (%u); overriding with component "
938 "recommendation.", clientInputSize, maxInputSize.value);
939 ALOGW("This behavior is subject to change. It is recommended that "
940 "app developers double check whether the requested "
941 "max input size is in reasonable range.");
942 } else {
943 maxInputSize.value = clientInputSize;
944 }
945 }
946 // Pass max input size on input format to the buffer channel (if supplied by the
947 // component or by a default)
948 if (maxInputSize.value) {
949 config->mInputFormat->setInt32(
950 KEY_MAX_INPUT_SIZE,
951 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
952 }
953 }
954
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700955 int32_t clientPrepend;
956 if ((config->mDomain & Config::IS_VIDEO)
957 && (config->mDomain & Config::IS_ENCODER)
958 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
959 && clientPrepend
960 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
961 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
962 return BAD_VALUE;
963 }
964
Pawin Vongmasa36653902018-11-15 00:10:25 -0800965 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
966 // propagate HDR static info to output format for both encoders and decoders
967 // if component supports this info, we will update from component, but only the raw port,
968 // so don't propagate if component already filled it in.
969 sp<ABuffer> hdrInfo;
970 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
971 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
972 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
973 }
974
975 // Set desired color format from configuration parameter
976 int32_t format;
977 if (msg->findInt32("android._color-format", &format)) {
978 if (config->mDomain & Config::IS_ENCODER) {
979 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
980 } else {
981 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
982 }
983 }
984 }
985
986 // propagate encoder delay and padding to output format
987 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
988 int delay = 0;
989 if (msg->findInt32("encoder-delay", &delay)) {
990 config->mOutputFormat->setInt32("encoder-delay", delay);
991 }
992 int padding = 0;
993 if (msg->findInt32("encoder-padding", &padding)) {
994 config->mOutputFormat->setInt32("encoder-padding", padding);
995 }
996 }
997
998 // set channel-mask
999 if (config->mDomain & Config::IS_AUDIO) {
1000 int32_t mask;
1001 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1002 if (config->mDomain & Config::IS_ENCODER) {
1003 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1004 } else {
1005 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1006 }
1007 }
1008 }
1009
1010 ALOGD("setup formats input: %s and output: %s",
1011 config->mInputFormat->debugString().c_str(),
1012 config->mOutputFormat->debugString().c_str());
1013 return OK;
1014 };
1015 if (tryAndReportOnError(doConfig) != OK) {
1016 return;
1017 }
1018
1019 Mutexed<Config>::Locked config(mConfig);
1020
1021 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1022}
1023
1024void CCodec::initiateCreateInputSurface() {
1025 status_t err = [this] {
1026 Mutexed<State>::Locked state(mState);
1027 if (state->get() != ALLOCATED) {
1028 return UNKNOWN_ERROR;
1029 }
1030 // TODO: read it from intf() properly.
1031 if (state->comp->getName().find("encoder") == std::string::npos) {
1032 return INVALID_OPERATION;
1033 }
1034 return OK;
1035 }();
1036 if (err != OK) {
1037 mCallback->onInputSurfaceCreationFailed(err);
1038 return;
1039 }
1040
1041 (new AMessage(kWhatCreateInputSurface, this))->post();
1042}
1043
Lajos Molnar47118272019-01-31 16:28:04 -08001044sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1045 using namespace android::hardware::media::omx::V1_0;
1046 using namespace android::hardware::media::omx::V1_0::utils;
1047 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1048 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1049 android::sp<IOmx> omx = IOmx::getService();
1050 typedef android::hardware::graphics::bufferqueue::V1_0::
1051 IGraphicBufferProducer HGraphicBufferProducer;
1052 typedef android::hardware::media::omx::V1_0::
1053 IGraphicBufferSource HGraphicBufferSource;
1054 OmxStatus s;
1055 android::sp<HGraphicBufferProducer> gbp;
1056 android::sp<HGraphicBufferSource> gbs;
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001057 using ::android::hardware::Return;
1058 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001059 [&s, &gbp, &gbs](
1060 OmxStatus status,
1061 const android::sp<HGraphicBufferProducer>& producer,
1062 const android::sp<HGraphicBufferSource>& source) {
1063 s = status;
1064 gbp = producer;
1065 gbs = source;
1066 });
1067 if (transStatus.isOk() && s == OmxStatus::OK) {
1068 return new PersistentSurface(
1069 new H2BGraphicBufferProducer(gbp),
1070 sp<::android::IGraphicBufferSource>(new LWGraphicBufferSource(gbs)));
1071 }
1072
1073 return nullptr;
1074}
1075
1076sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1077 sp<PersistentSurface> surface(CreateInputSurface());
1078
1079 if (surface == nullptr) {
1080 surface = CreateOmxInputSurface();
1081 }
1082
1083 return surface;
1084}
1085
Pawin Vongmasa36653902018-11-15 00:10:25 -08001086void CCodec::createInputSurface() {
1087 status_t err;
1088 sp<IGraphicBufferProducer> bufferProducer;
1089
1090 sp<AMessage> inputFormat;
1091 sp<AMessage> outputFormat;
1092 {
1093 Mutexed<Config>::Locked config(mConfig);
1094 inputFormat = config->mInputFormat;
1095 outputFormat = config->mOutputFormat;
1096 }
1097
Lajos Molnar47118272019-01-31 16:28:04 -08001098 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001099
1100 if (persistentSurface->getHidlTarget()) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001101 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001102 persistentSurface->getHidlTarget());
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001103 if (!hidlInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001104 ALOGE("Corrupted input surface");
1105 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1106 return;
1107 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001108 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1109 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001110 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001111 inputSurface));
1112 bufferProducer = inputSurface->getGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001113 } else {
1114 int32_t width = 0;
1115 (void)outputFormat->findInt32("width", &width);
1116 int32_t height = 0;
1117 (void)outputFormat->findInt32("height", &height);
1118 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1119 persistentSurface->getBufferSource(), width, height));
1120 bufferProducer = persistentSurface->getBufferProducer();
1121 }
1122
1123 if (err != OK) {
1124 ALOGE("Failed to set up input surface: %d", err);
1125 mCallback->onInputSurfaceCreationFailed(err);
1126 return;
1127 }
1128
1129 mCallback->onInputSurfaceCreated(
1130 inputFormat,
1131 outputFormat,
1132 new BufferProducerWrapper(bufferProducer));
1133}
1134
1135status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
1136 Mutexed<Config>::Locked config(mConfig);
1137 config->mUsingSurface = true;
1138
1139 // we are now using surface - apply default color aspects to input format - as well as
1140 // get dataspace
1141 bool inputFormatChanged = config->updateFormats(config->IS_INPUT);
1142 ALOGD("input format %s to %s",
1143 inputFormatChanged ? "changed" : "unchanged",
1144 config->mInputFormat->debugString().c_str());
1145
1146 // configure dataspace
1147 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1148 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1149 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1150 surface->setDataSpace(dataSpace);
1151
1152 status_t err = mChannel->setInputSurface(surface);
1153 if (err != OK) {
1154 // undo input format update
1155 config->mUsingSurface = false;
1156 (void)config->updateFormats(config->IS_INPUT);
1157 return err;
1158 }
1159 config->mInputSurface = surface;
1160
1161 if (config->mISConfig) {
1162 surface->configure(*config->mISConfig);
1163 } else {
1164 ALOGD("ISConfig: no configuration");
1165 }
1166
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001167 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001168}
1169
1170void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1171 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1172 msg->setObject("surface", surface);
1173 msg->post();
1174}
1175
1176void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1177 sp<AMessage> inputFormat;
1178 sp<AMessage> outputFormat;
1179 {
1180 Mutexed<Config>::Locked config(mConfig);
1181 inputFormat = config->mInputFormat;
1182 outputFormat = config->mOutputFormat;
1183 }
1184 auto hidlTarget = surface->getHidlTarget();
1185 if (hidlTarget) {
1186 sp<IInputSurface> inputSurface =
1187 IInputSurface::castFrom(hidlTarget);
1188 if (!inputSurface) {
1189 ALOGE("Failed to set input surface: Corrupted surface.");
1190 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1191 return;
1192 }
1193 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1194 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1195 if (err != OK) {
1196 ALOGE("Failed to set up input surface: %d", err);
1197 mCallback->onInputSurfaceDeclined(err);
1198 return;
1199 }
1200 } else {
1201 int32_t width = 0;
1202 (void)outputFormat->findInt32("width", &width);
1203 int32_t height = 0;
1204 (void)outputFormat->findInt32("height", &height);
1205 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1206 surface->getBufferSource(), width, height));
1207 if (err != OK) {
1208 ALOGE("Failed to set up input surface: %d", err);
1209 mCallback->onInputSurfaceDeclined(err);
1210 return;
1211 }
1212 }
1213 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1214}
1215
1216void CCodec::initiateStart() {
1217 auto setStarting = [this] {
1218 Mutexed<State>::Locked state(mState);
1219 if (state->get() != ALLOCATED) {
1220 return UNKNOWN_ERROR;
1221 }
1222 state->set(STARTING);
1223 return OK;
1224 };
1225 if (tryAndReportOnError(setStarting) != OK) {
1226 return;
1227 }
1228
1229 (new AMessage(kWhatStart, this))->post();
1230}
1231
1232void CCodec::start() {
1233 std::shared_ptr<Codec2Client::Component> comp;
1234 auto checkStarting = [this, &comp] {
1235 Mutexed<State>::Locked state(mState);
1236 if (state->get() != STARTING) {
1237 return UNKNOWN_ERROR;
1238 }
1239 comp = state->comp;
1240 return OK;
1241 };
1242 if (tryAndReportOnError(checkStarting) != OK) {
1243 return;
1244 }
1245
1246 c2_status_t err = comp->start();
1247 if (err != C2_OK) {
1248 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1249 ACTION_CODE_FATAL);
1250 return;
1251 }
1252 sp<AMessage> inputFormat;
1253 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001254 status_t err2 = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001255 {
1256 Mutexed<Config>::Locked config(mConfig);
1257 inputFormat = config->mInputFormat;
1258 outputFormat = config->mOutputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001259 if (config->mInputSurface) {
1260 err2 = config->mInputSurface->start();
1261 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001262 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001263 if (err2 != OK) {
1264 mCallback->onError(err2, ACTION_CODE_FATAL);
1265 return;
1266 }
1267 err2 = mChannel->start(inputFormat, outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001268 if (err2 != OK) {
1269 mCallback->onError(err2, ACTION_CODE_FATAL);
1270 return;
1271 }
1272
1273 auto setRunning = [this] {
1274 Mutexed<State>::Locked state(mState);
1275 if (state->get() != STARTING) {
1276 return UNKNOWN_ERROR;
1277 }
1278 state->set(RUNNING);
1279 return OK;
1280 };
1281 if (tryAndReportOnError(setRunning) != OK) {
1282 return;
1283 }
1284 mCallback->onStartCompleted();
1285
1286 (void)mChannel->requestInitialInputBuffers();
1287}
1288
1289void CCodec::initiateShutdown(bool keepComponentAllocated) {
1290 if (keepComponentAllocated) {
1291 initiateStop();
1292 } else {
1293 initiateRelease();
1294 }
1295}
1296
1297void CCodec::initiateStop() {
1298 {
1299 Mutexed<State>::Locked state(mState);
1300 if (state->get() == ALLOCATED
1301 || state->get() == RELEASED
1302 || state->get() == STOPPING
1303 || state->get() == RELEASING) {
1304 // We're already stopped, released, or doing it right now.
1305 state.unlock();
1306 mCallback->onStopCompleted();
1307 state.lock();
1308 return;
1309 }
1310 state->set(STOPPING);
1311 }
1312
1313 mChannel->stop();
1314 (new AMessage(kWhatStop, this))->post();
1315}
1316
1317void CCodec::stop() {
1318 std::shared_ptr<Codec2Client::Component> comp;
1319 {
1320 Mutexed<State>::Locked state(mState);
1321 if (state->get() == RELEASING) {
1322 state.unlock();
1323 // We're already stopped or release is in progress.
1324 mCallback->onStopCompleted();
1325 state.lock();
1326 return;
1327 } else if (state->get() != STOPPING) {
1328 state.unlock();
1329 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1330 state.lock();
1331 return;
1332 }
1333 comp = state->comp;
1334 }
1335 status_t err = comp->stop();
1336 if (err != C2_OK) {
1337 // TODO: convert err into status_t
1338 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1339 }
1340
1341 {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001342 Mutexed<Config>::Locked config(mConfig);
1343 if (config->mInputSurface) {
1344 config->mInputSurface->disconnect();
1345 config->mInputSurface = nullptr;
1346 }
1347 }
1348 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001349 Mutexed<State>::Locked state(mState);
1350 if (state->get() == STOPPING) {
1351 state->set(ALLOCATED);
1352 }
1353 }
1354 mCallback->onStopCompleted();
1355}
1356
1357void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001358 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001359 {
1360 Mutexed<State>::Locked state(mState);
1361 if (state->get() == RELEASED || state->get() == RELEASING) {
1362 // We're already released or doing it right now.
1363 if (sendCallback) {
1364 state.unlock();
1365 mCallback->onReleaseCompleted();
1366 state.lock();
1367 }
1368 return;
1369 }
1370 if (state->get() == ALLOCATING) {
1371 state->set(RELEASING);
1372 // With the altered state allocate() would fail and clean up.
1373 if (sendCallback) {
1374 state.unlock();
1375 mCallback->onReleaseCompleted();
1376 state.lock();
1377 }
1378 return;
1379 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001380 if (state->get() == STARTING
1381 || state->get() == RUNNING
1382 || state->get() == STOPPING) {
1383 // Input surface may have been started, so clean up is needed.
1384 clearInputSurfaceIfNeeded = true;
1385 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001386 state->set(RELEASING);
1387 }
1388
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001389 if (clearInputSurfaceIfNeeded) {
1390 Mutexed<Config>::Locked config(mConfig);
1391 if (config->mInputSurface) {
1392 config->mInputSurface->disconnect();
1393 config->mInputSurface = nullptr;
1394 }
1395 }
1396
Pawin Vongmasa36653902018-11-15 00:10:25 -08001397 mChannel->stop();
1398 // thiz holds strong ref to this while the thread is running.
1399 sp<CCodec> thiz(this);
1400 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1401}
1402
1403void CCodec::release(bool sendCallback) {
1404 std::shared_ptr<Codec2Client::Component> comp;
1405 {
1406 Mutexed<State>::Locked state(mState);
1407 if (state->get() == RELEASED) {
1408 if (sendCallback) {
1409 state.unlock();
1410 mCallback->onReleaseCompleted();
1411 state.lock();
1412 }
1413 return;
1414 }
1415 comp = state->comp;
1416 }
1417 comp->release();
1418
1419 {
1420 Mutexed<State>::Locked state(mState);
1421 state->set(RELEASED);
1422 state->comp.reset();
1423 }
1424 if (sendCallback) {
1425 mCallback->onReleaseCompleted();
1426 }
1427}
1428
1429status_t CCodec::setSurface(const sp<Surface> &surface) {
1430 return mChannel->setSurface(surface);
1431}
1432
1433void CCodec::signalFlush() {
1434 status_t err = [this] {
1435 Mutexed<State>::Locked state(mState);
1436 if (state->get() == FLUSHED) {
1437 return ALREADY_EXISTS;
1438 }
1439 if (state->get() != RUNNING) {
1440 return UNKNOWN_ERROR;
1441 }
1442 state->set(FLUSHING);
1443 return OK;
1444 }();
1445 switch (err) {
1446 case ALREADY_EXISTS:
1447 mCallback->onFlushCompleted();
1448 return;
1449 case OK:
1450 break;
1451 default:
1452 mCallback->onError(err, ACTION_CODE_FATAL);
1453 return;
1454 }
1455
1456 mChannel->stop();
1457 (new AMessage(kWhatFlush, this))->post();
1458}
1459
1460void CCodec::flush() {
1461 std::shared_ptr<Codec2Client::Component> comp;
1462 auto checkFlushing = [this, &comp] {
1463 Mutexed<State>::Locked state(mState);
1464 if (state->get() != FLUSHING) {
1465 return UNKNOWN_ERROR;
1466 }
1467 comp = state->comp;
1468 return OK;
1469 };
1470 if (tryAndReportOnError(checkFlushing) != OK) {
1471 return;
1472 }
1473
1474 std::list<std::unique_ptr<C2Work>> flushedWork;
1475 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1476 {
1477 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1478 flushedWork.splice(flushedWork.end(), *queue);
1479 }
1480 if (err != C2_OK) {
1481 // TODO: convert err into status_t
1482 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1483 }
1484
1485 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001486
1487 {
1488 Mutexed<State>::Locked state(mState);
1489 state->set(FLUSHED);
1490 }
1491 mCallback->onFlushCompleted();
1492}
1493
1494void CCodec::signalResume() {
1495 auto setResuming = [this] {
1496 Mutexed<State>::Locked state(mState);
1497 if (state->get() != FLUSHED) {
1498 return UNKNOWN_ERROR;
1499 }
1500 state->set(RESUMING);
1501 return OK;
1502 };
1503 if (tryAndReportOnError(setResuming) != OK) {
1504 return;
1505 }
1506
1507 (void)mChannel->start(nullptr, nullptr);
1508
1509 {
1510 Mutexed<State>::Locked state(mState);
1511 if (state->get() != RESUMING) {
1512 state.unlock();
1513 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1514 state.lock();
1515 return;
1516 }
1517 state->set(RUNNING);
1518 }
1519
1520 (void)mChannel->requestInitialInputBuffers();
1521}
1522
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001523void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001524 std::shared_ptr<Codec2Client::Component> comp;
1525 auto checkState = [this, &comp] {
1526 Mutexed<State>::Locked state(mState);
1527 if (state->get() == RELEASED) {
1528 return INVALID_OPERATION;
1529 }
1530 comp = state->comp;
1531 return OK;
1532 };
1533 if (tryAndReportOnError(checkState) != OK) {
1534 return;
1535 }
1536
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001537 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1538 // the behavior here.
1539 sp<AMessage> params = msg;
1540 int32_t bitrate;
1541 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1542 params = msg->dup();
1543 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1544 }
1545
Pawin Vongmasa36653902018-11-15 00:10:25 -08001546 Mutexed<Config>::Locked config(mConfig);
1547
1548 /**
1549 * Handle input surface parameters
1550 */
1551 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1552 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001553 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001554
1555 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1556 config->mISConfig->mStopped = false;
1557 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1558 config->mISConfig->mStopped = true;
1559 }
1560
1561 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001562 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001563 config->mISConfig->mSuspended = value;
1564 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001565 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001566 }
1567
1568 (void)config->mInputSurface->configure(*config->mISConfig);
1569 if (config->mISConfig->mStopped) {
1570 config->mInputFormat->setInt64(
1571 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1572 }
1573 }
1574
1575 std::vector<std::unique_ptr<C2Param>> configUpdate;
1576 (void)config->getConfigUpdateFromSdkParams(
1577 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1578 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1579 // Parameter synchronization is not defined when using input surface. For now, route
1580 // these directly to the component.
1581 if (config->mInputSurface == nullptr
1582 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1583 || comp->getName().find("c2.android.") == 0)) {
1584 mChannel->setParameters(configUpdate);
1585 } else {
1586 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1587 }
1588}
1589
1590void CCodec::signalEndOfInputStream() {
1591 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1592}
1593
1594void CCodec::signalRequestIDRFrame() {
1595 std::shared_ptr<Codec2Client::Component> comp;
1596 {
1597 Mutexed<State>::Locked state(mState);
1598 if (state->get() == RELEASED) {
1599 ALOGD("no IDR request sent since component is released");
1600 return;
1601 }
1602 comp = state->comp;
1603 }
1604 ALOGV("request IDR");
1605 Mutexed<Config>::Locked config(mConfig);
1606 std::vector<std::unique_ptr<C2Param>> params;
1607 params.push_back(
1608 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1609 config->setParameters(comp, params, C2_MAY_BLOCK);
1610}
1611
Wonsik Kimab34ed62019-01-31 15:28:46 -08001612void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001613 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001614 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1615 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001616 }
1617 (new AMessage(kWhatWorkDone, this))->post();
1618}
1619
Wonsik Kimab34ed62019-01-31 15:28:46 -08001620void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1621 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001622 if (arrayIndex == 0) {
1623 // We always put no more than one buffer per work, if we use an input surface.
1624 Mutexed<Config>::Locked config(mConfig);
1625 if (config->mInputSurface) {
1626 config->mInputSurface->onInputBufferDone(frameIndex);
1627 }
1628 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001629}
1630
1631void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1632 TimePoint now = std::chrono::steady_clock::now();
1633 CCodecWatchdog::getInstance()->watch(this);
1634 switch (msg->what()) {
1635 case kWhatAllocate: {
1636 // C2ComponentStore::createComponent() should return within 100ms.
1637 setDeadline(now, 150ms, "allocate");
1638 sp<RefBase> obj;
1639 CHECK(msg->findObject("codecInfo", &obj));
1640 allocate((MediaCodecInfo *)obj.get());
1641 break;
1642 }
1643 case kWhatConfigure: {
1644 // C2Component::commit_sm() should return within 5ms.
1645 setDeadline(now, 250ms, "configure");
1646 sp<AMessage> format;
1647 CHECK(msg->findMessage("format", &format));
1648 configure(format);
1649 break;
1650 }
1651 case kWhatStart: {
1652 // C2Component::start() should return within 500ms.
1653 setDeadline(now, 550ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001654 start();
1655 break;
1656 }
1657 case kWhatStop: {
1658 // C2Component::stop() should return within 500ms.
1659 setDeadline(now, 550ms, "stop");
1660 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001661 break;
1662 }
1663 case kWhatFlush: {
1664 // C2Component::flush_sm() should return within 5ms.
1665 setDeadline(now, 50ms, "flush");
1666 flush();
1667 break;
1668 }
1669 case kWhatCreateInputSurface: {
1670 // Surface operations may be briefly blocking.
1671 setDeadline(now, 100ms, "createInputSurface");
1672 createInputSurface();
1673 break;
1674 }
1675 case kWhatSetInputSurface: {
1676 // Surface operations may be briefly blocking.
1677 setDeadline(now, 100ms, "setInputSurface");
1678 sp<RefBase> obj;
1679 CHECK(msg->findObject("surface", &obj));
1680 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1681 setInputSurface(surface);
1682 break;
1683 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001684 case kWhatWorkDone: {
1685 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001686 bool shouldPost = false;
1687 {
1688 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1689 if (queue->empty()) {
1690 break;
1691 }
1692 work.swap(queue->front());
1693 queue->pop_front();
1694 shouldPost = !queue->empty();
1695 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001696 if (shouldPost) {
1697 (new AMessage(kWhatWorkDone, this))->post();
1698 }
1699
Pawin Vongmasa36653902018-11-15 00:10:25 -08001700 // handle configuration changes in work done
1701 Mutexed<Config>::Locked config(mConfig);
1702 bool changed = false;
1703 Config::Watcher<C2StreamInitDataInfo::output> initData =
1704 config->watch<C2StreamInitDataInfo::output>();
1705 if (!work->worklets.empty()
1706 && (work->worklets.front()->output.flags
1707 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1708
1709 // copy buffer info to config
1710 std::vector<std::unique_ptr<C2Param>> updates =
1711 std::move(work->worklets.front()->output.configUpdate);
1712 unsigned stream = 0;
1713 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1714 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1715 // move all info into output-stream #0 domain
1716 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1717 }
1718 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1719 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1720 // block.crop().left, block.crop().top,
1721 // block.crop().width, block.crop().height,
1722 // block.width(), block.height());
1723 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1724 updates.emplace_back(new C2StreamPictureSizeInfo::output(
1725 stream, block.width(), block.height()));
1726 break; // for now only do the first block
1727 }
1728 ++stream;
1729 }
1730
1731 changed = config->updateConfiguration(updates, config->mOutputDomain);
1732
1733 // copy standard infos to graphic buffers if not already present (otherwise, we
1734 // may overwrite the actual intermediate value with a final value)
1735 stream = 0;
1736 const static std::vector<C2Param::Index> stdGfxInfos = {
1737 C2StreamRotationInfo::output::PARAM_TYPE,
1738 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1739 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1740 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001741 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001742 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1743 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1744 };
1745 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1746 if (buf->data().graphicBlocks().size()) {
1747 for (C2Param::Index ix : stdGfxInfos) {
1748 if (!buf->hasInfo(ix)) {
1749 const C2Param *param =
1750 config->getConfigParameterValue(ix.withStream(stream));
1751 if (param) {
1752 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1753 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1754 }
1755 }
1756 }
1757 }
1758 ++stream;
1759 }
1760 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001761 if (config->mInputSurface) {
1762 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1763 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001764 mChannel->onWorkDone(
1765 std::move(work), changed ? config->mOutputFormat : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001766 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001767 break;
1768 }
1769 case kWhatWatch: {
1770 // watch message already posted; no-op.
1771 break;
1772 }
1773 default: {
1774 ALOGE("unrecognized message");
1775 break;
1776 }
1777 }
1778 setDeadline(TimePoint::max(), 0ms, "none");
1779}
1780
1781void CCodec::setDeadline(
1782 const TimePoint &now,
1783 const std::chrono::milliseconds &timeout,
1784 const char *name) {
1785 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1786 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1787 deadline->set(now + (timeout * mult), name);
1788}
1789
1790void CCodec::initiateReleaseIfStuck() {
1791 std::string name;
1792 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001793 {
1794 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001795 if (deadline->get() < std::chrono::steady_clock::now()) {
1796 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001797 }
1798 if (deadline->get() != TimePoint::max()) {
1799 pendingDeadline = true;
1800 }
1801 }
1802 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001803 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1804 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1805 if (elapsed >= kWorkDurationThreshold) {
1806 name = "queue";
1807 }
1808 if (elapsed > 0s) {
1809 pendingDeadline = true;
1810 }
1811 }
1812 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001813 // We're not stuck.
1814 if (pendingDeadline) {
1815 // If we are not stuck yet but still has deadline coming up,
1816 // post watch message to check back later.
1817 (new AMessage(kWhatWatch, this))->post();
1818 }
1819 return;
1820 }
1821
1822 ALOGW("previous call to %s exceeded timeout", name.c_str());
1823 initiateRelease(false);
1824 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1825}
1826
Pawin Vongmasa36653902018-11-15 00:10:25 -08001827} // namespace android
1828
1829extern "C" android::CodecBase *CreateCodec() {
1830 return new android::CCodec;
1831}
1832
Lajos Molnar47118272019-01-31 16:28:04 -08001833// Create Codec 2.0 input surface
Pawin Vongmasa36653902018-11-15 00:10:25 -08001834extern "C" android::PersistentSurface *CreateInputSurface() {
1835 // Attempt to create a Codec2's input surface.
1836 std::shared_ptr<android::Codec2Client::InputSurface> inputSurface =
1837 android::Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001838 if (!inputSurface) {
1839 return nullptr;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001840 }
Lajos Molnar47118272019-01-31 16:28:04 -08001841 return new android::PersistentSurface(
1842 inputSurface->getGraphicBufferProducer(),
1843 static_cast<android::sp<android::hidl::base::V1_0::IBase>>(
1844 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001845}
1846