blob: 895be1a6fbc76a971ef1691a2d1476bb0f32c782 [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
Wonsik Kimbd557932019-07-02 15:51:20 -0700377 if (status.str().empty()) {
378 ALOGD("ISConfig not changed");
379 } else {
380 ALOGD("ISConfig%s", status.str().c_str());
381 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800382 return err;
383 }
384
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700385 void onInputBufferDone(c2_cntr64_t index) override {
386 mNode->onInputBufferDone(index);
387 }
388
Pawin Vongmasa36653902018-11-15 00:10:25 -0800389private:
390 sp<BGraphicBufferSource> mSource;
391 sp<C2OMXNode> mNode;
392 uint32_t mWidth;
393 uint32_t mHeight;
394 Config mConfig;
395};
396
397class Codec2ClientInterfaceWrapper : public C2ComponentStore {
398 std::shared_ptr<Codec2Client> mClient;
399
400public:
401 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
402 : mClient(client) { }
403
404 virtual ~Codec2ClientInterfaceWrapper() = default;
405
406 virtual c2_status_t config_sm(
407 const std::vector<C2Param *> &params,
408 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
409 return mClient->config(params, C2_MAY_BLOCK, failures);
410 };
411
412 virtual c2_status_t copyBuffer(
413 std::shared_ptr<C2GraphicBuffer>,
414 std::shared_ptr<C2GraphicBuffer>) {
415 return C2_OMITTED;
416 }
417
418 virtual c2_status_t createComponent(
419 C2String, std::shared_ptr<C2Component> *const component) {
420 component->reset();
421 return C2_OMITTED;
422 }
423
424 virtual c2_status_t createInterface(
425 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
426 interface->reset();
427 return C2_OMITTED;
428 }
429
430 virtual c2_status_t query_sm(
431 const std::vector<C2Param *> &stackParams,
432 const std::vector<C2Param::Index> &heapParamIndices,
433 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
434 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
435 }
436
437 virtual c2_status_t querySupportedParams_nb(
438 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
439 return mClient->querySupportedParams(params);
440 }
441
442 virtual c2_status_t querySupportedValues_sm(
443 std::vector<C2FieldSupportedValuesQuery> &fields) const {
444 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
445 }
446
447 virtual C2String getName() const {
448 return mClient->getName();
449 }
450
451 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
452 return mClient->getParamReflector();
453 }
454
455 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
456 return std::vector<std::shared_ptr<const C2Component::Traits>>();
457 }
458};
459
460} // namespace
461
462// CCodec::ClientListener
463
464struct CCodec::ClientListener : public Codec2Client::Listener {
465
466 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
467
468 virtual void onWorkDone(
469 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800470 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800471 (void)component;
472 sp<CCodec> codec(mCodec.promote());
473 if (!codec) {
474 return;
475 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800476 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800477 }
478
479 virtual void onTripped(
480 const std::weak_ptr<Codec2Client::Component>& component,
481 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
482 ) override {
483 // TODO
484 (void)component;
485 (void)settingResult;
486 }
487
488 virtual void onError(
489 const std::weak_ptr<Codec2Client::Component>& component,
490 uint32_t errorCode) override {
491 // TODO
492 (void)component;
493 (void)errorCode;
494 }
495
496 virtual void onDeath(
497 const std::weak_ptr<Codec2Client::Component>& component) override {
498 { // Log the death of the component.
499 std::shared_ptr<Codec2Client::Component> comp = component.lock();
500 if (!comp) {
501 ALOGE("Codec2 component died.");
502 } else {
503 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
504 }
505 }
506
507 // Report to MediaCodec.
508 sp<CCodec> codec(mCodec.promote());
509 if (!codec || !codec->mCallback) {
510 return;
511 }
512 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
513 }
514
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800515 virtual void onFrameRendered(uint64_t bufferQueueId,
516 int32_t slotId,
517 int64_t timestampNs) override {
518 // TODO: implement
519 (void)bufferQueueId;
520 (void)slotId;
521 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800522 }
523
524 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800525 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800526 sp<CCodec> codec(mCodec.promote());
527 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800528 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800529 }
530 }
531
532private:
533 wp<CCodec> mCodec;
534};
535
536// CCodecCallbackImpl
537
538class CCodecCallbackImpl : public CCodecCallback {
539public:
540 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
541 ~CCodecCallbackImpl() override = default;
542
543 void onError(status_t err, enum ActionCode actionCode) override {
544 mCodec->mCallback->onError(err, actionCode);
545 }
546
547 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
548 mCodec->mCallback->onOutputFramesRendered(
549 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
550 }
551
Pawin Vongmasa36653902018-11-15 00:10:25 -0800552 void onOutputBuffersChanged() override {
553 mCodec->mCallback->onOutputBuffersChanged();
554 }
555
556private:
557 CCodec *mCodec;
558};
559
560// CCodec
561
562CCodec::CCodec()
Wonsik Kimab34ed62019-01-31 15:28:46 -0800563 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800564}
565
566CCodec::~CCodec() {
567}
568
569std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
570 return mChannel;
571}
572
573status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
574 status_t err = job();
575 if (err != C2_OK) {
576 mCallback->onError(err, ACTION_CODE_FATAL);
577 }
578 return err;
579}
580
581void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
582 auto setAllocating = [this] {
583 Mutexed<State>::Locked state(mState);
584 if (state->get() != RELEASED) {
585 return INVALID_OPERATION;
586 }
587 state->set(ALLOCATING);
588 return OK;
589 };
590 if (tryAndReportOnError(setAllocating) != OK) {
591 return;
592 }
593
594 sp<RefBase> codecInfo;
595 CHECK(msg->findObject("codecInfo", &codecInfo));
596 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
597
598 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
599 allocMsg->setObject("codecInfo", codecInfo);
600 allocMsg->post();
601}
602
603void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
604 if (codecInfo == nullptr) {
605 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
606 return;
607 }
608 ALOGD("allocate(%s)", codecInfo->getCodecName());
609 mClientListener.reset(new ClientListener(this));
610
611 AString componentName = codecInfo->getCodecName();
612 std::shared_ptr<Codec2Client> client;
613
614 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700615 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800616 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800617 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800618 SetPreferredCodec2ComponentStore(
619 std::make_shared<Codec2ClientInterfaceWrapper>(client));
620 }
621
622 std::shared_ptr<Codec2Client::Component> comp =
623 Codec2Client::CreateComponentByName(
624 componentName.c_str(),
625 mClientListener,
626 &client);
627 if (!comp) {
628 ALOGE("Failed Create component: %s", componentName.c_str());
629 Mutexed<State>::Locked state(mState);
630 state->set(RELEASED);
631 state.unlock();
632 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
633 state.lock();
634 return;
635 }
636 ALOGI("Created component [%s]", componentName.c_str());
637 mChannel->setComponent(comp);
638 auto setAllocated = [this, comp, client] {
639 Mutexed<State>::Locked state(mState);
640 if (state->get() != ALLOCATING) {
641 state->set(RELEASED);
642 return UNKNOWN_ERROR;
643 }
644 state->set(ALLOCATED);
645 state->comp = comp;
646 mClient = client;
647 return OK;
648 };
649 if (tryAndReportOnError(setAllocated) != OK) {
650 return;
651 }
652
653 // initialize config here in case setParameters is called prior to configure
654 Mutexed<Config>::Locked config(mConfig);
655 status_t err = config->initialize(mClient, comp);
656 if (err != OK) {
657 ALOGW("Failed to initialize configuration support");
658 // TODO: report error once we complete implementation.
659 }
660 config->queryConfiguration(comp);
661
662 mCallback->onComponentAllocated(componentName.c_str());
663}
664
665void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
666 auto checkAllocated = [this] {
667 Mutexed<State>::Locked state(mState);
668 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
669 };
670 if (tryAndReportOnError(checkAllocated) != OK) {
671 return;
672 }
673
674 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
675 msg->setMessage("format", format);
676 msg->post();
677}
678
679void CCodec::configure(const sp<AMessage> &msg) {
680 std::shared_ptr<Codec2Client::Component> comp;
681 auto checkAllocated = [this, &comp] {
682 Mutexed<State>::Locked state(mState);
683 if (state->get() != ALLOCATED) {
684 state->set(RELEASED);
685 return UNKNOWN_ERROR;
686 }
687 comp = state->comp;
688 return OK;
689 };
690 if (tryAndReportOnError(checkAllocated) != OK) {
691 return;
692 }
693
694 auto doConfig = [msg, comp, this]() -> status_t {
695 AString mime;
696 if (!msg->findString("mime", &mime)) {
697 return BAD_VALUE;
698 }
699
700 int32_t encoder;
701 if (!msg->findInt32("encoder", &encoder)) {
702 encoder = false;
703 }
704
705 // TODO: read from intf()
706 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
707 return UNKNOWN_ERROR;
708 }
709
710 int32_t storeMeta;
711 if (encoder
712 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
713 && storeMeta != kMetadataBufferTypeInvalid) {
714 if (storeMeta != kMetadataBufferTypeANWBuffer) {
715 ALOGD("Only ANW buffers are supported for legacy metadata mode");
716 return BAD_VALUE;
717 }
718 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
719 }
720
721 sp<RefBase> obj;
722 sp<Surface> surface;
723 if (msg->findObject("native-window", &obj)) {
724 surface = static_cast<Surface *>(obj.get());
725 setSurface(surface);
726 }
727
728 Mutexed<Config>::Locked config(mConfig);
729 config->mUsingSurface = surface != nullptr;
730
Wonsik Kim1114eea2019-02-25 14:35:24 -0800731 // Enforce required parameters
732 int32_t i32;
733 float flt;
734 if (config->mDomain & Config::IS_AUDIO) {
735 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
736 ALOGD("sample rate is missing, which is required for audio components.");
737 return BAD_VALUE;
738 }
739 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
740 ALOGD("channel count is missing, which is required for audio components.");
741 return BAD_VALUE;
742 }
743 if ((config->mDomain & Config::IS_ENCODER)
744 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
745 && !msg->findInt32(KEY_BIT_RATE, &i32)
746 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
747 ALOGD("bitrate is missing, which is required for audio encoders.");
748 return BAD_VALUE;
749 }
750 }
751 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
752 if (!msg->findInt32(KEY_WIDTH, &i32)) {
753 ALOGD("width is missing, which is required for image/video components.");
754 return BAD_VALUE;
755 }
756 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
757 ALOGD("height is missing, which is required for image/video components.");
758 return BAD_VALUE;
759 }
760 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700761 int32_t mode = BITRATE_MODE_VBR;
762 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700763 if (!msg->findInt32(KEY_QUALITY, &i32)) {
764 ALOGD("quality is missing, which is required for video encoders in CQ.");
765 return BAD_VALUE;
766 }
767 } else {
768 if (!msg->findInt32(KEY_BIT_RATE, &i32)
769 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
770 ALOGD("bitrate is missing, which is required for video encoders.");
771 return BAD_VALUE;
772 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800773 }
774 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
775 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
776 ALOGD("I frame interval is missing, which is required for video encoders.");
777 return BAD_VALUE;
778 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700779 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
780 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
781 ALOGD("frame rate is missing, which is required for video encoders.");
782 return BAD_VALUE;
783 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800784 }
785 }
786
Pawin Vongmasa36653902018-11-15 00:10:25 -0800787 /*
788 * Handle input surface configuration
789 */
790 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
791 && (config->mDomain & Config::IS_ENCODER)) {
792 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
793 {
794 config->mISConfig->mMinFps = 0;
795 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800796 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800797 config->mISConfig->mMinFps = 1e6 / value;
798 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700799 if (!msg->findFloat(
800 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
801 config->mISConfig->mMaxFps = -1;
802 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800803 config->mISConfig->mMinAdjustedFps = 0;
804 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800805 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800806 if (value < 0 && value >= INT32_MIN) {
807 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700808 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800809 } else if (value > 0 && value <= INT32_MAX) {
810 config->mISConfig->mMinAdjustedFps = 1e6 / value;
811 }
812 }
813 }
814
815 {
816 double value;
817 if (msg->findDouble("time-lapse-fps", &value)) {
818 config->mISConfig->mCaptureFps = value;
819 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
820 }
821 }
822
823 {
824 config->mISConfig->mSuspended = false;
825 config->mISConfig->mSuspendAtUs = -1;
826 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800827 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800828 config->mISConfig->mSuspended = true;
829 }
830 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700831 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800832 }
833
834 /*
835 * Handle desired color format.
836 */
837 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
838 int32_t format = -1;
839 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
840 /*
841 * Also handle default color format (encoders require color format, so this is only
842 * needed for decoders.
843 */
844 if (!(config->mDomain & Config::IS_ENCODER)) {
845 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
846 }
847 }
848
849 if (format >= 0) {
850 msg->setInt32("android._color-format", format);
851 }
852 }
853
854 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800855 // NOTE: We used to ignore "video-bitrate" at configure; replicate
856 // the behavior here.
857 sp<AMessage> sdkParams = msg;
858 int32_t videoBitrate;
859 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
860 sdkParams = msg->dup();
861 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
862 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800863 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800864 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800865 if (err != OK) {
866 ALOGW("failed to convert configuration to c2 params");
867 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700868
869 int32_t maxBframes = 0;
870 if ((config->mDomain & Config::IS_ENCODER)
871 && (config->mDomain & Config::IS_VIDEO)
872 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
873 && maxBframes > 0) {
874 std::unique_ptr<C2StreamGopTuning::output> gop =
875 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
876 gop->m.values[0] = { P_FRAME, UINT32_MAX };
877 gop->m.values[1] = {
878 C2Config::picture_type_t(P_FRAME | B_FRAME),
879 uint32_t(maxBframes)
880 };
881 configUpdate.push_back(std::move(gop));
882 }
883
Pawin Vongmasa36653902018-11-15 00:10:25 -0800884 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
885 if (err != OK) {
886 ALOGW("failed to configure c2 params");
887 return err;
888 }
889
890 std::vector<std::unique_ptr<C2Param>> params;
891 C2StreamUsageTuning::input usage(0u, 0u);
892 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700893 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800894
895 std::initializer_list<C2Param::Index> indices {
896 };
897 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700898 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800899 indices,
900 C2_DONT_BLOCK,
901 &params);
902 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
903 ALOGE("Failed to query component interface: %d", c2err);
904 return UNKNOWN_ERROR;
905 }
906 if (params.size() != indices.size()) {
907 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
908 indices.size(), params.size());
909 return UNKNOWN_ERROR;
910 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700911 if (usage) {
912 if (usage.value & C2MemoryUsage::CPU_READ) {
913 config->mInputFormat->setInt32("using-sw-read-often", true);
914 }
915 if (config->mISConfig) {
916 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
917 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
918 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800919 }
920
921 // NOTE: we don't blindly use client specified input size if specified as clients
922 // at times specify too small size. Instead, mimic the behavior from OMX, where the
923 // client specified size is only used to ask for bigger buffers than component suggested
924 // size.
925 int32_t clientInputSize = 0;
926 bool clientSpecifiedInputSize =
927 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
928 // TEMP: enforce minimum buffer size of 1MB for video decoders
929 // and 16K / 4K for audio encoders/decoders
930 if (maxInputSize.value == 0) {
931 if (config->mDomain & Config::IS_AUDIO) {
932 maxInputSize.value = encoder ? 16384 : 4096;
933 } else if (!encoder) {
934 maxInputSize.value = 1048576u;
935 }
936 }
937
938 // verify that CSD fits into this size (if defined)
939 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
940 sp<ABuffer> csd;
941 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
942 if (csd && csd->size() > maxInputSize.value) {
943 maxInputSize.value = csd->size();
944 }
945 }
946 }
947
948 // TODO: do this based on component requiring linear allocator for input
949 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
950 if (clientSpecifiedInputSize) {
951 // Warn that we're overriding client's max input size if necessary.
952 if ((uint32_t)clientInputSize < maxInputSize.value) {
953 ALOGD("client requested max input size %d, which is smaller than "
954 "what component recommended (%u); overriding with component "
955 "recommendation.", clientInputSize, maxInputSize.value);
956 ALOGW("This behavior is subject to change. It is recommended that "
957 "app developers double check whether the requested "
958 "max input size is in reasonable range.");
959 } else {
960 maxInputSize.value = clientInputSize;
961 }
962 }
963 // Pass max input size on input format to the buffer channel (if supplied by the
964 // component or by a default)
965 if (maxInputSize.value) {
966 config->mInputFormat->setInt32(
967 KEY_MAX_INPUT_SIZE,
968 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
969 }
970 }
971
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700972 int32_t clientPrepend;
973 if ((config->mDomain & Config::IS_VIDEO)
974 && (config->mDomain & Config::IS_ENCODER)
975 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
976 && clientPrepend
977 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
978 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
979 return BAD_VALUE;
980 }
981
Pawin Vongmasa36653902018-11-15 00:10:25 -0800982 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
983 // propagate HDR static info to output format for both encoders and decoders
984 // if component supports this info, we will update from component, but only the raw port,
985 // so don't propagate if component already filled it in.
986 sp<ABuffer> hdrInfo;
987 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
988 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
989 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
990 }
991
992 // Set desired color format from configuration parameter
993 int32_t format;
994 if (msg->findInt32("android._color-format", &format)) {
995 if (config->mDomain & Config::IS_ENCODER) {
996 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
997 } else {
998 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
999 }
1000 }
1001 }
1002
1003 // propagate encoder delay and padding to output format
1004 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1005 int delay = 0;
1006 if (msg->findInt32("encoder-delay", &delay)) {
1007 config->mOutputFormat->setInt32("encoder-delay", delay);
1008 }
1009 int padding = 0;
1010 if (msg->findInt32("encoder-padding", &padding)) {
1011 config->mOutputFormat->setInt32("encoder-padding", padding);
1012 }
1013 }
1014
1015 // set channel-mask
1016 if (config->mDomain & Config::IS_AUDIO) {
1017 int32_t mask;
1018 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1019 if (config->mDomain & Config::IS_ENCODER) {
1020 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1021 } else {
1022 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1023 }
1024 }
1025 }
1026
1027 ALOGD("setup formats input: %s and output: %s",
1028 config->mInputFormat->debugString().c_str(),
1029 config->mOutputFormat->debugString().c_str());
1030 return OK;
1031 };
1032 if (tryAndReportOnError(doConfig) != OK) {
1033 return;
1034 }
1035
1036 Mutexed<Config>::Locked config(mConfig);
1037
1038 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1039}
1040
1041void CCodec::initiateCreateInputSurface() {
1042 status_t err = [this] {
1043 Mutexed<State>::Locked state(mState);
1044 if (state->get() != ALLOCATED) {
1045 return UNKNOWN_ERROR;
1046 }
1047 // TODO: read it from intf() properly.
1048 if (state->comp->getName().find("encoder") == std::string::npos) {
1049 return INVALID_OPERATION;
1050 }
1051 return OK;
1052 }();
1053 if (err != OK) {
1054 mCallback->onInputSurfaceCreationFailed(err);
1055 return;
1056 }
1057
1058 (new AMessage(kWhatCreateInputSurface, this))->post();
1059}
1060
Lajos Molnar47118272019-01-31 16:28:04 -08001061sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1062 using namespace android::hardware::media::omx::V1_0;
1063 using namespace android::hardware::media::omx::V1_0::utils;
1064 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1065 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1066 android::sp<IOmx> omx = IOmx::getService();
1067 typedef android::hardware::graphics::bufferqueue::V1_0::
1068 IGraphicBufferProducer HGraphicBufferProducer;
1069 typedef android::hardware::media::omx::V1_0::
1070 IGraphicBufferSource HGraphicBufferSource;
1071 OmxStatus s;
1072 android::sp<HGraphicBufferProducer> gbp;
1073 android::sp<HGraphicBufferSource> gbs;
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001074 using ::android::hardware::Return;
1075 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001076 [&s, &gbp, &gbs](
1077 OmxStatus status,
1078 const android::sp<HGraphicBufferProducer>& producer,
1079 const android::sp<HGraphicBufferSource>& source) {
1080 s = status;
1081 gbp = producer;
1082 gbs = source;
1083 });
1084 if (transStatus.isOk() && s == OmxStatus::OK) {
1085 return new PersistentSurface(
1086 new H2BGraphicBufferProducer(gbp),
1087 sp<::android::IGraphicBufferSource>(new LWGraphicBufferSource(gbs)));
1088 }
1089
1090 return nullptr;
1091}
1092
1093sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1094 sp<PersistentSurface> surface(CreateInputSurface());
1095
1096 if (surface == nullptr) {
1097 surface = CreateOmxInputSurface();
1098 }
1099
1100 return surface;
1101}
1102
Pawin Vongmasa36653902018-11-15 00:10:25 -08001103void CCodec::createInputSurface() {
1104 status_t err;
1105 sp<IGraphicBufferProducer> bufferProducer;
1106
1107 sp<AMessage> inputFormat;
1108 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001109 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001110 {
1111 Mutexed<Config>::Locked config(mConfig);
1112 inputFormat = config->mInputFormat;
1113 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001114 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001115 }
1116
Lajos Molnar47118272019-01-31 16:28:04 -08001117 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001118
1119 if (persistentSurface->getHidlTarget()) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001120 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(
Pawin Vongmasa36653902018-11-15 00:10:25 -08001121 persistentSurface->getHidlTarget());
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001122 if (!hidlInputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001123 ALOGE("Corrupted input surface");
1124 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1125 return;
1126 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001127 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1128 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001129 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001130 inputSurface));
1131 bufferProducer = inputSurface->getGraphicBufferProducer();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001132 } else {
1133 int32_t width = 0;
1134 (void)outputFormat->findInt32("width", &width);
1135 int32_t height = 0;
1136 (void)outputFormat->findInt32("height", &height);
1137 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001138 persistentSurface->getBufferSource(), width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001139 bufferProducer = persistentSurface->getBufferProducer();
1140 }
1141
1142 if (err != OK) {
1143 ALOGE("Failed to set up input surface: %d", err);
1144 mCallback->onInputSurfaceCreationFailed(err);
1145 return;
1146 }
1147
1148 mCallback->onInputSurfaceCreated(
1149 inputFormat,
1150 outputFormat,
1151 new BufferProducerWrapper(bufferProducer));
1152}
1153
1154status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
1155 Mutexed<Config>::Locked config(mConfig);
1156 config->mUsingSurface = true;
1157
1158 // we are now using surface - apply default color aspects to input format - as well as
1159 // get dataspace
1160 bool inputFormatChanged = config->updateFormats(config->IS_INPUT);
1161 ALOGD("input format %s to %s",
1162 inputFormatChanged ? "changed" : "unchanged",
1163 config->mInputFormat->debugString().c_str());
1164
1165 // configure dataspace
1166 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1167 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1168 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1169 surface->setDataSpace(dataSpace);
1170
1171 status_t err = mChannel->setInputSurface(surface);
1172 if (err != OK) {
1173 // undo input format update
1174 config->mUsingSurface = false;
1175 (void)config->updateFormats(config->IS_INPUT);
1176 return err;
1177 }
1178 config->mInputSurface = surface;
1179
1180 if (config->mISConfig) {
1181 surface->configure(*config->mISConfig);
1182 } else {
1183 ALOGD("ISConfig: no configuration");
1184 }
1185
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001186 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001187}
1188
1189void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1190 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1191 msg->setObject("surface", surface);
1192 msg->post();
1193}
1194
1195void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1196 sp<AMessage> inputFormat;
1197 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001198 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001199 {
1200 Mutexed<Config>::Locked config(mConfig);
1201 inputFormat = config->mInputFormat;
1202 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001203 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001204 }
1205 auto hidlTarget = surface->getHidlTarget();
1206 if (hidlTarget) {
1207 sp<IInputSurface> inputSurface =
1208 IInputSurface::castFrom(hidlTarget);
1209 if (!inputSurface) {
1210 ALOGE("Failed to set input surface: Corrupted surface.");
1211 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1212 return;
1213 }
1214 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1215 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1216 if (err != OK) {
1217 ALOGE("Failed to set up input surface: %d", err);
1218 mCallback->onInputSurfaceDeclined(err);
1219 return;
1220 }
1221 } else {
1222 int32_t width = 0;
1223 (void)outputFormat->findInt32("width", &width);
1224 int32_t height = 0;
1225 (void)outputFormat->findInt32("height", &height);
1226 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001227 surface->getBufferSource(), width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001228 if (err != OK) {
1229 ALOGE("Failed to set up input surface: %d", err);
1230 mCallback->onInputSurfaceDeclined(err);
1231 return;
1232 }
1233 }
1234 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1235}
1236
1237void CCodec::initiateStart() {
1238 auto setStarting = [this] {
1239 Mutexed<State>::Locked state(mState);
1240 if (state->get() != ALLOCATED) {
1241 return UNKNOWN_ERROR;
1242 }
1243 state->set(STARTING);
1244 return OK;
1245 };
1246 if (tryAndReportOnError(setStarting) != OK) {
1247 return;
1248 }
1249
1250 (new AMessage(kWhatStart, this))->post();
1251}
1252
1253void CCodec::start() {
1254 std::shared_ptr<Codec2Client::Component> comp;
1255 auto checkStarting = [this, &comp] {
1256 Mutexed<State>::Locked state(mState);
1257 if (state->get() != STARTING) {
1258 return UNKNOWN_ERROR;
1259 }
1260 comp = state->comp;
1261 return OK;
1262 };
1263 if (tryAndReportOnError(checkStarting) != OK) {
1264 return;
1265 }
1266
1267 c2_status_t err = comp->start();
1268 if (err != C2_OK) {
1269 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1270 ACTION_CODE_FATAL);
1271 return;
1272 }
1273 sp<AMessage> inputFormat;
1274 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001275 status_t err2 = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001276 {
1277 Mutexed<Config>::Locked config(mConfig);
1278 inputFormat = config->mInputFormat;
1279 outputFormat = config->mOutputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001280 if (config->mInputSurface) {
1281 err2 = config->mInputSurface->start();
1282 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001283 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001284 if (err2 != OK) {
1285 mCallback->onError(err2, ACTION_CODE_FATAL);
1286 return;
1287 }
1288 err2 = mChannel->start(inputFormat, outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001289 if (err2 != OK) {
1290 mCallback->onError(err2, ACTION_CODE_FATAL);
1291 return;
1292 }
1293
1294 auto setRunning = [this] {
1295 Mutexed<State>::Locked state(mState);
1296 if (state->get() != STARTING) {
1297 return UNKNOWN_ERROR;
1298 }
1299 state->set(RUNNING);
1300 return OK;
1301 };
1302 if (tryAndReportOnError(setRunning) != OK) {
1303 return;
1304 }
1305 mCallback->onStartCompleted();
1306
1307 (void)mChannel->requestInitialInputBuffers();
1308}
1309
1310void CCodec::initiateShutdown(bool keepComponentAllocated) {
1311 if (keepComponentAllocated) {
1312 initiateStop();
1313 } else {
1314 initiateRelease();
1315 }
1316}
1317
1318void CCodec::initiateStop() {
1319 {
1320 Mutexed<State>::Locked state(mState);
1321 if (state->get() == ALLOCATED
1322 || state->get() == RELEASED
1323 || state->get() == STOPPING
1324 || state->get() == RELEASING) {
1325 // We're already stopped, released, or doing it right now.
1326 state.unlock();
1327 mCallback->onStopCompleted();
1328 state.lock();
1329 return;
1330 }
1331 state->set(STOPPING);
1332 }
1333
1334 mChannel->stop();
1335 (new AMessage(kWhatStop, this))->post();
1336}
1337
1338void CCodec::stop() {
1339 std::shared_ptr<Codec2Client::Component> comp;
1340 {
1341 Mutexed<State>::Locked state(mState);
1342 if (state->get() == RELEASING) {
1343 state.unlock();
1344 // We're already stopped or release is in progress.
1345 mCallback->onStopCompleted();
1346 state.lock();
1347 return;
1348 } else if (state->get() != STOPPING) {
1349 state.unlock();
1350 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1351 state.lock();
1352 return;
1353 }
1354 comp = state->comp;
1355 }
1356 status_t err = comp->stop();
1357 if (err != C2_OK) {
1358 // TODO: convert err into status_t
1359 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1360 }
1361
1362 {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001363 Mutexed<Config>::Locked config(mConfig);
1364 if (config->mInputSurface) {
1365 config->mInputSurface->disconnect();
1366 config->mInputSurface = nullptr;
1367 }
1368 }
1369 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001370 Mutexed<State>::Locked state(mState);
1371 if (state->get() == STOPPING) {
1372 state->set(ALLOCATED);
1373 }
1374 }
1375 mCallback->onStopCompleted();
1376}
1377
1378void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001379 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001380 {
1381 Mutexed<State>::Locked state(mState);
1382 if (state->get() == RELEASED || state->get() == RELEASING) {
1383 // We're already released or doing it right now.
1384 if (sendCallback) {
1385 state.unlock();
1386 mCallback->onReleaseCompleted();
1387 state.lock();
1388 }
1389 return;
1390 }
1391 if (state->get() == ALLOCATING) {
1392 state->set(RELEASING);
1393 // With the altered state allocate() would fail and clean up.
1394 if (sendCallback) {
1395 state.unlock();
1396 mCallback->onReleaseCompleted();
1397 state.lock();
1398 }
1399 return;
1400 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001401 if (state->get() == STARTING
1402 || state->get() == RUNNING
1403 || state->get() == STOPPING) {
1404 // Input surface may have been started, so clean up is needed.
1405 clearInputSurfaceIfNeeded = true;
1406 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001407 state->set(RELEASING);
1408 }
1409
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001410 if (clearInputSurfaceIfNeeded) {
1411 Mutexed<Config>::Locked config(mConfig);
1412 if (config->mInputSurface) {
1413 config->mInputSurface->disconnect();
1414 config->mInputSurface = nullptr;
1415 }
1416 }
1417
Pawin Vongmasa36653902018-11-15 00:10:25 -08001418 mChannel->stop();
1419 // thiz holds strong ref to this while the thread is running.
1420 sp<CCodec> thiz(this);
1421 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1422}
1423
1424void CCodec::release(bool sendCallback) {
1425 std::shared_ptr<Codec2Client::Component> comp;
1426 {
1427 Mutexed<State>::Locked state(mState);
1428 if (state->get() == RELEASED) {
1429 if (sendCallback) {
1430 state.unlock();
1431 mCallback->onReleaseCompleted();
1432 state.lock();
1433 }
1434 return;
1435 }
1436 comp = state->comp;
1437 }
1438 comp->release();
1439
1440 {
1441 Mutexed<State>::Locked state(mState);
1442 state->set(RELEASED);
1443 state->comp.reset();
1444 }
1445 if (sendCallback) {
1446 mCallback->onReleaseCompleted();
1447 }
1448}
1449
1450status_t CCodec::setSurface(const sp<Surface> &surface) {
1451 return mChannel->setSurface(surface);
1452}
1453
1454void CCodec::signalFlush() {
1455 status_t err = [this] {
1456 Mutexed<State>::Locked state(mState);
1457 if (state->get() == FLUSHED) {
1458 return ALREADY_EXISTS;
1459 }
1460 if (state->get() != RUNNING) {
1461 return UNKNOWN_ERROR;
1462 }
1463 state->set(FLUSHING);
1464 return OK;
1465 }();
1466 switch (err) {
1467 case ALREADY_EXISTS:
1468 mCallback->onFlushCompleted();
1469 return;
1470 case OK:
1471 break;
1472 default:
1473 mCallback->onError(err, ACTION_CODE_FATAL);
1474 return;
1475 }
1476
1477 mChannel->stop();
1478 (new AMessage(kWhatFlush, this))->post();
1479}
1480
1481void CCodec::flush() {
1482 std::shared_ptr<Codec2Client::Component> comp;
1483 auto checkFlushing = [this, &comp] {
1484 Mutexed<State>::Locked state(mState);
1485 if (state->get() != FLUSHING) {
1486 return UNKNOWN_ERROR;
1487 }
1488 comp = state->comp;
1489 return OK;
1490 };
1491 if (tryAndReportOnError(checkFlushing) != OK) {
1492 return;
1493 }
1494
1495 std::list<std::unique_ptr<C2Work>> flushedWork;
1496 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1497 {
1498 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1499 flushedWork.splice(flushedWork.end(), *queue);
1500 }
1501 if (err != C2_OK) {
1502 // TODO: convert err into status_t
1503 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1504 }
1505
1506 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001507
1508 {
1509 Mutexed<State>::Locked state(mState);
1510 state->set(FLUSHED);
1511 }
1512 mCallback->onFlushCompleted();
1513}
1514
1515void CCodec::signalResume() {
1516 auto setResuming = [this] {
1517 Mutexed<State>::Locked state(mState);
1518 if (state->get() != FLUSHED) {
1519 return UNKNOWN_ERROR;
1520 }
1521 state->set(RESUMING);
1522 return OK;
1523 };
1524 if (tryAndReportOnError(setResuming) != OK) {
1525 return;
1526 }
1527
1528 (void)mChannel->start(nullptr, nullptr);
1529
1530 {
1531 Mutexed<State>::Locked state(mState);
1532 if (state->get() != RESUMING) {
1533 state.unlock();
1534 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1535 state.lock();
1536 return;
1537 }
1538 state->set(RUNNING);
1539 }
1540
1541 (void)mChannel->requestInitialInputBuffers();
1542}
1543
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001544void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001545 std::shared_ptr<Codec2Client::Component> comp;
1546 auto checkState = [this, &comp] {
1547 Mutexed<State>::Locked state(mState);
1548 if (state->get() == RELEASED) {
1549 return INVALID_OPERATION;
1550 }
1551 comp = state->comp;
1552 return OK;
1553 };
1554 if (tryAndReportOnError(checkState) != OK) {
1555 return;
1556 }
1557
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001558 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1559 // the behavior here.
1560 sp<AMessage> params = msg;
1561 int32_t bitrate;
1562 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1563 params = msg->dup();
1564 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1565 }
1566
Pawin Vongmasa36653902018-11-15 00:10:25 -08001567 Mutexed<Config>::Locked config(mConfig);
1568
1569 /**
1570 * Handle input surface parameters
1571 */
1572 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1573 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001574 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001575
1576 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1577 config->mISConfig->mStopped = false;
1578 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1579 config->mISConfig->mStopped = true;
1580 }
1581
1582 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001583 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001584 config->mISConfig->mSuspended = value;
1585 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001586 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001587 }
1588
1589 (void)config->mInputSurface->configure(*config->mISConfig);
1590 if (config->mISConfig->mStopped) {
1591 config->mInputFormat->setInt64(
1592 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1593 }
1594 }
1595
1596 std::vector<std::unique_ptr<C2Param>> configUpdate;
1597 (void)config->getConfigUpdateFromSdkParams(
1598 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1599 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1600 // Parameter synchronization is not defined when using input surface. For now, route
1601 // these directly to the component.
1602 if (config->mInputSurface == nullptr
1603 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1604 || comp->getName().find("c2.android.") == 0)) {
1605 mChannel->setParameters(configUpdate);
1606 } else {
1607 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1608 }
1609}
1610
1611void CCodec::signalEndOfInputStream() {
1612 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1613}
1614
1615void CCodec::signalRequestIDRFrame() {
1616 std::shared_ptr<Codec2Client::Component> comp;
1617 {
1618 Mutexed<State>::Locked state(mState);
1619 if (state->get() == RELEASED) {
1620 ALOGD("no IDR request sent since component is released");
1621 return;
1622 }
1623 comp = state->comp;
1624 }
1625 ALOGV("request IDR");
1626 Mutexed<Config>::Locked config(mConfig);
1627 std::vector<std::unique_ptr<C2Param>> params;
1628 params.push_back(
1629 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1630 config->setParameters(comp, params, C2_MAY_BLOCK);
1631}
1632
Wonsik Kimab34ed62019-01-31 15:28:46 -08001633void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001634 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001635 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1636 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001637 }
1638 (new AMessage(kWhatWorkDone, this))->post();
1639}
1640
Wonsik Kimab34ed62019-01-31 15:28:46 -08001641void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1642 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001643 if (arrayIndex == 0) {
1644 // We always put no more than one buffer per work, if we use an input surface.
1645 Mutexed<Config>::Locked config(mConfig);
1646 if (config->mInputSurface) {
1647 config->mInputSurface->onInputBufferDone(frameIndex);
1648 }
1649 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001650}
1651
1652void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1653 TimePoint now = std::chrono::steady_clock::now();
1654 CCodecWatchdog::getInstance()->watch(this);
1655 switch (msg->what()) {
1656 case kWhatAllocate: {
1657 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001658 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001659 sp<RefBase> obj;
1660 CHECK(msg->findObject("codecInfo", &obj));
1661 allocate((MediaCodecInfo *)obj.get());
1662 break;
1663 }
1664 case kWhatConfigure: {
1665 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001666 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001667 sp<AMessage> format;
1668 CHECK(msg->findMessage("format", &format));
1669 configure(format);
1670 break;
1671 }
1672 case kWhatStart: {
1673 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001674 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001675 start();
1676 break;
1677 }
1678 case kWhatStop: {
1679 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001680 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001681 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001682 break;
1683 }
1684 case kWhatFlush: {
1685 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001686 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001687 flush();
1688 break;
1689 }
1690 case kWhatCreateInputSurface: {
1691 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001692 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001693 createInputSurface();
1694 break;
1695 }
1696 case kWhatSetInputSurface: {
1697 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001698 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001699 sp<RefBase> obj;
1700 CHECK(msg->findObject("surface", &obj));
1701 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1702 setInputSurface(surface);
1703 break;
1704 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001705 case kWhatWorkDone: {
1706 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001707 bool shouldPost = false;
1708 {
1709 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1710 if (queue->empty()) {
1711 break;
1712 }
1713 work.swap(queue->front());
1714 queue->pop_front();
1715 shouldPost = !queue->empty();
1716 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001717 if (shouldPost) {
1718 (new AMessage(kWhatWorkDone, this))->post();
1719 }
1720
Pawin Vongmasa36653902018-11-15 00:10:25 -08001721 // handle configuration changes in work done
1722 Mutexed<Config>::Locked config(mConfig);
1723 bool changed = false;
1724 Config::Watcher<C2StreamInitDataInfo::output> initData =
1725 config->watch<C2StreamInitDataInfo::output>();
1726 if (!work->worklets.empty()
1727 && (work->worklets.front()->output.flags
1728 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1729
1730 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001731 std::vector<std::unique_ptr<C2Param>> updates;
1732 for (const std::unique_ptr<C2Param> &param
1733 : work->worklets.front()->output.configUpdate) {
1734 updates.push_back(C2Param::Copy(*param));
1735 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001736 unsigned stream = 0;
1737 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1738 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1739 // move all info into output-stream #0 domain
1740 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1741 }
1742 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1743 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1744 // block.crop().left, block.crop().top,
1745 // block.crop().width, block.crop().height,
1746 // block.width(), block.height());
1747 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1748 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07001749 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001750 break; // for now only do the first block
1751 }
1752 ++stream;
1753 }
1754
1755 changed = config->updateConfiguration(updates, config->mOutputDomain);
1756
1757 // copy standard infos to graphic buffers if not already present (otherwise, we
1758 // may overwrite the actual intermediate value with a final value)
1759 stream = 0;
1760 const static std::vector<C2Param::Index> stdGfxInfos = {
1761 C2StreamRotationInfo::output::PARAM_TYPE,
1762 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1763 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1764 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001765 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001766 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1767 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1768 };
1769 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1770 if (buf->data().graphicBlocks().size()) {
1771 for (C2Param::Index ix : stdGfxInfos) {
1772 if (!buf->hasInfo(ix)) {
1773 const C2Param *param =
1774 config->getConfigParameterValue(ix.withStream(stream));
1775 if (param) {
1776 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1777 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1778 }
1779 }
1780 }
1781 }
1782 ++stream;
1783 }
1784 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001785 if (config->mInputSurface) {
1786 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1787 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001788 mChannel->onWorkDone(
1789 std::move(work), changed ? config->mOutputFormat : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001790 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001791 break;
1792 }
1793 case kWhatWatch: {
1794 // watch message already posted; no-op.
1795 break;
1796 }
1797 default: {
1798 ALOGE("unrecognized message");
1799 break;
1800 }
1801 }
1802 setDeadline(TimePoint::max(), 0ms, "none");
1803}
1804
1805void CCodec::setDeadline(
1806 const TimePoint &now,
1807 const std::chrono::milliseconds &timeout,
1808 const char *name) {
1809 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1810 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1811 deadline->set(now + (timeout * mult), name);
1812}
1813
1814void CCodec::initiateReleaseIfStuck() {
1815 std::string name;
1816 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001817 {
1818 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001819 if (deadline->get() < std::chrono::steady_clock::now()) {
1820 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001821 }
1822 if (deadline->get() != TimePoint::max()) {
1823 pendingDeadline = true;
1824 }
1825 }
1826 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001827 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1828 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1829 if (elapsed >= kWorkDurationThreshold) {
1830 name = "queue";
1831 }
1832 if (elapsed > 0s) {
1833 pendingDeadline = true;
1834 }
1835 }
1836 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001837 // We're not stuck.
1838 if (pendingDeadline) {
1839 // If we are not stuck yet but still has deadline coming up,
1840 // post watch message to check back later.
1841 (new AMessage(kWhatWatch, this))->post();
1842 }
1843 return;
1844 }
1845
1846 ALOGW("previous call to %s exceeded timeout", name.c_str());
1847 initiateRelease(false);
1848 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1849}
1850
Pawin Vongmasa36653902018-11-15 00:10:25 -08001851} // namespace android
1852
1853extern "C" android::CodecBase *CreateCodec() {
1854 return new android::CCodec;
1855}
1856
Lajos Molnar47118272019-01-31 16:28:04 -08001857// Create Codec 2.0 input surface
Pawin Vongmasa36653902018-11-15 00:10:25 -08001858extern "C" android::PersistentSurface *CreateInputSurface() {
1859 // Attempt to create a Codec2's input surface.
1860 std::shared_ptr<android::Codec2Client::InputSurface> inputSurface =
1861 android::Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001862 if (!inputSurface) {
1863 return nullptr;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001864 }
Lajos Molnar47118272019-01-31 16:28:04 -08001865 return new android::PersistentSurface(
1866 inputSurface->getGraphicBufferProducer(),
1867 static_cast<android::sp<android::hidl::base::V1_0::IBase>>(
1868 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001869}
1870