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