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