blob: dce3222cef0d931506f255715b82de44b986025a [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
712 /*
713 * Handle input surface configuration
714 */
715 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
716 && (config->mDomain & Config::IS_ENCODER)) {
717 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
718 {
719 config->mISConfig->mMinFps = 0;
720 int64_t value;
721 if (msg->findInt64("repeat-previous-frame-after", &value) && value > 0) {
722 config->mISConfig->mMinFps = 1e6 / value;
723 }
724 (void)msg->findFloat("max-fps-to-encoder", &config->mISConfig->mMaxFps);
725 config->mISConfig->mMinAdjustedFps = 0;
726 config->mISConfig->mFixedAdjustedFps = 0;
727 if (msg->findInt64("max-pts-gap-to-encoder", &value)) {
728 if (value < 0 && value >= INT32_MIN) {
729 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
730 } else if (value > 0 && value <= INT32_MAX) {
731 config->mISConfig->mMinAdjustedFps = 1e6 / value;
732 }
733 }
734 }
735
736 {
737 double value;
738 if (msg->findDouble("time-lapse-fps", &value)) {
739 config->mISConfig->mCaptureFps = value;
740 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
741 }
742 }
743
744 {
745 config->mISConfig->mSuspended = false;
746 config->mISConfig->mSuspendAtUs = -1;
747 int32_t value;
748 if (msg->findInt32("create-input-buffers-suspended", &value) && value) {
749 config->mISConfig->mSuspended = true;
750 }
751 }
752 }
753
754 /*
755 * Handle desired color format.
756 */
757 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
758 int32_t format = -1;
759 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
760 /*
761 * Also handle default color format (encoders require color format, so this is only
762 * needed for decoders.
763 */
764 if (!(config->mDomain & Config::IS_ENCODER)) {
765 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
766 }
767 }
768
769 if (format >= 0) {
770 msg->setInt32("android._color-format", format);
771 }
772 }
773
774 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800775 // NOTE: We used to ignore "video-bitrate" at configure; replicate
776 // the behavior here.
777 sp<AMessage> sdkParams = msg;
778 int32_t videoBitrate;
779 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
780 sdkParams = msg->dup();
781 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
782 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800783 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800784 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800785 if (err != OK) {
786 ALOGW("failed to convert configuration to c2 params");
787 }
788 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
789 if (err != OK) {
790 ALOGW("failed to configure c2 params");
791 return err;
792 }
793
794 std::vector<std::unique_ptr<C2Param>> params;
795 C2StreamUsageTuning::input usage(0u, 0u);
796 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
797
798 std::initializer_list<C2Param::Index> indices {
799 };
800 c2_status_t c2err = comp->query(
801 { &usage, &maxInputSize },
802 indices,
803 C2_DONT_BLOCK,
804 &params);
805 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
806 ALOGE("Failed to query component interface: %d", c2err);
807 return UNKNOWN_ERROR;
808 }
809 if (params.size() != indices.size()) {
810 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
811 indices.size(), params.size());
812 return UNKNOWN_ERROR;
813 }
814 if (usage && (usage.value & C2MemoryUsage::CPU_READ)) {
815 config->mInputFormat->setInt32("using-sw-read-often", true);
816 }
817
818 // NOTE: we don't blindly use client specified input size if specified as clients
819 // at times specify too small size. Instead, mimic the behavior from OMX, where the
820 // client specified size is only used to ask for bigger buffers than component suggested
821 // size.
822 int32_t clientInputSize = 0;
823 bool clientSpecifiedInputSize =
824 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
825 // TEMP: enforce minimum buffer size of 1MB for video decoders
826 // and 16K / 4K for audio encoders/decoders
827 if (maxInputSize.value == 0) {
828 if (config->mDomain & Config::IS_AUDIO) {
829 maxInputSize.value = encoder ? 16384 : 4096;
830 } else if (!encoder) {
831 maxInputSize.value = 1048576u;
832 }
833 }
834
835 // verify that CSD fits into this size (if defined)
836 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
837 sp<ABuffer> csd;
838 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
839 if (csd && csd->size() > maxInputSize.value) {
840 maxInputSize.value = csd->size();
841 }
842 }
843 }
844
845 // TODO: do this based on component requiring linear allocator for input
846 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
847 if (clientSpecifiedInputSize) {
848 // Warn that we're overriding client's max input size if necessary.
849 if ((uint32_t)clientInputSize < maxInputSize.value) {
850 ALOGD("client requested max input size %d, which is smaller than "
851 "what component recommended (%u); overriding with component "
852 "recommendation.", clientInputSize, maxInputSize.value);
853 ALOGW("This behavior is subject to change. It is recommended that "
854 "app developers double check whether the requested "
855 "max input size is in reasonable range.");
856 } else {
857 maxInputSize.value = clientInputSize;
858 }
859 }
860 // Pass max input size on input format to the buffer channel (if supplied by the
861 // component or by a default)
862 if (maxInputSize.value) {
863 config->mInputFormat->setInt32(
864 KEY_MAX_INPUT_SIZE,
865 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
866 }
867 }
868
869 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
870 // propagate HDR static info to output format for both encoders and decoders
871 // if component supports this info, we will update from component, but only the raw port,
872 // so don't propagate if component already filled it in.
873 sp<ABuffer> hdrInfo;
874 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
875 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
876 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
877 }
878
879 // Set desired color format from configuration parameter
880 int32_t format;
881 if (msg->findInt32("android._color-format", &format)) {
882 if (config->mDomain & Config::IS_ENCODER) {
883 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
884 } else {
885 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
886 }
887 }
888 }
889
890 // propagate encoder delay and padding to output format
891 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
892 int delay = 0;
893 if (msg->findInt32("encoder-delay", &delay)) {
894 config->mOutputFormat->setInt32("encoder-delay", delay);
895 }
896 int padding = 0;
897 if (msg->findInt32("encoder-padding", &padding)) {
898 config->mOutputFormat->setInt32("encoder-padding", padding);
899 }
900 }
901
902 // set channel-mask
903 if (config->mDomain & Config::IS_AUDIO) {
904 int32_t mask;
905 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
906 if (config->mDomain & Config::IS_ENCODER) {
907 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
908 } else {
909 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
910 }
911 }
912 }
913
914 ALOGD("setup formats input: %s and output: %s",
915 config->mInputFormat->debugString().c_str(),
916 config->mOutputFormat->debugString().c_str());
917 return OK;
918 };
919 if (tryAndReportOnError(doConfig) != OK) {
920 return;
921 }
922
923 Mutexed<Config>::Locked config(mConfig);
924
925 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
926}
927
928void CCodec::initiateCreateInputSurface() {
929 status_t err = [this] {
930 Mutexed<State>::Locked state(mState);
931 if (state->get() != ALLOCATED) {
932 return UNKNOWN_ERROR;
933 }
934 // TODO: read it from intf() properly.
935 if (state->comp->getName().find("encoder") == std::string::npos) {
936 return INVALID_OPERATION;
937 }
938 return OK;
939 }();
940 if (err != OK) {
941 mCallback->onInputSurfaceCreationFailed(err);
942 return;
943 }
944
945 (new AMessage(kWhatCreateInputSurface, this))->post();
946}
947
Lajos Molnar47118272019-01-31 16:28:04 -0800948sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
949 using namespace android::hardware::media::omx::V1_0;
950 using namespace android::hardware::media::omx::V1_0::utils;
951 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
952 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
953 android::sp<IOmx> omx = IOmx::getService();
954 typedef android::hardware::graphics::bufferqueue::V1_0::
955 IGraphicBufferProducer HGraphicBufferProducer;
956 typedef android::hardware::media::omx::V1_0::
957 IGraphicBufferSource HGraphicBufferSource;
958 OmxStatus s;
959 android::sp<HGraphicBufferProducer> gbp;
960 android::sp<HGraphicBufferSource> gbs;
961 android::Return<void> transStatus = omx->createInputSurface(
962 [&s, &gbp, &gbs](
963 OmxStatus status,
964 const android::sp<HGraphicBufferProducer>& producer,
965 const android::sp<HGraphicBufferSource>& source) {
966 s = status;
967 gbp = producer;
968 gbs = source;
969 });
970 if (transStatus.isOk() && s == OmxStatus::OK) {
971 return new PersistentSurface(
972 new H2BGraphicBufferProducer(gbp),
973 sp<::android::IGraphicBufferSource>(new LWGraphicBufferSource(gbs)));
974 }
975
976 return nullptr;
977}
978
979sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
980 sp<PersistentSurface> surface(CreateInputSurface());
981
982 if (surface == nullptr) {
983 surface = CreateOmxInputSurface();
984 }
985
986 return surface;
987}
988
Pawin Vongmasa36653902018-11-15 00:10:25 -0800989void CCodec::createInputSurface() {
990 status_t err;
991 sp<IGraphicBufferProducer> bufferProducer;
992
993 sp<AMessage> inputFormat;
994 sp<AMessage> outputFormat;
995 {
996 Mutexed<Config>::Locked config(mConfig);
997 inputFormat = config->mInputFormat;
998 outputFormat = config->mOutputFormat;
999 }
1000
Lajos Molnar47118272019-01-31 16:28:04 -08001001 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001002
1003 if (persistentSurface->getHidlTarget()) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001004 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001005 persistentSurface->getHidlTarget());
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001006 if (!hidlInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001007 ALOGE("Corrupted input surface");
1008 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1009 return;
1010 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001011 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1012 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001013 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001014 inputSurface));
1015 bufferProducer = inputSurface->getGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001016 } else {
1017 int32_t width = 0;
1018 (void)outputFormat->findInt32("width", &width);
1019 int32_t height = 0;
1020 (void)outputFormat->findInt32("height", &height);
1021 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1022 persistentSurface->getBufferSource(), width, height));
1023 bufferProducer = persistentSurface->getBufferProducer();
1024 }
1025
1026 if (err != OK) {
1027 ALOGE("Failed to set up input surface: %d", err);
1028 mCallback->onInputSurfaceCreationFailed(err);
1029 return;
1030 }
1031
1032 mCallback->onInputSurfaceCreated(
1033 inputFormat,
1034 outputFormat,
1035 new BufferProducerWrapper(bufferProducer));
1036}
1037
1038status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
1039 Mutexed<Config>::Locked config(mConfig);
1040 config->mUsingSurface = true;
1041
1042 // we are now using surface - apply default color aspects to input format - as well as
1043 // get dataspace
1044 bool inputFormatChanged = config->updateFormats(config->IS_INPUT);
1045 ALOGD("input format %s to %s",
1046 inputFormatChanged ? "changed" : "unchanged",
1047 config->mInputFormat->debugString().c_str());
1048
1049 // configure dataspace
1050 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1051 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1052 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1053 surface->setDataSpace(dataSpace);
1054
1055 status_t err = mChannel->setInputSurface(surface);
1056 if (err != OK) {
1057 // undo input format update
1058 config->mUsingSurface = false;
1059 (void)config->updateFormats(config->IS_INPUT);
1060 return err;
1061 }
1062 config->mInputSurface = surface;
1063
1064 if (config->mISConfig) {
1065 surface->configure(*config->mISConfig);
1066 } else {
1067 ALOGD("ISConfig: no configuration");
1068 }
1069
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001070 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001071}
1072
1073void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1074 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1075 msg->setObject("surface", surface);
1076 msg->post();
1077}
1078
1079void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1080 sp<AMessage> inputFormat;
1081 sp<AMessage> outputFormat;
1082 {
1083 Mutexed<Config>::Locked config(mConfig);
1084 inputFormat = config->mInputFormat;
1085 outputFormat = config->mOutputFormat;
1086 }
1087 auto hidlTarget = surface->getHidlTarget();
1088 if (hidlTarget) {
1089 sp<IInputSurface> inputSurface =
1090 IInputSurface::castFrom(hidlTarget);
1091 if (!inputSurface) {
1092 ALOGE("Failed to set input surface: Corrupted surface.");
1093 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1094 return;
1095 }
1096 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1097 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1098 if (err != OK) {
1099 ALOGE("Failed to set up input surface: %d", err);
1100 mCallback->onInputSurfaceDeclined(err);
1101 return;
1102 }
1103 } else {
1104 int32_t width = 0;
1105 (void)outputFormat->findInt32("width", &width);
1106 int32_t height = 0;
1107 (void)outputFormat->findInt32("height", &height);
1108 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1109 surface->getBufferSource(), width, height));
1110 if (err != OK) {
1111 ALOGE("Failed to set up input surface: %d", err);
1112 mCallback->onInputSurfaceDeclined(err);
1113 return;
1114 }
1115 }
1116 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1117}
1118
1119void CCodec::initiateStart() {
1120 auto setStarting = [this] {
1121 Mutexed<State>::Locked state(mState);
1122 if (state->get() != ALLOCATED) {
1123 return UNKNOWN_ERROR;
1124 }
1125 state->set(STARTING);
1126 return OK;
1127 };
1128 if (tryAndReportOnError(setStarting) != OK) {
1129 return;
1130 }
1131
1132 (new AMessage(kWhatStart, this))->post();
1133}
1134
1135void CCodec::start() {
1136 std::shared_ptr<Codec2Client::Component> comp;
1137 auto checkStarting = [this, &comp] {
1138 Mutexed<State>::Locked state(mState);
1139 if (state->get() != STARTING) {
1140 return UNKNOWN_ERROR;
1141 }
1142 comp = state->comp;
1143 return OK;
1144 };
1145 if (tryAndReportOnError(checkStarting) != OK) {
1146 return;
1147 }
1148
1149 c2_status_t err = comp->start();
1150 if (err != C2_OK) {
1151 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1152 ACTION_CODE_FATAL);
1153 return;
1154 }
1155 sp<AMessage> inputFormat;
1156 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001157 status_t err2 = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001158 {
1159 Mutexed<Config>::Locked config(mConfig);
1160 inputFormat = config->mInputFormat;
1161 outputFormat = config->mOutputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001162 if (config->mInputSurface) {
1163 err2 = config->mInputSurface->start();
1164 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001165 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001166 if (err2 != OK) {
1167 mCallback->onError(err2, ACTION_CODE_FATAL);
1168 return;
1169 }
1170 err2 = mChannel->start(inputFormat, outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001171 if (err2 != OK) {
1172 mCallback->onError(err2, ACTION_CODE_FATAL);
1173 return;
1174 }
1175
1176 auto setRunning = [this] {
1177 Mutexed<State>::Locked state(mState);
1178 if (state->get() != STARTING) {
1179 return UNKNOWN_ERROR;
1180 }
1181 state->set(RUNNING);
1182 return OK;
1183 };
1184 if (tryAndReportOnError(setRunning) != OK) {
1185 return;
1186 }
1187 mCallback->onStartCompleted();
1188
1189 (void)mChannel->requestInitialInputBuffers();
1190}
1191
1192void CCodec::initiateShutdown(bool keepComponentAllocated) {
1193 if (keepComponentAllocated) {
1194 initiateStop();
1195 } else {
1196 initiateRelease();
1197 }
1198}
1199
1200void CCodec::initiateStop() {
1201 {
1202 Mutexed<State>::Locked state(mState);
1203 if (state->get() == ALLOCATED
1204 || state->get() == RELEASED
1205 || state->get() == STOPPING
1206 || state->get() == RELEASING) {
1207 // We're already stopped, released, or doing it right now.
1208 state.unlock();
1209 mCallback->onStopCompleted();
1210 state.lock();
1211 return;
1212 }
1213 state->set(STOPPING);
1214 }
1215
1216 mChannel->stop();
1217 (new AMessage(kWhatStop, this))->post();
1218}
1219
1220void CCodec::stop() {
1221 std::shared_ptr<Codec2Client::Component> comp;
1222 {
1223 Mutexed<State>::Locked state(mState);
1224 if (state->get() == RELEASING) {
1225 state.unlock();
1226 // We're already stopped or release is in progress.
1227 mCallback->onStopCompleted();
1228 state.lock();
1229 return;
1230 } else if (state->get() != STOPPING) {
1231 state.unlock();
1232 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1233 state.lock();
1234 return;
1235 }
1236 comp = state->comp;
1237 }
1238 status_t err = comp->stop();
1239 if (err != C2_OK) {
1240 // TODO: convert err into status_t
1241 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1242 }
1243
1244 {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001245 Mutexed<Config>::Locked config(mConfig);
1246 if (config->mInputSurface) {
1247 config->mInputSurface->disconnect();
1248 config->mInputSurface = nullptr;
1249 }
1250 }
1251 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001252 Mutexed<State>::Locked state(mState);
1253 if (state->get() == STOPPING) {
1254 state->set(ALLOCATED);
1255 }
1256 }
1257 mCallback->onStopCompleted();
1258}
1259
1260void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001261 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001262 {
1263 Mutexed<State>::Locked state(mState);
1264 if (state->get() == RELEASED || state->get() == RELEASING) {
1265 // We're already released or doing it right now.
1266 if (sendCallback) {
1267 state.unlock();
1268 mCallback->onReleaseCompleted();
1269 state.lock();
1270 }
1271 return;
1272 }
1273 if (state->get() == ALLOCATING) {
1274 state->set(RELEASING);
1275 // With the altered state allocate() would fail and clean up.
1276 if (sendCallback) {
1277 state.unlock();
1278 mCallback->onReleaseCompleted();
1279 state.lock();
1280 }
1281 return;
1282 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001283 if (state->get() == STARTING
1284 || state->get() == RUNNING
1285 || state->get() == STOPPING) {
1286 // Input surface may have been started, so clean up is needed.
1287 clearInputSurfaceIfNeeded = true;
1288 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001289 state->set(RELEASING);
1290 }
1291
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001292 if (clearInputSurfaceIfNeeded) {
1293 Mutexed<Config>::Locked config(mConfig);
1294 if (config->mInputSurface) {
1295 config->mInputSurface->disconnect();
1296 config->mInputSurface = nullptr;
1297 }
1298 }
1299
Pawin Vongmasa36653902018-11-15 00:10:25 -08001300 mChannel->stop();
1301 // thiz holds strong ref to this while the thread is running.
1302 sp<CCodec> thiz(this);
1303 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1304}
1305
1306void CCodec::release(bool sendCallback) {
1307 std::shared_ptr<Codec2Client::Component> comp;
1308 {
1309 Mutexed<State>::Locked state(mState);
1310 if (state->get() == RELEASED) {
1311 if (sendCallback) {
1312 state.unlock();
1313 mCallback->onReleaseCompleted();
1314 state.lock();
1315 }
1316 return;
1317 }
1318 comp = state->comp;
1319 }
1320 comp->release();
1321
1322 {
1323 Mutexed<State>::Locked state(mState);
1324 state->set(RELEASED);
1325 state->comp.reset();
1326 }
1327 if (sendCallback) {
1328 mCallback->onReleaseCompleted();
1329 }
1330}
1331
1332status_t CCodec::setSurface(const sp<Surface> &surface) {
1333 return mChannel->setSurface(surface);
1334}
1335
1336void CCodec::signalFlush() {
1337 status_t err = [this] {
1338 Mutexed<State>::Locked state(mState);
1339 if (state->get() == FLUSHED) {
1340 return ALREADY_EXISTS;
1341 }
1342 if (state->get() != RUNNING) {
1343 return UNKNOWN_ERROR;
1344 }
1345 state->set(FLUSHING);
1346 return OK;
1347 }();
1348 switch (err) {
1349 case ALREADY_EXISTS:
1350 mCallback->onFlushCompleted();
1351 return;
1352 case OK:
1353 break;
1354 default:
1355 mCallback->onError(err, ACTION_CODE_FATAL);
1356 return;
1357 }
1358
1359 mChannel->stop();
1360 (new AMessage(kWhatFlush, this))->post();
1361}
1362
1363void CCodec::flush() {
1364 std::shared_ptr<Codec2Client::Component> comp;
1365 auto checkFlushing = [this, &comp] {
1366 Mutexed<State>::Locked state(mState);
1367 if (state->get() != FLUSHING) {
1368 return UNKNOWN_ERROR;
1369 }
1370 comp = state->comp;
1371 return OK;
1372 };
1373 if (tryAndReportOnError(checkFlushing) != OK) {
1374 return;
1375 }
1376
1377 std::list<std::unique_ptr<C2Work>> flushedWork;
1378 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1379 {
1380 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1381 flushedWork.splice(flushedWork.end(), *queue);
1382 }
1383 if (err != C2_OK) {
1384 // TODO: convert err into status_t
1385 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1386 }
1387
1388 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001389
1390 {
1391 Mutexed<State>::Locked state(mState);
1392 state->set(FLUSHED);
1393 }
1394 mCallback->onFlushCompleted();
1395}
1396
1397void CCodec::signalResume() {
1398 auto setResuming = [this] {
1399 Mutexed<State>::Locked state(mState);
1400 if (state->get() != FLUSHED) {
1401 return UNKNOWN_ERROR;
1402 }
1403 state->set(RESUMING);
1404 return OK;
1405 };
1406 if (tryAndReportOnError(setResuming) != OK) {
1407 return;
1408 }
1409
1410 (void)mChannel->start(nullptr, nullptr);
1411
1412 {
1413 Mutexed<State>::Locked state(mState);
1414 if (state->get() != RESUMING) {
1415 state.unlock();
1416 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1417 state.lock();
1418 return;
1419 }
1420 state->set(RUNNING);
1421 }
1422
1423 (void)mChannel->requestInitialInputBuffers();
1424}
1425
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001426void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001427 std::shared_ptr<Codec2Client::Component> comp;
1428 auto checkState = [this, &comp] {
1429 Mutexed<State>::Locked state(mState);
1430 if (state->get() == RELEASED) {
1431 return INVALID_OPERATION;
1432 }
1433 comp = state->comp;
1434 return OK;
1435 };
1436 if (tryAndReportOnError(checkState) != OK) {
1437 return;
1438 }
1439
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001440 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1441 // the behavior here.
1442 sp<AMessage> params = msg;
1443 int32_t bitrate;
1444 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1445 params = msg->dup();
1446 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1447 }
1448
Pawin Vongmasa36653902018-11-15 00:10:25 -08001449 Mutexed<Config>::Locked config(mConfig);
1450
1451 /**
1452 * Handle input surface parameters
1453 */
1454 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1455 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
1456 (void)params->findInt64("time-offset-us", &config->mISConfig->mTimeOffsetUs);
1457
1458 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1459 config->mISConfig->mStopped = false;
1460 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1461 config->mISConfig->mStopped = true;
1462 }
1463
1464 int32_t value;
1465 if (params->findInt32("drop-input-frames", &value)) {
1466 config->mISConfig->mSuspended = value;
1467 config->mISConfig->mSuspendAtUs = -1;
1468 (void)params->findInt64("drop-start-time-us", &config->mISConfig->mSuspendAtUs);
1469 }
1470
1471 (void)config->mInputSurface->configure(*config->mISConfig);
1472 if (config->mISConfig->mStopped) {
1473 config->mInputFormat->setInt64(
1474 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1475 }
1476 }
1477
1478 std::vector<std::unique_ptr<C2Param>> configUpdate;
1479 (void)config->getConfigUpdateFromSdkParams(
1480 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1481 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1482 // Parameter synchronization is not defined when using input surface. For now, route
1483 // these directly to the component.
1484 if (config->mInputSurface == nullptr
1485 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1486 || comp->getName().find("c2.android.") == 0)) {
1487 mChannel->setParameters(configUpdate);
1488 } else {
1489 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1490 }
1491}
1492
1493void CCodec::signalEndOfInputStream() {
1494 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1495}
1496
1497void CCodec::signalRequestIDRFrame() {
1498 std::shared_ptr<Codec2Client::Component> comp;
1499 {
1500 Mutexed<State>::Locked state(mState);
1501 if (state->get() == RELEASED) {
1502 ALOGD("no IDR request sent since component is released");
1503 return;
1504 }
1505 comp = state->comp;
1506 }
1507 ALOGV("request IDR");
1508 Mutexed<Config>::Locked config(mConfig);
1509 std::vector<std::unique_ptr<C2Param>> params;
1510 params.push_back(
1511 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1512 config->setParameters(comp, params, C2_MAY_BLOCK);
1513}
1514
Wonsik Kimab34ed62019-01-31 15:28:46 -08001515void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001516 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001517 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1518 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001519 }
1520 (new AMessage(kWhatWorkDone, this))->post();
1521}
1522
Wonsik Kimab34ed62019-01-31 15:28:46 -08001523void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1524 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525}
1526
1527void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1528 TimePoint now = std::chrono::steady_clock::now();
1529 CCodecWatchdog::getInstance()->watch(this);
1530 switch (msg->what()) {
1531 case kWhatAllocate: {
1532 // C2ComponentStore::createComponent() should return within 100ms.
1533 setDeadline(now, 150ms, "allocate");
1534 sp<RefBase> obj;
1535 CHECK(msg->findObject("codecInfo", &obj));
1536 allocate((MediaCodecInfo *)obj.get());
1537 break;
1538 }
1539 case kWhatConfigure: {
1540 // C2Component::commit_sm() should return within 5ms.
1541 setDeadline(now, 250ms, "configure");
1542 sp<AMessage> format;
1543 CHECK(msg->findMessage("format", &format));
1544 configure(format);
1545 break;
1546 }
1547 case kWhatStart: {
1548 // C2Component::start() should return within 500ms.
1549 setDeadline(now, 550ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001550 start();
1551 break;
1552 }
1553 case kWhatStop: {
1554 // C2Component::stop() should return within 500ms.
1555 setDeadline(now, 550ms, "stop");
1556 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001557 break;
1558 }
1559 case kWhatFlush: {
1560 // C2Component::flush_sm() should return within 5ms.
1561 setDeadline(now, 50ms, "flush");
1562 flush();
1563 break;
1564 }
1565 case kWhatCreateInputSurface: {
1566 // Surface operations may be briefly blocking.
1567 setDeadline(now, 100ms, "createInputSurface");
1568 createInputSurface();
1569 break;
1570 }
1571 case kWhatSetInputSurface: {
1572 // Surface operations may be briefly blocking.
1573 setDeadline(now, 100ms, "setInputSurface");
1574 sp<RefBase> obj;
1575 CHECK(msg->findObject("surface", &obj));
1576 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1577 setInputSurface(surface);
1578 break;
1579 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001580 case kWhatWorkDone: {
1581 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001582 bool shouldPost = false;
1583 {
1584 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1585 if (queue->empty()) {
1586 break;
1587 }
1588 work.swap(queue->front());
1589 queue->pop_front();
1590 shouldPost = !queue->empty();
1591 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001592 if (shouldPost) {
1593 (new AMessage(kWhatWorkDone, this))->post();
1594 }
1595
Pawin Vongmasa36653902018-11-15 00:10:25 -08001596 // handle configuration changes in work done
1597 Mutexed<Config>::Locked config(mConfig);
1598 bool changed = false;
1599 Config::Watcher<C2StreamInitDataInfo::output> initData =
1600 config->watch<C2StreamInitDataInfo::output>();
1601 if (!work->worklets.empty()
1602 && (work->worklets.front()->output.flags
1603 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1604
1605 // copy buffer info to config
1606 std::vector<std::unique_ptr<C2Param>> updates =
1607 std::move(work->worklets.front()->output.configUpdate);
1608 unsigned stream = 0;
1609 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1610 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1611 // move all info into output-stream #0 domain
1612 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1613 }
1614 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1615 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1616 // block.crop().left, block.crop().top,
1617 // block.crop().width, block.crop().height,
1618 // block.width(), block.height());
1619 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1620 updates.emplace_back(new C2StreamPictureSizeInfo::output(
1621 stream, block.width(), block.height()));
1622 break; // for now only do the first block
1623 }
1624 ++stream;
1625 }
1626
1627 changed = config->updateConfiguration(updates, config->mOutputDomain);
1628
1629 // copy standard infos to graphic buffers if not already present (otherwise, we
1630 // may overwrite the actual intermediate value with a final value)
1631 stream = 0;
1632 const static std::vector<C2Param::Index> stdGfxInfos = {
1633 C2StreamRotationInfo::output::PARAM_TYPE,
1634 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1635 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1636 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001637 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001638 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1639 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1640 };
1641 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1642 if (buf->data().graphicBlocks().size()) {
1643 for (C2Param::Index ix : stdGfxInfos) {
1644 if (!buf->hasInfo(ix)) {
1645 const C2Param *param =
1646 config->getConfigParameterValue(ix.withStream(stream));
1647 if (param) {
1648 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1649 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1650 }
1651 }
1652 }
1653 }
1654 ++stream;
1655 }
1656 }
1657 mChannel->onWorkDone(
1658 std::move(work), changed ? config->mOutputFormat : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001659 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001660 break;
1661 }
1662 case kWhatWatch: {
1663 // watch message already posted; no-op.
1664 break;
1665 }
1666 default: {
1667 ALOGE("unrecognized message");
1668 break;
1669 }
1670 }
1671 setDeadline(TimePoint::max(), 0ms, "none");
1672}
1673
1674void CCodec::setDeadline(
1675 const TimePoint &now,
1676 const std::chrono::milliseconds &timeout,
1677 const char *name) {
1678 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1679 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1680 deadline->set(now + (timeout * mult), name);
1681}
1682
1683void CCodec::initiateReleaseIfStuck() {
1684 std::string name;
1685 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001686 {
1687 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001688 if (deadline->get() < std::chrono::steady_clock::now()) {
1689 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001690 }
1691 if (deadline->get() != TimePoint::max()) {
1692 pendingDeadline = true;
1693 }
1694 }
1695 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001696 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1697 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1698 if (elapsed >= kWorkDurationThreshold) {
1699 name = "queue";
1700 }
1701 if (elapsed > 0s) {
1702 pendingDeadline = true;
1703 }
1704 }
1705 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001706 // We're not stuck.
1707 if (pendingDeadline) {
1708 // If we are not stuck yet but still has deadline coming up,
1709 // post watch message to check back later.
1710 (new AMessage(kWhatWatch, this))->post();
1711 }
1712 return;
1713 }
1714
1715 ALOGW("previous call to %s exceeded timeout", name.c_str());
1716 initiateRelease(false);
1717 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1718}
1719
Pawin Vongmasa36653902018-11-15 00:10:25 -08001720} // namespace android
1721
1722extern "C" android::CodecBase *CreateCodec() {
1723 return new android::CCodec;
1724}
1725
Lajos Molnar47118272019-01-31 16:28:04 -08001726// Create Codec 2.0 input surface
Pawin Vongmasa36653902018-11-15 00:10:25 -08001727extern "C" android::PersistentSurface *CreateInputSurface() {
1728 // Attempt to create a Codec2's input surface.
1729 std::shared_ptr<android::Codec2Client::InputSurface> inputSurface =
1730 android::Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001731 if (!inputSurface) {
1732 return nullptr;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001733 }
Lajos Molnar47118272019-01-31 16:28:04 -08001734 return new android::PersistentSurface(
1735 inputSurface->getGraphicBufferProducer(),
1736 static_cast<android::sp<android::hidl::base::V1_0::IBase>>(
1737 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001738}
1739