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 "Codec2InfoBuilder"
19 #include <log/log.h>
20 
21 #include <strings.h>
22 
23 #include <C2Component.h>
24 #include <C2Config.h>
25 #include <C2Debug.h>
26 #include <C2PlatformSupport.h>
27 #include <Codec2Mapper.h>
28 
29 #include <OMX_Audio.h>
30 #include <OMX_AudioExt.h>
31 #include <OMX_IndexExt.h>
32 #include <OMX_Types.h>
33 #include <OMX_Video.h>
34 #include <OMX_VideoExt.h>
35 #include <OMX_AsString.h>
36 
37 #include <android/hardware/media/omx/1.0/IOmx.h>
38 #include <android/hardware/media/omx/1.0/IOmxObserver.h>
39 #include <android/hardware/media/omx/1.0/IOmxNode.h>
40 #include <android/hardware/media/omx/1.0/types.h>
41 
42 #include <android-base/properties.h>
43 #include <codec2/hidl/client.h>
44 #include <cutils/native_handle.h>
45 #include <media/omx/1.0/WOmxNode.h>
46 #include <media/stagefright/foundation/ALookup.h>
47 #include <media/stagefright/foundation/MediaDefs.h>
48 #include <media/stagefright/omx/OMXUtils.h>
49 #include <media/stagefright/xmlparser/MediaCodecsXmlParser.h>
50 #include <media/stagefright/Codec2InfoBuilder.h>
51 #include <media/stagefright/MediaCodecConstants.h>
52 
53 namespace android {
54 
55 using Traits = C2Component::Traits;
56 
57 namespace /* unnamed */ {
58 
hasPrefix(const std::string & s,const char * prefix)59 bool hasPrefix(const std::string& s, const char* prefix) {
60     size_t prefixLen = strlen(prefix);
61     return s.compare(0, prefixLen, prefix) == 0;
62 }
63 
hasSuffix(const std::string & s,const char * suffix)64 bool hasSuffix(const std::string& s, const char* suffix) {
65     size_t suffixLen = strlen(suffix);
66     return suffixLen > s.size() ? false :
67             s.compare(s.size() - suffixLen, suffixLen, suffix) == 0;
68 }
69 
70 // returns true if component advertised supported profile level(s)
addSupportedProfileLevels(std::shared_ptr<Codec2Client::Interface> intf,MediaCodecInfo::CapabilitiesWriter * caps,const Traits & trait,const std::string & mediaType)71 bool addSupportedProfileLevels(
72         std::shared_ptr<Codec2Client::Interface> intf,
73         MediaCodecInfo::CapabilitiesWriter *caps,
74         const Traits& trait, const std::string &mediaType) {
75     std::shared_ptr<C2Mapper::ProfileLevelMapper> mapper =
76         C2Mapper::GetProfileLevelMapper(trait.mediaType);
77     // if we don't know the media type, pass through all values unmapped
78 
79     // TODO: we cannot find levels that are local 'maxima' without knowing the coding
80     // e.g. H.263 level 45 and level 30 could be two values for highest level as
81     // they don't include one another. For now we use the last supported value.
82     bool encoder = trait.kind == C2Component::KIND_ENCODER;
83     C2StreamProfileLevelInfo pl(encoder /* output */, 0u);
84     std::vector<C2FieldSupportedValuesQuery> profileQuery = {
85         C2FieldSupportedValuesQuery::Possible(C2ParamField(&pl, &pl.profile))
86     };
87 
88     c2_status_t err = intf->querySupportedValues(profileQuery, C2_DONT_BLOCK);
89     ALOGV("query supported profiles -> %s | %s", asString(err), asString(profileQuery[0].status));
90     if (err != C2_OK || profileQuery[0].status != C2_OK) {
91         return false;
92     }
93 
94     // we only handle enumerated values
95     if (profileQuery[0].values.type != C2FieldSupportedValues::VALUES) {
96         return false;
97     }
98 
99     // determine if codec supports HDR
100     bool supportsHdr = false;
101     bool supportsHdr10Plus = false;
102 
103     std::vector<std::shared_ptr<C2ParamDescriptor>> paramDescs;
104     c2_status_t err1 = intf->querySupportedParams(&paramDescs);
105     if (err1 == C2_OK) {
106         for (const std::shared_ptr<C2ParamDescriptor> &desc : paramDescs) {
107             C2Param::Type type = desc->index();
108             // only consider supported parameters on raw ports
109             if (!(encoder ? type.forInput() : type.forOutput())) {
110                 continue;
111             }
112             switch (type.coreIndex()) {
113             case C2StreamHdr10PlusInfo::CORE_INDEX:
114                 supportsHdr10Plus = true;
115                 break;
116             case C2StreamHdrStaticInfo::CORE_INDEX:
117                 supportsHdr = true;
118                 break;
119             default:
120                 break;
121             }
122         }
123     }
124 
125     // For VP9/AV1, the static info is always propagated by framework.
126     supportsHdr |= (mediaType == MIMETYPE_VIDEO_VP9);
127     supportsHdr |= (mediaType == MIMETYPE_VIDEO_AV1);
128 
129     bool added = false;
130 
131     for (C2Value::Primitive profile : profileQuery[0].values.values) {
132         pl.profile = (C2Config::profile_t)profile.ref<uint32_t>();
133         std::vector<std::unique_ptr<C2SettingResult>> failures;
134         err = intf->config({&pl}, C2_DONT_BLOCK, &failures);
135         ALOGV("set profile to %u -> %s", pl.profile, asString(err));
136         std::vector<C2FieldSupportedValuesQuery> levelQuery = {
137             C2FieldSupportedValuesQuery::Current(C2ParamField(&pl, &pl.level))
138         };
139         err = intf->querySupportedValues(levelQuery, C2_DONT_BLOCK);
140         ALOGV("query supported levels -> %s | %s", asString(err), asString(levelQuery[0].status));
141         if (err != C2_OK || levelQuery[0].status != C2_OK
142                 || levelQuery[0].values.type != C2FieldSupportedValues::VALUES
143                 || levelQuery[0].values.values.size() == 0) {
144             continue;
145         }
146 
147         C2Value::Primitive level = levelQuery[0].values.values.back();
148         pl.level = (C2Config::level_t)level.ref<uint32_t>();
149         ALOGV("supporting level: %u", pl.level);
150         int32_t sdkProfile, sdkLevel;
151         if (mapper && mapper->mapProfile(pl.profile, &sdkProfile)
152                 && mapper->mapLevel(pl.level, &sdkLevel)) {
153             caps->addProfileLevel((uint32_t)sdkProfile, (uint32_t)sdkLevel);
154             // also list HDR profiles if component supports HDR
155             if (supportsHdr) {
156                 auto hdrMapper = C2Mapper::GetHdrProfileLevelMapper(trait.mediaType);
157                 if (hdrMapper && hdrMapper->mapProfile(pl.profile, &sdkProfile)) {
158                     caps->addProfileLevel((uint32_t)sdkProfile, (uint32_t)sdkLevel);
159                 }
160                 if (supportsHdr10Plus) {
161                     hdrMapper = C2Mapper::GetHdrProfileLevelMapper(
162                             trait.mediaType, true /*isHdr10Plus*/);
163                     if (hdrMapper && hdrMapper->mapProfile(pl.profile, &sdkProfile)) {
164                         caps->addProfileLevel((uint32_t)sdkProfile, (uint32_t)sdkLevel);
165                     }
166                 }
167             }
168         } else if (!mapper) {
169             caps->addProfileLevel(pl.profile, pl.level);
170         }
171         added = true;
172 
173         // for H.263 also advertise the second highest level if the
174         // codec supports level 45, as level 45 only covers level 10
175         // TODO: move this to some form of a setting so it does not
176         // have to be here
177         if (mediaType == MIMETYPE_VIDEO_H263) {
178             C2Config::level_t nextLevel = C2Config::LEVEL_UNUSED;
179             for (C2Value::Primitive v : levelQuery[0].values.values) {
180                 C2Config::level_t level = (C2Config::level_t)v.ref<uint32_t>();
181                 if (level < C2Config::LEVEL_H263_45 && level > nextLevel) {
182                     nextLevel = level;
183                 }
184             }
185             if (nextLevel != C2Config::LEVEL_UNUSED
186                     && nextLevel != pl.level
187                     && mapper
188                     && mapper->mapProfile(pl.profile, &sdkProfile)
189                     && mapper->mapLevel(nextLevel, &sdkLevel)) {
190                 caps->addProfileLevel(
191                         (uint32_t)sdkProfile, (uint32_t)sdkLevel);
192             }
193         }
194     }
195     return added;
196 }
197 
addSupportedColorFormats(std::shared_ptr<Codec2Client::Interface> intf,MediaCodecInfo::CapabilitiesWriter * caps,const Traits & trait,const std::string & mediaType)198 void addSupportedColorFormats(
199         std::shared_ptr<Codec2Client::Interface> intf,
200         MediaCodecInfo::CapabilitiesWriter *caps,
201         const Traits& trait, const std::string &mediaType) {
202     (void)intf;
203 
204     // TODO: get this from intf() as well, but how do we map them to
205     // MediaCodec color formats?
206     bool encoder = trait.kind == C2Component::KIND_ENCODER;
207     if (mediaType.find("video") != std::string::npos
208             || mediaType.find("image") != std::string::npos) {
209         // vendor video codecs prefer opaque format
210         if (trait.name.find("android") == std::string::npos) {
211             caps->addColorFormat(COLOR_FormatSurface);
212         }
213         caps->addColorFormat(COLOR_FormatYUV420Flexible);
214         caps->addColorFormat(COLOR_FormatYUV420Planar);
215         caps->addColorFormat(COLOR_FormatYUV420SemiPlanar);
216         caps->addColorFormat(COLOR_FormatYUV420PackedPlanar);
217         caps->addColorFormat(COLOR_FormatYUV420PackedSemiPlanar);
218         // framework video encoders must support surface format, though it is unclear
219         // that they will be able to map it if it is opaque
220         if (encoder && trait.name.find("android") != std::string::npos) {
221             caps->addColorFormat(COLOR_FormatSurface);
222         }
223     }
224 }
225 
226 class Switch {
227     enum Flags : uint8_t {
228         // flags
229         IS_ENABLED = (1 << 0),
230         BY_DEFAULT = (1 << 1),
231     };
232 
Switch(uint8_t flags)233     constexpr Switch(uint8_t flags) : mFlags(flags) {}
234 
235     uint8_t mFlags;
236 
237 public:
238     // have to create class due to this bool conversion operator...
239     constexpr operator bool() const {
240         return mFlags & IS_ENABLED;
241     }
242 
operator !() const243     constexpr Switch operator!() const {
244         return Switch(mFlags ^ IS_ENABLED);
245     }
246 
DISABLED()247     static constexpr Switch DISABLED() { return 0; };
ENABLED()248     static constexpr Switch ENABLED() { return IS_ENABLED; };
DISABLED_BY_DEFAULT()249     static constexpr Switch DISABLED_BY_DEFAULT() { return BY_DEFAULT; };
ENABLED_BY_DEFAULT()250     static constexpr Switch ENABLED_BY_DEFAULT() { return IS_ENABLED | BY_DEFAULT; };
251 
toString(const char * def="") const252     const char *toString(const char *def = "??") const {
253         switch (mFlags) {
254         case 0:                         return "0";
255         case IS_ENABLED:                return "1";
256         case BY_DEFAULT:                return "(0)";
257         case IS_ENABLED | BY_DEFAULT:   return "(1)";
258         default: return def;
259         }
260     }
261 
262 };
263 
asString(const Switch & s,const char * def="")264 const char *asString(const Switch &s, const char *def = "??") {
265     return s.toString(def);
266 }
267 
isSettingEnabled(std::string setting,const MediaCodecsXmlParser::AttributeMap & settings,Switch def=Switch::DISABLED_BY_DEFAULT ())268 Switch isSettingEnabled(
269         std::string setting, const MediaCodecsXmlParser::AttributeMap &settings,
270         Switch def = Switch::DISABLED_BY_DEFAULT()) {
271     const auto enablement = settings.find(setting);
272     if (enablement == settings.end()) {
273         return def;
274     }
275     return enablement->second == "1" ? Switch::ENABLED() : Switch::DISABLED();
276 }
277 
isVariantEnabled(std::string variant,const MediaCodecsXmlParser::AttributeMap & settings)278 Switch isVariantEnabled(
279         std::string variant, const MediaCodecsXmlParser::AttributeMap &settings) {
280     return isSettingEnabled("variant-" + variant, settings);
281 }
282 
isVariantExpressionEnabled(std::string exp,const MediaCodecsXmlParser::AttributeMap & settings)283 Switch isVariantExpressionEnabled(
284         std::string exp, const MediaCodecsXmlParser::AttributeMap &settings) {
285     if (!exp.empty() && exp.at(0) == '!') {
286         return !isVariantEnabled(exp.substr(1, exp.size() - 1), settings);
287     }
288     return isVariantEnabled(exp, settings);
289 }
290 
isDomainEnabled(std::string domain,const MediaCodecsXmlParser::AttributeMap & settings)291 Switch isDomainEnabled(
292         std::string domain, const MediaCodecsXmlParser::AttributeMap &settings) {
293     return isSettingEnabled("domain-" + domain, settings);
294 }
295 
296 } // unnamed namespace
297 
buildMediaCodecList(MediaCodecListWriter * writer)298 status_t Codec2InfoBuilder::buildMediaCodecList(MediaCodecListWriter* writer) {
299     // TODO: Remove run-time configurations once all codecs are working
300     // properly. (Assume "full" behavior eventually.)
301     //
302     // debug.stagefright.ccodec supports 5 values.
303     //   0 - No Codec 2.0 components are available.
304     //   1 - Audio decoders and encoders with prefix "c2.android." are available
305     //       and ranked first.
306     //       All other components with prefix "c2.android." are available with
307     //       their normal ranks.
308     //       Components with prefix "c2.vda." are available with their normal
309     //       ranks.
310     //       All other components with suffix ".avc.decoder" or ".avc.encoder"
311     //       are available but ranked last.
312     //   2 - Components with prefix "c2.android." are available and ranked
313     //       first.
314     //       Components with prefix "c2.vda." are available with their normal
315     //       ranks.
316     //       All other components with suffix ".avc.decoder" or ".avc.encoder"
317     //       are available but ranked last.
318     //   3 - Components with prefix "c2.android." are available and ranked
319     //       first.
320     //       All other components are available with their normal ranks.
321     //   4 - All components are available with their normal ranks.
322     //
323     // The default value (boot time) is 1.
324     //
325     // Note: Currently, OMX components have default rank 0x100, while all
326     // Codec2.0 software components have default rank 0x200.
327     int option = ::android::base::GetIntProperty("debug.stagefright.ccodec", 4);
328 
329     // Obtain Codec2Client
330     std::vector<Traits> traits = Codec2Client::ListComponents();
331 
332     // parse APEX XML first, followed by vendor XML.
333     // Note: APEX XML names do not depend on ro.media.xml_variant.* properties.
334     MediaCodecsXmlParser parser;
335     parser.parseXmlFilesInSearchDirs(
336             { "media_codecs.xml", "media_codecs_performance.xml" },
337             { "/apex/com.android.media.swcodec/etc" });
338 
339     // TODO: remove these c2-specific files once product moved to default file names
340     parser.parseXmlFilesInSearchDirs(
341             { "media_codecs_c2.xml", "media_codecs_performance_c2.xml" });
342 
343     // parse default XML files
344     parser.parseXmlFilesInSearchDirs();
345 
346     // The mainline modules for media may optionally include some codec shaping information.
347     // Based on vendor partition SDK, and the brand/product/device information
348     // (expect to be empty in almost always)
349     //
350     {
351         // get build info so we know what file to search
352         // ro.vendor.build.fingerprint
353         std::string fingerprint = base::GetProperty("ro.vendor.build.fingerprint",
354                                                "brand/product/device:");
355         ALOGV("property_get for ro.vendor.build.fingerprint == '%s'", fingerprint.c_str());
356 
357         // ro.vendor.build.version.sdk
358         std::string sdk = base::GetProperty("ro.vendor.build.version.sdk", "0");
359         ALOGV("property_get for ro.vendor.build.version.sdk == '%s'", sdk.c_str());
360 
361         std::string brand;
362         std::string product;
363         std::string device;
364         size_t pos1;
365         pos1 = fingerprint.find('/');
366         if (pos1 != std::string::npos) {
367             brand = fingerprint.substr(0, pos1);
368             size_t pos2 = fingerprint.find('/', pos1+1);
369             if (pos2 != std::string::npos) {
370                 product = fingerprint.substr(pos1+1, pos2 - pos1 - 1);
371                 size_t pos3 = fingerprint.find('/', pos2+1);
372                 if (pos3 != std::string::npos) {
373                     device = fingerprint.substr(pos2+1, pos3 - pos2 - 1);
374                     size_t pos4 = device.find(':');
375                     if (pos4 != std::string::npos) {
376                         device.resize(pos4);
377                     }
378                 }
379             }
380         }
381 
382         ALOGV("parsed: sdk '%s' brand '%s' product '%s' device '%s'",
383             sdk.c_str(), brand.c_str(), product.c_str(), device.c_str());
384 
385         std::string base = "/apex/com.android.media/etc/formatshaper";
386 
387         // looking in these directories within the apex
388         const std::vector<std::string> modulePathnames = {
389             base + "/" + sdk + "/" + brand + "/" + product + "/" + device,
390             base + "/" + sdk + "/" + brand + "/" + product,
391             base + "/" + sdk + "/" + brand,
392             base + "/" + sdk,
393             base
394         };
395 
396         parser.parseXmlFilesInSearchDirs( { "media_codecs_shaping.xml" }, modulePathnames);
397     }
398 
399     if (parser.getParsingStatus() != OK) {
400         ALOGD("XML parser no good");
401         return OK;
402     }
403 
404     MediaCodecsXmlParser::AttributeMap settings = parser.getServiceAttributeMap();
405     for (const auto &v : settings) {
406         if (!hasPrefix(v.first, "media-type-")
407                 && !hasPrefix(v.first, "domain-")
408                 && !hasPrefix(v.first, "variant-")) {
409             writer->addGlobalSetting(v.first.c_str(), v.second.c_str());
410         }
411     }
412 
413     for (const Traits& trait : traits) {
414         C2Component::rank_t rank = trait.rank;
415 
416         // Interface must be accessible for us to list the component, and there also
417         // must be an XML entry for the codec. Codec aliases listed in the traits
418         // allow additional XML entries to be specified for each alias. These will
419         // be listed as separate codecs. If no XML entry is specified for an alias,
420         // those will be treated as an additional alias specified in the XML entry
421         // for the interface name.
422         std::vector<std::string> nameAndAliases = trait.aliases;
423         nameAndAliases.insert(nameAndAliases.begin(), trait.name);
424         for (const std::string &nameOrAlias : nameAndAliases) {
425             bool isAlias = trait.name != nameOrAlias;
426             std::shared_ptr<Codec2Client::Interface> intf =
427                 Codec2Client::CreateInterfaceByName(nameOrAlias.c_str());
428             if (!intf) {
429                 ALOGD("could not create interface for %s'%s'",
430                         isAlias ? "alias " : "",
431                         nameOrAlias.c_str());
432                 continue;
433             }
434             if (parser.getCodecMap().count(nameOrAlias) == 0) {
435                 if (isAlias) {
436                     std::unique_ptr<MediaCodecInfoWriter> baseCodecInfo =
437                         writer->findMediaCodecInfo(trait.name.c_str());
438                     if (!baseCodecInfo) {
439                         ALOGD("alias '%s' not found in xml but canonical codec info '%s' missing",
440                                 nameOrAlias.c_str(),
441                                 trait.name.c_str());
442                     } else {
443                         ALOGD("alias '%s' not found in xml; use an XML <Alias> tag for this",
444                                 nameOrAlias.c_str());
445                         // merge alias into existing codec
446                         baseCodecInfo->addAlias(nameOrAlias.c_str());
447                     }
448                 } else {
449                     ALOGD("component '%s' not found in xml", trait.name.c_str());
450                 }
451                 continue;
452             }
453             std::string canonName = trait.name;
454 
455             // TODO: Remove this block once all codecs are enabled by default.
456             switch (option) {
457             case 0:
458                 continue;
459             case 1:
460                 if (hasPrefix(canonName, "c2.vda.")) {
461                     break;
462                 }
463                 if (hasPrefix(canonName, "c2.android.")) {
464                     if (trait.domain == C2Component::DOMAIN_AUDIO) {
465                         rank = 1;
466                         break;
467                     }
468                     break;
469                 }
470                 if (hasSuffix(canonName, ".avc.decoder") ||
471                         hasSuffix(canonName, ".avc.encoder")) {
472                     rank = std::numeric_limits<decltype(rank)>::max();
473                     break;
474                 }
475                 continue;
476             case 2:
477                 if (hasPrefix(canonName, "c2.vda.")) {
478                     break;
479                 }
480                 if (hasPrefix(canonName, "c2.android.")) {
481                     rank = 1;
482                     break;
483                 }
484                 if (hasSuffix(canonName, ".avc.decoder") ||
485                         hasSuffix(canonName, ".avc.encoder")) {
486                     rank = std::numeric_limits<decltype(rank)>::max();
487                     break;
488                 }
489                 continue;
490             case 3:
491                 if (hasPrefix(canonName, "c2.android.")) {
492                     rank = 1;
493                 }
494                 break;
495             }
496 
497             const MediaCodecsXmlParser::CodecProperties &codec =
498                 parser.getCodecMap().at(nameOrAlias);
499 
500             // verify that either the codec is explicitly enabled, or one of its domains is
501             bool codecEnabled = codec.quirkSet.find("attribute::disabled") == codec.quirkSet.end();
502             if (!codecEnabled) {
503                 for (const std::string &domain : codec.domainSet) {
504                     const Switch enabled = isDomainEnabled(domain, settings);
505                     ALOGV("codec entry '%s' is in domain '%s' that is '%s'",
506                             nameOrAlias.c_str(), domain.c_str(), asString(enabled));
507                     if (enabled) {
508                         codecEnabled = true;
509                         break;
510                     }
511                 }
512             }
513             // if codec has variants, also check that at least one of them is enabled
514             bool variantEnabled = codec.variantSet.empty();
515             for (const std::string &variant : codec.variantSet) {
516                 const Switch enabled = isVariantExpressionEnabled(variant, settings);
517                 ALOGV("codec entry '%s' has a variant '%s' that is '%s'",
518                         nameOrAlias.c_str(), variant.c_str(), asString(enabled));
519                 if (enabled) {
520                     variantEnabled = true;
521                     break;
522                 }
523             }
524             if (!codecEnabled || !variantEnabled) {
525                 ALOGD("codec entry for '%s' is disabled", nameOrAlias.c_str());
526                 continue;
527             }
528 
529             ALOGV("adding codec entry for '%s'", nameOrAlias.c_str());
530             std::unique_ptr<MediaCodecInfoWriter> codecInfo = writer->addMediaCodecInfo();
531             codecInfo->setName(nameOrAlias.c_str());
532             codecInfo->setOwner(("codec2::" + trait.owner).c_str());
533 
534             bool encoder = trait.kind == C2Component::KIND_ENCODER;
535             typename std::underlying_type<MediaCodecInfo::Attributes>::type attrs = 0;
536 
537             if (encoder) {
538                 attrs |= MediaCodecInfo::kFlagIsEncoder;
539             }
540             if (trait.owner == "software") {
541                 attrs |= MediaCodecInfo::kFlagIsSoftwareOnly;
542             } else {
543                 attrs |= MediaCodecInfo::kFlagIsVendor;
544                 if (trait.owner == "vendor-software") {
545                     attrs |= MediaCodecInfo::kFlagIsSoftwareOnly;
546                 } else if (codec.quirkSet.find("attribute::software-codec")
547                         == codec.quirkSet.end()) {
548                     attrs |= MediaCodecInfo::kFlagIsHardwareAccelerated;
549                 }
550             }
551             codecInfo->setAttributes(attrs);
552             if (!codec.rank.empty()) {
553                 uint32_t xmlRank;
554                 char dummy;
555                 if (sscanf(codec.rank.c_str(), "%u%c", &xmlRank, &dummy) == 1) {
556                     rank = xmlRank;
557                 }
558             }
559             ALOGV("rank: %u", (unsigned)rank);
560             codecInfo->setRank(rank);
561 
562             for (const std::string &alias : codec.aliases) {
563                 ALOGV("adding alias '%s'", alias.c_str());
564                 codecInfo->addAlias(alias.c_str());
565             }
566 
567             for (auto typeIt = codec.typeMap.begin(); typeIt != codec.typeMap.end(); ++typeIt) {
568                 const std::string &mediaType = typeIt->first;
569                 const Switch typeEnabled = isSettingEnabled(
570                         "media-type-" + mediaType, settings, Switch::ENABLED_BY_DEFAULT());
571                 const Switch domainTypeEnabled = isSettingEnabled(
572                         "media-type-" + mediaType + (encoder ? "-encoder" : "-decoder"),
573                         settings, Switch::ENABLED_BY_DEFAULT());
574                 ALOGV("type '%s-%s' is '%s/%s'",
575                         mediaType.c_str(), (encoder ? "encoder" : "decoder"),
576                         asString(typeEnabled), asString(domainTypeEnabled));
577                 if (!typeEnabled || !domainTypeEnabled) {
578                     ALOGD("media type '%s' for codec entry '%s' is disabled", mediaType.c_str(),
579                             nameOrAlias.c_str());
580                     continue;
581                 }
582 
583                 ALOGI("adding type '%s'", typeIt->first.c_str());
584                 const MediaCodecsXmlParser::AttributeMap &attrMap = typeIt->second;
585                 std::unique_ptr<MediaCodecInfo::CapabilitiesWriter> caps =
586                     codecInfo->addMediaType(mediaType.c_str());
587                 for (const auto &v : attrMap) {
588                     std::string key = v.first;
589                     std::string value = v.second;
590 
591                     size_t variantSep = key.find(":::");
592                     if (variantSep != std::string::npos) {
593                         std::string variant = key.substr(0, variantSep);
594                         const Switch enabled = isVariantExpressionEnabled(variant, settings);
595                         ALOGV("variant '%s' is '%s'", variant.c_str(), asString(enabled));
596                         if (!enabled) {
597                             continue;
598                         }
599                         key = key.substr(variantSep + 3);
600                     }
601 
602                     if (key.find("feature-") == 0 && key.find("feature-bitrate-modes") != 0) {
603                         int32_t intValue = 0;
604                         // Ignore trailing bad characters and default to 0.
605                         (void)sscanf(value.c_str(), "%d", &intValue);
606                         caps->addDetail(key.c_str(), intValue);
607                     } else {
608                         caps->addDetail(key.c_str(), value.c_str());
609                     }
610                 }
611 
612                 if (!addSupportedProfileLevels(intf, caps.get(), trait, mediaType)) {
613                     // TODO(b/193279646) This will get fixed in C2InterfaceHelper
614                     // Some components may not advertise supported values if they use a const
615                     // param for profile/level (they support only one profile). For now cover
616                     // only VP8 here until it is fixed.
617                     if (mediaType == MIMETYPE_VIDEO_VP8) {
618                         caps->addProfileLevel(VP8ProfileMain, VP8Level_Version0);
619                     }
620                 }
621                 addSupportedColorFormats(intf, caps.get(), trait, mediaType);
622             }
623         }
624     }
625     return OK;
626 }
627 
628 }  // namespace android
629 
CreateBuilder()630 extern "C" android::MediaCodecListBuilderBase *CreateBuilder() {
631     return new android::Codec2InfoBuilder;
632 }
633