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