blob: 5c572e1ebfd61df14704be4b917948276755bf57 [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>
Pawin Vongmasabf69de92019-10-29 06:21:27 -070030#include <android/hardware/media/c2/1.0/IInputSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080031#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>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070038#include <media/omx/1.0/WOmxNode.h>
39#include <media/openmax/OMX_Core.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080040#include <media/openmax/OMX_IndexExt.h>
Wonsik Kim9917d4a2019-10-24 12:56:38 -070041#include <media/stagefright/omx/1.0/WGraphicBufferSource.h>
42#include <media/stagefright/omx/OmxGraphicBufferSource.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070043#include <media/stagefright/CCodec.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080044#include <media/stagefright/BufferProducerWrapper.h>
45#include <media/stagefright/MediaCodecConstants.h>
46#include <media/stagefright/PersistentSurface.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080047
48#include "C2OMXNode.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080049#include "CCodecBufferChannel.h"
Wonsik Kim155d5cb2019-10-09 12:49:49 -070050#include "CCodecConfig.h"
Pawin Vongmasa36653902018-11-15 00:10:25 -080051#include "InputSurfaceWrapper.h"
52
53extern "C" android::PersistentSurface *CreateInputSurface();
54
55namespace android {
56
57using namespace std::chrono_literals;
58using ::android::hardware::graphics::bufferqueue::V1_0::utils::H2BGraphicBufferProducer;
59using android::base::StringPrintf;
Pawin Vongmasad0f0e142018-11-15 03:36:28 -080060using ::android::hardware::media::c2::V1_0::IInputSurface;
Pawin Vongmasa36653902018-11-15 00:10:25 -080061
Wonsik Kim9917d4a2019-10-24 12:56:38 -070062typedef hardware::media::omx::V1_0::IGraphicBufferSource HGraphicBufferSource;
Wonsik Kim155d5cb2019-10-09 12:49:49 -070063typedef CCodecConfig Config;
Wonsik Kim9917d4a2019-10-24 12:56:38 -070064
Pawin Vongmasa36653902018-11-15 00:10:25 -080065namespace {
66
67class CCodecWatchdog : public AHandler {
68private:
69 enum {
70 kWhatWatch,
71 };
72 constexpr static int64_t kWatchIntervalUs = 3300000; // 3.3 secs
73
74public:
75 static sp<CCodecWatchdog> getInstance() {
76 static sp<CCodecWatchdog> instance(new CCodecWatchdog);
77 static std::once_flag flag;
78 // Call Init() only once.
79 std::call_once(flag, Init, instance);
80 return instance;
81 }
82
83 ~CCodecWatchdog() = default;
84
85 void watch(sp<CCodec> codec) {
86 bool shouldPost = false;
87 {
88 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
89 // If a watch message is in flight, piggy-back this instance as well.
90 // Otherwise, post a new watch message.
91 shouldPost = codecs->empty();
92 codecs->emplace(codec);
93 }
94 if (shouldPost) {
95 ALOGV("posting watch message");
96 (new AMessage(kWhatWatch, this))->post(kWatchIntervalUs);
97 }
98 }
99
100protected:
101 void onMessageReceived(const sp<AMessage> &msg) {
102 switch (msg->what()) {
103 case kWhatWatch: {
104 Mutexed<std::set<wp<CCodec>>>::Locked codecs(mCodecsToWatch);
105 ALOGV("watch for %zu codecs", codecs->size());
106 for (auto it = codecs->begin(); it != codecs->end(); ++it) {
107 sp<CCodec> codec = it->promote();
108 if (codec == nullptr) {
109 continue;
110 }
111 codec->initiateReleaseIfStuck();
112 }
113 codecs->clear();
114 break;
115 }
116
117 default: {
118 TRESPASS("CCodecWatchdog: unrecognized message");
119 }
120 }
121 }
122
123private:
124 CCodecWatchdog() : mLooper(new ALooper) {}
125
126 static void Init(const sp<CCodecWatchdog> &thiz) {
127 ALOGV("Init");
128 thiz->mLooper->setName("CCodecWatchdog");
129 thiz->mLooper->registerHandler(thiz);
130 thiz->mLooper->start();
131 }
132
133 sp<ALooper> mLooper;
134
135 Mutexed<std::set<wp<CCodec>>> mCodecsToWatch;
136};
137
138class C2InputSurfaceWrapper : public InputSurfaceWrapper {
139public:
140 explicit C2InputSurfaceWrapper(
141 const std::shared_ptr<Codec2Client::InputSurface> &surface) :
142 mSurface(surface) {
143 }
144
145 ~C2InputSurfaceWrapper() override = default;
146
147 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
148 if (mConnection != nullptr) {
149 return ALREADY_EXISTS;
150 }
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800151 return toStatusT(comp->connectToInputSurface(mSurface, &mConnection));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800152 }
153
154 void disconnect() override {
155 if (mConnection != nullptr) {
156 mConnection->disconnect();
157 mConnection = nullptr;
158 }
159 }
160
161 status_t start() override {
162 // InputSurface does not distinguish started state
163 return OK;
164 }
165
166 status_t signalEndOfInputStream() override {
167 C2InputSurfaceEosTuning eos(true);
168 std::vector<std::unique_ptr<C2SettingResult>> failures;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800169 c2_status_t err = mSurface->config({&eos}, C2_MAY_BLOCK, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800170 if (err != C2_OK) {
171 return UNKNOWN_ERROR;
172 }
173 return OK;
174 }
175
176 status_t configure(Config &config __unused) {
177 // TODO
178 return OK;
179 }
180
181private:
182 std::shared_ptr<Codec2Client::InputSurface> mSurface;
183 std::shared_ptr<Codec2Client::InputSurfaceConnection> mConnection;
184};
185
186class GraphicBufferSourceWrapper : public InputSurfaceWrapper {
187public:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700188 typedef hardware::media::omx::V1_0::Status OmxStatus;
189
Pawin Vongmasa36653902018-11-15 00:10:25 -0800190 GraphicBufferSourceWrapper(
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700191 const sp<HGraphicBufferSource> &source,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800192 uint32_t width,
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700193 uint32_t height,
194 uint64_t usage)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800195 : mSource(source), mWidth(width), mHeight(height) {
196 mDataSpace = HAL_DATASPACE_BT709;
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700197 mConfig.mUsage = usage;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800198 }
199 ~GraphicBufferSourceWrapper() override = default;
200
201 status_t connect(const std::shared_ptr<Codec2Client::Component> &comp) override {
202 mNode = new C2OMXNode(comp);
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700203 mOmxNode = new hardware::media::omx::V1_0::utils::TWOmxNode(mNode);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800204 mNode->setFrameSize(mWidth, mHeight);
205
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700206 // Usage is queried during configure(), so setting it beforehand.
207 OMX_U32 usage = mConfig.mUsage & 0xFFFFFFFF;
208 (void)mNode->setParameter(
209 (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits,
210 &usage, sizeof(usage));
211
Pawin Vongmasa36653902018-11-15 00:10:25 -0800212 // NOTE: we do not use/pass through color aspects from GraphicBufferSource as we
213 // communicate that directly to the component.
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700214 mSource->configure(
215 mOmxNode, static_cast<hardware::graphics::common::V1_0::Dataspace>(mDataSpace));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800216 return OK;
217 }
218
219 void disconnect() override {
220 if (mNode == nullptr) {
221 return;
222 }
223 sp<IOMXBufferSource> source = mNode->getSource();
224 if (source == nullptr) {
225 ALOGD("GBSWrapper::disconnect: node is not configured with OMXBufferSource.");
226 return;
227 }
228 source->onOmxIdle();
229 source->onOmxLoaded();
230 mNode.clear();
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700231 mOmxNode.clear();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800232 }
233
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700234 status_t GetStatus(hardware::Return<OmxStatus> &&status) {
235 if (status.isOk()) {
236 return static_cast<status_t>(status.withDefault(OmxStatus::UNKNOWN_ERROR));
237 } else if (status.isDeadObject()) {
238 return DEAD_OBJECT;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800239 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700240 return UNKNOWN_ERROR;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800241 }
242
243 status_t start() override {
244 sp<IOMXBufferSource> source = mNode->getSource();
245 if (source == nullptr) {
246 return NO_INIT;
247 }
248 constexpr size_t kNumSlots = 16;
249 for (size_t i = 0; i < kNumSlots; ++i) {
250 source->onInputBufferAdded(i);
251 }
252
253 source->onOmxExecuting();
254 return OK;
255 }
256
257 status_t signalEndOfInputStream() override {
258 return GetStatus(mSource->signalEndOfInputStream());
259 }
260
261 status_t configure(Config &config) {
262 std::stringstream status;
263 status_t err = OK;
264
265 // handle each configuration granually, in case we need to handle part of the configuration
266 // elsewhere
267
268 // TRICKY: we do not unset frame delay repeating
269 if (config.mMinFps > 0 && config.mMinFps != mConfig.mMinFps) {
270 int64_t us = 1e6 / config.mMinFps + 0.5;
271 status_t res = GetStatus(mSource->setRepeatPreviousFrameDelayUs(us));
272 status << " minFps=" << config.mMinFps << " => repeatDelayUs=" << us;
273 if (res != OK) {
274 status << " (=> " << asString(res) << ")";
275 err = res;
276 }
277 mConfig.mMinFps = config.mMinFps;
278 }
279
280 // pts gap
281 if (config.mMinAdjustedFps > 0 || config.mFixedAdjustedFps > 0) {
282 if (mNode != nullptr) {
283 OMX_PARAM_U32TYPE ptrGapParam = {};
284 ptrGapParam.nSize = sizeof(OMX_PARAM_U32TYPE);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700285 float gap = (config.mMinAdjustedFps > 0)
Pawin Vongmasa36653902018-11-15 00:10:25 -0800286 ? c2_min(INT32_MAX + 0., 1e6 / config.mMinAdjustedFps + 0.5)
287 : c2_max(0. - INT32_MAX, -1e6 / config.mFixedAdjustedFps - 0.5);
Wonsik Kim95ba0162019-03-19 15:51:54 -0700288 // float -> uint32_t is undefined if the value is negative.
289 // First convert to int32_t to ensure the expected behavior.
290 ptrGapParam.nU32 = int32_t(gap);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800291 (void)mNode->setParameter(
292 (OMX_INDEXTYPE)OMX_IndexParamMaxFrameDurationForBitrateControl,
293 &ptrGapParam, sizeof(ptrGapParam));
294 }
295 }
296
297 // max fps
298 // TRICKY: we do not unset max fps to 0 unless using fixed fps
Wonsik Kim95ba0162019-03-19 15:51:54 -0700299 if ((config.mMaxFps > 0 || (config.mFixedAdjustedFps > 0 && config.mMaxFps == -1))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800300 && config.mMaxFps != mConfig.mMaxFps) {
301 status_t res = GetStatus(mSource->setMaxFps(config.mMaxFps));
302 status << " maxFps=" << config.mMaxFps;
303 if (res != OK) {
304 status << " (=> " << asString(res) << ")";
305 err = res;
306 }
307 mConfig.mMaxFps = config.mMaxFps;
308 }
309
310 if (config.mTimeOffsetUs != mConfig.mTimeOffsetUs) {
311 status_t res = GetStatus(mSource->setTimeOffsetUs(config.mTimeOffsetUs));
312 status << " timeOffset " << config.mTimeOffsetUs << "us";
313 if (res != OK) {
314 status << " (=> " << asString(res) << ")";
315 err = res;
316 }
317 mConfig.mTimeOffsetUs = config.mTimeOffsetUs;
318 }
319
320 if (config.mCaptureFps != mConfig.mCaptureFps || config.mCodedFps != mConfig.mCodedFps) {
321 status_t res =
322 GetStatus(mSource->setTimeLapseConfig(config.mCodedFps, config.mCaptureFps));
323 status << " timeLapse " << config.mCaptureFps << "fps as " << config.mCodedFps << "fps";
324 if (res != OK) {
325 status << " (=> " << asString(res) << ")";
326 err = res;
327 }
328 mConfig.mCaptureFps = config.mCaptureFps;
329 mConfig.mCodedFps = config.mCodedFps;
330 }
331
332 if (config.mStartAtUs != mConfig.mStartAtUs
333 || (config.mStopped != mConfig.mStopped && !config.mStopped)) {
334 status_t res = GetStatus(mSource->setStartTimeUs(config.mStartAtUs));
335 status << " start at " << config.mStartAtUs << "us";
336 if (res != OK) {
337 status << " (=> " << asString(res) << ")";
338 err = res;
339 }
340 mConfig.mStartAtUs = config.mStartAtUs;
341 mConfig.mStopped = config.mStopped;
342 }
343
344 // suspend-resume
345 if (config.mSuspended != mConfig.mSuspended) {
346 status_t res = GetStatus(mSource->setSuspend(config.mSuspended, config.mSuspendAtUs));
347 status << " " << (config.mSuspended ? "suspend" : "resume")
348 << " at " << config.mSuspendAtUs << "us";
349 if (res != OK) {
350 status << " (=> " << asString(res) << ")";
351 err = res;
352 }
353 mConfig.mSuspended = config.mSuspended;
354 mConfig.mSuspendAtUs = config.mSuspendAtUs;
355 }
356
357 if (config.mStopped != mConfig.mStopped && config.mStopped) {
358 status_t res = GetStatus(mSource->setStopTimeUs(config.mStopAtUs));
359 status << " stop at " << config.mStopAtUs << "us";
360 if (res != OK) {
361 status << " (=> " << asString(res) << ")";
362 err = res;
363 } else {
364 status << " delayUs";
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700365 hardware::Return<void> trans = mSource->getStopTimeOffsetUs(
366 [&res, &delayUs = config.mInputDelayUs](
367 auto status, auto stopTimeOffsetUs) {
368 res = static_cast<status_t>(status);
369 delayUs = stopTimeOffsetUs;
370 });
371 if (!trans.isOk()) {
372 res = trans.isDeadObject() ? DEAD_OBJECT : UNKNOWN_ERROR;
373 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800374 if (res != OK) {
375 status << " (=> " << asString(res) << ")";
376 } else {
377 status << "=" << config.mInputDelayUs << "us";
378 }
379 mConfig.mInputDelayUs = config.mInputDelayUs;
380 }
381 mConfig.mStopAtUs = config.mStopAtUs;
382 mConfig.mStopped = config.mStopped;
383 }
384
385 // color aspects (android._color-aspects)
386
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700387 // consumer usage is queried earlier.
388
Wonsik Kimbd557932019-07-02 15:51:20 -0700389 if (status.str().empty()) {
390 ALOGD("ISConfig not changed");
391 } else {
392 ALOGD("ISConfig%s", status.str().c_str());
393 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800394 return err;
395 }
396
Wonsik Kim4f3314d2019-03-26 17:00:34 -0700397 void onInputBufferDone(c2_cntr64_t index) override {
398 mNode->onInputBufferDone(index);
399 }
400
Pawin Vongmasa36653902018-11-15 00:10:25 -0800401private:
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700402 sp<HGraphicBufferSource> mSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800403 sp<C2OMXNode> mNode;
Wonsik Kim9917d4a2019-10-24 12:56:38 -0700404 sp<hardware::media::omx::V1_0::IOmxNode> mOmxNode;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800405 uint32_t mWidth;
406 uint32_t mHeight;
407 Config mConfig;
408};
409
410class Codec2ClientInterfaceWrapper : public C2ComponentStore {
411 std::shared_ptr<Codec2Client> mClient;
412
413public:
414 Codec2ClientInterfaceWrapper(std::shared_ptr<Codec2Client> client)
415 : mClient(client) { }
416
417 virtual ~Codec2ClientInterfaceWrapper() = default;
418
419 virtual c2_status_t config_sm(
420 const std::vector<C2Param *> &params,
421 std::vector<std::unique_ptr<C2SettingResult>> *const failures) {
422 return mClient->config(params, C2_MAY_BLOCK, failures);
423 };
424
425 virtual c2_status_t copyBuffer(
426 std::shared_ptr<C2GraphicBuffer>,
427 std::shared_ptr<C2GraphicBuffer>) {
428 return C2_OMITTED;
429 }
430
431 virtual c2_status_t createComponent(
432 C2String, std::shared_ptr<C2Component> *const component) {
433 component->reset();
434 return C2_OMITTED;
435 }
436
437 virtual c2_status_t createInterface(
438 C2String, std::shared_ptr<C2ComponentInterface> *const interface) {
439 interface->reset();
440 return C2_OMITTED;
441 }
442
443 virtual c2_status_t query_sm(
444 const std::vector<C2Param *> &stackParams,
445 const std::vector<C2Param::Index> &heapParamIndices,
446 std::vector<std::unique_ptr<C2Param>> *const heapParams) const {
447 return mClient->query(stackParams, heapParamIndices, C2_MAY_BLOCK, heapParams);
448 }
449
450 virtual c2_status_t querySupportedParams_nb(
451 std::vector<std::shared_ptr<C2ParamDescriptor>> *const params) const {
452 return mClient->querySupportedParams(params);
453 }
454
455 virtual c2_status_t querySupportedValues_sm(
456 std::vector<C2FieldSupportedValuesQuery> &fields) const {
457 return mClient->querySupportedValues(fields, C2_MAY_BLOCK);
458 }
459
460 virtual C2String getName() const {
461 return mClient->getName();
462 }
463
464 virtual std::shared_ptr<C2ParamReflector> getParamReflector() const {
465 return mClient->getParamReflector();
466 }
467
468 virtual std::vector<std::shared_ptr<const C2Component::Traits>> listComponents() {
469 return std::vector<std::shared_ptr<const C2Component::Traits>>();
470 }
471};
472
473} // namespace
474
475// CCodec::ClientListener
476
477struct CCodec::ClientListener : public Codec2Client::Listener {
478
479 explicit ClientListener(const wp<CCodec> &codec) : mCodec(codec) {}
480
481 virtual void onWorkDone(
482 const std::weak_ptr<Codec2Client::Component>& component,
Wonsik Kimab34ed62019-01-31 15:28:46 -0800483 std::list<std::unique_ptr<C2Work>>& workItems) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800484 (void)component;
485 sp<CCodec> codec(mCodec.promote());
486 if (!codec) {
487 return;
488 }
Wonsik Kimab34ed62019-01-31 15:28:46 -0800489 codec->onWorkDone(workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800490 }
491
492 virtual void onTripped(
493 const std::weak_ptr<Codec2Client::Component>& component,
494 const std::vector<std::shared_ptr<C2SettingResult>>& settingResult
495 ) override {
496 // TODO
497 (void)component;
498 (void)settingResult;
499 }
500
501 virtual void onError(
502 const std::weak_ptr<Codec2Client::Component>& component,
503 uint32_t errorCode) override {
504 // TODO
505 (void)component;
506 (void)errorCode;
507 }
508
509 virtual void onDeath(
510 const std::weak_ptr<Codec2Client::Component>& component) override {
511 { // Log the death of the component.
512 std::shared_ptr<Codec2Client::Component> comp = component.lock();
513 if (!comp) {
514 ALOGE("Codec2 component died.");
515 } else {
516 ALOGE("Codec2 component \"%s\" died.", comp->getName().c_str());
517 }
518 }
519
520 // Report to MediaCodec.
521 sp<CCodec> codec(mCodec.promote());
522 if (!codec || !codec->mCallback) {
523 return;
524 }
525 codec->mCallback->onError(DEAD_OBJECT, ACTION_CODE_FATAL);
526 }
527
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800528 virtual void onFrameRendered(uint64_t bufferQueueId,
529 int32_t slotId,
530 int64_t timestampNs) override {
531 // TODO: implement
532 (void)bufferQueueId;
533 (void)slotId;
534 (void)timestampNs;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800535 }
536
537 virtual void onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -0800538 uint64_t frameIndex, size_t arrayIndex) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800539 sp<CCodec> codec(mCodec.promote());
540 if (codec) {
Wonsik Kimab34ed62019-01-31 15:28:46 -0800541 codec->onInputBufferDone(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800542 }
543 }
544
545private:
546 wp<CCodec> mCodec;
547};
548
549// CCodecCallbackImpl
550
551class CCodecCallbackImpl : public CCodecCallback {
552public:
553 explicit CCodecCallbackImpl(CCodec *codec) : mCodec(codec) {}
554 ~CCodecCallbackImpl() override = default;
555
556 void onError(status_t err, enum ActionCode actionCode) override {
557 mCodec->mCallback->onError(err, actionCode);
558 }
559
560 void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) override {
561 mCodec->mCallback->onOutputFramesRendered(
562 {RenderedFrameInfo(mediaTimeUs, renderTimeNs)});
563 }
564
Pawin Vongmasa36653902018-11-15 00:10:25 -0800565 void onOutputBuffersChanged() override {
566 mCodec->mCallback->onOutputBuffersChanged();
567 }
568
569private:
570 CCodec *mCodec;
571};
572
573// CCodec
574
575CCodec::CCodec()
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700576 : mChannel(new CCodecBufferChannel(std::make_shared<CCodecCallbackImpl>(this))),
577 mConfig(new CCodecConfig) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800578}
579
580CCodec::~CCodec() {
581}
582
583std::shared_ptr<BufferChannelBase> CCodec::getBufferChannel() {
584 return mChannel;
585}
586
587status_t CCodec::tryAndReportOnError(std::function<status_t()> job) {
588 status_t err = job();
589 if (err != C2_OK) {
590 mCallback->onError(err, ACTION_CODE_FATAL);
591 }
592 return err;
593}
594
595void CCodec::initiateAllocateComponent(const sp<AMessage> &msg) {
596 auto setAllocating = [this] {
597 Mutexed<State>::Locked state(mState);
598 if (state->get() != RELEASED) {
599 return INVALID_OPERATION;
600 }
601 state->set(ALLOCATING);
602 return OK;
603 };
604 if (tryAndReportOnError(setAllocating) != OK) {
605 return;
606 }
607
608 sp<RefBase> codecInfo;
609 CHECK(msg->findObject("codecInfo", &codecInfo));
610 // For Codec 2.0 components, componentName == codecInfo->getCodecName().
611
612 sp<AMessage> allocMsg(new AMessage(kWhatAllocate, this));
613 allocMsg->setObject("codecInfo", codecInfo);
614 allocMsg->post();
615}
616
617void CCodec::allocate(const sp<MediaCodecInfo> &codecInfo) {
618 if (codecInfo == nullptr) {
619 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
620 return;
621 }
622 ALOGD("allocate(%s)", codecInfo->getCodecName());
623 mClientListener.reset(new ClientListener(this));
624
625 AString componentName = codecInfo->getCodecName();
626 std::shared_ptr<Codec2Client> client;
627
628 // set up preferred component store to access vendor store parameters
Pawin Vongmasa892c81d2019-03-12 00:56:50 -0700629 client = Codec2Client::CreateFromService("default");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800630 if (client) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -0800631 ALOGI("setting up '%s' as default (vendor) store", client->getServiceName().c_str());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800632 SetPreferredCodec2ComponentStore(
633 std::make_shared<Codec2ClientInterfaceWrapper>(client));
634 }
635
636 std::shared_ptr<Codec2Client::Component> comp =
637 Codec2Client::CreateComponentByName(
638 componentName.c_str(),
639 mClientListener,
640 &client);
641 if (!comp) {
642 ALOGE("Failed Create component: %s", componentName.c_str());
643 Mutexed<State>::Locked state(mState);
644 state->set(RELEASED);
645 state.unlock();
646 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
647 state.lock();
648 return;
649 }
650 ALOGI("Created component [%s]", componentName.c_str());
651 mChannel->setComponent(comp);
652 auto setAllocated = [this, comp, client] {
653 Mutexed<State>::Locked state(mState);
654 if (state->get() != ALLOCATING) {
655 state->set(RELEASED);
656 return UNKNOWN_ERROR;
657 }
658 state->set(ALLOCATED);
659 state->comp = comp;
660 mClient = client;
661 return OK;
662 };
663 if (tryAndReportOnError(setAllocated) != OK) {
664 return;
665 }
666
667 // initialize config here in case setParameters is called prior to configure
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700668 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
669 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800670 status_t err = config->initialize(mClient, comp);
671 if (err != OK) {
672 ALOGW("Failed to initialize configuration support");
673 // TODO: report error once we complete implementation.
674 }
675 config->queryConfiguration(comp);
676
677 mCallback->onComponentAllocated(componentName.c_str());
678}
679
680void CCodec::initiateConfigureComponent(const sp<AMessage> &format) {
681 auto checkAllocated = [this] {
682 Mutexed<State>::Locked state(mState);
683 return (state->get() != ALLOCATED) ? UNKNOWN_ERROR : OK;
684 };
685 if (tryAndReportOnError(checkAllocated) != OK) {
686 return;
687 }
688
689 sp<AMessage> msg(new AMessage(kWhatConfigure, this));
690 msg->setMessage("format", format);
691 msg->post();
692}
693
694void CCodec::configure(const sp<AMessage> &msg) {
695 std::shared_ptr<Codec2Client::Component> comp;
696 auto checkAllocated = [this, &comp] {
697 Mutexed<State>::Locked state(mState);
698 if (state->get() != ALLOCATED) {
699 state->set(RELEASED);
700 return UNKNOWN_ERROR;
701 }
702 comp = state->comp;
703 return OK;
704 };
705 if (tryAndReportOnError(checkAllocated) != OK) {
706 return;
707 }
708
709 auto doConfig = [msg, comp, this]() -> status_t {
710 AString mime;
711 if (!msg->findString("mime", &mime)) {
712 return BAD_VALUE;
713 }
714
715 int32_t encoder;
716 if (!msg->findInt32("encoder", &encoder)) {
717 encoder = false;
718 }
719
720 // TODO: read from intf()
721 if ((!encoder) != (comp->getName().find("encoder") == std::string::npos)) {
722 return UNKNOWN_ERROR;
723 }
724
725 int32_t storeMeta;
726 if (encoder
727 && msg->findInt32("android._input-metadata-buffer-type", &storeMeta)
728 && storeMeta != kMetadataBufferTypeInvalid) {
729 if (storeMeta != kMetadataBufferTypeANWBuffer) {
730 ALOGD("Only ANW buffers are supported for legacy metadata mode");
731 return BAD_VALUE;
732 }
733 mChannel->setMetaMode(CCodecBufferChannel::MODE_ANW);
734 }
735
736 sp<RefBase> obj;
737 sp<Surface> surface;
738 if (msg->findObject("native-window", &obj)) {
739 surface = static_cast<Surface *>(obj.get());
740 setSurface(surface);
741 }
742
Wonsik Kim155d5cb2019-10-09 12:49:49 -0700743 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
744 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800745 config->mUsingSurface = surface != nullptr;
746
Wonsik Kim1114eea2019-02-25 14:35:24 -0800747 // Enforce required parameters
748 int32_t i32;
749 float flt;
750 if (config->mDomain & Config::IS_AUDIO) {
751 if (!msg->findInt32(KEY_SAMPLE_RATE, &i32)) {
752 ALOGD("sample rate is missing, which is required for audio components.");
753 return BAD_VALUE;
754 }
755 if (!msg->findInt32(KEY_CHANNEL_COUNT, &i32)) {
756 ALOGD("channel count is missing, which is required for audio components.");
757 return BAD_VALUE;
758 }
759 if ((config->mDomain & Config::IS_ENCODER)
760 && !mime.equalsIgnoreCase(MEDIA_MIMETYPE_AUDIO_FLAC)
761 && !msg->findInt32(KEY_BIT_RATE, &i32)
762 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
763 ALOGD("bitrate is missing, which is required for audio encoders.");
764 return BAD_VALUE;
765 }
766 }
767 if (config->mDomain & (Config::IS_IMAGE | Config::IS_VIDEO)) {
768 if (!msg->findInt32(KEY_WIDTH, &i32)) {
769 ALOGD("width is missing, which is required for image/video components.");
770 return BAD_VALUE;
771 }
772 if (!msg->findInt32(KEY_HEIGHT, &i32)) {
773 ALOGD("height is missing, which is required for image/video components.");
774 return BAD_VALUE;
775 }
776 if ((config->mDomain & Config::IS_ENCODER) && (config->mDomain & Config::IS_VIDEO)) {
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700777 int32_t mode = BITRATE_MODE_VBR;
778 if (msg->findInt32(KEY_BITRATE_MODE, &mode) && mode == BITRATE_MODE_CQ) {
Harish Mahendrakar817d3182019-03-11 16:37:47 -0700779 if (!msg->findInt32(KEY_QUALITY, &i32)) {
780 ALOGD("quality is missing, which is required for video encoders in CQ.");
781 return BAD_VALUE;
782 }
783 } else {
784 if (!msg->findInt32(KEY_BIT_RATE, &i32)
785 && !msg->findFloat(KEY_BIT_RATE, &flt)) {
786 ALOGD("bitrate is missing, which is required for video encoders.");
787 return BAD_VALUE;
788 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800789 }
790 if (!msg->findInt32(KEY_I_FRAME_INTERVAL, &i32)
791 && !msg->findFloat(KEY_I_FRAME_INTERVAL, &flt)) {
792 ALOGD("I frame interval is missing, which is required for video encoders.");
793 return BAD_VALUE;
794 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700795 if (!msg->findInt32(KEY_FRAME_RATE, &i32)
796 && !msg->findFloat(KEY_FRAME_RATE, &flt)) {
797 ALOGD("frame rate is missing, which is required for video encoders.");
798 return BAD_VALUE;
799 }
Wonsik Kim1114eea2019-02-25 14:35:24 -0800800 }
801 }
802
Pawin Vongmasa36653902018-11-15 00:10:25 -0800803 /*
804 * Handle input surface configuration
805 */
806 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
807 && (config->mDomain & Config::IS_ENCODER)) {
808 config->mISConfig.reset(new InputSurfaceWrapper::Config{});
809 {
810 config->mISConfig->mMinFps = 0;
811 int64_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800812 if (msg->findInt64(KEY_REPEAT_PREVIOUS_FRAME_AFTER, &value) && value > 0) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800813 config->mISConfig->mMinFps = 1e6 / value;
814 }
Wonsik Kim95ba0162019-03-19 15:51:54 -0700815 if (!msg->findFloat(
816 KEY_MAX_FPS_TO_ENCODER, &config->mISConfig->mMaxFps)) {
817 config->mISConfig->mMaxFps = -1;
818 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800819 config->mISConfig->mMinAdjustedFps = 0;
820 config->mISConfig->mFixedAdjustedFps = 0;
Chong Zhang038e8f82019-02-06 19:05:14 -0800821 if (msg->findInt64(KEY_MAX_PTS_GAP_TO_ENCODER, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800822 if (value < 0 && value >= INT32_MIN) {
823 config->mISConfig->mFixedAdjustedFps = -1e6 / value;
Wonsik Kim95ba0162019-03-19 15:51:54 -0700824 config->mISConfig->mMaxFps = -1;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800825 } else if (value > 0 && value <= INT32_MAX) {
826 config->mISConfig->mMinAdjustedFps = 1e6 / value;
827 }
828 }
829 }
830
831 {
Wonsik Kim8e55f3a2019-09-03 14:10:37 -0700832 bool captureFpsFound = false;
833 double timeLapseFps;
834 float captureRate;
835 if (msg->findDouble("time-lapse-fps", &timeLapseFps)) {
836 config->mISConfig->mCaptureFps = timeLapseFps;
837 captureFpsFound = true;
838 } else if (msg->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
839 config->mISConfig->mCaptureFps = captureRate;
840 captureFpsFound = true;
841 }
842 if (captureFpsFound) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800843 (void)msg->findAsFloat(KEY_FRAME_RATE, &config->mISConfig->mCodedFps);
844 }
845 }
846
847 {
848 config->mISConfig->mSuspended = false;
849 config->mISConfig->mSuspendAtUs = -1;
850 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -0800851 if (msg->findInt32(KEY_CREATE_INPUT_SURFACE_SUSPENDED, &value) && value) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800852 config->mISConfig->mSuspended = true;
853 }
854 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700855 config->mISConfig->mUsage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800856 }
857
858 /*
859 * Handle desired color format.
860 */
861 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
862 int32_t format = -1;
863 if (!msg->findInt32(KEY_COLOR_FORMAT, &format)) {
864 /*
865 * Also handle default color format (encoders require color format, so this is only
866 * needed for decoders.
867 */
868 if (!(config->mDomain & Config::IS_ENCODER)) {
869 format = (surface == nullptr) ? COLOR_FormatYUV420Planar : COLOR_FormatSurface;
870 }
871 }
872
873 if (format >= 0) {
874 msg->setInt32("android._color-format", format);
875 }
876 }
877
878 std::vector<std::unique_ptr<C2Param>> configUpdate;
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800879 // NOTE: We used to ignore "video-bitrate" at configure; replicate
880 // the behavior here.
881 sp<AMessage> sdkParams = msg;
882 int32_t videoBitrate;
883 if (sdkParams->findInt32(PARAMETER_KEY_VIDEO_BITRATE, &videoBitrate)) {
884 sdkParams = msg->dup();
885 sdkParams->removeEntryAt(sdkParams->findEntryByName(PARAMETER_KEY_VIDEO_BITRATE));
886 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800887 status_t err = config->getConfigUpdateFromSdkParams(
Wonsik Kimaa484ac2019-02-13 16:54:02 -0800888 comp, sdkParams, Config::IS_CONFIG, C2_DONT_BLOCK, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800889 if (err != OK) {
890 ALOGW("failed to convert configuration to c2 params");
891 }
Wonsik Kimaab2eea2019-05-22 10:37:58 -0700892
893 int32_t maxBframes = 0;
894 if ((config->mDomain & Config::IS_ENCODER)
895 && (config->mDomain & Config::IS_VIDEO)
896 && sdkParams->findInt32(KEY_MAX_B_FRAMES, &maxBframes)
897 && maxBframes > 0) {
898 std::unique_ptr<C2StreamGopTuning::output> gop =
899 C2StreamGopTuning::output::AllocUnique(2 /* flexCount */, 0u /* stream */);
900 gop->m.values[0] = { P_FRAME, UINT32_MAX };
901 gop->m.values[1] = {
902 C2Config::picture_type_t(P_FRAME | B_FRAME),
903 uint32_t(maxBframes)
904 };
905 configUpdate.push_back(std::move(gop));
906 }
907
Pawin Vongmasa36653902018-11-15 00:10:25 -0800908 err = config->setParameters(comp, configUpdate, C2_DONT_BLOCK);
909 if (err != OK) {
910 ALOGW("failed to configure c2 params");
911 return err;
912 }
913
914 std::vector<std::unique_ptr<C2Param>> params;
915 C2StreamUsageTuning::input usage(0u, 0u);
916 C2StreamMaxBufferSizeInfo::input maxInputSize(0u, 0u);
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700917 C2PrependHeaderModeSetting prepend(PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800918
919 std::initializer_list<C2Param::Index> indices {
920 };
921 c2_status_t c2err = comp->query(
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700922 { &usage, &maxInputSize, &prepend },
Pawin Vongmasa36653902018-11-15 00:10:25 -0800923 indices,
924 C2_DONT_BLOCK,
925 &params);
926 if (c2err != C2_OK && c2err != C2_BAD_INDEX) {
927 ALOGE("Failed to query component interface: %d", c2err);
928 return UNKNOWN_ERROR;
929 }
930 if (params.size() != indices.size()) {
931 ALOGE("Component returns wrong number of params: expected %zu actual %zu",
932 indices.size(), params.size());
933 return UNKNOWN_ERROR;
934 }
Wonsik Kim9eac4d12019-05-23 12:58:48 -0700935 if (usage) {
936 if (usage.value & C2MemoryUsage::CPU_READ) {
937 config->mInputFormat->setInt32("using-sw-read-often", true);
938 }
939 if (config->mISConfig) {
940 C2AndroidMemoryUsage androidUsage(C2MemoryUsage(usage.value));
941 config->mISConfig->mUsage = androidUsage.asGrallocUsage();
942 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800943 }
944
945 // NOTE: we don't blindly use client specified input size if specified as clients
946 // at times specify too small size. Instead, mimic the behavior from OMX, where the
947 // client specified size is only used to ask for bigger buffers than component suggested
948 // size.
949 int32_t clientInputSize = 0;
950 bool clientSpecifiedInputSize =
951 msg->findInt32(KEY_MAX_INPUT_SIZE, &clientInputSize) && clientInputSize > 0;
952 // TEMP: enforce minimum buffer size of 1MB for video decoders
953 // and 16K / 4K for audio encoders/decoders
954 if (maxInputSize.value == 0) {
955 if (config->mDomain & Config::IS_AUDIO) {
956 maxInputSize.value = encoder ? 16384 : 4096;
957 } else if (!encoder) {
958 maxInputSize.value = 1048576u;
959 }
960 }
961
962 // verify that CSD fits into this size (if defined)
963 if ((config->mDomain & Config::IS_DECODER) && maxInputSize.value > 0) {
964 sp<ABuffer> csd;
965 for (size_t ix = 0; msg->findBuffer(StringPrintf("csd-%zu", ix).c_str(), &csd); ++ix) {
966 if (csd && csd->size() > maxInputSize.value) {
967 maxInputSize.value = csd->size();
968 }
969 }
970 }
971
972 // TODO: do this based on component requiring linear allocator for input
973 if ((config->mDomain & Config::IS_DECODER) || (config->mDomain & Config::IS_AUDIO)) {
974 if (clientSpecifiedInputSize) {
975 // Warn that we're overriding client's max input size if necessary.
976 if ((uint32_t)clientInputSize < maxInputSize.value) {
977 ALOGD("client requested max input size %d, which is smaller than "
978 "what component recommended (%u); overriding with component "
979 "recommendation.", clientInputSize, maxInputSize.value);
980 ALOGW("This behavior is subject to change. It is recommended that "
981 "app developers double check whether the requested "
982 "max input size is in reasonable range.");
983 } else {
984 maxInputSize.value = clientInputSize;
985 }
986 }
987 // Pass max input size on input format to the buffer channel (if supplied by the
988 // component or by a default)
989 if (maxInputSize.value) {
990 config->mInputFormat->setInt32(
991 KEY_MAX_INPUT_SIZE,
992 (int32_t)(c2_min(maxInputSize.value, uint32_t(INT32_MAX))));
993 }
994 }
995
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700996 int32_t clientPrepend;
997 if ((config->mDomain & Config::IS_VIDEO)
998 && (config->mDomain & Config::IS_ENCODER)
999 && msg->findInt32(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES, &clientPrepend)
1000 && clientPrepend
1001 && (!prepend || prepend.value != PREPEND_HEADER_TO_ALL_SYNC)) {
1002 ALOGE("Failed to set KEY_PREPEND_HEADERS_TO_SYNC_FRAMES");
1003 return BAD_VALUE;
1004 }
1005
Pawin Vongmasa36653902018-11-15 00:10:25 -08001006 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))) {
1007 // propagate HDR static info to output format for both encoders and decoders
1008 // if component supports this info, we will update from component, but only the raw port,
1009 // so don't propagate if component already filled it in.
1010 sp<ABuffer> hdrInfo;
1011 if (msg->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)
1012 && !config->mOutputFormat->findBuffer(KEY_HDR_STATIC_INFO, &hdrInfo)) {
1013 config->mOutputFormat->setBuffer(KEY_HDR_STATIC_INFO, hdrInfo);
1014 }
1015
1016 // Set desired color format from configuration parameter
1017 int32_t format;
1018 if (msg->findInt32("android._color-format", &format)) {
1019 if (config->mDomain & Config::IS_ENCODER) {
1020 config->mInputFormat->setInt32(KEY_COLOR_FORMAT, format);
1021 } else {
1022 config->mOutputFormat->setInt32(KEY_COLOR_FORMAT, format);
1023 }
1024 }
1025 }
1026
1027 // propagate encoder delay and padding to output format
1028 if ((config->mDomain & Config::IS_DECODER) && (config->mDomain & Config::IS_AUDIO)) {
1029 int delay = 0;
1030 if (msg->findInt32("encoder-delay", &delay)) {
1031 config->mOutputFormat->setInt32("encoder-delay", delay);
1032 }
1033 int padding = 0;
1034 if (msg->findInt32("encoder-padding", &padding)) {
1035 config->mOutputFormat->setInt32("encoder-padding", padding);
1036 }
1037 }
1038
1039 // set channel-mask
1040 if (config->mDomain & Config::IS_AUDIO) {
1041 int32_t mask;
1042 if (msg->findInt32(KEY_CHANNEL_MASK, &mask)) {
1043 if (config->mDomain & Config::IS_ENCODER) {
1044 config->mInputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1045 } else {
1046 config->mOutputFormat->setInt32(KEY_CHANNEL_MASK, mask);
1047 }
1048 }
1049 }
1050
1051 ALOGD("setup formats input: %s and output: %s",
1052 config->mInputFormat->debugString().c_str(),
1053 config->mOutputFormat->debugString().c_str());
1054 return OK;
1055 };
1056 if (tryAndReportOnError(doConfig) != OK) {
1057 return;
1058 }
1059
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001060 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1061 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001062
1063 mCallback->onComponentConfigured(config->mInputFormat, config->mOutputFormat);
1064}
1065
1066void CCodec::initiateCreateInputSurface() {
1067 status_t err = [this] {
1068 Mutexed<State>::Locked state(mState);
1069 if (state->get() != ALLOCATED) {
1070 return UNKNOWN_ERROR;
1071 }
1072 // TODO: read it from intf() properly.
1073 if (state->comp->getName().find("encoder") == std::string::npos) {
1074 return INVALID_OPERATION;
1075 }
1076 return OK;
1077 }();
1078 if (err != OK) {
1079 mCallback->onInputSurfaceCreationFailed(err);
1080 return;
1081 }
1082
1083 (new AMessage(kWhatCreateInputSurface, this))->post();
1084}
1085
Lajos Molnar47118272019-01-31 16:28:04 -08001086sp<PersistentSurface> CCodec::CreateOmxInputSurface() {
1087 using namespace android::hardware::media::omx::V1_0;
1088 using namespace android::hardware::media::omx::V1_0::utils;
1089 using namespace android::hardware::graphics::bufferqueue::V1_0::utils;
1090 typedef android::hardware::media::omx::V1_0::Status OmxStatus;
1091 android::sp<IOmx> omx = IOmx::getService();
1092 typedef android::hardware::graphics::bufferqueue::V1_0::
1093 IGraphicBufferProducer HGraphicBufferProducer;
1094 typedef android::hardware::media::omx::V1_0::
1095 IGraphicBufferSource HGraphicBufferSource;
1096 OmxStatus s;
1097 android::sp<HGraphicBufferProducer> gbp;
1098 android::sp<HGraphicBufferSource> gbs;
Pawin Vongmasa18588322019-05-18 01:52:13 -07001099
Chong Zhangc8ce1d82019-03-27 10:18:38 -07001100 using ::android::hardware::Return;
1101 Return<void> transStatus = omx->createInputSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001102 [&s, &gbp, &gbs](
1103 OmxStatus status,
1104 const android::sp<HGraphicBufferProducer>& producer,
1105 const android::sp<HGraphicBufferSource>& source) {
1106 s = status;
1107 gbp = producer;
1108 gbs = source;
1109 });
1110 if (transStatus.isOk() && s == OmxStatus::OK) {
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001111 return new PersistentSurface(new H2BGraphicBufferProducer(gbp), gbs);
Lajos Molnar47118272019-01-31 16:28:04 -08001112 }
1113
1114 return nullptr;
1115}
1116
1117sp<PersistentSurface> CCodec::CreateCompatibleInputSurface() {
1118 sp<PersistentSurface> surface(CreateInputSurface());
1119
1120 if (surface == nullptr) {
1121 surface = CreateOmxInputSurface();
1122 }
1123
1124 return surface;
1125}
1126
Pawin Vongmasa36653902018-11-15 00:10:25 -08001127void CCodec::createInputSurface() {
1128 status_t err;
1129 sp<IGraphicBufferProducer> bufferProducer;
1130
1131 sp<AMessage> inputFormat;
1132 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001133 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001134 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001135 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1136 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001137 inputFormat = config->mInputFormat;
1138 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001139 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001140 }
1141
Lajos Molnar47118272019-01-31 16:28:04 -08001142 sp<PersistentSurface> persistentSurface = CreateCompatibleInputSurface();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001143 sp<hidl::base::V1_0::IBase> hidlTarget = persistentSurface->getHidlTarget();
1144 sp<IInputSurface> hidlInputSurface = IInputSurface::castFrom(hidlTarget);
1145 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001146
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001147 if (hidlInputSurface) {
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001148 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1149 std::make_shared<Codec2Client::InputSurface>(hidlInputSurface);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001150 err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001151 inputSurface));
1152 bufferProducer = inputSurface->getGraphicBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001153 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001154 int32_t width = 0;
1155 (void)outputFormat->findInt32("width", &width);
1156 int32_t height = 0;
1157 (void)outputFormat->findInt32("height", &height);
1158 err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001159 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001160 bufferProducer = persistentSurface->getBufferProducer();
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001161 } else {
1162 ALOGE("Corrupted input surface");
1163 mCallback->onInputSurfaceCreationFailed(UNKNOWN_ERROR);
1164 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001165 }
1166
1167 if (err != OK) {
1168 ALOGE("Failed to set up input surface: %d", err);
1169 mCallback->onInputSurfaceCreationFailed(err);
1170 return;
1171 }
1172
1173 mCallback->onInputSurfaceCreated(
1174 inputFormat,
1175 outputFormat,
1176 new BufferProducerWrapper(bufferProducer));
1177}
1178
1179status_t CCodec::setupInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001180 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1181 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001182 config->mUsingSurface = true;
1183
1184 // we are now using surface - apply default color aspects to input format - as well as
1185 // get dataspace
1186 bool inputFormatChanged = config->updateFormats(config->IS_INPUT);
1187 ALOGD("input format %s to %s",
1188 inputFormatChanged ? "changed" : "unchanged",
1189 config->mInputFormat->debugString().c_str());
1190
1191 // configure dataspace
1192 static_assert(sizeof(int32_t) == sizeof(android_dataspace), "dataspace size mismatch");
1193 android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
1194 (void)config->mInputFormat->findInt32("android._dataspace", (int32_t*)&dataSpace);
1195 surface->setDataSpace(dataSpace);
1196
1197 status_t err = mChannel->setInputSurface(surface);
1198 if (err != OK) {
1199 // undo input format update
1200 config->mUsingSurface = false;
1201 (void)config->updateFormats(config->IS_INPUT);
1202 return err;
1203 }
1204 config->mInputSurface = surface;
1205
1206 if (config->mISConfig) {
1207 surface->configure(*config->mISConfig);
1208 } else {
1209 ALOGD("ISConfig: no configuration");
1210 }
1211
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001212 return OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001213}
1214
1215void CCodec::initiateSetInputSurface(const sp<PersistentSurface> &surface) {
1216 sp<AMessage> msg = new AMessage(kWhatSetInputSurface, this);
1217 msg->setObject("surface", surface);
1218 msg->post();
1219}
1220
1221void CCodec::setInputSurface(const sp<PersistentSurface> &surface) {
1222 sp<AMessage> inputFormat;
1223 sp<AMessage> outputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001224 uint64_t usage = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001225 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001226 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1227 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001228 inputFormat = config->mInputFormat;
1229 outputFormat = config->mOutputFormat;
Wonsik Kim9eac4d12019-05-23 12:58:48 -07001230 usage = config->mISConfig ? config->mISConfig->mUsage : 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001231 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001232 sp<hidl::base::V1_0::IBase> hidlTarget = surface->getHidlTarget();
1233 sp<IInputSurface> inputSurface = IInputSurface::castFrom(hidlTarget);
1234 sp<HGraphicBufferSource> gbs = HGraphicBufferSource::castFrom(hidlTarget);
1235 if (inputSurface) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001236 status_t err = setupInputSurface(std::make_shared<C2InputSurfaceWrapper>(
1237 std::make_shared<Codec2Client::InputSurface>(inputSurface)));
1238 if (err != OK) {
1239 ALOGE("Failed to set up input surface: %d", err);
1240 mCallback->onInputSurfaceDeclined(err);
1241 return;
1242 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001243 } else if (gbs) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001244 int32_t width = 0;
1245 (void)outputFormat->findInt32("width", &width);
1246 int32_t height = 0;
1247 (void)outputFormat->findInt32("height", &height);
1248 status_t err = setupInputSurface(std::make_shared<GraphicBufferSourceWrapper>(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001249 gbs, width, height, usage));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001250 if (err != OK) {
1251 ALOGE("Failed to set up input surface: %d", err);
1252 mCallback->onInputSurfaceDeclined(err);
1253 return;
1254 }
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001255 } else {
1256 ALOGE("Failed to set input surface: Corrupted surface.");
1257 mCallback->onInputSurfaceDeclined(UNKNOWN_ERROR);
1258 return;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001259 }
1260 mCallback->onInputSurfaceAccepted(inputFormat, outputFormat);
1261}
1262
1263void CCodec::initiateStart() {
1264 auto setStarting = [this] {
1265 Mutexed<State>::Locked state(mState);
1266 if (state->get() != ALLOCATED) {
1267 return UNKNOWN_ERROR;
1268 }
1269 state->set(STARTING);
1270 return OK;
1271 };
1272 if (tryAndReportOnError(setStarting) != OK) {
1273 return;
1274 }
1275
1276 (new AMessage(kWhatStart, this))->post();
1277}
1278
1279void CCodec::start() {
1280 std::shared_ptr<Codec2Client::Component> comp;
1281 auto checkStarting = [this, &comp] {
1282 Mutexed<State>::Locked state(mState);
1283 if (state->get() != STARTING) {
1284 return UNKNOWN_ERROR;
1285 }
1286 comp = state->comp;
1287 return OK;
1288 };
1289 if (tryAndReportOnError(checkStarting) != OK) {
1290 return;
1291 }
1292
1293 c2_status_t err = comp->start();
1294 if (err != C2_OK) {
1295 mCallback->onError(toStatusT(err, C2_OPERATION_Component_start),
1296 ACTION_CODE_FATAL);
1297 return;
1298 }
1299 sp<AMessage> inputFormat;
1300 sp<AMessage> outputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001301 status_t err2 = OK;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001302 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001303 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1304 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001305 inputFormat = config->mInputFormat;
1306 outputFormat = config->mOutputFormat;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001307 if (config->mInputSurface) {
1308 err2 = config->mInputSurface->start();
1309 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001310 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001311 if (err2 != OK) {
1312 mCallback->onError(err2, ACTION_CODE_FATAL);
1313 return;
1314 }
1315 err2 = mChannel->start(inputFormat, outputFormat);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001316 if (err2 != OK) {
1317 mCallback->onError(err2, ACTION_CODE_FATAL);
1318 return;
1319 }
1320
1321 auto setRunning = [this] {
1322 Mutexed<State>::Locked state(mState);
1323 if (state->get() != STARTING) {
1324 return UNKNOWN_ERROR;
1325 }
1326 state->set(RUNNING);
1327 return OK;
1328 };
1329 if (tryAndReportOnError(setRunning) != OK) {
1330 return;
1331 }
1332 mCallback->onStartCompleted();
1333
1334 (void)mChannel->requestInitialInputBuffers();
1335}
1336
1337void CCodec::initiateShutdown(bool keepComponentAllocated) {
1338 if (keepComponentAllocated) {
1339 initiateStop();
1340 } else {
1341 initiateRelease();
1342 }
1343}
1344
1345void CCodec::initiateStop() {
1346 {
1347 Mutexed<State>::Locked state(mState);
1348 if (state->get() == ALLOCATED
1349 || state->get() == RELEASED
1350 || state->get() == STOPPING
1351 || state->get() == RELEASING) {
1352 // We're already stopped, released, or doing it right now.
1353 state.unlock();
1354 mCallback->onStopCompleted();
1355 state.lock();
1356 return;
1357 }
1358 state->set(STOPPING);
1359 }
1360
1361 mChannel->stop();
1362 (new AMessage(kWhatStop, this))->post();
1363}
1364
1365void CCodec::stop() {
1366 std::shared_ptr<Codec2Client::Component> comp;
1367 {
1368 Mutexed<State>::Locked state(mState);
1369 if (state->get() == RELEASING) {
1370 state.unlock();
1371 // We're already stopped or release is in progress.
1372 mCallback->onStopCompleted();
1373 state.lock();
1374 return;
1375 } else if (state->get() != STOPPING) {
1376 state.unlock();
1377 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1378 state.lock();
1379 return;
1380 }
1381 comp = state->comp;
1382 }
1383 status_t err = comp->stop();
1384 if (err != C2_OK) {
1385 // TODO: convert err into status_t
1386 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1387 }
1388
1389 {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001390 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1391 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001392 if (config->mInputSurface) {
1393 config->mInputSurface->disconnect();
1394 config->mInputSurface = nullptr;
1395 }
1396 }
1397 {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001398 Mutexed<State>::Locked state(mState);
1399 if (state->get() == STOPPING) {
1400 state->set(ALLOCATED);
1401 }
1402 }
1403 mCallback->onStopCompleted();
1404}
1405
1406void CCodec::initiateRelease(bool sendCallback /* = true */) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001407 bool clearInputSurfaceIfNeeded = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001408 {
1409 Mutexed<State>::Locked state(mState);
1410 if (state->get() == RELEASED || state->get() == RELEASING) {
1411 // We're already released or doing it right now.
1412 if (sendCallback) {
1413 state.unlock();
1414 mCallback->onReleaseCompleted();
1415 state.lock();
1416 }
1417 return;
1418 }
1419 if (state->get() == ALLOCATING) {
1420 state->set(RELEASING);
1421 // With the altered state allocate() would fail and clean up.
1422 if (sendCallback) {
1423 state.unlock();
1424 mCallback->onReleaseCompleted();
1425 state.lock();
1426 }
1427 return;
1428 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001429 if (state->get() == STARTING
1430 || state->get() == RUNNING
1431 || state->get() == STOPPING) {
1432 // Input surface may have been started, so clean up is needed.
1433 clearInputSurfaceIfNeeded = true;
1434 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001435 state->set(RELEASING);
1436 }
1437
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001438 if (clearInputSurfaceIfNeeded) {
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001439 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1440 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001441 if (config->mInputSurface) {
1442 config->mInputSurface->disconnect();
1443 config->mInputSurface = nullptr;
1444 }
1445 }
1446
Pawin Vongmasa36653902018-11-15 00:10:25 -08001447 mChannel->stop();
1448 // thiz holds strong ref to this while the thread is running.
1449 sp<CCodec> thiz(this);
1450 std::thread([thiz, sendCallback] { thiz->release(sendCallback); }).detach();
1451}
1452
1453void CCodec::release(bool sendCallback) {
1454 std::shared_ptr<Codec2Client::Component> comp;
1455 {
1456 Mutexed<State>::Locked state(mState);
1457 if (state->get() == RELEASED) {
1458 if (sendCallback) {
1459 state.unlock();
1460 mCallback->onReleaseCompleted();
1461 state.lock();
1462 }
1463 return;
1464 }
1465 comp = state->comp;
1466 }
1467 comp->release();
1468
1469 {
1470 Mutexed<State>::Locked state(mState);
1471 state->set(RELEASED);
1472 state->comp.reset();
1473 }
1474 if (sendCallback) {
1475 mCallback->onReleaseCompleted();
1476 }
1477}
1478
1479status_t CCodec::setSurface(const sp<Surface> &surface) {
1480 return mChannel->setSurface(surface);
1481}
1482
1483void CCodec::signalFlush() {
1484 status_t err = [this] {
1485 Mutexed<State>::Locked state(mState);
1486 if (state->get() == FLUSHED) {
1487 return ALREADY_EXISTS;
1488 }
1489 if (state->get() != RUNNING) {
1490 return UNKNOWN_ERROR;
1491 }
1492 state->set(FLUSHING);
1493 return OK;
1494 }();
1495 switch (err) {
1496 case ALREADY_EXISTS:
1497 mCallback->onFlushCompleted();
1498 return;
1499 case OK:
1500 break;
1501 default:
1502 mCallback->onError(err, ACTION_CODE_FATAL);
1503 return;
1504 }
1505
1506 mChannel->stop();
1507 (new AMessage(kWhatFlush, this))->post();
1508}
1509
1510void CCodec::flush() {
1511 std::shared_ptr<Codec2Client::Component> comp;
1512 auto checkFlushing = [this, &comp] {
1513 Mutexed<State>::Locked state(mState);
1514 if (state->get() != FLUSHING) {
1515 return UNKNOWN_ERROR;
1516 }
1517 comp = state->comp;
1518 return OK;
1519 };
1520 if (tryAndReportOnError(checkFlushing) != OK) {
1521 return;
1522 }
1523
1524 std::list<std::unique_ptr<C2Work>> flushedWork;
1525 c2_status_t err = comp->flush(C2Component::FLUSH_COMPONENT, &flushedWork);
1526 {
1527 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1528 flushedWork.splice(flushedWork.end(), *queue);
1529 }
1530 if (err != C2_OK) {
1531 // TODO: convert err into status_t
1532 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1533 }
1534
1535 mChannel->flush(flushedWork);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001536
1537 {
1538 Mutexed<State>::Locked state(mState);
Iris Changce521ee2019-07-05 16:18:54 +08001539 if (state->get() == FLUSHING) {
1540 state->set(FLUSHED);
1541 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001542 }
1543 mCallback->onFlushCompleted();
1544}
1545
1546void CCodec::signalResume() {
1547 auto setResuming = [this] {
1548 Mutexed<State>::Locked state(mState);
1549 if (state->get() != FLUSHED) {
1550 return UNKNOWN_ERROR;
1551 }
1552 state->set(RESUMING);
1553 return OK;
1554 };
1555 if (tryAndReportOnError(setResuming) != OK) {
1556 return;
1557 }
1558
1559 (void)mChannel->start(nullptr, nullptr);
1560
1561 {
1562 Mutexed<State>::Locked state(mState);
1563 if (state->get() != RESUMING) {
1564 state.unlock();
1565 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1566 state.lock();
1567 return;
1568 }
1569 state->set(RUNNING);
1570 }
1571
1572 (void)mChannel->requestInitialInputBuffers();
1573}
1574
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001575void CCodec::signalSetParameters(const sp<AMessage> &msg) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001576 std::shared_ptr<Codec2Client::Component> comp;
1577 auto checkState = [this, &comp] {
1578 Mutexed<State>::Locked state(mState);
1579 if (state->get() == RELEASED) {
1580 return INVALID_OPERATION;
1581 }
1582 comp = state->comp;
1583 return OK;
1584 };
1585 if (tryAndReportOnError(checkState) != OK) {
1586 return;
1587 }
1588
Wonsik Kimaa484ac2019-02-13 16:54:02 -08001589 // NOTE: We used to ignore "bitrate" at setParameters; replicate
1590 // the behavior here.
1591 sp<AMessage> params = msg;
1592 int32_t bitrate;
1593 if (params->findInt32(KEY_BIT_RATE, &bitrate)) {
1594 params = msg->dup();
1595 params->removeEntryAt(params->findEntryByName(KEY_BIT_RATE));
1596 }
1597
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001598 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1599 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001600
1601 /**
1602 * Handle input surface parameters
1603 */
1604 if ((config->mDomain & (Config::IS_VIDEO | Config::IS_IMAGE))
1605 && (config->mDomain & Config::IS_ENCODER) && config->mInputSurface && config->mISConfig) {
Chong Zhang038e8f82019-02-06 19:05:14 -08001606 (void)params->findInt64(PARAMETER_KEY_OFFSET_TIME, &config->mISConfig->mTimeOffsetUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001607
1608 if (params->findInt64("skip-frames-before", &config->mISConfig->mStartAtUs)) {
1609 config->mISConfig->mStopped = false;
1610 } else if (params->findInt64("stop-time-us", &config->mISConfig->mStopAtUs)) {
1611 config->mISConfig->mStopped = true;
1612 }
1613
1614 int32_t value;
Chong Zhang038e8f82019-02-06 19:05:14 -08001615 if (params->findInt32(PARAMETER_KEY_SUSPEND, &value)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001616 config->mISConfig->mSuspended = value;
1617 config->mISConfig->mSuspendAtUs = -1;
Chong Zhang038e8f82019-02-06 19:05:14 -08001618 (void)params->findInt64(PARAMETER_KEY_SUSPEND_TIME, &config->mISConfig->mSuspendAtUs);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001619 }
1620
1621 (void)config->mInputSurface->configure(*config->mISConfig);
1622 if (config->mISConfig->mStopped) {
1623 config->mInputFormat->setInt64(
1624 "android._stop-time-offset-us", config->mISConfig->mInputDelayUs);
1625 }
1626 }
1627
1628 std::vector<std::unique_ptr<C2Param>> configUpdate;
1629 (void)config->getConfigUpdateFromSdkParams(
1630 comp, params, Config::IS_PARAM, C2_MAY_BLOCK, &configUpdate);
1631 // Prefer to pass parameters to the buffer channel, so they can be synchronized with the frames.
1632 // Parameter synchronization is not defined when using input surface. For now, route
1633 // these directly to the component.
1634 if (config->mInputSurface == nullptr
1635 && (property_get_bool("debug.stagefright.ccodec_delayed_params", false)
1636 || comp->getName().find("c2.android.") == 0)) {
1637 mChannel->setParameters(configUpdate);
1638 } else {
1639 (void)config->setParameters(comp, configUpdate, C2_MAY_BLOCK);
1640 }
1641}
1642
1643void CCodec::signalEndOfInputStream() {
1644 mCallback->onSignaledInputEOS(mChannel->signalEndOfInputStream());
1645}
1646
1647void CCodec::signalRequestIDRFrame() {
1648 std::shared_ptr<Codec2Client::Component> comp;
1649 {
1650 Mutexed<State>::Locked state(mState);
1651 if (state->get() == RELEASED) {
1652 ALOGD("no IDR request sent since component is released");
1653 return;
1654 }
1655 comp = state->comp;
1656 }
1657 ALOGV("request IDR");
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001658 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1659 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001660 std::vector<std::unique_ptr<C2Param>> params;
1661 params.push_back(
1662 std::make_unique<C2StreamRequestSyncFrameTuning::output>(0u, true));
1663 config->setParameters(comp, params, C2_MAY_BLOCK);
1664}
1665
Wonsik Kimab34ed62019-01-31 15:28:46 -08001666void CCodec::onWorkDone(std::list<std::unique_ptr<C2Work>> &workItems) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001667 if (!workItems.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001668 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1669 queue->splice(queue->end(), workItems);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001670 }
1671 (new AMessage(kWhatWorkDone, this))->post();
1672}
1673
Wonsik Kimab34ed62019-01-31 15:28:46 -08001674void CCodec::onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) {
1675 mChannel->onInputBufferDone(frameIndex, arrayIndex);
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001676 if (arrayIndex == 0) {
1677 // We always put no more than one buffer per work, if we use an input surface.
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001678 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1679 const std::unique_ptr<Config> &config = *configLocked;
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001680 if (config->mInputSurface) {
1681 config->mInputSurface->onInputBufferDone(frameIndex);
1682 }
1683 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001684}
1685
1686void CCodec::onMessageReceived(const sp<AMessage> &msg) {
1687 TimePoint now = std::chrono::steady_clock::now();
1688 CCodecWatchdog::getInstance()->watch(this);
1689 switch (msg->what()) {
1690 case kWhatAllocate: {
1691 // C2ComponentStore::createComponent() should return within 100ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001692 setDeadline(now, 1500ms, "allocate");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001693 sp<RefBase> obj;
1694 CHECK(msg->findObject("codecInfo", &obj));
1695 allocate((MediaCodecInfo *)obj.get());
1696 break;
1697 }
1698 case kWhatConfigure: {
1699 // C2Component::commit_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001700 setDeadline(now, 1500ms, "configure");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001701 sp<AMessage> format;
1702 CHECK(msg->findMessage("format", &format));
1703 configure(format);
1704 break;
1705 }
1706 case kWhatStart: {
1707 // C2Component::start() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001708 setDeadline(now, 1500ms, "start");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001709 start();
1710 break;
1711 }
1712 case kWhatStop: {
1713 // C2Component::stop() should return within 500ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001714 setDeadline(now, 1500ms, "stop");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001715 stop();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001716 break;
1717 }
1718 case kWhatFlush: {
1719 // C2Component::flush_sm() should return within 5ms.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001720 setDeadline(now, 1500ms, "flush");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001721 flush();
1722 break;
1723 }
1724 case kWhatCreateInputSurface: {
1725 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001726 setDeadline(now, 1500ms, "createInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001727 createInputSurface();
1728 break;
1729 }
1730 case kWhatSetInputSurface: {
1731 // Surface operations may be briefly blocking.
Wonsik Kim9ee5a7c2019-06-17 11:33:24 -07001732 setDeadline(now, 1500ms, "setInputSurface");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001733 sp<RefBase> obj;
1734 CHECK(msg->findObject("surface", &obj));
1735 sp<PersistentSurface> surface(static_cast<PersistentSurface *>(obj.get()));
1736 setInputSurface(surface);
1737 break;
1738 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001739 case kWhatWorkDone: {
1740 std::unique_ptr<C2Work> work;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001741 bool shouldPost = false;
1742 {
1743 Mutexed<std::list<std::unique_ptr<C2Work>>>::Locked queue(mWorkDoneQueue);
1744 if (queue->empty()) {
1745 break;
1746 }
1747 work.swap(queue->front());
1748 queue->pop_front();
1749 shouldPost = !queue->empty();
1750 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001751 if (shouldPost) {
1752 (new AMessage(kWhatWorkDone, this))->post();
1753 }
1754
Pawin Vongmasa36653902018-11-15 00:10:25 -08001755 // handle configuration changes in work done
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001756 Mutexed<std::unique_ptr<Config>>::Locked configLocked(mConfig);
1757 const std::unique_ptr<Config> &config = *configLocked;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001758 bool changed = false;
1759 Config::Watcher<C2StreamInitDataInfo::output> initData =
1760 config->watch<C2StreamInitDataInfo::output>();
1761 if (!work->worklets.empty()
1762 && (work->worklets.front()->output.flags
1763 & C2FrameData::FLAG_DISCARD_FRAME) == 0) {
1764
1765 // copy buffer info to config
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001766 std::vector<std::unique_ptr<C2Param>> updates;
1767 for (const std::unique_ptr<C2Param> &param
1768 : work->worklets.front()->output.configUpdate) {
1769 updates.push_back(C2Param::Copy(*param));
1770 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001771 unsigned stream = 0;
1772 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1773 for (const std::shared_ptr<const C2Info> &info : buf->info()) {
1774 // move all info into output-stream #0 domain
1775 updates.emplace_back(C2Param::CopyAsStream(*info, true /* output */, stream));
1776 }
1777 for (const C2ConstGraphicBlock &block : buf->data().graphicBlocks()) {
1778 // ALOGV("got output buffer with crop %u,%u+%u,%u and size %u,%u",
1779 // block.crop().left, block.crop().top,
1780 // block.crop().width, block.crop().height,
1781 // block.width(), block.height());
1782 updates.emplace_back(new C2StreamCropRectInfo::output(stream, block.crop()));
1783 updates.emplace_back(new C2StreamPictureSizeInfo::output(
Harish Mahendrakarf7c49e22019-05-24 14:19:16 -07001784 stream, block.crop().width, block.crop().height));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001785 break; // for now only do the first block
1786 }
1787 ++stream;
1788 }
1789
1790 changed = config->updateConfiguration(updates, config->mOutputDomain);
1791
1792 // copy standard infos to graphic buffers if not already present (otherwise, we
1793 // may overwrite the actual intermediate value with a final value)
1794 stream = 0;
1795 const static std::vector<C2Param::Index> stdGfxInfos = {
1796 C2StreamRotationInfo::output::PARAM_TYPE,
1797 C2StreamColorAspectsInfo::output::PARAM_TYPE,
1798 C2StreamDataSpaceInfo::output::PARAM_TYPE,
1799 C2StreamHdrStaticInfo::output::PARAM_TYPE,
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001800 C2StreamHdr10PlusInfo::output::PARAM_TYPE,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001801 C2StreamPixelAspectRatioInfo::output::PARAM_TYPE,
1802 C2StreamSurfaceScalingInfo::output::PARAM_TYPE
1803 };
1804 for (const std::shared_ptr<C2Buffer> &buf : work->worklets.front()->output.buffers) {
1805 if (buf->data().graphicBlocks().size()) {
1806 for (C2Param::Index ix : stdGfxInfos) {
1807 if (!buf->hasInfo(ix)) {
1808 const C2Param *param =
1809 config->getConfigParameterValue(ix.withStream(stream));
1810 if (param) {
1811 std::shared_ptr<C2Param> info(C2Param::Copy(*param));
1812 buf->setInfo(std::static_pointer_cast<C2Info>(info));
1813 }
1814 }
1815 }
1816 }
1817 ++stream;
1818 }
1819 }
Wonsik Kim4f3314d2019-03-26 17:00:34 -07001820 if (config->mInputSurface) {
1821 config->mInputSurface->onInputBufferDone(work->input.ordinal.frameIndex);
1822 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001823 mChannel->onWorkDone(
1824 std::move(work), changed ? config->mOutputFormat : nullptr,
Wonsik Kimab34ed62019-01-31 15:28:46 -08001825 initData.hasChanged() ? initData.update().get() : nullptr);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001826 break;
1827 }
1828 case kWhatWatch: {
1829 // watch message already posted; no-op.
1830 break;
1831 }
1832 default: {
1833 ALOGE("unrecognized message");
1834 break;
1835 }
1836 }
1837 setDeadline(TimePoint::max(), 0ms, "none");
1838}
1839
1840void CCodec::setDeadline(
1841 const TimePoint &now,
1842 const std::chrono::milliseconds &timeout,
1843 const char *name) {
1844 int32_t mult = std::max(1, property_get_int32("debug.stagefright.ccodec_timeout_mult", 1));
1845 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
1846 deadline->set(now + (timeout * mult), name);
1847}
1848
1849void CCodec::initiateReleaseIfStuck() {
1850 std::string name;
1851 bool pendingDeadline = false;
Wonsik Kimab34ed62019-01-31 15:28:46 -08001852 {
1853 Mutexed<NamedTimePoint>::Locked deadline(mDeadline);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001854 if (deadline->get() < std::chrono::steady_clock::now()) {
1855 name = deadline->getName();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001856 }
1857 if (deadline->get() != TimePoint::max()) {
1858 pendingDeadline = true;
1859 }
1860 }
1861 if (name.empty()) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08001862 constexpr std::chrono::steady_clock::duration kWorkDurationThreshold = 3s;
1863 std::chrono::steady_clock::duration elapsed = mChannel->elapsed();
1864 if (elapsed >= kWorkDurationThreshold) {
1865 name = "queue";
1866 }
1867 if (elapsed > 0s) {
1868 pendingDeadline = true;
1869 }
1870 }
1871 if (name.empty()) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001872 // We're not stuck.
1873 if (pendingDeadline) {
1874 // If we are not stuck yet but still has deadline coming up,
1875 // post watch message to check back later.
1876 (new AMessage(kWhatWatch, this))->post();
1877 }
1878 return;
1879 }
1880
1881 ALOGW("previous call to %s exceeded timeout", name.c_str());
1882 initiateRelease(false);
1883 mCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
1884}
1885
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001886// static
1887PersistentSurface *CCodec::CreateInputSurface() {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001888 using namespace android;
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001889 using ::android::hardware::media::omx::V1_0::implementation::TWGraphicBufferSource;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001890 // Attempt to create a Codec2's input surface.
Pawin Vongmasa18588322019-05-18 01:52:13 -07001891 std::shared_ptr<Codec2Client::InputSurface> inputSurface =
1892 Codec2Client::CreateInputSurface();
Lajos Molnar47118272019-01-31 16:28:04 -08001893 if (!inputSurface) {
Pawin Vongmasa18588322019-05-18 01:52:13 -07001894 if (property_get_int32("debug.stagefright.c2inputsurface", 0) == -1) {
1895 sp<IGraphicBufferProducer> gbp;
1896 sp<OmxGraphicBufferSource> gbs = new OmxGraphicBufferSource();
1897 status_t err = gbs->initCheck();
1898 if (err != OK) {
1899 ALOGE("Failed to create persistent input surface: error %d", err);
1900 return nullptr;
1901 }
1902 return new PersistentSurface(
Wonsik Kim9917d4a2019-10-24 12:56:38 -07001903 gbs->getIGraphicBufferProducer(), new TWGraphicBufferSource(gbs));
Pawin Vongmasa18588322019-05-18 01:52:13 -07001904 } else {
1905 return nullptr;
1906 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001907 }
Pawin Vongmasa18588322019-05-18 01:52:13 -07001908 return new PersistentSurface(
Lajos Molnar47118272019-01-31 16:28:04 -08001909 inputSurface->getGraphicBufferProducer(),
Pawin Vongmasa18588322019-05-18 01:52:13 -07001910 static_cast<sp<android::hidl::base::V1_0::IBase>>(
Lajos Molnar47118272019-01-31 16:28:04 -08001911 inputSurface->getHalInterface()));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001912}
1913
Wonsik Kim155d5cb2019-10-09 12:49:49 -07001914} // namespace android
1915