blob: c324949e2f02b3fb92c14012d89858c711abbf3b [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright (C) 2018 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 "CCodecConfig"
19#include <cutils/properties.h>
20#include <log/log.h>
21
22#include <C2Component.h>
Pawin Vongmasa36653902018-11-15 00:10:25 -080023#include <C2Param.h>
24#include <util/C2InterfaceHelper.h>
25
26#include <media/stagefright/MediaCodecConstants.h>
27
28#include "CCodecConfig.h"
29#include "Codec2Mapper.h"
30
31#define DRC_DEFAULT_MOBILE_REF_LEVEL 64 /* 64*-0.25dB = -16 dB below full scale for mobile conf */
32#define DRC_DEFAULT_MOBILE_DRC_CUT 127 /* maximum compression of dynamic range for mobile conf */
33#define DRC_DEFAULT_MOBILE_DRC_BOOST 127 /* maximum compression of dynamic range for mobile conf */
34#define DRC_DEFAULT_MOBILE_DRC_HEAVY 1 /* switch for heavy compression for mobile conf */
35#define DRC_DEFAULT_MOBILE_DRC_EFFECT 3 /* MPEG-D DRC effect type; 3 => Limited playback range */
Jean-Michel Trivi670b8fb2020-02-18 07:54:05 -080036#define DRC_DEFAULT_MOBILE_DRC_ALBUM 0 /* MPEG-D DRC album mode; 0 => album mode is disabled, 1 => album mode is enabled */
Jean-Michel Trivi4b936cc2020-02-17 16:29:47 -080037#define DRC_DEFAULT_MOBILE_OUTPUT_LOUDNESS -1 /* decoder output loudness; -1 => the value is unknown, otherwise dB step value (e.g. 64 for -16 dB) */
Pawin Vongmasa36653902018-11-15 00:10:25 -080038#define DRC_DEFAULT_MOBILE_ENC_LEVEL (-1) /* encoder target level; -1 => the value is unknown, otherwise dB step value (e.g. 64 for -16 dB) */
39// names of properties that can be used to override the default DRC settings
40#define PROP_DRC_OVERRIDE_REF_LEVEL "aac_drc_reference_level"
41#define PROP_DRC_OVERRIDE_CUT "aac_drc_cut"
42#define PROP_DRC_OVERRIDE_BOOST "aac_drc_boost"
43#define PROP_DRC_OVERRIDE_HEAVY "aac_drc_heavy"
44#define PROP_DRC_OVERRIDE_ENC_LEVEL "aac_drc_enc_target_level"
45#define PROP_DRC_OVERRIDE_EFFECT "ro.aac_drc_effect_type"
46
47namespace android {
48
49// CCodecConfig
50
51namespace {
52
Wonsik Kim8a6ed372019-12-03 16:05:51 -080053void C2ValueToMessageItem(const C2Value &value, AMessage::ItemData &item) {
54 int32_t int32Value;
55 uint32_t uint32Value;
56 int64_t int64Value;
57 uint64_t uint64Value;
58 float floatValue;
59 if (value.get(&int32Value)) {
60 item.set(int32Value);
61 } else if (value.get(&uint32Value) && uint32Value <= uint32_t(INT32_MAX)) {
62 // SDK does not support unsigned values
63 item.set((int32_t)uint32Value);
64 } else if (value.get(&int64Value)) {
65 item.set(int64Value);
66 } else if (value.get(&uint64Value) && uint64Value <= uint64_t(INT64_MAX)) {
67 // SDK does not support unsigned values
68 item.set((int64_t)uint64Value);
69 } else if (value.get(&floatValue)) {
70 item.set(floatValue);
71 }
72}
73
Pawin Vongmasa36653902018-11-15 00:10:25 -080074/**
75 * mapping between SDK and Codec 2.0 configurations.
76 */
77struct ConfigMapper {
78 /**
79 * Value mapper (C2Value => C2Value)
80 */
81 typedef std::function<C2Value(C2Value)> Mapper;
82
83 /// shorthand
84 typedef CCodecConfig::Domain Domain;
85
86 ConfigMapper(std::string mediaKey, C2String c2struct, C2String c2field)
87 : mDomain(Domain::ALL), mMediaKey(mediaKey), mStruct(c2struct), mField(c2field) { }
88
89 /// Limits this parameter to the given domain
90 ConfigMapper &limitTo(uint32_t domain) {
91 C2_CHECK(domain & Domain::GUARD_BIT);
92 mDomain = Domain(mDomain & domain);
93 return *this;
94 }
95
96 /// Adds SDK => Codec 2.0 mapper (should not be in the SDK format)
97 ConfigMapper &withMapper(Mapper mapper) {
98 C2_CHECK(!mMapper);
99 C2_CHECK(!mReverse);
100 mMapper = mapper;
101 return *this;
102 }
103
104 /// Adds SDK <=> Codec 2.0 value mappers
105 ConfigMapper &withMappers(Mapper mapper, Mapper reverse) {
106 C2_CHECK(!mMapper);
107 C2_CHECK(!mReverse);
108 mMapper = mapper;
109 mReverse = reverse;
110 return *this;
111 }
112
113 /// Adds SDK <=> Codec 2.0 value mappers based on C2Mapper
114 template<typename C2Type, typename SdkType=int32_t>
115 ConfigMapper &withC2Mappers() {
116 C2_CHECK(!mMapper);
117 C2_CHECK(!mReverse);
118 mMapper = [](C2Value v) -> C2Value {
119 SdkType sdkValue;
120 C2Type c2Value;
121 if (v.get(&sdkValue) && C2Mapper::map(sdkValue, &c2Value)) {
122 return c2Value;
123 }
124 return C2Value();
125 };
126 mReverse = [](C2Value v) -> C2Value {
127 SdkType sdkValue;
128 C2Type c2Value;
129 using C2ValueType=typename _c2_reduce_enum_to_underlying_type<C2Type>::type;
130 if (v.get((C2ValueType*)&c2Value) && C2Mapper::map(c2Value, &sdkValue)) {
131 return sdkValue;
132 }
133 return C2Value();
134 };
135 return *this;
136 }
137
138 /// Maps from SDK values in an AMessage to a suitable C2Value.
139 C2Value mapFromMessage(const AMessage::ItemData &item) const {
140 C2Value value;
141 int32_t int32Value;
142 int64_t int64Value;
143 float floatValue;
144 double doubleValue;
145 if (item.find(&int32Value)) {
146 value = int32Value;
147 } else if (item.find(&int64Value)) {
148 value = int64Value;
149 } else if (item.find(&floatValue)) {
150 value = floatValue;
151 } else if (item.find(&doubleValue)) {
152 value = (float)doubleValue;
153 }
154 if (value.type() != C2Value::NO_INIT && mMapper) {
155 value = mMapper(value);
156 }
157 return value;
158 }
159
160 /// Maps from a C2Value to an SDK value in an AMessage.
161 AMessage::ItemData mapToMessage(C2Value value) const {
162 AMessage::ItemData item;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800163 if (value.type() != C2Value::NO_INIT && mReverse) {
164 value = mReverse(value);
165 }
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800166 C2ValueToMessageItem(value, item);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800167 return item;
168 }
169
170 Domain domain() const { return mDomain; }
171 std::string mediaKey() const { return mMediaKey; }
172 std::string path() const { return mField.size() ? mStruct + '.' + mField : mStruct; }
173 Mapper mapper() const { return mMapper; }
174 Mapper reverse() const { return mReverse; }
175
176private:
177 Domain mDomain; ///< parameter domain (mask) containing port, kind and config domains
178 std::string mMediaKey; ///< SDK key
179 C2String mStruct; ///< Codec 2.0 struct name
180 C2String mField; ///< Codec 2.0 field name
181 Mapper mMapper; ///< optional SDK => Codec 2.0 value mapper
182 Mapper mReverse; ///< optional Codec 2.0 => SDK value mapper
183};
184
185template <typename PORT, typename STREAM>
186AString QueryMediaTypeImpl(
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800187 const std::shared_ptr<Codec2Client::Configurable> &configurable) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800188 AString mediaType;
189 std::vector<std::unique_ptr<C2Param>> queried;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800190 c2_status_t c2err = configurable->query(
Pawin Vongmasa36653902018-11-15 00:10:25 -0800191 {}, { PORT::PARAM_TYPE, STREAM::PARAM_TYPE }, C2_DONT_BLOCK, &queried);
192 if (c2err != C2_OK && queried.size() == 0) {
193 ALOGD("Query media type failed => %s", asString(c2err));
194 } else {
195 PORT *portMediaType =
196 PORT::From(queried[0].get());
197 if (portMediaType) {
198 mediaType = AString(
199 portMediaType->m.value,
200 strnlen(portMediaType->m.value, portMediaType->flexCount()));
201 } else {
202 STREAM *streamMediaType = STREAM::From(queried[0].get());
203 if (streamMediaType) {
204 mediaType = AString(
205 streamMediaType->m.value,
206 strnlen(streamMediaType->m.value, streamMediaType->flexCount()));
207 }
208 }
209 ALOGD("read media type: %s", mediaType.c_str());
210 }
211 return mediaType;
212}
213
214AString QueryMediaType(
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800215 bool input, const std::shared_ptr<Codec2Client::Configurable> &configurable) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800216 typedef C2PortMediaTypeSetting P;
217 typedef C2StreamMediaTypeSetting S;
218 if (input) {
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800219 return QueryMediaTypeImpl<P::input, S::input>(configurable);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800220 } else {
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800221 return QueryMediaTypeImpl<P::output, S::output>(configurable);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800222 }
223}
224
225} // namespace
226
227/**
228 * Set of standard parameters used by CCodec that are exposed to MediaCodec.
229 */
230struct StandardParams {
231 typedef CCodecConfig::Domain Domain;
232
233 // standard (MediaCodec) params are keyed by media format key
234 typedef std::string SdkKey;
235
236 /// used to return reference to no config mappers in getConfigMappersForSdkKey
237 static const std::vector<ConfigMapper> NO_MAPPERS;
238
239 /// Returns Codec 2.0 equivalent parameters for an SDK format key.
240 const std::vector<ConfigMapper> &getConfigMappersForSdkKey(std::string key) const {
241 auto it = mConfigMappers.find(key);
242 if (it == mConfigMappers.end()) {
Wonsik Kimbd557932019-07-02 15:51:20 -0700243 if (mComplained.count(key) == 0) {
244 ALOGD("no c2 equivalents for %s", key.c_str());
245 mComplained.insert(key);
246 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800247 return NO_MAPPERS;
248 }
249 ALOGV("found %zu eqs for %s", it->second.size(), key.c_str());
250 return it->second;
251 }
252
253 /**
254 * Adds a SDK <=> Codec 2.0 parameter mapping. Multiple Codec 2.0 parameters may map to a
255 * single SDK key, in which case they shall be ordered from least authoritative to most
256 * authoritative. When constructing SDK formats, the last mapped Codec 2.0 parameter that
257 * is supported by the component will determine the exposed value. (TODO: perhaps restrict this
258 * by domain.)
259 */
260 void add(const ConfigMapper &cm) {
261 auto it = mConfigMappers.find(cm.mediaKey());
262 ALOGV("%c%c%c%c %c%c%c %04x %9s %s => %s",
263 ((cm.domain() & Domain::IS_INPUT) ? 'I' : ' '),
264 ((cm.domain() & Domain::IS_OUTPUT) ? 'O' : ' '),
265 ((cm.domain() & Domain::IS_CODED) ? 'C' : ' '),
266 ((cm.domain() & Domain::IS_RAW) ? 'R' : ' '),
267 ((cm.domain() & Domain::IS_CONFIG) ? 'c' : ' '),
268 ((cm.domain() & Domain::IS_PARAM) ? 'p' : ' '),
269 ((cm.domain() & Domain::IS_READ) ? 'r' : ' '),
270 cm.domain(),
271 it == mConfigMappers.end() ? "adding" : "extending",
272 cm.mediaKey().c_str(), cm.path().c_str());
273 if (it == mConfigMappers.end()) {
274 std::vector<ConfigMapper> eqs = { cm };
275 mConfigMappers.emplace(cm.mediaKey(), eqs);
276 } else {
277 it->second.push_back(cm);
278 }
279 }
280
281 /**
282 * Returns all paths for a specific domain.
283 *
284 * \param any maximum domain mask. Returned parameters must match at least one of the domains
285 * in the mask.
286 * \param all minimum domain mask. Returned parameters must match all of the domains in the
287 * mask. This is restricted to the bits of the maximum mask.
288 */
289 std::vector<std::string> getPathsForDomain(
290 Domain any, Domain all = Domain::ALL) const {
291 std::vector<std::string> res;
292 for (const std::pair<std::string, std::vector<ConfigMapper>> &el : mConfigMappers) {
293 for (const ConfigMapper &cm : el.second) {
294 ALOGV("filtering %s %x %x %x %x", cm.path().c_str(), cm.domain(), any,
295 (cm.domain() & any), (cm.domain() & any & all));
296 if ((cm.domain() & any) && ((cm.domain() & any & all) == (any & all))) {
297 res.push_back(cm.path());
298 }
299 }
300 }
301 return res;
302 }
303
304 /**
305 * Returns SDK <=> Codec 2.0 mappings.
306 *
307 * TODO: replace these with better methods as this exposes the inner structure.
308 */
309 const std::map<SdkKey, std::vector<ConfigMapper>> getKeys() const {
310 return mConfigMappers;
311 }
312
313private:
314 std::map<SdkKey, std::vector<ConfigMapper>> mConfigMappers;
Wonsik Kimbd557932019-07-02 15:51:20 -0700315 mutable std::set<std::string> mComplained;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800316};
317
318const std::vector<ConfigMapper> StandardParams::NO_MAPPERS;
319
320
321CCodecConfig::CCodecConfig()
322 : mInputFormat(new AMessage),
323 mOutputFormat(new AMessage),
324 mUsingSurface(false) { }
325
326void CCodecConfig::initializeStandardParams() {
327 typedef Domain D;
328 mStandardParams = std::make_shared<StandardParams>();
329 std::function<void(const ConfigMapper &)> add =
330 [params = mStandardParams](const ConfigMapper &cm) {
331 params->add(cm);
332 };
333 std::function<void(const ConfigMapper &)> deprecated = add;
334
335 // allow int32 or float SDK values and represent them as float
336 ConfigMapper::Mapper makeFloat = [](C2Value v) -> C2Value {
337 // convert from i32 to float
338 int32_t i32Value;
339 float fpValue;
340 if (v.get(&i32Value)) {
341 return (float)i32Value;
342 } else if (v.get(&fpValue)) {
343 return fpValue;
344 }
345 return C2Value();
346 };
347
348 ConfigMapper::Mapper negate = [](C2Value v) -> C2Value {
349 int32_t value;
350 if (v.get(&value)) {
351 return -value;
352 }
353 return C2Value();
354 };
355
356 add(ConfigMapper(KEY_MIME, C2_PARAMKEY_INPUT_MEDIA_TYPE, "value")
357 .limitTo(D::INPUT & D::READ));
358 add(ConfigMapper(KEY_MIME, C2_PARAMKEY_OUTPUT_MEDIA_TYPE, "value")
359 .limitTo(D::OUTPUT & D::READ));
360
361 add(ConfigMapper(KEY_BIT_RATE, C2_PARAMKEY_BITRATE, "value")
362 .limitTo(D::ENCODER & D::OUTPUT));
363 // we also need to put the bitrate in the max bitrate field
364 add(ConfigMapper(KEY_MAX_BIT_RATE, C2_PARAMKEY_BITRATE, "value")
365 .limitTo(D::ENCODER & D::READ & D::OUTPUT));
366 add(ConfigMapper(PARAMETER_KEY_VIDEO_BITRATE, C2_PARAMKEY_BITRATE, "value")
367 .limitTo(D::ENCODER & D::VIDEO & D::PARAM));
368 add(ConfigMapper(KEY_BITRATE_MODE, C2_PARAMKEY_BITRATE_MODE, "value")
369 .limitTo(D::ENCODER & D::CODED)
Harish Mahendrakar71cbb9d2019-05-21 11:21:27 -0700370 .withC2Mappers<C2Config::bitrate_mode_t>());
Pawin Vongmasa36653902018-11-15 00:10:25 -0800371 // remove when codecs switch to PARAMKEY and new modes
372 deprecated(ConfigMapper(KEY_BITRATE_MODE, "coded.bitrate-mode", "value")
373 .limitTo(D::ENCODER));
374 add(ConfigMapper(KEY_FRAME_RATE, C2_PARAMKEY_FRAME_RATE, "value")
375 .limitTo(D::VIDEO)
376 .withMappers(makeFloat, [](C2Value v) -> C2Value {
377 // read back always as int
378 float value;
379 if (v.get(&value)) {
380 return (int32_t)value;
381 }
382 return C2Value();
383 }));
384
385 add(ConfigMapper(KEY_MAX_INPUT_SIZE, C2_PARAMKEY_INPUT_MAX_BUFFER_SIZE, "value")
386 .limitTo(D::INPUT));
387 // remove when codecs switch to PARAMKEY
388 deprecated(ConfigMapper(KEY_MAX_INPUT_SIZE, "coded.max-frame-size", "value")
389 .limitTo(D::INPUT));
390
391 // Rotation
392 // Note: SDK rotation is clock-wise, while C2 rotation is counter-clock-wise
393 add(ConfigMapper(KEY_ROTATION, C2_PARAMKEY_VUI_ROTATION, "value")
394 .limitTo(D::VIDEO & D::CODED)
395 .withMappers(negate, negate));
396 add(ConfigMapper(KEY_ROTATION, C2_PARAMKEY_ROTATION, "value")
397 .limitTo(D::VIDEO & D::RAW)
398 .withMappers(negate, negate));
399
400 // android 'video-scaling'
401 add(ConfigMapper("android._video-scaling", C2_PARAMKEY_SURFACE_SCALING_MODE, "value")
402 .limitTo(D::VIDEO & D::DECODER & D::RAW));
403
404 // Color Aspects
405 //
406 // configure default for decoders
407 add(ConfigMapper(KEY_COLOR_RANGE, C2_PARAMKEY_DEFAULT_COLOR_ASPECTS, "range")
408 .limitTo((D::VIDEO | D::IMAGE) & D::DECODER & D::CODED & (D::CONFIG | D::PARAM))
409 .withC2Mappers<C2Color::range_t>());
410 add(ConfigMapper(KEY_COLOR_TRANSFER, C2_PARAMKEY_DEFAULT_COLOR_ASPECTS, "transfer")
411 .limitTo((D::VIDEO | D::IMAGE) & D::DECODER & D::CODED & (D::CONFIG | D::PARAM))
412 .withC2Mappers<C2Color::transfer_t>());
413 add(ConfigMapper("color-primaries", C2_PARAMKEY_DEFAULT_COLOR_ASPECTS, "primaries")
414 .limitTo((D::VIDEO | D::IMAGE) & D::DECODER & D::CODED & (D::CONFIG | D::PARAM)));
415 add(ConfigMapper("color-matrix", C2_PARAMKEY_DEFAULT_COLOR_ASPECTS, "matrix")
416 .limitTo((D::VIDEO | D::IMAGE) & D::DECODER & D::CODED & (D::CONFIG | D::PARAM)));
417
418 // read back final for decoder output (also, configure final aspects as well. This should be
419 // overwritten based on coded/default values if component supports color aspects, but is used
420 // as final values if component does not support aspects at all)
421 add(ConfigMapper(KEY_COLOR_RANGE, C2_PARAMKEY_COLOR_ASPECTS, "range")
422 .limitTo((D::VIDEO | D::IMAGE) & D::DECODER & D::RAW)
423 .withC2Mappers<C2Color::range_t>());
424 add(ConfigMapper(KEY_COLOR_TRANSFER, C2_PARAMKEY_COLOR_ASPECTS, "transfer")
425 .limitTo((D::VIDEO | D::IMAGE) & D::DECODER & D::RAW)
426 .withC2Mappers<C2Color::transfer_t>());
427 add(ConfigMapper("color-primaries", C2_PARAMKEY_COLOR_ASPECTS, "primaries")
428 .limitTo((D::VIDEO | D::IMAGE) & D::DECODER & D::RAW));
429 add(ConfigMapper("color-matrix", C2_PARAMKEY_COLOR_ASPECTS, "matrix")
430 .limitTo((D::VIDEO | D::IMAGE) & D::DECODER & D::RAW));
431
432 // configure source aspects for encoders and read them back on the coded(!) port.
433 // This is to ensure muxing the desired aspects into the container.
434 add(ConfigMapper(KEY_COLOR_RANGE, C2_PARAMKEY_COLOR_ASPECTS, "range")
435 .limitTo((D::VIDEO | D::IMAGE) & D::ENCODER & D::CODED)
436 .withC2Mappers<C2Color::range_t>());
437 add(ConfigMapper(KEY_COLOR_TRANSFER, C2_PARAMKEY_COLOR_ASPECTS, "transfer")
438 .limitTo((D::VIDEO | D::IMAGE) & D::ENCODER & D::CODED)
439 .withC2Mappers<C2Color::transfer_t>());
440 add(ConfigMapper("color-primaries", C2_PARAMKEY_COLOR_ASPECTS, "primaries")
441 .limitTo((D::VIDEO | D::IMAGE) & D::ENCODER & D::CODED));
442 add(ConfigMapper("color-matrix", C2_PARAMKEY_COLOR_ASPECTS, "matrix")
443 .limitTo((D::VIDEO | D::IMAGE) & D::ENCODER & D::CODED));
444
445 // read back coded aspects for encoders (on the raw port), but also configure
446 // desired aspects here.
447 add(ConfigMapper(KEY_COLOR_RANGE, C2_PARAMKEY_VUI_COLOR_ASPECTS, "range")
448 .limitTo((D::VIDEO | D::IMAGE) & D::ENCODER & D::RAW)
449 .withC2Mappers<C2Color::range_t>());
450 add(ConfigMapper(KEY_COLOR_TRANSFER, C2_PARAMKEY_VUI_COLOR_ASPECTS, "transfer")
451 .limitTo((D::VIDEO | D::IMAGE) & D::ENCODER & D::RAW)
452 .withC2Mappers<C2Color::transfer_t>());
453 add(ConfigMapper("color-primaries", C2_PARAMKEY_VUI_COLOR_ASPECTS, "primaries")
454 .limitTo((D::VIDEO | D::IMAGE) & D::ENCODER & D::RAW));
455 add(ConfigMapper("color-matrix", C2_PARAMKEY_VUI_COLOR_ASPECTS, "matrix")
456 .limitTo((D::VIDEO | D::IMAGE) & D::ENCODER & D::RAW));
457
458 // Dataspace
459 add(ConfigMapper("android._dataspace", C2_PARAMKEY_DATA_SPACE, "value")
460 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
461
462 // HDR
463 add(ConfigMapper("smpte2086.red.x", C2_PARAMKEY_HDR_STATIC_INFO, "mastering.red.x")
464 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
465 add(ConfigMapper("smpte2086.red.y", C2_PARAMKEY_HDR_STATIC_INFO, "mastering.red.y")
466 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
467 add(ConfigMapper("smpte2086.green.x", C2_PARAMKEY_HDR_STATIC_INFO, "mastering.green.x")
468 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
469 add(ConfigMapper("smpte2086.green.y", C2_PARAMKEY_HDR_STATIC_INFO, "mastering.green.y")
470 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
471 add(ConfigMapper("smpte2086.blue.x", C2_PARAMKEY_HDR_STATIC_INFO, "mastering.blue.x")
472 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
473 add(ConfigMapper("smpte2086.blue.y", C2_PARAMKEY_HDR_STATIC_INFO, "mastering.blue.y")
474 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
475 add(ConfigMapper("smpte2086.white.x", C2_PARAMKEY_HDR_STATIC_INFO, "mastering.white.x")
476 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
477 add(ConfigMapper("smpte2086.white.y", C2_PARAMKEY_HDR_STATIC_INFO, "mastering.white.y")
478 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
479 add(ConfigMapper("smpte2086.max-luminance", C2_PARAMKEY_HDR_STATIC_INFO, "mastering.max-luminance")
480 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
481 add(ConfigMapper("smpte2086.min-luminance", C2_PARAMKEY_HDR_STATIC_INFO, "mastering.min-luminance")
482 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
483 add(ConfigMapper("cta861.max-cll", C2_PARAMKEY_HDR_STATIC_INFO, "max-cll")
484 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
485 add(ConfigMapper("cta861.max-fall", C2_PARAMKEY_HDR_STATIC_INFO, "max-fall")
486 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
487
488 add(ConfigMapper(std::string(KEY_FEATURE_) + FEATURE_SecurePlayback,
489 C2_PARAMKEY_SECURE_MODE, "value"));
490
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700491 add(ConfigMapper(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800492 C2_PARAMKEY_PREPEND_HEADER_MODE, "value")
493 .limitTo(D::ENCODER & D::VIDEO)
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700494 .withMappers([](C2Value v) -> C2Value {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800495 int32_t value;
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700496 if (v.get(&value)) {
497 return value ? C2Value(C2Config::PREPEND_HEADER_TO_ALL_SYNC)
498 : C2Value(C2Config::PREPEND_HEADER_TO_NONE);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800499 }
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700500 return C2Value();
501 }, [](C2Value v) -> C2Value {
502 C2Config::prepend_header_mode_t value;
503 using C2ValueType=typename _c2_reduce_enum_to_underlying_type<decltype(value)>::type;
504 if (v.get((C2ValueType *)&value)) {
505 switch (value) {
506 case C2Config::PREPEND_HEADER_TO_NONE: return 0;
507 case C2Config::PREPEND_HEADER_TO_ALL_SYNC: return 1;
508 case C2Config::PREPEND_HEADER_ON_CHANGE: [[fallthrough]];
509 default: return C2Value();
510 }
511 }
512 return C2Value();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800513 }));
514 // remove when codecs switch to PARAMKEY
Wonsik Kim9ca01d32019-04-01 14:45:47 -0700515 deprecated(ConfigMapper(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800516 "coding.add-csd-to-sync-frames", "value")
517 .limitTo(D::ENCODER & D::VIDEO));
518 // convert to timestamp base
519 add(ConfigMapper(KEY_I_FRAME_INTERVAL, C2_PARAMKEY_SYNC_FRAME_INTERVAL, "value")
Wonsik Kimec588002019-07-11 13:43:38 -0700520 .limitTo(D::VIDEO & D::ENCODER & D::CONFIG)
521 .withMapper([](C2Value v) -> C2Value {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800522 // convert from i32 to float
523 int32_t i32Value;
524 float fpValue;
525 if (v.get(&i32Value)) {
526 return int64_t(1000000) * i32Value;
527 } else if (v.get(&fpValue)) {
528 return int64_t(c2_min(1000000 * fpValue + 0.5, (double)INT64_MAX));
529 }
530 return C2Value();
531 }));
532 // remove when codecs switch to proper coding.gop (add support for calculating gop)
533 deprecated(ConfigMapper("i-frame-period", "coding.gop", "intra-period")
534 .limitTo(D::ENCODER & D::VIDEO));
535 add(ConfigMapper(KEY_INTRA_REFRESH_PERIOD, C2_PARAMKEY_INTRA_REFRESH, "period")
536 .limitTo(D::VIDEO & D::ENCODER)
537 .withMappers(makeFloat, [](C2Value v) -> C2Value {
538 // read back always as int
539 float value;
540 if (v.get(&value)) {
541 return (int32_t)value;
542 }
543 return C2Value();
544 }));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800545 deprecated(ConfigMapper(PARAMETER_KEY_REQUEST_SYNC_FRAME,
546 "coding.request-sync", "value")
547 .limitTo(D::PARAM & D::ENCODER)
548 .withMapper([](C2Value) -> C2Value { return uint32_t(1); }));
549 add(ConfigMapper(PARAMETER_KEY_REQUEST_SYNC_FRAME,
550 C2_PARAMKEY_REQUEST_SYNC_FRAME, "value")
551 .limitTo(D::PARAM & D::ENCODER)
552 .withMapper([](C2Value) -> C2Value { return uint32_t(1); }));
553
554 add(ConfigMapper(KEY_OPERATING_RATE, C2_PARAMKEY_OPERATING_RATE, "value")
555 .limitTo(D::PARAM | D::CONFIG) // write-only
556 .withMapper(makeFloat));
557 // C2 priorities are inverted
558 add(ConfigMapper(KEY_PRIORITY, C2_PARAMKEY_PRIORITY, "value")
559 .withMappers(negate, negate));
560 // remove when codecs switch to PARAMKEY
561 deprecated(ConfigMapper(KEY_OPERATING_RATE, "ctrl.operating-rate", "value")
562 .withMapper(makeFloat));
563 deprecated(ConfigMapper(KEY_PRIORITY, "ctrl.priority", "value"));
564
565 add(ConfigMapper(KEY_WIDTH, C2_PARAMKEY_PICTURE_SIZE, "width")
566 .limitTo(D::VIDEO | D::IMAGE));
567 add(ConfigMapper(KEY_HEIGHT, C2_PARAMKEY_PICTURE_SIZE, "height")
568 .limitTo(D::VIDEO | D::IMAGE));
569
570 add(ConfigMapper("crop-left", C2_PARAMKEY_CROP_RECT, "left")
571 .limitTo(D::VIDEO | D::IMAGE));
572 add(ConfigMapper("crop-top", C2_PARAMKEY_CROP_RECT, "top")
573 .limitTo(D::VIDEO | D::IMAGE));
574 add(ConfigMapper("crop-width", C2_PARAMKEY_CROP_RECT, "width")
575 .limitTo(D::VIDEO | D::IMAGE));
576 add(ConfigMapper("crop-height", C2_PARAMKEY_CROP_RECT, "height")
577 .limitTo(D::VIDEO | D::IMAGE));
578
579 add(ConfigMapper(KEY_MAX_WIDTH, C2_PARAMKEY_MAX_PICTURE_SIZE, "width")
580 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
581 add(ConfigMapper(KEY_MAX_HEIGHT, C2_PARAMKEY_MAX_PICTURE_SIZE, "height")
582 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
583
584 add(ConfigMapper("csd-0", C2_PARAMKEY_INIT_DATA, "value")
585 .limitTo(D::OUTPUT & D::READ));
586
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800587 add(ConfigMapper(KEY_HDR10_PLUS_INFO, C2_PARAMKEY_INPUT_HDR10_PLUS_INFO, "value")
588 .limitTo(D::VIDEO & D::PARAM & D::INPUT));
589
590 add(ConfigMapper(KEY_HDR10_PLUS_INFO, C2_PARAMKEY_OUTPUT_HDR10_PLUS_INFO, "value")
591 .limitTo(D::VIDEO & D::OUTPUT));
592
Pawin Vongmasa36653902018-11-15 00:10:25 -0800593 add(ConfigMapper(C2_PARAMKEY_TEMPORAL_LAYERING, C2_PARAMKEY_TEMPORAL_LAYERING, "")
594 .limitTo(D::ENCODER & D::VIDEO & D::OUTPUT));
595
596 // Pixel Format (use local key for actual pixel format as we don't distinguish between
597 // SDK layouts for flexible format and we need the actual SDK color format in the media format)
598 add(ConfigMapper("android._color-format", C2_PARAMKEY_PIXEL_FORMAT, "value")
599 .limitTo((D::VIDEO | D::IMAGE) & D::RAW)
600 .withMappers([](C2Value v) -> C2Value {
601 int32_t value;
602 if (v.get(&value)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800603 uint32_t result;
604 if (C2Mapper::mapPixelFormatFrameworkToCodec(value, &result)) {
605 return result;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800606 }
607 }
608 return C2Value();
609 }, [](C2Value v) -> C2Value {
610 uint32_t value;
611 if (v.get(&value)) {
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800612 int32_t result;
613 if (C2Mapper::mapPixelFormatCodecToFramework(value, &result)) {
614 return result;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800615 }
616 }
617 return C2Value();
618 }));
619
Wonsik Kim79c78eb2020-04-23 14:13:37 -0700620 add(ConfigMapper(KEY_PIXEL_ASPECT_RATIO_WIDTH, C2_PARAMKEY_PIXEL_ASPECT_RATIO, "width")
621 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
622 add(ConfigMapper(KEY_PIXEL_ASPECT_RATIO_HEIGHT, C2_PARAMKEY_PIXEL_ASPECT_RATIO, "height")
623 .limitTo((D::VIDEO | D::IMAGE) & D::RAW));
624
Pawin Vongmasa36653902018-11-15 00:10:25 -0800625 add(ConfigMapper(KEY_CHANNEL_COUNT, C2_PARAMKEY_CHANNEL_COUNT, "value")
626 .limitTo(D::AUDIO)); // read back to both formats
627 add(ConfigMapper(KEY_CHANNEL_COUNT, C2_PARAMKEY_CODED_CHANNEL_COUNT, "value")
628 .limitTo(D::AUDIO & D::CODED));
629
630 add(ConfigMapper(KEY_SAMPLE_RATE, C2_PARAMKEY_SAMPLE_RATE, "value")
631 .limitTo(D::AUDIO)); // read back to both port formats
632 add(ConfigMapper(KEY_SAMPLE_RATE, C2_PARAMKEY_CODED_SAMPLE_RATE, "value")
633 .limitTo(D::AUDIO & D::CODED));
634
635 add(ConfigMapper(KEY_PCM_ENCODING, C2_PARAMKEY_PCM_ENCODING, "value")
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800636 .limitTo(D::AUDIO)
637 .withMappers([](C2Value v) -> C2Value {
638 int32_t value;
639 C2Config::pcm_encoding_t to;
640 if (v.get(&value) && C2Mapper::map(value, &to)) {
641 return to;
642 }
643 return C2Value();
644 }, [](C2Value v) -> C2Value {
645 C2Config::pcm_encoding_t value;
646 int32_t to;
647 using C2ValueType=typename _c2_reduce_enum_to_underlying_type<decltype(value)>::type;
648 if (v.get((C2ValueType*)&value) && C2Mapper::map(value, &to)) {
649 return to;
650 }
651 return C2Value();
652 }));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800653
654 add(ConfigMapper(KEY_IS_ADTS, C2_PARAMKEY_AAC_PACKAGING, "value")
655 .limitTo(D::AUDIO & D::CODED)
656 .withMappers([](C2Value v) -> C2Value {
657 int32_t value;
658 if (v.get(&value) && value) {
659 return C2Config::AAC_PACKAGING_ADTS;
660 }
661 return C2Value();
662 }, [](C2Value v) -> C2Value {
663 uint32_t value;
664 if (v.get(&value) && value == C2Config::AAC_PACKAGING_ADTS) {
665 return (int32_t)1;
666 }
667 return C2Value();
668 }));
669
670 std::shared_ptr<C2Mapper::ProfileLevelMapper> mapper =
671 C2Mapper::GetProfileLevelMapper(mCodingMediaType);
672
673 add(ConfigMapper(KEY_PROFILE, C2_PARAMKEY_PROFILE_LEVEL, "profile")
674 .limitTo(D::CODED)
675 .withMappers([mapper](C2Value v) -> C2Value {
676 C2Config::profile_t c2 = PROFILE_UNUSED;
677 int32_t sdk;
678 if (mapper && v.get(&sdk) && mapper->mapProfile(sdk, &c2)) {
679 return c2;
680 }
681 return PROFILE_UNUSED;
682 }, [mapper](C2Value v) -> C2Value {
683 C2Config::profile_t c2;
684 int32_t sdk;
685 using C2ValueType=typename _c2_reduce_enum_to_underlying_type<decltype(c2)>::type;
686 if (mapper && v.get((C2ValueType*)&c2) && mapper->mapProfile(c2, &sdk)) {
687 return sdk;
688 }
689 return C2Value();
690 }));
691
692 add(ConfigMapper(KEY_LEVEL, C2_PARAMKEY_PROFILE_LEVEL, "level")
693 .limitTo(D::CODED)
694 .withMappers([mapper](C2Value v) -> C2Value {
695 C2Config::level_t c2 = LEVEL_UNUSED;
696 int32_t sdk;
697 if (mapper && v.get(&sdk) && mapper->mapLevel(sdk, &c2)) {
698 return c2;
699 }
700 return LEVEL_UNUSED;
701 }, [mapper](C2Value v) -> C2Value {
702 C2Config::level_t c2;
703 int32_t sdk;
704 using C2ValueType=typename _c2_reduce_enum_to_underlying_type<decltype(c2)>::type;
705 if (mapper && v.get((C2ValueType*)&c2) && mapper->mapLevel(c2, &sdk)) {
706 return sdk;
707 }
708 return C2Value();
709 }));
710
711 // convert to dBFS and add default
712 add(ConfigMapper(KEY_AAC_DRC_TARGET_REFERENCE_LEVEL, C2_PARAMKEY_DRC_TARGET_REFERENCE_LEVEL, "value")
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800713 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
714 .withMappers([](C2Value v) -> C2Value {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800715 int32_t value;
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800716 if (!v.get(&value) || value < -1) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800717 value = property_get_int32(PROP_DRC_OVERRIDE_REF_LEVEL, DRC_DEFAULT_MOBILE_REF_LEVEL);
718 }
719 return float(-0.25 * c2_min(value, 127));
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800720 },[](C2Value v) -> C2Value {
721 float value;
722 if (v.get(&value)) {
723 return (int32_t) (-4. * value);
724 }
725 return C2Value();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800726 }));
727
728 // convert to 0-1 (%) and add default
729 add(ConfigMapper(KEY_AAC_DRC_ATTENUATION_FACTOR, C2_PARAMKEY_DRC_ATTENUATION_FACTOR, "value")
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800730 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
731 .withMappers([](C2Value v) -> C2Value {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800732 int32_t value;
733 if (!v.get(&value) || value < 0) {
734 value = property_get_int32(PROP_DRC_OVERRIDE_CUT, DRC_DEFAULT_MOBILE_DRC_CUT);
735 }
736 return float(c2_min(value, 127) / 127.);
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800737 },[](C2Value v) -> C2Value {
738 float value;
739 if (v.get(&value)) {
740 return (int32_t) (value * 127. + 0.5);
741 }
742 else {
743 return C2Value();
744 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800745 }));
746
747 // convert to 0-1 (%) and add default
748 add(ConfigMapper(KEY_AAC_DRC_BOOST_FACTOR, C2_PARAMKEY_DRC_BOOST_FACTOR, "value")
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800749 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
750 .withMappers([](C2Value v) -> C2Value {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800751 int32_t value;
752 if (!v.get(&value) || value < 0) {
753 value = property_get_int32(PROP_DRC_OVERRIDE_BOOST, DRC_DEFAULT_MOBILE_DRC_BOOST);
754 }
755 return float(c2_min(value, 127) / 127.);
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800756 },[](C2Value v) -> C2Value {
757 float value;
758 if (v.get(&value)) {
759 return (int32_t) (value * 127. + 0.5);
760 }
761 else {
762 return C2Value();
763 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800764 }));
765
766 // convert to compression type and add default
767 add(ConfigMapper(KEY_AAC_DRC_HEAVY_COMPRESSION, C2_PARAMKEY_DRC_COMPRESSION_MODE, "value")
Wonsik Kim30c1d422020-10-27 17:00:36 -0700768 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM))
769 .withMapper([](C2Value v) -> C2Value {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800770 int32_t value;
771 if (!v.get(&value) || value < 0) {
772 value = property_get_int32(PROP_DRC_OVERRIDE_HEAVY, DRC_DEFAULT_MOBILE_DRC_HEAVY);
773 }
774 return value == 1 ? C2Config::DRC_COMPRESSION_HEAVY : C2Config::DRC_COMPRESSION_LIGHT;
775 }));
776
777 // convert to dBFS and add default
778 add(ConfigMapper(KEY_AAC_ENCODED_TARGET_LEVEL, C2_PARAMKEY_DRC_ENCODED_TARGET_LEVEL, "value")
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800779 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
780 .withMappers([](C2Value v) -> C2Value {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800781 int32_t value;
782 if (!v.get(&value) || value < 0) {
783 value = property_get_int32(PROP_DRC_OVERRIDE_ENC_LEVEL, DRC_DEFAULT_MOBILE_ENC_LEVEL);
784 }
785 return float(-0.25 * c2_min(value, 127));
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800786 },[](C2Value v) -> C2Value {
787 float value;
788 if (v.get(&value)) {
789 return (int32_t) (-4. * value);
790 }
791 else {
792 return C2Value();
793 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800794 }));
795
796 // convert to effect type (these map to SDK values) and add default
797 add(ConfigMapper(KEY_AAC_DRC_EFFECT_TYPE, C2_PARAMKEY_DRC_EFFECT_TYPE, "value")
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800798 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
799 .withMappers([](C2Value v) -> C2Value {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800800 int32_t value;
801 if (!v.get(&value) || value < -1 || value > 8) {
802 value = property_get_int32(PROP_DRC_OVERRIDE_EFFECT, DRC_DEFAULT_MOBILE_DRC_EFFECT);
803 // ensure value is within range
804 if (value < -1 || value > 8) {
805 value = DRC_DEFAULT_MOBILE_DRC_EFFECT;
806 }
807 }
808 return value;
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800809 },[](C2Value v) -> C2Value {
810 int32_t value;
811 if (v.get(&value)) {
812 return value;
813 }
814 else {
815 return C2Value();
816 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800817 }));
818
Jean-Michel Trivi670b8fb2020-02-18 07:54:05 -0800819 // convert to album mode and add default
820 add(ConfigMapper(KEY_AAC_DRC_ALBUM_MODE, C2_PARAMKEY_DRC_ALBUM_MODE, "value")
821 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
822 .withMappers([](C2Value v) -> C2Value {
823 int32_t value;
824 if (!v.get(&value) || value < 0 || value > 1) {
825 value = DRC_DEFAULT_MOBILE_DRC_ALBUM;
826 // ensure value is within range
827 if (value < 0 || value > 1) {
828 value = DRC_DEFAULT_MOBILE_DRC_ALBUM;
829 }
830 }
831 return value;
832 },[](C2Value v) -> C2Value {
833 int32_t value;
834 if (v.get(&value)) {
835 return value;
836 }
837 else {
838 return C2Value();
839 }
840 }));
841
Jean-Michel Trivi4b936cc2020-02-17 16:29:47 -0800842 add(ConfigMapper(KEY_AAC_DRC_OUTPUT_LOUDNESS, C2_PARAMKEY_DRC_OUTPUT_LOUDNESS, "value")
843 .limitTo(D::OUTPUT & D::DECODER & D::READ)
844 .withMappers([](C2Value v) -> C2Value {
845 int32_t value;
846 if (!v.get(&value) || value < -1) {
847 value = DRC_DEFAULT_MOBILE_OUTPUT_LOUDNESS;
848 }
849 return float(-0.25 * c2_min(value, 127));
850 },[](C2Value v) -> C2Value {
851 float value;
852 if (v.get(&value)) {
853 return (int32_t) (-4. * value);
854 }
855 return C2Value();
856 }));
857
Pawin Vongmasa36653902018-11-15 00:10:25 -0800858 add(ConfigMapper(KEY_AAC_MAX_OUTPUT_CHANNEL_COUNT, C2_PARAMKEY_MAX_CHANNEL_COUNT, "value")
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800859 .limitTo(D::AUDIO & (D::CONFIG | D::PARAM | D::READ)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800860
861 add(ConfigMapper(KEY_AAC_SBR_MODE, C2_PARAMKEY_AAC_SBR_MODE, "value")
Jean-Michel Triviedf942b2020-01-29 09:59:44 -0800862 .limitTo(D::AUDIO & D::ENCODER & (D::CONFIG | D::PARAM | D::READ))
Pawin Vongmasa36653902018-11-15 00:10:25 -0800863 .withMapper([](C2Value v) -> C2Value {
864 int32_t value;
865 if (!v.get(&value) || value < 0) {
866 return C2Config::AAC_SBR_AUTO;
867 }
868 switch (value) {
869 case 0: return C2Config::AAC_SBR_OFF;
870 case 1: return C2Config::AAC_SBR_SINGLE_RATE;
871 case 2: return C2Config::AAC_SBR_DUAL_RATE;
872 default: return C2Config::AAC_SBR_AUTO + 1; // invalid value
873 }
874 }));
875
Harish Mahendrakar9a4c8eb2019-05-29 15:41:20 -0700876 add(ConfigMapper(KEY_QUALITY, C2_PARAMKEY_QUALITY, "value")
877 .limitTo(D::ENCODER & (D::CONFIG | D::PARAM)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800878 add(ConfigMapper(KEY_FLAC_COMPRESSION_LEVEL, C2_PARAMKEY_COMPLEXITY, "value")
879 .limitTo(D::AUDIO & D::ENCODER));
880 add(ConfigMapper("complexity", C2_PARAMKEY_COMPLEXITY, "value")
Harish Mahendrakar9a4c8eb2019-05-29 15:41:20 -0700881 .limitTo(D::ENCODER & (D::CONFIG | D::PARAM)));
Pawin Vongmasa36653902018-11-15 00:10:25 -0800882
883 add(ConfigMapper(KEY_GRID_COLUMNS, C2_PARAMKEY_TILE_LAYOUT, "columns")
884 .limitTo(D::IMAGE));
885 add(ConfigMapper(KEY_GRID_ROWS, C2_PARAMKEY_TILE_LAYOUT, "rows")
886 .limitTo(D::IMAGE));
887 add(ConfigMapper(KEY_TILE_WIDTH, C2_PARAMKEY_TILE_LAYOUT, "tile.width")
888 .limitTo(D::IMAGE));
889 add(ConfigMapper(KEY_TILE_HEIGHT, C2_PARAMKEY_TILE_LAYOUT, "tile.height")
890 .limitTo(D::IMAGE));
891
892 add(ConfigMapper(KEY_LATENCY, C2_PARAMKEY_PIPELINE_DELAY_REQUEST, "value")
893 .limitTo(D::VIDEO & D::ENCODER));
894
895 add(ConfigMapper(C2_PARAMKEY_INPUT_TIME_STRETCH, C2_PARAMKEY_INPUT_TIME_STRETCH, "value"));
896
Wei Jia48ab6ef2019-10-11 16:06:42 -0700897 add(ConfigMapper(KEY_LOW_LATENCY, C2_PARAMKEY_LOW_LATENCY_MODE, "value")
898 .limitTo(D::DECODER & (D::CONFIG | D::PARAM))
899 .withMapper([](C2Value v) -> C2Value {
900 int32_t value = 0;
901 (void)v.get(&value);
902 return value == 0 ? C2_FALSE : C2_TRUE;
903 }));
904
Pawin Vongmasa36653902018-11-15 00:10:25 -0800905 /* still to do
906 constexpr char KEY_PUSH_BLANK_BUFFERS_ON_STOP[] = "push-blank-buffers-on-shutdown";
907
908 not yet used by MediaCodec, but defined as MediaFormat
909 KEY_AUDIO_SESSION_ID // we use "audio-hw-sync"
910 KEY_OUTPUT_REORDER_DEPTH
911 */
912}
913
914status_t CCodecConfig::initialize(
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800915 const std::shared_ptr<C2ParamReflector> &reflector,
916 const std::shared_ptr<Codec2Client::Configurable> &configurable) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800917 C2ComponentDomainSetting domain(C2Component::DOMAIN_OTHER);
918 C2ComponentKindSetting kind(C2Component::KIND_OTHER);
919
920 std::vector<std::unique_ptr<C2Param>> queried;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800921 c2_status_t c2err = configurable->query({ &domain, &kind }, {}, C2_DONT_BLOCK, &queried);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800922 if (c2err != C2_OK) {
923 ALOGD("Query domain & kind failed => %s", asString(c2err));
924 // TEMP: determine kind from component name
925 if (kind.value == C2Component::KIND_OTHER) {
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800926 if (configurable->getName().find("encoder") != std::string::npos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800927 kind.value = C2Component::KIND_ENCODER;
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800928 } else if (configurable->getName().find("decoder") != std::string::npos) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800929 kind.value = C2Component::KIND_DECODER;
930 }
931 }
932
933 // TEMP: determine domain from media type (port (preferred) or stream #0)
934 if (domain.value == C2Component::DOMAIN_OTHER) {
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800935 AString mediaType = QueryMediaType(true /* input */, configurable);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800936 if (mediaType.startsWith("audio/")) {
937 domain.value = C2Component::DOMAIN_AUDIO;
938 } else if (mediaType.startsWith("video/")) {
939 domain.value = C2Component::DOMAIN_VIDEO;
940 } else if (mediaType.startsWith("image/")) {
941 domain.value = C2Component::DOMAIN_IMAGE;
942 }
943 }
944 }
945
946 mDomain = (domain.value == C2Component::DOMAIN_VIDEO ? Domain::IS_VIDEO :
947 domain.value == C2Component::DOMAIN_IMAGE ? Domain::IS_IMAGE :
948 domain.value == C2Component::DOMAIN_AUDIO ? Domain::IS_AUDIO : Domain::OTHER_DOMAIN)
949 | (kind.value == C2Component::KIND_DECODER ? Domain::IS_DECODER :
950 kind.value == C2Component::KIND_ENCODER ? Domain::IS_ENCODER : Domain::OTHER_KIND);
951
952 mInputDomain = Domain(((mDomain & IS_DECODER) ? IS_CODED : IS_RAW) | IS_INPUT);
953 mOutputDomain = Domain(((mDomain & IS_ENCODER) ? IS_CODED : IS_RAW) | IS_OUTPUT);
954
955 ALOGV("domain is %#x (%u %u)", mDomain, domain.value, kind.value);
956
957 std::vector<C2Param::Index> paramIndices;
958 switch (kind.value) {
959 case C2Component::KIND_DECODER:
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800960 mCodingMediaType = QueryMediaType(true /* input */, configurable).c_str();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800961 break;
962 case C2Component::KIND_ENCODER:
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800963 mCodingMediaType = QueryMediaType(false /* input */, configurable).c_str();
Pawin Vongmasa36653902018-11-15 00:10:25 -0800964 break;
965 default:
966 mCodingMediaType = "";
967 }
968
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800969 c2err = configurable->querySupportedParams(&mParamDescs);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800970 if (c2err != C2_OK) {
971 ALOGD("Query supported params failed after returning %zu values => %s",
972 mParamDescs.size(), asString(c2err));
973 return UNKNOWN_ERROR;
974 }
975 for (const std::shared_ptr<C2ParamDescriptor> &desc : mParamDescs) {
976 mSupportedIndices.emplace(desc->index());
977 }
978
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800979 mReflector = reflector;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800980 if (mReflector == nullptr) {
Wonsik Kim8a6ed372019-12-03 16:05:51 -0800981 ALOGE("Null param reflector");
Pawin Vongmasa36653902018-11-15 00:10:25 -0800982 return UNKNOWN_ERROR;
983 }
984
985 // enumerate all fields
986 mParamUpdater = std::make_shared<ReflectedParamUpdater>();
987 mParamUpdater->clear();
988 mParamUpdater->supportWholeParam(
989 C2_PARAMKEY_TEMPORAL_LAYERING, C2StreamTemporalLayeringTuning::CORE_INDEX);
990 mParamUpdater->addParamDesc(mReflector, mParamDescs);
991
992 // TEMP: add some standard fields even if not reflected
993 if (kind.value == C2Component::KIND_ENCODER) {
994 mParamUpdater->addStandardParam<C2StreamInitDataInfo::output>(C2_PARAMKEY_INIT_DATA);
995 }
996 if (domain.value == C2Component::DOMAIN_IMAGE || domain.value == C2Component::DOMAIN_VIDEO) {
997 if (kind.value != C2Component::KIND_ENCODER) {
998 addLocalParam<C2StreamPictureSizeInfo::output>(C2_PARAMKEY_PICTURE_SIZE);
999 addLocalParam<C2StreamCropRectInfo::output>(C2_PARAMKEY_CROP_RECT);
1000 addLocalParam(
1001 new C2StreamPixelAspectRatioInfo::output(0u, 1u, 1u),
1002 C2_PARAMKEY_PIXEL_ASPECT_RATIO);
1003 addLocalParam(new C2StreamRotationInfo::output(0u, 0), C2_PARAMKEY_ROTATION);
1004 addLocalParam(new C2StreamColorAspectsInfo::output(0u), C2_PARAMKEY_COLOR_ASPECTS);
1005 addLocalParam<C2StreamDataSpaceInfo::output>(C2_PARAMKEY_DATA_SPACE);
1006 addLocalParam<C2StreamHdrStaticInfo::output>(C2_PARAMKEY_HDR_STATIC_INFO);
1007 addLocalParam(new C2StreamSurfaceScalingInfo::output(0u, VIDEO_SCALING_MODE_SCALE_TO_FIT),
1008 C2_PARAMKEY_SURFACE_SCALING_MODE);
1009 } else {
1010 addLocalParam(new C2StreamColorAspectsInfo::input(0u), C2_PARAMKEY_COLOR_ASPECTS);
1011 }
1012 }
1013
1014 initializeStandardParams();
1015
1016 // subscribe to all supported standard (exposed) params
1017 // TODO: limit this to params that are actually in the domain
1018 std::vector<std::string> formatKeys = mStandardParams->getPathsForDomain(Domain(1 << 30));
1019 std::vector<C2Param::Index> indices;
1020 mParamUpdater->getParamIndicesForKeys(formatKeys, &indices);
1021 mSubscribedIndices.insert(indices.begin(), indices.end());
1022
1023 // also subscribe to some non-SDK standard parameters
1024 // for number of input/output buffers
1025 mSubscribedIndices.emplace(C2PortSuggestedBufferCountTuning::input::PARAM_TYPE);
1026 mSubscribedIndices.emplace(C2PortSuggestedBufferCountTuning::output::PARAM_TYPE);
1027 mSubscribedIndices.emplace(C2ActualPipelineDelayTuning::PARAM_TYPE);
1028 mSubscribedIndices.emplace(C2PortActualDelayTuning::input::PARAM_TYPE);
1029 mSubscribedIndices.emplace(C2PortActualDelayTuning::output::PARAM_TYPE);
1030 // for output buffer array allocation
1031 mSubscribedIndices.emplace(C2StreamMaxBufferSizeInfo::output::PARAM_TYPE);
1032 // init data (CSD)
1033 mSubscribedIndices.emplace(C2StreamInitDataInfo::output::PARAM_TYPE);
1034
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001035 for (const std::shared_ptr<C2ParamDescriptor> &desc : mParamDescs) {
1036 if (desc->index().isVendor()) {
1037 std::vector<std::string> keys;
1038 mParamUpdater->getKeysForParamIndex(desc->index(), &keys);
1039 for (const std::string &key : keys) {
1040 mVendorParamIndices.insert_or_assign(key, desc->index());
1041 }
1042 }
1043 }
1044
Pawin Vongmasa36653902018-11-15 00:10:25 -08001045 return OK;
1046}
1047
1048status_t CCodecConfig::subscribeToConfigUpdate(
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001049 const std::shared_ptr<Codec2Client::Configurable> &configurable,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001050 const std::vector<C2Param::Index> &indices,
1051 c2_blocking_t blocking) {
1052 mSubscribedIndices.insert(indices.begin(), indices.end());
1053 // TODO: enable this when components no longer crash on this config
1054 if (mSubscribedIndices.size() != mSubscribedIndicesSize && false) {
1055 std::vector<uint32_t> indices;
1056 for (C2Param::Index ix : mSubscribedIndices) {
1057 indices.push_back(ix);
1058 }
1059 std::unique_ptr<C2SubscribedParamIndicesTuning> subscribeTuning =
1060 C2SubscribedParamIndicesTuning::AllocUnique(indices);
1061 std::vector<std::unique_ptr<C2SettingResult>> results;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001062 c2_status_t c2Err = configurable->config({ subscribeTuning.get() }, blocking, &results);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001063 if (c2Err != C2_OK && c2Err != C2_BAD_INDEX) {
1064 ALOGD("Failed to subscribe to parameters => %s", asString(c2Err));
1065 // TODO: error
1066 }
1067 ALOGV("Subscribed to %zu params", mSubscribedIndices.size());
1068 mSubscribedIndicesSize = mSubscribedIndices.size();
1069 }
1070 return OK;
1071}
1072
1073status_t CCodecConfig::queryConfiguration(
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001074 const std::shared_ptr<Codec2Client::Configurable> &configurable) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001075 // query all subscribed parameters
1076 std::vector<C2Param::Index> indices(mSubscribedIndices.begin(), mSubscribedIndices.end());
1077 std::vector<std::unique_ptr<C2Param>> queried;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001078 c2_status_t c2Err = configurable->query({}, indices, C2_MAY_BLOCK, &queried);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001079 if (c2Err != OK) {
1080 ALOGI("query failed after returning %zu values (%s)", queried.size(), asString(c2Err));
1081 // TODO: error
1082 }
1083
1084 updateConfiguration(queried, ALL);
1085 return OK;
1086}
1087
1088bool CCodecConfig::updateConfiguration(
1089 std::vector<std::unique_ptr<C2Param>> &configUpdate, Domain domain) {
1090 ALOGV("updating configuration with %zu params", configUpdate.size());
1091 bool changed = false;
1092 for (std::unique_ptr<C2Param> &p : configUpdate) {
1093 if (p && *p) {
1094 auto insertion = mCurrentConfig.emplace(p->index(), nullptr);
1095 if (insertion.second || *insertion.first->second != *p) {
1096 if (mSupportedIndices.count(p->index()) || mLocalParams.count(p->index())) {
1097 // only track changes in supported (reflected or local) indices
1098 changed = true;
1099 } else {
1100 ALOGV("an unlisted config was %s: %#x",
1101 insertion.second ? "added" : "updated", p->index());
1102 }
1103 }
1104 insertion.first->second = std::move(p);
1105 }
1106 }
1107
1108 ALOGV("updated configuration has %zu params (%s)", mCurrentConfig.size(),
1109 changed ? "CHANGED" : "no change");
1110 if (changed) {
1111 return updateFormats(domain);
1112 }
1113 return false;
1114}
1115
1116bool CCodecConfig::updateFormats(Domain domain) {
1117 // get addresses of params in the current config
1118 std::vector<C2Param*> paramPointers;
1119 for (const auto &it : mCurrentConfig) {
1120 paramPointers.push_back(it.second.get());
1121 }
1122
1123 ReflectedParamUpdater::Dict reflected = mParamUpdater->getParams(paramPointers);
Wonsik Kimbd557932019-07-02 15:51:20 -07001124 std::string config = reflected.debugString();
1125 std::set<std::string> configLines;
1126 std::string diff;
1127 for (size_t start = 0; start != std::string::npos; ) {
1128 size_t end = config.find('\n', start);
1129 size_t count = (end == std::string::npos)
1130 ? std::string::npos
1131 : end - start + 1;
1132 std::string line = config.substr(start, count);
1133 configLines.insert(line);
1134 if (mLastConfig.count(line) == 0) {
1135 diff.append(line);
1136 }
1137 start = (end == std::string::npos) ? std::string::npos : end + 1;
1138 }
1139 if (!diff.empty()) {
1140 ALOGD("c2 config diff is %s", diff.c_str());
1141 }
1142 mLastConfig.swap(configLines);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001143
1144 bool changed = false;
1145 if (domain & mInputDomain) {
1146 sp<AMessage> oldFormat = mInputFormat;
1147 mInputFormat = mInputFormat->dup(); // trigger format changed
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001148 mInputFormat->extend(getFormatForDomain(reflected, mInputDomain));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001149 if (mInputFormat->countEntries() != oldFormat->countEntries()
1150 || mInputFormat->changesFrom(oldFormat)->countEntries() > 0) {
1151 changed = true;
1152 } else {
1153 mInputFormat = oldFormat; // no change
1154 }
1155 }
1156 if (domain & mOutputDomain) {
1157 sp<AMessage> oldFormat = mOutputFormat;
1158 mOutputFormat = mOutputFormat->dup(); // trigger output format changed
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001159 mOutputFormat->extend(getFormatForDomain(reflected, mOutputDomain));
Pawin Vongmasa36653902018-11-15 00:10:25 -08001160 if (mOutputFormat->countEntries() != oldFormat->countEntries()
1161 || mOutputFormat->changesFrom(oldFormat)->countEntries() > 0) {
1162 changed = true;
1163 } else {
1164 mOutputFormat = oldFormat; // no change
1165 }
1166 }
1167 ALOGV_IF(changed, "format(s) changed");
1168 return changed;
1169}
1170
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001171sp<AMessage> CCodecConfig::getFormatForDomain(
1172 const ReflectedParamUpdater::Dict &reflected,
1173 Domain portDomain) const {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001174 sp<AMessage> msg = new AMessage;
1175 for (const std::pair<std::string, std::vector<ConfigMapper>> &el : mStandardParams->getKeys()) {
1176 for (const ConfigMapper &cm : el.second) {
1177 if ((cm.domain() & portDomain) == 0 // input-output-coded-raw
1178 || (cm.domain() & mDomain) != mDomain // component domain + kind (these must match)
1179 || (cm.domain() & IS_READ) == 0) {
1180 continue;
1181 }
1182 auto it = reflected.find(cm.path());
1183 if (it == reflected.end()) {
1184 continue;
1185 }
1186 C2Value c2Value;
1187 sp<ABuffer> bufValue;
1188 AString strValue;
1189 AMessage::ItemData item;
1190 if (it->second.find(&c2Value)) {
1191 item = cm.mapToMessage(c2Value);
1192 } else if (it->second.find(&bufValue)) {
1193 item.set(bufValue);
1194 } else if (it->second.find(&strValue)) {
1195 item.set(strValue);
1196 } else {
1197 ALOGD("unexpected untyped query value for key: %s", cm.path().c_str());
1198 continue;
1199 }
1200 msg->setItem(el.first.c_str(), item);
1201 }
1202 }
1203
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001204 bool input = (portDomain & Domain::IS_INPUT);
1205 std::vector<std::string> vendorKeys;
1206 for (const std::pair<std::string, ReflectedParamUpdater::Value> &entry : reflected) {
1207 auto it = mVendorParamIndices.find(entry.first);
1208 if (it == mVendorParamIndices.end()) {
1209 continue;
1210 }
1211 if (mSubscribedIndices.count(it->second) == 0) {
1212 continue;
1213 }
1214 // For vendor parameters, we only care about direction
1215 if ((input && !it->second.forInput())
1216 || (!input && !it->second.forOutput())) {
1217 continue;
1218 }
1219 const ReflectedParamUpdater::Value &value = entry.second;
1220 C2Value c2Value;
1221 sp<ABuffer> bufValue;
1222 AString strValue;
1223 AMessage::ItemData item;
1224 if (value.find(&c2Value)) {
1225 C2ValueToMessageItem(c2Value, item);
1226 } else if (value.find(&bufValue)) {
1227 item.set(bufValue);
1228 } else if (value.find(&strValue)) {
1229 item.set(strValue);
1230 } else {
1231 ALOGD("unexpected untyped query value for key: %s", entry.first.c_str());
1232 continue;
1233 }
1234 msg->setItem(entry.first.c_str(), item);
1235 }
1236
Pawin Vongmasa36653902018-11-15 00:10:25 -08001237 { // convert from Codec 2.0 rect to MediaFormat rect and add crop rect if not present
1238 int32_t left, top, width, height;
1239 if (msg->findInt32("crop-left", &left) && msg->findInt32("crop-width", &width)
1240 && msg->findInt32("crop-top", &top) && msg->findInt32("crop-height", &height)
1241 && left >= 0 && width >=0 && width <= INT32_MAX - left
1242 && top >= 0 && height >=0 && height <= INT32_MAX - top) {
1243 msg->removeEntryAt(msg->findEntryByName("crop-left"));
1244 msg->removeEntryAt(msg->findEntryByName("crop-top"));
1245 msg->removeEntryAt(msg->findEntryByName("crop-width"));
1246 msg->removeEntryAt(msg->findEntryByName("crop-height"));
1247 msg->setRect("crop", left, top, left + width - 1, top + height - 1);
1248 } else if (msg->findInt32("width", &width) && msg->findInt32("height", &height)) {
1249 msg->setRect("crop", 0, 0, width - 1, height - 1);
1250 }
1251 }
1252
1253 { // convert temporal layering to schema
1254 sp<ABuffer> tmp;
1255 if (msg->findBuffer(C2_PARAMKEY_TEMPORAL_LAYERING, &tmp) && tmp != nullptr) {
1256 C2StreamTemporalLayeringTuning *layering =
1257 C2StreamTemporalLayeringTuning::From(C2Param::From(tmp->data(), tmp->size()));
1258 if (layering && layering->m.layerCount > 0
1259 && layering->m.bLayerCount < layering->m.layerCount) {
1260 // check if this is webrtc compatible
1261 AString mime;
1262 if (msg->findString(KEY_MIME, &mime) &&
1263 mime.equalsIgnoreCase(MIMETYPE_VIDEO_VP8) &&
1264 layering->m.bLayerCount == 0 &&
1265 (layering->m.layerCount == 1
1266 || (layering->m.layerCount == 2
1267 && layering->flexCount() >= 1
1268 && layering->m.bitrateRatios[0] == .6f)
1269 || (layering->m.layerCount == 3
1270 && layering->flexCount() >= 2
1271 && layering->m.bitrateRatios[0] == .4f
1272 && layering->m.bitrateRatios[1] == .6f)
1273 || (layering->m.layerCount == 4
1274 && layering->flexCount() >= 3
1275 && layering->m.bitrateRatios[0] == .25f
1276 && layering->m.bitrateRatios[1] == .4f
1277 && layering->m.bitrateRatios[2] == .6f))) {
1278 msg->setString(KEY_TEMPORAL_LAYERING, AStringPrintf(
1279 "webrtc.vp8.%u-layer", layering->m.layerCount));
1280 } else if (layering->m.bLayerCount) {
1281 msg->setString(KEY_TEMPORAL_LAYERING, AStringPrintf(
1282 "android.generic.%u+%u",
1283 layering->m.layerCount - layering->m.bLayerCount,
1284 layering->m.bLayerCount));
1285 } else if (layering->m.bLayerCount) {
1286 msg->setString(KEY_TEMPORAL_LAYERING, AStringPrintf(
1287 "android.generic.%u", layering->m.layerCount));
1288 }
1289 }
1290 msg->removeEntryAt(msg->findEntryByName(C2_PARAMKEY_TEMPORAL_LAYERING));
1291 }
1292 }
1293
1294 { // convert color info
1295 C2Color::primaries_t primaries;
1296 C2Color::matrix_t matrix;
1297 if (msg->findInt32("color-primaries", (int32_t*)&primaries)
1298 && msg->findInt32("color-matrix", (int32_t*)&matrix)) {
1299 int32_t standard;
1300
1301 if (C2Mapper::map(primaries, matrix, &standard)) {
1302 msg->setInt32(KEY_COLOR_STANDARD, standard);
1303 }
1304
1305 msg->removeEntryAt(msg->findEntryByName("color-primaries"));
1306 msg->removeEntryAt(msg->findEntryByName("color-matrix"));
1307 }
1308
1309
1310 // calculate dataspace for raw graphic buffers if not specified by component, or if
1311 // using surface with unspecified aspects (as those must be defaulted which may change
1312 // the dataspace)
1313 if ((portDomain & IS_RAW) && (mDomain & (IS_IMAGE | IS_VIDEO))) {
1314 android_dataspace dataspace;
1315 ColorAspects aspects = {
1316 ColorAspects::RangeUnspecified, ColorAspects::PrimariesUnspecified,
1317 ColorAspects::TransferUnspecified, ColorAspects::MatrixUnspecified
1318 };
1319 ColorUtils::getColorAspectsFromFormat(msg, aspects);
1320 ColorAspects origAspects = aspects;
1321 if (mUsingSurface) {
1322 // get image size (default to HD)
1323 int32_t width = 1280;
1324 int32_t height = 720;
1325 int32_t left, top, right, bottom;
1326 if (msg->findRect("crop", &left, &top, &right, &bottom)) {
1327 width = right - left + 1;
1328 height = bottom - top + 1;
1329 } else {
1330 (void)msg->findInt32(KEY_WIDTH, &width);
1331 (void)msg->findInt32(KEY_HEIGHT, &height);
1332 }
1333 ColorUtils::setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
1334 ColorUtils::setColorAspectsIntoFormat(aspects, msg);
1335 }
1336
1337 if (!msg->findInt32("android._dataspace", (int32_t*)&dataspace)
1338 || aspects.mRange != origAspects.mRange
1339 || aspects.mPrimaries != origAspects.mPrimaries
1340 || aspects.mTransfer != origAspects.mTransfer
1341 || aspects.mMatrixCoeffs != origAspects.mMatrixCoeffs) {
1342 dataspace = ColorUtils::getDataSpaceForColorAspects(aspects, true /* mayExpand */);
1343 msg->setInt32("android._dataspace", dataspace);
1344 }
1345 }
1346
1347 // HDR static info
1348
1349 C2HdrStaticMetadataStruct hdr;
1350 if (msg->findFloat("smpte2086.red.x", &hdr.mastering.red.x)
1351 && msg->findFloat("smpte2086.red.y", &hdr.mastering.red.y)
1352 && msg->findFloat("smpte2086.green.x", &hdr.mastering.green.x)
1353 && msg->findFloat("smpte2086.green.y", &hdr.mastering.green.y)
1354 && msg->findFloat("smpte2086.blue.x", &hdr.mastering.blue.x)
1355 && msg->findFloat("smpte2086.blue.y", &hdr.mastering.blue.y)
1356 && msg->findFloat("smpte2086.white.x", &hdr.mastering.white.x)
1357 && msg->findFloat("smpte2086.white.y", &hdr.mastering.white.y)
1358 && msg->findFloat("smpte2086.max-luminance", &hdr.mastering.maxLuminance)
1359 && msg->findFloat("smpte2086.min-luminance", &hdr.mastering.minLuminance)
1360 && msg->findFloat("cta861.max-cll", &hdr.maxCll)
1361 && msg->findFloat("cta861.max-fall", &hdr.maxFall)) {
1362 if (hdr.mastering.red.x >= 0 && hdr.mastering.red.x <= 1
1363 && hdr.mastering.red.y >= 0 && hdr.mastering.red.y <= 1
1364 && hdr.mastering.green.x >= 0 && hdr.mastering.green.x <= 1
1365 && hdr.mastering.green.y >= 0 && hdr.mastering.green.y <= 1
1366 && hdr.mastering.blue.x >= 0 && hdr.mastering.blue.x <= 1
1367 && hdr.mastering.blue.y >= 0 && hdr.mastering.blue.y <= 1
1368 && hdr.mastering.white.x >= 0 && hdr.mastering.white.x <= 1
1369 && hdr.mastering.white.y >= 0 && hdr.mastering.white.y <= 1
1370 && hdr.mastering.maxLuminance >= 0 && hdr.mastering.maxLuminance <= 65535
1371 && hdr.mastering.minLuminance >= 0 && hdr.mastering.minLuminance <= 6.5535
1372 && hdr.maxCll >= 0 && hdr.maxCll <= 65535
1373 && hdr.maxFall >= 0 && hdr.maxFall <= 65535) {
1374 HDRStaticInfo meta;
1375 meta.mID = meta.kType1;
1376 meta.sType1.mR.x = hdr.mastering.red.x / 0.00002 + 0.5;
1377 meta.sType1.mR.y = hdr.mastering.red.y / 0.00002 + 0.5;
1378 meta.sType1.mG.x = hdr.mastering.green.x / 0.00002 + 0.5;
1379 meta.sType1.mG.y = hdr.mastering.green.y / 0.00002 + 0.5;
1380 meta.sType1.mB.x = hdr.mastering.blue.x / 0.00002 + 0.5;
1381 meta.sType1.mB.y = hdr.mastering.blue.y / 0.00002 + 0.5;
1382 meta.sType1.mW.x = hdr.mastering.white.x / 0.00002 + 0.5;
1383 meta.sType1.mW.y = hdr.mastering.white.y / 0.00002 + 0.5;
1384 meta.sType1.mMaxDisplayLuminance = hdr.mastering.maxLuminance + 0.5;
1385 meta.sType1.mMinDisplayLuminance = hdr.mastering.minLuminance / 0.0001 + 0.5;
1386 meta.sType1.mMaxContentLightLevel = hdr.maxCll + 0.5;
1387 meta.sType1.mMaxFrameAverageLightLevel = hdr.maxFall + 0.5;
1388 msg->removeEntryAt(msg->findEntryByName("smpte2086.red.x"));
1389 msg->removeEntryAt(msg->findEntryByName("smpte2086.red.y"));
1390 msg->removeEntryAt(msg->findEntryByName("smpte2086.green.x"));
1391 msg->removeEntryAt(msg->findEntryByName("smpte2086.green.y"));
1392 msg->removeEntryAt(msg->findEntryByName("smpte2086.blue.x"));
1393 msg->removeEntryAt(msg->findEntryByName("smpte2086.blue.y"));
1394 msg->removeEntryAt(msg->findEntryByName("smpte2086.white.x"));
1395 msg->removeEntryAt(msg->findEntryByName("smpte2086.white.y"));
1396 msg->removeEntryAt(msg->findEntryByName("smpte2086.max-luminance"));
1397 msg->removeEntryAt(msg->findEntryByName("smpte2086.min-luminance"));
1398 msg->removeEntryAt(msg->findEntryByName("cta861.max-cll"));
1399 msg->removeEntryAt(msg->findEntryByName("cta861.max-fall"));
1400 msg->setBuffer(KEY_HDR_STATIC_INFO, ABuffer::CreateAsCopy(&meta, sizeof(meta)));
1401 } else {
1402 ALOGD("found invalid HDR static metadata %s", msg->debugString(8).c_str());
1403 }
1404 }
1405 }
1406
1407 ALOGV("converted to SDK values as %s", msg->debugString().c_str());
1408 return msg;
1409}
1410
1411/// converts an AMessage value to a ParamUpdater value
1412static void convert(const AMessage::ItemData &from, ReflectedParamUpdater::Value *to) {
1413 int32_t int32Value;
1414 int64_t int64Value;
1415 sp<ABuffer> bufValue;
1416 AString strValue;
1417 float floatValue;
1418 double doubleValue;
1419
1420 if (from.find(&int32Value)) {
1421 to->set(int32Value);
1422 } else if (from.find(&int64Value)) {
1423 to->set(int64Value);
1424 } else if (from.find(&bufValue)) {
1425 to->set(bufValue);
1426 } else if (from.find(&strValue)) {
1427 to->set(strValue);
1428 } else if (from.find(&floatValue)) {
1429 to->set(C2Value(floatValue));
1430 } else if (from.find(&doubleValue)) {
1431 // convert double to float
1432 to->set(C2Value((float)doubleValue));
1433 }
1434 // ignore all other AMessage types
1435}
1436
1437/// relaxes Codec 2.0 specific value types to SDK types (mainly removes signedness and counterness
1438/// from 32/64-bit values.)
1439static void relaxValues(ReflectedParamUpdater::Value &item) {
1440 C2Value c2Value;
1441 int32_t int32Value;
1442 int64_t int64Value;
1443 (void)item.find(&c2Value);
1444 if (c2Value.get(&int32Value) || c2Value.get((uint32_t*)&int32Value)
1445 || c2Value.get((c2_cntr32_t*)&int32Value)) {
1446 item.set(int32Value);
1447 } else if (c2Value.get(&int64Value)
1448 || c2Value.get((uint64_t*)&int64Value)
1449 || c2Value.get((c2_cntr64_t*)&int64Value)) {
1450 item.set(int64Value);
1451 }
1452}
1453
1454ReflectedParamUpdater::Dict CCodecConfig::getReflectedFormat(
1455 const sp<AMessage> &params_, Domain configDomain) const {
1456 // create a modifiable copy of params
1457 sp<AMessage> params = params_->dup();
1458 ALOGV("filtering with config domain %x", configDomain);
1459
1460 // convert some macro parameters to Codec 2.0 specific expressions
1461
1462 { // make i-frame-interval frame based
1463 float iFrameInterval;
1464 if (params->findAsFloat(KEY_I_FRAME_INTERVAL, &iFrameInterval)) {
1465 float frameRate;
1466 if (params->findAsFloat(KEY_FRAME_RATE, &frameRate)) {
1467 params->setInt32("i-frame-period",
1468 (frameRate <= 0 || iFrameInterval < 0)
1469 ? -1 /* no sync frames */
1470 : (int32_t)c2_min(iFrameInterval * frameRate + 0.5,
1471 (float)INT32_MAX));
1472 }
1473 }
1474 }
1475
1476 if (mDomain == (IS_VIDEO | IS_ENCODER)) {
1477 // convert capture-rate into input-time-stretch
1478 float frameRate, captureRate;
1479 if (params->findAsFloat(KEY_FRAME_RATE, &frameRate)) {
1480 if (!params->findAsFloat("time-lapse-fps", &captureRate)
1481 && !params->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
1482 captureRate = frameRate;
1483 }
1484 if (captureRate > 0 && frameRate > 0) {
1485 params->setFloat(C2_PARAMKEY_INPUT_TIME_STRETCH, captureRate / frameRate);
1486 }
1487 }
1488 }
1489
1490 { // reflect temporal layering into a binary blob
1491 AString schema;
1492 if (params->findString(KEY_TEMPORAL_LAYERING, &schema)) {
1493 unsigned int numLayers = 0;
1494 unsigned int numBLayers = 0;
1495 int tags;
1496 char dummy;
1497 std::unique_ptr<C2StreamTemporalLayeringTuning::output> layering;
1498 if (sscanf(schema.c_str(), "webrtc.vp8.%u-layer%c", &numLayers, &dummy) == 1
1499 && numLayers > 0) {
1500 switch (numLayers) {
1501 case 1:
1502 layering = C2StreamTemporalLayeringTuning::output::AllocUnique(
1503 {}, 0u, 1u, 0u);
1504 break;
1505 case 2:
1506 layering = C2StreamTemporalLayeringTuning::output::AllocUnique(
1507 { .6f }, 0u, 2u, 0u);
1508 break;
1509 case 3:
1510 layering = C2StreamTemporalLayeringTuning::output::AllocUnique(
1511 { .4f, .6f }, 0u, 3u, 0u);
1512 break;
1513 default:
1514 layering = C2StreamTemporalLayeringTuning::output::AllocUnique(
1515 { .25f, .4f, .6f }, 0u, 4u, 0u);
1516 break;
1517 }
1518 } else if ((tags = sscanf(schema.c_str(), "android.generic.%u%c%u%c",
1519 &numLayers, &dummy, &numBLayers, &dummy))
1520 && (tags == 1 || (tags == 3 && dummy == '+'))
1521 && numLayers > 0 && numLayers < UINT32_MAX - numBLayers) {
1522 layering = C2StreamTemporalLayeringTuning::output::AllocUnique(
1523 {}, 0u, numLayers + numBLayers, numBLayers);
1524 } else {
1525 ALOGD("Ignoring unsupported ts-schema [%s]", schema.c_str());
1526 }
1527 if (layering) {
1528 params->setBuffer(C2_PARAMKEY_TEMPORAL_LAYERING,
1529 ABuffer::CreateAsCopy(layering.get(), layering->size()));
1530 }
1531 }
1532 }
1533
1534 { // convert from MediaFormat rect to Codec 2.0 rect
1535 int32_t offset;
1536 int32_t end;
1537 AMessage::ItemData item;
1538 if (params->findInt32("crop-left", &offset) && params->findInt32("crop-right", &end)
1539 && offset >= 0 && end >= offset - 1) {
1540 size_t ix = params->findEntryByName("crop-right");
1541 params->setEntryNameAt(ix, "crop-width");
1542 item.set(end - offset + 1);
1543 params->setEntryAt(ix, item);
1544 }
1545 if (params->findInt32("crop-top", &offset) && params->findInt32("crop-bottom", &end)
1546 && offset >= 0 && end >= offset - 1) {
1547 size_t ix = params->findEntryByName("crop-bottom");
1548 params->setEntryNameAt(ix, "crop-height");
1549 item.set(end - offset + 1);
1550 params->setEntryAt(ix, item);
1551 }
1552 }
1553
1554 { // convert color info
1555 int32_t standard;
1556 if (params->findInt32(KEY_COLOR_STANDARD, &standard)) {
1557 C2Color::primaries_t primaries;
1558 C2Color::matrix_t matrix;
1559
1560 if (C2Mapper::map(standard, &primaries, &matrix)) {
1561 params->setInt32("color-primaries", primaries);
1562 params->setInt32("color-matrix", matrix);
1563 }
1564 }
1565
1566 sp<ABuffer> hdrMeta;
1567 if (params->findBuffer(KEY_HDR_STATIC_INFO, &hdrMeta)
1568 && hdrMeta->size() == sizeof(HDRStaticInfo)) {
1569 HDRStaticInfo *meta = (HDRStaticInfo*)hdrMeta->data();
1570 if (meta->mID == meta->kType1) {
1571 params->setFloat("smpte2086.red.x", meta->sType1.mR.x * 0.00002);
1572 params->setFloat("smpte2086.red.y", meta->sType1.mR.y * 0.00002);
1573 params->setFloat("smpte2086.green.x", meta->sType1.mG.x * 0.00002);
1574 params->setFloat("smpte2086.green.y", meta->sType1.mG.y * 0.00002);
1575 params->setFloat("smpte2086.blue.x", meta->sType1.mB.x * 0.00002);
1576 params->setFloat("smpte2086.blue.y", meta->sType1.mB.y * 0.00002);
1577 params->setFloat("smpte2086.white.x", meta->sType1.mW.x * 0.00002);
1578 params->setFloat("smpte2086.white.y", meta->sType1.mW.y * 0.00002);
1579 params->setFloat("smpte2086.max-luminance", meta->sType1.mMaxDisplayLuminance);
1580 params->setFloat("smpte2086.min-luminance", meta->sType1.mMinDisplayLuminance * 0.0001);
1581 params->setFloat("cta861.max-cll", meta->sType1.mMaxContentLightLevel);
1582 params->setFloat("cta861.max-fall", meta->sType1.mMaxFrameAverageLightLevel);
1583 }
1584 }
1585 }
1586
1587 // this is to verify that we set proper signedness for standard parameters
1588 bool beVeryStrict = property_get_bool("debug.stagefright.ccodec_strict_type", false);
1589 // this is to allow vendors to use the wrong signedness for standard parameters
1590 bool beVeryLax = property_get_bool("debug.stagefright.ccodec_lax_type", false);
1591
1592 ReflectedParamUpdater::Dict filtered;
1593 for (size_t ix = 0; ix < params->countEntries(); ++ix) {
1594 AMessage::Type type;
1595 AString name = params->getEntryNameAt(ix, &type);
1596 AMessage::ItemData msgItem = params->getEntryAt(ix);
1597 ReflectedParamUpdater::Value item;
1598 convert(msgItem, &item); // convert item to param updater item
1599
1600 if (name.startsWith("vendor.")) {
1601 // vendor params pass through as is
1602 filtered.emplace(name.c_str(), item);
1603 continue;
1604 }
1605 // standard parameters may get modified, filtered or duplicated
1606 for (const ConfigMapper &cm : mStandardParams->getConfigMappersForSdkKey(name.c_str())) {
1607 // note: we ignore port domain for configuration
1608 if ((cm.domain() & configDomain)
1609 // component domain + kind (these must match)
1610 && (cm.domain() & mDomain) == mDomain) {
1611 // map arithmetic values, pass through string or buffer
1612 switch (type) {
1613 case AMessage::kTypeBuffer:
1614 case AMessage::kTypeString:
1615 break;
1616 case AMessage::kTypeInt32:
1617 case AMessage::kTypeInt64:
1618 case AMessage::kTypeFloat:
1619 case AMessage::kTypeDouble:
1620 // for now only map settings with mappers as we are not creating
1621 // signed <=> unsigned mappers
1622 // TODO: be precise about signed unsigned
1623 if (beVeryStrict || cm.mapper()) {
1624 item.set(cm.mapFromMessage(params->getEntryAt(ix)));
1625 // also allow to relax type strictness
1626 if (beVeryLax) {
1627 relaxValues(item);
1628 }
1629 }
1630 break;
1631 default:
1632 continue;
1633 }
1634 filtered.emplace(cm.path(), item);
1635 }
1636 }
1637 }
1638 ALOGV("filtered %s to %s", params->debugString(4).c_str(),
1639 filtered.debugString(4).c_str());
1640 return filtered;
1641}
1642
1643status_t CCodecConfig::getConfigUpdateFromSdkParams(
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001644 std::shared_ptr<Codec2Client::Configurable> configurable,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001645 const sp<AMessage> &sdkParams, Domain configDomain,
1646 c2_blocking_t blocking,
1647 std::vector<std::unique_ptr<C2Param>> *configUpdate) const {
1648 ReflectedParamUpdater::Dict params = getReflectedFormat(sdkParams, configDomain);
1649
1650 std::vector<C2Param::Index> indices;
1651 mParamUpdater->getParamIndicesFromMessage(params, &indices);
1652 if (indices.empty()) {
1653 ALOGD("no recognized params in: %s", params.debugString().c_str());
1654 return OK;
1655 }
1656
1657 configUpdate->clear();
1658 std::vector<C2Param::Index> supportedIndices;
1659 for (C2Param::Index ix : indices) {
1660 if (mSupportedIndices.count(ix)) {
1661 supportedIndices.push_back(ix);
1662 } else if (mLocalParams.count(ix)) {
1663 // query local parameter here
1664 auto it = mCurrentConfig.find(ix);
1665 if (it != mCurrentConfig.end()) {
1666 configUpdate->emplace_back(C2Param::Copy(*it->second));
1667 }
1668 }
1669 }
1670
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001671 c2_status_t err = configurable->query({ }, supportedIndices, blocking, configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001672 if (err != C2_OK) {
1673 ALOGD("query failed after returning %zu params => %s", configUpdate->size(), asString(err));
1674 }
1675
1676 if (configUpdate->size()) {
1677 mParamUpdater->updateParamsFromMessage(params, configUpdate);
1678 }
1679 return OK;
1680}
1681
1682status_t CCodecConfig::setParameters(
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001683 std::shared_ptr<Codec2Client::Configurable> configurable,
Pawin Vongmasa36653902018-11-15 00:10:25 -08001684 std::vector<std::unique_ptr<C2Param>> &configUpdate,
1685 c2_blocking_t blocking) {
1686 status_t result = OK;
1687 if (configUpdate.empty()) {
1688 return OK;
1689 }
1690
1691 std::vector<C2Param::Index> indices;
1692 std::vector<C2Param *> paramVector;
1693 for (const std::unique_ptr<C2Param> &param : configUpdate) {
1694 if (mSupportedIndices.count(param->index())) {
1695 // component parameter
1696 paramVector.push_back(param.get());
1697 indices.push_back(param->index());
1698 } else if (mLocalParams.count(param->index())) {
1699 // handle local parameter here
1700 LocalParamValidator validator = mLocalParams.find(param->index())->second;
1701 c2_status_t err = C2_OK;
1702 std::unique_ptr<C2Param> copy = C2Param::Copy(*param);
1703 if (validator) {
1704 err = validator(copy);
1705 }
1706 if (err == C2_OK) {
1707 ALOGV("updated local parameter value for %s",
1708 mParamUpdater->getParamName(param->index()).c_str());
1709
1710 mCurrentConfig[param->index()] = std::move(copy);
1711 } else {
1712 ALOGD("failed to set parameter value for %s => %s",
1713 mParamUpdater->getParamName(param->index()).c_str(), asString(err));
1714 result = BAD_VALUE;
1715 }
1716 }
1717 }
1718 // update subscribed param indices
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001719 subscribeToConfigUpdate(configurable, indices, blocking);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001720
1721 std::vector<std::unique_ptr<C2SettingResult>> failures;
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001722 c2_status_t err = configurable->config(paramVector, blocking, &failures);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001723 if (err != C2_OK) {
1724 ALOGD("config failed => %s", asString(err));
1725 // This is non-fatal.
1726 }
1727 for (const std::unique_ptr<C2SettingResult> &failure : failures) {
1728 switch (failure->failure) {
1729 case C2SettingResult::BAD_VALUE:
1730 ALOGD("Bad parameter value");
1731 result = BAD_VALUE;
1732 break;
1733 default:
1734 ALOGV("failure = %d", int(failure->failure));
1735 break;
1736 }
1737 }
1738
1739 // Re-query parameter values in case config could not update them and update the current
1740 // configuration.
1741 configUpdate.clear();
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001742 err = configurable->query({}, indices, blocking, &configUpdate);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001743 if (err != C2_OK) {
1744 ALOGD("query failed after returning %zu params => %s", configUpdate.size(), asString(err));
1745 }
1746 (void)updateConfiguration(configUpdate, ALL);
1747
1748 // TODO: error value
1749 return result;
1750}
1751
1752const C2Param *CCodecConfig::getConfigParameterValue(C2Param::Index index) const {
1753 auto it = mCurrentConfig.find(index);
1754 if (it == mCurrentConfig.end()) {
1755 return nullptr;
1756 } else {
1757 return it->second.get();
1758 }
1759}
1760
Wonsik Kim8a6ed372019-12-03 16:05:51 -08001761status_t CCodecConfig::subscribeToAllVendorParams(
1762 const std::shared_ptr<Codec2Client::Configurable> &configurable,
1763 c2_blocking_t blocking) {
1764 for (const std::pair<std::string, C2Param::Index> &entry : mVendorParamIndices) {
1765 mSubscribedIndices.insert(entry.second);
1766 }
1767 return subscribeToConfigUpdate(configurable, {}, blocking);
1768}
1769
Pawin Vongmasa36653902018-11-15 00:10:25 -08001770} // namespace android