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