1 /*
2  * Copyright (C) 2019 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_TAG "HeicEncoderInfoManager"
18 //#define LOG_NDEBUG 0
19 
20 #include <cstdint>
21 #include <regex>
22 
23 #include <cutils/properties.h>
24 #include <log/log_main.h>
25 #include <system/graphics.h>
26 
27 #include <media/stagefright/MediaCodecList.h>
28 #include <media/stagefright/foundation/MediaDefs.h>
29 #include <media/stagefright/foundation/ABuffer.h>
30 
31 #include "HeicEncoderInfoManager.h"
32 
33 namespace android {
34 namespace camera3 {
35 
HeicEncoderInfoManager()36 HeicEncoderInfoManager::HeicEncoderInfoManager() :
37         mIsInited(false),
38         mMinSizeHeic(0, 0),
39         mMaxSizeHeic(INT32_MAX, INT32_MAX),
40         mHasHEVC(false),
41         mHasHEIC(false),
42         mDisableGrid(false) {
43     if (initialize() == OK) {
44         mIsInited = true;
45     }
46 }
47 
~HeicEncoderInfoManager()48 HeicEncoderInfoManager::~HeicEncoderInfoManager() {
49 }
50 
isSizeSupported(int32_t width,int32_t height,bool * useHeic,bool * useGrid,int64_t * stall,AString * hevcName) const51 bool HeicEncoderInfoManager::isSizeSupported(int32_t width, int32_t height, bool* useHeic,
52         bool* useGrid, int64_t* stall, AString* hevcName) const {
53     if (useHeic == nullptr || useGrid == nullptr) {
54         ALOGE("%s: invalid parameters: useHeic %p, useGrid %p",
55                 __FUNCTION__, useHeic, useGrid);
56         return false;
57     }
58     if (!mIsInited) return false;
59 
60     bool chooseHeic = false, enableGrid = true;
61     if (mHasHEIC && width >= mMinSizeHeic.first &&
62             height >= mMinSizeHeic.second && width <= mMaxSizeHeic.first &&
63             height <= mMaxSizeHeic.second) {
64         chooseHeic = true;
65         enableGrid = false;
66     } else if (mHasHEVC) {
67         bool fullSizeSupportedByHevc = (width >= mMinSizeHevc.first &&
68                 height >= mMinSizeHevc.second &&
69                 width <= mMaxSizeHevc.first &&
70                 height <= mMaxSizeHevc.second);
71         if (fullSizeSupportedByHevc && (mDisableGrid ||
72                 (width <= 1920 && height <= 1080))) {
73             enableGrid = false;
74         }
75         if (hevcName != nullptr) {
76             *hevcName = mHevcName;
77         }
78     } else {
79         // No encoder available for the requested size.
80         return false;
81     }
82 
83     if (stall != nullptr) {
84         // Find preferred encoder which advertise
85         // "measured-frame-rate-WIDTHxHEIGHT-range" key.
86         const FrameRateMaps& maps =
87                 (chooseHeic && mHeicFrameRateMaps.size() > 0) ?
88                 mHeicFrameRateMaps : mHevcFrameRateMaps;
89         const auto& closestSize = findClosestSize(maps, width, height);
90         if (closestSize == maps.end()) {
91             // The "measured-frame-rate-WIDTHxHEIGHT-range" key is optional.
92             // Hardcode to some default value (3.33ms * tile count) based on resolution.
93             *stall = 3333333LL * width * height / (kGridWidth * kGridHeight);
94             return true;
95         }
96 
97         // Derive stall durations based on average fps of the closest size.
98         constexpr int64_t NSEC_PER_SEC = 1000000000LL;
99         int32_t avgFps = (closestSize->second.first + closestSize->second.second)/2;
100         float ratio = 1.0f * width * height /
101                 (closestSize->first.first * closestSize->first.second);
102         *stall = ratio * NSEC_PER_SEC / avgFps;
103     }
104 
105     *useHeic = chooseHeic;
106     *useGrid = enableGrid;
107     return true;
108 }
109 
initialize()110 status_t HeicEncoderInfoManager::initialize() {
111     mDisableGrid = property_get_bool("camera.heic.disable_grid", false);
112     sp<IMediaCodecList> codecsList = MediaCodecList::getInstance();
113     if (codecsList == nullptr) {
114         // No media codec available.
115         return OK;
116     }
117 
118     sp<AMessage> heicDetails = getCodecDetails(codecsList, MEDIA_MIMETYPE_IMAGE_ANDROID_HEIC);
119 
120     if (!getHevcCodecDetails(codecsList, MEDIA_MIMETYPE_VIDEO_HEVC)) {
121         if (heicDetails != nullptr) {
122             ALOGE("%s: Device must support HEVC codec if HEIC codec is available!",
123                     __FUNCTION__);
124             return BAD_VALUE;
125         }
126         return OK;
127     }
128     mHasHEVC = true;
129 
130     // HEIC size range
131     if (heicDetails != nullptr) {
132         auto res = getCodecSizeRange(MEDIA_MIMETYPE_IMAGE_ANDROID_HEIC,
133                 heicDetails, &mMinSizeHeic, &mMaxSizeHeic, &mHeicFrameRateMaps);
134         if (res != OK) {
135             ALOGE("%s: Failed to get HEIC codec size range: %s (%d)", __FUNCTION__,
136                     strerror(-res), res);
137             return BAD_VALUE;
138         }
139         mHasHEIC = true;
140     }
141 
142     return OK;
143 }
144 
getFrameRateMaps(sp<AMessage> details,FrameRateMaps * maps)145 status_t HeicEncoderInfoManager::getFrameRateMaps(sp<AMessage> details, FrameRateMaps* maps) {
146     if (details == nullptr || maps == nullptr) {
147         ALOGE("%s: Invalid input: details: %p, maps: %p", __FUNCTION__, details.get(), maps);
148         return BAD_VALUE;
149     }
150 
151     for (size_t i = 0; i < details->countEntries(); i++) {
152         AMessage::Type type;
153         const char* entryName = details->getEntryNameAt(i, &type);
154         if (type != AMessage::kTypeString) continue;
155         std::regex frameRateNamePattern("measured-frame-rate-([0-9]+)[*x]([0-9]+)-range",
156                 std::regex_constants::icase);
157         std::cmatch sizeMatch;
158         if (std::regex_match(entryName, sizeMatch, frameRateNamePattern) &&
159                 sizeMatch.size() == 3) {
160             AMessage::ItemData item = details->getEntryAt(i);
161             AString fpsRangeStr;
162             if (item.find(&fpsRangeStr)) {
163                 ALOGV("%s: %s", entryName, fpsRangeStr.c_str());
164                 std::regex frameRatePattern("([0-9]+)-([0-9]+)");
165                 std::cmatch fpsMatch;
166                 if (std::regex_match(fpsRangeStr.c_str(), fpsMatch, frameRatePattern) &&
167                         fpsMatch.size() == 3) {
168                     maps->emplace(
169                             std::make_pair(stoi(sizeMatch[1]), stoi(sizeMatch[2])),
170                             std::make_pair(stoi(fpsMatch[1]), stoi(fpsMatch[2])));
171                 } else {
172                     return BAD_VALUE;
173                 }
174             }
175         }
176     }
177     return OK;
178 }
179 
getCodecSizeRange(const char * codecName,sp<AMessage> details,std::pair<int32_t,int32_t> * minSize,std::pair<int32_t,int32_t> * maxSize,FrameRateMaps * frameRateMaps)180 status_t HeicEncoderInfoManager::getCodecSizeRange(
181         const char* codecName,
182         sp<AMessage> details,
183         std::pair<int32_t, int32_t>* minSize,
184         std::pair<int32_t, int32_t>* maxSize,
185         FrameRateMaps* frameRateMaps) {
186     if (codecName == nullptr || minSize == nullptr || maxSize == nullptr ||
187             details == nullptr || frameRateMaps == nullptr) {
188         return BAD_VALUE;
189     }
190 
191     AString sizeRange;
192     auto hasItem = details->findString("size-range", &sizeRange);
193     if (!hasItem) {
194         ALOGE("%s: Failed to query size range for codec %s", __FUNCTION__, codecName);
195         return BAD_VALUE;
196     }
197     ALOGV("%s: %s codec's size range is %s", __FUNCTION__, codecName, sizeRange.c_str());
198     std::regex pattern("([0-9]+)[*x]([0-9]+)-([0-9]+)[*x]([0-9]+)");
199     std::cmatch match;
200     if (std::regex_match(sizeRange.c_str(), match, pattern)) {
201         if (match.size() == 5) {
202             minSize->first = stoi(match[1]);
203             minSize->second = stoi(match[2]);
204             maxSize->first = stoi(match[3]);
205             maxSize->second = stoi(match[4]);
206             if (minSize->first > maxSize->first ||
207                     minSize->second > maxSize->second) {
208                 ALOGE("%s: Invalid %s code size range: %s",
209                         __FUNCTION__, codecName, sizeRange.c_str());
210                 return BAD_VALUE;
211             }
212         } else {
213             return BAD_VALUE;
214         }
215     }
216 
217     auto res = getFrameRateMaps(details, frameRateMaps);
218     if (res != OK) {
219         return res;
220     }
221 
222     return OK;
223 }
224 
findClosestSize(const FrameRateMaps & maps,int32_t width,int32_t height) const225 HeicEncoderInfoManager::FrameRateMaps::const_iterator HeicEncoderInfoManager::findClosestSize(
226         const FrameRateMaps& maps, int32_t width, int32_t height) const {
227     int32_t minDiff = INT32_MAX;
228     FrameRateMaps::const_iterator closestIter = maps.begin();
229     for (auto iter = maps.begin(); iter != maps.end(); iter++) {
230         // Use area difference between the sizes to approximate size
231         // difference.
232         int32_t diff = abs(iter->first.first * iter->first.second - width * height);
233         if (diff < minDiff) {
234             closestIter = iter;
235             minDiff = diff;
236         }
237     }
238     return closestIter;
239 }
240 
getCodecDetails(sp<IMediaCodecList> codecsList,const char * name)241 sp<AMessage> HeicEncoderInfoManager::getCodecDetails(
242         sp<IMediaCodecList> codecsList, const char* name) {
243     ssize_t idx = codecsList->findCodecByType(name, true /*encoder*/);
244     if (idx < 0) {
245         return nullptr;
246     }
247 
248     const sp<MediaCodecInfo> info = codecsList->getCodecInfo(idx);
249     if (info == nullptr) {
250         ALOGE("%s: Failed to get codec info for %s", __FUNCTION__, name);
251         return nullptr;
252     }
253     const sp<MediaCodecInfo::Capabilities> caps =
254             info->getCapabilitiesFor(name);
255     if (caps == nullptr) {
256         ALOGE("%s: Failed to get capabilities for codec %s", __FUNCTION__, name);
257         return nullptr;
258     }
259     const sp<AMessage> details = caps->getDetails();
260     if (details == nullptr) {
261         ALOGE("%s: Failed to get details for codec %s", __FUNCTION__, name);
262         return nullptr;
263     }
264 
265     return details;
266 }
267 
getHevcCodecDetails(sp<IMediaCodecList> codecsList,const char * mime)268 bool HeicEncoderInfoManager::getHevcCodecDetails(
269         sp<IMediaCodecList> codecsList, const char* mime) {
270     bool found = false;
271     ssize_t idx = 0;
272     while ((idx = codecsList->findCodecByType(mime, true /*encoder*/, idx)) >= 0) {
273         const sp<MediaCodecInfo> info = codecsList->getCodecInfo(idx++);
274         if (info == nullptr) {
275             ALOGE("%s: Failed to get codec info for %s", __FUNCTION__, mime);
276             break;
277         }
278 
279         // Filter out software ones as they may be too slow
280         if (!(info->getAttributes() & MediaCodecInfo::kFlagIsHardwareAccelerated)) {
281             continue;
282         }
283 
284         const sp<MediaCodecInfo::Capabilities> caps =
285                 info->getCapabilitiesFor(mime);
286         if (caps == nullptr) {
287             ALOGE("%s: [%s] Failed to get capabilities", __FUNCTION__,
288                     info->getCodecName());
289             break;
290         }
291         const sp<AMessage> details = caps->getDetails();
292         if (details == nullptr) {
293             ALOGE("%s: [%s] Failed to get details", __FUNCTION__,
294                     info->getCodecName());
295             break;
296         }
297 
298         // Check CQ mode
299         AString bitrateModes;
300         auto hasItem = details->findString("feature-bitrate-modes", &bitrateModes);
301         if (!hasItem) {
302             ALOGE("%s: [%s] Failed to query bitrate modes", __FUNCTION__,
303                     info->getCodecName());
304             break;
305         }
306         ALOGV("%s: [%s] feature-bitrate-modes value is %d, %s",
307                 __FUNCTION__, info->getCodecName(), hasItem, bitrateModes.c_str());
308         std::regex pattern("(^|,)CQ($|,)", std::regex_constants::icase);
309         if (!std::regex_search(bitrateModes.c_str(), pattern)) {
310             continue; // move on to next encoder
311         }
312 
313         std::pair<int32_t, int32_t> minSizeHevc, maxSizeHevc;
314         FrameRateMaps hevcFrameRateMaps;
315         auto res = getCodecSizeRange(MEDIA_MIMETYPE_VIDEO_HEVC,
316                 details, &minSizeHevc, &maxSizeHevc, &hevcFrameRateMaps);
317         if (res != OK) {
318             ALOGE("%s: [%s] Failed to get size range: %s (%d)", __FUNCTION__,
319                     info->getCodecName(), strerror(-res), res);
320             break;
321         }
322         if (kGridWidth < minSizeHevc.first
323                 || kGridWidth > maxSizeHevc.first
324                 || kGridHeight < minSizeHevc.second
325                 || kGridHeight > maxSizeHevc.second) {
326             continue; // move on to next encoder
327         }
328 
329         // Found: save name, size, frame rate
330         mHevcName = info->getCodecName();
331         mMinSizeHevc = minSizeHevc;
332         mMaxSizeHevc = maxSizeHevc;
333         mHevcFrameRateMaps = hevcFrameRateMaps;
334 
335         found = true;
336         break;
337     }
338 
339     return found;
340 }
341 
342 } //namespace camera3
343 } // namespace android
344