blob: 4b7fa562ae82d600219b72b8fcc02271e0067aae [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 Mahendrakar71cbb9d2019-05-21 11:21:27 -0700757 int32_t mode = BITRATE_MODE_VBR;
758 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700759 if (!msg->findInt32(KEY_QUALITY, &i32)) {
760 ALOGD("quality is missing, which is required for video encoders in CQ.");
761 return BAD_VALUE;
762 }
763 } else {
764 if (!msg->findInt32(KEY_BIT_RATE, &i32)
765 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
766 ALOGD("bitrate is missing, which is required for video encoders.");
767 return BAD_VALUE;
768 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800769 }
770 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
771 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
772 ALOGD("I frame interval is missing, which is required for video encoders.");
773 return BAD_VALUE;
774 }
775 }
776 }
777
Pawin Vongmasa36653902018-11-15 00:10:25 -0800778 /*
779 * Handle input surface configuration
780 */
781 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
782 && (config->mDomain & Config::IS_ENCODER)) {
783 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
784 {
785 config->mISConfig->mMinFps = 0;
786 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800787 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800788 config->mISConfig->mMinFps = 1e6 / value;
789 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700790 if (!msg->findFloat(
791 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
792 config->mISConfig->mMaxFps = -1;
793 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800794 config->mISConfig->mMinAdjustedFps = 0;
795 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800796 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800797 if (value < 0 && value >= INT32_MIN) {
798 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700799 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800800 } else if (value > 0 && value <= INT32_MAX) {
801 config->mISConfig->mMinAdjustedFps = 1e6 / value;
802 }
803 }
804 }
805
806 {
807 double value;
808 if (msg->findDouble("time-lapse-fps", &value)) {
809 config->mISConfig->mCaptureFps = value;
810 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
811 }
812 }
813
814 {
815 config->mISConfig->mSuspended = false;
816 config->mISConfig->mSuspendAtUs = -1;
817 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800818 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800819 config->mISConfig->mSuspended = true;
820 }
821 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700822 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800823 }
824
825 /*
826 * Handle desired color format.
827 */
828 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
829 int32_t format = -1;
830 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
831 /*
832 * Also handle default color format (encoders require color format, so this is only
833 * needed for decoders.
834 */
835 if (!(config->mDomain & Config::IS_ENCODER)) {
836 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
837 }
838 }
839
840 if (format >= 0) {
841 msg->setInt32("android._color-format", format);
842 }
843 }
844
845 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800846 // NOTE: We used to ignore "video-bitrate" at configure; replicate
847 // the behavior here.
848 sp<AMessage> sdkParams = msg;
849 int32_t videoBitrate;
850 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
851 sdkParams = msg->dup();
852 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
853 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800854 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800855 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800856 if (err != OK) {
857 ALOGW("failed to convert configuration to c2 params");
858 }
859 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
860 if (err != OK) {
861 ALOGW("failed to configure c2 params");
862 return err;
863 }
864
865 std::vector<std::unique_ptr<C2Param>> params;
866 C2StreamUsageTuning::input usage(0u, 0u);
867 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700868 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800869
870 std::initializer_list<C2Param::Index> indices {
871 };
872 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700873 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800874 indices,
875 C2_DONT_BLOCK,
876 &params);
877 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
878 ALOGE("Failed to query component interface: %d", c2err);
879 return UNKNOWN_ERROR;
880 }
881 if (params.size() != indices.size()) {
882 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
883 indices.size(), params.size());
884 return UNKNOWN_ERROR;
885 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700886 if (usage) {
887 if (usage.value & C2MemoryUsage::CPU_READ) {
888 config->mInputFormat->setInt32("using-sw-read-often", true);
889 }
890 if (config->mISConfig) {
891 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
892 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
893 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800894 }
895
896 // NOTE: we don't blindly use client specified input size if specified as clients
897 // at times specify too small size. Instead, mimic the behavior from OMX, where the
898 // client specified size is only used to ask for bigger buffers than component suggested
899 // size.
900 int32_t clientInputSize = 0;
901 bool clientSpecifiedInputSize =
902 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
903 // TEMP: enforce minimum buffer size of 1MB for video decoders
904 // and 16K / 4K for audio encoders/decoders
905 if (maxInputSize.value == 0) {
906 if (config->mDomain & Config::IS_AUDIO) {
907 maxInputSize.value = encoder ? 16384 : 4096;
908 } else if (!encoder) {
909 maxInputSize.value = 1048576u;
910 }
911 }
912
913 // verify that CSD fits into this size (if defined)
914 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
915 sp<ABuffer> csd;
916 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
917 if (csd && csd->size() > maxInputSize.value) {
918 maxInputSize.value = csd->size();
919 }
920 }
921 }
922
923 // TODO: do this based on component requiring linear allocator for input
924 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
925 if (clientSpecifiedInputSize) {
926 // Warn that we're overriding client's max input size if necessary.
927 if ((uint32_t)clientInputSize < maxInputSize.value) {
928 ALOGD("client requested max input size %d, which is smaller than "
929 "what component recommended (%u); overriding with component "
930 "recommendation.", clientInputSize, maxInputSize.value);
931 ALOGW("This behavior is subject to change. It is recommended that "
932 "app developers double check whether the requested "
933 "max input size is in reasonable range.");
934 } else {
935 maxInputSize.value = clientInputSize;
936 }
937 }
938 // Pass max input size on input format to the buffer channel (if supplied by the
939 // component or by a default)
940 if (maxInputSize.value) {
941 config->mInputFormat->setInt32(
942 KEY_MAX_INPUT_SIZE,
943 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
944 }
945 }
946
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700947 int32_t clientPrepend;
948 if ((config->mDomain & Config::IS_VIDEO)
949 && (config->mDomain & Config::IS_ENCODER)
950 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
951 && clientPrepend
952 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
953 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
954 return BAD_VALUE;
955 }
956
Pawin Vongmasa36653902018-11-15 00:10:25 -0800957 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
958 // propagate HDR static info to output format for both encoders and decoders
959 // if component supports this info, we will update from component, but only the raw port,
960 // so don't propagate if component already filled it in.
961 sp<ABuffer> hdrInfo;
962 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
963 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
964 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
965 }
966
967 // Set desired color format from configuration parameter
968 int32_t format;
969 if (msg->findInt32("android._color-format", &format)) {
970 if (config->mDomain & Config::IS_ENCODER) {
971 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
972 } else {
973 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
974 }
975 }
976 }
977
978 // propagate encoder delay and padding to output format
979 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
980 int delay = 0;
981 if (msg->findInt32("encoder-delay", &delay)) {
982 config->mOutputFormat->setInt32("encoder-delay", delay);
983 }
984 int padding = 0;
985 if (msg->findInt32("encoder-padding", &padding)) {
986 config->mOutputFormat->setInt32("encoder-padding", padding);
987 }
988 }
989
990 // set channel-mask
991 if (config->mDomain & Config::IS_AUDIO) {
992 int32_t mask;
993 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
994 if (config->mDomain & Config::IS_ENCODER) {
995 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
996 } else {
997 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
998 }
999 }
1000 }
1001
1002 ALOGD("setup formats input: %s and output: %s",
1003 config->mInputFormat->debugString().c_str(),
1004 config->mOutputFormat->debugString().c_str());
1005 return OK;
1006 };
1007 if (tryAndReportOnError(doConfig) != OK) {
1008 return;
1009 }
1010
1011 Mutexed<Config>::Locked config(mConfig);
1012
1013 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1014}
1015
1016void CCodec::initiateCreateInputSurface() {
1017 status_t err = [this] {
1018 Mutexed<State>::Locked state(mState);
1019 if (state->get() != ALLOCATED) {
1020 return UNKNOWN_ERROR;
1021 }
1022 // TODO: read it from intf() properly.
1023 if (state->comp->getName().find("encoder") == std::string::npos) {
1024 return INVALID_OPERATION;
1025 }
1026 return OK;
1027 }();
1028 if (err != OK) {
1029 mCallback->onInputSurfaceCreationFailed(err);
1030 return;
1031 }
1032
1033 (new AMessage(kWhatCreateInputSurface, this))->post();
1034}
1035
Lajos Molnar47118272019-01-31 16:28:04 -08001036sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1037 using namespace android::hardware::media::omx::V1_0;
1038 using namespace android::hardware::media::omx::V1_0::utils;
1039 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1040 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1041 android::sp<IOmx> omx = IOmx::getService();
1042 typedef android::hardware::graphics::bufferqueue::V1_0::
1043 IGraphicBufferProducer HGraphicBufferProducer;
1044 typedef android::hardware::media::omx::V1_0::
1045 IGraphicBufferSource HGraphicBufferSource;
1046 OmxStatus s;
1047 android::sp<HGraphicBufferProducer> gbp;
1048 android::sp<HGraphicBufferSource> gbs;
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001049 using ::android::hardware::Return;
1050 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001051 [&s, &gbp, &gbs](
1052 OmxStatus status,
1053 const android::sp<HGraphicBufferProducer>& producer,
1054 const android::sp<HGraphicBufferSource>& source) {
1055 s = status;
1056 gbp = producer;
1057 gbs = source;
1058 });
1059 if (transStatus.isOk() && s == OmxStatus::OK) {
1060 return new PersistentSurface(
1061 new H2BGraphicBufferProducer(gbp),
1062 sp<::android::IGraphicBufferSource>(new LWGraphicBufferSource(gbs)));
1063 }
1064
1065 return nullptr;
1066}
1067
1068sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1069 sp<PersistentSurface> surface(CreateInputSurface());
1070
1071 if (surface == nullptr) {
1072 surface = CreateOmxInputSurface();
1073 }
1074
1075 return surface;
1076}
1077
Pawin Vongmasa36653902018-11-15 00:10:25 -08001078void CCodec::createInputSurface() {
1079 status_t err;
1080 sp<IGraphicBufferProducer> bufferProducer;
1081
1082 sp<AMessage> inputFormat;
1083 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001084 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001085 {
1086 Mutexed<Config>::Locked config(mConfig);
1087 inputFormat = config->mInputFormat;
1088 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001089 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001090 }
1091
Lajos Molnar47118272019-01-31 16:28:04 -08001092 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001093
1094 if (persistentSurface->getHidlTarget()) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001095 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001096 persistentSurface->getHidlTarget());
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001097 if (!hidlInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001098 ALOGE("Corrupted input surface");
1099 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1100 return;
1101 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001102 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1103 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001104 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001105 inputSurface));
1106 bufferProducer = inputSurface->getGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001107 } else {
1108 int32_t width = 0;
1109 (void)outputFormat->findInt32("width", &width);
1110 int32_t height = 0;
1111 (void)outputFormat->findInt32("height", &height);
1112 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001113 persistentSurface->getBufferSource(), width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001114 bufferProducer = persistentSurface->getBufferProducer();
1115 }
1116
1117 if (err != OK) {
1118 ALOGE("Failed to set up input surface: %d", err);
1119 mCallback->onInputSurfaceCreationFailed(err);
1120 return;
1121 }
1122
1123 mCallback->onInputSurfaceCreated(
1124 inputFormat,
1125 outputFormat,
1126 new BufferProducerWrapper(bufferProducer));
1127}
1128
1129status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
1130 Mutexed<Config>::Locked config(mConfig);
1131 config->mUsingSurface = true;
1132
1133 // we are now using surface - apply default color aspects to input format - as well as
1134 // get dataspace
1135 bool inputFormatChanged = config->updateFormats(config->IS_INPUT);
1136 ALOGD("input format %s to %s",
1137 inputFormatChanged ? "changed" : "unchanged",
1138 config->mInputFormat->debugString().c_str());
1139
1140 // configure dataspace
1141 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1142 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1143 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1144 surface->setDataSpace(dataSpace);
1145
1146 status_t err = mChannel->setInputSurface(surface);
1147 if (err != OK) {
1148 // undo input format update
1149 config->mUsingSurface = false;
1150 (void)config->updateFormats(config->IS_INPUT);
1151 return err;
1152 }
1153 config->mInputSurface = surface;
1154
1155 if (config->mISConfig) {
1156 surface->configure(*config->mISConfig);
1157 } else {
1158 ALOGD("ISConfig: no configuration");
1159 }
1160
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001161 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001162}
1163
1164void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1165 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1166 msg->setObject("surface", surface);
1167 msg->post();
1168}
1169
1170void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1171 sp<AMessage> inputFormat;
1172 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001173 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001174 {
1175 Mutexed<Config>::Locked config(mConfig);
1176 inputFormat = config->mInputFormat;
1177 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001178 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001179 }
1180 auto hidlTarget = surface->getHidlTarget();
1181 if (hidlTarget) {
1182 sp<IInputSurface> inputSurface =
1183 IInputSurface::castFrom(hidlTarget);
1184 if (!inputSurface) {
1185 ALOGE("Failed to set input surface: Corrupted surface.");
1186 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1187 return;
1188 }
1189 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1190 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1191 if (err != OK) {
1192 ALOGE("Failed to set up input surface: %d", err);
1193 mCallback->onInputSurfaceDeclined(err);
1194 return;
1195 }
1196 } else {
1197 int32_t width = 0;
1198 (void)outputFormat->findInt32("width", &width);
1199 int32_t height = 0;
1200 (void)outputFormat->findInt32("height", &height);
1201 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001202 surface->getBufferSource(), width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001203 if (err != OK) {
1204 ALOGE("Failed to set up input surface: %d", err);
1205 mCallback->onInputSurfaceDeclined(err);
1206 return;
1207 }
1208 }
1209 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1210}
1211
1212void CCodec::initiateStart() {
1213 auto setStarting = [this] {
1214 Mutexed<State>::Locked state(mState);
1215 if (state->get() != ALLOCATED) {
1216 return UNKNOWN_ERROR;
1217 }
1218 state->set(STARTING);
1219 return OK;
1220 };
1221 if (tryAndReportOnError(setStarting) != OK) {
1222 return;
1223 }
1224
1225 (new AMessage(kWhatStart, this))->post();
1226}
1227
1228void CCodec::start() {
1229 std::shared_ptr<Codec2Client::Component> comp;
1230 auto checkStarting = [this, &comp] {
1231 Mutexed<State>::Locked state(mState);
1232 if (state->get() != STARTING) {
1233 return UNKNOWN_ERROR;
1234 }
1235 comp = state->comp;
1236 return OK;
1237 };
1238 if (tryAndReportOnError(checkStarting) != OK) {
1239 return;
1240 }
1241
1242 c2_status_t err = comp->start();
1243 if (err != C2_OK) {
1244 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1245 ACTION_CODE_FATAL);
1246 return;
1247 }
1248 sp<AMessage> inputFormat;
1249 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001250 status_t err2 = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001251 {
1252 Mutexed<Config>::Locked config(mConfig);
1253 inputFormat = config->mInputFormat;
1254 outputFormat = config->mOutputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001255 if (config->mInputSurface) {
1256 err2 = config->mInputSurface->start();
1257 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001258 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001259 if (err2 != OK) {
1260 mCallback->onError(err2, ACTION_CODE_FATAL);
1261 return;
1262 }
1263 err2 = mChannel->start(inputFormat, outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001264 if (err2 != OK) {
1265 mCallback->onError(err2, ACTION_CODE_FATAL);
1266 return;
1267 }
1268
1269 auto setRunning = [this] {
1270 Mutexed<State>::Locked state(mState);
1271 if (state->get() != STARTING) {
1272 return UNKNOWN_ERROR;
1273 }
1274 state->set(RUNNING);
1275 return OK;
1276 };
1277 if (tryAndReportOnError(setRunning) != OK) {
1278 return;
1279 }
1280 mCallback->onStartCompleted();
1281
1282 (void)mChannel->requestInitialInputBuffers();
1283}
1284
1285void CCodec::initiateShutdown(bool keepComponentAllocated) {
1286 if (keepComponentAllocated) {
1287 initiateStop();
1288 } else {
1289 initiateRelease();
1290 }
1291}
1292
1293void CCodec::initiateStop() {
1294 {
1295 Mutexed<State>::Locked state(mState);
1296 if (state->get() == ALLOCATED
1297 || state->get() == RELEASED
1298 || state->get() == STOPPING
1299 || state->get() == RELEASING) {
1300 // We're already stopped, released, or doing it right now.
1301 state.unlock();
1302 mCallback->onStopCompleted();
1303 state.lock();
1304 return;
1305 }
1306 state->set(STOPPING);
1307 }
1308
1309 mChannel->stop();
1310 (new AMessage(kWhatStop, this))->post();
1311}
1312
1313void CCodec::stop() {
1314 std::shared_ptr<Codec2Client::Component> comp;
1315 {
1316 Mutexed<State>::Locked state(mState);
1317 if (state->get() == RELEASING) {
1318 state.unlock();
1319 // We're already stopped or release is in progress.
1320 mCallback->onStopCompleted();
1321 state.lock();
1322 return;
1323 } else if (state->get() != STOPPING) {
1324 state.unlock();
1325 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1326 state.lock();
1327 return;
1328 }
1329 comp = state->comp;
1330 }
1331 status_t err = comp->stop();
1332 if (err != C2_OK) {
1333 // TODO: convert err into status_t
1334 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1335 }
1336
1337 {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001338 Mutexed<Config>::Locked config(mConfig);
1339 if (config->mInputSurface) {
1340 config->mInputSurface->disconnect();
1341 config->mInputSurface = nullptr;
1342 }
1343 }
1344 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001345 Mutexed<State>::Locked state(mState);
1346 if (state->get() == STOPPING) {
1347 state->set(ALLOCATED);
1348 }
1349 }
1350 mCallback->onStopCompleted();
1351}
1352
1353void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001354 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001355 {
1356 Mutexed<State>::Locked state(mState);
1357 if (state->get() == RELEASED || state->get() == RELEASING) {
1358 // We're already released or doing it right now.
1359 if (sendCallback) {
1360 state.unlock();
1361 mCallback->onReleaseCompleted();
1362 state.lock();
1363 }
1364 return;
1365 }
1366 if (state->get() == ALLOCATING) {
1367 state->set(RELEASING);
1368 // With the altered state allocate() would fail and clean up.
1369 if (sendCallback) {
1370 state.unlock();
1371 mCallback->onReleaseCompleted();
1372 state.lock();
1373 }
1374 return;
1375 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001376 if (state->get() == STARTING
1377 || state->get() == RUNNING
1378 || state->get() == STOPPING) {
1379 // Input surface may have been started, so clean up is needed.
1380 clearInputSurfaceIfNeeded = true;
1381 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001382 state->set(RELEASING);
1383 }
1384
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001385 if (clearInputSurfaceIfNeeded) {
1386 Mutexed<Config>::Locked config(mConfig);
1387 if (config->mInputSurface) {
1388 config->mInputSurface->disconnect();
1389 config->mInputSurface = nullptr;
1390 }
1391 }
1392
Pawin Vongmasa36653902018-11-15 00:10:25 -08001393 mChannel->stop();
1394 // thiz holds strong ref to this while the thread is running.
1395 sp<CCodec> thiz(this);
1396 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1397}
1398
1399void CCodec::release(bool sendCallback) {
1400 std::shared_ptr<Codec2Client::Component> comp;
1401 {
1402 Mutexed<State>::Locked state(mState);
1403 if (state->get() == RELEASED) {
1404 if (sendCallback) {
1405 state.unlock();
1406 mCallback->onReleaseCompleted();
1407 state.lock();
1408 }
1409 return;
1410 }
1411 comp = state->comp;
1412 }
1413 comp->release();
1414
1415 {
1416 Mutexed<State>::Locked state(mState);
1417 state->set(RELEASED);
1418 state->comp.reset();
1419 }
1420 if (sendCallback) {
1421 mCallback->onReleaseCompleted();
1422 }
1423}
1424
1425status_t CCodec::setSurface(const sp<Surface> &surface) {
1426 return mChannel->setSurface(surface);
1427}
1428
1429void CCodec::signalFlush() {
1430 status_t err = [this] {
1431 Mutexed<State>::Locked state(mState);
1432 if (state->get() == FLUSHED) {
1433 return ALREADY_EXISTS;
1434 }
1435 if (state->get() != RUNNING) {
1436 return UNKNOWN_ERROR;
1437 }
1438 state->set(FLUSHING);
1439 return OK;
1440 }();
1441 switch (err) {
1442 case ALREADY_EXISTS:
1443 mCallback->onFlushCompleted();
1444 return;
1445 case OK:
1446 break;
1447 default:
1448 mCallback->onError(err, ACTION_CODE_FATAL);
1449 return;
1450 }
1451
1452 mChannel->stop();
1453 (new AMessage(kWhatFlush, this))->post();
1454}
1455
1456void CCodec::flush() {
1457 std::shared_ptr<Codec2Client::Component> comp;
1458 auto checkFlushing = [this, &comp] {
1459 Mutexed<State>::Locked state(mState);
1460 if (state->get() != FLUSHING) {
1461 return UNKNOWN_ERROR;
1462 }
1463 comp = state->comp;
1464 return OK;
1465 };
1466 if (tryAndReportOnError(checkFlushing) != OK) {
1467 return;
1468 }
1469
1470 std::list<std::unique_ptr<C2Work>> flushedWork;
1471 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1472 {
1473 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1474 flushedWork.splice(flushedWork.end(), *queue);
1475 }
1476 if (err != C2_OK) {
1477 // TODO: convert err into status_t
1478 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1479 }
1480
1481 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001482
1483 {
1484 Mutexed<State>::Locked state(mState);
1485 state->set(FLUSHED);
1486 }
1487 mCallback->onFlushCompleted();
1488}
1489
1490void CCodec::signalResume() {
1491 auto setResuming = [this] {
1492 Mutexed<State>::Locked state(mState);
1493 if (state->get() != FLUSHED) {
1494 return UNKNOWN_ERROR;
1495 }
1496 state->set(RESUMING);
1497 return OK;
1498 };
1499 if (tryAndReportOnError(setResuming) != OK) {
1500 return;
1501 }
1502
1503 (void)mChannel->start(nullptr, nullptr);
1504
1505 {
1506 Mutexed<State>::Locked state(mState);
1507 if (state->get() != RESUMING) {
1508 state.unlock();
1509 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1510 state.lock();
1511 return;
1512 }
1513 state->set(RUNNING);
1514 }
1515
1516 (void)mChannel->requestInitialInputBuffers();
1517}
1518
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001519void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001520 std::shared_ptr<Codec2Client::Component> comp;
1521 auto checkState = [this, &comp] {
1522 Mutexed<State>::Locked state(mState);
1523 if (state->get() == RELEASED) {
1524 return INVALID_OPERATION;
1525 }
1526 comp = state->comp;
1527 return OK;
1528 };
1529 if (tryAndReportOnError(checkState) != OK) {
1530 return;
1531 }
1532
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001533 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1534 // the behavior here.
1535 sp<AMessage> params = msg;
1536 int32_t bitrate;
1537 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1538 params = msg->dup();
1539 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1540 }
1541
Pawin Vongmasa36653902018-11-15 00:10:25 -08001542 Mutexed<Config>::Locked config(mConfig);
1543
1544 /**
1545 * Handle input surface parameters
1546 */
1547 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1548 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001549 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001550
1551 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1552 config->mISConfig->mStopped = false;
1553 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1554 config->mISConfig->mStopped = true;
1555 }
1556
1557 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001558 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001559 config->mISConfig->mSuspended = value;
1560 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001561 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001562 }
1563
1564 (void)config->mInputSurface->configure(*config->mISConfig);
1565 if (config->mISConfig->mStopped) {
1566 config->mInputFormat->setInt64(
1567 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1568 }
1569 }
1570
1571 std::vector<std::unique_ptr<C2Param>> configUpdate;
1572 (void)config->getConfigUpdateFromSdkParams(
1573 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1574 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1575 // Parameter synchronization is not defined when using input surface. For now, route
1576 // these directly to the component.
1577 if (config->mInputSurface == nullptr
1578 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1579 || comp->getName().find("c2.android.") == 0)) {
1580 mChannel->setParameters(configUpdate);
1581 } else {
1582 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1583 }
1584}
1585
1586void CCodec::signalEndOfInputStream() {
1587 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1588}
1589
1590void CCodec::signalRequestIDRFrame() {
1591 std::shared_ptr<Codec2Client::Component> comp;
1592 {
1593 Mutexed<State>::Locked state(mState);
1594 if (state->get() == RELEASED) {
1595 ALOGD("no IDR request sent since component is released");
1596 return;
1597 }
1598 comp = state->comp;
1599 }
1600 ALOGV("request IDR");
1601 Mutexed<Config>::Locked config(mConfig);
1602 std::vector<std::unique_ptr<C2Param>> params;
1603 params.push_back(
1604 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1605 config->setParameters(comp, params, C2_MAY_BLOCK);
1606}
1607
Wonsik Kimab34ed62019-01-31 15:28:46 -08001608void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001609 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001610 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1611 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001612 }
1613 (new AMessage(kWhatWorkDone, this))->post();
1614}
1615
Wonsik Kimab34ed62019-01-31 15:28:46 -08001616void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1617 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001618 if (arrayIndex == 0) {
1619 // We always put no more than one buffer per work, if we use an input surface.
1620 Mutexed<Config>::Locked config(mConfig);
1621 if (config->mInputSurface) {
1622 config->mInputSurface->onInputBufferDone(frameIndex);
1623 }
1624 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001625}
1626
1627void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1628 TimePoint now = std::chrono::steady_clock::now();
1629 CCodecWatchdog::getInstance()->watch(this);
1630 switch (msg->what()) {
1631 case kWhatAllocate: {
1632 // C2ComponentStore::createComponent() should return within 100ms.
1633 setDeadline(now, 150ms, "allocate");
1634 sp<RefBase> obj;
1635 CHECK(msg->findObject("codecInfo", &obj));
1636 allocate((MediaCodecInfo *)obj.get());
1637 break;
1638 }
1639 case kWhatConfigure: {
1640 // C2Component::commit_sm() should return within 5ms.
1641 setDeadline(now, 250ms, "configure");
1642 sp<AMessage> format;
1643 CHECK(msg->findMessage("format", &format));
1644 configure(format);
1645 break;
1646 }
1647 case kWhatStart: {
1648 // C2Component::start() should return within 500ms.
1649 setDeadline(now, 550ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001650 start();
1651 break;
1652 }
1653 case kWhatStop: {
1654 // C2Component::stop() should return within 500ms.
1655 setDeadline(now, 550ms, "stop");
1656 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001657 break;
1658 }
1659 case kWhatFlush: {
1660 // C2Component::flush_sm() should return within 5ms.
1661 setDeadline(now, 50ms, "flush");
1662 flush();
1663 break;
1664 }
1665 case kWhatCreateInputSurface: {
1666 // Surface operations may be briefly blocking.
1667 setDeadline(now, 100ms, "createInputSurface");
1668 createInputSurface();
1669 break;
1670 }
1671 case kWhatSetInputSurface: {
1672 // Surface operations may be briefly blocking.
1673 setDeadline(now, 100ms, "setInputSurface");
1674 sp<RefBase> obj;
1675 CHECK(msg->findObject("surface", &obj));
1676 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1677 setInputSurface(surface);
1678 break;
1679 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001680 case kWhatWorkDone: {
1681 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001682 bool shouldPost = false;
1683 {
1684 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1685 if (queue->empty()) {
1686 break;
1687 }
1688 work.swap(queue->front());
1689 queue->pop_front();
1690 shouldPost = !queue->empty();
1691 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001692 if (shouldPost) {
1693 (new AMessage(kWhatWorkDone, this))->post();
1694 }
1695
Pawin Vongmasa36653902018-11-15 00:10:25 -08001696 // handle configuration changes in work done
1697 Mutexed<Config>::Locked config(mConfig);
1698 bool changed = false;
1699 Config::Watcher<C2StreamInitDataInfo::output> initData =
1700 config->watch<C2StreamInitDataInfo::output>();
1701 if (!work->worklets.empty()
1702 && (work->worklets.front()->output.flags
1703 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1704
1705 // copy buffer info to config
1706 std::vector<std::unique_ptr<C2Param>> updates =
1707 std::move(work->worklets.front()->output.configUpdate);
1708 unsigned stream = 0;
1709 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1710 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1711 // move all info into output-stream #0 domain
1712 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1713 }
1714 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1715 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1716 // block.crop().left, block.crop().top,
1717 // block.crop().width, block.crop().height,
1718 // block.width(), block.height());
1719 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1720 updates.emplace_back(new C2StreamPictureSizeInfo::output(
1721 stream, block.width(), block.height()));
1722 break; // for now only do the first block
1723 }
1724 ++stream;
1725 }
1726
1727 changed = config->updateConfiguration(updates, config->mOutputDomain);
1728
1729 // copy standard infos to graphic buffers if not already present (otherwise, we
1730 // may overwrite the actual intermediate value with a final value)
1731 stream = 0;
1732 const static std::vector<C2Param::Index> stdGfxInfos = {
1733 C2StreamRotationInfo::output::PARAM_TYPE,
1734 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1735 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1736 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001737 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001738 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1739 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1740 };
1741 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1742 if (buf->data().graphicBlocks().size()) {
1743 for (C2Param::Index ix : stdGfxInfos) {
1744 if (!buf->hasInfo(ix)) {
1745 const C2Param *param =
1746 config->getConfigParameterValue(ix.withStream(stream));
1747 if (param) {
1748 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1749 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1750 }
1751 }
1752 }
1753 }
1754 ++stream;
1755 }
1756 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001757 if (config->mInputSurface) {
1758 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1759 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001760 mChannel->onWorkDone(
1761 std::move(work), changed ? config->mOutputFormat : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001762 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001763 break;
1764 }
1765 case kWhatWatch: {
1766 // watch message already posted; no-op.
1767 break;
1768 }
1769 default: {
1770 ALOGE("unrecognized message");
1771 break;
1772 }
1773 }
1774 setDeadline(TimePoint::max(), 0ms, "none");
1775}
1776
1777void CCodec::setDeadline(
1778 const TimePoint &now,
1779 const std::chrono::milliseconds &timeout,
1780 const char *name) {
1781 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1782 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1783 deadline->set(now + (timeout * mult), name);
1784}
1785
1786void CCodec::initiateReleaseIfStuck() {
1787 std::string name;
1788 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001789 {
1790 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001791 if (deadline->get() < std::chrono::steady_clock::now()) {
1792 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001793 }
1794 if (deadline->get() != TimePoint::max()) {
1795 pendingDeadline = true;
1796 }
1797 }
1798 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001799 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1800 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1801 if (elapsed >= kWorkDurationThreshold) {
1802 name = "queue";
1803 }
1804 if (elapsed > 0s) {
1805 pendingDeadline = true;
1806 }
1807 }
1808 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001809 // We're not stuck.
1810 if (pendingDeadline) {
1811 // If we are not stuck yet but still has deadline coming up,
1812 // post watch message to check back later.
1813 (new AMessage(kWhatWatch, this))->post();
1814 }
1815 return;
1816 }
1817
1818 ALOGW("previous call to %s exceeded timeout", name.c_str());
1819 initiateRelease(false);
1820 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1821}
1822
Pawin Vongmasa36653902018-11-15 00:10:25 -08001823} // namespace android
1824
1825extern "C" android::CodecBase *CreateCodec() {
1826 return new android::CCodec;
1827}
1828
Lajos Molnar47118272019-01-31 16:28:04 -08001829// Create Codec 2.0 input surface
Pawin Vongmasa36653902018-11-15 00:10:25 -08001830extern "C" android::PersistentSurface *CreateInputSurface() {
1831 // Attempt to create a Codec2's input surface.
1832 std::shared_ptr<android::Codec2Client::InputSurface> inputSurface =
1833 android::Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001834 if (!inputSurface) {
1835 return nullptr;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001836 }
Lajos Molnar47118272019-01-31 16:28:04 -08001837 return new android::PersistentSurface(
1838 inputSurface->getGraphicBufferProducer(),
1839 static_cast<android::sp<android::hidl::base::V1_0::IBase>>(
1840 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001841}
1842