1 /*
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>
23 #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 */
36 #define DRC_DEFAULT_MOBILE_DRC_ALBUM 0 /* MPEG-D DRC album mode; 0 => album mode is disabled, 1 => album mode is enabled */
37 #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) */
38 #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
47 namespace android {
48
49 // CCodecConfig
50
51 namespace {
52
C2ValueToMessageItem(const C2Value & value,AMessage::ItemData & item)53 void 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
74 /**
75 * mapping between SDK and Codec 2.0 configurations.
76 */
77 struct ConfigMapper {
78 /**
79 * Value mapper (C2Value => C2Value)
80 */
81 typedef std::function<C2Value(C2Value)> Mapper;
82
83 /// shorthand
84 typedef CCodecConfig::Domain Domain;
85
ConfigMapperandroid::__anon5f9fd7420111::ConfigMapper86 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
limitToandroid::__anon5f9fd7420111::ConfigMapper90 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)
withMapperandroid::__anon5f9fd7420111::ConfigMapper97 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
withMappersandroid::__anon5f9fd7420111::ConfigMapper105 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>
withC2Mappersandroid::__anon5f9fd7420111::ConfigMapper115 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.
mapFromMessageandroid::__anon5f9fd7420111::ConfigMapper139 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.
mapToMessageandroid::__anon5f9fd7420111::ConfigMapper161 AMessage::ItemData mapToMessage(C2Value value) const {
162 AMessage::ItemData item;
163 if (value.type() != C2Value::NO_INIT && mReverse) {
164 value = mReverse(value);
165 }
166 C2ValueToMessageItem(value, item);
167 return item;
168 }
169
domainandroid::__anon5f9fd7420111::ConfigMapper170 Domain domain() const { return mDomain; }
mediaKeyandroid::__anon5f9fd7420111::ConfigMapper171 std::string mediaKey() const { return mMediaKey; }
pathandroid::__anon5f9fd7420111::ConfigMapper172 std::string path() const { return mField.size() ? mStruct + '.' + mField : mStruct; }
mapperandroid::__anon5f9fd7420111::ConfigMapper173 Mapper mapper() const { return mMapper; }
reverseandroid::__anon5f9fd7420111::ConfigMapper174 Mapper reverse() const { return mReverse; }
175
176 private:
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
185 template <typename PORT, typename STREAM>
QueryMediaTypeImpl(const std::shared_ptr<Codec2Client::Configurable> & configurable)186 AString QueryMediaTypeImpl(
187 const std::shared_ptr<Codec2Client::Configurable> &configurable) {
188 AString mediaType;
189 std::vector<std::unique_ptr<C2Param>> queried;
190 c2_status_t c2err = configurable->query(
191 {}, { 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
QueryMediaType(bool input,const std::shared_ptr<Codec2Client::Configurable> & configurable)214 AString QueryMediaType(
215 bool input, const std::shared_ptr<Codec2Client::Configurable> &configurable) {
216 typedef C2PortMediaTypeSetting P;
217 typedef C2StreamMediaTypeSetting S;
218 if (input) {
219 return QueryMediaTypeImpl<P::input, S::input>(configurable);
220 } else {
221 return QueryMediaTypeImpl<P::output, S::output>(configurable);
222 }
223 }
224
225 } // namespace
226
227 /**
228 * Set of standard parameters used by CCodec that are exposed to MediaCodec.
229 */
230 struct 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.
getConfigMappersForSdkKeyandroid::StandardParams240 const std::vector<ConfigMapper> &getConfigMappersForSdkKey(std::string key) const {
241 auto it = mConfigMappers.find(key);
242 if (it == mConfigMappers.end()) {
243 if (mComplained.count(key) == 0) {
244 ALOGD("no c2 equivalents for %s", key.c_str());
245 mComplained.insert(key);
246 }
247 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 */
addandroid::StandardParams260 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 */
getPathsForDomainandroid::StandardParams289 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 */
getKeysandroid::StandardParams309 const std::map<SdkKey, std::vector<ConfigMapper>> getKeys() const {
310 return mConfigMappers;
311 }
312
313 private:
314 std::map<SdkKey, std::vector<ConfigMapper>> mConfigMappers;
315 mutable std::set<std::string> mComplained;
316 };
317
318 const std::vector<ConfigMapper> StandardParams::NO_MAPPERS;
319
320
CCodecConfig()321 CCodecConfig::CCodecConfig()
322 : mInputFormat(new AMessage),
323 mOutputFormat(new AMessage),
324 mUsingSurface(false) { }
325
initializeStandardParams()326 void 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)
370 .withC2Mappers<C2Config::bitrate_mode_t>());
371 // 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
491 add(ConfigMapper(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES,
492 C2_PARAMKEY_PREPEND_HEADER_MODE, "value")
493 .limitTo(D::ENCODER & D::VIDEO)
494 .withMappers([](C2Value v) -> C2Value {
495 int32_t value;
496 if (v.get(&value)) {
497 return value ? C2Value(C2Config::PREPEND_HEADER_TO_ALL_SYNC)
498 : C2Value(C2Config::PREPEND_HEADER_TO_NONE);
499 }
500 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();
513 }));
514 // remove when codecs switch to PARAMKEY
515 deprecated(ConfigMapper(KEY_PREPEND_HEADERS_TO_SYNC_FRAMES,
516 "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")
520 .limitTo(D::VIDEO & D::ENCODER & D::CONFIG)
521 .withMapper([](C2Value v) -> C2Value {
522 // 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 }));
545 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
587 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
593 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)) {
603 uint32_t result;
604 if (C2Mapper::mapPixelFormatFrameworkToCodec(value, &result)) {
605 return result;
606 }
607 }
608 return C2Value();
609 }, [](C2Value v) -> C2Value {
610 uint32_t value;
611 if (v.get(&value)) {
612 int32_t result;
613 if (C2Mapper::mapPixelFormatCodecToFramework(value, &result)) {
614 return result;
615 }
616 }
617 return C2Value();
618 }));
619
620 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
625 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")
636 .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 }));
653
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")
713 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
714 .withMappers([](C2Value v) -> C2Value {
715 int32_t value;
716 if (!v.get(&value) || value < -1) {
717 value = property_get_int32(PROP_DRC_OVERRIDE_REF_LEVEL, DRC_DEFAULT_MOBILE_REF_LEVEL);
718 }
719 return float(-0.25 * c2_min(value, 127));
720 },[](C2Value v) -> C2Value {
721 float value;
722 if (v.get(&value)) {
723 return (int32_t) (-4. * value);
724 }
725 return C2Value();
726 }));
727
728 // convert to 0-1 (%) and add default
729 add(ConfigMapper(KEY_AAC_DRC_ATTENUATION_FACTOR, C2_PARAMKEY_DRC_ATTENUATION_FACTOR, "value")
730 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
731 .withMappers([](C2Value v) -> C2Value {
732 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.);
737 },[](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 }
745 }));
746
747 // convert to 0-1 (%) and add default
748 add(ConfigMapper(KEY_AAC_DRC_BOOST_FACTOR, C2_PARAMKEY_DRC_BOOST_FACTOR, "value")
749 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
750 .withMappers([](C2Value v) -> C2Value {
751 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.);
756 },[](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 }
764 }));
765
766 // convert to compression type and add default
767 add(ConfigMapper(KEY_AAC_DRC_HEAVY_COMPRESSION, C2_PARAMKEY_DRC_COMPRESSION_MODE, "value")
768 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
769 .withMappers([](C2Value v) -> C2Value {
770 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 },[](C2Value v) -> C2Value {
776 int32_t value;
777 if (v.get(&value)) {
778 return value;
779 }
780 else {
781 return C2Value();
782 }
783 }));
784
785 // convert to dBFS and add default
786 add(ConfigMapper(KEY_AAC_ENCODED_TARGET_LEVEL, C2_PARAMKEY_DRC_ENCODED_TARGET_LEVEL, "value")
787 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
788 .withMappers([](C2Value v) -> C2Value {
789 int32_t value;
790 if (!v.get(&value) || value < 0) {
791 value = property_get_int32(PROP_DRC_OVERRIDE_ENC_LEVEL, DRC_DEFAULT_MOBILE_ENC_LEVEL);
792 }
793 return float(-0.25 * c2_min(value, 127));
794 },[](C2Value v) -> C2Value {
795 float value;
796 if (v.get(&value)) {
797 return (int32_t) (-4. * value);
798 }
799 else {
800 return C2Value();
801 }
802 }));
803
804 // convert to effect type (these map to SDK values) and add default
805 add(ConfigMapper(KEY_AAC_DRC_EFFECT_TYPE, C2_PARAMKEY_DRC_EFFECT_TYPE, "value")
806 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
807 .withMappers([](C2Value v) -> C2Value {
808 int32_t value;
809 if (!v.get(&value) || value < -1 || value > 8) {
810 value = property_get_int32(PROP_DRC_OVERRIDE_EFFECT, DRC_DEFAULT_MOBILE_DRC_EFFECT);
811 // ensure value is within range
812 if (value < -1 || value > 8) {
813 value = DRC_DEFAULT_MOBILE_DRC_EFFECT;
814 }
815 }
816 return value;
817 },[](C2Value v) -> C2Value {
818 int32_t value;
819 if (v.get(&value)) {
820 return value;
821 }
822 else {
823 return C2Value();
824 }
825 }));
826
827 // convert to album mode and add default
828 add(ConfigMapper(KEY_AAC_DRC_ALBUM_MODE, C2_PARAMKEY_DRC_ALBUM_MODE, "value")
829 .limitTo(D::AUDIO & D::DECODER & (D::CONFIG | D::PARAM | D::READ))
830 .withMappers([](C2Value v) -> C2Value {
831 int32_t value;
832 if (!v.get(&value) || value < 0 || value > 1) {
833 value = DRC_DEFAULT_MOBILE_DRC_ALBUM;
834 // ensure value is within range
835 if (value < 0 || value > 1) {
836 value = DRC_DEFAULT_MOBILE_DRC_ALBUM;
837 }
838 }
839 return value;
840 },[](C2Value v) -> C2Value {
841 int32_t value;
842 if (v.get(&value)) {
843 return value;
844 }
845 else {
846 return C2Value();
847 }
848 }));
849
850 add(ConfigMapper(KEY_AAC_DRC_OUTPUT_LOUDNESS, C2_PARAMKEY_DRC_OUTPUT_LOUDNESS, "value")
851 .limitTo(D::OUTPUT & D::DECODER & D::READ)
852 .withMappers([](C2Value v) -> C2Value {
853 int32_t value;
854 if (!v.get(&value) || value < -1) {
855 value = DRC_DEFAULT_MOBILE_OUTPUT_LOUDNESS;
856 }
857 return float(-0.25 * c2_min(value, 127));
858 },[](C2Value v) -> C2Value {
859 float value;
860 if (v.get(&value)) {
861 return (int32_t) (-4. * value);
862 }
863 return C2Value();
864 }));
865
866 add(ConfigMapper(KEY_AAC_MAX_OUTPUT_CHANNEL_COUNT, C2_PARAMKEY_MAX_CHANNEL_COUNT, "value")
867 .limitTo(D::AUDIO & (D::CONFIG | D::PARAM | D::READ)));
868
869 add(ConfigMapper(KEY_AAC_SBR_MODE, C2_PARAMKEY_AAC_SBR_MODE, "value")
870 .limitTo(D::AUDIO & D::ENCODER & (D::CONFIG | D::PARAM | D::READ))
871 .withMapper([](C2Value v) -> C2Value {
872 int32_t value;
873 if (!v.get(&value) || value < 0) {
874 return C2Config::AAC_SBR_AUTO;
875 }
876 switch (value) {
877 case 0: return C2Config::AAC_SBR_OFF;
878 case 1: return C2Config::AAC_SBR_SINGLE_RATE;
879 case 2: return C2Config::AAC_SBR_DUAL_RATE;
880 default: return C2Config::AAC_SBR_AUTO + 1; // invalid value
881 }
882 }));
883
884 add(ConfigMapper(KEY_QUALITY, C2_PARAMKEY_QUALITY, "value")
885 .limitTo(D::ENCODER & (D::CONFIG | D::PARAM)));
886 add(ConfigMapper(KEY_FLAC_COMPRESSION_LEVEL, C2_PARAMKEY_COMPLEXITY, "value")
887 .limitTo(D::AUDIO & D::ENCODER));
888 add(ConfigMapper("complexity", C2_PARAMKEY_COMPLEXITY, "value")
889 .limitTo(D::ENCODER & (D::CONFIG | D::PARAM)));
890
891 add(ConfigMapper(KEY_GRID_COLUMNS, C2_PARAMKEY_TILE_LAYOUT, "columns")
892 .limitTo(D::IMAGE));
893 add(ConfigMapper(KEY_GRID_ROWS, C2_PARAMKEY_TILE_LAYOUT, "rows")
894 .limitTo(D::IMAGE));
895 add(ConfigMapper(KEY_TILE_WIDTH, C2_PARAMKEY_TILE_LAYOUT, "tile.width")
896 .limitTo(D::IMAGE));
897 add(ConfigMapper(KEY_TILE_HEIGHT, C2_PARAMKEY_TILE_LAYOUT, "tile.height")
898 .limitTo(D::IMAGE));
899
900 add(ConfigMapper(KEY_LATENCY, C2_PARAMKEY_PIPELINE_DELAY_REQUEST, "value")
901 .limitTo(D::VIDEO & D::ENCODER));
902
903 add(ConfigMapper(C2_PARAMKEY_INPUT_TIME_STRETCH, C2_PARAMKEY_INPUT_TIME_STRETCH, "value"));
904
905 add(ConfigMapper(KEY_LOW_LATENCY, C2_PARAMKEY_LOW_LATENCY_MODE, "value")
906 .limitTo(D::DECODER & (D::CONFIG | D::PARAM))
907 .withMapper([](C2Value v) -> C2Value {
908 int32_t value = 0;
909 (void)v.get(&value);
910 return value == 0 ? C2_FALSE : C2_TRUE;
911 }));
912
913 /* still to do
914 constexpr char KEY_PUSH_BLANK_BUFFERS_ON_STOP[] = "push-blank-buffers-on-shutdown";
915
916 not yet used by MediaCodec, but defined as MediaFormat
917 KEY_AUDIO_SESSION_ID // we use "audio-hw-sync"
918 KEY_OUTPUT_REORDER_DEPTH
919 */
920 }
921
initialize(const std::shared_ptr<C2ParamReflector> & reflector,const std::shared_ptr<Codec2Client::Configurable> & configurable)922 status_t CCodecConfig::initialize(
923 const std::shared_ptr<C2ParamReflector> &reflector,
924 const std::shared_ptr<Codec2Client::Configurable> &configurable) {
925 C2ComponentDomainSetting domain(C2Component::DOMAIN_OTHER);
926 C2ComponentKindSetting kind(C2Component::KIND_OTHER);
927
928 std::vector<std::unique_ptr<C2Param>> queried;
929 c2_status_t c2err = configurable->query({ &domain, &kind }, {}, C2_DONT_BLOCK, &queried);
930 if (c2err != C2_OK) {
931 ALOGD("Query domain & kind failed => %s", asString(c2err));
932 // TEMP: determine kind from component name
933 if (kind.value == C2Component::KIND_OTHER) {
934 if (configurable->getName().find("encoder") != std::string::npos) {
935 kind.value = C2Component::KIND_ENCODER;
936 } else if (configurable->getName().find("decoder") != std::string::npos) {
937 kind.value = C2Component::KIND_DECODER;
938 }
939 }
940
941 // TEMP: determine domain from media type (port (preferred) or stream #0)
942 if (domain.value == C2Component::DOMAIN_OTHER) {
943 AString mediaType = QueryMediaType(true /* input */, configurable);
944 if (mediaType.startsWith("audio/")) {
945 domain.value = C2Component::DOMAIN_AUDIO;
946 } else if (mediaType.startsWith("video/")) {
947 domain.value = C2Component::DOMAIN_VIDEO;
948 } else if (mediaType.startsWith("image/")) {
949 domain.value = C2Component::DOMAIN_IMAGE;
950 }
951 }
952 }
953
954 mDomain = (domain.value == C2Component::DOMAIN_VIDEO ? Domain::IS_VIDEO :
955 domain.value == C2Component::DOMAIN_IMAGE ? Domain::IS_IMAGE :
956 domain.value == C2Component::DOMAIN_AUDIO ? Domain::IS_AUDIO : Domain::OTHER_DOMAIN)
957 | (kind.value == C2Component::KIND_DECODER ? Domain::IS_DECODER :
958 kind.value == C2Component::KIND_ENCODER ? Domain::IS_ENCODER : Domain::OTHER_KIND);
959
960 mInputDomain = Domain(((mDomain & IS_DECODER) ? IS_CODED : IS_RAW) | IS_INPUT);
961 mOutputDomain = Domain(((mDomain & IS_ENCODER) ? IS_CODED : IS_RAW) | IS_OUTPUT);
962
963 ALOGV("domain is %#x (%u %u)", mDomain, domain.value, kind.value);
964
965 std::vector<C2Param::Index> paramIndices;
966 switch (kind.value) {
967 case C2Component::KIND_DECODER:
968 mCodingMediaType = QueryMediaType(true /* input */, configurable).c_str();
969 break;
970 case C2Component::KIND_ENCODER:
971 mCodingMediaType = QueryMediaType(false /* input */, configurable).c_str();
972 break;
973 default:
974 mCodingMediaType = "";
975 }
976
977 c2err = configurable->querySupportedParams(&mParamDescs);
978 if (c2err != C2_OK) {
979 ALOGD("Query supported params failed after returning %zu values => %s",
980 mParamDescs.size(), asString(c2err));
981 return UNKNOWN_ERROR;
982 }
983 for (const std::shared_ptr<C2ParamDescriptor> &desc : mParamDescs) {
984 mSupportedIndices.emplace(desc->index());
985 }
986
987 mReflector = reflector;
988 if (mReflector == nullptr) {
989 ALOGE("Null param reflector");
990 return UNKNOWN_ERROR;
991 }
992
993 // enumerate all fields
994 mParamUpdater = std::make_shared<ReflectedParamUpdater>();
995 mParamUpdater->clear();
996 mParamUpdater->supportWholeParam(
997 C2_PARAMKEY_TEMPORAL_LAYERING, C2StreamTemporalLayeringTuning::CORE_INDEX);
998 mParamUpdater->addParamDesc(mReflector, mParamDescs);
999
1000 // TEMP: add some standard fields even if not reflected
1001 if (kind.value == C2Component::KIND_ENCODER) {
1002 mParamUpdater->addStandardParam<C2StreamInitDataInfo::output>(C2_PARAMKEY_INIT_DATA);
1003 }
1004 if (domain.value == C2Component::DOMAIN_IMAGE || domain.value == C2Component::DOMAIN_VIDEO) {
1005 if (kind.value != C2Component::KIND_ENCODER) {
1006 addLocalParam<C2StreamPictureSizeInfo::output>(C2_PARAMKEY_PICTURE_SIZE);
1007 addLocalParam<C2StreamCropRectInfo::output>(C2_PARAMKEY_CROP_RECT);
1008 addLocalParam(
1009 new C2StreamPixelAspectRatioInfo::output(0u, 1u, 1u),
1010 C2_PARAMKEY_PIXEL_ASPECT_RATIO);
1011 addLocalParam(new C2StreamRotationInfo::output(0u, 0), C2_PARAMKEY_ROTATION);
1012 addLocalParam(new C2StreamColorAspectsInfo::output(0u), C2_PARAMKEY_COLOR_ASPECTS);
1013 addLocalParam<C2StreamDataSpaceInfo::output>(C2_PARAMKEY_DATA_SPACE);
1014 addLocalParam<C2StreamHdrStaticInfo::output>(C2_PARAMKEY_HDR_STATIC_INFO);
1015 addLocalParam(new C2StreamSurfaceScalingInfo::output(0u, VIDEO_SCALING_MODE_SCALE_TO_FIT),
1016 C2_PARAMKEY_SURFACE_SCALING_MODE);
1017 } else {
1018 addLocalParam(new C2StreamColorAspectsInfo::input(0u), C2_PARAMKEY_COLOR_ASPECTS);
1019 }
1020 }
1021
1022 initializeStandardParams();
1023
1024 // subscribe to all supported standard (exposed) params
1025 // TODO: limit this to params that are actually in the domain
1026 std::vector<std::string> formatKeys = mStandardParams->getPathsForDomain(Domain(1 << 30));
1027 std::vector<C2Param::Index> indices;
1028 mParamUpdater->getParamIndicesForKeys(formatKeys, &indices);
1029 mSubscribedIndices.insert(indices.begin(), indices.end());
1030
1031 // also subscribe to some non-SDK standard parameters
1032 // for number of input/output buffers
1033 mSubscribedIndices.emplace(C2PortSuggestedBufferCountTuning::input::PARAM_TYPE);
1034 mSubscribedIndices.emplace(C2PortSuggestedBufferCountTuning::output::PARAM_TYPE);
1035 mSubscribedIndices.emplace(C2ActualPipelineDelayTuning::PARAM_TYPE);
1036 mSubscribedIndices.emplace(C2PortActualDelayTuning::input::PARAM_TYPE);
1037 mSubscribedIndices.emplace(C2PortActualDelayTuning::output::PARAM_TYPE);
1038 // for output buffer array allocation
1039 mSubscribedIndices.emplace(C2StreamMaxBufferSizeInfo::output::PARAM_TYPE);
1040 // init data (CSD)
1041 mSubscribedIndices.emplace(C2StreamInitDataInfo::output::PARAM_TYPE);
1042
1043 for (const std::shared_ptr<C2ParamDescriptor> &desc : mParamDescs) {
1044 if (desc->index().isVendor()) {
1045 std::vector<std::string> keys;
1046 mParamUpdater->getKeysForParamIndex(desc->index(), &keys);
1047 for (const std::string &key : keys) {
1048 mVendorParamIndices.insert_or_assign(key, desc->index());
1049 }
1050 }
1051 }
1052
1053 return OK;
1054 }
1055
subscribeToConfigUpdate(const std::shared_ptr<Codec2Client::Configurable> & configurable,const std::vector<C2Param::Index> & indices,c2_blocking_t blocking)1056 status_t CCodecConfig::subscribeToConfigUpdate(
1057 const std::shared_ptr<Codec2Client::Configurable> &configurable,
1058 const std::vector<C2Param::Index> &indices,
1059 c2_blocking_t blocking) {
1060 mSubscribedIndices.insert(indices.begin(), indices.end());
1061 // TODO: enable this when components no longer crash on this config
1062 if (mSubscribedIndices.size() != mSubscribedIndicesSize && false) {
1063 std::vector<uint32_t> indices;
1064 for (C2Param::Index ix : mSubscribedIndices) {
1065 indices.push_back(ix);
1066 }
1067 std::unique_ptr<C2SubscribedParamIndicesTuning> subscribeTuning =
1068 C2SubscribedParamIndicesTuning::AllocUnique(indices);
1069 std::vector<std::unique_ptr<C2SettingResult>> results;
1070 c2_status_t c2Err = configurable->config({ subscribeTuning.get() }, blocking, &results);
1071 if (c2Err != C2_OK && c2Err != C2_BAD_INDEX) {
1072 ALOGD("Failed to subscribe to parameters => %s", asString(c2Err));
1073 // TODO: error
1074 }
1075 ALOGV("Subscribed to %zu params", mSubscribedIndices.size());
1076 mSubscribedIndicesSize = mSubscribedIndices.size();
1077 }
1078 return OK;
1079 }
1080
queryConfiguration(const std::shared_ptr<Codec2Client::Configurable> & configurable)1081 status_t CCodecConfig::queryConfiguration(
1082 const std::shared_ptr<Codec2Client::Configurable> &configurable) {
1083 // query all subscribed parameters
1084 std::vector<C2Param::Index> indices(mSubscribedIndices.begin(), mSubscribedIndices.end());
1085 std::vector<std::unique_ptr<C2Param>> queried;
1086 c2_status_t c2Err = configurable->query({}, indices, C2_MAY_BLOCK, &queried);
1087 if (c2Err != OK) {
1088 ALOGI("query failed after returning %zu values (%s)", queried.size(), asString(c2Err));
1089 // TODO: error
1090 }
1091
1092 updateConfiguration(queried, ALL);
1093 return OK;
1094 }
1095
updateConfiguration(std::vector<std::unique_ptr<C2Param>> & configUpdate,Domain domain)1096 bool CCodecConfig::updateConfiguration(
1097 std::vector<std::unique_ptr<C2Param>> &configUpdate, Domain domain) {
1098 ALOGV("updating configuration with %zu params", configUpdate.size());
1099 bool changed = false;
1100 for (std::unique_ptr<C2Param> &p : configUpdate) {
1101 if (p && *p) {
1102 auto insertion = mCurrentConfig.emplace(p->index(), nullptr);
1103 if (insertion.second || *insertion.first->second != *p) {
1104 if (mSupportedIndices.count(p->index()) || mLocalParams.count(p->index())) {
1105 // only track changes in supported (reflected or local) indices
1106 changed = true;
1107 } else {
1108 ALOGV("an unlisted config was %s: %#x",
1109 insertion.second ? "added" : "updated", p->index());
1110 }
1111 }
1112 insertion.first->second = std::move(p);
1113 }
1114 }
1115
1116 ALOGV("updated configuration has %zu params (%s)", mCurrentConfig.size(),
1117 changed ? "CHANGED" : "no change");
1118 if (changed) {
1119 return updateFormats(domain);
1120 }
1121 return false;
1122 }
1123
updateFormats(Domain domain)1124 bool CCodecConfig::updateFormats(Domain domain) {
1125 // get addresses of params in the current config
1126 std::vector<C2Param*> paramPointers;
1127 for (const auto &it : mCurrentConfig) {
1128 paramPointers.push_back(it.second.get());
1129 }
1130
1131 ReflectedParamUpdater::Dict reflected = mParamUpdater->getParams(paramPointers);
1132 std::string config = reflected.debugString();
1133 std::set<std::string> configLines;
1134 std::string diff;
1135 for (size_t start = 0; start != std::string::npos; ) {
1136 size_t end = config.find('\n', start);
1137 size_t count = (end == std::string::npos)
1138 ? std::string::npos
1139 : end - start + 1;
1140 std::string line = config.substr(start, count);
1141 configLines.insert(line);
1142 if (mLastConfig.count(line) == 0) {
1143 diff.append(line);
1144 }
1145 start = (end == std::string::npos) ? std::string::npos : end + 1;
1146 }
1147 if (!diff.empty()) {
1148 ALOGD("c2 config diff is %s", diff.c_str());
1149 }
1150 mLastConfig.swap(configLines);
1151
1152 bool changed = false;
1153 if (domain & mInputDomain) {
1154 sp<AMessage> oldFormat = mInputFormat;
1155 mInputFormat = mInputFormat->dup(); // trigger format changed
1156 mInputFormat->extend(getFormatForDomain(reflected, mInputDomain));
1157 if (mInputFormat->countEntries() != oldFormat->countEntries()
1158 || mInputFormat->changesFrom(oldFormat)->countEntries() > 0) {
1159 changed = true;
1160 } else {
1161 mInputFormat = oldFormat; // no change
1162 }
1163 }
1164 if (domain & mOutputDomain) {
1165 sp<AMessage> oldFormat = mOutputFormat;
1166 mOutputFormat = mOutputFormat->dup(); // trigger output format changed
1167 mOutputFormat->extend(getFormatForDomain(reflected, mOutputDomain));
1168 if (mOutputFormat->countEntries() != oldFormat->countEntries()
1169 || mOutputFormat->changesFrom(oldFormat)->countEntries() > 0) {
1170 changed = true;
1171 } else {
1172 mOutputFormat = oldFormat; // no change
1173 }
1174 }
1175 ALOGV_IF(changed, "format(s) changed");
1176 return changed;
1177 }
1178
getFormatForDomain(const ReflectedParamUpdater::Dict & reflected,Domain portDomain) const1179 sp<AMessage> CCodecConfig::getFormatForDomain(
1180 const ReflectedParamUpdater::Dict &reflected,
1181 Domain portDomain) const {
1182 sp<AMessage> msg = new AMessage;
1183 for (const std::pair<std::string, std::vector<ConfigMapper>> &el : mStandardParams->getKeys()) {
1184 for (const ConfigMapper &cm : el.second) {
1185 if ((cm.domain() & portDomain) == 0 // input-output-coded-raw
1186 || (cm.domain() & mDomain) != mDomain // component domain + kind (these must match)
1187 || (cm.domain() & IS_READ) == 0) {
1188 continue;
1189 }
1190 auto it = reflected.find(cm.path());
1191 if (it == reflected.end()) {
1192 continue;
1193 }
1194 C2Value c2Value;
1195 sp<ABuffer> bufValue;
1196 AString strValue;
1197 AMessage::ItemData item;
1198 if (it->second.find(&c2Value)) {
1199 item = cm.mapToMessage(c2Value);
1200 } else if (it->second.find(&bufValue)) {
1201 item.set(bufValue);
1202 } else if (it->second.find(&strValue)) {
1203 item.set(strValue);
1204 } else {
1205 ALOGD("unexpected untyped query value for key: %s", cm.path().c_str());
1206 continue;
1207 }
1208 msg->setItem(el.first.c_str(), item);
1209 }
1210 }
1211
1212 bool input = (portDomain & Domain::IS_INPUT);
1213 std::vector<std::string> vendorKeys;
1214 for (const std::pair<std::string, ReflectedParamUpdater::Value> &entry : reflected) {
1215 auto it = mVendorParamIndices.find(entry.first);
1216 if (it == mVendorParamIndices.end()) {
1217 continue;
1218 }
1219 if (mSubscribedIndices.count(it->second) == 0) {
1220 continue;
1221 }
1222 // For vendor parameters, we only care about direction
1223 if ((input && !it->second.forInput())
1224 || (!input && !it->second.forOutput())) {
1225 continue;
1226 }
1227 const ReflectedParamUpdater::Value &value = entry.second;
1228 C2Value c2Value;
1229 sp<ABuffer> bufValue;
1230 AString strValue;
1231 AMessage::ItemData item;
1232 if (value.find(&c2Value)) {
1233 C2ValueToMessageItem(c2Value, item);
1234 } else if (value.find(&bufValue)) {
1235 item.set(bufValue);
1236 } else if (value.find(&strValue)) {
1237 item.set(strValue);
1238 } else {
1239 ALOGD("unexpected untyped query value for key: %s", entry.first.c_str());
1240 continue;
1241 }
1242 msg->setItem(entry.first.c_str(), item);
1243 }
1244
1245 { // convert from Codec 2.0 rect to MediaFormat rect and add crop rect if not present
1246 int32_t left, top, width, height;
1247 if (msg->findInt32("crop-left", &left) && msg->findInt32("crop-width", &width)
1248 && msg->findInt32("crop-top", &top) && msg->findInt32("crop-height", &height)
1249 && left >= 0 && width >=0 && width <= INT32_MAX - left
1250 && top >= 0 && height >=0 && height <= INT32_MAX - top) {
1251 msg->removeEntryAt(msg->findEntryByName("crop-left"));
1252 msg->removeEntryAt(msg->findEntryByName("crop-top"));
1253 msg->removeEntryAt(msg->findEntryByName("crop-width"));
1254 msg->removeEntryAt(msg->findEntryByName("crop-height"));
1255 msg->setRect("crop", left, top, left + width - 1, top + height - 1);
1256 } else if (msg->findInt32("width", &width) && msg->findInt32("height", &height)) {
1257 msg->setRect("crop", 0, 0, width - 1, height - 1);
1258 }
1259 }
1260
1261 { // convert temporal layering to schema
1262 sp<ABuffer> tmp;
1263 if (msg->findBuffer(C2_PARAMKEY_TEMPORAL_LAYERING, &tmp) && tmp != nullptr) {
1264 C2StreamTemporalLayeringTuning *layering =
1265 C2StreamTemporalLayeringTuning::From(C2Param::From(tmp->data(), tmp->size()));
1266 if (layering && layering->m.layerCount > 0
1267 && layering->m.bLayerCount < layering->m.layerCount) {
1268 // check if this is webrtc compatible
1269 AString mime;
1270 if (msg->findString(KEY_MIME, &mime) &&
1271 mime.equalsIgnoreCase(MIMETYPE_VIDEO_VP8) &&
1272 layering->m.bLayerCount == 0 &&
1273 (layering->m.layerCount == 1
1274 || (layering->m.layerCount == 2
1275 && layering->flexCount() >= 1
1276 && layering->m.bitrateRatios[0] == .6f)
1277 || (layering->m.layerCount == 3
1278 && layering->flexCount() >= 2
1279 && layering->m.bitrateRatios[0] == .4f
1280 && layering->m.bitrateRatios[1] == .6f)
1281 || (layering->m.layerCount == 4
1282 && layering->flexCount() >= 3
1283 && layering->m.bitrateRatios[0] == .25f
1284 && layering->m.bitrateRatios[1] == .4f
1285 && layering->m.bitrateRatios[2] == .6f))) {
1286 msg->setString(KEY_TEMPORAL_LAYERING, AStringPrintf(
1287 "webrtc.vp8.%u-layer", layering->m.layerCount));
1288 } else if (layering->m.bLayerCount) {
1289 msg->setString(KEY_TEMPORAL_LAYERING, AStringPrintf(
1290 "android.generic.%u+%u",
1291 layering->m.layerCount - layering->m.bLayerCount,
1292 layering->m.bLayerCount));
1293 } else if (layering->m.bLayerCount) {
1294 msg->setString(KEY_TEMPORAL_LAYERING, AStringPrintf(
1295 "android.generic.%u", layering->m.layerCount));
1296 }
1297 }
1298 msg->removeEntryAt(msg->findEntryByName(C2_PARAMKEY_TEMPORAL_LAYERING));
1299 }
1300 }
1301
1302 { // convert color info
1303 C2Color::primaries_t primaries;
1304 C2Color::matrix_t matrix;
1305 if (msg->findInt32("color-primaries", (int32_t*)&primaries)
1306 && msg->findInt32("color-matrix", (int32_t*)&matrix)) {
1307 int32_t standard;
1308
1309 if (C2Mapper::map(primaries, matrix, &standard)) {
1310 msg->setInt32(KEY_COLOR_STANDARD, standard);
1311 }
1312
1313 msg->removeEntryAt(msg->findEntryByName("color-primaries"));
1314 msg->removeEntryAt(msg->findEntryByName("color-matrix"));
1315 }
1316
1317
1318 // calculate dataspace for raw graphic buffers if not specified by component, or if
1319 // using surface with unspecified aspects (as those must be defaulted which may change
1320 // the dataspace)
1321 if ((portDomain & IS_RAW) && (mDomain & (IS_IMAGE | IS_VIDEO))) {
1322 android_dataspace dataspace;
1323 ColorAspects aspects = {
1324 ColorAspects::RangeUnspecified, ColorAspects::PrimariesUnspecified,
1325 ColorAspects::TransferUnspecified, ColorAspects::MatrixUnspecified
1326 };
1327 ColorUtils::getColorAspectsFromFormat(msg, aspects);
1328 ColorAspects origAspects = aspects;
1329 if (mUsingSurface) {
1330 // get image size (default to HD)
1331 int32_t width = 1280;
1332 int32_t height = 720;
1333 int32_t left, top, right, bottom;
1334 if (msg->findRect("crop", &left, &top, &right, &bottom)) {
1335 width = right - left + 1;
1336 height = bottom - top + 1;
1337 } else {
1338 (void)msg->findInt32(KEY_WIDTH, &width);
1339 (void)msg->findInt32(KEY_HEIGHT, &height);
1340 }
1341 ColorUtils::setDefaultCodecColorAspectsIfNeeded(aspects, width, height);
1342 ColorUtils::setColorAspectsIntoFormat(aspects, msg);
1343 }
1344
1345 if (!msg->findInt32("android._dataspace", (int32_t*)&dataspace)
1346 || aspects.mRange != origAspects.mRange
1347 || aspects.mPrimaries != origAspects.mPrimaries
1348 || aspects.mTransfer != origAspects.mTransfer
1349 || aspects.mMatrixCoeffs != origAspects.mMatrixCoeffs) {
1350 dataspace = ColorUtils::getDataSpaceForColorAspects(aspects, true /* mayExpand */);
1351 msg->setInt32("android._dataspace", dataspace);
1352 }
1353 }
1354
1355 // HDR static info
1356
1357 C2HdrStaticMetadataStruct hdr;
1358 if (msg->findFloat("smpte2086.red.x", &hdr.mastering.red.x)
1359 && msg->findFloat("smpte2086.red.y", &hdr.mastering.red.y)
1360 && msg->findFloat("smpte2086.green.x", &hdr.mastering.green.x)
1361 && msg->findFloat("smpte2086.green.y", &hdr.mastering.green.y)
1362 && msg->findFloat("smpte2086.blue.x", &hdr.mastering.blue.x)
1363 && msg->findFloat("smpte2086.blue.y", &hdr.mastering.blue.y)
1364 && msg->findFloat("smpte2086.white.x", &hdr.mastering.white.x)
1365 && msg->findFloat("smpte2086.white.y", &hdr.mastering.white.y)
1366 && msg->findFloat("smpte2086.max-luminance", &hdr.mastering.maxLuminance)
1367 && msg->findFloat("smpte2086.min-luminance", &hdr.mastering.minLuminance)
1368 && msg->findFloat("cta861.max-cll", &hdr.maxCll)
1369 && msg->findFloat("cta861.max-fall", &hdr.maxFall)) {
1370 if (hdr.mastering.red.x >= 0 && hdr.mastering.red.x <= 1
1371 && hdr.mastering.red.y >= 0 && hdr.mastering.red.y <= 1
1372 && hdr.mastering.green.x >= 0 && hdr.mastering.green.x <= 1
1373 && hdr.mastering.green.y >= 0 && hdr.mastering.green.y <= 1
1374 && hdr.mastering.blue.x >= 0 && hdr.mastering.blue.x <= 1
1375 && hdr.mastering.blue.y >= 0 && hdr.mastering.blue.y <= 1
1376 && hdr.mastering.white.x >= 0 && hdr.mastering.white.x <= 1
1377 && hdr.mastering.white.y >= 0 && hdr.mastering.white.y <= 1
1378 && hdr.mastering.maxLuminance >= 0 && hdr.mastering.maxLuminance <= 65535
1379 && hdr.mastering.minLuminance >= 0 && hdr.mastering.minLuminance <= 6.5535
1380 && hdr.maxCll >= 0 && hdr.maxCll <= 65535
1381 && hdr.maxFall >= 0 && hdr.maxFall <= 65535) {
1382 HDRStaticInfo meta;
1383 meta.mID = meta.kType1;
1384 meta.sType1.mR.x = hdr.mastering.red.x / 0.00002 + 0.5;
1385 meta.sType1.mR.y = hdr.mastering.red.y / 0.00002 + 0.5;
1386 meta.sType1.mG.x = hdr.mastering.green.x / 0.00002 + 0.5;
1387 meta.sType1.mG.y = hdr.mastering.green.y / 0.00002 + 0.5;
1388 meta.sType1.mB.x = hdr.mastering.blue.x / 0.00002 + 0.5;
1389 meta.sType1.mB.y = hdr.mastering.blue.y / 0.00002 + 0.5;
1390 meta.sType1.mW.x = hdr.mastering.white.x / 0.00002 + 0.5;
1391 meta.sType1.mW.y = hdr.mastering.white.y / 0.00002 + 0.5;
1392 meta.sType1.mMaxDisplayLuminance = hdr.mastering.maxLuminance + 0.5;
1393 meta.sType1.mMinDisplayLuminance = hdr.mastering.minLuminance / 0.0001 + 0.5;
1394 meta.sType1.mMaxContentLightLevel = hdr.maxCll + 0.5;
1395 meta.sType1.mMaxFrameAverageLightLevel = hdr.maxFall + 0.5;
1396 msg->removeEntryAt(msg->findEntryByName("smpte2086.red.x"));
1397 msg->removeEntryAt(msg->findEntryByName("smpte2086.red.y"));
1398 msg->removeEntryAt(msg->findEntryByName("smpte2086.green.x"));
1399 msg->removeEntryAt(msg->findEntryByName("smpte2086.green.y"));
1400 msg->removeEntryAt(msg->findEntryByName("smpte2086.blue.x"));
1401 msg->removeEntryAt(msg->findEntryByName("smpte2086.blue.y"));
1402 msg->removeEntryAt(msg->findEntryByName("smpte2086.white.x"));
1403 msg->removeEntryAt(msg->findEntryByName("smpte2086.white.y"));
1404 msg->removeEntryAt(msg->findEntryByName("smpte2086.max-luminance"));
1405 msg->removeEntryAt(msg->findEntryByName("smpte2086.min-luminance"));
1406 msg->removeEntryAt(msg->findEntryByName("cta861.max-cll"));
1407 msg->removeEntryAt(msg->findEntryByName("cta861.max-fall"));
1408 msg->setBuffer(KEY_HDR_STATIC_INFO, ABuffer::CreateAsCopy(&meta, sizeof(meta)));
1409 } else {
1410 ALOGD("found invalid HDR static metadata %s", msg->debugString(8).c_str());
1411 }
1412 }
1413 }
1414
1415 ALOGV("converted to SDK values as %s", msg->debugString().c_str());
1416 return msg;
1417 }
1418
1419 /// converts an AMessage value to a ParamUpdater value
convert(const AMessage::ItemData & from,ReflectedParamUpdater::Value * to)1420 static void convert(const AMessage::ItemData &from, ReflectedParamUpdater::Value *to) {
1421 int32_t int32Value;
1422 int64_t int64Value;
1423 sp<ABuffer> bufValue;
1424 AString strValue;
1425 float floatValue;
1426 double doubleValue;
1427
1428 if (from.find(&int32Value)) {
1429 to->set(int32Value);
1430 } else if (from.find(&int64Value)) {
1431 to->set(int64Value);
1432 } else if (from.find(&bufValue)) {
1433 to->set(bufValue);
1434 } else if (from.find(&strValue)) {
1435 to->set(strValue);
1436 } else if (from.find(&floatValue)) {
1437 to->set(C2Value(floatValue));
1438 } else if (from.find(&doubleValue)) {
1439 // convert double to float
1440 to->set(C2Value((float)doubleValue));
1441 }
1442 // ignore all other AMessage types
1443 }
1444
1445 /// relaxes Codec 2.0 specific value types to SDK types (mainly removes signedness and counterness
1446 /// from 32/64-bit values.)
relaxValues(ReflectedParamUpdater::Value & item)1447 static void relaxValues(ReflectedParamUpdater::Value &item) {
1448 C2Value c2Value;
1449 int32_t int32Value;
1450 int64_t int64Value;
1451 (void)item.find(&c2Value);
1452 if (c2Value.get(&int32Value) || c2Value.get((uint32_t*)&int32Value)
1453 || c2Value.get((c2_cntr32_t*)&int32Value)) {
1454 item.set(int32Value);
1455 } else if (c2Value.get(&int64Value)
1456 || c2Value.get((uint64_t*)&int64Value)
1457 || c2Value.get((c2_cntr64_t*)&int64Value)) {
1458 item.set(int64Value);
1459 }
1460 }
1461
getReflectedFormat(const sp<AMessage> & params_,Domain configDomain) const1462 ReflectedParamUpdater::Dict CCodecConfig::getReflectedFormat(
1463 const sp<AMessage> ¶ms_, Domain configDomain) const {
1464 // create a modifiable copy of params
1465 sp<AMessage> params = params_->dup();
1466 ALOGV("filtering with config domain %x", configDomain);
1467
1468 // convert some macro parameters to Codec 2.0 specific expressions
1469
1470 { // make i-frame-interval frame based
1471 float iFrameInterval;
1472 if (params->findAsFloat(KEY_I_FRAME_INTERVAL, &iFrameInterval)) {
1473 float frameRate;
1474 if (params->findAsFloat(KEY_FRAME_RATE, &frameRate)) {
1475 params->setInt32("i-frame-period",
1476 (frameRate <= 0 || iFrameInterval < 0)
1477 ? -1 /* no sync frames */
1478 : (int32_t)c2_min(iFrameInterval * frameRate + 0.5,
1479 (float)INT32_MAX));
1480 }
1481 }
1482 }
1483
1484 if (mDomain == (IS_VIDEO | IS_ENCODER)) {
1485 // convert capture-rate into input-time-stretch
1486 float frameRate, captureRate;
1487 if (params->findAsFloat(KEY_FRAME_RATE, &frameRate)) {
1488 if (!params->findAsFloat("time-lapse-fps", &captureRate)
1489 && !params->findAsFloat(KEY_CAPTURE_RATE, &captureRate)) {
1490 captureRate = frameRate;
1491 }
1492 if (captureRate > 0 && frameRate > 0) {
1493 params->setFloat(C2_PARAMKEY_INPUT_TIME_STRETCH, captureRate / frameRate);
1494 }
1495 }
1496 }
1497
1498 { // reflect temporal layering into a binary blob
1499 AString schema;
1500 if (params->findString(KEY_TEMPORAL_LAYERING, &schema)) {
1501 unsigned int numLayers = 0;
1502 unsigned int numBLayers = 0;
1503 int tags;
1504 char dummy;
1505 std::unique_ptr<C2StreamTemporalLayeringTuning::output> layering;
1506 if (sscanf(schema.c_str(), "webrtc.vp8.%u-layer%c", &numLayers, &dummy) == 1
1507 && numLayers > 0) {
1508 switch (numLayers) {
1509 case 1:
1510 layering = C2StreamTemporalLayeringTuning::output::AllocUnique(
1511 {}, 0u, 1u, 0u);
1512 break;
1513 case 2:
1514 layering = C2StreamTemporalLayeringTuning::output::AllocUnique(
1515 { .6f }, 0u, 2u, 0u);
1516 break;
1517 case 3:
1518 layering = C2StreamTemporalLayeringTuning::output::AllocUnique(
1519 { .4f, .6f }, 0u, 3u, 0u);
1520 break;
1521 default:
1522 layering = C2StreamTemporalLayeringTuning::output::AllocUnique(
1523 { .25f, .4f, .6f }, 0u, 4u, 0u);
1524 break;
1525 }
1526 } else if ((tags = sscanf(schema.c_str(), "android.generic.%u%c%u%c",
1527 &numLayers, &dummy, &numBLayers, &dummy))
1528 && (tags == 1 || (tags == 3 && dummy == '+'))
1529 && numLayers > 0 && numLayers < UINT32_MAX - numBLayers) {
1530 layering = C2StreamTemporalLayeringTuning::output::AllocUnique(
1531 {}, 0u, numLayers + numBLayers, numBLayers);
1532 } else {
1533 ALOGD("Ignoring unsupported ts-schema [%s]", schema.c_str());
1534 }
1535 if (layering) {
1536 params->setBuffer(C2_PARAMKEY_TEMPORAL_LAYERING,
1537 ABuffer::CreateAsCopy(layering.get(), layering->size()));
1538 }
1539 }
1540 }
1541
1542 { // convert from MediaFormat rect to Codec 2.0 rect
1543 int32_t offset;
1544 int32_t end;
1545 AMessage::ItemData item;
1546 if (params->findInt32("crop-left", &offset) && params->findInt32("crop-right", &end)
1547 && offset >= 0 && end >= offset - 1) {
1548 size_t ix = params->findEntryByName("crop-right");
1549 params->setEntryNameAt(ix, "crop-width");
1550 item.set(end - offset + 1);
1551 params->setEntryAt(ix, item);
1552 }
1553 if (params->findInt32("crop-top", &offset) && params->findInt32("crop-bottom", &end)
1554 && offset >= 0 && end >= offset - 1) {
1555 size_t ix = params->findEntryByName("crop-bottom");
1556 params->setEntryNameAt(ix, "crop-height");
1557 item.set(end - offset + 1);
1558 params->setEntryAt(ix, item);
1559 }
1560 }
1561
1562 { // convert color info
1563 int32_t standard;
1564 if (params->findInt32(KEY_COLOR_STANDARD, &standard)) {
1565 C2Color::primaries_t primaries;
1566 C2Color::matrix_t matrix;
1567
1568 if (C2Mapper::map(standard, &primaries, &matrix)) {
1569 params->setInt32("color-primaries", primaries);
1570 params->setInt32("color-matrix", matrix);
1571 }
1572 }
1573
1574 sp<ABuffer> hdrMeta;
1575 if (params->findBuffer(KEY_HDR_STATIC_INFO, &hdrMeta)
1576 && hdrMeta->size() == sizeof(HDRStaticInfo)) {
1577 HDRStaticInfo *meta = (HDRStaticInfo*)hdrMeta->data();
1578 if (meta->mID == meta->kType1) {
1579 params->setFloat("smpte2086.red.x", meta->sType1.mR.x * 0.00002);
1580 params->setFloat("smpte2086.red.y", meta->sType1.mR.y * 0.00002);
1581 params->setFloat("smpte2086.green.x", meta->sType1.mG.x * 0.00002);
1582 params->setFloat("smpte2086.green.y", meta->sType1.mG.y * 0.00002);
1583 params->setFloat("smpte2086.blue.x", meta->sType1.mB.x * 0.00002);
1584 params->setFloat("smpte2086.blue.y", meta->sType1.mB.y * 0.00002);
1585 params->setFloat("smpte2086.white.x", meta->sType1.mW.x * 0.00002);
1586 params->setFloat("smpte2086.white.y", meta->sType1.mW.y * 0.00002);
1587 params->setFloat("smpte2086.max-luminance", meta->sType1.mMaxDisplayLuminance);
1588 params->setFloat("smpte2086.min-luminance", meta->sType1.mMinDisplayLuminance * 0.0001);
1589 params->setFloat("cta861.max-cll", meta->sType1.mMaxContentLightLevel);
1590 params->setFloat("cta861.max-fall", meta->sType1.mMaxFrameAverageLightLevel);
1591 }
1592 }
1593 }
1594
1595 // this is to verify that we set proper signedness for standard parameters
1596 bool beVeryStrict = property_get_bool("debug.stagefright.ccodec_strict_type", false);
1597 // this is to allow vendors to use the wrong signedness for standard parameters
1598 bool beVeryLax = property_get_bool("debug.stagefright.ccodec_lax_type", false);
1599
1600 ReflectedParamUpdater::Dict filtered;
1601 for (size_t ix = 0; ix < params->countEntries(); ++ix) {
1602 AMessage::Type type;
1603 AString name = params->getEntryNameAt(ix, &type);
1604 AMessage::ItemData msgItem = params->getEntryAt(ix);
1605 ReflectedParamUpdater::Value item;
1606 convert(msgItem, &item); // convert item to param updater item
1607
1608 if (name.startsWith("vendor.")) {
1609 // vendor params pass through as is
1610 filtered.emplace(name.c_str(), item);
1611 continue;
1612 }
1613 // standard parameters may get modified, filtered or duplicated
1614 for (const ConfigMapper &cm : mStandardParams->getConfigMappersForSdkKey(name.c_str())) {
1615 // note: we ignore port domain for configuration
1616 if ((cm.domain() & configDomain)
1617 // component domain + kind (these must match)
1618 && (cm.domain() & mDomain) == mDomain) {
1619 // map arithmetic values, pass through string or buffer
1620 switch (type) {
1621 case AMessage::kTypeBuffer:
1622 case AMessage::kTypeString:
1623 break;
1624 case AMessage::kTypeInt32:
1625 case AMessage::kTypeInt64:
1626 case AMessage::kTypeFloat:
1627 case AMessage::kTypeDouble:
1628 // for now only map settings with mappers as we are not creating
1629 // signed <=> unsigned mappers
1630 // TODO: be precise about signed unsigned
1631 if (beVeryStrict || cm.mapper()) {
1632 item.set(cm.mapFromMessage(params->getEntryAt(ix)));
1633 // also allow to relax type strictness
1634 if (beVeryLax) {
1635 relaxValues(item);
1636 }
1637 }
1638 break;
1639 default:
1640 continue;
1641 }
1642 filtered.emplace(cm.path(), item);
1643 }
1644 }
1645 }
1646 ALOGV("filtered %s to %s", params->debugString(4).c_str(),
1647 filtered.debugString(4).c_str());
1648 return filtered;
1649 }
1650
getConfigUpdateFromSdkParams(std::shared_ptr<Codec2Client::Configurable> configurable,const sp<AMessage> & sdkParams,Domain configDomain,c2_blocking_t blocking,std::vector<std::unique_ptr<C2Param>> * configUpdate) const1651 status_t CCodecConfig::getConfigUpdateFromSdkParams(
1652 std::shared_ptr<Codec2Client::Configurable> configurable,
1653 const sp<AMessage> &sdkParams, Domain configDomain,
1654 c2_blocking_t blocking,
1655 std::vector<std::unique_ptr<C2Param>> *configUpdate) const {
1656 ReflectedParamUpdater::Dict params = getReflectedFormat(sdkParams, configDomain);
1657
1658 std::vector<C2Param::Index> indices;
1659 mParamUpdater->getParamIndicesFromMessage(params, &indices);
1660 if (indices.empty()) {
1661 ALOGD("no recognized params in: %s", params.debugString().c_str());
1662 return OK;
1663 }
1664
1665 configUpdate->clear();
1666 std::vector<C2Param::Index> supportedIndices;
1667 for (C2Param::Index ix : indices) {
1668 if (mSupportedIndices.count(ix)) {
1669 supportedIndices.push_back(ix);
1670 } else if (mLocalParams.count(ix)) {
1671 // query local parameter here
1672 auto it = mCurrentConfig.find(ix);
1673 if (it != mCurrentConfig.end()) {
1674 configUpdate->emplace_back(C2Param::Copy(*it->second));
1675 }
1676 }
1677 }
1678
1679 c2_status_t err = configurable->query({ }, supportedIndices, blocking, configUpdate);
1680 if (err != C2_OK) {
1681 ALOGD("query failed after returning %zu params => %s", configUpdate->size(), asString(err));
1682 }
1683
1684 if (configUpdate->size()) {
1685 mParamUpdater->updateParamsFromMessage(params, configUpdate);
1686 }
1687 return OK;
1688 }
1689
setParameters(std::shared_ptr<Codec2Client::Configurable> configurable,std::vector<std::unique_ptr<C2Param>> & configUpdate,c2_blocking_t blocking)1690 status_t CCodecConfig::setParameters(
1691 std::shared_ptr<Codec2Client::Configurable> configurable,
1692 std::vector<std::unique_ptr<C2Param>> &configUpdate,
1693 c2_blocking_t blocking) {
1694 status_t result = OK;
1695 if (configUpdate.empty()) {
1696 return OK;
1697 }
1698
1699 std::vector<C2Param::Index> indices;
1700 std::vector<C2Param *> paramVector;
1701 for (const std::unique_ptr<C2Param> ¶m : configUpdate) {
1702 if (mSupportedIndices.count(param->index())) {
1703 // component parameter
1704 paramVector.push_back(param.get());
1705 indices.push_back(param->index());
1706 } else if (mLocalParams.count(param->index())) {
1707 // handle local parameter here
1708 LocalParamValidator validator = mLocalParams.find(param->index())->second;
1709 c2_status_t err = C2_OK;
1710 std::unique_ptr<C2Param> copy = C2Param::Copy(*param);
1711 if (validator) {
1712 err = validator(copy);
1713 }
1714 if (err == C2_OK) {
1715 ALOGV("updated local parameter value for %s",
1716 mParamUpdater->getParamName(param->index()).c_str());
1717
1718 mCurrentConfig[param->index()] = std::move(copy);
1719 } else {
1720 ALOGD("failed to set parameter value for %s => %s",
1721 mParamUpdater->getParamName(param->index()).c_str(), asString(err));
1722 result = BAD_VALUE;
1723 }
1724 }
1725 }
1726 // update subscribed param indices
1727 subscribeToConfigUpdate(configurable, indices, blocking);
1728
1729 std::vector<std::unique_ptr<C2SettingResult>> failures;
1730 c2_status_t err = configurable->config(paramVector, blocking, &failures);
1731 if (err != C2_OK) {
1732 ALOGD("config failed => %s", asString(err));
1733 // This is non-fatal.
1734 }
1735 for (const std::unique_ptr<C2SettingResult> &failure : failures) {
1736 switch (failure->failure) {
1737 case C2SettingResult::BAD_VALUE:
1738 ALOGD("Bad parameter value");
1739 result = BAD_VALUE;
1740 break;
1741 default:
1742 ALOGV("failure = %d", int(failure->failure));
1743 break;
1744 }
1745 }
1746
1747 // Re-query parameter values in case config could not update them and update the current
1748 // configuration.
1749 configUpdate.clear();
1750 err = configurable->query({}, indices, blocking, &configUpdate);
1751 if (err != C2_OK) {
1752 ALOGD("query failed after returning %zu params => %s", configUpdate.size(), asString(err));
1753 }
1754 (void)updateConfiguration(configUpdate, ALL);
1755
1756 // TODO: error value
1757 return result;
1758 }
1759
getConfigParameterValue(C2Param::Index index) const1760 const C2Param *CCodecConfig::getConfigParameterValue(C2Param::Index index) const {
1761 auto it = mCurrentConfig.find(index);
1762 if (it == mCurrentConfig.end()) {
1763 return nullptr;
1764 } else {
1765 return it->second.get();
1766 }
1767 }
1768
subscribeToAllVendorParams(const std::shared_ptr<Codec2Client::Configurable> & configurable,c2_blocking_t blocking)1769 status_t CCodecConfig::subscribeToAllVendorParams(
1770 const std::shared_ptr<Codec2Client::Configurable> &configurable,
1771 c2_blocking_t blocking) {
1772 for (const std::pair<std::string, C2Param::Index> &entry : mVendorParamIndices) {
1773 mSubscribedIndices.insert(entry.second);
1774 }
1775 return subscribeToConfigUpdate(configurable, {}, blocking);
1776 }
1777
1778 } // namespace android
1779