blob: ed1f85b844271100c5d0803fa48a9369d9c9b901 [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
940void CCodec::createInputSurface() {
941 status_t err;
942 sp<IGraphicBufferProducer> bufferProducer;
943
944 sp<AMessage> inputFormat;
945 sp<AMessage> outputFormat;
946 {
947 Mutexed<Config>::Locked config(mConfig);
948 inputFormat = config->mInputFormat;
949 outputFormat = config->mOutputFormat;
950 }
951
952 std::shared_ptr<PersistentSurface> persistentSurface(CreateInputSurface());
953
954 if (persistentSurface->getHidlTarget()) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800955 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800956 persistentSurface->getHidlTarget());
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800957 if (!hidlInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800958 ALOGE("Corrupted input surface");
959 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
960 return;
961 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800962 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
963 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800964 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800965 inputSurface));
966 bufferProducer = inputSurface->getGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800967 } else {
968 int32_t width = 0;
969 (void)outputFormat->findInt32("width", &width);
970 int32_t height = 0;
971 (void)outputFormat->findInt32("height", &height);
972 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
973 persistentSurface->getBufferSource(), width, height));
974 bufferProducer = persistentSurface->getBufferProducer();
975 }
976
977 if (err != OK) {
978 ALOGE("Failed to set up input surface: %d", err);
979 mCallback->onInputSurfaceCreationFailed(err);
980 return;
981 }
982
983 mCallback->onInputSurfaceCreated(
984 inputFormat,
985 outputFormat,
986 new BufferProducerWrapper(bufferProducer));
987}
988
989status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
990 Mutexed<Config>::Locked config(mConfig);
991 config->mUsingSurface = true;
992
993 // we are now using surface - apply default color aspects to input format - as well as
994 // get dataspace
995 bool inputFormatChanged = config->updateFormats(config->IS_INPUT);
996 ALOGD("input format %s to %s",
997 inputFormatChanged ? "changed" : "unchanged",
998 config->mInputFormat->debugString().c_str());
999
1000 // configure dataspace
1001 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1002 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1003 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1004 surface->setDataSpace(dataSpace);
1005
1006 status_t err = mChannel->setInputSurface(surface);
1007 if (err != OK) {
1008 // undo input format update
1009 config->mUsingSurface = false;
1010 (void)config->updateFormats(config->IS_INPUT);
1011 return err;
1012 }
1013 config->mInputSurface = surface;
1014
1015 if (config->mISConfig) {
1016 surface->configure(*config->mISConfig);
1017 } else {
1018 ALOGD("ISConfig: no configuration");
1019 }
1020
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001021 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001022}
1023
1024void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1025 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1026 msg->setObject("surface", surface);
1027 msg->post();
1028}
1029
1030void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1031 sp<AMessage> inputFormat;
1032 sp<AMessage> outputFormat;
1033 {
1034 Mutexed<Config>::Locked config(mConfig);
1035 inputFormat = config->mInputFormat;
1036 outputFormat = config->mOutputFormat;
1037 }
1038 auto hidlTarget = surface->getHidlTarget();
1039 if (hidlTarget) {
1040 sp<IInputSurface> inputSurface =
1041 IInputSurface::castFrom(hidlTarget);
1042 if (!inputSurface) {
1043 ALOGE("Failed to set input surface: Corrupted surface.");
1044 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1045 return;
1046 }
1047 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1048 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1049 if (err != OK) {
1050 ALOGE("Failed to set up input surface: %d", err);
1051 mCallback->onInputSurfaceDeclined(err);
1052 return;
1053 }
1054 } else {
1055 int32_t width = 0;
1056 (void)outputFormat->findInt32("width", &width);
1057 int32_t height = 0;
1058 (void)outputFormat->findInt32("height", &height);
1059 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
1060 surface->getBufferSource(), width, height));
1061 if (err != OK) {
1062 ALOGE("Failed to set up input surface: %d", err);
1063 mCallback->onInputSurfaceDeclined(err);
1064 return;
1065 }
1066 }
1067 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1068}
1069
1070void CCodec::initiateStart() {
1071 auto setStarting = [this] {
1072 Mutexed<State>::Locked state(mState);
1073 if (state->get() != ALLOCATED) {
1074 return UNKNOWN_ERROR;
1075 }
1076 state->set(STARTING);
1077 return OK;
1078 };
1079 if (tryAndReportOnError(setStarting) != OK) {
1080 return;
1081 }
1082
1083 (new AMessage(kWhatStart, this))->post();
1084}
1085
1086void CCodec::start() {
1087 std::shared_ptr<Codec2Client::Component> comp;
1088 auto checkStarting = [this, &comp] {
1089 Mutexed<State>::Locked state(mState);
1090 if (state->get() != STARTING) {
1091 return UNKNOWN_ERROR;
1092 }
1093 comp = state->comp;
1094 return OK;
1095 };
1096 if (tryAndReportOnError(checkStarting) != OK) {
1097 return;
1098 }
1099
1100 c2_status_t err = comp->start();
1101 if (err != C2_OK) {
1102 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1103 ACTION_CODE_FATAL);
1104 return;
1105 }
1106 sp<AMessage> inputFormat;
1107 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001108 status_t err2 = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001109 {
1110 Mutexed<Config>::Locked config(mConfig);
1111 inputFormat = config->mInputFormat;
1112 outputFormat = config->mOutputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001113 if (config->mInputSurface) {
1114 err2 = config->mInputSurface->start();
1115 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001116 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001117 if (err2 != OK) {
1118 mCallback->onError(err2, ACTION_CODE_FATAL);
1119 return;
1120 }
1121 err2 = mChannel->start(inputFormat, outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001122 if (err2 != OK) {
1123 mCallback->onError(err2, ACTION_CODE_FATAL);
1124 return;
1125 }
1126
1127 auto setRunning = [this] {
1128 Mutexed<State>::Locked state(mState);
1129 if (state->get() != STARTING) {
1130 return UNKNOWN_ERROR;
1131 }
1132 state->set(RUNNING);
1133 return OK;
1134 };
1135 if (tryAndReportOnError(setRunning) != OK) {
1136 return;
1137 }
1138 mCallback->onStartCompleted();
1139
1140 (void)mChannel->requestInitialInputBuffers();
1141}
1142
1143void CCodec::initiateShutdown(bool keepComponentAllocated) {
1144 if (keepComponentAllocated) {
1145 initiateStop();
1146 } else {
1147 initiateRelease();
1148 }
1149}
1150
1151void CCodec::initiateStop() {
1152 {
1153 Mutexed<State>::Locked state(mState);
1154 if (state->get() == ALLOCATED
1155 || state->get() == RELEASED
1156 || state->get() == STOPPING
1157 || state->get() == RELEASING) {
1158 // We're already stopped, released, or doing it right now.
1159 state.unlock();
1160 mCallback->onStopCompleted();
1161 state.lock();
1162 return;
1163 }
1164 state->set(STOPPING);
1165 }
1166
1167 mChannel->stop();
1168 (new AMessage(kWhatStop, this))->post();
1169}
1170
1171void CCodec::stop() {
1172 std::shared_ptr<Codec2Client::Component> comp;
1173 {
1174 Mutexed<State>::Locked state(mState);
1175 if (state->get() == RELEASING) {
1176 state.unlock();
1177 // We're already stopped or release is in progress.
1178 mCallback->onStopCompleted();
1179 state.lock();
1180 return;
1181 } else if (state->get() != STOPPING) {
1182 state.unlock();
1183 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1184 state.lock();
1185 return;
1186 }
1187 comp = state->comp;
1188 }
1189 status_t err = comp->stop();
1190 if (err != C2_OK) {
1191 // TODO: convert err into status_t
1192 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1193 }
1194
1195 {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001196 Mutexed<Config>::Locked config(mConfig);
1197 if (config->mInputSurface) {
1198 config->mInputSurface->disconnect();
1199 config->mInputSurface = nullptr;
1200 }
1201 }
1202 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001203 Mutexed<State>::Locked state(mState);
1204 if (state->get() == STOPPING) {
1205 state->set(ALLOCATED);
1206 }
1207 }
1208 mCallback->onStopCompleted();
1209}
1210
1211void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001212 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001213 {
1214 Mutexed<State>::Locked state(mState);
1215 if (state->get() == RELEASED || state->get() == RELEASING) {
1216 // We're already released or doing it right now.
1217 if (sendCallback) {
1218 state.unlock();
1219 mCallback->onReleaseCompleted();
1220 state.lock();
1221 }
1222 return;
1223 }
1224 if (state->get() == ALLOCATING) {
1225 state->set(RELEASING);
1226 // With the altered state allocate() would fail and clean up.
1227 if (sendCallback) {
1228 state.unlock();
1229 mCallback->onReleaseCompleted();
1230 state.lock();
1231 }
1232 return;
1233 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001234 if (state->get() == STARTING
1235 || state->get() == RUNNING
1236 || state->get() == STOPPING) {
1237 // Input surface may have been started, so clean up is needed.
1238 clearInputSurfaceIfNeeded = true;
1239 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001240 state->set(RELEASING);
1241 }
1242
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001243 if (clearInputSurfaceIfNeeded) {
1244 Mutexed<Config>::Locked config(mConfig);
1245 if (config->mInputSurface) {
1246 config->mInputSurface->disconnect();
1247 config->mInputSurface = nullptr;
1248 }
1249 }
1250
Pawin Vongmasa36653902018-11-15 00:10:25 -08001251 mChannel->stop();
1252 // thiz holds strong ref to this while the thread is running.
1253 sp<CCodec> thiz(this);
1254 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1255}
1256
1257void CCodec::release(bool sendCallback) {
1258 std::shared_ptr<Codec2Client::Component> comp;
1259 {
1260 Mutexed<State>::Locked state(mState);
1261 if (state->get() == RELEASED) {
1262 if (sendCallback) {
1263 state.unlock();
1264 mCallback->onReleaseCompleted();
1265 state.lock();
1266 }
1267 return;
1268 }
1269 comp = state->comp;
1270 }
1271 comp->release();
1272
1273 {
1274 Mutexed<State>::Locked state(mState);
1275 state->set(RELEASED);
1276 state->comp.reset();
1277 }
1278 if (sendCallback) {
1279 mCallback->onReleaseCompleted();
1280 }
1281}
1282
1283status_t CCodec::setSurface(const sp<Surface> &surface) {
1284 return mChannel->setSurface(surface);
1285}
1286
1287void CCodec::signalFlush() {
1288 status_t err = [this] {
1289 Mutexed<State>::Locked state(mState);
1290 if (state->get() == FLUSHED) {
1291 return ALREADY_EXISTS;
1292 }
1293 if (state->get() != RUNNING) {
1294 return UNKNOWN_ERROR;
1295 }
1296 state->set(FLUSHING);
1297 return OK;
1298 }();
1299 switch (err) {
1300 case ALREADY_EXISTS:
1301 mCallback->onFlushCompleted();
1302 return;
1303 case OK:
1304 break;
1305 default:
1306 mCallback->onError(err, ACTION_CODE_FATAL);
1307 return;
1308 }
1309
1310 mChannel->stop();
1311 (new AMessage(kWhatFlush, this))->post();
1312}
1313
1314void CCodec::flush() {
1315 std::shared_ptr<Codec2Client::Component> comp;
1316 auto checkFlushing = [this, &comp] {
1317 Mutexed<State>::Locked state(mState);
1318 if (state->get() != FLUSHING) {
1319 return UNKNOWN_ERROR;
1320 }
1321 comp = state->comp;
1322 return OK;
1323 };
1324 if (tryAndReportOnError(checkFlushing) != OK) {
1325 return;
1326 }
1327
1328 std::list<std::unique_ptr<C2Work>> flushedWork;
1329 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1330 {
1331 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1332 flushedWork.splice(flushedWork.end(), *queue);
1333 }
1334 if (err != C2_OK) {
1335 // TODO: convert err into status_t
1336 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1337 }
1338
1339 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001340
1341 {
1342 Mutexed<State>::Locked state(mState);
1343 state->set(FLUSHED);
1344 }
1345 mCallback->onFlushCompleted();
1346}
1347
1348void CCodec::signalResume() {
1349 auto setResuming = [this] {
1350 Mutexed<State>::Locked state(mState);
1351 if (state->get() != FLUSHED) {
1352 return UNKNOWN_ERROR;
1353 }
1354 state->set(RESUMING);
1355 return OK;
1356 };
1357 if (tryAndReportOnError(setResuming) != OK) {
1358 return;
1359 }
1360
1361 (void)mChannel->start(nullptr, nullptr);
1362
1363 {
1364 Mutexed<State>::Locked state(mState);
1365 if (state->get() != RESUMING) {
1366 state.unlock();
1367 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1368 state.lock();
1369 return;
1370 }
1371 state->set(RUNNING);
1372 }
1373
1374 (void)mChannel->requestInitialInputBuffers();
1375}
1376
1377void CCodec::signalSetParameters(const sp<AMessage> &params) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001378 setParameters(params);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001379}
1380
1381void CCodec::setParameters(const sp<AMessage> &params) {
1382 std::shared_ptr<Codec2Client::Component> comp;
1383 auto checkState = [this, &comp] {
1384 Mutexed<State>::Locked state(mState);
1385 if (state->get() == RELEASED) {
1386 return INVALID_OPERATION;
1387 }
1388 comp = state->comp;
1389 return OK;
1390 };
1391 if (tryAndReportOnError(checkState) != OK) {
1392 return;
1393 }
1394
1395 Mutexed<Config>::Locked config(mConfig);
1396
1397 /**
1398 * Handle input surface parameters
1399 */
1400 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1401 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
1402 (void)params->findInt64("time-offset-us", &config->mISConfig->mTimeOffsetUs);
1403
1404 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1405 config->mISConfig->mStopped = false;
1406 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1407 config->mISConfig->mStopped = true;
1408 }
1409
1410 int32_t value;
1411 if (params->findInt32("drop-input-frames", &value)) {
1412 config->mISConfig->mSuspended = value;
1413 config->mISConfig->mSuspendAtUs = -1;
1414 (void)params->findInt64("drop-start-time-us", &config->mISConfig->mSuspendAtUs);
1415 }
1416
1417 (void)config->mInputSurface->configure(*config->mISConfig);
1418 if (config->mISConfig->mStopped) {
1419 config->mInputFormat->setInt64(
1420 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1421 }
1422 }
1423
1424 std::vector<std::unique_ptr<C2Param>> configUpdate;
1425 (void)config->getConfigUpdateFromSdkParams(
1426 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1427 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1428 // Parameter synchronization is not defined when using input surface. For now, route
1429 // these directly to the component.
1430 if (config->mInputSurface == nullptr
1431 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1432 || comp->getName().find("c2.android.") == 0)) {
1433 mChannel->setParameters(configUpdate);
1434 } else {
1435 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1436 }
1437}
1438
1439void CCodec::signalEndOfInputStream() {
1440 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1441}
1442
1443void CCodec::signalRequestIDRFrame() {
1444 std::shared_ptr<Codec2Client::Component> comp;
1445 {
1446 Mutexed<State>::Locked state(mState);
1447 if (state->get() == RELEASED) {
1448 ALOGD("no IDR request sent since component is released");
1449 return;
1450 }
1451 comp = state->comp;
1452 }
1453 ALOGV("request IDR");
1454 Mutexed<Config>::Locked config(mConfig);
1455 std::vector<std::unique_ptr<C2Param>> params;
1456 params.push_back(
1457 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1458 config->setParameters(comp, params, C2_MAY_BLOCK);
1459}
1460
Wonsik Kimab34ed62019-01-31 15:28:46 -08001461void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001462 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001463 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1464 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001465 }
1466 (new AMessage(kWhatWorkDone, this))->post();
1467}
1468
Wonsik Kimab34ed62019-01-31 15:28:46 -08001469void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1470 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001471}
1472
1473void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1474 TimePoint now = std::chrono::steady_clock::now();
1475 CCodecWatchdog::getInstance()->watch(this);
1476 switch (msg->what()) {
1477 case kWhatAllocate: {
1478 // C2ComponentStore::createComponent() should return within 100ms.
1479 setDeadline(now, 150ms, "allocate");
1480 sp<RefBase> obj;
1481 CHECK(msg->findObject("codecInfo", &obj));
1482 allocate((MediaCodecInfo *)obj.get());
1483 break;
1484 }
1485 case kWhatConfigure: {
1486 // C2Component::commit_sm() should return within 5ms.
1487 setDeadline(now, 250ms, "configure");
1488 sp<AMessage> format;
1489 CHECK(msg->findMessage("format", &format));
1490 configure(format);
1491 break;
1492 }
1493 case kWhatStart: {
1494 // C2Component::start() should return within 500ms.
1495 setDeadline(now, 550ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001496 start();
1497 break;
1498 }
1499 case kWhatStop: {
1500 // C2Component::stop() should return within 500ms.
1501 setDeadline(now, 550ms, "stop");
1502 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001503 break;
1504 }
1505 case kWhatFlush: {
1506 // C2Component::flush_sm() should return within 5ms.
1507 setDeadline(now, 50ms, "flush");
1508 flush();
1509 break;
1510 }
1511 case kWhatCreateInputSurface: {
1512 // Surface operations may be briefly blocking.
1513 setDeadline(now, 100ms, "createInputSurface");
1514 createInputSurface();
1515 break;
1516 }
1517 case kWhatSetInputSurface: {
1518 // Surface operations may be briefly blocking.
1519 setDeadline(now, 100ms, "setInputSurface");
1520 sp<RefBase> obj;
1521 CHECK(msg->findObject("surface", &obj));
1522 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1523 setInputSurface(surface);
1524 break;
1525 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001526 case kWhatWorkDone: {
1527 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001528 bool shouldPost = false;
1529 {
1530 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1531 if (queue->empty()) {
1532 break;
1533 }
1534 work.swap(queue->front());
1535 queue->pop_front();
1536 shouldPost = !queue->empty();
1537 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001538 if (shouldPost) {
1539 (new AMessage(kWhatWorkDone, this))->post();
1540 }
1541
Pawin Vongmasa36653902018-11-15 00:10:25 -08001542 // handle configuration changes in work done
1543 Mutexed<Config>::Locked config(mConfig);
1544 bool changed = false;
1545 Config::Watcher<C2StreamInitDataInfo::output> initData =
1546 config->watch<C2StreamInitDataInfo::output>();
1547 if (!work->worklets.empty()
1548 && (work->worklets.front()->output.flags
1549 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1550
1551 // copy buffer info to config
1552 std::vector<std::unique_ptr<C2Param>> updates =
1553 std::move(work->worklets.front()->output.configUpdate);
1554 unsigned stream = 0;
1555 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1556 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1557 // move all info into output-stream #0 domain
1558 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1559 }
1560 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1561 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1562 // block.crop().left, block.crop().top,
1563 // block.crop().width, block.crop().height,
1564 // block.width(), block.height());
1565 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1566 updates.emplace_back(new C2StreamPictureSizeInfo::output(
1567 stream, block.width(), block.height()));
1568 break; // for now only do the first block
1569 }
1570 ++stream;
1571 }
1572
1573 changed = config->updateConfiguration(updates, config->mOutputDomain);
1574
1575 // copy standard infos to graphic buffers if not already present (otherwise, we
1576 // may overwrite the actual intermediate value with a final value)
1577 stream = 0;
1578 const static std::vector<C2Param::Index> stdGfxInfos = {
1579 C2StreamRotationInfo::output::PARAM_TYPE,
1580 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1581 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1582 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001583 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1585 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1586 };
1587 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1588 if (buf->data().graphicBlocks().size()) {
1589 for (C2Param::Index ix : stdGfxInfos) {
1590 if (!buf->hasInfo(ix)) {
1591 const C2Param *param =
1592 config->getConfigParameterValue(ix.withStream(stream));
1593 if (param) {
1594 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1595 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1596 }
1597 }
1598 }
1599 }
1600 ++stream;
1601 }
1602 }
1603 mChannel->onWorkDone(
1604 std::move(work), changed ? config->mOutputFormat : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001605 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001606 break;
1607 }
1608 case kWhatWatch: {
1609 // watch message already posted; no-op.
1610 break;
1611 }
1612 default: {
1613 ALOGE("unrecognized message");
1614 break;
1615 }
1616 }
1617 setDeadline(TimePoint::max(), 0ms, "none");
1618}
1619
1620void CCodec::setDeadline(
1621 const TimePoint &now,
1622 const std::chrono::milliseconds &timeout,
1623 const char *name) {
1624 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1625 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1626 deadline->set(now + (timeout * mult), name);
1627}
1628
1629void CCodec::initiateReleaseIfStuck() {
1630 std::string name;
1631 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001632 {
1633 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001634 if (deadline->get() < std::chrono::steady_clock::now()) {
1635 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001636 }
1637 if (deadline->get() != TimePoint::max()) {
1638 pendingDeadline = true;
1639 }
1640 }
1641 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001642 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1643 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1644 if (elapsed >= kWorkDurationThreshold) {
1645 name = "queue";
1646 }
1647 if (elapsed > 0s) {
1648 pendingDeadline = true;
1649 }
1650 }
1651 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001652 // We're not stuck.
1653 if (pendingDeadline) {
1654 // If we are not stuck yet but still has deadline coming up,
1655 // post watch message to check back later.
1656 (new AMessage(kWhatWatch, this))->post();
1657 }
1658 return;
1659 }
1660
1661 ALOGW("previous call to %s exceeded timeout", name.c_str());
1662 initiateRelease(false);
1663 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1664}
1665
Pawin Vongmasa36653902018-11-15 00:10:25 -08001666} // namespace android
1667
1668extern "C" android::CodecBase *CreateCodec() {
1669 return new android::CCodec;
1670}
1671
1672extern "C" android::PersistentSurface *CreateInputSurface() {
1673 // Attempt to create a Codec2's input surface.
1674 std::shared_ptr<android::Codec2Client::InputSurface> inputSurface =
1675 android::Codec2Client::CreateInputSurface();
1676 if (inputSurface) {
1677 return new android::PersistentSurface(
1678 inputSurface->getGraphicBufferProducer(),
1679 static_cast<android::sp<android::hidl::base::V1_0::IBase>>(
1680 inputSurface->getHalInterface()));
1681 }
1682
1683 // Fall back to OMX.
1684 using namespace android::hardware::media::omx::V1_0;
1685 using namespace android::hardware::media::omx::V1_0::utils;
1686 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1687 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1688 android::sp<IOmx> omx = IOmx::getService();
1689 typedef android::hardware::graphics::bufferqueue::V1_0::
1690 IGraphicBufferProducer HGraphicBufferProducer;
1691 typedef android::hardware::media::omx::V1_0::
1692 IGraphicBufferSource HGraphicBufferSource;
1693 OmxStatus s;
1694 android::sp<HGraphicBufferProducer> gbp;
1695 android::sp<HGraphicBufferSource> gbs;
1696 android::Return<void> transStatus = omx->createInputSurface(
1697 [&s, &gbp, &gbs](
1698 OmxStatus status,
1699 const android::sp<HGraphicBufferProducer>& producer,
1700 const android::sp<HGraphicBufferSource>& source) {
1701 s = status;
1702 gbp = producer;
1703 gbs = source;
1704 });
1705 if (transStatus.isOk() && s == OmxStatus::OK) {
1706 return new android::PersistentSurface(
1707 new H2BGraphicBufferProducer(gbp),
1708 sp<::android::IGraphicBufferSource>(
1709 new LWGraphicBufferSource(gbs)));
1710 }
1711
1712 return nullptr;
1713}
1714