• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2024, 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 "CodecCapabilities"
19 
20 #include <android-base/strings.h>
21 #include <utils/Log.h>
22 #include <media/CodecCapabilities.h>
23 #include <media/CodecCapabilitiesUtils.h>
24 #include <media/stagefright/foundation/ADebug.h>
25 #include <media/stagefright/foundation/AMessage.h>
26 
27 namespace android {
28 
29 static const int32_t HEVCHighTierLevels =
30         HEVCHighTierLevel1 | HEVCHighTierLevel2 | HEVCHighTierLevel21 | HEVCHighTierLevel3 |
31         HEVCHighTierLevel31 | HEVCHighTierLevel4 | HEVCHighTierLevel41 | HEVCHighTierLevel5 |
32         HEVCHighTierLevel51 | HEVCHighTierLevel52 | HEVCHighTierLevel6 | HEVCHighTierLevel61 |
33         HEVCHighTierLevel62;
34 
35 static const int32_t DEFAULT_MAX_SUPPORTED_INSTANCES = 32;
36 static const int32_t MAX_SUPPORTED_INSTANCES_LIMIT = 256;
37 
38 // must not contain KEY_PROFILE
39 static const std::set<std::pair<std::string, AMessage::Type>> AUDIO_LEVEL_CRITICAL_FORMAT_KEYS = {
40     // We don't set level-specific limits for audio codecs today. Key candidates would
41     // be sample rate, bit rate or channel count.
42     // MediaFormat.KEY_SAMPLE_RATE,
43     // MediaFormat.KEY_CHANNEL_COUNT,
44     // MediaFormat.KEY_BIT_RATE,
45     { KEY_MIME, AMessage::kTypeString }
46 };
47 
48 // CodecCapabilities Features
49 static const std::vector<Feature> DECODER_FEATURES = {
50     Feature(FEATURE_AdaptivePlayback, (1 << 0), true),
51     Feature(FEATURE_SecurePlayback,   (1 << 1), false),
52     Feature(FEATURE_TunneledPlayback, (1 << 2), false),
53     Feature(FEATURE_PartialFrame,     (1 << 3), false),
54     Feature(FEATURE_FrameParsing,     (1 << 4), false),
55     Feature(FEATURE_MultipleFrames,   (1 << 5), false),
56     Feature(FEATURE_DynamicTimestamp, (1 << 6), false),
57     Feature(FEATURE_LowLatency,       (1 << 7), true),
58     Feature(FEATURE_DynamicColorAspects, (1 << 8), true),
59     Feature(FEATURE_DetachedSurface,     (1 << 9), true),
60     // feature to exclude codec from REGULAR codec list
61     Feature(FEATURE_SpecialCodec,     (1 << 30), false, true),
62 };
63 static const std::vector<Feature> ENCODER_FEATURES = {
64     Feature(FEATURE_IntraRefresh, (1 << 0), false),
65     Feature(FEATURE_MultipleFrames, (1 << 1), false),
66     Feature(FEATURE_DynamicTimestamp, (1 << 2), false),
67     Feature(FEATURE_QpBounds, (1 << 3), false),
68     Feature(FEATURE_EncodingStatistics, (1 << 4), false),
69     Feature(FEATURE_HdrEditing, (1 << 5), false),
70     Feature(FEATURE_HlgEditing, (1 << 6), true),
71     Feature(FEATURE_Roi, (1 << 7), true),
72     // feature to exclude codec from REGULAR codec list
73     Feature(FEATURE_SpecialCodec,     (1 << 30), false, true),
74 };
75 
76 // must not contain KEY_PROFILE
77 static const std::set<std::pair<std::string, AMessage::Type>> VIDEO_LEVEL_CRITICAL_FORMAT_KEYS = {
78     { KEY_WIDTH, AMessage::kTypeInt32 },
79     { KEY_HEIGHT, AMessage::kTypeInt32 },
80     { KEY_FRAME_RATE, AMessage::kTypeInt32 },
81     { KEY_BIT_RATE, AMessage::kTypeInt32 },
82     { KEY_MIME, AMessage::kTypeString }
83 };
84 
SupportsBitrate(Range<int32_t> bitrateRange,const sp<AMessage> & format)85 bool CodecCapabilities::SupportsBitrate(Range<int32_t> bitrateRange,
86         const sp<AMessage> &format) {
87     // consider max bitrate over average bitrate for support
88     int32_t maxBitrate = 0;
89     format->findInt32(KEY_MAX_BIT_RATE, &maxBitrate);
90     int32_t bitrate = 0;
91     format->findInt32(KEY_BIT_RATE, &bitrate);
92 
93     if (bitrate == 0) {
94         bitrate = maxBitrate;
95     } else if (maxBitrate != 0) {
96         bitrate = std::max(bitrate, maxBitrate);
97     }
98 
99     if (bitrate > 0) {
100         return bitrateRange.contains(bitrate);
101     }
102 
103     return true;
104 }
105 
isFeatureSupported(const std::string & name) const106 bool CodecCapabilities::isFeatureSupported(const std::string &name) const {
107     return mFeaturesSupported.contains(name);
108 }
109 
isFeatureRequired(const std::string & name) const110 bool CodecCapabilities::isFeatureRequired(const std::string &name) const {
111     return mFeaturesRequired.contains(name);
112 }
113 
validFeatures() const114 std::vector<std::string> CodecCapabilities::validFeatures() const {
115     std::vector<std::string> res;
116     for (const Feature& feature : getValidFeatures()) {
117         if (!feature.mInternal) {
118             res.push_back(feature.mName);
119         }
120     }
121     return res;
122 }
123 
getValidFeatures() const124 std::vector<Feature> CodecCapabilities::getValidFeatures() const {
125     if (isEncoder()) {
126         return ENCODER_FEATURES;
127     } else {
128         return DECODER_FEATURES;
129     }
130 }
131 
isRegular() const132 bool CodecCapabilities::isRegular() const {
133     // regular codecs only require default features
134     std::vector<Feature> features = getValidFeatures();
135     return std::all_of(features.begin(), features.end(),
136             [this](Feature feat){ return (feat.mDefault || !isFeatureRequired(feat.mName)); });
137 }
138 
isFormatSupported(const sp<AMessage> & format) const139 bool CodecCapabilities::isFormatSupported(const sp<AMessage> &format) const {
140     AString mediaType;
141     format->findString(KEY_MIME, &mediaType);
142     // mediaType must match if present
143     if (!base::EqualsIgnoreCase(mMediaType, mediaType.c_str())) {
144         return false;
145     }
146 
147     // check feature support
148     for (Feature feat: getValidFeatures()) {
149         if (feat.mInternal) {
150             continue;
151         }
152 
153         int32_t yesNo;
154         std::string key = KEY_FEATURE_;
155         key = key + feat.mName;
156         if (!format->findInt32(key.c_str(), &yesNo)) {
157             continue;
158         }
159         if ((yesNo == 1 && !isFeatureSupported(feat.mName)) ||
160                 (yesNo == 0 && isFeatureRequired(feat.mName))) {
161             return false;
162         }
163     }
164 
165     int32_t profile;
166     if (format->findInt32(KEY_PROFILE, &profile)) {
167         int32_t level = -1;
168         format->findInt32(KEY_LEVEL, &level);
169         if (!supportsProfileLevel(profile, level)) {
170             return false;
171         }
172 
173         // If we recognize this profile, check that this format is supported by the
174         // highest level supported by the codec for that profile. (Ignore specified
175         // level beyond the above profile/level check as level is only used as a
176         // guidance. E.g. AVC Level 1 CIF format is supported if codec supports level 1.1
177         // even though max size for Level 1 is QCIF. However, MPEG2 Simple Profile
178         // 1080p format is not supported even if codec supports Main Profile Level High,
179         // as Simple Profile does not support 1080p.
180         int32_t maxLevel = 0;
181         for (ProfileLevel pl : mProfileLevels) {
182             if (pl.mProfile == profile && pl.mLevel > maxLevel) {
183                 // H.263 levels are not completely ordered:
184                 // Level45 support only implies Level10 support
185                 if (!base::EqualsIgnoreCase(mMediaType, MIMETYPE_VIDEO_H263)
186                         || pl.mLevel != H263Level45
187                         || maxLevel == H263Level10) {
188                     maxLevel = pl.mLevel;
189                 }
190             }
191         }
192         std::shared_ptr<CodecCapabilities> levelCaps
193                 = CreateFromProfileLevel(mMediaType, profile, maxLevel);
194         // We must remove the profile from this format otherwise levelCaps.isFormatSupported
195         // will get into this same condition and loop forever. Furthermore, since levelCaps
196         // does not contain features and bitrate specific keys, keep only keys relevant for
197         // a level check.
198         sp<AMessage> levelCriticalFormat = new AMessage;
199 
200         // critical keys will always contain KEY_MIME, but should also contain others to be
201         // meaningful
202         if ((isVideo() || isAudio()) && levelCaps != nullptr) {
203             const std::set<std::pair<std::string, AMessage::Type>> criticalKeys =
204                 isVideo() ? VIDEO_LEVEL_CRITICAL_FORMAT_KEYS : AUDIO_LEVEL_CRITICAL_FORMAT_KEYS;
205             for (std::pair<std::string, AMessage::Type> key : criticalKeys) {
206                 if (format->contains(key.first.c_str())) {
207                     // AMessage::ItemData value = format->findItem(key.c_str());
208                     // levelCriticalFormat->setItem(key.c_str(), value);
209                     switch (key.second) {
210                         case AMessage::kTypeInt32: {
211                             int32_t value;
212                             format->findInt32(key.first.c_str(), &value);
213                             levelCriticalFormat->setInt32(key.first.c_str(), value);
214                             break;
215                         }
216                         case AMessage::kTypeString: {
217                             AString value;
218                             format->findString(key.first.c_str(), &value);
219                             levelCriticalFormat->setString(key.first.c_str(), value);
220                             break;
221                         }
222                         default:
223                             ALOGE("Unsupported type");
224                     }
225                 }
226             }
227             if (!levelCaps->isFormatSupported(levelCriticalFormat)) {
228                 return false;
229             }
230         }
231     }
232     if (mAudioCaps && !mAudioCaps->supportsFormat(format)) {
233         return false;
234     }
235     if (mVideoCaps && !mVideoCaps->supportsFormat(format)) {
236         return false;
237     }
238     if (mEncoderCaps && !mEncoderCaps->supportsFormat(format)) {
239         return false;
240     }
241     return true;
242 }
243 
supportsProfileLevel(int32_t profile,int32_t level) const244 bool CodecCapabilities::supportsProfileLevel(int32_t profile, int32_t level) const {
245     for (ProfileLevel pl: mProfileLevels) {
246         if (pl.mProfile != profile) {
247             continue;
248         }
249 
250         // No specific level requested
251         if (level == -1) {
252             return true;
253         }
254 
255         // AAC doesn't use levels
256         if (base::EqualsIgnoreCase(mMediaType, MIMETYPE_AUDIO_AAC)) {
257             return true;
258         }
259 
260         // DTS doesn't use levels
261         if (base::EqualsIgnoreCase(mMediaType, MIMETYPE_AUDIO_DTS)
262                 || base::EqualsIgnoreCase(mMediaType, MIMETYPE_AUDIO_DTS_HD)
263                 || base::EqualsIgnoreCase(mMediaType, MIMETYPE_AUDIO_DTS_UHD)) {
264             return true;
265         }
266 
267         // H.263 levels are not completely ordered:
268         // Level45 support only implies Level10 support
269         if (base::EqualsIgnoreCase(mMediaType, MIMETYPE_VIDEO_H263)) {
270             if (pl.mLevel != level && pl.mLevel == H263Level45
271                     && level > H263Level10) {
272                 continue;
273             }
274         }
275 
276         // MPEG4 levels are not completely ordered:
277         // Level1 support only implies Level0 (and not Level0b) support
278         if (base::EqualsIgnoreCase(mMediaType, MIMETYPE_VIDEO_MPEG4)) {
279             if (pl.mLevel != level && pl.mLevel == MPEG4Level1
280                     && level > MPEG4Level0) {
281                 continue;
282             }
283         }
284 
285         // HEVC levels incorporate both tiers and levels. Verify tier support.
286         if (base::EqualsIgnoreCase(mMediaType, MIMETYPE_VIDEO_HEVC)) {
287             bool supportsHighTier =
288                 (pl.mLevel & HEVCHighTierLevels) != 0;
289             bool checkingHighTier = (level & HEVCHighTierLevels) != 0;
290             // high tier levels are only supported by other high tier levels
291             if (checkingHighTier && !supportsHighTier) {
292                 continue;
293             }
294         }
295 
296         if (pl.mLevel >= level) {
297             // if we recognize the listed profile/level, we must also recognize the
298             // profile/level arguments.
299             if (CreateFromProfileLevel(mMediaType, profile, pl.mLevel) != nullptr) {
300                 return CreateFromProfileLevel(mMediaType, profile, level) != nullptr;
301             }
302             return true;
303         }
304     }
305     return false;
306 }
307 
getDefaultFormat() const308 sp<AMessage> CodecCapabilities::getDefaultFormat() const {
309     return mDefaultFormat;
310 }
311 
getMediaType()312 const std::string& CodecCapabilities::getMediaType() {
313     return mMediaType;
314 }
315 
getProfileLevels()316 const std::vector<ProfileLevel>& CodecCapabilities::getProfileLevels() {
317     return mProfileLevels;
318 }
319 
getColorFormats() const320 std::vector<uint32_t> CodecCapabilities::getColorFormats() const {
321     return mColorFormats;
322 }
323 
getMaxSupportedInstances() const324 int32_t CodecCapabilities::getMaxSupportedInstances() const {
325     return mMaxSupportedInstances;
326 }
327 
isAudio() const328 bool CodecCapabilities::isAudio() const {
329     return mAudioCaps != nullptr;
330 }
331 
332 std::shared_ptr<AudioCapabilities>
getAudioCapabilities() const333         CodecCapabilities::getAudioCapabilities() const {
334     return mAudioCaps;
335 }
336 
isEncoder() const337 bool CodecCapabilities::isEncoder() const {
338     return mEncoderCaps != nullptr;
339 }
340 
341 std::shared_ptr<EncoderCapabilities>
getEncoderCapabilities() const342         CodecCapabilities::getEncoderCapabilities() const {
343     return mEncoderCaps;
344 }
345 
isVideo() const346 bool CodecCapabilities::isVideo() const {
347     return mVideoCaps != nullptr;
348 }
349 
getVideoCapabilities() const350 std::shared_ptr<VideoCapabilities> CodecCapabilities::getVideoCapabilities() const {
351     return mVideoCaps;
352 }
353 
354 // static
CreateFromProfileLevel(std::string mediaType,int32_t profile,int32_t level,int32_t maxConcurrentInstances)355 std::shared_ptr<CodecCapabilities> CodecCapabilities::CreateFromProfileLevel(
356         std::string mediaType, int32_t profile, int32_t level, int32_t maxConcurrentInstances) {
357     ProfileLevel pl;
358     pl.mProfile = profile;
359     pl.mLevel = level;
360     sp<AMessage> defaultFormat = new AMessage;
361     defaultFormat->setString(KEY_MIME, mediaType.c_str());
362 
363     std::vector<ProfileLevel> pls;
364     pls.push_back(pl);
365     std::vector<uint32_t> colFmts;
366     sp<AMessage> capabilitiesInfo = new AMessage;
367     std::shared_ptr<CodecCapabilities> ret(new CodecCapabilities());
368     ret->init(pls, colFmts, true /* encoder */, defaultFormat, capabilitiesInfo,
369             maxConcurrentInstances);
370     if (ret->getErrors() != 0) {
371         return nullptr;
372     }
373     return ret;
374 }
375 
init(std::vector<ProfileLevel> profLevs,std::vector<uint32_t> colFmts,bool encoder,sp<AMessage> & defaultFormat,sp<AMessage> & capabilitiesInfo,int32_t maxConcurrentInstances)376 void CodecCapabilities::init(std::vector<ProfileLevel> profLevs, std::vector<uint32_t> colFmts,
377         bool encoder, sp<AMessage> &defaultFormat, sp<AMessage> &capabilitiesInfo,
378         int32_t maxConcurrentInstances) {
379     mColorFormats = colFmts;
380     mDefaultFormat = defaultFormat;
381     mCapabilitiesInfo = capabilitiesInfo;
382 
383     AString mediaTypeAStr;
384     mDefaultFormat->findString(KEY_MIME, &mediaTypeAStr);
385     mMediaType = mediaTypeAStr.c_str();
386 
387     /* VP9 introduced profiles around 2016, so some VP9 codecs may not advertise any
388        supported profiles. Determine the level for them using the info they provide. */
389     if (profLevs.size() == 0 && mMediaType == MIMETYPE_VIDEO_VP9) {
390         ProfileLevel profLev;
391         profLev.mProfile = VP9Profile0;
392         profLev.mLevel = VideoCapabilities::EquivalentVP9Level(capabilitiesInfo);
393         profLevs.push_back(profLev);
394     }
395     mProfileLevels = profLevs;
396 
397     if (mediaTypeAStr.startsWithIgnoreCase("audio/")) {
398         mAudioCaps = AudioCapabilities::Create(mMediaType, profLevs, capabilitiesInfo);
399         mAudioCaps->getDefaultFormat(mDefaultFormat);
400     } else if (mediaTypeAStr.startsWithIgnoreCase("video/")
401             || mediaTypeAStr.equalsIgnoreCase(MIMETYPE_IMAGE_ANDROID_HEIC)) {
402         mVideoCaps = VideoCapabilities::Create(mMediaType, profLevs, capabilitiesInfo);
403     }
404 
405     if (encoder) {
406         mEncoderCaps = EncoderCapabilities::Create(mMediaType, profLevs, capabilitiesInfo);
407         mEncoderCaps->getDefaultFormat(mDefaultFormat);
408     }
409 
410     mMaxSupportedInstances = maxConcurrentInstances > 0
411             ? maxConcurrentInstances : DEFAULT_MAX_SUPPORTED_INSTANCES;
412     AString maxConcurrentInstancesStr;
413     int32_t maxInstances
414             = capabilitiesInfo->findString("max-concurrent-instances", &maxConcurrentInstancesStr)
415             ? (int32_t)strtol(maxConcurrentInstancesStr.c_str(), NULL, 10)
416             : mMaxSupportedInstances;
417     mMaxSupportedInstances =
418             Range(1, MAX_SUPPORTED_INSTANCES_LIMIT).clamp(maxInstances);
419 
420     mFeaturesRequired.clear();
421     mFeaturesSupported.clear();
422     for (Feature feat: getValidFeatures()) {
423         std::string key = KEY_FEATURE_;
424         key = key + feat.mName;
425         int yesNo = -1;
426         if (!capabilitiesInfo->findInt32(key.c_str(), &yesNo)) {
427             continue;
428         }
429         if (yesNo > 0) {
430             mFeaturesRequired.insert(feat.mName);
431         }
432         mFeaturesSupported.insert(feat.mName);
433         if (!feat.mInternal) {
434             mDefaultFormat->setInt32(key.c_str(), 1);
435         }
436     }
437 }
438 
getErrors() const439 int32_t CodecCapabilities::getErrors() const {
440     if (mAudioCaps) {
441         return mAudioCaps->mError;
442     } else if (mVideoCaps) {
443         return mVideoCaps->mError;
444     }
445     return 0;
446 }
447 
448 }  // namespace android