blob: 98e5951ab7926ada1f21569d38e32efd23057e91 [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,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800451 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800452 (void)component;
453 sp<CCodec> codec(mCodec.promote());
454 if (!codec) {
455 return;
456 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800457 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800458 }
459
460 virtual void onTripped(
461 const std::weak_ptr<Codec2Client::Component>& component,
462 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
463 ) override {
464 // TODO
465 (void)component;
466 (void)settingResult;
467 }
468
469 virtual void onError(
470 const std::weak_ptr<Codec2Client::Component>& component,
471 uint32_t errorCode) override {
472 // TODO
473 (void)component;
474 (void)errorCode;
475 }
476
477 virtual void onDeath(
478 const std::weak_ptr<Codec2Client::Component>& component) override {
479 { // Log the death of the component.
480 std::shared_ptr<Codec2Client::Component> comp = component.lock();
481 if (!comp) {
482 ALOGE("Codec2 component died.");
483 } else {
484 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
485 }
486 }
487
488 // Report to MediaCodec.
489 sp<CCodec> codec(mCodec.promote());
490 if (!codec || !codec->mCallback) {
491 return;
492 }
493 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
494 }
495
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800496 virtual void onFrameRendered(uint64_t bufferQueueId,
497 int32_t slotId,
498 int64_t timestampNs) override {
499 // TODO: implement
500 (void)bufferQueueId;
501 (void)slotId;
502 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800503 }
504
505 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800506 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800507 sp<CCodec> codec(mCodec.promote());
508 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800509 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800510 }
511 }
512
513private:
514 wp<CCodec> mCodec;
515};
516
517// CCodecCallbackImpl
518
519class CCodecCallbackImpl : public CCodecCallback {
520public:
521 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
522 ~CCodecCallbackImpl() override = default;
523
524 void onError(status_t err, enum ActionCode actionCode) override {
525 mCodec->mCallback->onError(err, actionCode);
526 }
527
528 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
529 mCodec->mCallback->onOutputFramesRendered(
530 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
531 }
532
Pawin Vongmasa36653902018-11-15 00:10:25 -0800533 void onOutputBuffersChanged() override {
534 mCodec->mCallback->onOutputBuffersChanged();
535 }
536
537private:
538 CCodec *mCodec;
539};
540
541// CCodec
542
543CCodec::CCodec()
Wonsik Kimab34ed62019-01-31 15:28:46 -0800544 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800545}
546
547CCodec::~CCodec() {
548}
549
550std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
551 return mChannel;
552}
553
554status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
555 status_t err = job();
556 if (err != C2_OK) {
557 mCallback->onError(err, ACTION_CODE_FATAL);
558 }
559 return err;
560}
561
562void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
563 auto setAllocating = [this] {
564 Mutexed<State>::Locked state(mState);
565 if (state->get() != RELEASED) {
566 return INVALID_OPERATION;
567 }
568 state->set(ALLOCATING);
569 return OK;
570 };
571 if (tryAndReportOnError(setAllocating) != OK) {
572 return;
573 }
574
575 sp<RefBase> codecInfo;
576 CHECK(msg->findObject("codecInfo", &codecInfo));
577 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
578
579 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
580 allocMsg->setObject("codecInfo", codecInfo);
581 allocMsg->post();
582}
583
584void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
585 if (codecInfo == nullptr) {
586 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
587 return;
588 }
589 ALOGD("allocate(%s)", codecInfo->getCodecName());
590 mClientListener.reset(new ClientListener(this));
591
592 AString componentName = codecInfo->getCodecName();
593 std::shared_ptr<Codec2Client> client;
594
595 // set up preferred component store to access vendor store parameters
596 client = Codec2Client::CreateFromService("default", false);
597 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800598 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800599 SetPreferredCodec2ComponentStore(
600 std::make_shared<Codec2ClientInterfaceWrapper>(client));
601 }
602
603 std::shared_ptr<Codec2Client::Component> comp =
604 Codec2Client::CreateComponentByName(
605 componentName.c_str(),
606 mClientListener,
607 &client);
608 if (!comp) {
609 ALOGE("Failed Create component: %s", componentName.c_str());
610 Mutexed<State>::Locked state(mState);
611 state->set(RELEASED);
612 state.unlock();
613 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
614 state.lock();
615 return;
616 }
617 ALOGI("Created component [%s]", componentName.c_str());
618 mChannel->setComponent(comp);
619 auto setAllocated = [this, comp, client] {
620 Mutexed<State>::Locked state(mState);
621 if (state->get() != ALLOCATING) {
622 state->set(RELEASED);
623 return UNKNOWN_ERROR;
624 }
625 state->set(ALLOCATED);
626 state->comp = comp;
627 mClient = client;
628 return OK;
629 };
630 if (tryAndReportOnError(setAllocated) != OK) {
631 return;
632 }
633
634 // initialize config here in case setParameters is called prior to configure
635 Mutexed<Config>::Locked config(mConfig);
636 status_t err = config->initialize(mClient, comp);
637 if (err != OK) {
638 ALOGW("Failed to initialize configuration support");
639 // TODO: report error once we complete implementation.
640 }
641 config->queryConfiguration(comp);
642
643 mCallback->onComponentAllocated(componentName.c_str());
644}
645
646void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
647 auto checkAllocated = [this] {
648 Mutexed<State>::Locked state(mState);
649 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
650 };
651 if (tryAndReportOnError(checkAllocated) != OK) {
652 return;
653 }
654
655 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
656 msg->setMessage("format", format);
657 msg->post();
658}
659
660void CCodec::configure(const sp<AMessage> &msg) {
661 std::shared_ptr<Codec2Client::Component> comp;
662 auto checkAllocated = [this, &comp] {
663 Mutexed<State>::Locked state(mState);
664 if (state->get() != ALLOCATED) {
665 state->set(RELEASED);
666 return UNKNOWN_ERROR;
667 }
668 comp = state->comp;
669 return OK;
670 };
671 if (tryAndReportOnError(checkAllocated) != OK) {
672 return;
673 }
674
675 auto doConfig = [msg, comp, this]() -> status_t {
676 AString mime;
677 if (!msg->findString("mime", &mime)) {
678 return BAD_VALUE;
679 }
680
681 int32_t encoder;
682 if (!msg->findInt32("encoder", &encoder)) {
683 encoder = false;
684 }
685
686 // TODO: read from intf()
687 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
688 return UNKNOWN_ERROR;
689 }
690
691 int32_t storeMeta;
692 if (encoder
693 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
694 && storeMeta != kMetadataBufferTypeInvalid) {
695 if (storeMeta != kMetadataBufferTypeANWBuffer) {
696 ALOGD("Only ANW buffers are supported for legacy metadata mode");
697 return BAD_VALUE;
698 }
699 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
700 }
701
702 sp<RefBase> obj;
703 sp<Surface> surface;
704 if (msg->findObject("native-window", &obj)) {
705 surface = static_cast<Surface *>(obj.get());
706 setSurface(surface);
707 }
708
709 Mutexed<Config>::Locked config(mConfig);
710 config->mUsingSurface = surface != nullptr;
711
Wonsik Kim1114eea2019-02-25 14:35:24 -0800712 // Enforce required parameters
713 int32_t i32;
714 float flt;
715 if (config->mDomain & Config::IS_AUDIO) {
716 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
717 ALOGD("sample rate is missing, which is required for audio components.");
718 return BAD_VALUE;
719 }
720 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
721 ALOGD("channel count is missing, which is required for audio components.");
722 return BAD_VALUE;
723 }
724 if ((config->mDomain & Config::IS_ENCODER)
725 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
726 && !msg->findInt32(KEY_BIT_RATE, &i32)
727 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
728 ALOGD("bitrate is missing, which is required for audio encoders.");
729 return BAD_VALUE;
730 }
731 }
732 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
733 if (!msg->findInt32(KEY_WIDTH, &i32)) {
734 ALOGD("width is missing, which is required for image/video components.");
735 return BAD_VALUE;
736 }
737 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
738 ALOGD("height is missing, which is required for image/video components.");
739 return BAD_VALUE;
740 }
741 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
742 if (!msg->findInt32(KEY_BIT_RATE, &i32)
743 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
744 ALOGD("bitrate is missing, which is required for video encoders.");
745 return BAD_VALUE;
746 }
747 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
748 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
749 ALOGD("I frame interval is missing, which is required for video encoders.");
750 return BAD_VALUE;
751 }
752 }
753 }
754
Pawin Vongmasa36653902018-11-15 00:10:25 -0800755 /*
756 * Handle input surface configuration
757 */
758 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
759 && (config->mDomain & Config::IS_ENCODER)) {
760 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
761 {
762 config->mISConfig->mMinFps = 0;
763 int64_t value;
764 if (msg->findInt64("repeat-previous-frame-after", &value) && value > 0) {
765 config->mISConfig->mMinFps = 1e6 / value;
766 }
767 (void)msg->findFloat("max-fps-to-encoder", &config->mISConfig->mMaxFps);
768 config->mISConfig->mMinAdjustedFps = 0;
769 config->mISConfig->mFixedAdjustedFps = 0;
770 if (msg->findInt64("max-pts-gap-to-encoder", &value)) {
771 if (value < 0 && value >= INT32_MIN) {
772 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
773 } else if (value > 0 && value <= INT32_MAX) {
774 config->mISConfig->mMinAdjustedFps = 1e6 / value;
775 }
776 }
777 }
778
779 {
780 double value;
781 if (msg->findDouble("time-lapse-fps", &value)) {
782 config->mISConfig->mCaptureFps = value;
783 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
784 }
785 }
786
787 {
788 config->mISConfig->mSuspended = false;
789 config->mISConfig->mSuspendAtUs = -1;
790 int32_t value;
791 if (msg->findInt32("create-input-buffers-suspended", &value) && value) {
792 config->mISConfig->mSuspended = true;
793 }
794 }
795 }
796
797 /*
798 * Handle desired color format.
799 */
800 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
801 int32_t format = -1;
802 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
803 /*
804 * Also handle default color format (encoders require color format, so this is only
805 * needed for decoders.
806 */
807 if (!(config->mDomain & Config::IS_ENCODER)) {
808 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
809 }
810 }
811
812 if (format >= 0) {
813 msg->setInt32("android._color-format", format);
814 }
815 }
816
817 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800818 // NOTE: We used to ignore "video-bitrate" at configure; replicate
819 // the behavior here.
820 sp<AMessage> sdkParams = msg;
821 int32_t videoBitrate;
822 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
823 sdkParams = msg->dup();
824 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
825 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800826 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800827 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800828 if (err != OK) {
829 ALOGW("failed to convert configuration to c2 params");
830 }
831 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
832 if (err != OK) {
833 ALOGW("failed to configure c2 params");
834 return err;
835 }
836
837 std::vector<std::unique_ptr<C2Param>> params;
838 C2StreamUsageTuning::input usage(0u, 0u);
839 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
840
841 std::initializer_list<C2Param::Index> indices {
842 };
843 c2_status_t c2err = comp->query(
844 { &usage, &maxInputSize },
845 indices,
846 C2_DONT_BLOCK,
847 &params);
848 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
849 ALOGE("Failed to query component interface: %d", c2err);
850 return UNKNOWN_ERROR;
851 }
852 if (params.size() != indices.size()) {
853 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
854 indices.size(), params.size());
855 return UNKNOWN_ERROR;
856 }
857 if (usage && (usage.value & C2MemoryUsage::CPU_READ)) {
858 config->mInputFormat->setInt32("using-sw-read-often", true);
859 }
860
861 // NOTE: we don't blindly use client specified input size if specified as clients
862 // at times specify too small size. Instead, mimic the behavior from OMX, where the
863 // client specified size is only used to ask for bigger buffers than component suggested
864 // size.
865 int32_t clientInputSize = 0;
866 bool clientSpecifiedInputSize =
867 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
868 // TEMP: enforce minimum buffer size of 1MB for video decoders
869 // and 16K / 4K for audio encoders/decoders
870 if (maxInputSize.value == 0) {
871 if (config->mDomain & Config::IS_AUDIO) {
872 maxInputSize.value = encoder ? 16384 : 4096;
873 } else if (!encoder) {
874 maxInputSize.value = 1048576u;
875 }
876 }
877
878 // verify that CSD fits into this size (if defined)
879 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
880 sp<ABuffer> csd;
881 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
882 if (csd && csd->size() > maxInputSize.value) {
883 maxInputSize.value = csd->size();
884 }
885 }
886 }
887
888 // TODO: do this based on component requiring linear allocator for input
889 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
890 if (clientSpecifiedInputSize) {
891 // Warn that we're overriding client's max input size if necessary.
892 if ((uint32_t)clientInputSize < maxInputSize.value) {
893 ALOGD("client requested max input size %d, which is smaller than "
894 "what component recommended (%u); overriding with component "
895 "recommendation.", clientInputSize, maxInputSize.value);
896 ALOGW("This behavior is subject to change. It is recommended that "
897 "app developers double check whether the requested "
898 "max input size is in reasonable range.");
899 } else {
900 maxInputSize.value = clientInputSize;
901 }
902 }
903 // Pass max input size on input format to the buffer channel (if supplied by the
904 // component or by a default)
905 if (maxInputSize.value) {
906 config->mInputFormat->setInt32(
907 KEY_MAX_INPUT_SIZE,
908 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
909 }
910 }
911
912 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
913 // propagate HDR static info to output format for both encoders and decoders
914 // if component supports this info, we will update from component, but only the raw port,
915 // so don't propagate if component already filled it in.
916 sp<ABuffer> hdrInfo;
917 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
918 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
919 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
920 }
921
922 // Set desired color format from configuration parameter
923 int32_t format;
924 if (msg->findInt32("android._color-format", &format)) {
925 if (config->mDomain & Config::IS_ENCODER) {
926 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
927 } else {
928 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
929 }
930 }
931 }
932
933 // propagate encoder delay and padding to output format
934 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
935 int delay = 0;
936 if (msg->findInt32("encoder-delay", &delay)) {
937 config->mOutputFormat->setInt32("encoder-delay", delay);
938 }
939 int padding = 0;
940 if (msg->findInt32("encoder-padding", &padding)) {
941 config->mOutputFormat->setInt32("encoder-padding", padding);
942 }
943 }
944
945 // set channel-mask
946 if (config->mDomain & Config::IS_AUDIO) {
947 int32_t mask;
948 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
949 if (config->mDomain & Config::IS_ENCODER) {
950 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
951 } else {
952 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
953 }
954 }
955 }
956
957 ALOGD("setup formats input: %s and output: %s",
958 config->mInputFormat->debugString().c_str(),
959 config->mOutputFormat->debugString().c_str());
960 return OK;
961 };
962 if (tryAndReportOnError(doConfig) != OK) {
963 return;
964 }
965
966 Mutexed<Config>::Locked config(mConfig);
967
968 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
969}
970
971void CCodec::initiateCreateInputSurface() {
972 status_t err = [this] {
973 Mutexed<State>::Locked state(mState);
974 if (state->get() != ALLOCATED) {
975 return UNKNOWN_ERROR;
976 }
977 // TODO: read it from intf() properly.
978 if (state->comp->getName().find("encoder") == std::string::npos) {
979 return INVALID_OPERATION;
980 }
981 return OK;
982 }();
983 if (err != OK) {
984 mCallback->onInputSurfaceCreationFailed(err);
985 return;
986 }
987
988 (new AMessage(kWhatCreateInputSurface, this))->post();
989}
990
Lajos Molnar47118272019-01-31 16:28:04 -0800991sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
992 using namespace android::hardware::media::omx::V1_0;
993 using namespace android::hardware::media::omx::V1_0::utils;
994 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
995 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
996 android::sp<IOmx> omx = IOmx::getService();
997 typedef android::hardware::graphics::bufferqueue::V1_0::
998 IGraphicBufferProducer HGraphicBufferProducer;
999 typedef android::hardware::media::omx::V1_0::
1000 IGraphicBufferSource HGraphicBufferSource;
1001 OmxStatus s;
1002 android::sp<HGraphicBufferProducer> gbp;
1003 android::sp<HGraphicBufferSource> gbs;
1004 android::Return<void> transStatus = omx->createInputSurface(
1005 [&s, &gbp, &gbs](
1006 OmxStatus status,
1007 const android::sp<HGraphicBufferProducer>& producer,
1008 const android::sp<HGraphicBufferSource>& source) {
1009 s = status;
1010 gbp = producer;
1011 gbs = source;
1012 });
1013 if (transStatus.isOk() && s == OmxStatus::OK) {
1014 return new PersistentSurface(
1015 new H2BGraphicBufferProducer(gbp),
1016 sp<::android::IGraphicBufferSource>(new LWGraphicBufferSource(gbs)));
1017 }
1018
1019 return nullptr;
1020}
1021
1022sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1023 sp<PersistentSurface> surface(CreateInputSurface());
1024
1025 if (surface == nullptr) {
1026 surface = CreateOmxInputSurface();
1027 }
1028
1029 return surface;
1030}
1031
Pawin Vongmasa36653902018-11-15 00:10:25 -08001032void CCodec::createInputSurface() {
1033 status_t err;
1034 sp<IGraphicBufferProducer> bufferProducer;
1035
1036 sp<AMessage> inputFormat;
1037 sp<AMessage> outputFormat;
1038 {
1039 Mutexed<Config>::Locked config(mConfig);
1040 inputFormat = config->mInputFormat;
1041 outputFormat = config->mOutputFormat;
1042 }
1043
Lajos Molnar47118272019-01-31 16:28:04 -08001044 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001045
1046 if (persistentSurface->getHidlTarget()) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001047 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001048 persistentSurface->getHidlTarget());
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001049 if (!hidlInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001050 ALOGE("Corrupted input surface");
1051 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1052 return;
1053 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001054 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1055 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001056 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001057 inputSurface));
1058 bufferProducer = inputSurface->getGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001059 } else {
1060 int32_t width = 0;
1061 (void)outputFormat->findInt32("width", &width);
1062 int32_t height = 0;
1063 (void)outputFormat->findInt32("height", &height);
1064 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1065 persistentSurface->getBufferSource(), width, height));
1066 bufferProducer = persistentSurface->getBufferProducer();
1067 }
1068
1069 if (err != OK) {
1070 ALOGE("Failed to set up input surface: %d", err);
1071 mCallback->onInputSurfaceCreationFailed(err);
1072 return;
1073 }
1074
1075 mCallback->onInputSurfaceCreated(
1076 inputFormat,
1077 outputFormat,
1078 new BufferProducerWrapper(bufferProducer));
1079}
1080
1081status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
1082 Mutexed<Config>::Locked config(mConfig);
1083 config->mUsingSurface = true;
1084
1085 // we are now using surface - apply default color aspects to input format - as well as
1086 // get dataspace
1087 bool inputFormatChanged = config->updateFormats(config->IS_INPUT);
1088 ALOGD("input format %s to %s",
1089 inputFormatChanged ? "changed" : "unchanged",
1090 config->mInputFormat->debugString().c_str());
1091
1092 // configure dataspace
1093 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1094 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1095 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1096 surface->setDataSpace(dataSpace);
1097
1098 status_t err = mChannel->setInputSurface(surface);
1099 if (err != OK) {
1100 // undo input format update
1101 config->mUsingSurface = false;
1102 (void)config->updateFormats(config->IS_INPUT);
1103 return err;
1104 }
1105 config->mInputSurface = surface;
1106
1107 if (config->mISConfig) {
1108 surface->configure(*config->mISConfig);
1109 } else {
1110 ALOGD("ISConfig: no configuration");
1111 }
1112
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001113 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001114}
1115
1116void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1117 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1118 msg->setObject("surface", surface);
1119 msg->post();
1120}
1121
1122void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1123 sp<AMessage> inputFormat;
1124 sp<AMessage> outputFormat;
1125 {
1126 Mutexed<Config>::Locked config(mConfig);
1127 inputFormat = config->mInputFormat;
1128 outputFormat = config->mOutputFormat;
1129 }
1130 auto hidlTarget = surface->getHidlTarget();
1131 if (hidlTarget) {
1132 sp<IInputSurface> inputSurface =
1133 IInputSurface::castFrom(hidlTarget);
1134 if (!inputSurface) {
1135 ALOGE("Failed to set input surface: Corrupted surface.");
1136 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1137 return;
1138 }
1139 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1140 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1141 if (err != OK) {
1142 ALOGE("Failed to set up input surface: %d", err);
1143 mCallback->onInputSurfaceDeclined(err);
1144 return;
1145 }
1146 } else {
1147 int32_t width = 0;
1148 (void)outputFormat->findInt32("width", &width);
1149 int32_t height = 0;
1150 (void)outputFormat->findInt32("height", &height);
1151 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1152 surface->getBufferSource(), width, height));
1153 if (err != OK) {
1154 ALOGE("Failed to set up input surface: %d", err);
1155 mCallback->onInputSurfaceDeclined(err);
1156 return;
1157 }
1158 }
1159 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1160}
1161
1162void CCodec::initiateStart() {
1163 auto setStarting = [this] {
1164 Mutexed<State>::Locked state(mState);
1165 if (state->get() != ALLOCATED) {
1166 return UNKNOWN_ERROR;
1167 }
1168 state->set(STARTING);
1169 return OK;
1170 };
1171 if (tryAndReportOnError(setStarting) != OK) {
1172 return;
1173 }
1174
1175 (new AMessage(kWhatStart, this))->post();
1176}
1177
1178void CCodec::start() {
1179 std::shared_ptr<Codec2Client::Component> comp;
1180 auto checkStarting = [this, &comp] {
1181 Mutexed<State>::Locked state(mState);
1182 if (state->get() != STARTING) {
1183 return UNKNOWN_ERROR;
1184 }
1185 comp = state->comp;
1186 return OK;
1187 };
1188 if (tryAndReportOnError(checkStarting) != OK) {
1189 return;
1190 }
1191
1192 c2_status_t err = comp->start();
1193 if (err != C2_OK) {
1194 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1195 ACTION_CODE_FATAL);
1196 return;
1197 }
1198 sp<AMessage> inputFormat;
1199 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001200 status_t err2 = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001201 {
1202 Mutexed<Config>::Locked config(mConfig);
1203 inputFormat = config->mInputFormat;
1204 outputFormat = config->mOutputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001205 if (config->mInputSurface) {
1206 err2 = config->mInputSurface->start();
1207 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001208 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001209 if (err2 != OK) {
1210 mCallback->onError(err2, ACTION_CODE_FATAL);
1211 return;
1212 }
1213 err2 = mChannel->start(inputFormat, outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001214 if (err2 != OK) {
1215 mCallback->onError(err2, ACTION_CODE_FATAL);
1216 return;
1217 }
1218
1219 auto setRunning = [this] {
1220 Mutexed<State>::Locked state(mState);
1221 if (state->get() != STARTING) {
1222 return UNKNOWN_ERROR;
1223 }
1224 state->set(RUNNING);
1225 return OK;
1226 };
1227 if (tryAndReportOnError(setRunning) != OK) {
1228 return;
1229 }
1230 mCallback->onStartCompleted();
1231
1232 (void)mChannel->requestInitialInputBuffers();
1233}
1234
1235void CCodec::initiateShutdown(bool keepComponentAllocated) {
1236 if (keepComponentAllocated) {
1237 initiateStop();
1238 } else {
1239 initiateRelease();
1240 }
1241}
1242
1243void CCodec::initiateStop() {
1244 {
1245 Mutexed<State>::Locked state(mState);
1246 if (state->get() == ALLOCATED
1247 || state->get() == RELEASED
1248 || state->get() == STOPPING
1249 || state->get() == RELEASING) {
1250 // We're already stopped, released, or doing it right now.
1251 state.unlock();
1252 mCallback->onStopCompleted();
1253 state.lock();
1254 return;
1255 }
1256 state->set(STOPPING);
1257 }
1258
1259 mChannel->stop();
1260 (new AMessage(kWhatStop, this))->post();
1261}
1262
1263void CCodec::stop() {
1264 std::shared_ptr<Codec2Client::Component> comp;
1265 {
1266 Mutexed<State>::Locked state(mState);
1267 if (state->get() == RELEASING) {
1268 state.unlock();
1269 // We're already stopped or release is in progress.
1270 mCallback->onStopCompleted();
1271 state.lock();
1272 return;
1273 } else if (state->get() != STOPPING) {
1274 state.unlock();
1275 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1276 state.lock();
1277 return;
1278 }
1279 comp = state->comp;
1280 }
1281 status_t err = comp->stop();
1282 if (err != C2_OK) {
1283 // TODO: convert err into status_t
1284 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1285 }
1286
1287 {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001288 Mutexed<Config>::Locked config(mConfig);
1289 if (config->mInputSurface) {
1290 config->mInputSurface->disconnect();
1291 config->mInputSurface = nullptr;
1292 }
1293 }
1294 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001295 Mutexed<State>::Locked state(mState);
1296 if (state->get() == STOPPING) {
1297 state->set(ALLOCATED);
1298 }
1299 }
1300 mCallback->onStopCompleted();
1301}
1302
1303void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001304 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001305 {
1306 Mutexed<State>::Locked state(mState);
1307 if (state->get() == RELEASED || state->get() == RELEASING) {
1308 // We're already released or doing it right now.
1309 if (sendCallback) {
1310 state.unlock();
1311 mCallback->onReleaseCompleted();
1312 state.lock();
1313 }
1314 return;
1315 }
1316 if (state->get() == ALLOCATING) {
1317 state->set(RELEASING);
1318 // With the altered state allocate() would fail and clean up.
1319 if (sendCallback) {
1320 state.unlock();
1321 mCallback->onReleaseCompleted();
1322 state.lock();
1323 }
1324 return;
1325 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001326 if (state->get() == STARTING
1327 || state->get() == RUNNING
1328 || state->get() == STOPPING) {
1329 // Input surface may have been started, so clean up is needed.
1330 clearInputSurfaceIfNeeded = true;
1331 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001332 state->set(RELEASING);
1333 }
1334
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001335 if (clearInputSurfaceIfNeeded) {
1336 Mutexed<Config>::Locked config(mConfig);
1337 if (config->mInputSurface) {
1338 config->mInputSurface->disconnect();
1339 config->mInputSurface = nullptr;
1340 }
1341 }
1342
Pawin Vongmasa36653902018-11-15 00:10:25 -08001343 mChannel->stop();
1344 // thiz holds strong ref to this while the thread is running.
1345 sp<CCodec> thiz(this);
1346 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1347}
1348
1349void CCodec::release(bool sendCallback) {
1350 std::shared_ptr<Codec2Client::Component> comp;
1351 {
1352 Mutexed<State>::Locked state(mState);
1353 if (state->get() == RELEASED) {
1354 if (sendCallback) {
1355 state.unlock();
1356 mCallback->onReleaseCompleted();
1357 state.lock();
1358 }
1359 return;
1360 }
1361 comp = state->comp;
1362 }
1363 comp->release();
1364
1365 {
1366 Mutexed<State>::Locked state(mState);
1367 state->set(RELEASED);
1368 state->comp.reset();
1369 }
1370 if (sendCallback) {
1371 mCallback->onReleaseCompleted();
1372 }
1373}
1374
1375status_t CCodec::setSurface(const sp<Surface> &surface) {
1376 return mChannel->setSurface(surface);
1377}
1378
1379void CCodec::signalFlush() {
1380 status_t err = [this] {
1381 Mutexed<State>::Locked state(mState);
1382 if (state->get() == FLUSHED) {
1383 return ALREADY_EXISTS;
1384 }
1385 if (state->get() != RUNNING) {
1386 return UNKNOWN_ERROR;
1387 }
1388 state->set(FLUSHING);
1389 return OK;
1390 }();
1391 switch (err) {
1392 case ALREADY_EXISTS:
1393 mCallback->onFlushCompleted();
1394 return;
1395 case OK:
1396 break;
1397 default:
1398 mCallback->onError(err, ACTION_CODE_FATAL);
1399 return;
1400 }
1401
1402 mChannel->stop();
1403 (new AMessage(kWhatFlush, this))->post();
1404}
1405
1406void CCodec::flush() {
1407 std::shared_ptr<Codec2Client::Component> comp;
1408 auto checkFlushing = [this, &comp] {
1409 Mutexed<State>::Locked state(mState);
1410 if (state->get() != FLUSHING) {
1411 return UNKNOWN_ERROR;
1412 }
1413 comp = state->comp;
1414 return OK;
1415 };
1416 if (tryAndReportOnError(checkFlushing) != OK) {
1417 return;
1418 }
1419
1420 std::list<std::unique_ptr<C2Work>> flushedWork;
1421 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1422 {
1423 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1424 flushedWork.splice(flushedWork.end(), *queue);
1425 }
1426 if (err != C2_OK) {
1427 // TODO: convert err into status_t
1428 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1429 }
1430
1431 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001432
1433 {
1434 Mutexed<State>::Locked state(mState);
1435 state->set(FLUSHED);
1436 }
1437 mCallback->onFlushCompleted();
1438}
1439
1440void CCodec::signalResume() {
1441 auto setResuming = [this] {
1442 Mutexed<State>::Locked state(mState);
1443 if (state->get() != FLUSHED) {
1444 return UNKNOWN_ERROR;
1445 }
1446 state->set(RESUMING);
1447 return OK;
1448 };
1449 if (tryAndReportOnError(setResuming) != OK) {
1450 return;
1451 }
1452
1453 (void)mChannel->start(nullptr, nullptr);
1454
1455 {
1456 Mutexed<State>::Locked state(mState);
1457 if (state->get() != RESUMING) {
1458 state.unlock();
1459 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1460 state.lock();
1461 return;
1462 }
1463 state->set(RUNNING);
1464 }
1465
1466 (void)mChannel->requestInitialInputBuffers();
1467}
1468
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001469void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001470 std::shared_ptr<Codec2Client::Component> comp;
1471 auto checkState = [this, &comp] {
1472 Mutexed<State>::Locked state(mState);
1473 if (state->get() == RELEASED) {
1474 return INVALID_OPERATION;
1475 }
1476 comp = state->comp;
1477 return OK;
1478 };
1479 if (tryAndReportOnError(checkState) != OK) {
1480 return;
1481 }
1482
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001483 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1484 // the behavior here.
1485 sp<AMessage> params = msg;
1486 int32_t bitrate;
1487 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1488 params = msg->dup();
1489 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1490 }
1491
Pawin Vongmasa36653902018-11-15 00:10:25 -08001492 Mutexed<Config>::Locked config(mConfig);
1493
1494 /**
1495 * Handle input surface parameters
1496 */
1497 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1498 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
1499 (void)params->findInt64("time-offset-us", &config->mISConfig->mTimeOffsetUs);
1500
1501 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1502 config->mISConfig->mStopped = false;
1503 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1504 config->mISConfig->mStopped = true;
1505 }
1506
1507 int32_t value;
1508 if (params->findInt32("drop-input-frames", &value)) {
1509 config->mISConfig->mSuspended = value;
1510 config->mISConfig->mSuspendAtUs = -1;
1511 (void)params->findInt64("drop-start-time-us", &config->mISConfig->mSuspendAtUs);
1512 }
1513
1514 (void)config->mInputSurface->configure(*config->mISConfig);
1515 if (config->mISConfig->mStopped) {
1516 config->mInputFormat->setInt64(
1517 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1518 }
1519 }
1520
1521 std::vector<std::unique_ptr<C2Param>> configUpdate;
1522 (void)config->getConfigUpdateFromSdkParams(
1523 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1524 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1525 // Parameter synchronization is not defined when using input surface. For now, route
1526 // these directly to the component.
1527 if (config->mInputSurface == nullptr
1528 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1529 || comp->getName().find("c2.android.") == 0)) {
1530 mChannel->setParameters(configUpdate);
1531 } else {
1532 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1533 }
1534}
1535
1536void CCodec::signalEndOfInputStream() {
1537 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1538}
1539
1540void CCodec::signalRequestIDRFrame() {
1541 std::shared_ptr<Codec2Client::Component> comp;
1542 {
1543 Mutexed<State>::Locked state(mState);
1544 if (state->get() == RELEASED) {
1545 ALOGD("no IDR request sent since component is released");
1546 return;
1547 }
1548 comp = state->comp;
1549 }
1550 ALOGV("request IDR");
1551 Mutexed<Config>::Locked config(mConfig);
1552 std::vector<std::unique_ptr<C2Param>> params;
1553 params.push_back(
1554 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1555 config->setParameters(comp, params, C2_MAY_BLOCK);
1556}
1557
Wonsik Kimab34ed62019-01-31 15:28:46 -08001558void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001559 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001560 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1561 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001562 }
1563 (new AMessage(kWhatWorkDone, this))->post();
1564}
1565
Wonsik Kimab34ed62019-01-31 15:28:46 -08001566void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1567 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001568}
1569
1570void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1571 TimePoint now = std::chrono::steady_clock::now();
1572 CCodecWatchdog::getInstance()->watch(this);
1573 switch (msg->what()) {
1574 case kWhatAllocate: {
1575 // C2ComponentStore::createComponent() should return within 100ms.
1576 setDeadline(now, 150ms, "allocate");
1577 sp<RefBase> obj;
1578 CHECK(msg->findObject("codecInfo", &obj));
1579 allocate((MediaCodecInfo *)obj.get());
1580 break;
1581 }
1582 case kWhatConfigure: {
1583 // C2Component::commit_sm() should return within 5ms.
1584 setDeadline(now, 250ms, "configure");
1585 sp<AMessage> format;
1586 CHECK(msg->findMessage("format", &format));
1587 configure(format);
1588 break;
1589 }
1590 case kWhatStart: {
1591 // C2Component::start() should return within 500ms.
1592 setDeadline(now, 550ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001593 start();
1594 break;
1595 }
1596 case kWhatStop: {
1597 // C2Component::stop() should return within 500ms.
1598 setDeadline(now, 550ms, "stop");
1599 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001600 break;
1601 }
1602 case kWhatFlush: {
1603 // C2Component::flush_sm() should return within 5ms.
1604 setDeadline(now, 50ms, "flush");
1605 flush();
1606 break;
1607 }
1608 case kWhatCreateInputSurface: {
1609 // Surface operations may be briefly blocking.
1610 setDeadline(now, 100ms, "createInputSurface");
1611 createInputSurface();
1612 break;
1613 }
1614 case kWhatSetInputSurface: {
1615 // Surface operations may be briefly blocking.
1616 setDeadline(now, 100ms, "setInputSurface");
1617 sp<RefBase> obj;
1618 CHECK(msg->findObject("surface", &obj));
1619 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1620 setInputSurface(surface);
1621 break;
1622 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001623 case kWhatWorkDone: {
1624 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001625 bool shouldPost = false;
1626 {
1627 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1628 if (queue->empty()) {
1629 break;
1630 }
1631 work.swap(queue->front());
1632 queue->pop_front();
1633 shouldPost = !queue->empty();
1634 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001635 if (shouldPost) {
1636 (new AMessage(kWhatWorkDone, this))->post();
1637 }
1638
Pawin Vongmasa36653902018-11-15 00:10:25 -08001639 // handle configuration changes in work done
1640 Mutexed<Config>::Locked config(mConfig);
1641 bool changed = false;
1642 Config::Watcher<C2StreamInitDataInfo::output> initData =
1643 config->watch<C2StreamInitDataInfo::output>();
1644 if (!work->worklets.empty()
1645 && (work->worklets.front()->output.flags
1646 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1647
1648 // copy buffer info to config
1649 std::vector<std::unique_ptr<C2Param>> updates =
1650 std::move(work->worklets.front()->output.configUpdate);
1651 unsigned stream = 0;
1652 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1653 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1654 // move all info into output-stream #0 domain
1655 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1656 }
1657 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1658 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1659 // block.crop().left, block.crop().top,
1660 // block.crop().width, block.crop().height,
1661 // block.width(), block.height());
1662 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1663 updates.emplace_back(new C2StreamPictureSizeInfo::output(
1664 stream, block.width(), block.height()));
1665 break; // for now only do the first block
1666 }
1667 ++stream;
1668 }
1669
1670 changed = config->updateConfiguration(updates, config->mOutputDomain);
1671
1672 // copy standard infos to graphic buffers if not already present (otherwise, we
1673 // may overwrite the actual intermediate value with a final value)
1674 stream = 0;
1675 const static std::vector<C2Param::Index> stdGfxInfos = {
1676 C2StreamRotationInfo::output::PARAM_TYPE,
1677 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1678 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1679 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001680 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001681 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1682 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1683 };
1684 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1685 if (buf->data().graphicBlocks().size()) {
1686 for (C2Param::Index ix : stdGfxInfos) {
1687 if (!buf->hasInfo(ix)) {
1688 const C2Param *param =
1689 config->getConfigParameterValue(ix.withStream(stream));
1690 if (param) {
1691 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1692 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1693 }
1694 }
1695 }
1696 }
1697 ++stream;
1698 }
1699 }
1700 mChannel->onWorkDone(
1701 std::move(work), changed ? config->mOutputFormat : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001702 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001703 break;
1704 }
1705 case kWhatWatch: {
1706 // watch message already posted; no-op.
1707 break;
1708 }
1709 default: {
1710 ALOGE("unrecognized message");
1711 break;
1712 }
1713 }
1714 setDeadline(TimePoint::max(), 0ms, "none");
1715}
1716
1717void CCodec::setDeadline(
1718 const TimePoint &now,
1719 const std::chrono::milliseconds &timeout,
1720 const char *name) {
1721 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1722 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1723 deadline->set(now + (timeout * mult), name);
1724}
1725
1726void CCodec::initiateReleaseIfStuck() {
1727 std::string name;
1728 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001729 {
1730 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001731 if (deadline->get() < std::chrono::steady_clock::now()) {
1732 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001733 }
1734 if (deadline->get() != TimePoint::max()) {
1735 pendingDeadline = true;
1736 }
1737 }
1738 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001739 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1740 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1741 if (elapsed >= kWorkDurationThreshold) {
1742 name = "queue";
1743 }
1744 if (elapsed > 0s) {
1745 pendingDeadline = true;
1746 }
1747 }
1748 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001749 // We're not stuck.
1750 if (pendingDeadline) {
1751 // If we are not stuck yet but still has deadline coming up,
1752 // post watch message to check back later.
1753 (new AMessage(kWhatWatch, this))->post();
1754 }
1755 return;
1756 }
1757
1758 ALOGW("previous call to %s exceeded timeout", name.c_str());
1759 initiateRelease(false);
1760 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1761}
1762
Pawin Vongmasa36653902018-11-15 00:10:25 -08001763} // namespace android
1764
1765extern "C" android::CodecBase *CreateCodec() {
1766 return new android::CCodec;
1767}
1768
Lajos Molnar47118272019-01-31 16:28:04 -08001769// Create Codec 2.0 input surface
Pawin Vongmasa36653902018-11-15 00:10:25 -08001770extern "C" android::PersistentSurface *CreateInputSurface() {
1771 // Attempt to create a Codec2's input surface.
1772 std::shared_ptr<android::Codec2Client::InputSurface> inputSurface =
1773 android::Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001774 if (!inputSurface) {
1775 return nullptr;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001776 }
Lajos Molnar47118272019-01-31 16:28:04 -08001777 return new android::PersistentSurface(
1778 inputSurface->getGraphicBufferProducer(),
1779 static_cast<android::sp<android::hidl::base::V1_0::IBase>>(
1780 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001781}
1782