blob: 10263dedfb72ab1e956af938592089ba51b95874 [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
946void CCodec::createInputSurface() {
947 status_t err;
948 sp<IGraphicBufferProducer> bufferProducer;
949
950 sp<AMessage> inputFormat;
951 sp<AMessage> outputFormat;
952 {
953 Mutexed<Config>::Locked config(mConfig);
954 inputFormat = config->mInputFormat;
955 outputFormat = config->mOutputFormat;
956 }
957
958 std::shared_ptr<PersistentSurface> persistentSurface(CreateInputSurface());
959
960 if (persistentSurface->getHidlTarget()) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800961 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800962 persistentSurface->getHidlTarget());
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800963 if (!hidlInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800964 ALOGE("Corrupted input surface");
965 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
966 return;
967 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800968 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
969 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800970 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800971 inputSurface));
972 bufferProducer = inputSurface->getGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800973 } else {
974 int32_t width = 0;
975 (void)outputFormat->findInt32("width", &width);
976 int32_t height = 0;
977 (void)outputFormat->findInt32("height", &height);
978 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
979 persistentSurface->getBufferSource(), width, height));
980 bufferProducer = persistentSurface->getBufferProducer();
981 }
982
983 if (err != OK) {
984 ALOGE("Failed to set up input surface: %d", err);
985 mCallback->onInputSurfaceCreationFailed(err);
986 return;
987 }
988
989 mCallback->onInputSurfaceCreated(
990 inputFormat,
991 outputFormat,
992 new BufferProducerWrapper(bufferProducer));
993}
994
995status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
996 Mutexed<Config>::Locked config(mConfig);
997 config->mUsingSurface = true;
998
999 // we are now using surface - apply default color aspects to input format - as well as
1000 // get dataspace
1001 bool inputFormatChanged = config->updateFormats(config->IS_INPUT);
1002 ALOGD("input format %s to %s",
1003 inputFormatChanged ? "changed" : "unchanged",
1004 config->mInputFormat->debugString().c_str());
1005
1006 // configure dataspace
1007 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1008 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1009 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1010 surface->setDataSpace(dataSpace);
1011
1012 status_t err = mChannel->setInputSurface(surface);
1013 if (err != OK) {
1014 // undo input format update
1015 config->mUsingSurface = false;
1016 (void)config->updateFormats(config->IS_INPUT);
1017 return err;
1018 }
1019 config->mInputSurface = surface;
1020
1021 if (config->mISConfig) {
1022 surface->configure(*config->mISConfig);
1023 } else {
1024 ALOGD("ISConfig: no configuration");
1025 }
1026
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001027 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001028}
1029
1030void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1031 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1032 msg->setObject("surface", surface);
1033 msg->post();
1034}
1035
1036void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1037 sp<AMessage> inputFormat;
1038 sp<AMessage> outputFormat;
1039 {
1040 Mutexed<Config>::Locked config(mConfig);
1041 inputFormat = config->mInputFormat;
1042 outputFormat = config->mOutputFormat;
1043 }
1044 auto hidlTarget = surface->getHidlTarget();
1045 if (hidlTarget) {
1046 sp<IInputSurface> inputSurface =
1047 IInputSurface::castFrom(hidlTarget);
1048 if (!inputSurface) {
1049 ALOGE("Failed to set input surface: Corrupted surface.");
1050 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1051 return;
1052 }
1053 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1054 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1055 if (err != OK) {
1056 ALOGE("Failed to set up input surface: %d", err);
1057 mCallback->onInputSurfaceDeclined(err);
1058 return;
1059 }
1060 } else {
1061 int32_t width = 0;
1062 (void)outputFormat->findInt32("width", &width);
1063 int32_t height = 0;
1064 (void)outputFormat->findInt32("height", &height);
1065 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1066 surface->getBufferSource(), width, height));
1067 if (err != OK) {
1068 ALOGE("Failed to set up input surface: %d", err);
1069 mCallback->onInputSurfaceDeclined(err);
1070 return;
1071 }
1072 }
1073 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1074}
1075
1076void CCodec::initiateStart() {
1077 auto setStarting = [this] {
1078 Mutexed<State>::Locked state(mState);
1079 if (state->get() != ALLOCATED) {
1080 return UNKNOWN_ERROR;
1081 }
1082 state->set(STARTING);
1083 return OK;
1084 };
1085 if (tryAndReportOnError(setStarting) != OK) {
1086 return;
1087 }
1088
1089 (new AMessage(kWhatStart, this))->post();
1090}
1091
1092void CCodec::start() {
1093 std::shared_ptr<Codec2Client::Component> comp;
1094 auto checkStarting = [this, &comp] {
1095 Mutexed<State>::Locked state(mState);
1096 if (state->get() != STARTING) {
1097 return UNKNOWN_ERROR;
1098 }
1099 comp = state->comp;
1100 return OK;
1101 };
1102 if (tryAndReportOnError(checkStarting) != OK) {
1103 return;
1104 }
1105
1106 c2_status_t err = comp->start();
1107 if (err != C2_OK) {
1108 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1109 ACTION_CODE_FATAL);
1110 return;
1111 }
1112 sp<AMessage> inputFormat;
1113 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001114 status_t err2 = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001115 {
1116 Mutexed<Config>::Locked config(mConfig);
1117 inputFormat = config->mInputFormat;
1118 outputFormat = config->mOutputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001119 if (config->mInputSurface) {
1120 err2 = config->mInputSurface->start();
1121 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001122 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001123 if (err2 != OK) {
1124 mCallback->onError(err2, ACTION_CODE_FATAL);
1125 return;
1126 }
1127 err2 = mChannel->start(inputFormat, outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001128 if (err2 != OK) {
1129 mCallback->onError(err2, ACTION_CODE_FATAL);
1130 return;
1131 }
1132
1133 auto setRunning = [this] {
1134 Mutexed<State>::Locked state(mState);
1135 if (state->get() != STARTING) {
1136 return UNKNOWN_ERROR;
1137 }
1138 state->set(RUNNING);
1139 return OK;
1140 };
1141 if (tryAndReportOnError(setRunning) != OK) {
1142 return;
1143 }
1144 mCallback->onStartCompleted();
1145
1146 (void)mChannel->requestInitialInputBuffers();
1147}
1148
1149void CCodec::initiateShutdown(bool keepComponentAllocated) {
1150 if (keepComponentAllocated) {
1151 initiateStop();
1152 } else {
1153 initiateRelease();
1154 }
1155}
1156
1157void CCodec::initiateStop() {
1158 {
1159 Mutexed<State>::Locked state(mState);
1160 if (state->get() == ALLOCATED
1161 || state->get() == RELEASED
1162 || state->get() == STOPPING
1163 || state->get() == RELEASING) {
1164 // We're already stopped, released, or doing it right now.
1165 state.unlock();
1166 mCallback->onStopCompleted();
1167 state.lock();
1168 return;
1169 }
1170 state->set(STOPPING);
1171 }
1172
1173 mChannel->stop();
1174 (new AMessage(kWhatStop, this))->post();
1175}
1176
1177void CCodec::stop() {
1178 std::shared_ptr<Codec2Client::Component> comp;
1179 {
1180 Mutexed<State>::Locked state(mState);
1181 if (state->get() == RELEASING) {
1182 state.unlock();
1183 // We're already stopped or release is in progress.
1184 mCallback->onStopCompleted();
1185 state.lock();
1186 return;
1187 } else if (state->get() != STOPPING) {
1188 state.unlock();
1189 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1190 state.lock();
1191 return;
1192 }
1193 comp = state->comp;
1194 }
1195 status_t err = comp->stop();
1196 if (err != C2_OK) {
1197 // TODO: convert err into status_t
1198 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1199 }
1200
1201 {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001202 Mutexed<Config>::Locked config(mConfig);
1203 if (config->mInputSurface) {
1204 config->mInputSurface->disconnect();
1205 config->mInputSurface = nullptr;
1206 }
1207 }
1208 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001209 Mutexed<State>::Locked state(mState);
1210 if (state->get() == STOPPING) {
1211 state->set(ALLOCATED);
1212 }
1213 }
1214 mCallback->onStopCompleted();
1215}
1216
1217void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001218 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001219 {
1220 Mutexed<State>::Locked state(mState);
1221 if (state->get() == RELEASED || state->get() == RELEASING) {
1222 // We're already released or doing it right now.
1223 if (sendCallback) {
1224 state.unlock();
1225 mCallback->onReleaseCompleted();
1226 state.lock();
1227 }
1228 return;
1229 }
1230 if (state->get() == ALLOCATING) {
1231 state->set(RELEASING);
1232 // With the altered state allocate() would fail and clean up.
1233 if (sendCallback) {
1234 state.unlock();
1235 mCallback->onReleaseCompleted();
1236 state.lock();
1237 }
1238 return;
1239 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001240 if (state->get() == STARTING
1241 || state->get() == RUNNING
1242 || state->get() == STOPPING) {
1243 // Input surface may have been started, so clean up is needed.
1244 clearInputSurfaceIfNeeded = true;
1245 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001246 state->set(RELEASING);
1247 }
1248
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001249 if (clearInputSurfaceIfNeeded) {
1250 Mutexed<Config>::Locked config(mConfig);
1251 if (config->mInputSurface) {
1252 config->mInputSurface->disconnect();
1253 config->mInputSurface = nullptr;
1254 }
1255 }
1256
Pawin Vongmasa36653902018-11-15 00:10:25 -08001257 mChannel->stop();
1258 // thiz holds strong ref to this while the thread is running.
1259 sp<CCodec> thiz(this);
1260 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1261}
1262
1263void CCodec::release(bool sendCallback) {
1264 std::shared_ptr<Codec2Client::Component> comp;
1265 {
1266 Mutexed<State>::Locked state(mState);
1267 if (state->get() == RELEASED) {
1268 if (sendCallback) {
1269 state.unlock();
1270 mCallback->onReleaseCompleted();
1271 state.lock();
1272 }
1273 return;
1274 }
1275 comp = state->comp;
1276 }
1277 comp->release();
1278
1279 {
1280 Mutexed<State>::Locked state(mState);
1281 state->set(RELEASED);
1282 state->comp.reset();
1283 }
1284 if (sendCallback) {
1285 mCallback->onReleaseCompleted();
1286 }
1287}
1288
1289status_t CCodec::setSurface(const sp<Surface> &surface) {
1290 return mChannel->setSurface(surface);
1291}
1292
1293void CCodec::signalFlush() {
1294 status_t err = [this] {
1295 Mutexed<State>::Locked state(mState);
1296 if (state->get() == FLUSHED) {
1297 return ALREADY_EXISTS;
1298 }
1299 if (state->get() != RUNNING) {
1300 return UNKNOWN_ERROR;
1301 }
1302 state->set(FLUSHING);
1303 return OK;
1304 }();
1305 switch (err) {
1306 case ALREADY_EXISTS:
1307 mCallback->onFlushCompleted();
1308 return;
1309 case OK:
1310 break;
1311 default:
1312 mCallback->onError(err, ACTION_CODE_FATAL);
1313 return;
1314 }
1315
1316 mChannel->stop();
1317 (new AMessage(kWhatFlush, this))->post();
1318}
1319
1320void CCodec::flush() {
1321 std::shared_ptr<Codec2Client::Component> comp;
1322 auto checkFlushing = [this, &comp] {
1323 Mutexed<State>::Locked state(mState);
1324 if (state->get() != FLUSHING) {
1325 return UNKNOWN_ERROR;
1326 }
1327 comp = state->comp;
1328 return OK;
1329 };
1330 if (tryAndReportOnError(checkFlushing) != OK) {
1331 return;
1332 }
1333
1334 std::list<std::unique_ptr<C2Work>> flushedWork;
1335 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1336 {
1337 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1338 flushedWork.splice(flushedWork.end(), *queue);
1339 }
1340 if (err != C2_OK) {
1341 // TODO: convert err into status_t
1342 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1343 }
1344
1345 mChannel->flush(flushedWork);
1346 subQueuedWorkCount(flushedWork.size());
1347
1348 {
1349 Mutexed<State>::Locked state(mState);
1350 state->set(FLUSHED);
1351 }
1352 mCallback->onFlushCompleted();
1353}
1354
1355void CCodec::signalResume() {
1356 auto setResuming = [this] {
1357 Mutexed<State>::Locked state(mState);
1358 if (state->get() != FLUSHED) {
1359 return UNKNOWN_ERROR;
1360 }
1361 state->set(RESUMING);
1362 return OK;
1363 };
1364 if (tryAndReportOnError(setResuming) != OK) {
1365 return;
1366 }
1367
1368 (void)mChannel->start(nullptr, nullptr);
1369
1370 {
1371 Mutexed<State>::Locked state(mState);
1372 if (state->get() != RESUMING) {
1373 state.unlock();
1374 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1375 state.lock();
1376 return;
1377 }
1378 state->set(RUNNING);
1379 }
1380
1381 (void)mChannel->requestInitialInputBuffers();
1382}
1383
1384void CCodec::signalSetParameters(const sp<AMessage> &params) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001385 setParameters(params);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001386}
1387
1388void CCodec::setParameters(const sp<AMessage> &params) {
1389 std::shared_ptr<Codec2Client::Component> comp;
1390 auto checkState = [this, &comp] {
1391 Mutexed<State>::Locked state(mState);
1392 if (state->get() == RELEASED) {
1393 return INVALID_OPERATION;
1394 }
1395 comp = state->comp;
1396 return OK;
1397 };
1398 if (tryAndReportOnError(checkState) != OK) {
1399 return;
1400 }
1401
1402 Mutexed<Config>::Locked config(mConfig);
1403
1404 /**
1405 * Handle input surface parameters
1406 */
1407 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1408 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
1409 (void)params->findInt64("time-offset-us", &config->mISConfig->mTimeOffsetUs);
1410
1411 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1412 config->mISConfig->mStopped = false;
1413 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1414 config->mISConfig->mStopped = true;
1415 }
1416
1417 int32_t value;
1418 if (params->findInt32("drop-input-frames", &value)) {
1419 config->mISConfig->mSuspended = value;
1420 config->mISConfig->mSuspendAtUs = -1;
1421 (void)params->findInt64("drop-start-time-us", &config->mISConfig->mSuspendAtUs);
1422 }
1423
1424 (void)config->mInputSurface->configure(*config->mISConfig);
1425 if (config->mISConfig->mStopped) {
1426 config->mInputFormat->setInt64(
1427 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1428 }
1429 }
1430
1431 std::vector<std::unique_ptr<C2Param>> configUpdate;
1432 (void)config->getConfigUpdateFromSdkParams(
1433 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1434 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1435 // Parameter synchronization is not defined when using input surface. For now, route
1436 // these directly to the component.
1437 if (config->mInputSurface == nullptr
1438 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1439 || comp->getName().find("c2.android.") == 0)) {
1440 mChannel->setParameters(configUpdate);
1441 } else {
1442 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1443 }
1444}
1445
1446void CCodec::signalEndOfInputStream() {
1447 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1448}
1449
1450void CCodec::signalRequestIDRFrame() {
1451 std::shared_ptr<Codec2Client::Component> comp;
1452 {
1453 Mutexed<State>::Locked state(mState);
1454 if (state->get() == RELEASED) {
1455 ALOGD("no IDR request sent since component is released");
1456 return;
1457 }
1458 comp = state->comp;
1459 }
1460 ALOGV("request IDR");
1461 Mutexed<Config>::Locked config(mConfig);
1462 std::vector<std::unique_ptr<C2Param>> params;
1463 params.push_back(
1464 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1465 config->setParameters(comp, params, C2_MAY_BLOCK);
1466}
1467
1468void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems,
1469 size_t numDiscardedInputBuffers) {
1470 if (!workItems.empty()) {
1471 {
1472 Mutexed<std::list<size_t>>::Locked numDiscardedInputBuffersQueue(
1473 mNumDiscardedInputBuffersQueue);
1474 numDiscardedInputBuffersQueue->insert(
1475 numDiscardedInputBuffersQueue->end(),
1476 workItems.size() - 1, 0);
1477 numDiscardedInputBuffersQueue->emplace_back(
1478 numDiscardedInputBuffers);
1479 }
1480 {
1481 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1482 queue->splice(queue->end(), workItems);
1483 }
1484 }
1485 (new AMessage(kWhatWorkDone, this))->post();
1486}
1487
1488void CCodec::onInputBufferDone(const std::shared_ptr<C2Buffer>& buffer) {
1489 mChannel->onInputBufferDone(buffer);
1490}
1491
1492void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1493 TimePoint now = std::chrono::steady_clock::now();
1494 CCodecWatchdog::getInstance()->watch(this);
1495 switch (msg->what()) {
1496 case kWhatAllocate: {
1497 // C2ComponentStore::createComponent() should return within 100ms.
1498 setDeadline(now, 150ms, "allocate");
1499 sp<RefBase> obj;
1500 CHECK(msg->findObject("codecInfo", &obj));
1501 allocate((MediaCodecInfo *)obj.get());
1502 break;
1503 }
1504 case kWhatConfigure: {
1505 // C2Component::commit_sm() should return within 5ms.
1506 setDeadline(now, 250ms, "configure");
1507 sp<AMessage> format;
1508 CHECK(msg->findMessage("format", &format));
1509 configure(format);
1510 break;
1511 }
1512 case kWhatStart: {
1513 // C2Component::start() should return within 500ms.
1514 setDeadline(now, 550ms, "start");
1515 mQueuedWorkCount = 0;
1516 start();
1517 break;
1518 }
1519 case kWhatStop: {
1520 // C2Component::stop() should return within 500ms.
1521 setDeadline(now, 550ms, "stop");
1522 stop();
1523
1524 mQueuedWorkCount = 0;
1525 Mutexed<NamedTimePoint>::Locked deadline(mQueueDeadline);
1526 deadline->set(TimePoint::max(), "none");
1527 break;
1528 }
1529 case kWhatFlush: {
1530 // C2Component::flush_sm() should return within 5ms.
1531 setDeadline(now, 50ms, "flush");
1532 flush();
1533 break;
1534 }
1535 case kWhatCreateInputSurface: {
1536 // Surface operations may be briefly blocking.
1537 setDeadline(now, 100ms, "createInputSurface");
1538 createInputSurface();
1539 break;
1540 }
1541 case kWhatSetInputSurface: {
1542 // Surface operations may be briefly blocking.
1543 setDeadline(now, 100ms, "setInputSurface");
1544 sp<RefBase> obj;
1545 CHECK(msg->findObject("surface", &obj));
1546 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1547 setInputSurface(surface);
1548 break;
1549 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001550 case kWhatWorkDone: {
1551 std::unique_ptr<C2Work> work;
1552 size_t numDiscardedInputBuffers;
1553 bool shouldPost = false;
1554 {
1555 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1556 if (queue->empty()) {
1557 break;
1558 }
1559 work.swap(queue->front());
1560 queue->pop_front();
1561 shouldPost = !queue->empty();
1562 }
1563 {
1564 Mutexed<std::list<size_t>>::Locked numDiscardedInputBuffersQueue(
1565 mNumDiscardedInputBuffersQueue);
1566 if (numDiscardedInputBuffersQueue->empty()) {
1567 numDiscardedInputBuffers = 0;
1568 } else {
1569 numDiscardedInputBuffers = numDiscardedInputBuffersQueue->front();
1570 numDiscardedInputBuffersQueue->pop_front();
1571 }
1572 }
1573 if (shouldPost) {
1574 (new AMessage(kWhatWorkDone, this))->post();
1575 }
1576
1577 if (work->worklets.empty()
1578 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE)) {
1579 subQueuedWorkCount(1);
1580 }
1581 // handle configuration changes in work done
1582 Mutexed<Config>::Locked config(mConfig);
1583 bool changed = false;
1584 Config::Watcher<C2StreamInitDataInfo::output> initData =
1585 config->watch<C2StreamInitDataInfo::output>();
1586 if (!work->worklets.empty()
1587 && (work->worklets.front()->output.flags
1588 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1589
1590 // copy buffer info to config
1591 std::vector<std::unique_ptr<C2Param>> updates =
1592 std::move(work->worklets.front()->output.configUpdate);
1593 unsigned stream = 0;
1594 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1595 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1596 // move all info into output-stream #0 domain
1597 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1598 }
1599 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1600 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1601 // block.crop().left, block.crop().top,
1602 // block.crop().width, block.crop().height,
1603 // block.width(), block.height());
1604 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1605 updates.emplace_back(new C2StreamPictureSizeInfo::output(
1606 stream, block.width(), block.height()));
1607 break; // for now only do the first block
1608 }
1609 ++stream;
1610 }
1611
1612 changed = config->updateConfiguration(updates, config->mOutputDomain);
1613
1614 // copy standard infos to graphic buffers if not already present (otherwise, we
1615 // may overwrite the actual intermediate value with a final value)
1616 stream = 0;
1617 const static std::vector<C2Param::Index> stdGfxInfos = {
1618 C2StreamRotationInfo::output::PARAM_TYPE,
1619 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1620 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1621 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001622 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001623 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1624 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1625 };
1626 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1627 if (buf->data().graphicBlocks().size()) {
1628 for (C2Param::Index ix : stdGfxInfos) {
1629 if (!buf->hasInfo(ix)) {
1630 const C2Param *param =
1631 config->getConfigParameterValue(ix.withStream(stream));
1632 if (param) {
1633 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1634 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1635 }
1636 }
1637 }
1638 }
1639 ++stream;
1640 }
1641 }
1642 mChannel->onWorkDone(
1643 std::move(work), changed ? config->mOutputFormat : nullptr,
1644 initData.hasChanged() ? initData.update().get() : nullptr,
1645 numDiscardedInputBuffers);
1646 break;
1647 }
1648 case kWhatWatch: {
1649 // watch message already posted; no-op.
1650 break;
1651 }
1652 default: {
1653 ALOGE("unrecognized message");
1654 break;
1655 }
1656 }
1657 setDeadline(TimePoint::max(), 0ms, "none");
1658}
1659
1660void CCodec::setDeadline(
1661 const TimePoint &now,
1662 const std::chrono::milliseconds &timeout,
1663 const char *name) {
1664 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1665 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1666 deadline->set(now + (timeout * mult), name);
1667}
1668
1669void CCodec::initiateReleaseIfStuck() {
1670 std::string name;
1671 bool pendingDeadline = false;
1672 for (Mutexed<NamedTimePoint> *deadlinePtr : { &mDeadline, &mQueueDeadline, &mEosDeadline }) {
1673 Mutexed<NamedTimePoint>::Locked deadline(*deadlinePtr);
1674 if (deadline->get() < std::chrono::steady_clock::now()) {
1675 name = deadline->getName();
1676 break;
1677 }
1678 if (deadline->get() != TimePoint::max()) {
1679 pendingDeadline = true;
1680 }
1681 }
1682 if (name.empty()) {
1683 // We're not stuck.
1684 if (pendingDeadline) {
1685 // If we are not stuck yet but still has deadline coming up,
1686 // post watch message to check back later.
1687 (new AMessage(kWhatWatch, this))->post();
1688 }
1689 return;
1690 }
1691
1692 ALOGW("previous call to %s exceeded timeout", name.c_str());
1693 initiateRelease(false);
1694 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1695}
1696
1697void CCodec::onWorkQueued(bool eos) {
1698 ALOGV("queued work count +1 from %d", mQueuedWorkCount.load());
1699 int32_t count = ++mQueuedWorkCount;
1700 if (eos) {
1701 CCodecWatchdog::getInstance()->watch(this);
1702 Mutexed<NamedTimePoint>::Locked deadline(mEosDeadline);
1703 deadline->set(std::chrono::steady_clock::now() + 3s, "eos");
1704 }
1705 // TODO: query and use input/pipeline/output delay combined
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001706 if (count >= 4) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001707 CCodecWatchdog::getInstance()->watch(this);
1708 Mutexed<NamedTimePoint>::Locked deadline(mQueueDeadline);
1709 deadline->set(std::chrono::steady_clock::now() + 3s, "queue");
1710 }
1711}
1712
1713void CCodec::subQueuedWorkCount(uint32_t count) {
1714 ALOGV("queued work count -%u from %d", count, mQueuedWorkCount.load());
1715 int32_t currentCount = (mQueuedWorkCount -= count);
1716 if (currentCount == 0) {
1717 Mutexed<NamedTimePoint>::Locked deadline(mEosDeadline);
1718 deadline->set(TimePoint::max(), "none");
1719 }
1720 Mutexed<NamedTimePoint>::Locked deadline(mQueueDeadline);
1721 deadline->set(TimePoint::max(), "none");
1722}
1723
1724} // namespace android
1725
1726extern "C" android::CodecBase *CreateCodec() {
1727 return new android::CCodec;
1728}
1729
1730extern "C" android::PersistentSurface *CreateInputSurface() {
1731 // Attempt to create a Codec2's input surface.
1732 std::shared_ptr<android::Codec2Client::InputSurface> inputSurface =
1733 android::Codec2Client::CreateInputSurface();
1734 if (inputSurface) {
1735 return new android::PersistentSurface(
1736 inputSurface->getGraphicBufferProducer(),
1737 static_cast<android::sp<android::hidl::base::V1_0::IBase>>(
1738 inputSurface->getHalInterface()));
1739 }
1740
1741 // Fall back to OMX.
1742 using namespace android::hardware::media::omx::V1_0;
1743 using namespace android::hardware::media::omx::V1_0::utils;
1744 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1745 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1746 android::sp<IOmx> omx = IOmx::getService();
1747 typedef android::hardware::graphics::bufferqueue::V1_0::
1748 IGraphicBufferProducer HGraphicBufferProducer;
1749 typedef android::hardware::media::omx::V1_0::
1750 IGraphicBufferSource HGraphicBufferSource;
1751 OmxStatus s;
1752 android::sp<HGraphicBufferProducer> gbp;
1753 android::sp<HGraphicBufferSource> gbs;
1754 android::Return<void> transStatus = omx->createInputSurface(
1755 [&s, &gbp, &gbs](
1756 OmxStatus status,
1757 const android::sp<HGraphicBufferProducer>& producer,
1758 const android::sp<HGraphicBufferSource>& source) {
1759 s = status;
1760 gbp = producer;
1761 gbs = source;
1762 });
1763 if (transStatus.isOk() && s == OmxStatus::OK) {
1764 return new android::PersistentSurface(
1765 new H2BGraphicBufferProducer(gbp),
1766 sp<::android::IGraphicBufferSource>(
1767 new LWGraphicBufferSource(gbs)));
1768 }
1769
1770 return nullptr;
1771}
1772