blob: c72b58d3ffedcffada42c27ebb0a11be7056ac92 [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodec"
19#include <utils/Log.h>
20
21#include <sstream>
22#include <thread>
23
24#include <C2Config.h>
25#include <C2Debug.h>
26#include <C2ParamInternal.h>
27#include <C2PlatformSupport.h>
28
29#include <android/IGraphicBufferSource.h>
30#include <android/IOMXBufferSource.h>
31#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
32#include <android/hardware/media/omx/1.0/IOmx.h>
33#include <android-base/stringprintf.h>
34#include <cutils/properties.h>
35#include <gui/IGraphicBufferProducer.h>
36#include <gui/Surface.h>
37#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
38#include <media/omx/1.0/WGraphicBufferSource.h>
39#include <media/openmax/OMX_IndexExt.h>
40#include <media/stagefright/BufferProducerWrapper.h>
41#include <media/stagefright/MediaCodecConstants.h>
42#include <media/stagefright/PersistentSurface.h>
43#include <media/stagefright/codec2/1.0/InputSurface.h>
44
45#include "C2OMXNode.h"
46#include "CCodec.h"
47#include "CCodecBufferChannel.h"
48#include "InputSurfaceWrapper.h"
49
50extern "C" android::PersistentSurface *CreateInputSurface();
51
52namespace android {
53
54using namespace std::chrono_literals;
55using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
56using android::base::StringPrintf;
57using BGraphicBufferSource = ::android::IGraphicBufferSource;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080058using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080059
60namespace {
61
62class CCodecWatchdog : public AHandler {
63private:
64 enum {
65 kWhatWatch,
66 };
67 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
68
69public:
70 static sp<CCodecWatchdog> getInstance() {
71 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
72 static std::once_flag flag;
73 // Call Init() only once.
74 std::call_once(flag, Init, instance);
75 return instance;
76 }
77
78 ~CCodecWatchdog() = default;
79
80 void watch(sp<CCodec> codec) {
81 bool shouldPost = false;
82 {
83 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
84 // If a watch message is in flight, piggy-back this instance as well.
85 // Otherwise, post a new watch message.
86 shouldPost = codecs->empty();
87 codecs->emplace(codec);
88 }
89 if (shouldPost) {
90 ALOGV("posting watch message");
91 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
92 }
93 }
94
95protected:
96 void onMessageReceived(const sp<AMessage> &msg) {
97 switch (msg->what()) {
98 case kWhatWatch: {
99 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
100 ALOGV("watch for %zu codecs", codecs->size());
101 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
102 sp<CCodec> codec = it->promote();
103 if (codec == nullptr) {
104 continue;
105 }
106 codec->initiateReleaseIfStuck();
107 }
108 codecs->clear();
109 break;
110 }
111
112 default: {
113 TRESPASS("CCodecWatchdog: unrecognized message");
114 }
115 }
116 }
117
118private:
119 CCodecWatchdog() : mLooper(new ALooper) {}
120
121 static void Init(const sp<CCodecWatchdog> &thiz) {
122 ALOGV("Init");
123 thiz->mLooper->setName("CCodecWatchdog");
124 thiz->mLooper->registerHandler(thiz);
125 thiz->mLooper->start();
126 }
127
128 sp<ALooper> mLooper;
129
130 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
131};
132
133class C2InputSurfaceWrapper : public InputSurfaceWrapper {
134public:
135 explicit C2InputSurfaceWrapper(
136 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
137 mSurface(surface) {
138 }
139
140 ~C2InputSurfaceWrapper() override = default;
141
142 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
143 if (mConnection != nullptr) {
144 return ALREADY_EXISTS;
145 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800146 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800147 }
148
149 void disconnect() override {
150 if (mConnection != nullptr) {
151 mConnection->disconnect();
152 mConnection = nullptr;
153 }
154 }
155
156 status_t start() override {
157 // InputSurface does not distinguish started state
158 return OK;
159 }
160
161 status_t signalEndOfInputStream() override {
162 C2InputSurfaceEosTuning eos(true);
163 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800164 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800165 if (err != C2_OK) {
166 return UNKNOWN_ERROR;
167 }
168 return OK;
169 }
170
171 status_t configure(Config &config __unused) {
172 // TODO
173 return OK;
174 }
175
176private:
177 std::shared_ptr<Codec2Client::InputSurface> mSurface;
178 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
179};
180
181class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
182public:
183// explicit GraphicBufferSourceWrapper(const sp<BGraphicBufferSource> &source) : mSource(source) {}
184 GraphicBufferSourceWrapper(
185 const sp<BGraphicBufferSource> &source,
186 uint32_t width,
187 uint32_t height)
188 : mSource(source), mWidth(width), mHeight(height) {
189 mDataSpace = HAL_DATASPACE_BT709;
190 }
191 ~GraphicBufferSourceWrapper() override = default;
192
193 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
194 mNode = new C2OMXNode(comp);
195 mNode->setFrameSize(mWidth, mHeight);
196
197 // NOTE: we do not use/pass through color aspects from GraphicBufferSource as we
198 // communicate that directly to the component.
199 mSource->configure(mNode, mDataSpace);
200 return OK;
201 }
202
203 void disconnect() override {
204 if (mNode == nullptr) {
205 return;
206 }
207 sp<IOMXBufferSource> source = mNode->getSource();
208 if (source == nullptr) {
209 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
210 return;
211 }
212 source->onOmxIdle();
213 source->onOmxLoaded();
214 mNode.clear();
215 }
216
217 status_t GetStatus(const binder::Status &status) {
218 status_t err = OK;
219 if (!status.isOk()) {
220 err = status.serviceSpecificErrorCode();
221 if (err == OK) {
222 err = status.transactionError();
223 if (err == OK) {
224 // binder status failed, but there is no servie or transaction error
225 err = UNKNOWN_ERROR;
226 }
227 }
228 }
229 return err;
230 }
231
232 status_t start() override {
233 sp<IOMXBufferSource> source = mNode->getSource();
234 if (source == nullptr) {
235 return NO_INIT;
236 }
237 constexpr size_t kNumSlots = 16;
238 for (size_t i = 0; i < kNumSlots; ++i) {
239 source->onInputBufferAdded(i);
240 }
241
242 source->onOmxExecuting();
243 return OK;
244 }
245
246 status_t signalEndOfInputStream() override {
247 return GetStatus(mSource->signalEndOfInputStream());
248 }
249
250 status_t configure(Config &config) {
251 std::stringstream status;
252 status_t err = OK;
253
254 // handle each configuration granually, in case we need to handle part of the configuration
255 // elsewhere
256
257 // TRICKY: we do not unset frame delay repeating
258 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
259 int64_t us = 1e6 / config.mMinFps + 0.5;
260 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
261 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
262 if (res != OK) {
263 status << " (=> " << asString(res) << ")";
264 err = res;
265 }
266 mConfig.mMinFps = config.mMinFps;
267 }
268
269 // pts gap
270 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
271 if (mNode != nullptr) {
272 OMX_PARAM_U32TYPE ptrGapParam = {};
273 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
274 ptrGapParam.nU32 = (config.mMinAdjustedFps > 0)
275 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
276 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
277 (void)mNode->setParameter(
278 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
279 &ptrGapParam, sizeof(ptrGapParam));
280 }
281 }
282
283 // max fps
284 // TRICKY: we do not unset max fps to 0 unless using fixed fps
285 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == 0))
286 && config.mMaxFps != mConfig.mMaxFps) {
287 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
288 status << " maxFps=" << config.mMaxFps;
289 if (res != OK) {
290 status << " (=> " << asString(res) << ")";
291 err = res;
292 }
293 mConfig.mMaxFps = config.mMaxFps;
294 }
295
296 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
297 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
298 status << " timeOffset " << config.mTimeOffsetUs << "us";
299 if (res != OK) {
300 status << " (=> " << asString(res) << ")";
301 err = res;
302 }
303 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
304 }
305
306 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
307 status_t res =
308 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
309 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
310 if (res != OK) {
311 status << " (=> " << asString(res) << ")";
312 err = res;
313 }
314 mConfig.mCaptureFps = config.mCaptureFps;
315 mConfig.mCodedFps = config.mCodedFps;
316 }
317
318 if (config.mStartAtUs != mConfig.mStartAtUs
319 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
320 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
321 status << " start at " << config.mStartAtUs << "us";
322 if (res != OK) {
323 status << " (=> " << asString(res) << ")";
324 err = res;
325 }
326 mConfig.mStartAtUs = config.mStartAtUs;
327 mConfig.mStopped = config.mStopped;
328 }
329
330 // suspend-resume
331 if (config.mSuspended != mConfig.mSuspended) {
332 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
333 status << " " << (config.mSuspended ? "suspend" : "resume")
334 << " at " << config.mSuspendAtUs << "us";
335 if (res != OK) {
336 status << " (=> " << asString(res) << ")";
337 err = res;
338 }
339 mConfig.mSuspended = config.mSuspended;
340 mConfig.mSuspendAtUs = config.mSuspendAtUs;
341 }
342
343 if (config.mStopped != mConfig.mStopped && config.mStopped) {
344 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
345 status << " stop at " << config.mStopAtUs << "us";
346 if (res != OK) {
347 status << " (=> " << asString(res) << ")";
348 err = res;
349 } else {
350 status << " delayUs";
351 res = GetStatus(mSource->getStopTimeOffsetUs(&config.mInputDelayUs));
352 if (res != OK) {
353 status << " (=> " << asString(res) << ")";
354 } else {
355 status << "=" << config.mInputDelayUs << "us";
356 }
357 mConfig.mInputDelayUs = config.mInputDelayUs;
358 }
359 mConfig.mStopAtUs = config.mStopAtUs;
360 mConfig.mStopped = config.mStopped;
361 }
362
363 // color aspects (android._color-aspects)
364
365 // consumer usage
366 ALOGD("ISConfig%s", status.str().c_str());
367 return err;
368 }
369
370private:
371 sp<BGraphicBufferSource> mSource;
372 sp<C2OMXNode> mNode;
373 uint32_t mWidth;
374 uint32_t mHeight;
375 Config mConfig;
376};
377
378class Codec2ClientInterfaceWrapper : public C2ComponentStore {
379 std::shared_ptr<Codec2Client> mClient;
380
381public:
382 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
383 : mClient(client) { }
384
385 virtual ~Codec2ClientInterfaceWrapper() = default;
386
387 virtual c2_status_t config_sm(
388 const std::vector<C2Param *> &params,
389 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
390 return mClient->config(params, C2_MAY_BLOCK, failures);
391 };
392
393 virtual c2_status_t copyBuffer(
394 std::shared_ptr<C2GraphicBuffer>,
395 std::shared_ptr<C2GraphicBuffer>) {
396 return C2_OMITTED;
397 }
398
399 virtual c2_status_t createComponent(
400 C2String, std::shared_ptr<C2Component> *const component) {
401 component->reset();
402 return C2_OMITTED;
403 }
404
405 virtual c2_status_t createInterface(
406 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
407 interface->reset();
408 return C2_OMITTED;
409 }
410
411 virtual c2_status_t query_sm(
412 const std::vector<C2Param *> &stackParams,
413 const std::vector<C2Param::Index> &heapParamIndices,
414 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
415 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
416 }
417
418 virtual c2_status_t querySupportedParams_nb(
419 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
420 return mClient->querySupportedParams(params);
421 }
422
423 virtual c2_status_t querySupportedValues_sm(
424 std::vector<C2FieldSupportedValuesQuery> &fields) const {
425 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
426 }
427
428 virtual C2String getName() const {
429 return mClient->getName();
430 }
431
432 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
433 return mClient->getParamReflector();
434 }
435
436 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
437 return std::vector<std::shared_ptr<const C2Component::Traits>>();
438 }
439};
440
441} // namespace
442
443// CCodec::ClientListener
444
445struct CCodec::ClientListener : public Codec2Client::Listener {
446
447 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
448
449 virtual void onWorkDone(
450 const std::weak_ptr<Codec2Client::Component>& component,
451 std::list<std::unique_ptr<C2Work>>& workItems,
452 size_t numDiscardedInputBuffers) override {
453 (void)component;
454 sp<CCodec> codec(mCodec.promote());
455 if (!codec) {
456 return;
457 }
458 codec->onWorkDone(workItems, numDiscardedInputBuffers);
459 }
460
461 virtual void onTripped(
462 const std::weak_ptr<Codec2Client::Component>& component,
463 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
464 ) override {
465 // TODO
466 (void)component;
467 (void)settingResult;
468 }
469
470 virtual void onError(
471 const std::weak_ptr<Codec2Client::Component>& component,
472 uint32_t errorCode) override {
473 // TODO
474 (void)component;
475 (void)errorCode;
476 }
477
478 virtual void onDeath(
479 const std::weak_ptr<Codec2Client::Component>& component) override {
480 { // Log the death of the component.
481 std::shared_ptr<Codec2Client::Component> comp = component.lock();
482 if (!comp) {
483 ALOGE("Codec2 component died.");
484 } else {
485 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
486 }
487 }
488
489 // Report to MediaCodec.
490 sp<CCodec> codec(mCodec.promote());
491 if (!codec || !codec->mCallback) {
492 return;
493 }
494 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
495 }
496
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800497 virtual void onFrameRendered(uint64_t bufferQueueId,
498 int32_t slotId,
499 int64_t timestampNs) override {
500 // TODO: implement
501 (void)bufferQueueId;
502 (void)slotId;
503 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800504 }
505
506 virtual void onInputBufferDone(
507 const std::shared_ptr<C2Buffer>& buffer) override {
508 sp<CCodec> codec(mCodec.promote());
509 if (codec) {
510 codec->onInputBufferDone(buffer);
511 }
512 }
513
514private:
515 wp<CCodec> mCodec;
516};
517
518// CCodecCallbackImpl
519
520class CCodecCallbackImpl : public CCodecCallback {
521public:
522 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
523 ~CCodecCallbackImpl() override = default;
524
525 void onError(status_t err, enum ActionCode actionCode) override {
526 mCodec->mCallback->onError(err, actionCode);
527 }
528
529 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
530 mCodec->mCallback->onOutputFramesRendered(
531 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
532 }
533
534 void onWorkQueued(bool eos) override {
535 mCodec->onWorkQueued(eos);
536 }
537
538 void onOutputBuffersChanged() override {
539 mCodec->mCallback->onOutputBuffersChanged();
540 }
541
542private:
543 CCodec *mCodec;
544};
545
546// CCodec
547
548CCodec::CCodec()
549 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
550 mQueuedWorkCount(0) {
551}
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
602 client = Codec2Client::CreateFromService("default", false);
603 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
718 /*
719 * Handle input surface configuration
720 */
721 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
722 && (config->mDomain & Config::IS_ENCODER)) {
723 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
724 {
725 config->mISConfig->mMinFps = 0;
726 int64_t value;
727 if (msg->findInt64("repeat-previous-frame-after", &value) && value > 0) {
728 config->mISConfig->mMinFps = 1e6 / value;
729 }
730 (void)msg->findFloat("max-fps-to-encoder", &config->mISConfig->mMaxFps);
731 config->mISConfig->mMinAdjustedFps = 0;
732 config->mISConfig->mFixedAdjustedFps = 0;
733 if (msg->findInt64("max-pts-gap-to-encoder", &value)) {
734 if (value < 0 && value >= INT32_MIN) {
735 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
736 } else if (value > 0 && value <= INT32_MAX) {
737 config->mISConfig->mMinAdjustedFps = 1e6 / value;
738 }
739 }
740 }
741
742 {
743 double value;
744 if (msg->findDouble("time-lapse-fps", &value)) {
745 config->mISConfig->mCaptureFps = value;
746 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
747 }
748 }
749
750 {
751 config->mISConfig->mSuspended = false;
752 config->mISConfig->mSuspendAtUs = -1;
753 int32_t value;
754 if (msg->findInt32("create-input-buffers-suspended", &value) && value) {
755 config->mISConfig->mSuspended = true;
756 }
757 }
758 }
759
760 /*
761 * Handle desired color format.
762 */
763 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
764 int32_t format = -1;
765 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
766 /*
767 * Also handle default color format (encoders require color format, so this is only
768 * needed for decoders.
769 */
770 if (!(config->mDomain & Config::IS_ENCODER)) {
771 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
772 }
773 }
774
775 if (format >= 0) {
776 msg->setInt32("android._color-format", format);
777 }
778 }
779
780 std::vector<std::unique_ptr<C2Param>> configUpdate;
781 status_t err = config->getConfigUpdateFromSdkParams(
782 comp, msg, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
783 if (err != OK) {
784 ALOGW("failed to convert configuration to c2 params");
785 }
786 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
787 if (err != OK) {
788 ALOGW("failed to configure c2 params");
789 return err;
790 }
791
792 std::vector<std::unique_ptr<C2Param>> params;
793 C2StreamUsageTuning::input usage(0u, 0u);
794 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
795
796 std::initializer_list<C2Param::Index> indices {
797 };
798 c2_status_t c2err = comp->query(
799 { &usage, &maxInputSize },
800 indices,
801 C2_DONT_BLOCK,
802 &params);
803 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
804 ALOGE("Failed to query component interface: %d", c2err);
805 return UNKNOWN_ERROR;
806 }
807 if (params.size() != indices.size()) {
808 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
809 indices.size(), params.size());
810 return UNKNOWN_ERROR;
811 }
812 if (usage && (usage.value & C2MemoryUsage::CPU_READ)) {
813 config->mInputFormat->setInt32("using-sw-read-often", true);
814 }
815
816 // NOTE: we don't blindly use client specified input size if specified as clients
817 // at times specify too small size. Instead, mimic the behavior from OMX, where the
818 // client specified size is only used to ask for bigger buffers than component suggested
819 // size.
820 int32_t clientInputSize = 0;
821 bool clientSpecifiedInputSize =
822 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
823 // TEMP: enforce minimum buffer size of 1MB for video decoders
824 // and 16K / 4K for audio encoders/decoders
825 if (maxInputSize.value == 0) {
826 if (config->mDomain & Config::IS_AUDIO) {
827 maxInputSize.value = encoder ? 16384 : 4096;
828 } else if (!encoder) {
829 maxInputSize.value = 1048576u;
830 }
831 }
832
833 // verify that CSD fits into this size (if defined)
834 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
835 sp<ABuffer> csd;
836 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
837 if (csd && csd->size() > maxInputSize.value) {
838 maxInputSize.value = csd->size();
839 }
840 }
841 }
842
843 // TODO: do this based on component requiring linear allocator for input
844 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
845 if (clientSpecifiedInputSize) {
846 // Warn that we're overriding client's max input size if necessary.
847 if ((uint32_t)clientInputSize < maxInputSize.value) {
848 ALOGD("client requested max input size %d, which is smaller than "
849 "what component recommended (%u); overriding with component "
850 "recommendation.", clientInputSize, maxInputSize.value);
851 ALOGW("This behavior is subject to change. It is recommended that "
852 "app developers double check whether the requested "
853 "max input size is in reasonable range.");
854 } else {
855 maxInputSize.value = clientInputSize;
856 }
857 }
858 // Pass max input size on input format to the buffer channel (if supplied by the
859 // component or by a default)
860 if (maxInputSize.value) {
861 config->mInputFormat->setInt32(
862 KEY_MAX_INPUT_SIZE,
863 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
864 }
865 }
866
867 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
868 // propagate HDR static info to output format for both encoders and decoders
869 // if component supports this info, we will update from component, but only the raw port,
870 // so don't propagate if component already filled it in.
871 sp<ABuffer> hdrInfo;
872 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
873 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
874 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
875 }
876
877 // Set desired color format from configuration parameter
878 int32_t format;
879 if (msg->findInt32("android._color-format", &format)) {
880 if (config->mDomain & Config::IS_ENCODER) {
881 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
882 } else {
883 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
884 }
885 }
886 }
887
888 // propagate encoder delay and padding to output format
889 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
890 int delay = 0;
891 if (msg->findInt32("encoder-delay", &delay)) {
892 config->mOutputFormat->setInt32("encoder-delay", delay);
893 }
894 int padding = 0;
895 if (msg->findInt32("encoder-padding", &padding)) {
896 config->mOutputFormat->setInt32("encoder-padding", padding);
897 }
898 }
899
900 // set channel-mask
901 if (config->mDomain & Config::IS_AUDIO) {
902 int32_t mask;
903 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
904 if (config->mDomain & Config::IS_ENCODER) {
905 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
906 } else {
907 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
908 }
909 }
910 }
911
912 ALOGD("setup formats input: %s and output: %s",
913 config->mInputFormat->debugString().c_str(),
914 config->mOutputFormat->debugString().c_str());
915 return OK;
916 };
917 if (tryAndReportOnError(doConfig) != OK) {
918 return;
919 }
920
921 Mutexed<Config>::Locked config(mConfig);
922
923 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
924}
925
926void CCodec::initiateCreateInputSurface() {
927 status_t err = [this] {
928 Mutexed<State>::Locked state(mState);
929 if (state->get() != ALLOCATED) {
930 return UNKNOWN_ERROR;
931 }
932 // TODO: read it from intf() properly.
933 if (state->comp->getName().find("encoder") == std::string::npos) {
934 return INVALID_OPERATION;
935 }
936 return OK;
937 }();
938 if (err != OK) {
939 mCallback->onInputSurfaceCreationFailed(err);
940 return;
941 }
942
943 (new AMessage(kWhatCreateInputSurface, this))->post();
944}
945
Lajos Molnar47118272019-01-31 16:28:04 -0800946sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
947 using namespace android::hardware::media::omx::V1_0;
948 using namespace android::hardware::media::omx::V1_0::utils;
949 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
950 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
951 android::sp<IOmx> omx = IOmx::getService();
952 typedef android::hardware::graphics::bufferqueue::V1_0::
953 IGraphicBufferProducer HGraphicBufferProducer;
954 typedef android::hardware::media::omx::V1_0::
955 IGraphicBufferSource HGraphicBufferSource;
956 OmxStatus s;
957 android::sp<HGraphicBufferProducer> gbp;
958 android::sp<HGraphicBufferSource> gbs;
959 android::Return<void> transStatus = omx->createInputSurface(
960 [&s, &gbp, &gbs](
961 OmxStatus status,
962 const android::sp<HGraphicBufferProducer>& producer,
963 const android::sp<HGraphicBufferSource>& source) {
964 s = status;
965 gbp = producer;
966 gbs = source;
967 });
968 if (transStatus.isOk() && s == OmxStatus::OK) {
969 return new PersistentSurface(
970 new H2BGraphicBufferProducer(gbp),
971 sp<::android::IGraphicBufferSource>(new LWGraphicBufferSource(gbs)));
972 }
973
974 return nullptr;
975}
976
977sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
978 sp<PersistentSurface> surface(CreateInputSurface());
979
980 if (surface == nullptr) {
981 surface = CreateOmxInputSurface();
982 }
983
984 return surface;
985}
986
Pawin Vongmasa36653902018-11-15 00:10:25 -0800987void CCodec::createInputSurface() {
988 status_t err;
989 sp<IGraphicBufferProducer> bufferProducer;
990
991 sp<AMessage> inputFormat;
992 sp<AMessage> outputFormat;
993 {
994 Mutexed<Config>::Locked config(mConfig);
995 inputFormat = config->mInputFormat;
996 outputFormat = config->mOutputFormat;
997 }
998
Lajos Molnar47118272019-01-31 16:28:04 -0800999 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001000
1001 if (persistentSurface->getHidlTarget()) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001002 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001003 persistentSurface->getHidlTarget());
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001004 if (!hidlInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001005 ALOGE("Corrupted input surface");
1006 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1007 return;
1008 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001009 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1010 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001011 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001012 inputSurface));
1013 bufferProducer = inputSurface->getGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001014 } else {
1015 int32_t width = 0;
1016 (void)outputFormat->findInt32("width", &width);
1017 int32_t height = 0;
1018 (void)outputFormat->findInt32("height", &height);
1019 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1020 persistentSurface->getBufferSource(), width, height));
1021 bufferProducer = persistentSurface->getBufferProducer();
1022 }
1023
1024 if (err != OK) {
1025 ALOGE("Failed to set up input surface: %d", err);
1026 mCallback->onInputSurfaceCreationFailed(err);
1027 return;
1028 }
1029
1030 mCallback->onInputSurfaceCreated(
1031 inputFormat,
1032 outputFormat,
1033 new BufferProducerWrapper(bufferProducer));
1034}
1035
1036status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
1037 Mutexed<Config>::Locked config(mConfig);
1038 config->mUsingSurface = true;
1039
1040 // we are now using surface - apply default color aspects to input format - as well as
1041 // get dataspace
1042 bool inputFormatChanged = config->updateFormats(config->IS_INPUT);
1043 ALOGD("input format %s to %s",
1044 inputFormatChanged ? "changed" : "unchanged",
1045 config->mInputFormat->debugString().c_str());
1046
1047 // configure dataspace
1048 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1049 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1050 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1051 surface->setDataSpace(dataSpace);
1052
1053 status_t err = mChannel->setInputSurface(surface);
1054 if (err != OK) {
1055 // undo input format update
1056 config->mUsingSurface = false;
1057 (void)config->updateFormats(config->IS_INPUT);
1058 return err;
1059 }
1060 config->mInputSurface = surface;
1061
1062 if (config->mISConfig) {
1063 surface->configure(*config->mISConfig);
1064 } else {
1065 ALOGD("ISConfig: no configuration");
1066 }
1067
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001068 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001069}
1070
1071void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1072 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1073 msg->setObject("surface", surface);
1074 msg->post();
1075}
1076
1077void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1078 sp<AMessage> inputFormat;
1079 sp<AMessage> outputFormat;
1080 {
1081 Mutexed<Config>::Locked config(mConfig);
1082 inputFormat = config->mInputFormat;
1083 outputFormat = config->mOutputFormat;
1084 }
1085 auto hidlTarget = surface->getHidlTarget();
1086 if (hidlTarget) {
1087 sp<IInputSurface> inputSurface =
1088 IInputSurface::castFrom(hidlTarget);
1089 if (!inputSurface) {
1090 ALOGE("Failed to set input surface: Corrupted surface.");
1091 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1092 return;
1093 }
1094 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1095 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1096 if (err != OK) {
1097 ALOGE("Failed to set up input surface: %d", err);
1098 mCallback->onInputSurfaceDeclined(err);
1099 return;
1100 }
1101 } else {
1102 int32_t width = 0;
1103 (void)outputFormat->findInt32("width", &width);
1104 int32_t height = 0;
1105 (void)outputFormat->findInt32("height", &height);
1106 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1107 surface->getBufferSource(), width, height));
1108 if (err != OK) {
1109 ALOGE("Failed to set up input surface: %d", err);
1110 mCallback->onInputSurfaceDeclined(err);
1111 return;
1112 }
1113 }
1114 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1115}
1116
1117void CCodec::initiateStart() {
1118 auto setStarting = [this] {
1119 Mutexed<State>::Locked state(mState);
1120 if (state->get() != ALLOCATED) {
1121 return UNKNOWN_ERROR;
1122 }
1123 state->set(STARTING);
1124 return OK;
1125 };
1126 if (tryAndReportOnError(setStarting) != OK) {
1127 return;
1128 }
1129
1130 (new AMessage(kWhatStart, this))->post();
1131}
1132
1133void CCodec::start() {
1134 std::shared_ptr<Codec2Client::Component> comp;
1135 auto checkStarting = [this, &comp] {
1136 Mutexed<State>::Locked state(mState);
1137 if (state->get() != STARTING) {
1138 return UNKNOWN_ERROR;
1139 }
1140 comp = state->comp;
1141 return OK;
1142 };
1143 if (tryAndReportOnError(checkStarting) != OK) {
1144 return;
1145 }
1146
1147 c2_status_t err = comp->start();
1148 if (err != C2_OK) {
1149 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1150 ACTION_CODE_FATAL);
1151 return;
1152 }
1153 sp<AMessage> inputFormat;
1154 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001155 status_t err2 = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001156 {
1157 Mutexed<Config>::Locked config(mConfig);
1158 inputFormat = config->mInputFormat;
1159 outputFormat = config->mOutputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001160 if (config->mInputSurface) {
1161 err2 = config->mInputSurface->start();
1162 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001163 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001164 if (err2 != OK) {
1165 mCallback->onError(err2, ACTION_CODE_FATAL);
1166 return;
1167 }
1168 err2 = mChannel->start(inputFormat, outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001169 if (err2 != OK) {
1170 mCallback->onError(err2, ACTION_CODE_FATAL);
1171 return;
1172 }
1173
1174 auto setRunning = [this] {
1175 Mutexed<State>::Locked state(mState);
1176 if (state->get() != STARTING) {
1177 return UNKNOWN_ERROR;
1178 }
1179 state->set(RUNNING);
1180 return OK;
1181 };
1182 if (tryAndReportOnError(setRunning) != OK) {
1183 return;
1184 }
1185 mCallback->onStartCompleted();
1186
1187 (void)mChannel->requestInitialInputBuffers();
1188}
1189
1190void CCodec::initiateShutdown(bool keepComponentAllocated) {
1191 if (keepComponentAllocated) {
1192 initiateStop();
1193 } else {
1194 initiateRelease();
1195 }
1196}
1197
1198void CCodec::initiateStop() {
1199 {
1200 Mutexed<State>::Locked state(mState);
1201 if (state->get() == ALLOCATED
1202 || state->get() == RELEASED
1203 || state->get() == STOPPING
1204 || state->get() == RELEASING) {
1205 // We're already stopped, released, or doing it right now.
1206 state.unlock();
1207 mCallback->onStopCompleted();
1208 state.lock();
1209 return;
1210 }
1211 state->set(STOPPING);
1212 }
1213
1214 mChannel->stop();
1215 (new AMessage(kWhatStop, this))->post();
1216}
1217
1218void CCodec::stop() {
1219 std::shared_ptr<Codec2Client::Component> comp;
1220 {
1221 Mutexed<State>::Locked state(mState);
1222 if (state->get() == RELEASING) {
1223 state.unlock();
1224 // We're already stopped or release is in progress.
1225 mCallback->onStopCompleted();
1226 state.lock();
1227 return;
1228 } else if (state->get() != STOPPING) {
1229 state.unlock();
1230 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1231 state.lock();
1232 return;
1233 }
1234 comp = state->comp;
1235 }
1236 status_t err = comp->stop();
1237 if (err != C2_OK) {
1238 // TODO: convert err into status_t
1239 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1240 }
1241
1242 {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001243 Mutexed<Config>::Locked config(mConfig);
1244 if (config->mInputSurface) {
1245 config->mInputSurface->disconnect();
1246 config->mInputSurface = nullptr;
1247 }
1248 }
1249 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001250 Mutexed<State>::Locked state(mState);
1251 if (state->get() == STOPPING) {
1252 state->set(ALLOCATED);
1253 }
1254 }
1255 mCallback->onStopCompleted();
1256}
1257
1258void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001259 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001260 {
1261 Mutexed<State>::Locked state(mState);
1262 if (state->get() == RELEASED || state->get() == RELEASING) {
1263 // We're already released or doing it right now.
1264 if (sendCallback) {
1265 state.unlock();
1266 mCallback->onReleaseCompleted();
1267 state.lock();
1268 }
1269 return;
1270 }
1271 if (state->get() == ALLOCATING) {
1272 state->set(RELEASING);
1273 // With the altered state allocate() would fail and clean up.
1274 if (sendCallback) {
1275 state.unlock();
1276 mCallback->onReleaseCompleted();
1277 state.lock();
1278 }
1279 return;
1280 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001281 if (state->get() == STARTING
1282 || state->get() == RUNNING
1283 || state->get() == STOPPING) {
1284 // Input surface may have been started, so clean up is needed.
1285 clearInputSurfaceIfNeeded = true;
1286 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001287 state->set(RELEASING);
1288 }
1289
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001290 if (clearInputSurfaceIfNeeded) {
1291 Mutexed<Config>::Locked config(mConfig);
1292 if (config->mInputSurface) {
1293 config->mInputSurface->disconnect();
1294 config->mInputSurface = nullptr;
1295 }
1296 }
1297
Pawin Vongmasa36653902018-11-15 00:10:25 -08001298 mChannel->stop();
1299 // thiz holds strong ref to this while the thread is running.
1300 sp<CCodec> thiz(this);
1301 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1302}
1303
1304void CCodec::release(bool sendCallback) {
1305 std::shared_ptr<Codec2Client::Component> comp;
1306 {
1307 Mutexed<State>::Locked state(mState);
1308 if (state->get() == RELEASED) {
1309 if (sendCallback) {
1310 state.unlock();
1311 mCallback->onReleaseCompleted();
1312 state.lock();
1313 }
1314 return;
1315 }
1316 comp = state->comp;
1317 }
1318 comp->release();
1319
1320 {
1321 Mutexed<State>::Locked state(mState);
1322 state->set(RELEASED);
1323 state->comp.reset();
1324 }
1325 if (sendCallback) {
1326 mCallback->onReleaseCompleted();
1327 }
1328}
1329
1330status_t CCodec::setSurface(const sp<Surface> &surface) {
1331 return mChannel->setSurface(surface);
1332}
1333
1334void CCodec::signalFlush() {
1335 status_t err = [this] {
1336 Mutexed<State>::Locked state(mState);
1337 if (state->get() == FLUSHED) {
1338 return ALREADY_EXISTS;
1339 }
1340 if (state->get() != RUNNING) {
1341 return UNKNOWN_ERROR;
1342 }
1343 state->set(FLUSHING);
1344 return OK;
1345 }();
1346 switch (err) {
1347 case ALREADY_EXISTS:
1348 mCallback->onFlushCompleted();
1349 return;
1350 case OK:
1351 break;
1352 default:
1353 mCallback->onError(err, ACTION_CODE_FATAL);
1354 return;
1355 }
1356
1357 mChannel->stop();
1358 (new AMessage(kWhatFlush, this))->post();
1359}
1360
1361void CCodec::flush() {
1362 std::shared_ptr<Codec2Client::Component> comp;
1363 auto checkFlushing = [this, &comp] {
1364 Mutexed<State>::Locked state(mState);
1365 if (state->get() != FLUSHING) {
1366 return UNKNOWN_ERROR;
1367 }
1368 comp = state->comp;
1369 return OK;
1370 };
1371 if (tryAndReportOnError(checkFlushing) != OK) {
1372 return;
1373 }
1374
1375 std::list<std::unique_ptr<C2Work>> flushedWork;
1376 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1377 {
1378 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1379 flushedWork.splice(flushedWork.end(), *queue);
1380 }
1381 if (err != C2_OK) {
1382 // TODO: convert err into status_t
1383 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1384 }
1385
1386 mChannel->flush(flushedWork);
1387 subQueuedWorkCount(flushedWork.size());
1388
1389 {
1390 Mutexed<State>::Locked state(mState);
1391 state->set(FLUSHED);
1392 }
1393 mCallback->onFlushCompleted();
1394}
1395
1396void CCodec::signalResume() {
1397 auto setResuming = [this] {
1398 Mutexed<State>::Locked state(mState);
1399 if (state->get() != FLUSHED) {
1400 return UNKNOWN_ERROR;
1401 }
1402 state->set(RESUMING);
1403 return OK;
1404 };
1405 if (tryAndReportOnError(setResuming) != OK) {
1406 return;
1407 }
1408
1409 (void)mChannel->start(nullptr, nullptr);
1410
1411 {
1412 Mutexed<State>::Locked state(mState);
1413 if (state->get() != RESUMING) {
1414 state.unlock();
1415 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1416 state.lock();
1417 return;
1418 }
1419 state->set(RUNNING);
1420 }
1421
1422 (void)mChannel->requestInitialInputBuffers();
1423}
1424
1425void CCodec::signalSetParameters(const sp<AMessage> &params) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001426 setParameters(params);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001427}
1428
1429void CCodec::setParameters(const sp<AMessage> &params) {
1430 std::shared_ptr<Codec2Client::Component> comp;
1431 auto checkState = [this, &comp] {
1432 Mutexed<State>::Locked state(mState);
1433 if (state->get() == RELEASED) {
1434 return INVALID_OPERATION;
1435 }
1436 comp = state->comp;
1437 return OK;
1438 };
1439 if (tryAndReportOnError(checkState) != OK) {
1440 return;
1441 }
1442
1443 Mutexed<Config>::Locked config(mConfig);
1444
1445 /**
1446 * Handle input surface parameters
1447 */
1448 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1449 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
1450 (void)params->findInt64("time-offset-us", &config->mISConfig->mTimeOffsetUs);
1451
1452 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1453 config->mISConfig->mStopped = false;
1454 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1455 config->mISConfig->mStopped = true;
1456 }
1457
1458 int32_t value;
1459 if (params->findInt32("drop-input-frames", &value)) {
1460 config->mISConfig->mSuspended = value;
1461 config->mISConfig->mSuspendAtUs = -1;
1462 (void)params->findInt64("drop-start-time-us", &config->mISConfig->mSuspendAtUs);
1463 }
1464
1465 (void)config->mInputSurface->configure(*config->mISConfig);
1466 if (config->mISConfig->mStopped) {
1467 config->mInputFormat->setInt64(
1468 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1469 }
1470 }
1471
1472 std::vector<std::unique_ptr<C2Param>> configUpdate;
1473 (void)config->getConfigUpdateFromSdkParams(
1474 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1475 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1476 // Parameter synchronization is not defined when using input surface. For now, route
1477 // these directly to the component.
1478 if (config->mInputSurface == nullptr
1479 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1480 || comp->getName().find("c2.android.") == 0)) {
1481 mChannel->setParameters(configUpdate);
1482 } else {
1483 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1484 }
1485}
1486
1487void CCodec::signalEndOfInputStream() {
1488 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1489}
1490
1491void CCodec::signalRequestIDRFrame() {
1492 std::shared_ptr<Codec2Client::Component> comp;
1493 {
1494 Mutexed<State>::Locked state(mState);
1495 if (state->get() == RELEASED) {
1496 ALOGD("no IDR request sent since component is released");
1497 return;
1498 }
1499 comp = state->comp;
1500 }
1501 ALOGV("request IDR");
1502 Mutexed<Config>::Locked config(mConfig);
1503 std::vector<std::unique_ptr<C2Param>> params;
1504 params.push_back(
1505 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1506 config->setParameters(comp, params, C2_MAY_BLOCK);
1507}
1508
1509void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems,
1510 size_t numDiscardedInputBuffers) {
1511 if (!workItems.empty()) {
1512 {
1513 Mutexed<std::list<size_t>>::Locked numDiscardedInputBuffersQueue(
1514 mNumDiscardedInputBuffersQueue);
1515 numDiscardedInputBuffersQueue->insert(
1516 numDiscardedInputBuffersQueue->end(),
1517 workItems.size() - 1, 0);
1518 numDiscardedInputBuffersQueue->emplace_back(
1519 numDiscardedInputBuffers);
1520 }
1521 {
1522 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1523 queue->splice(queue->end(), workItems);
1524 }
1525 }
1526 (new AMessage(kWhatWorkDone, this))->post();
1527}
1528
1529void CCodec::onInputBufferDone(const std::shared_ptr<C2Buffer>& buffer) {
1530 mChannel->onInputBufferDone(buffer);
1531}
1532
1533void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1534 TimePoint now = std::chrono::steady_clock::now();
1535 CCodecWatchdog::getInstance()->watch(this);
1536 switch (msg->what()) {
1537 case kWhatAllocate: {
1538 // C2ComponentStore::createComponent() should return within 100ms.
1539 setDeadline(now, 150ms, "allocate");
1540 sp<RefBase> obj;
1541 CHECK(msg->findObject("codecInfo", &obj));
1542 allocate((MediaCodecInfo *)obj.get());
1543 break;
1544 }
1545 case kWhatConfigure: {
1546 // C2Component::commit_sm() should return within 5ms.
1547 setDeadline(now, 250ms, "configure");
1548 sp<AMessage> format;
1549 CHECK(msg->findMessage("format", &format));
1550 configure(format);
1551 break;
1552 }
1553 case kWhatStart: {
1554 // C2Component::start() should return within 500ms.
1555 setDeadline(now, 550ms, "start");
1556 mQueuedWorkCount = 0;
1557 start();
1558 break;
1559 }
1560 case kWhatStop: {
1561 // C2Component::stop() should return within 500ms.
1562 setDeadline(now, 550ms, "stop");
1563 stop();
1564
1565 mQueuedWorkCount = 0;
1566 Mutexed<NamedTimePoint>::Locked deadline(mQueueDeadline);
1567 deadline->set(TimePoint::max(), "none");
1568 break;
1569 }
1570 case kWhatFlush: {
1571 // C2Component::flush_sm() should return within 5ms.
1572 setDeadline(now, 50ms, "flush");
1573 flush();
1574 break;
1575 }
1576 case kWhatCreateInputSurface: {
1577 // Surface operations may be briefly blocking.
1578 setDeadline(now, 100ms, "createInputSurface");
1579 createInputSurface();
1580 break;
1581 }
1582 case kWhatSetInputSurface: {
1583 // Surface operations may be briefly blocking.
1584 setDeadline(now, 100ms, "setInputSurface");
1585 sp<RefBase> obj;
1586 CHECK(msg->findObject("surface", &obj));
1587 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1588 setInputSurface(surface);
1589 break;
1590 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001591 case kWhatWorkDone: {
1592 std::unique_ptr<C2Work> work;
1593 size_t numDiscardedInputBuffers;
1594 bool shouldPost = false;
1595 {
1596 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1597 if (queue->empty()) {
1598 break;
1599 }
1600 work.swap(queue->front());
1601 queue->pop_front();
1602 shouldPost = !queue->empty();
1603 }
1604 {
1605 Mutexed<std::list<size_t>>::Locked numDiscardedInputBuffersQueue(
1606 mNumDiscardedInputBuffersQueue);
1607 if (numDiscardedInputBuffersQueue->empty()) {
1608 numDiscardedInputBuffers = 0;
1609 } else {
1610 numDiscardedInputBuffers = numDiscardedInputBuffersQueue->front();
1611 numDiscardedInputBuffersQueue->pop_front();
1612 }
1613 }
1614 if (shouldPost) {
1615 (new AMessage(kWhatWorkDone, this))->post();
1616 }
1617
1618 if (work->worklets.empty()
1619 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE)) {
1620 subQueuedWorkCount(1);
1621 }
1622 // handle configuration changes in work done
1623 Mutexed<Config>::Locked config(mConfig);
1624 bool changed = false;
1625 Config::Watcher<C2StreamInitDataInfo::output> initData =
1626 config->watch<C2StreamInitDataInfo::output>();
1627 if (!work->worklets.empty()
1628 && (work->worklets.front()->output.flags
1629 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1630
1631 // copy buffer info to config
1632 std::vector<std::unique_ptr<C2Param>> updates =
1633 std::move(work->worklets.front()->output.configUpdate);
1634 unsigned stream = 0;
1635 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1636 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1637 // move all info into output-stream #0 domain
1638 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1639 }
1640 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1641 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1642 // block.crop().left, block.crop().top,
1643 // block.crop().width, block.crop().height,
1644 // block.width(), block.height());
1645 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1646 updates.emplace_back(new C2StreamPictureSizeInfo::output(
1647 stream, block.width(), block.height()));
1648 break; // for now only do the first block
1649 }
1650 ++stream;
1651 }
1652
1653 changed = config->updateConfiguration(updates, config->mOutputDomain);
1654
1655 // copy standard infos to graphic buffers if not already present (otherwise, we
1656 // may overwrite the actual intermediate value with a final value)
1657 stream = 0;
1658 const static std::vector<C2Param::Index> stdGfxInfos = {
1659 C2StreamRotationInfo::output::PARAM_TYPE,
1660 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1661 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1662 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001663 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001664 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1665 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1666 };
1667 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1668 if (buf->data().graphicBlocks().size()) {
1669 for (C2Param::Index ix : stdGfxInfos) {
1670 if (!buf->hasInfo(ix)) {
1671 const C2Param *param =
1672 config->getConfigParameterValue(ix.withStream(stream));
1673 if (param) {
1674 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1675 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1676 }
1677 }
1678 }
1679 }
1680 ++stream;
1681 }
1682 }
1683 mChannel->onWorkDone(
1684 std::move(work), changed ? config->mOutputFormat : nullptr,
1685 initData.hasChanged() ? initData.update().get() : nullptr,
1686 numDiscardedInputBuffers);
1687 break;
1688 }
1689 case kWhatWatch: {
1690 // watch message already posted; no-op.
1691 break;
1692 }
1693 default: {
1694 ALOGE("unrecognized message");
1695 break;
1696 }
1697 }
1698 setDeadline(TimePoint::max(), 0ms, "none");
1699}
1700
1701void CCodec::setDeadline(
1702 const TimePoint &now,
1703 const std::chrono::milliseconds &timeout,
1704 const char *name) {
1705 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1706 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1707 deadline->set(now + (timeout * mult), name);
1708}
1709
1710void CCodec::initiateReleaseIfStuck() {
1711 std::string name;
1712 bool pendingDeadline = false;
1713 for (Mutexed<NamedTimePoint> *deadlinePtr : { &mDeadline, &mQueueDeadline, &mEosDeadline }) {
1714 Mutexed<NamedTimePoint>::Locked deadline(*deadlinePtr);
1715 if (deadline->get() < std::chrono::steady_clock::now()) {
1716 name = deadline->getName();
1717 break;
1718 }
1719 if (deadline->get() != TimePoint::max()) {
1720 pendingDeadline = true;
1721 }
1722 }
1723 if (name.empty()) {
1724 // We're not stuck.
1725 if (pendingDeadline) {
1726 // If we are not stuck yet but still has deadline coming up,
1727 // post watch message to check back later.
1728 (new AMessage(kWhatWatch, this))->post();
1729 }
1730 return;
1731 }
1732
1733 ALOGW("previous call to %s exceeded timeout", name.c_str());
1734 initiateRelease(false);
1735 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1736}
1737
1738void CCodec::onWorkQueued(bool eos) {
1739 ALOGV("queued work count +1 from %d", mQueuedWorkCount.load());
1740 int32_t count = ++mQueuedWorkCount;
1741 if (eos) {
1742 CCodecWatchdog::getInstance()->watch(this);
1743 Mutexed<NamedTimePoint>::Locked deadline(mEosDeadline);
1744 deadline->set(std::chrono::steady_clock::now() + 3s, "eos");
1745 }
1746 // TODO: query and use input/pipeline/output delay combined
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001747 if (count >= 4) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001748 CCodecWatchdog::getInstance()->watch(this);
1749 Mutexed<NamedTimePoint>::Locked deadline(mQueueDeadline);
1750 deadline->set(std::chrono::steady_clock::now() + 3s, "queue");
1751 }
1752}
1753
1754void CCodec::subQueuedWorkCount(uint32_t count) {
1755 ALOGV("queued work count -%u from %d", count, mQueuedWorkCount.load());
1756 int32_t currentCount = (mQueuedWorkCount -= count);
1757 if (currentCount == 0) {
1758 Mutexed<NamedTimePoint>::Locked deadline(mEosDeadline);
1759 deadline->set(TimePoint::max(), "none");
1760 }
1761 Mutexed<NamedTimePoint>::Locked deadline(mQueueDeadline);
1762 deadline->set(TimePoint::max(), "none");
1763}
1764
1765} // namespace android
1766
1767extern "C" android::CodecBase *CreateCodec() {
1768 return new android::CCodec;
1769}
1770
Lajos Molnar47118272019-01-31 16:28:04 -08001771// Create Codec 2.0 input surface
Pawin Vongmasa36653902018-11-15 00:10:25 -08001772extern "C" android::PersistentSurface *CreateInputSurface() {
1773 // Attempt to create a Codec2's input surface.
1774 std::shared_ptr<android::Codec2Client::InputSurface> inputSurface =
1775 android::Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001776 if (!inputSurface) {
1777 return nullptr;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001778 }
Lajos Molnar47118272019-01-31 16:28:04 -08001779 return new android::PersistentSurface(
1780 inputSurface->getGraphicBufferProducer(),
1781 static_cast<android::sp<android::hidl::base::V1_0::IBase>>(
1782 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001783}
1784