blob: 2527b00771bd37206faaf8d71e482acad7d9ce12 [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
1027 return surface->start();
1028}
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;
1114 {
1115 Mutexed<Config>::Locked config(mConfig);
1116 inputFormat = config->mInputFormat;
1117 outputFormat = config->mOutputFormat;
1118 }
1119 status_t err2 = mChannel->start(inputFormat, outputFormat);
1120 if (err2 != OK) {
1121 mCallback->onError(err2, ACTION_CODE_FATAL);
1122 return;
1123 }
1124
1125 auto setRunning = [this] {
1126 Mutexed<State>::Locked state(mState);
1127 if (state->get() != STARTING) {
1128 return UNKNOWN_ERROR;
1129 }
1130 state->set(RUNNING);
1131 return OK;
1132 };
1133 if (tryAndReportOnError(setRunning) != OK) {
1134 return;
1135 }
1136 mCallback->onStartCompleted();
1137
1138 (void)mChannel->requestInitialInputBuffers();
1139}
1140
1141void CCodec::initiateShutdown(bool keepComponentAllocated) {
1142 if (keepComponentAllocated) {
1143 initiateStop();
1144 } else {
1145 initiateRelease();
1146 }
1147}
1148
1149void CCodec::initiateStop() {
1150 {
1151 Mutexed<State>::Locked state(mState);
1152 if (state->get() == ALLOCATED
1153 || state->get() == RELEASED
1154 || state->get() == STOPPING
1155 || state->get() == RELEASING) {
1156 // We're already stopped, released, or doing it right now.
1157 state.unlock();
1158 mCallback->onStopCompleted();
1159 state.lock();
1160 return;
1161 }
1162 state->set(STOPPING);
1163 }
1164
1165 mChannel->stop();
1166 (new AMessage(kWhatStop, this))->post();
1167}
1168
1169void CCodec::stop() {
1170 std::shared_ptr<Codec2Client::Component> comp;
1171 {
1172 Mutexed<State>::Locked state(mState);
1173 if (state->get() == RELEASING) {
1174 state.unlock();
1175 // We're already stopped or release is in progress.
1176 mCallback->onStopCompleted();
1177 state.lock();
1178 return;
1179 } else if (state->get() != STOPPING) {
1180 state.unlock();
1181 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1182 state.lock();
1183 return;
1184 }
1185 comp = state->comp;
1186 }
1187 status_t err = comp->stop();
1188 if (err != C2_OK) {
1189 // TODO: convert err into status_t
1190 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1191 }
1192
1193 {
1194 Mutexed<State>::Locked state(mState);
1195 if (state->get() == STOPPING) {
1196 state->set(ALLOCATED);
1197 }
1198 }
1199 mCallback->onStopCompleted();
1200}
1201
1202void CCodec::initiateRelease(bool sendCallback /* = true */) {
1203 {
1204 Mutexed<State>::Locked state(mState);
1205 if (state->get() == RELEASED || state->get() == RELEASING) {
1206 // We're already released or doing it right now.
1207 if (sendCallback) {
1208 state.unlock();
1209 mCallback->onReleaseCompleted();
1210 state.lock();
1211 }
1212 return;
1213 }
1214 if (state->get() == ALLOCATING) {
1215 state->set(RELEASING);
1216 // With the altered state allocate() would fail and clean up.
1217 if (sendCallback) {
1218 state.unlock();
1219 mCallback->onReleaseCompleted();
1220 state.lock();
1221 }
1222 return;
1223 }
1224 state->set(RELEASING);
1225 }
1226
1227 mChannel->stop();
1228 // thiz holds strong ref to this while the thread is running.
1229 sp<CCodec> thiz(this);
1230 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1231}
1232
1233void CCodec::release(bool sendCallback) {
1234 std::shared_ptr<Codec2Client::Component> comp;
1235 {
1236 Mutexed<State>::Locked state(mState);
1237 if (state->get() == RELEASED) {
1238 if (sendCallback) {
1239 state.unlock();
1240 mCallback->onReleaseCompleted();
1241 state.lock();
1242 }
1243 return;
1244 }
1245 comp = state->comp;
1246 }
1247 comp->release();
1248
1249 {
1250 Mutexed<State>::Locked state(mState);
1251 state->set(RELEASED);
1252 state->comp.reset();
1253 }
1254 if (sendCallback) {
1255 mCallback->onReleaseCompleted();
1256 }
1257}
1258
1259status_t CCodec::setSurface(const sp<Surface> &surface) {
1260 return mChannel->setSurface(surface);
1261}
1262
1263void CCodec::signalFlush() {
1264 status_t err = [this] {
1265 Mutexed<State>::Locked state(mState);
1266 if (state->get() == FLUSHED) {
1267 return ALREADY_EXISTS;
1268 }
1269 if (state->get() != RUNNING) {
1270 return UNKNOWN_ERROR;
1271 }
1272 state->set(FLUSHING);
1273 return OK;
1274 }();
1275 switch (err) {
1276 case ALREADY_EXISTS:
1277 mCallback->onFlushCompleted();
1278 return;
1279 case OK:
1280 break;
1281 default:
1282 mCallback->onError(err, ACTION_CODE_FATAL);
1283 return;
1284 }
1285
1286 mChannel->stop();
1287 (new AMessage(kWhatFlush, this))->post();
1288}
1289
1290void CCodec::flush() {
1291 std::shared_ptr<Codec2Client::Component> comp;
1292 auto checkFlushing = [this, &comp] {
1293 Mutexed<State>::Locked state(mState);
1294 if (state->get() != FLUSHING) {
1295 return UNKNOWN_ERROR;
1296 }
1297 comp = state->comp;
1298 return OK;
1299 };
1300 if (tryAndReportOnError(checkFlushing) != OK) {
1301 return;
1302 }
1303
1304 std::list<std::unique_ptr<C2Work>> flushedWork;
1305 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1306 {
1307 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1308 flushedWork.splice(flushedWork.end(), *queue);
1309 }
1310 if (err != C2_OK) {
1311 // TODO: convert err into status_t
1312 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1313 }
1314
1315 mChannel->flush(flushedWork);
1316 subQueuedWorkCount(flushedWork.size());
1317
1318 {
1319 Mutexed<State>::Locked state(mState);
1320 state->set(FLUSHED);
1321 }
1322 mCallback->onFlushCompleted();
1323}
1324
1325void CCodec::signalResume() {
1326 auto setResuming = [this] {
1327 Mutexed<State>::Locked state(mState);
1328 if (state->get() != FLUSHED) {
1329 return UNKNOWN_ERROR;
1330 }
1331 state->set(RESUMING);
1332 return OK;
1333 };
1334 if (tryAndReportOnError(setResuming) != OK) {
1335 return;
1336 }
1337
1338 (void)mChannel->start(nullptr, nullptr);
1339
1340 {
1341 Mutexed<State>::Locked state(mState);
1342 if (state->get() != RESUMING) {
1343 state.unlock();
1344 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1345 state.lock();
1346 return;
1347 }
1348 state->set(RUNNING);
1349 }
1350
1351 (void)mChannel->requestInitialInputBuffers();
1352}
1353
1354void CCodec::signalSetParameters(const sp<AMessage> &params) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001355 setParameters(params);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001356}
1357
1358void CCodec::setParameters(const sp<AMessage> &params) {
1359 std::shared_ptr<Codec2Client::Component> comp;
1360 auto checkState = [this, &comp] {
1361 Mutexed<State>::Locked state(mState);
1362 if (state->get() == RELEASED) {
1363 return INVALID_OPERATION;
1364 }
1365 comp = state->comp;
1366 return OK;
1367 };
1368 if (tryAndReportOnError(checkState) != OK) {
1369 return;
1370 }
1371
1372 Mutexed<Config>::Locked config(mConfig);
1373
1374 /**
1375 * Handle input surface parameters
1376 */
1377 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1378 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
1379 (void)params->findInt64("time-offset-us", &config->mISConfig->mTimeOffsetUs);
1380
1381 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1382 config->mISConfig->mStopped = false;
1383 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1384 config->mISConfig->mStopped = true;
1385 }
1386
1387 int32_t value;
1388 if (params->findInt32("drop-input-frames", &value)) {
1389 config->mISConfig->mSuspended = value;
1390 config->mISConfig->mSuspendAtUs = -1;
1391 (void)params->findInt64("drop-start-time-us", &config->mISConfig->mSuspendAtUs);
1392 }
1393
1394 (void)config->mInputSurface->configure(*config->mISConfig);
1395 if (config->mISConfig->mStopped) {
1396 config->mInputFormat->setInt64(
1397 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1398 }
1399 }
1400
1401 std::vector<std::unique_ptr<C2Param>> configUpdate;
1402 (void)config->getConfigUpdateFromSdkParams(
1403 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1404 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1405 // Parameter synchronization is not defined when using input surface. For now, route
1406 // these directly to the component.
1407 if (config->mInputSurface == nullptr
1408 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1409 || comp->getName().find("c2.android.") == 0)) {
1410 mChannel->setParameters(configUpdate);
1411 } else {
1412 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1413 }
1414}
1415
1416void CCodec::signalEndOfInputStream() {
1417 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1418}
1419
1420void CCodec::signalRequestIDRFrame() {
1421 std::shared_ptr<Codec2Client::Component> comp;
1422 {
1423 Mutexed<State>::Locked state(mState);
1424 if (state->get() == RELEASED) {
1425 ALOGD("no IDR request sent since component is released");
1426 return;
1427 }
1428 comp = state->comp;
1429 }
1430 ALOGV("request IDR");
1431 Mutexed<Config>::Locked config(mConfig);
1432 std::vector<std::unique_ptr<C2Param>> params;
1433 params.push_back(
1434 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1435 config->setParameters(comp, params, C2_MAY_BLOCK);
1436}
1437
1438void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems,
1439 size_t numDiscardedInputBuffers) {
1440 if (!workItems.empty()) {
1441 {
1442 Mutexed<std::list<size_t>>::Locked numDiscardedInputBuffersQueue(
1443 mNumDiscardedInputBuffersQueue);
1444 numDiscardedInputBuffersQueue->insert(
1445 numDiscardedInputBuffersQueue->end(),
1446 workItems.size() - 1, 0);
1447 numDiscardedInputBuffersQueue->emplace_back(
1448 numDiscardedInputBuffers);
1449 }
1450 {
1451 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1452 queue->splice(queue->end(), workItems);
1453 }
1454 }
1455 (new AMessage(kWhatWorkDone, this))->post();
1456}
1457
1458void CCodec::onInputBufferDone(const std::shared_ptr<C2Buffer>& buffer) {
1459 mChannel->onInputBufferDone(buffer);
1460}
1461
1462void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1463 TimePoint now = std::chrono::steady_clock::now();
1464 CCodecWatchdog::getInstance()->watch(this);
1465 switch (msg->what()) {
1466 case kWhatAllocate: {
1467 // C2ComponentStore::createComponent() should return within 100ms.
1468 setDeadline(now, 150ms, "allocate");
1469 sp<RefBase> obj;
1470 CHECK(msg->findObject("codecInfo", &obj));
1471 allocate((MediaCodecInfo *)obj.get());
1472 break;
1473 }
1474 case kWhatConfigure: {
1475 // C2Component::commit_sm() should return within 5ms.
1476 setDeadline(now, 250ms, "configure");
1477 sp<AMessage> format;
1478 CHECK(msg->findMessage("format", &format));
1479 configure(format);
1480 break;
1481 }
1482 case kWhatStart: {
1483 // C2Component::start() should return within 500ms.
1484 setDeadline(now, 550ms, "start");
1485 mQueuedWorkCount = 0;
1486 start();
1487 break;
1488 }
1489 case kWhatStop: {
1490 // C2Component::stop() should return within 500ms.
1491 setDeadline(now, 550ms, "stop");
1492 stop();
1493
1494 mQueuedWorkCount = 0;
1495 Mutexed<NamedTimePoint>::Locked deadline(mQueueDeadline);
1496 deadline->set(TimePoint::max(), "none");
1497 break;
1498 }
1499 case kWhatFlush: {
1500 // C2Component::flush_sm() should return within 5ms.
1501 setDeadline(now, 50ms, "flush");
1502 flush();
1503 break;
1504 }
1505 case kWhatCreateInputSurface: {
1506 // Surface operations may be briefly blocking.
1507 setDeadline(now, 100ms, "createInputSurface");
1508 createInputSurface();
1509 break;
1510 }
1511 case kWhatSetInputSurface: {
1512 // Surface operations may be briefly blocking.
1513 setDeadline(now, 100ms, "setInputSurface");
1514 sp<RefBase> obj;
1515 CHECK(msg->findObject("surface", &obj));
1516 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1517 setInputSurface(surface);
1518 break;
1519 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001520 case kWhatWorkDone: {
1521 std::unique_ptr<C2Work> work;
1522 size_t numDiscardedInputBuffers;
1523 bool shouldPost = false;
1524 {
1525 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1526 if (queue->empty()) {
1527 break;
1528 }
1529 work.swap(queue->front());
1530 queue->pop_front();
1531 shouldPost = !queue->empty();
1532 }
1533 {
1534 Mutexed<std::list<size_t>>::Locked numDiscardedInputBuffersQueue(
1535 mNumDiscardedInputBuffersQueue);
1536 if (numDiscardedInputBuffersQueue->empty()) {
1537 numDiscardedInputBuffers = 0;
1538 } else {
1539 numDiscardedInputBuffers = numDiscardedInputBuffersQueue->front();
1540 numDiscardedInputBuffersQueue->pop_front();
1541 }
1542 }
1543 if (shouldPost) {
1544 (new AMessage(kWhatWorkDone, this))->post();
1545 }
1546
1547 if (work->worklets.empty()
1548 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE)) {
1549 subQueuedWorkCount(1);
1550 }
1551 // handle configuration changes in work done
1552 Mutexed<Config>::Locked config(mConfig);
1553 bool changed = false;
1554 Config::Watcher<C2StreamInitDataInfo::output> initData =
1555 config->watch<C2StreamInitDataInfo::output>();
1556 if (!work->worklets.empty()
1557 && (work->worklets.front()->output.flags
1558 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1559
1560 // copy buffer info to config
1561 std::vector<std::unique_ptr<C2Param>> updates =
1562 std::move(work->worklets.front()->output.configUpdate);
1563 unsigned stream = 0;
1564 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1565 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1566 // move all info into output-stream #0 domain
1567 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1568 }
1569 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1570 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1571 // block.crop().left, block.crop().top,
1572 // block.crop().width, block.crop().height,
1573 // block.width(), block.height());
1574 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1575 updates.emplace_back(new C2StreamPictureSizeInfo::output(
1576 stream, block.width(), block.height()));
1577 break; // for now only do the first block
1578 }
1579 ++stream;
1580 }
1581
1582 changed = config->updateConfiguration(updates, config->mOutputDomain);
1583
1584 // copy standard infos to graphic buffers if not already present (otherwise, we
1585 // may overwrite the actual intermediate value with a final value)
1586 stream = 0;
1587 const static std::vector<C2Param::Index> stdGfxInfos = {
1588 C2StreamRotationInfo::output::PARAM_TYPE,
1589 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1590 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1591 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001592 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001593 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1594 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1595 };
1596 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1597 if (buf->data().graphicBlocks().size()) {
1598 for (C2Param::Index ix : stdGfxInfos) {
1599 if (!buf->hasInfo(ix)) {
1600 const C2Param *param =
1601 config->getConfigParameterValue(ix.withStream(stream));
1602 if (param) {
1603 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1604 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1605 }
1606 }
1607 }
1608 }
1609 ++stream;
1610 }
1611 }
1612 mChannel->onWorkDone(
1613 std::move(work), changed ? config->mOutputFormat : nullptr,
1614 initData.hasChanged() ? initData.update().get() : nullptr,
1615 numDiscardedInputBuffers);
1616 break;
1617 }
1618 case kWhatWatch: {
1619 // watch message already posted; no-op.
1620 break;
1621 }
1622 default: {
1623 ALOGE("unrecognized message");
1624 break;
1625 }
1626 }
1627 setDeadline(TimePoint::max(), 0ms, "none");
1628}
1629
1630void CCodec::setDeadline(
1631 const TimePoint &now,
1632 const std::chrono::milliseconds &timeout,
1633 const char *name) {
1634 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1635 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1636 deadline->set(now + (timeout * mult), name);
1637}
1638
1639void CCodec::initiateReleaseIfStuck() {
1640 std::string name;
1641 bool pendingDeadline = false;
1642 for (Mutexed<NamedTimePoint> *deadlinePtr : { &mDeadline, &mQueueDeadline, &mEosDeadline }) {
1643 Mutexed<NamedTimePoint>::Locked deadline(*deadlinePtr);
1644 if (deadline->get() < std::chrono::steady_clock::now()) {
1645 name = deadline->getName();
1646 break;
1647 }
1648 if (deadline->get() != TimePoint::max()) {
1649 pendingDeadline = true;
1650 }
1651 }
1652 if (name.empty()) {
1653 // We're not stuck.
1654 if (pendingDeadline) {
1655 // If we are not stuck yet but still has deadline coming up,
1656 // post watch message to check back later.
1657 (new AMessage(kWhatWatch, this))->post();
1658 }
1659 return;
1660 }
1661
1662 ALOGW("previous call to %s exceeded timeout", name.c_str());
1663 initiateRelease(false);
1664 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1665}
1666
1667void CCodec::onWorkQueued(bool eos) {
1668 ALOGV("queued work count +1 from %d", mQueuedWorkCount.load());
1669 int32_t count = ++mQueuedWorkCount;
1670 if (eos) {
1671 CCodecWatchdog::getInstance()->watch(this);
1672 Mutexed<NamedTimePoint>::Locked deadline(mEosDeadline);
1673 deadline->set(std::chrono::steady_clock::now() + 3s, "eos");
1674 }
1675 // TODO: query and use input/pipeline/output delay combined
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001676 if (count >= 4) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001677 CCodecWatchdog::getInstance()->watch(this);
1678 Mutexed<NamedTimePoint>::Locked deadline(mQueueDeadline);
1679 deadline->set(std::chrono::steady_clock::now() + 3s, "queue");
1680 }
1681}
1682
1683void CCodec::subQueuedWorkCount(uint32_t count) {
1684 ALOGV("queued work count -%u from %d", count, mQueuedWorkCount.load());
1685 int32_t currentCount = (mQueuedWorkCount -= count);
1686 if (currentCount == 0) {
1687 Mutexed<NamedTimePoint>::Locked deadline(mEosDeadline);
1688 deadline->set(TimePoint::max(), "none");
1689 }
1690 Mutexed<NamedTimePoint>::Locked deadline(mQueueDeadline);
1691 deadline->set(TimePoint::max(), "none");
1692}
1693
1694} // namespace android
1695
1696extern "C" android::CodecBase *CreateCodec() {
1697 return new android::CCodec;
1698}
1699
1700extern "C" android::PersistentSurface *CreateInputSurface() {
1701 // Attempt to create a Codec2's input surface.
1702 std::shared_ptr<android::Codec2Client::InputSurface> inputSurface =
1703 android::Codec2Client::CreateInputSurface();
1704 if (inputSurface) {
1705 return new android::PersistentSurface(
1706 inputSurface->getGraphicBufferProducer(),
1707 static_cast<android::sp<android::hidl::base::V1_0::IBase>>(
1708 inputSurface->getHalInterface()));
1709 }
1710
1711 // Fall back to OMX.
1712 using namespace android::hardware::media::omx::V1_0;
1713 using namespace android::hardware::media::omx::V1_0::utils;
1714 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1715 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1716 android::sp<IOmx> omx = IOmx::getService();
1717 typedef android::hardware::graphics::bufferqueue::V1_0::
1718 IGraphicBufferProducer HGraphicBufferProducer;
1719 typedef android::hardware::media::omx::V1_0::
1720 IGraphicBufferSource HGraphicBufferSource;
1721 OmxStatus s;
1722 android::sp<HGraphicBufferProducer> gbp;
1723 android::sp<HGraphicBufferSource> gbs;
1724 android::Return<void> transStatus = omx->createInputSurface(
1725 [&s, &gbp, &gbs](
1726 OmxStatus status,
1727 const android::sp<HGraphicBufferProducer>& producer,
1728 const android::sp<HGraphicBufferSource>& source) {
1729 s = status;
1730 gbp = producer;
1731 gbs = source;
1732 });
1733 if (transStatus.isOk() && s == OmxStatus::OK) {
1734 return new android::PersistentSurface(
1735 new H2BGraphicBufferProducer(gbp),
1736 sp<::android::IGraphicBufferSource>(
1737 new LWGraphicBufferSource(gbs)));
1738 }
1739
1740 return nullptr;
1741}
1742