blob: 1cbbbb8acf45885876db6e0e437e67b2369ea133 [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
Pawin Vongmasa36653902018-11-15 00:10:25 -080029#include <android/IOMXBufferSource.h>
30#include <android/hardware/media/omx/1.0/IGraphicBufferSource.h>
31#include <android/hardware/media/omx/1.0/IOmx.h>
32#include <android-base/stringprintf.h>
33#include <cutils/properties.h>
34#include <gui/IGraphicBufferProducer.h>
35#include <gui/Surface.h>
36#include <gui/bufferqueue/1.0/H2BGraphicBufferProducer.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070037#include <media/omx/1.0/WOmxNode.h>
38#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080039#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070040#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
41#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080042#include <media/stagefright/BufferProducerWrapper.h>
43#include <media/stagefright/MediaCodecConstants.h>
44#include <media/stagefright/PersistentSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080045
46#include "C2OMXNode.h"
47#include "CCodec.h"
48#include "CCodecBufferChannel.h"
49#include "InputSurfaceWrapper.h"
50
51extern "C" android::PersistentSurface *CreateInputSurface();
52
53namespace android {
54
55using namespace std::chrono_literals;
56using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
57using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080058using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080059
Wonsik Kim9917d4a2019-10-24 12:56:38 -070060typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
61
Pawin Vongmasa36653902018-11-15 00:10:25 -080062namespace {
63
64class CCodecWatchdog : public AHandler {
65private:
66 enum {
67 kWhatWatch,
68 };
69 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
70
71public:
72 static sp<CCodecWatchdog> getInstance() {
73 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
74 static std::once_flag flag;
75 // Call Init() only once.
76 std::call_once(flag, Init, instance);
77 return instance;
78 }
79
80 ~CCodecWatchdog() = default;
81
82 void watch(sp<CCodec> codec) {
83 bool shouldPost = false;
84 {
85 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
86 // If a watch message is in flight, piggy-back this instance as well.
87 // Otherwise, post a new watch message.
88 shouldPost = codecs->empty();
89 codecs->emplace(codec);
90 }
91 if (shouldPost) {
92 ALOGV("posting watch message");
93 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
94 }
95 }
96
97protected:
98 void onMessageReceived(const sp<AMessage> &msg) {
99 switch (msg->what()) {
100 case kWhatWatch: {
101 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
102 ALOGV("watch for %zu codecs", codecs->size());
103 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
104 sp<CCodec> codec = it->promote();
105 if (codec == nullptr) {
106 continue;
107 }
108 codec->initiateReleaseIfStuck();
109 }
110 codecs->clear();
111 break;
112 }
113
114 default: {
115 TRESPASS("CCodecWatchdog: unrecognized message");
116 }
117 }
118 }
119
120private:
121 CCodecWatchdog() : mLooper(new ALooper) {}
122
123 static void Init(const sp<CCodecWatchdog> &thiz) {
124 ALOGV("Init");
125 thiz->mLooper->setName("CCodecWatchdog");
126 thiz->mLooper->registerHandler(thiz);
127 thiz->mLooper->start();
128 }
129
130 sp<ALooper> mLooper;
131
132 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
133};
134
135class C2InputSurfaceWrapper : public InputSurfaceWrapper {
136public:
137 explicit C2InputSurfaceWrapper(
138 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
139 mSurface(surface) {
140 }
141
142 ~C2InputSurfaceWrapper() override = default;
143
144 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
145 if (mConnection != nullptr) {
146 return ALREADY_EXISTS;
147 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800148 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800149 }
150
151 void disconnect() override {
152 if (mConnection != nullptr) {
153 mConnection->disconnect();
154 mConnection = nullptr;
155 }
156 }
157
158 status_t start() override {
159 // InputSurface does not distinguish started state
160 return OK;
161 }
162
163 status_t signalEndOfInputStream() override {
164 C2InputSurfaceEosTuning eos(true);
165 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800166 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800167 if (err != C2_OK) {
168 return UNKNOWN_ERROR;
169 }
170 return OK;
171 }
172
173 status_t configure(Config &config __unused) {
174 // TODO
175 return OK;
176 }
177
178private:
179 std::shared_ptr<Codec2Client::InputSurface> mSurface;
180 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
181};
182
183class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
184public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700185 typedef hardware::media::omx::V1_0::Status OmxStatus;
186
Pawin Vongmasa36653902018-11-15 00:10:25 -0800187 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700188 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800189 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700190 uint32_t height,
191 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800192 : mSource(source), mWidth(width), mHeight(height) {
193 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700194 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800195 }
196 ~GraphicBufferSourceWrapper() override = default;
197
198 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
199 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700200 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800201 mNode->setFrameSize(mWidth, mHeight);
202
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700203 // Usage is queried during configure(), so setting it beforehand.
204 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
205 (void)mNode->setParameter(
206 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
207 &usage, sizeof(usage));
208
Pawin Vongmasa36653902018-11-15 00:10:25 -0800209 // NOTE: we do not use/pass through color aspects from GraphicBufferSource as we
210 // communicate that directly to the component.
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700211 mSource->configure(
212 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800213 return OK;
214 }
215
216 void disconnect() override {
217 if (mNode == nullptr) {
218 return;
219 }
220 sp<IOMXBufferSource> source = mNode->getSource();
221 if (source == nullptr) {
222 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
223 return;
224 }
225 source->onOmxIdle();
226 source->onOmxLoaded();
227 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700228 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800229 }
230
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700231 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
232 if (status.isOk()) {
233 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
234 } else if (status.isDeadObject()) {
235 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800236 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700237 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800238 }
239
240 status_t start() override {
241 sp<IOMXBufferSource> source = mNode->getSource();
242 if (source == nullptr) {
243 return NO_INIT;
244 }
245 constexpr size_t kNumSlots = 16;
246 for (size_t i = 0; i < kNumSlots; ++i) {
247 source->onInputBufferAdded(i);
248 }
249
250 source->onOmxExecuting();
251 return OK;
252 }
253
254 status_t signalEndOfInputStream() override {
255 return GetStatus(mSource->signalEndOfInputStream());
256 }
257
258 status_t configure(Config &config) {
259 std::stringstream status;
260 status_t err = OK;
261
262 // handle each configuration granually, in case we need to handle part of the configuration
263 // elsewhere
264
265 // TRICKY: we do not unset frame delay repeating
266 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
267 int64_t us = 1e6 / config.mMinFps + 0.5;
268 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
269 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
270 if (res != OK) {
271 status << " (=> " << asString(res) << ")";
272 err = res;
273 }
274 mConfig.mMinFps = config.mMinFps;
275 }
276
277 // pts gap
278 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
279 if (mNode != nullptr) {
280 OMX_PARAM_U32TYPE ptrGapParam = {};
281 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700282 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800283 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
284 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700285 // float -> uint32_t is undefined if the value is negative.
286 // First convert to int32_t to ensure the expected behavior.
287 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800288 (void)mNode->setParameter(
289 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
290 &ptrGapParam, sizeof(ptrGapParam));
291 }
292 }
293
294 // max fps
295 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700296 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800297 && config.mMaxFps != mConfig.mMaxFps) {
298 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
299 status << " maxFps=" << config.mMaxFps;
300 if (res != OK) {
301 status << " (=> " << asString(res) << ")";
302 err = res;
303 }
304 mConfig.mMaxFps = config.mMaxFps;
305 }
306
307 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
308 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
309 status << " timeOffset " << config.mTimeOffsetUs << "us";
310 if (res != OK) {
311 status << " (=> " << asString(res) << ")";
312 err = res;
313 }
314 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
315 }
316
317 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
318 status_t res =
319 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
320 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
321 if (res != OK) {
322 status << " (=> " << asString(res) << ")";
323 err = res;
324 }
325 mConfig.mCaptureFps = config.mCaptureFps;
326 mConfig.mCodedFps = config.mCodedFps;
327 }
328
329 if (config.mStartAtUs != mConfig.mStartAtUs
330 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
331 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
332 status << " start at " << config.mStartAtUs << "us";
333 if (res != OK) {
334 status << " (=> " << asString(res) << ")";
335 err = res;
336 }
337 mConfig.mStartAtUs = config.mStartAtUs;
338 mConfig.mStopped = config.mStopped;
339 }
340
341 // suspend-resume
342 if (config.mSuspended != mConfig.mSuspended) {
343 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
344 status << " " << (config.mSuspended ? "suspend" : "resume")
345 << " at " << config.mSuspendAtUs << "us";
346 if (res != OK) {
347 status << " (=> " << asString(res) << ")";
348 err = res;
349 }
350 mConfig.mSuspended = config.mSuspended;
351 mConfig.mSuspendAtUs = config.mSuspendAtUs;
352 }
353
354 if (config.mStopped != mConfig.mStopped && config.mStopped) {
355 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
356 status << " stop at " << config.mStopAtUs << "us";
357 if (res != OK) {
358 status << " (=> " << asString(res) << ")";
359 err = res;
360 } else {
361 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700362 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
363 [&res, &delayUs = config.mInputDelayUs](
364 auto status, auto stopTimeOffsetUs) {
365 res = static_cast<status_t>(status);
366 delayUs = stopTimeOffsetUs;
367 });
368 if (!trans.isOk()) {
369 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
370 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800371 if (res != OK) {
372 status << " (=> " << asString(res) << ")";
373 } else {
374 status << "=" << config.mInputDelayUs << "us";
375 }
376 mConfig.mInputDelayUs = config.mInputDelayUs;
377 }
378 mConfig.mStopAtUs = config.mStopAtUs;
379 mConfig.mStopped = config.mStopped;
380 }
381
382 // color aspects (android._color-aspects)
383
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700384 // consumer usage is queried earlier.
385
Wonsik Kimbd557932019-07-02 15:51:20 -0700386 if (status.str().empty()) {
387 ALOGD("ISConfig not changed");
388 } else {
389 ALOGD("ISConfig%s", status.str().c_str());
390 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800391 return err;
392 }
393
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700394 void onInputBufferDone(c2_cntr64_t index) override {
395 mNode->onInputBufferDone(index);
396 }
397
Pawin Vongmasa36653902018-11-15 00:10:25 -0800398private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700399 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800400 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700401 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800402 uint32_t mWidth;
403 uint32_t mHeight;
404 Config mConfig;
405};
406
407class Codec2ClientInterfaceWrapper : public C2ComponentStore {
408 std::shared_ptr<Codec2Client> mClient;
409
410public:
411 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
412 : mClient(client) { }
413
414 virtual ~Codec2ClientInterfaceWrapper() = default;
415
416 virtual c2_status_t config_sm(
417 const std::vector<C2Param *> &params,
418 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
419 return mClient->config(params, C2_MAY_BLOCK, failures);
420 };
421
422 virtual c2_status_t copyBuffer(
423 std::shared_ptr<C2GraphicBuffer>,
424 std::shared_ptr<C2GraphicBuffer>) {
425 return C2_OMITTED;
426 }
427
428 virtual c2_status_t createComponent(
429 C2String, std::shared_ptr<C2Component> *const component) {
430 component->reset();
431 return C2_OMITTED;
432 }
433
434 virtual c2_status_t createInterface(
435 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
436 interface->reset();
437 return C2_OMITTED;
438 }
439
440 virtual c2_status_t query_sm(
441 const std::vector<C2Param *> &stackParams,
442 const std::vector<C2Param::Index> &heapParamIndices,
443 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
444 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
445 }
446
447 virtual c2_status_t querySupportedParams_nb(
448 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
449 return mClient->querySupportedParams(params);
450 }
451
452 virtual c2_status_t querySupportedValues_sm(
453 std::vector<C2FieldSupportedValuesQuery> &fields) const {
454 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
455 }
456
457 virtual C2String getName() const {
458 return mClient->getName();
459 }
460
461 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
462 return mClient->getParamReflector();
463 }
464
465 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
466 return std::vector<std::shared_ptr<const C2Component::Traits>>();
467 }
468};
469
470} // namespace
471
472// CCodec::ClientListener
473
474struct CCodec::ClientListener : public Codec2Client::Listener {
475
476 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
477
478 virtual void onWorkDone(
479 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800480 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800481 (void)component;
482 sp<CCodec> codec(mCodec.promote());
483 if (!codec) {
484 return;
485 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800486 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800487 }
488
489 virtual void onTripped(
490 const std::weak_ptr<Codec2Client::Component>& component,
491 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
492 ) override {
493 // TODO
494 (void)component;
495 (void)settingResult;
496 }
497
498 virtual void onError(
499 const std::weak_ptr<Codec2Client::Component>& component,
500 uint32_t errorCode) override {
501 // TODO
502 (void)component;
503 (void)errorCode;
504 }
505
506 virtual void onDeath(
507 const std::weak_ptr<Codec2Client::Component>& component) override {
508 { // Log the death of the component.
509 std::shared_ptr<Codec2Client::Component> comp = component.lock();
510 if (!comp) {
511 ALOGE("Codec2 component died.");
512 } else {
513 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
514 }
515 }
516
517 // Report to MediaCodec.
518 sp<CCodec> codec(mCodec.promote());
519 if (!codec || !codec->mCallback) {
520 return;
521 }
522 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
523 }
524
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800525 virtual void onFrameRendered(uint64_t bufferQueueId,
526 int32_t slotId,
527 int64_t timestampNs) override {
528 // TODO: implement
529 (void)bufferQueueId;
530 (void)slotId;
531 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800532 }
533
534 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800535 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800536 sp<CCodec> codec(mCodec.promote());
537 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800538 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800539 }
540 }
541
542private:
543 wp<CCodec> mCodec;
544};
545
546// CCodecCallbackImpl
547
548class CCodecCallbackImpl : public CCodecCallback {
549public:
550 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
551 ~CCodecCallbackImpl() override = default;
552
553 void onError(status_t err, enum ActionCode actionCode) override {
554 mCodec->mCallback->onError(err, actionCode);
555 }
556
557 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
558 mCodec->mCallback->onOutputFramesRendered(
559 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
560 }
561
Pawin Vongmasa36653902018-11-15 00:10:25 -0800562 void onOutputBuffersChanged() override {
563 mCodec->mCallback->onOutputBuffersChanged();
564 }
565
566private:
567 CCodec *mCodec;
568};
569
570// CCodec
571
572CCodec::CCodec()
Wonsik Kimab34ed62019-01-31 15:28:46 -0800573 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800574}
575
576CCodec::~CCodec() {
577}
578
579std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
580 return mChannel;
581}
582
583status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
584 status_t err = job();
585 if (err != C2_OK) {
586 mCallback->onError(err, ACTION_CODE_FATAL);
587 }
588 return err;
589}
590
591void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
592 auto setAllocating = [this] {
593 Mutexed<State>::Locked state(mState);
594 if (state->get() != RELEASED) {
595 return INVALID_OPERATION;
596 }
597 state->set(ALLOCATING);
598 return OK;
599 };
600 if (tryAndReportOnError(setAllocating) != OK) {
601 return;
602 }
603
604 sp<RefBase> codecInfo;
605 CHECK(msg->findObject("codecInfo", &codecInfo));
606 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
607
608 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
609 allocMsg->setObject("codecInfo", codecInfo);
610 allocMsg->post();
611}
612
613void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
614 if (codecInfo == nullptr) {
615 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
616 return;
617 }
618 ALOGD("allocate(%s)", codecInfo->getCodecName());
619 mClientListener.reset(new ClientListener(this));
620
621 AString componentName = codecInfo->getCodecName();
622 std::shared_ptr<Codec2Client> client;
623
624 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700625 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800626 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800627 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800628 SetPreferredCodec2ComponentStore(
629 std::make_shared<Codec2ClientInterfaceWrapper>(client));
630 }
631
632 std::shared_ptr<Codec2Client::Component> comp =
633 Codec2Client::CreateComponentByName(
634 componentName.c_str(),
635 mClientListener,
636 &client);
637 if (!comp) {
638 ALOGE("Failed Create component: %s", componentName.c_str());
639 Mutexed<State>::Locked state(mState);
640 state->set(RELEASED);
641 state.unlock();
642 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
643 state.lock();
644 return;
645 }
646 ALOGI("Created component [%s]", componentName.c_str());
647 mChannel->setComponent(comp);
648 auto setAllocated = [this, comp, client] {
649 Mutexed<State>::Locked state(mState);
650 if (state->get() != ALLOCATING) {
651 state->set(RELEASED);
652 return UNKNOWN_ERROR;
653 }
654 state->set(ALLOCATED);
655 state->comp = comp;
656 mClient = client;
657 return OK;
658 };
659 if (tryAndReportOnError(setAllocated) != OK) {
660 return;
661 }
662
663 // initialize config here in case setParameters is called prior to configure
664 Mutexed<Config>::Locked config(mConfig);
665 status_t err = config->initialize(mClient, comp);
666 if (err != OK) {
667 ALOGW("Failed to initialize configuration support");
668 // TODO: report error once we complete implementation.
669 }
670 config->queryConfiguration(comp);
671
672 mCallback->onComponentAllocated(componentName.c_str());
673}
674
675void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
676 auto checkAllocated = [this] {
677 Mutexed<State>::Locked state(mState);
678 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
679 };
680 if (tryAndReportOnError(checkAllocated) != OK) {
681 return;
682 }
683
684 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
685 msg->setMessage("format", format);
686 msg->post();
687}
688
689void CCodec::configure(const sp<AMessage> &msg) {
690 std::shared_ptr<Codec2Client::Component> comp;
691 auto checkAllocated = [this, &comp] {
692 Mutexed<State>::Locked state(mState);
693 if (state->get() != ALLOCATED) {
694 state->set(RELEASED);
695 return UNKNOWN_ERROR;
696 }
697 comp = state->comp;
698 return OK;
699 };
700 if (tryAndReportOnError(checkAllocated) != OK) {
701 return;
702 }
703
704 auto doConfig = [msg, comp, this]() -> status_t {
705 AString mime;
706 if (!msg->findString("mime", &mime)) {
707 return BAD_VALUE;
708 }
709
710 int32_t encoder;
711 if (!msg->findInt32("encoder", &encoder)) {
712 encoder = false;
713 }
714
715 // TODO: read from intf()
716 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
717 return UNKNOWN_ERROR;
718 }
719
720 int32_t storeMeta;
721 if (encoder
722 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
723 && storeMeta != kMetadataBufferTypeInvalid) {
724 if (storeMeta != kMetadataBufferTypeANWBuffer) {
725 ALOGD("Only ANW buffers are supported for legacy metadata mode");
726 return BAD_VALUE;
727 }
728 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
729 }
730
731 sp<RefBase> obj;
732 sp<Surface> surface;
733 if (msg->findObject("native-window", &obj)) {
734 surface = static_cast<Surface *>(obj.get());
735 setSurface(surface);
736 }
737
738 Mutexed<Config>::Locked config(mConfig);
739 config->mUsingSurface = surface != nullptr;
740
Wonsik Kim1114eea2019-02-25 14:35:24 -0800741 // Enforce required parameters
742 int32_t i32;
743 float flt;
744 if (config->mDomain & Config::IS_AUDIO) {
745 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
746 ALOGD("sample rate is missing, which is required for audio components.");
747 return BAD_VALUE;
748 }
749 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
750 ALOGD("channel count is missing, which is required for audio components.");
751 return BAD_VALUE;
752 }
753 if ((config->mDomain & Config::IS_ENCODER)
754 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
755 && !msg->findInt32(KEY_BIT_RATE, &i32)
756 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
757 ALOGD("bitrate is missing, which is required for audio encoders.");
758 return BAD_VALUE;
759 }
760 }
761 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
762 if (!msg->findInt32(KEY_WIDTH, &i32)) {
763 ALOGD("width is missing, which is required for image/video components.");
764 return BAD_VALUE;
765 }
766 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
767 ALOGD("height is missing, which is required for image/video components.");
768 return BAD_VALUE;
769 }
770 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700771 int32_t mode = BITRATE_MODE_VBR;
772 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700773 if (!msg->findInt32(KEY_QUALITY, &i32)) {
774 ALOGD("quality is missing, which is required for video encoders in CQ.");
775 return BAD_VALUE;
776 }
777 } else {
778 if (!msg->findInt32(KEY_BIT_RATE, &i32)
779 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
780 ALOGD("bitrate is missing, which is required for video encoders.");
781 return BAD_VALUE;
782 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800783 }
784 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
785 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
786 ALOGD("I frame interval is missing, which is required for video encoders.");
787 return BAD_VALUE;
788 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700789 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
790 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
791 ALOGD("frame rate is missing, which is required for video encoders.");
792 return BAD_VALUE;
793 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800794 }
795 }
796
Pawin Vongmasa36653902018-11-15 00:10:25 -0800797 /*
798 * Handle input surface configuration
799 */
800 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
801 && (config->mDomain & Config::IS_ENCODER)) {
802 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
803 {
804 config->mISConfig->mMinFps = 0;
805 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800806 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800807 config->mISConfig->mMinFps = 1e6 / value;
808 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700809 if (!msg->findFloat(
810 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
811 config->mISConfig->mMaxFps = -1;
812 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800813 config->mISConfig->mMinAdjustedFps = 0;
814 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800815 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800816 if (value < 0 && value >= INT32_MIN) {
817 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700818 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800819 } else if (value > 0 && value <= INT32_MAX) {
820 config->mISConfig->mMinAdjustedFps = 1e6 / value;
821 }
822 }
823 }
824
825 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700826 bool captureFpsFound = false;
827 double timeLapseFps;
828 float captureRate;
829 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
830 config->mISConfig->mCaptureFps = timeLapseFps;
831 captureFpsFound = true;
832 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
833 config->mISConfig->mCaptureFps = captureRate;
834 captureFpsFound = true;
835 }
836 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800837 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
838 }
839 }
840
841 {
842 config->mISConfig->mSuspended = false;
843 config->mISConfig->mSuspendAtUs = -1;
844 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800845 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800846 config->mISConfig->mSuspended = true;
847 }
848 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700849 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800850 }
851
852 /*
853 * Handle desired color format.
854 */
855 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
856 int32_t format = -1;
857 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
858 /*
859 * Also handle default color format (encoders require color format, so this is only
860 * needed for decoders.
861 */
862 if (!(config->mDomain & Config::IS_ENCODER)) {
863 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
864 }
865 }
866
867 if (format >= 0) {
868 msg->setInt32("android._color-format", format);
869 }
870 }
871
872 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800873 // NOTE: We used to ignore "video-bitrate" at configure; replicate
874 // the behavior here.
875 sp<AMessage> sdkParams = msg;
876 int32_t videoBitrate;
877 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
878 sdkParams = msg->dup();
879 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
880 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800881 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800882 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800883 if (err != OK) {
884 ALOGW("failed to convert configuration to c2 params");
885 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700886
887 int32_t maxBframes = 0;
888 if ((config->mDomain & Config::IS_ENCODER)
889 && (config->mDomain & Config::IS_VIDEO)
890 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
891 && maxBframes > 0) {
892 std::unique_ptr<C2StreamGopTuning::output> gop =
893 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
894 gop->m.values[0] = { P_FRAME, UINT32_MAX };
895 gop->m.values[1] = {
896 C2Config::picture_type_t(P_FRAME | B_FRAME),
897 uint32_t(maxBframes)
898 };
899 configUpdate.push_back(std::move(gop));
900 }
901
Pawin Vongmasa36653902018-11-15 00:10:25 -0800902 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
903 if (err != OK) {
904 ALOGW("failed to configure c2 params");
905 return err;
906 }
907
908 std::vector<std::unique_ptr<C2Param>> params;
909 C2StreamUsageTuning::input usage(0u, 0u);
910 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700911 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800912
913 std::initializer_list<C2Param::Index> indices {
914 };
915 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700916 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800917 indices,
918 C2_DONT_BLOCK,
919 &params);
920 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
921 ALOGE("Failed to query component interface: %d", c2err);
922 return UNKNOWN_ERROR;
923 }
924 if (params.size() != indices.size()) {
925 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
926 indices.size(), params.size());
927 return UNKNOWN_ERROR;
928 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700929 if (usage) {
930 if (usage.value & C2MemoryUsage::CPU_READ) {
931 config->mInputFormat->setInt32("using-sw-read-often", true);
932 }
933 if (config->mISConfig) {
934 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
935 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
936 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800937 }
938
939 // NOTE: we don't blindly use client specified input size if specified as clients
940 // at times specify too small size. Instead, mimic the behavior from OMX, where the
941 // client specified size is only used to ask for bigger buffers than component suggested
942 // size.
943 int32_t clientInputSize = 0;
944 bool clientSpecifiedInputSize =
945 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
946 // TEMP: enforce minimum buffer size of 1MB for video decoders
947 // and 16K / 4K for audio encoders/decoders
948 if (maxInputSize.value == 0) {
949 if (config->mDomain & Config::IS_AUDIO) {
950 maxInputSize.value = encoder ? 16384 : 4096;
951 } else if (!encoder) {
952 maxInputSize.value = 1048576u;
953 }
954 }
955
956 // verify that CSD fits into this size (if defined)
957 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
958 sp<ABuffer> csd;
959 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
960 if (csd && csd->size() > maxInputSize.value) {
961 maxInputSize.value = csd->size();
962 }
963 }
964 }
965
966 // TODO: do this based on component requiring linear allocator for input
967 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
968 if (clientSpecifiedInputSize) {
969 // Warn that we're overriding client's max input size if necessary.
970 if ((uint32_t)clientInputSize < maxInputSize.value) {
971 ALOGD("client requested max input size %d, which is smaller than "
972 "what component recommended (%u); overriding with component "
973 "recommendation.", clientInputSize, maxInputSize.value);
974 ALOGW("This behavior is subject to change. It is recommended that "
975 "app developers double check whether the requested "
976 "max input size is in reasonable range.");
977 } else {
978 maxInputSize.value = clientInputSize;
979 }
980 }
981 // Pass max input size on input format to the buffer channel (if supplied by the
982 // component or by a default)
983 if (maxInputSize.value) {
984 config->mInputFormat->setInt32(
985 KEY_MAX_INPUT_SIZE,
986 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
987 }
988 }
989
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700990 int32_t clientPrepend;
991 if ((config->mDomain & Config::IS_VIDEO)
992 && (config->mDomain & Config::IS_ENCODER)
993 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
994 && clientPrepend
995 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
996 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
997 return BAD_VALUE;
998 }
999
Pawin Vongmasa36653902018-11-15 00:10:25 -08001000 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1001 // propagate HDR static info to output format for both encoders and decoders
1002 // if component supports this info, we will update from component, but only the raw port,
1003 // so don't propagate if component already filled it in.
1004 sp<ABuffer> hdrInfo;
1005 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1006 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1007 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1008 }
1009
1010 // Set desired color format from configuration parameter
1011 int32_t format;
1012 if (msg->findInt32("android._color-format", &format)) {
1013 if (config->mDomain & Config::IS_ENCODER) {
1014 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
1015 } else {
1016 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
1017 }
1018 }
1019 }
1020
1021 // propagate encoder delay and padding to output format
1022 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1023 int delay = 0;
1024 if (msg->findInt32("encoder-delay", &delay)) {
1025 config->mOutputFormat->setInt32("encoder-delay", delay);
1026 }
1027 int padding = 0;
1028 if (msg->findInt32("encoder-padding", &padding)) {
1029 config->mOutputFormat->setInt32("encoder-padding", padding);
1030 }
1031 }
1032
1033 // set channel-mask
1034 if (config->mDomain & Config::IS_AUDIO) {
1035 int32_t mask;
1036 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1037 if (config->mDomain & Config::IS_ENCODER) {
1038 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1039 } else {
1040 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1041 }
1042 }
1043 }
1044
1045 ALOGD("setup formats input: %s and output: %s",
1046 config->mInputFormat->debugString().c_str(),
1047 config->mOutputFormat->debugString().c_str());
1048 return OK;
1049 };
1050 if (tryAndReportOnError(doConfig) != OK) {
1051 return;
1052 }
1053
1054 Mutexed<Config>::Locked config(mConfig);
1055
1056 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1057}
1058
1059void CCodec::initiateCreateInputSurface() {
1060 status_t err = [this] {
1061 Mutexed<State>::Locked state(mState);
1062 if (state->get() != ALLOCATED) {
1063 return UNKNOWN_ERROR;
1064 }
1065 // TODO: read it from intf() properly.
1066 if (state->comp->getName().find("encoder") == std::string::npos) {
1067 return INVALID_OPERATION;
1068 }
1069 return OK;
1070 }();
1071 if (err != OK) {
1072 mCallback->onInputSurfaceCreationFailed(err);
1073 return;
1074 }
1075
1076 (new AMessage(kWhatCreateInputSurface, this))->post();
1077}
1078
Lajos Molnar47118272019-01-31 16:28:04 -08001079sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1080 using namespace android::hardware::media::omx::V1_0;
1081 using namespace android::hardware::media::omx::V1_0::utils;
1082 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1083 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1084 android::sp<IOmx> omx = IOmx::getService();
1085 typedef android::hardware::graphics::bufferqueue::V1_0::
1086 IGraphicBufferProducer HGraphicBufferProducer;
1087 typedef android::hardware::media::omx::V1_0::
1088 IGraphicBufferSource HGraphicBufferSource;
1089 OmxStatus s;
1090 android::sp<HGraphicBufferProducer> gbp;
1091 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001092
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001093 using ::android::hardware::Return;
1094 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001095 [&s, &gbp, &gbs](
1096 OmxStatus status,
1097 const android::sp<HGraphicBufferProducer>& producer,
1098 const android::sp<HGraphicBufferSource>& source) {
1099 s = status;
1100 gbp = producer;
1101 gbs = source;
1102 });
1103 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001104 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001105 }
1106
1107 return nullptr;
1108}
1109
1110sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1111 sp<PersistentSurface> surface(CreateInputSurface());
1112
1113 if (surface == nullptr) {
1114 surface = CreateOmxInputSurface();
1115 }
1116
1117 return surface;
1118}
1119
Pawin Vongmasa36653902018-11-15 00:10:25 -08001120void CCodec::createInputSurface() {
1121 status_t err;
1122 sp<IGraphicBufferProducer> bufferProducer;
1123
1124 sp<AMessage> inputFormat;
1125 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001126 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001127 {
1128 Mutexed<Config>::Locked config(mConfig);
1129 inputFormat = config->mInputFormat;
1130 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001131 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001132 }
1133
Lajos Molnar47118272019-01-31 16:28:04 -08001134 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001135 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1136 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1137 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001138
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001139 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001140 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1141 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001142 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001143 inputSurface));
1144 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001145 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001146 int32_t width = 0;
1147 (void)outputFormat->findInt32("width", &width);
1148 int32_t height = 0;
1149 (void)outputFormat->findInt32("height", &height);
1150 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001151 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001152 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001153 } else {
1154 ALOGE("Corrupted input surface");
1155 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1156 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001157 }
1158
1159 if (err != OK) {
1160 ALOGE("Failed to set up input surface: %d", err);
1161 mCallback->onInputSurfaceCreationFailed(err);
1162 return;
1163 }
1164
1165 mCallback->onInputSurfaceCreated(
1166 inputFormat,
1167 outputFormat,
1168 new BufferProducerWrapper(bufferProducer));
1169}
1170
1171status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
1172 Mutexed<Config>::Locked config(mConfig);
1173 config->mUsingSurface = true;
1174
1175 // we are now using surface - apply default color aspects to input format - as well as
1176 // get dataspace
1177 bool inputFormatChanged = config->updateFormats(config->IS_INPUT);
1178 ALOGD("input format %s to %s",
1179 inputFormatChanged ? "changed" : "unchanged",
1180 config->mInputFormat->debugString().c_str());
1181
1182 // configure dataspace
1183 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1184 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1185 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1186 surface->setDataSpace(dataSpace);
1187
1188 status_t err = mChannel->setInputSurface(surface);
1189 if (err != OK) {
1190 // undo input format update
1191 config->mUsingSurface = false;
1192 (void)config->updateFormats(config->IS_INPUT);
1193 return err;
1194 }
1195 config->mInputSurface = surface;
1196
1197 if (config->mISConfig) {
1198 surface->configure(*config->mISConfig);
1199 } else {
1200 ALOGD("ISConfig: no configuration");
1201 }
1202
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001203 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001204}
1205
1206void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1207 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1208 msg->setObject("surface", surface);
1209 msg->post();
1210}
1211
1212void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1213 sp<AMessage> inputFormat;
1214 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001215 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001216 {
1217 Mutexed<Config>::Locked config(mConfig);
1218 inputFormat = config->mInputFormat;
1219 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001220 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001221 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001222 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1223 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1224 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1225 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001226 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1227 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1228 if (err != OK) {
1229 ALOGE("Failed to set up input surface: %d", err);
1230 mCallback->onInputSurfaceDeclined(err);
1231 return;
1232 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001233 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001234 int32_t width = 0;
1235 (void)outputFormat->findInt32("width", &width);
1236 int32_t height = 0;
1237 (void)outputFormat->findInt32("height", &height);
1238 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001239 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001240 if (err != OK) {
1241 ALOGE("Failed to set up input surface: %d", err);
1242 mCallback->onInputSurfaceDeclined(err);
1243 return;
1244 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001245 } else {
1246 ALOGE("Failed to set input surface: Corrupted surface.");
1247 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1248 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001249 }
1250 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1251}
1252
1253void CCodec::initiateStart() {
1254 auto setStarting = [this] {
1255 Mutexed<State>::Locked state(mState);
1256 if (state->get() != ALLOCATED) {
1257 return UNKNOWN_ERROR;
1258 }
1259 state->set(STARTING);
1260 return OK;
1261 };
1262 if (tryAndReportOnError(setStarting) != OK) {
1263 return;
1264 }
1265
1266 (new AMessage(kWhatStart, this))->post();
1267}
1268
1269void CCodec::start() {
1270 std::shared_ptr<Codec2Client::Component> comp;
1271 auto checkStarting = [this, &comp] {
1272 Mutexed<State>::Locked state(mState);
1273 if (state->get() != STARTING) {
1274 return UNKNOWN_ERROR;
1275 }
1276 comp = state->comp;
1277 return OK;
1278 };
1279 if (tryAndReportOnError(checkStarting) != OK) {
1280 return;
1281 }
1282
1283 c2_status_t err = comp->start();
1284 if (err != C2_OK) {
1285 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1286 ACTION_CODE_FATAL);
1287 return;
1288 }
1289 sp<AMessage> inputFormat;
1290 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001291 status_t err2 = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001292 {
1293 Mutexed<Config>::Locked config(mConfig);
1294 inputFormat = config->mInputFormat;
1295 outputFormat = config->mOutputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001296 if (config->mInputSurface) {
1297 err2 = config->mInputSurface->start();
1298 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001299 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001300 if (err2 != OK) {
1301 mCallback->onError(err2, ACTION_CODE_FATAL);
1302 return;
1303 }
1304 err2 = mChannel->start(inputFormat, outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001305 if (err2 != OK) {
1306 mCallback->onError(err2, ACTION_CODE_FATAL);
1307 return;
1308 }
1309
1310 auto setRunning = [this] {
1311 Mutexed<State>::Locked state(mState);
1312 if (state->get() != STARTING) {
1313 return UNKNOWN_ERROR;
1314 }
1315 state->set(RUNNING);
1316 return OK;
1317 };
1318 if (tryAndReportOnError(setRunning) != OK) {
1319 return;
1320 }
1321 mCallback->onStartCompleted();
1322
1323 (void)mChannel->requestInitialInputBuffers();
1324}
1325
1326void CCodec::initiateShutdown(bool keepComponentAllocated) {
1327 if (keepComponentAllocated) {
1328 initiateStop();
1329 } else {
1330 initiateRelease();
1331 }
1332}
1333
1334void CCodec::initiateStop() {
1335 {
1336 Mutexed<State>::Locked state(mState);
1337 if (state->get() == ALLOCATED
1338 || state->get() == RELEASED
1339 || state->get() == STOPPING
1340 || state->get() == RELEASING) {
1341 // We're already stopped, released, or doing it right now.
1342 state.unlock();
1343 mCallback->onStopCompleted();
1344 state.lock();
1345 return;
1346 }
1347 state->set(STOPPING);
1348 }
1349
1350 mChannel->stop();
1351 (new AMessage(kWhatStop, this))->post();
1352}
1353
1354void CCodec::stop() {
1355 std::shared_ptr<Codec2Client::Component> comp;
1356 {
1357 Mutexed<State>::Locked state(mState);
1358 if (state->get() == RELEASING) {
1359 state.unlock();
1360 // We're already stopped or release is in progress.
1361 mCallback->onStopCompleted();
1362 state.lock();
1363 return;
1364 } else if (state->get() != STOPPING) {
1365 state.unlock();
1366 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1367 state.lock();
1368 return;
1369 }
1370 comp = state->comp;
1371 }
1372 status_t err = comp->stop();
1373 if (err != C2_OK) {
1374 // TODO: convert err into status_t
1375 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1376 }
1377
1378 {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001379 Mutexed<Config>::Locked config(mConfig);
1380 if (config->mInputSurface) {
1381 config->mInputSurface->disconnect();
1382 config->mInputSurface = nullptr;
1383 }
1384 }
1385 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001386 Mutexed<State>::Locked state(mState);
1387 if (state->get() == STOPPING) {
1388 state->set(ALLOCATED);
1389 }
1390 }
1391 mCallback->onStopCompleted();
1392}
1393
1394void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001395 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001396 {
1397 Mutexed<State>::Locked state(mState);
1398 if (state->get() == RELEASED || state->get() == RELEASING) {
1399 // We're already released or doing it right now.
1400 if (sendCallback) {
1401 state.unlock();
1402 mCallback->onReleaseCompleted();
1403 state.lock();
1404 }
1405 return;
1406 }
1407 if (state->get() == ALLOCATING) {
1408 state->set(RELEASING);
1409 // With the altered state allocate() would fail and clean up.
1410 if (sendCallback) {
1411 state.unlock();
1412 mCallback->onReleaseCompleted();
1413 state.lock();
1414 }
1415 return;
1416 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001417 if (state->get() == STARTING
1418 || state->get() == RUNNING
1419 || state->get() == STOPPING) {
1420 // Input surface may have been started, so clean up is needed.
1421 clearInputSurfaceIfNeeded = true;
1422 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001423 state->set(RELEASING);
1424 }
1425
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001426 if (clearInputSurfaceIfNeeded) {
1427 Mutexed<Config>::Locked config(mConfig);
1428 if (config->mInputSurface) {
1429 config->mInputSurface->disconnect();
1430 config->mInputSurface = nullptr;
1431 }
1432 }
1433
Pawin Vongmasa36653902018-11-15 00:10:25 -08001434 mChannel->stop();
1435 // thiz holds strong ref to this while the thread is running.
1436 sp<CCodec> thiz(this);
1437 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1438}
1439
1440void CCodec::release(bool sendCallback) {
1441 std::shared_ptr<Codec2Client::Component> comp;
1442 {
1443 Mutexed<State>::Locked state(mState);
1444 if (state->get() == RELEASED) {
1445 if (sendCallback) {
1446 state.unlock();
1447 mCallback->onReleaseCompleted();
1448 state.lock();
1449 }
1450 return;
1451 }
1452 comp = state->comp;
1453 }
1454 comp->release();
1455
1456 {
1457 Mutexed<State>::Locked state(mState);
1458 state->set(RELEASED);
1459 state->comp.reset();
1460 }
1461 if (sendCallback) {
1462 mCallback->onReleaseCompleted();
1463 }
1464}
1465
1466status_t CCodec::setSurface(const sp<Surface> &surface) {
1467 return mChannel->setSurface(surface);
1468}
1469
1470void CCodec::signalFlush() {
1471 status_t err = [this] {
1472 Mutexed<State>::Locked state(mState);
1473 if (state->get() == FLUSHED) {
1474 return ALREADY_EXISTS;
1475 }
1476 if (state->get() != RUNNING) {
1477 return UNKNOWN_ERROR;
1478 }
1479 state->set(FLUSHING);
1480 return OK;
1481 }();
1482 switch (err) {
1483 case ALREADY_EXISTS:
1484 mCallback->onFlushCompleted();
1485 return;
1486 case OK:
1487 break;
1488 default:
1489 mCallback->onError(err, ACTION_CODE_FATAL);
1490 return;
1491 }
1492
1493 mChannel->stop();
1494 (new AMessage(kWhatFlush, this))->post();
1495}
1496
1497void CCodec::flush() {
1498 std::shared_ptr<Codec2Client::Component> comp;
1499 auto checkFlushing = [this, &comp] {
1500 Mutexed<State>::Locked state(mState);
1501 if (state->get() != FLUSHING) {
1502 return UNKNOWN_ERROR;
1503 }
1504 comp = state->comp;
1505 return OK;
1506 };
1507 if (tryAndReportOnError(checkFlushing) != OK) {
1508 return;
1509 }
1510
1511 std::list<std::unique_ptr<C2Work>> flushedWork;
1512 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1513 {
1514 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1515 flushedWork.splice(flushedWork.end(), *queue);
1516 }
1517 if (err != C2_OK) {
1518 // TODO: convert err into status_t
1519 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1520 }
1521
1522 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001523
1524 {
1525 Mutexed<State>::Locked state(mState);
1526 state->set(FLUSHED);
1527 }
1528 mCallback->onFlushCompleted();
1529}
1530
1531void CCodec::signalResume() {
1532 auto setResuming = [this] {
1533 Mutexed<State>::Locked state(mState);
1534 if (state->get() != FLUSHED) {
1535 return UNKNOWN_ERROR;
1536 }
1537 state->set(RESUMING);
1538 return OK;
1539 };
1540 if (tryAndReportOnError(setResuming) != OK) {
1541 return;
1542 }
1543
1544 (void)mChannel->start(nullptr, nullptr);
1545
1546 {
1547 Mutexed<State>::Locked state(mState);
1548 if (state->get() != RESUMING) {
1549 state.unlock();
1550 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1551 state.lock();
1552 return;
1553 }
1554 state->set(RUNNING);
1555 }
1556
1557 (void)mChannel->requestInitialInputBuffers();
1558}
1559
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001560void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001561 std::shared_ptr<Codec2Client::Component> comp;
1562 auto checkState = [this, &comp] {
1563 Mutexed<State>::Locked state(mState);
1564 if (state->get() == RELEASED) {
1565 return INVALID_OPERATION;
1566 }
1567 comp = state->comp;
1568 return OK;
1569 };
1570 if (tryAndReportOnError(checkState) != OK) {
1571 return;
1572 }
1573
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001574 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1575 // the behavior here.
1576 sp<AMessage> params = msg;
1577 int32_t bitrate;
1578 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1579 params = msg->dup();
1580 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1581 }
1582
Pawin Vongmasa36653902018-11-15 00:10:25 -08001583 Mutexed<Config>::Locked config(mConfig);
1584
1585 /**
1586 * Handle input surface parameters
1587 */
1588 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1589 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001590 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001591
1592 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1593 config->mISConfig->mStopped = false;
1594 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1595 config->mISConfig->mStopped = true;
1596 }
1597
1598 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001599 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001600 config->mISConfig->mSuspended = value;
1601 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001602 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001603 }
1604
1605 (void)config->mInputSurface->configure(*config->mISConfig);
1606 if (config->mISConfig->mStopped) {
1607 config->mInputFormat->setInt64(
1608 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1609 }
1610 }
1611
1612 std::vector<std::unique_ptr<C2Param>> configUpdate;
1613 (void)config->getConfigUpdateFromSdkParams(
1614 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1615 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1616 // Parameter synchronization is not defined when using input surface. For now, route
1617 // these directly to the component.
1618 if (config->mInputSurface == nullptr
1619 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1620 || comp->getName().find("c2.android.") == 0)) {
1621 mChannel->setParameters(configUpdate);
1622 } else {
1623 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1624 }
1625}
1626
1627void CCodec::signalEndOfInputStream() {
1628 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1629}
1630
1631void CCodec::signalRequestIDRFrame() {
1632 std::shared_ptr<Codec2Client::Component> comp;
1633 {
1634 Mutexed<State>::Locked state(mState);
1635 if (state->get() == RELEASED) {
1636 ALOGD("no IDR request sent since component is released");
1637 return;
1638 }
1639 comp = state->comp;
1640 }
1641 ALOGV("request IDR");
1642 Mutexed<Config>::Locked config(mConfig);
1643 std::vector<std::unique_ptr<C2Param>> params;
1644 params.push_back(
1645 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1646 config->setParameters(comp, params, C2_MAY_BLOCK);
1647}
1648
Wonsik Kimab34ed62019-01-31 15:28:46 -08001649void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001650 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001651 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1652 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001653 }
1654 (new AMessage(kWhatWorkDone, this))->post();
1655}
1656
Wonsik Kimab34ed62019-01-31 15:28:46 -08001657void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1658 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001659 if (arrayIndex == 0) {
1660 // We always put no more than one buffer per work, if we use an input surface.
1661 Mutexed<Config>::Locked config(mConfig);
1662 if (config->mInputSurface) {
1663 config->mInputSurface->onInputBufferDone(frameIndex);
1664 }
1665 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001666}
1667
1668void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1669 TimePoint now = std::chrono::steady_clock::now();
1670 CCodecWatchdog::getInstance()->watch(this);
1671 switch (msg->what()) {
1672 case kWhatAllocate: {
1673 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001674 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001675 sp<RefBase> obj;
1676 CHECK(msg->findObject("codecInfo", &obj));
1677 allocate((MediaCodecInfo *)obj.get());
1678 break;
1679 }
1680 case kWhatConfigure: {
1681 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001682 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001683 sp<AMessage> format;
1684 CHECK(msg->findMessage("format", &format));
1685 configure(format);
1686 break;
1687 }
1688 case kWhatStart: {
1689 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001690 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001691 start();
1692 break;
1693 }
1694 case kWhatStop: {
1695 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001696 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001697 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001698 break;
1699 }
1700 case kWhatFlush: {
1701 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001702 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001703 flush();
1704 break;
1705 }
1706 case kWhatCreateInputSurface: {
1707 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001708 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001709 createInputSurface();
1710 break;
1711 }
1712 case kWhatSetInputSurface: {
1713 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001714 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001715 sp<RefBase> obj;
1716 CHECK(msg->findObject("surface", &obj));
1717 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1718 setInputSurface(surface);
1719 break;
1720 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001721 case kWhatWorkDone: {
1722 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001723 bool shouldPost = false;
1724 {
1725 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1726 if (queue->empty()) {
1727 break;
1728 }
1729 work.swap(queue->front());
1730 queue->pop_front();
1731 shouldPost = !queue->empty();
1732 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001733 if (shouldPost) {
1734 (new AMessage(kWhatWorkDone, this))->post();
1735 }
1736
Pawin Vongmasa36653902018-11-15 00:10:25 -08001737 // handle configuration changes in work done
1738 Mutexed<Config>::Locked config(mConfig);
1739 bool changed = false;
1740 Config::Watcher<C2StreamInitDataInfo::output> initData =
1741 config->watch<C2StreamInitDataInfo::output>();
1742 if (!work->worklets.empty()
1743 && (work->worklets.front()->output.flags
1744 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1745
1746 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001747 std::vector<std::unique_ptr<C2Param>> updates;
1748 for (const std::unique_ptr<C2Param> &param
1749 : work->worklets.front()->output.configUpdate) {
1750 updates.push_back(C2Param::Copy(*param));
1751 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001752 unsigned stream = 0;
1753 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1754 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1755 // move all info into output-stream #0 domain
1756 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1757 }
1758 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1759 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1760 // block.crop().left, block.crop().top,
1761 // block.crop().width, block.crop().height,
1762 // block.width(), block.height());
1763 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1764 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07001765 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001766 break; // for now only do the first block
1767 }
1768 ++stream;
1769 }
1770
1771 changed = config->updateConfiguration(updates, config->mOutputDomain);
1772
1773 // copy standard infos to graphic buffers if not already present (otherwise, we
1774 // may overwrite the actual intermediate value with a final value)
1775 stream = 0;
1776 const static std::vector<C2Param::Index> stdGfxInfos = {
1777 C2StreamRotationInfo::output::PARAM_TYPE,
1778 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1779 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1780 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001781 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001782 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1783 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1784 };
1785 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1786 if (buf->data().graphicBlocks().size()) {
1787 for (C2Param::Index ix : stdGfxInfos) {
1788 if (!buf->hasInfo(ix)) {
1789 const C2Param *param =
1790 config->getConfigParameterValue(ix.withStream(stream));
1791 if (param) {
1792 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1793 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1794 }
1795 }
1796 }
1797 }
1798 ++stream;
1799 }
1800 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001801 if (config->mInputSurface) {
1802 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1803 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001804 mChannel->onWorkDone(
1805 std::move(work), changed ? config->mOutputFormat : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001806 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001807 break;
1808 }
1809 case kWhatWatch: {
1810 // watch message already posted; no-op.
1811 break;
1812 }
1813 default: {
1814 ALOGE("unrecognized message");
1815 break;
1816 }
1817 }
1818 setDeadline(TimePoint::max(), 0ms, "none");
1819}
1820
1821void CCodec::setDeadline(
1822 const TimePoint &now,
1823 const std::chrono::milliseconds &timeout,
1824 const char *name) {
1825 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1826 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1827 deadline->set(now + (timeout * mult), name);
1828}
1829
1830void CCodec::initiateReleaseIfStuck() {
1831 std::string name;
1832 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001833 {
1834 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001835 if (deadline->get() < std::chrono::steady_clock::now()) {
1836 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001837 }
1838 if (deadline->get() != TimePoint::max()) {
1839 pendingDeadline = true;
1840 }
1841 }
1842 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001843 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1844 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1845 if (elapsed >= kWorkDurationThreshold) {
1846 name = "queue";
1847 }
1848 if (elapsed > 0s) {
1849 pendingDeadline = true;
1850 }
1851 }
1852 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001853 // We're not stuck.
1854 if (pendingDeadline) {
1855 // If we are not stuck yet but still has deadline coming up,
1856 // post watch message to check back later.
1857 (new AMessage(kWhatWatch, this))->post();
1858 }
1859 return;
1860 }
1861
1862 ALOGW("previous call to %s exceeded timeout", name.c_str());
1863 initiateRelease(false);
1864 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1865}
1866
Pawin Vongmasa36653902018-11-15 00:10:25 -08001867} // namespace android
1868
1869extern "C" android::CodecBase *CreateCodec() {
1870 return new android::CCodec;
1871}
1872
Lajos Molnar47118272019-01-31 16:28:04 -08001873// Create Codec 2.0 input surface
Pawin Vongmasa36653902018-11-15 00:10:25 -08001874extern "C" android::PersistentSurface *CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001875 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001876 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001877 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07001878 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1879 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001880 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001881 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
1882 sp<IGraphicBufferProducer> gbp;
1883 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
1884 status_t err = gbs->initCheck();
1885 if (err != OK) {
1886 ALOGE("Failed to create persistent input surface: error %d", err);
1887 return nullptr;
1888 }
1889 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001890 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07001891 } else {
1892 return nullptr;
1893 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001894 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07001895 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001896 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07001897 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08001898 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001899}
1900