blob: 008e20e985ea9e1c8c55fd12a472198265435199 [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>
Pawin Vongmasa36653902018-11-15 00:10:25 -080043
44#include "C2OMXNode.h"
45#include "CCodec.h"
46#include "CCodecBufferChannel.h"
47#include "InputSurfaceWrapper.h"
48
49extern "C" android::PersistentSurface *CreateInputSurface();
50
51namespace android {
52
53using namespace std::chrono_literals;
54using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
55using android::base::StringPrintf;
56using BGraphicBufferSource = ::android::IGraphicBufferSource;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080057using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080058
59namespace {
60
61class CCodecWatchdog : public AHandler {
62private:
63 enum {
64 kWhatWatch,
65 };
66 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
67
68public:
69 static sp<CCodecWatchdog> getInstance() {
70 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
71 static std::once_flag flag;
72 // Call Init() only once.
73 std::call_once(flag, Init, instance);
74 return instance;
75 }
76
77 ~CCodecWatchdog() = default;
78
79 void watch(sp<CCodec> codec) {
80 bool shouldPost = false;
81 {
82 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
83 // If a watch message is in flight, piggy-back this instance as well.
84 // Otherwise, post a new watch message.
85 shouldPost = codecs->empty();
86 codecs->emplace(codec);
87 }
88 if (shouldPost) {
89 ALOGV("posting watch message");
90 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
91 }
92 }
93
94protected:
95 void onMessageReceived(const sp<AMessage> &msg) {
96 switch (msg->what()) {
97 case kWhatWatch: {
98 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
99 ALOGV("watch for %zu codecs", codecs->size());
100 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
101 sp<CCodec> codec = it->promote();
102 if (codec == nullptr) {
103 continue;
104 }
105 codec->initiateReleaseIfStuck();
106 }
107 codecs->clear();
108 break;
109 }
110
111 default: {
112 TRESPASS("CCodecWatchdog: unrecognized message");
113 }
114 }
115 }
116
117private:
118 CCodecWatchdog() : mLooper(new ALooper) {}
119
120 static void Init(const sp<CCodecWatchdog> &thiz) {
121 ALOGV("Init");
122 thiz->mLooper->setName("CCodecWatchdog");
123 thiz->mLooper->registerHandler(thiz);
124 thiz->mLooper->start();
125 }
126
127 sp<ALooper> mLooper;
128
129 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
130};
131
132class C2InputSurfaceWrapper : public InputSurfaceWrapper {
133public:
134 explicit C2InputSurfaceWrapper(
135 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
136 mSurface(surface) {
137 }
138
139 ~C2InputSurfaceWrapper() override = default;
140
141 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
142 if (mConnection != nullptr) {
143 return ALREADY_EXISTS;
144 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800145 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800146 }
147
148 void disconnect() override {
149 if (mConnection != nullptr) {
150 mConnection->disconnect();
151 mConnection = nullptr;
152 }
153 }
154
155 status_t start() override {
156 // InputSurface does not distinguish started state
157 return OK;
158 }
159
160 status_t signalEndOfInputStream() override {
161 C2InputSurfaceEosTuning eos(true);
162 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800163 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800164 if (err != C2_OK) {
165 return UNKNOWN_ERROR;
166 }
167 return OK;
168 }
169
170 status_t configure(Config &config __unused) {
171 // TODO
172 return OK;
173 }
174
175private:
176 std::shared_ptr<Codec2Client::InputSurface> mSurface;
177 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
178};
179
180class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
181public:
182// explicit GraphicBufferSourceWrapper(const sp<BGraphicBufferSource> &source) : mSource(source) {}
183 GraphicBufferSourceWrapper(
184 const sp<BGraphicBufferSource> &source,
185 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700186 uint32_t height,
187 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800188 : mSource(source), mWidth(width), mHeight(height) {
189 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700190 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800191 }
192 ~GraphicBufferSourceWrapper() override = default;
193
194 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
195 mNode = new C2OMXNode(comp);
196 mNode->setFrameSize(mWidth, mHeight);
197
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700198 // Usage is queried during configure(), so setting it beforehand.
199 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
200 (void)mNode->setParameter(
201 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
202 &usage, sizeof(usage));
203
Pawin Vongmasa36653902018-11-15 00:10:25 -0800204 // NOTE: we do not use/pass through color aspects from GraphicBufferSource as we
205 // communicate that directly to the component.
206 mSource->configure(mNode, mDataSpace);
207 return OK;
208 }
209
210 void disconnect() override {
211 if (mNode == nullptr) {
212 return;
213 }
214 sp<IOMXBufferSource> source = mNode->getSource();
215 if (source == nullptr) {
216 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
217 return;
218 }
219 source->onOmxIdle();
220 source->onOmxLoaded();
221 mNode.clear();
222 }
223
224 status_t GetStatus(const binder::Status &status) {
225 status_t err = OK;
226 if (!status.isOk()) {
227 err = status.serviceSpecificErrorCode();
228 if (err == OK) {
229 err = status.transactionError();
230 if (err == OK) {
231 // binder status failed, but there is no servie or transaction error
232 err = UNKNOWN_ERROR;
233 }
234 }
235 }
236 return err;
237 }
238
239 status_t start() override {
240 sp<IOMXBufferSource> source = mNode->getSource();
241 if (source == nullptr) {
242 return NO_INIT;
243 }
244 constexpr size_t kNumSlots = 16;
245 for (size_t i = 0; i < kNumSlots; ++i) {
246 source->onInputBufferAdded(i);
247 }
248
249 source->onOmxExecuting();
250 return OK;
251 }
252
253 status_t signalEndOfInputStream() override {
254 return GetStatus(mSource->signalEndOfInputStream());
255 }
256
257 status_t configure(Config &config) {
258 std::stringstream status;
259 status_t err = OK;
260
261 // handle each configuration granually, in case we need to handle part of the configuration
262 // elsewhere
263
264 // TRICKY: we do not unset frame delay repeating
265 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
266 int64_t us = 1e6 / config.mMinFps + 0.5;
267 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
268 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
269 if (res != OK) {
270 status << " (=> " << asString(res) << ")";
271 err = res;
272 }
273 mConfig.mMinFps = config.mMinFps;
274 }
275
276 // pts gap
277 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
278 if (mNode != nullptr) {
279 OMX_PARAM_U32TYPE ptrGapParam = {};
280 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700281 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800282 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
283 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700284 // float -> uint32_t is undefined if the value is negative.
285 // First convert to int32_t to ensure the expected behavior.
286 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800287 (void)mNode->setParameter(
288 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
289 &ptrGapParam, sizeof(ptrGapParam));
290 }
291 }
292
293 // max fps
294 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700295 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800296 && config.mMaxFps != mConfig.mMaxFps) {
297 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
298 status << " maxFps=" << config.mMaxFps;
299 if (res != OK) {
300 status << " (=> " << asString(res) << ")";
301 err = res;
302 }
303 mConfig.mMaxFps = config.mMaxFps;
304 }
305
306 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
307 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
308 status << " timeOffset " << config.mTimeOffsetUs << "us";
309 if (res != OK) {
310 status << " (=> " << asString(res) << ")";
311 err = res;
312 }
313 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
314 }
315
316 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
317 status_t res =
318 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
319 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
320 if (res != OK) {
321 status << " (=> " << asString(res) << ")";
322 err = res;
323 }
324 mConfig.mCaptureFps = config.mCaptureFps;
325 mConfig.mCodedFps = config.mCodedFps;
326 }
327
328 if (config.mStartAtUs != mConfig.mStartAtUs
329 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
330 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
331 status << " start at " << config.mStartAtUs << "us";
332 if (res != OK) {
333 status << " (=> " << asString(res) << ")";
334 err = res;
335 }
336 mConfig.mStartAtUs = config.mStartAtUs;
337 mConfig.mStopped = config.mStopped;
338 }
339
340 // suspend-resume
341 if (config.mSuspended != mConfig.mSuspended) {
342 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
343 status << " " << (config.mSuspended ? "suspend" : "resume")
344 << " at " << config.mSuspendAtUs << "us";
345 if (res != OK) {
346 status << " (=> " << asString(res) << ")";
347 err = res;
348 }
349 mConfig.mSuspended = config.mSuspended;
350 mConfig.mSuspendAtUs = config.mSuspendAtUs;
351 }
352
353 if (config.mStopped != mConfig.mStopped && config.mStopped) {
354 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
355 status << " stop at " << config.mStopAtUs << "us";
356 if (res != OK) {
357 status << " (=> " << asString(res) << ")";
358 err = res;
359 } else {
360 status << " delayUs";
361 res = GetStatus(mSource->getStopTimeOffsetUs(&config.mInputDelayUs));
362 if (res != OK) {
363 status << " (=> " << asString(res) << ")";
364 } else {
365 status << "=" << config.mInputDelayUs << "us";
366 }
367 mConfig.mInputDelayUs = config.mInputDelayUs;
368 }
369 mConfig.mStopAtUs = config.mStopAtUs;
370 mConfig.mStopped = config.mStopped;
371 }
372
373 // color aspects (android._color-aspects)
374
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700375 // consumer usage is queried earlier.
376
Pawin Vongmasa36653902018-11-15 00:10:25 -0800377 ALOGD("ISConfig%s", status.str().c_str());
378 return err;
379 }
380
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700381 void onInputBufferDone(c2_cntr64_t index) override {
382 mNode->onInputBufferDone(index);
383 }
384
Pawin Vongmasa36653902018-11-15 00:10:25 -0800385private:
386 sp<BGraphicBufferSource> mSource;
387 sp<C2OMXNode> mNode;
388 uint32_t mWidth;
389 uint32_t mHeight;
390 Config mConfig;
391};
392
393class Codec2ClientInterfaceWrapper : public C2ComponentStore {
394 std::shared_ptr<Codec2Client> mClient;
395
396public:
397 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
398 : mClient(client) { }
399
400 virtual ~Codec2ClientInterfaceWrapper() = default;
401
402 virtual c2_status_t config_sm(
403 const std::vector<C2Param *> &params,
404 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
405 return mClient->config(params, C2_MAY_BLOCK, failures);
406 };
407
408 virtual c2_status_t copyBuffer(
409 std::shared_ptr<C2GraphicBuffer>,
410 std::shared_ptr<C2GraphicBuffer>) {
411 return C2_OMITTED;
412 }
413
414 virtual c2_status_t createComponent(
415 C2String, std::shared_ptr<C2Component> *const component) {
416 component->reset();
417 return C2_OMITTED;
418 }
419
420 virtual c2_status_t createInterface(
421 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
422 interface->reset();
423 return C2_OMITTED;
424 }
425
426 virtual c2_status_t query_sm(
427 const std::vector<C2Param *> &stackParams,
428 const std::vector<C2Param::Index> &heapParamIndices,
429 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
430 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
431 }
432
433 virtual c2_status_t querySupportedParams_nb(
434 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
435 return mClient->querySupportedParams(params);
436 }
437
438 virtual c2_status_t querySupportedValues_sm(
439 std::vector<C2FieldSupportedValuesQuery> &fields) const {
440 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
441 }
442
443 virtual C2String getName() const {
444 return mClient->getName();
445 }
446
447 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
448 return mClient->getParamReflector();
449 }
450
451 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
452 return std::vector<std::shared_ptr<const C2Component::Traits>>();
453 }
454};
455
456} // namespace
457
458// CCodec::ClientListener
459
460struct CCodec::ClientListener : public Codec2Client::Listener {
461
462 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
463
464 virtual void onWorkDone(
465 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800466 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800467 (void)component;
468 sp<CCodec> codec(mCodec.promote());
469 if (!codec) {
470 return;
471 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800472 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800473 }
474
475 virtual void onTripped(
476 const std::weak_ptr<Codec2Client::Component>& component,
477 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
478 ) override {
479 // TODO
480 (void)component;
481 (void)settingResult;
482 }
483
484 virtual void onError(
485 const std::weak_ptr<Codec2Client::Component>& component,
486 uint32_t errorCode) override {
487 // TODO
488 (void)component;
489 (void)errorCode;
490 }
491
492 virtual void onDeath(
493 const std::weak_ptr<Codec2Client::Component>& component) override {
494 { // Log the death of the component.
495 std::shared_ptr<Codec2Client::Component> comp = component.lock();
496 if (!comp) {
497 ALOGE("Codec2 component died.");
498 } else {
499 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
500 }
501 }
502
503 // Report to MediaCodec.
504 sp<CCodec> codec(mCodec.promote());
505 if (!codec || !codec->mCallback) {
506 return;
507 }
508 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
509 }
510
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800511 virtual void onFrameRendered(uint64_t bufferQueueId,
512 int32_t slotId,
513 int64_t timestampNs) override {
514 // TODO: implement
515 (void)bufferQueueId;
516 (void)slotId;
517 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800518 }
519
520 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800521 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800522 sp<CCodec> codec(mCodec.promote());
523 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800524 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800525 }
526 }
527
528private:
529 wp<CCodec> mCodec;
530};
531
532// CCodecCallbackImpl
533
534class CCodecCallbackImpl : public CCodecCallback {
535public:
536 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
537 ~CCodecCallbackImpl() override = default;
538
539 void onError(status_t err, enum ActionCode actionCode) override {
540 mCodec->mCallback->onError(err, actionCode);
541 }
542
543 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
544 mCodec->mCallback->onOutputFramesRendered(
545 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
546 }
547
Pawin Vongmasa36653902018-11-15 00:10:25 -0800548 void onOutputBuffersChanged() override {
549 mCodec->mCallback->onOutputBuffersChanged();
550 }
551
552private:
553 CCodec *mCodec;
554};
555
556// CCodec
557
558CCodec::CCodec()
Wonsik Kimab34ed62019-01-31 15:28:46 -0800559 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800560}
561
562CCodec::~CCodec() {
563}
564
565std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
566 return mChannel;
567}
568
569status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
570 status_t err = job();
571 if (err != C2_OK) {
572 mCallback->onError(err, ACTION_CODE_FATAL);
573 }
574 return err;
575}
576
577void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
578 auto setAllocating = [this] {
579 Mutexed<State>::Locked state(mState);
580 if (state->get() != RELEASED) {
581 return INVALID_OPERATION;
582 }
583 state->set(ALLOCATING);
584 return OK;
585 };
586 if (tryAndReportOnError(setAllocating) != OK) {
587 return;
588 }
589
590 sp<RefBase> codecInfo;
591 CHECK(msg->findObject("codecInfo", &codecInfo));
592 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
593
594 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
595 allocMsg->setObject("codecInfo", codecInfo);
596 allocMsg->post();
597}
598
599void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
600 if (codecInfo == nullptr) {
601 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
602 return;
603 }
604 ALOGD("allocate(%s)", codecInfo->getCodecName());
605 mClientListener.reset(new ClientListener(this));
606
607 AString componentName = codecInfo->getCodecName();
608 std::shared_ptr<Codec2Client> client;
609
610 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700611 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800612 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800613 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800614 SetPreferredCodec2ComponentStore(
615 std::make_shared<Codec2ClientInterfaceWrapper>(client));
616 }
617
618 std::shared_ptr<Codec2Client::Component> comp =
619 Codec2Client::CreateComponentByName(
620 componentName.c_str(),
621 mClientListener,
622 &client);
623 if (!comp) {
624 ALOGE("Failed Create component: %s", componentName.c_str());
625 Mutexed<State>::Locked state(mState);
626 state->set(RELEASED);
627 state.unlock();
628 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
629 state.lock();
630 return;
631 }
632 ALOGI("Created component [%s]", componentName.c_str());
633 mChannel->setComponent(comp);
634 auto setAllocated = [this, comp, client] {
635 Mutexed<State>::Locked state(mState);
636 if (state->get() != ALLOCATING) {
637 state->set(RELEASED);
638 return UNKNOWN_ERROR;
639 }
640 state->set(ALLOCATED);
641 state->comp = comp;
642 mClient = client;
643 return OK;
644 };
645 if (tryAndReportOnError(setAllocated) != OK) {
646 return;
647 }
648
649 // initialize config here in case setParameters is called prior to configure
650 Mutexed<Config>::Locked config(mConfig);
651 status_t err = config->initialize(mClient, comp);
652 if (err != OK) {
653 ALOGW("Failed to initialize configuration support");
654 // TODO: report error once we complete implementation.
655 }
656 config->queryConfiguration(comp);
657
658 mCallback->onComponentAllocated(componentName.c_str());
659}
660
661void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
662 auto checkAllocated = [this] {
663 Mutexed<State>::Locked state(mState);
664 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
665 };
666 if (tryAndReportOnError(checkAllocated) != OK) {
667 return;
668 }
669
670 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
671 msg->setMessage("format", format);
672 msg->post();
673}
674
675void CCodec::configure(const sp<AMessage> &msg) {
676 std::shared_ptr<Codec2Client::Component> comp;
677 auto checkAllocated = [this, &comp] {
678 Mutexed<State>::Locked state(mState);
679 if (state->get() != ALLOCATED) {
680 state->set(RELEASED);
681 return UNKNOWN_ERROR;
682 }
683 comp = state->comp;
684 return OK;
685 };
686 if (tryAndReportOnError(checkAllocated) != OK) {
687 return;
688 }
689
690 auto doConfig = [msg, comp, this]() -> status_t {
691 AString mime;
692 if (!msg->findString("mime", &mime)) {
693 return BAD_VALUE;
694 }
695
696 int32_t encoder;
697 if (!msg->findInt32("encoder", &encoder)) {
698 encoder = false;
699 }
700
701 // TODO: read from intf()
702 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
703 return UNKNOWN_ERROR;
704 }
705
706 int32_t storeMeta;
707 if (encoder
708 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
709 && storeMeta != kMetadataBufferTypeInvalid) {
710 if (storeMeta != kMetadataBufferTypeANWBuffer) {
711 ALOGD("Only ANW buffers are supported for legacy metadata mode");
712 return BAD_VALUE;
713 }
714 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
715 }
716
717 sp<RefBase> obj;
718 sp<Surface> surface;
719 if (msg->findObject("native-window", &obj)) {
720 surface = static_cast<Surface *>(obj.get());
721 setSurface(surface);
722 }
723
724 Mutexed<Config>::Locked config(mConfig);
725 config->mUsingSurface = surface != nullptr;
726
Wonsik Kim1114eea2019-02-25 14:35:24 -0800727 // Enforce required parameters
728 int32_t i32;
729 float flt;
730 if (config->mDomain & Config::IS_AUDIO) {
731 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
732 ALOGD("sample rate is missing, which is required for audio components.");
733 return BAD_VALUE;
734 }
735 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
736 ALOGD("channel count is missing, which is required for audio components.");
737 return BAD_VALUE;
738 }
739 if ((config->mDomain & Config::IS_ENCODER)
740 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
741 && !msg->findInt32(KEY_BIT_RATE, &i32)
742 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
743 ALOGD("bitrate is missing, which is required for audio encoders.");
744 return BAD_VALUE;
745 }
746 }
747 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
748 if (!msg->findInt32(KEY_WIDTH, &i32)) {
749 ALOGD("width is missing, which is required for image/video components.");
750 return BAD_VALUE;
751 }
752 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
753 ALOGD("height is missing, which is required for image/video components.");
754 return BAD_VALUE;
755 }
756 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700757 C2Config::bitrate_mode_t mode = C2Config::BITRATE_VARIABLE;
758 if (msg->findInt32(KEY_BITRATE_MODE, &i32)) {
759 mode = (C2Config::bitrate_mode_t) i32;
760 }
761 if (mode == BITRATE_MODE_CQ) {
762 if (!msg->findInt32(KEY_QUALITY, &i32)) {
763 ALOGD("quality is missing, which is required for video encoders in CQ.");
764 return BAD_VALUE;
765 }
766 } else {
767 if (!msg->findInt32(KEY_BIT_RATE, &i32)
768 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
769 ALOGD("bitrate is missing, which is required for video encoders.");
770 return BAD_VALUE;
771 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800772 }
773 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
774 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
775 ALOGD("I frame interval is missing, which is required for video encoders.");
776 return BAD_VALUE;
777 }
778 }
779 }
780
Pawin Vongmasa36653902018-11-15 00:10:25 -0800781 /*
782 * Handle input surface configuration
783 */
784 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
785 && (config->mDomain & Config::IS_ENCODER)) {
786 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
787 {
788 config->mISConfig->mMinFps = 0;
789 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800790 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800791 config->mISConfig->mMinFps = 1e6 / value;
792 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700793 if (!msg->findFloat(
794 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
795 config->mISConfig->mMaxFps = -1;
796 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800797 config->mISConfig->mMinAdjustedFps = 0;
798 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800799 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800800 if (value < 0 && value >= INT32_MIN) {
801 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700802 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800803 } else if (value > 0 && value <= INT32_MAX) {
804 config->mISConfig->mMinAdjustedFps = 1e6 / value;
805 }
806 }
807 }
808
809 {
810 double value;
811 if (msg->findDouble("time-lapse-fps", &value)) {
812 config->mISConfig->mCaptureFps = value;
813 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
814 }
815 }
816
817 {
818 config->mISConfig->mSuspended = false;
819 config->mISConfig->mSuspendAtUs = -1;
820 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800821 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800822 config->mISConfig->mSuspended = true;
823 }
824 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700825 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800826 }
827
828 /*
829 * Handle desired color format.
830 */
831 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
832 int32_t format = -1;
833 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
834 /*
835 * Also handle default color format (encoders require color format, so this is only
836 * needed for decoders.
837 */
838 if (!(config->mDomain & Config::IS_ENCODER)) {
839 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
840 }
841 }
842
843 if (format >= 0) {
844 msg->setInt32("android._color-format", format);
845 }
846 }
847
848 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800849 // NOTE: We used to ignore "video-bitrate" at configure; replicate
850 // the behavior here.
851 sp<AMessage> sdkParams = msg;
852 int32_t videoBitrate;
853 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
854 sdkParams = msg->dup();
855 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
856 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800857 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800858 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800859 if (err != OK) {
860 ALOGW("failed to convert configuration to c2 params");
861 }
862 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
863 if (err != OK) {
864 ALOGW("failed to configure c2 params");
865 return err;
866 }
867
868 std::vector<std::unique_ptr<C2Param>> params;
869 C2StreamUsageTuning::input usage(0u, 0u);
870 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700871 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800872
873 std::initializer_list<C2Param::Index> indices {
874 };
875 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700876 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800877 indices,
878 C2_DONT_BLOCK,
879 &params);
880 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
881 ALOGE("Failed to query component interface: %d", c2err);
882 return UNKNOWN_ERROR;
883 }
884 if (params.size() != indices.size()) {
885 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
886 indices.size(), params.size());
887 return UNKNOWN_ERROR;
888 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700889 if (usage) {
890 if (usage.value & C2MemoryUsage::CPU_READ) {
891 config->mInputFormat->setInt32("using-sw-read-often", true);
892 }
893 if (config->mISConfig) {
894 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
895 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
896 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800897 }
898
899 // NOTE: we don't blindly use client specified input size if specified as clients
900 // at times specify too small size. Instead, mimic the behavior from OMX, where the
901 // client specified size is only used to ask for bigger buffers than component suggested
902 // size.
903 int32_t clientInputSize = 0;
904 bool clientSpecifiedInputSize =
905 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
906 // TEMP: enforce minimum buffer size of 1MB for video decoders
907 // and 16K / 4K for audio encoders/decoders
908 if (maxInputSize.value == 0) {
909 if (config->mDomain & Config::IS_AUDIO) {
910 maxInputSize.value = encoder ? 16384 : 4096;
911 } else if (!encoder) {
912 maxInputSize.value = 1048576u;
913 }
914 }
915
916 // verify that CSD fits into this size (if defined)
917 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
918 sp<ABuffer> csd;
919 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
920 if (csd && csd->size() > maxInputSize.value) {
921 maxInputSize.value = csd->size();
922 }
923 }
924 }
925
926 // TODO: do this based on component requiring linear allocator for input
927 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
928 if (clientSpecifiedInputSize) {
929 // Warn that we're overriding client's max input size if necessary.
930 if ((uint32_t)clientInputSize < maxInputSize.value) {
931 ALOGD("client requested max input size %d, which is smaller than "
932 "what component recommended (%u); overriding with component "
933 "recommendation.", clientInputSize, maxInputSize.value);
934 ALOGW("This behavior is subject to change. It is recommended that "
935 "app developers double check whether the requested "
936 "max input size is in reasonable range.");
937 } else {
938 maxInputSize.value = clientInputSize;
939 }
940 }
941 // Pass max input size on input format to the buffer channel (if supplied by the
942 // component or by a default)
943 if (maxInputSize.value) {
944 config->mInputFormat->setInt32(
945 KEY_MAX_INPUT_SIZE,
946 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
947 }
948 }
949
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700950 int32_t clientPrepend;
951 if ((config->mDomain & Config::IS_VIDEO)
952 && (config->mDomain & Config::IS_ENCODER)
953 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
954 && clientPrepend
955 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
956 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
957 return BAD_VALUE;
958 }
959
Pawin Vongmasa36653902018-11-15 00:10:25 -0800960 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
961 // propagate HDR static info to output format for both encoders and decoders
962 // if component supports this info, we will update from component, but only the raw port,
963 // so don't propagate if component already filled it in.
964 sp<ABuffer> hdrInfo;
965 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
966 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
967 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
968 }
969
970 // Set desired color format from configuration parameter
971 int32_t format;
972 if (msg->findInt32("android._color-format", &format)) {
973 if (config->mDomain & Config::IS_ENCODER) {
974 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
975 } else {
976 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
977 }
978 }
979 }
980
981 // propagate encoder delay and padding to output format
982 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
983 int delay = 0;
984 if (msg->findInt32("encoder-delay", &delay)) {
985 config->mOutputFormat->setInt32("encoder-delay", delay);
986 }
987 int padding = 0;
988 if (msg->findInt32("encoder-padding", &padding)) {
989 config->mOutputFormat->setInt32("encoder-padding", padding);
990 }
991 }
992
993 // set channel-mask
994 if (config->mDomain & Config::IS_AUDIO) {
995 int32_t mask;
996 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
997 if (config->mDomain & Config::IS_ENCODER) {
998 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
999 } else {
1000 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1001 }
1002 }
1003 }
1004
1005 ALOGD("setup formats input: %s and output: %s",
1006 config->mInputFormat->debugString().c_str(),
1007 config->mOutputFormat->debugString().c_str());
1008 return OK;
1009 };
1010 if (tryAndReportOnError(doConfig) != OK) {
1011 return;
1012 }
1013
1014 Mutexed<Config>::Locked config(mConfig);
1015
1016 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1017}
1018
1019void CCodec::initiateCreateInputSurface() {
1020 status_t err = [this] {
1021 Mutexed<State>::Locked state(mState);
1022 if (state->get() != ALLOCATED) {
1023 return UNKNOWN_ERROR;
1024 }
1025 // TODO: read it from intf() properly.
1026 if (state->comp->getName().find("encoder") == std::string::npos) {
1027 return INVALID_OPERATION;
1028 }
1029 return OK;
1030 }();
1031 if (err != OK) {
1032 mCallback->onInputSurfaceCreationFailed(err);
1033 return;
1034 }
1035
1036 (new AMessage(kWhatCreateInputSurface, this))->post();
1037}
1038
Lajos Molnar47118272019-01-31 16:28:04 -08001039sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1040 using namespace android::hardware::media::omx::V1_0;
1041 using namespace android::hardware::media::omx::V1_0::utils;
1042 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1043 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1044 android::sp<IOmx> omx = IOmx::getService();
1045 typedef android::hardware::graphics::bufferqueue::V1_0::
1046 IGraphicBufferProducer HGraphicBufferProducer;
1047 typedef android::hardware::media::omx::V1_0::
1048 IGraphicBufferSource HGraphicBufferSource;
1049 OmxStatus s;
1050 android::sp<HGraphicBufferProducer> gbp;
1051 android::sp<HGraphicBufferSource> gbs;
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001052 using ::android::hardware::Return;
1053 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001054 [&s, &gbp, &gbs](
1055 OmxStatus status,
1056 const android::sp<HGraphicBufferProducer>& producer,
1057 const android::sp<HGraphicBufferSource>& source) {
1058 s = status;
1059 gbp = producer;
1060 gbs = source;
1061 });
1062 if (transStatus.isOk() && s == OmxStatus::OK) {
1063 return new PersistentSurface(
1064 new H2BGraphicBufferProducer(gbp),
1065 sp<::android::IGraphicBufferSource>(new LWGraphicBufferSource(gbs)));
1066 }
1067
1068 return nullptr;
1069}
1070
1071sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1072 sp<PersistentSurface> surface(CreateInputSurface());
1073
1074 if (surface == nullptr) {
1075 surface = CreateOmxInputSurface();
1076 }
1077
1078 return surface;
1079}
1080
Pawin Vongmasa36653902018-11-15 00:10:25 -08001081void CCodec::createInputSurface() {
1082 status_t err;
1083 sp<IGraphicBufferProducer> bufferProducer;
1084
1085 sp<AMessage> inputFormat;
1086 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001087 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001088 {
1089 Mutexed<Config>::Locked config(mConfig);
1090 inputFormat = config->mInputFormat;
1091 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001092 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001093 }
1094
Lajos Molnar47118272019-01-31 16:28:04 -08001095 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001096
1097 if (persistentSurface->getHidlTarget()) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001098 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001099 persistentSurface->getHidlTarget());
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001100 if (!hidlInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001101 ALOGE("Corrupted input surface");
1102 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1103 return;
1104 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001105 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1106 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001107 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001108 inputSurface));
1109 bufferProducer = inputSurface->getGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001110 } else {
1111 int32_t width = 0;
1112 (void)outputFormat->findInt32("width", &width);
1113 int32_t height = 0;
1114 (void)outputFormat->findInt32("height", &height);
1115 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001116 persistentSurface->getBufferSource(), width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001117 bufferProducer = persistentSurface->getBufferProducer();
1118 }
1119
1120 if (err != OK) {
1121 ALOGE("Failed to set up input surface: %d", err);
1122 mCallback->onInputSurfaceCreationFailed(err);
1123 return;
1124 }
1125
1126 mCallback->onInputSurfaceCreated(
1127 inputFormat,
1128 outputFormat,
1129 new BufferProducerWrapper(bufferProducer));
1130}
1131
1132status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
1133 Mutexed<Config>::Locked config(mConfig);
1134 config->mUsingSurface = true;
1135
1136 // we are now using surface - apply default color aspects to input format - as well as
1137 // get dataspace
1138 bool inputFormatChanged = config->updateFormats(config->IS_INPUT);
1139 ALOGD("input format %s to %s",
1140 inputFormatChanged ? "changed" : "unchanged",
1141 config->mInputFormat->debugString().c_str());
1142
1143 // configure dataspace
1144 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1145 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1146 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1147 surface->setDataSpace(dataSpace);
1148
1149 status_t err = mChannel->setInputSurface(surface);
1150 if (err != OK) {
1151 // undo input format update
1152 config->mUsingSurface = false;
1153 (void)config->updateFormats(config->IS_INPUT);
1154 return err;
1155 }
1156 config->mInputSurface = surface;
1157
1158 if (config->mISConfig) {
1159 surface->configure(*config->mISConfig);
1160 } else {
1161 ALOGD("ISConfig: no configuration");
1162 }
1163
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001164 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001165}
1166
1167void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1168 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1169 msg->setObject("surface", surface);
1170 msg->post();
1171}
1172
1173void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1174 sp<AMessage> inputFormat;
1175 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001176 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001177 {
1178 Mutexed<Config>::Locked config(mConfig);
1179 inputFormat = config->mInputFormat;
1180 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001181 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001182 }
1183 auto hidlTarget = surface->getHidlTarget();
1184 if (hidlTarget) {
1185 sp<IInputSurface> inputSurface =
1186 IInputSurface::castFrom(hidlTarget);
1187 if (!inputSurface) {
1188 ALOGE("Failed to set input surface: Corrupted surface.");
1189 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1190 return;
1191 }
1192 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1193 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1194 if (err != OK) {
1195 ALOGE("Failed to set up input surface: %d", err);
1196 mCallback->onInputSurfaceDeclined(err);
1197 return;
1198 }
1199 } else {
1200 int32_t width = 0;
1201 (void)outputFormat->findInt32("width", &width);
1202 int32_t height = 0;
1203 (void)outputFormat->findInt32("height", &height);
1204 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001205 surface->getBufferSource(), width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001206 if (err != OK) {
1207 ALOGE("Failed to set up input surface: %d", err);
1208 mCallback->onInputSurfaceDeclined(err);
1209 return;
1210 }
1211 }
1212 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1213}
1214
1215void CCodec::initiateStart() {
1216 auto setStarting = [this] {
1217 Mutexed<State>::Locked state(mState);
1218 if (state->get() != ALLOCATED) {
1219 return UNKNOWN_ERROR;
1220 }
1221 state->set(STARTING);
1222 return OK;
1223 };
1224 if (tryAndReportOnError(setStarting) != OK) {
1225 return;
1226 }
1227
1228 (new AMessage(kWhatStart, this))->post();
1229}
1230
1231void CCodec::start() {
1232 std::shared_ptr<Codec2Client::Component> comp;
1233 auto checkStarting = [this, &comp] {
1234 Mutexed<State>::Locked state(mState);
1235 if (state->get() != STARTING) {
1236 return UNKNOWN_ERROR;
1237 }
1238 comp = state->comp;
1239 return OK;
1240 };
1241 if (tryAndReportOnError(checkStarting) != OK) {
1242 return;
1243 }
1244
1245 c2_status_t err = comp->start();
1246 if (err != C2_OK) {
1247 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1248 ACTION_CODE_FATAL);
1249 return;
1250 }
1251 sp<AMessage> inputFormat;
1252 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001253 status_t err2 = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001254 {
1255 Mutexed<Config>::Locked config(mConfig);
1256 inputFormat = config->mInputFormat;
1257 outputFormat = config->mOutputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001258 if (config->mInputSurface) {
1259 err2 = config->mInputSurface->start();
1260 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001261 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001262 if (err2 != OK) {
1263 mCallback->onError(err2, ACTION_CODE_FATAL);
1264 return;
1265 }
1266 err2 = mChannel->start(inputFormat, outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001267 if (err2 != OK) {
1268 mCallback->onError(err2, ACTION_CODE_FATAL);
1269 return;
1270 }
1271
1272 auto setRunning = [this] {
1273 Mutexed<State>::Locked state(mState);
1274 if (state->get() != STARTING) {
1275 return UNKNOWN_ERROR;
1276 }
1277 state->set(RUNNING);
1278 return OK;
1279 };
1280 if (tryAndReportOnError(setRunning) != OK) {
1281 return;
1282 }
1283 mCallback->onStartCompleted();
1284
1285 (void)mChannel->requestInitialInputBuffers();
1286}
1287
1288void CCodec::initiateShutdown(bool keepComponentAllocated) {
1289 if (keepComponentAllocated) {
1290 initiateStop();
1291 } else {
1292 initiateRelease();
1293 }
1294}
1295
1296void CCodec::initiateStop() {
1297 {
1298 Mutexed<State>::Locked state(mState);
1299 if (state->get() == ALLOCATED
1300 || state->get() == RELEASED
1301 || state->get() == STOPPING
1302 || state->get() == RELEASING) {
1303 // We're already stopped, released, or doing it right now.
1304 state.unlock();
1305 mCallback->onStopCompleted();
1306 state.lock();
1307 return;
1308 }
1309 state->set(STOPPING);
1310 }
1311
1312 mChannel->stop();
1313 (new AMessage(kWhatStop, this))->post();
1314}
1315
1316void CCodec::stop() {
1317 std::shared_ptr<Codec2Client::Component> comp;
1318 {
1319 Mutexed<State>::Locked state(mState);
1320 if (state->get() == RELEASING) {
1321 state.unlock();
1322 // We're already stopped or release is in progress.
1323 mCallback->onStopCompleted();
1324 state.lock();
1325 return;
1326 } else if (state->get() != STOPPING) {
1327 state.unlock();
1328 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1329 state.lock();
1330 return;
1331 }
1332 comp = state->comp;
1333 }
1334 status_t err = comp->stop();
1335 if (err != C2_OK) {
1336 // TODO: convert err into status_t
1337 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1338 }
1339
1340 {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001341 Mutexed<Config>::Locked config(mConfig);
1342 if (config->mInputSurface) {
1343 config->mInputSurface->disconnect();
1344 config->mInputSurface = nullptr;
1345 }
1346 }
1347 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001348 Mutexed<State>::Locked state(mState);
1349 if (state->get() == STOPPING) {
1350 state->set(ALLOCATED);
1351 }
1352 }
1353 mCallback->onStopCompleted();
1354}
1355
1356void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001357 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001358 {
1359 Mutexed<State>::Locked state(mState);
1360 if (state->get() == RELEASED || state->get() == RELEASING) {
1361 // We're already released or doing it right now.
1362 if (sendCallback) {
1363 state.unlock();
1364 mCallback->onReleaseCompleted();
1365 state.lock();
1366 }
1367 return;
1368 }
1369 if (state->get() == ALLOCATING) {
1370 state->set(RELEASING);
1371 // With the altered state allocate() would fail and clean up.
1372 if (sendCallback) {
1373 state.unlock();
1374 mCallback->onReleaseCompleted();
1375 state.lock();
1376 }
1377 return;
1378 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001379 if (state->get() == STARTING
1380 || state->get() == RUNNING
1381 || state->get() == STOPPING) {
1382 // Input surface may have been started, so clean up is needed.
1383 clearInputSurfaceIfNeeded = true;
1384 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001385 state->set(RELEASING);
1386 }
1387
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001388 if (clearInputSurfaceIfNeeded) {
1389 Mutexed<Config>::Locked config(mConfig);
1390 if (config->mInputSurface) {
1391 config->mInputSurface->disconnect();
1392 config->mInputSurface = nullptr;
1393 }
1394 }
1395
Pawin Vongmasa36653902018-11-15 00:10:25 -08001396 mChannel->stop();
1397 // thiz holds strong ref to this while the thread is running.
1398 sp<CCodec> thiz(this);
1399 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1400}
1401
1402void CCodec::release(bool sendCallback) {
1403 std::shared_ptr<Codec2Client::Component> comp;
1404 {
1405 Mutexed<State>::Locked state(mState);
1406 if (state->get() == RELEASED) {
1407 if (sendCallback) {
1408 state.unlock();
1409 mCallback->onReleaseCompleted();
1410 state.lock();
1411 }
1412 return;
1413 }
1414 comp = state->comp;
1415 }
1416 comp->release();
1417
1418 {
1419 Mutexed<State>::Locked state(mState);
1420 state->set(RELEASED);
1421 state->comp.reset();
1422 }
1423 if (sendCallback) {
1424 mCallback->onReleaseCompleted();
1425 }
1426}
1427
1428status_t CCodec::setSurface(const sp<Surface> &surface) {
1429 return mChannel->setSurface(surface);
1430}
1431
1432void CCodec::signalFlush() {
1433 status_t err = [this] {
1434 Mutexed<State>::Locked state(mState);
1435 if (state->get() == FLUSHED) {
1436 return ALREADY_EXISTS;
1437 }
1438 if (state->get() != RUNNING) {
1439 return UNKNOWN_ERROR;
1440 }
1441 state->set(FLUSHING);
1442 return OK;
1443 }();
1444 switch (err) {
1445 case ALREADY_EXISTS:
1446 mCallback->onFlushCompleted();
1447 return;
1448 case OK:
1449 break;
1450 default:
1451 mCallback->onError(err, ACTION_CODE_FATAL);
1452 return;
1453 }
1454
1455 mChannel->stop();
1456 (new AMessage(kWhatFlush, this))->post();
1457}
1458
1459void CCodec::flush() {
1460 std::shared_ptr<Codec2Client::Component> comp;
1461 auto checkFlushing = [this, &comp] {
1462 Mutexed<State>::Locked state(mState);
1463 if (state->get() != FLUSHING) {
1464 return UNKNOWN_ERROR;
1465 }
1466 comp = state->comp;
1467 return OK;
1468 };
1469 if (tryAndReportOnError(checkFlushing) != OK) {
1470 return;
1471 }
1472
1473 std::list<std::unique_ptr<C2Work>> flushedWork;
1474 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1475 {
1476 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1477 flushedWork.splice(flushedWork.end(), *queue);
1478 }
1479 if (err != C2_OK) {
1480 // TODO: convert err into status_t
1481 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1482 }
1483
1484 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001485
1486 {
1487 Mutexed<State>::Locked state(mState);
1488 state->set(FLUSHED);
1489 }
1490 mCallback->onFlushCompleted();
1491}
1492
1493void CCodec::signalResume() {
1494 auto setResuming = [this] {
1495 Mutexed<State>::Locked state(mState);
1496 if (state->get() != FLUSHED) {
1497 return UNKNOWN_ERROR;
1498 }
1499 state->set(RESUMING);
1500 return OK;
1501 };
1502 if (tryAndReportOnError(setResuming) != OK) {
1503 return;
1504 }
1505
1506 (void)mChannel->start(nullptr, nullptr);
1507
1508 {
1509 Mutexed<State>::Locked state(mState);
1510 if (state->get() != RESUMING) {
1511 state.unlock();
1512 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1513 state.lock();
1514 return;
1515 }
1516 state->set(RUNNING);
1517 }
1518
1519 (void)mChannel->requestInitialInputBuffers();
1520}
1521
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001522void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001523 std::shared_ptr<Codec2Client::Component> comp;
1524 auto checkState = [this, &comp] {
1525 Mutexed<State>::Locked state(mState);
1526 if (state->get() == RELEASED) {
1527 return INVALID_OPERATION;
1528 }
1529 comp = state->comp;
1530 return OK;
1531 };
1532 if (tryAndReportOnError(checkState) != OK) {
1533 return;
1534 }
1535
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001536 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1537 // the behavior here.
1538 sp<AMessage> params = msg;
1539 int32_t bitrate;
1540 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1541 params = msg->dup();
1542 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1543 }
1544
Pawin Vongmasa36653902018-11-15 00:10:25 -08001545 Mutexed<Config>::Locked config(mConfig);
1546
1547 /**
1548 * Handle input surface parameters
1549 */
1550 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1551 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001552 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001553
1554 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1555 config->mISConfig->mStopped = false;
1556 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1557 config->mISConfig->mStopped = true;
1558 }
1559
1560 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001561 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001562 config->mISConfig->mSuspended = value;
1563 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001564 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001565 }
1566
1567 (void)config->mInputSurface->configure(*config->mISConfig);
1568 if (config->mISConfig->mStopped) {
1569 config->mInputFormat->setInt64(
1570 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1571 }
1572 }
1573
1574 std::vector<std::unique_ptr<C2Param>> configUpdate;
1575 (void)config->getConfigUpdateFromSdkParams(
1576 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1577 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1578 // Parameter synchronization is not defined when using input surface. For now, route
1579 // these directly to the component.
1580 if (config->mInputSurface == nullptr
1581 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1582 || comp->getName().find("c2.android.") == 0)) {
1583 mChannel->setParameters(configUpdate);
1584 } else {
1585 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1586 }
1587}
1588
1589void CCodec::signalEndOfInputStream() {
1590 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1591}
1592
1593void CCodec::signalRequestIDRFrame() {
1594 std::shared_ptr<Codec2Client::Component> comp;
1595 {
1596 Mutexed<State>::Locked state(mState);
1597 if (state->get() == RELEASED) {
1598 ALOGD("no IDR request sent since component is released");
1599 return;
1600 }
1601 comp = state->comp;
1602 }
1603 ALOGV("request IDR");
1604 Mutexed<Config>::Locked config(mConfig);
1605 std::vector<std::unique_ptr<C2Param>> params;
1606 params.push_back(
1607 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1608 config->setParameters(comp, params, C2_MAY_BLOCK);
1609}
1610
Wonsik Kimab34ed62019-01-31 15:28:46 -08001611void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001612 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001613 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1614 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001615 }
1616 (new AMessage(kWhatWorkDone, this))->post();
1617}
1618
Wonsik Kimab34ed62019-01-31 15:28:46 -08001619void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1620 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001621 if (arrayIndex == 0) {
1622 // We always put no more than one buffer per work, if we use an input surface.
1623 Mutexed<Config>::Locked config(mConfig);
1624 if (config->mInputSurface) {
1625 config->mInputSurface->onInputBufferDone(frameIndex);
1626 }
1627 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001628}
1629
1630void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1631 TimePoint now = std::chrono::steady_clock::now();
1632 CCodecWatchdog::getInstance()->watch(this);
1633 switch (msg->what()) {
1634 case kWhatAllocate: {
1635 // C2ComponentStore::createComponent() should return within 100ms.
1636 setDeadline(now, 150ms, "allocate");
1637 sp<RefBase> obj;
1638 CHECK(msg->findObject("codecInfo", &obj));
1639 allocate((MediaCodecInfo *)obj.get());
1640 break;
1641 }
1642 case kWhatConfigure: {
1643 // C2Component::commit_sm() should return within 5ms.
1644 setDeadline(now, 250ms, "configure");
1645 sp<AMessage> format;
1646 CHECK(msg->findMessage("format", &format));
1647 configure(format);
1648 break;
1649 }
1650 case kWhatStart: {
1651 // C2Component::start() should return within 500ms.
1652 setDeadline(now, 550ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001653 start();
1654 break;
1655 }
1656 case kWhatStop: {
1657 // C2Component::stop() should return within 500ms.
1658 setDeadline(now, 550ms, "stop");
1659 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001660 break;
1661 }
1662 case kWhatFlush: {
1663 // C2Component::flush_sm() should return within 5ms.
1664 setDeadline(now, 50ms, "flush");
1665 flush();
1666 break;
1667 }
1668 case kWhatCreateInputSurface: {
1669 // Surface operations may be briefly blocking.
1670 setDeadline(now, 100ms, "createInputSurface");
1671 createInputSurface();
1672 break;
1673 }
1674 case kWhatSetInputSurface: {
1675 // Surface operations may be briefly blocking.
1676 setDeadline(now, 100ms, "setInputSurface");
1677 sp<RefBase> obj;
1678 CHECK(msg->findObject("surface", &obj));
1679 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1680 setInputSurface(surface);
1681 break;
1682 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001683 case kWhatWorkDone: {
1684 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001685 bool shouldPost = false;
1686 {
1687 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1688 if (queue->empty()) {
1689 break;
1690 }
1691 work.swap(queue->front());
1692 queue->pop_front();
1693 shouldPost = !queue->empty();
1694 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001695 if (shouldPost) {
1696 (new AMessage(kWhatWorkDone, this))->post();
1697 }
1698
Pawin Vongmasa36653902018-11-15 00:10:25 -08001699 // handle configuration changes in work done
1700 Mutexed<Config>::Locked config(mConfig);
1701 bool changed = false;
1702 Config::Watcher<C2StreamInitDataInfo::output> initData =
1703 config->watch<C2StreamInitDataInfo::output>();
1704 if (!work->worklets.empty()
1705 && (work->worklets.front()->output.flags
1706 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1707
1708 // copy buffer info to config
1709 std::vector<std::unique_ptr<C2Param>> updates =
1710 std::move(work->worklets.front()->output.configUpdate);
1711 unsigned stream = 0;
1712 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1713 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1714 // move all info into output-stream #0 domain
1715 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1716 }
1717 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1718 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1719 // block.crop().left, block.crop().top,
1720 // block.crop().width, block.crop().height,
1721 // block.width(), block.height());
1722 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1723 updates.emplace_back(new C2StreamPictureSizeInfo::output(
1724 stream, block.width(), block.height()));
1725 break; // for now only do the first block
1726 }
1727 ++stream;
1728 }
1729
1730 changed = config->updateConfiguration(updates, config->mOutputDomain);
1731
1732 // copy standard infos to graphic buffers if not already present (otherwise, we
1733 // may overwrite the actual intermediate value with a final value)
1734 stream = 0;
1735 const static std::vector<C2Param::Index> stdGfxInfos = {
1736 C2StreamRotationInfo::output::PARAM_TYPE,
1737 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1738 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1739 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001740 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001741 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1742 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1743 };
1744 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1745 if (buf->data().graphicBlocks().size()) {
1746 for (C2Param::Index ix : stdGfxInfos) {
1747 if (!buf->hasInfo(ix)) {
1748 const C2Param *param =
1749 config->getConfigParameterValue(ix.withStream(stream));
1750 if (param) {
1751 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1752 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1753 }
1754 }
1755 }
1756 }
1757 ++stream;
1758 }
1759 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001760 if (config->mInputSurface) {
1761 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1762 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001763 mChannel->onWorkDone(
1764 std::move(work), changed ? config->mOutputFormat : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001765 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001766 break;
1767 }
1768 case kWhatWatch: {
1769 // watch message already posted; no-op.
1770 break;
1771 }
1772 default: {
1773 ALOGE("unrecognized message");
1774 break;
1775 }
1776 }
1777 setDeadline(TimePoint::max(), 0ms, "none");
1778}
1779
1780void CCodec::setDeadline(
1781 const TimePoint &now,
1782 const std::chrono::milliseconds &timeout,
1783 const char *name) {
1784 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1785 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1786 deadline->set(now + (timeout * mult), name);
1787}
1788
1789void CCodec::initiateReleaseIfStuck() {
1790 std::string name;
1791 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001792 {
1793 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001794 if (deadline->get() < std::chrono::steady_clock::now()) {
1795 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001796 }
1797 if (deadline->get() != TimePoint::max()) {
1798 pendingDeadline = true;
1799 }
1800 }
1801 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001802 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1803 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1804 if (elapsed >= kWorkDurationThreshold) {
1805 name = "queue";
1806 }
1807 if (elapsed > 0s) {
1808 pendingDeadline = true;
1809 }
1810 }
1811 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001812 // We're not stuck.
1813 if (pendingDeadline) {
1814 // If we are not stuck yet but still has deadline coming up,
1815 // post watch message to check back later.
1816 (new AMessage(kWhatWatch, this))->post();
1817 }
1818 return;
1819 }
1820
1821 ALOGW("previous call to %s exceeded timeout", name.c_str());
1822 initiateRelease(false);
1823 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1824}
1825
Pawin Vongmasa36653902018-11-15 00:10:25 -08001826} // namespace android
1827
1828extern "C" android::CodecBase *CreateCodec() {
1829 return new android::CCodec;
1830}
1831
Lajos Molnar47118272019-01-31 16:28:04 -08001832// Create Codec 2.0 input surface
Pawin Vongmasa36653902018-11-15 00:10:25 -08001833extern "C" android::PersistentSurface *CreateInputSurface() {
1834 // Attempt to create a Codec2's input surface.
1835 std::shared_ptr<android::Codec2Client::InputSurface> inputSurface =
1836 android::Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001837 if (!inputSurface) {
1838 return nullptr;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001839 }
Lajos Molnar47118272019-01-31 16:28:04 -08001840 return new android::PersistentSurface(
1841 inputSurface->getGraphicBufferProducer(),
1842 static_cast<android::sp<android::hidl::base::V1_0::IBase>>(
1843 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001844}
1845