xref: /aosp_15_r20/frameworks/av/media/libmedia/CharacterEncodingDetector.cpp (revision ec779b8e0859a360c3d303172224686826e6e0e1)
1 /*
2  * Copyright (C) 2013 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 "CharacterEncodingDector"
19 #include <utils/Log.h>
20 
21 #include <media/CharacterEncodingDetector.h>
22 #include "CharacterEncodingDetectorTables.h"
23 
24 #include <utils/Vector.h>
25 #include <media/StringArray.h>
26 
27 #include <unicode/ucnv.h>
28 #include <unicode/ucsdet.h>
29 #include <unicode/ustring.h>
30 
31 #include <cutils/properties.h>
32 
33 namespace android {
34 
CharacterEncodingDetector()35 CharacterEncodingDetector::CharacterEncodingDetector() {
36 
37     UErrorCode status = U_ZERO_ERROR;
38     mUtf8Conv = ucnv_open("UTF-8", &status);
39     if (U_FAILURE(status)) {
40         ALOGE("could not create UConverter for UTF-8");
41         mUtf8Conv = NULL;
42     }
43 
44     // Read system locale setting from system property and map to ICU encoding names.
45     mLocaleEnc = NULL;
46     char locale_value[PROPERTY_VALUE_MAX] = "";
47     if (property_get("persist.sys.locale", locale_value, NULL) > 0) {
48         const size_t len = strnlen(locale_value, sizeof(locale_value));
49 
50         if (len == 3 && !strncmp(locale_value, "und", 3)) {
51             // Undetermined
52         } else if (!strncmp(locale_value, "th", 2)) { // Thai
53             mLocaleEnc = "windows-874-2000";
54         }
55         if (mLocaleEnc != NULL) {
56             ALOGV("System locale encoding = %s", mLocaleEnc);
57         } else {
58             ALOGV("Didn't recognize system locale setting, defaulting to en_US");
59         }
60     } else {
61         ALOGV("Couldn't read system locale setting, assuming en_US");
62     }
63 }
64 
~CharacterEncodingDetector()65 CharacterEncodingDetector::~CharacterEncodingDetector() {
66     ucnv_close(mUtf8Conv);
67 }
68 
addTag(const char * name,const char * value)69 void CharacterEncodingDetector::addTag(const char *name, const char *value) {
70     mNames.push_back(name);
71     mValues.push_back(value);
72 }
73 
size()74 size_t CharacterEncodingDetector::size() {
75     return mNames.size();
76 }
77 
getTag(int index,const char ** name,const char ** value)78 status_t CharacterEncodingDetector::getTag(int index, const char **name, const char**value) {
79     if (index >= mNames.size()) {
80         return BAD_VALUE;
81     }
82 
83     *name = mNames.getEntry(index);
84     *value = mValues.getEntry(index);
85     return OK;
86 }
87 
isPrintableAscii(const char * value,size_t len)88 static bool isPrintableAscii(const char *value, size_t len) {
89     for (size_t i = 0; i < len; i++) {
90         if ((value[i] & 0x80) || value[i] < 0x20 || value[i] == 0x7f) {
91             return false;
92         }
93     }
94     return true;
95 }
96 
detectAndConvert()97 void CharacterEncodingDetector::detectAndConvert() {
98 
99     int size = mNames.size();
100     ALOGV("%d tags before conversion", size);
101     for (int i = 0; i < size; i++) {
102         ALOGV("%s: %s", mNames.getEntry(i), mValues.getEntry(i));
103     }
104 
105     if (size && mUtf8Conv) {
106 
107         UErrorCode status = U_ZERO_ERROR;
108         UCharsetDetector *csd = ucsdet_open(&status);
109         const UCharsetMatch *ucm;
110         bool goodmatch = true;
111         int highest = 0;
112 
113         // try combined detection of artist/album/title etc.
114         char buf[1024];
115         buf[0] = 0;
116         bool allprintable = true;
117         for (int i = 0; i < size; i++) {
118             const char *name = mNames.getEntry(i);
119             const char *value = mValues.getEntry(i);
120             if (!isPrintableAscii(value, strlen(value)) && (
121                         !strcmp(name, "artist") ||
122                         !strcmp(name, "albumartist") ||
123                         !strcmp(name, "composer") ||
124                         !strcmp(name, "genre") ||
125                         !strcmp(name, "album") ||
126                         !strcmp(name, "title"))) {
127                 strlcat(buf, value, sizeof(buf));
128                 // separate tags by space so ICU's ngram detector can do its job
129                 strlcat(buf, " ", sizeof(buf));
130                 allprintable = false;
131             }
132         }
133 
134         const char *combinedenc = "UTF-8";
135         if (allprintable) {
136             // since 'buf' is empty, ICU would return a UTF-8 matcher with low confidence, so
137             // no need to even call it
138             ALOGV("all tags are printable, assuming ascii (%zu)", strlen(buf));
139         } else {
140             ucsdet_setText(csd, buf, strlen(buf), &status);
141             int32_t matches;
142             const UCharsetMatch** ucma = ucsdet_detectAll(csd, &matches, &status);
143             const UCharsetMatch* bestCombinedMatch = getPreferred(buf, strlen(buf),
144                     ucma, matches, &goodmatch, &highest);
145 
146             ALOGV("goodmatch: %s, highest: %d", goodmatch ? "true" : "false", highest);
147             if (!goodmatch && (highest < 15 || strlen(buf) < 20)) {
148                 ALOGV("not a good match, trying with more data");
149                 // This string might be too short for ICU to do anything useful with.
150                 // (real world example: "Björk" in ISO-8859-1 might be detected as GB18030, because
151                 //  the ISO detector reports a confidence of 0, while the GB18030 detector reports
152                 //  a confidence of 10 with no invalid characters)
153                 // Append artist, album and title if they were previously omitted because they
154                 // were printable ascii.
155                 bool added = false;
156                 for (int i = 0; i < size; i++) {
157                     const char *name = mNames.getEntry(i);
158                     const char *value = mValues.getEntry(i);
159                     if (isPrintableAscii(value, strlen(value)) && (
160                                 !strcmp(name, "artist") ||
161                                 !strcmp(name, "album") ||
162                                 !strcmp(name, "title"))) {
163                         strlcat(buf, value, sizeof(buf));
164                         strlcat(buf, " ", sizeof(buf));
165                         added = true;
166                     }
167                 }
168                 if (added) {
169                     ucsdet_setText(csd, buf, strlen(buf), &status);
170                     ucma = ucsdet_detectAll(csd, &matches, &status);
171                     bestCombinedMatch = getPreferred(buf, strlen(buf),
172                             ucma, matches, &goodmatch, &highest);
173                     if (!goodmatch && highest <= 15) {
174                         ALOGV("still not a good match after adding printable tags");
175                         bestCombinedMatch = NULL;
176                     }
177                 } else {
178                     ALOGV("no printable tags to add");
179                 }
180             }
181 
182             if (mLocaleEnc != NULL && !goodmatch && highest < 50) {
183                 combinedenc = mLocaleEnc;
184                 ALOGV("confidence is low but we have recognized predefined encoding, "
185                         "so try this (%s) instead", mLocaleEnc);
186             } else if (bestCombinedMatch != NULL) {
187                 combinedenc = ucsdet_getName(bestCombinedMatch, &status);
188             } else {
189                 combinedenc = "ISO-8859-1";
190             }
191         }
192 
193         for (int i = 0; i < size; i++) {
194             const char *name = mNames.getEntry(i);
195             uint8_t* src = (uint8_t *)mValues.getEntry(i);
196             int len = strlen((char *)src);
197 
198             ALOGV("@@@ checking %s", name);
199             const char *s = mValues.getEntry(i);
200             int32_t inputLength = strlen(s);
201             // Use encoding determined from the combination of artist/album/title etc.
202             // as default if there is no better match found.
203             const char *enc = combinedenc;
204 
205             if (!allprintable && (!strcmp(name, "artist") ||
206                     !strcmp(name, "albumartist") ||
207                     !strcmp(name, "composer") ||
208                     !strcmp(name, "genre") ||
209                     !strcmp(name, "album") ||
210                     !strcmp(name, "title"))) {
211                 if (!goodmatch && highest < 0) {
212                     // Give it one more chance if there is no good match.
213                     ALOGV("Trying to detect %s separately", name);
214                     int32_t matches;
215                     bool goodmatchSingle = true;
216                     int highestSingle = 0;
217                     ucsdet_setText(csd, s, inputLength, &status);
218                     const UCharsetMatch** ucma = ucsdet_detectAll(csd, &matches, &status);
219                     const UCharsetMatch* bestSingleMatch = getPreferred(s, inputLength,
220                             ucma, matches, &goodmatchSingle, &highestSingle);
221                     // getPreferred could return a null. Check for null before calling
222                     // ucsdet_getName.
223                     if (bestSingleMatch != NULL) {
224                         if (goodmatchSingle || highestSingle > highest)
225                             enc = ucsdet_getName(bestSingleMatch, &status);
226                     }
227                 }
228             } else {
229                 if (isPrintableAscii(s, inputLength)) {
230                     enc = "UTF-8";
231                     ALOGV("@@@@ %s is ascii", mNames.getEntry(i));
232                 } else {
233                     ucsdet_setText(csd, s, inputLength, &status);
234                     ucm = ucsdet_detect(csd, &status);
235                     if (!ucm) {
236                         mValues.setEntry(i, "???");
237                         continue;
238                     }
239                     enc = ucsdet_getName(ucm, &status);
240                     ALOGV("@@@@ recognized charset: %s for %s confidence %d",
241                             enc, mNames.getEntry(i), ucsdet_getConfidence(ucm, &status));
242                 }
243             }
244 
245             if (strcmp(enc,"UTF-8") != 0) {
246                 // only convert if the source encoding isn't already UTF-8
247                 ALOGV("@@@ using converter %s for %s", enc, mNames.getEntry(i));
248                 status = U_ZERO_ERROR;
249                 UConverter *conv = ucnv_open(enc, &status);
250                 if (U_FAILURE(status)) {
251                     ALOGW("could not create UConverter for %s (%d), falling back to ISO-8859-1",
252                             enc, status);
253                     status = U_ZERO_ERROR;
254                     conv = ucnv_open("ISO-8859-1", &status);
255                     if (U_FAILURE(status)) {
256                         ALOGW("could not create UConverter for ISO-8859-1 either");
257                         continue;
258                     }
259                 }
260 
261                 // convert from native encoding to UTF-8
262                 const char* source = mValues.getEntry(i);
263                 int targetLength = len * 3 + 1;
264                 char* buffer = new char[targetLength];
265                 // don't normally check for NULL, but in this case targetLength may be large
266                 if (!buffer)
267                     break;
268                 char* target = buffer;
269 
270                 ucnv_convertEx(mUtf8Conv, conv, &target, target + targetLength,
271                         &source, source + strlen(source),
272                         NULL, NULL, NULL, NULL, true, true, &status);
273 
274                 if (U_FAILURE(status)) {
275                     ALOGE("ucnv_convertEx failed: %d", status);
276                     mValues.setEntry(i, "???");
277                 } else {
278                     // zero terminate
279                     *target = 0;
280                     // strip trailing spaces
281                     while (--target > buffer && *target == ' ') {
282                         *target = 0;
283                     }
284                     // skip leading spaces
285                     char *start = buffer;
286                     while (*start == ' ') {
287                         start++;
288                     }
289                     mValues.setEntry(i, start);
290                 }
291 
292                 delete[] buffer;
293 
294                 ucnv_close(conv);
295             }
296         }
297 
298         for (int i = size - 1; i >= 0; --i) {
299             if (strlen(mValues.getEntry(i)) == 0) {
300                 ALOGV("erasing %s because entry is empty", mNames.getEntry(i));
301                 mNames.erase(i);
302                 mValues.erase(i);
303             }
304         }
305 
306         ucsdet_close(csd);
307     }
308 }
309 
310 /*
311  * When ICU detects multiple encoding matches, apply additional heuristics to determine
312  * which one is the best match, since ICU can't always be trusted to make the right choice.
313  *
314  * What this method does is:
315  * - decode the input using each of the matches found
316  * - recalculate the starting confidence level for multibyte encodings using a different
317  *   algorithm and larger frequent character lists than ICU
318  * - devalue encoding where the conversion contains unlikely characters (symbols, reserved, etc)
319  * - pick the highest match
320  * - signal to the caller whether this match is considered good: confidence > 15, and confidence
321  *   delta with the next runner up > 15
322  */
getPreferred(const char * input,size_t len,const UCharsetMatch ** ucma,size_t nummatches,bool * goodmatch,int * highestmatch)323 const UCharsetMatch *CharacterEncodingDetector::getPreferred(
324         const char *input, size_t len,
325         const UCharsetMatch** ucma, size_t nummatches,
326         bool *goodmatch, int *highestmatch) {
327 
328     *goodmatch = false;
329     Vector<const UCharsetMatch*> matches;
330     UErrorCode status = U_ZERO_ERROR;
331 
332     ALOGV("%zu matches", nummatches);
333     for (size_t i = 0; i < nummatches; i++) {
334         const char *encname = ucsdet_getName(ucma[i], &status);
335         int confidence = ucsdet_getConfidence(ucma[i], &status);
336         ALOGV("%zu: %s %d", i, encname, confidence);
337         matches.push_back(ucma[i]);
338     }
339 
340     size_t num = matches.size();
341     if (num == 0) {
342         return NULL;
343     }
344     if (num == 1) {
345         int confidence = ucsdet_getConfidence(matches[0], &status);
346         if (confidence > 15) {
347             *goodmatch = true;
348         }
349         return matches[0];
350     }
351 
352     ALOGV("considering %zu matches", num);
353 
354     // keep track of how many "special" characters result when converting the input using each
355     // encoding
356     Vector<int> newconfidence;
357     for (size_t i = 0; i < num; i++) {
358         const uint16_t *freqdata = NULL;
359         float freqcoverage = 0;
360         status = U_ZERO_ERROR;
361         const char *encname = ucsdet_getName(matches[i], &status);
362         int confidence = ucsdet_getConfidence(matches[i], &status);
363         if (!strcmp("GB18030", encname)) {
364             freqdata = frequent_zhCN;
365             freqcoverage = frequent_zhCN_coverage;
366         } else if (!strcmp("Big5", encname)) {
367             freqdata = frequent_zhTW;
368             freqcoverage = frequent_zhTW_coverage;
369         } else if (!strcmp("EUC-KR", encname)) {
370             freqdata = frequent_ko;
371             freqcoverage = frequent_ko_coverage;
372         } else if (!strcmp("EUC-JP", encname)) {
373             freqdata = frequent_ja;
374             freqcoverage = frequent_ja_coverage;
375         } else if (!strcmp("Shift_JIS", encname)) {
376             freqdata = frequent_ja;
377             freqcoverage = frequent_ja_coverage;
378         }
379 
380         ALOGV("%zu: %s %d", i, encname, confidence);
381         status = U_ZERO_ERROR;
382         UConverter *conv = ucnv_open(encname, &status);
383         int demerit = 0;
384         if (U_FAILURE(status)) {
385             ALOGV("failed to open %s: %d", encname, status);
386             confidence = 0;
387             demerit += 1000;
388         }
389         const char *source = input;
390         const char *sourceLimit = input + len;
391         status = U_ZERO_ERROR;
392         int frequentchars = 0;
393         int totalchars = 0;
394         while (true) {
395             // demerit the current encoding for each "special" character found after conversion.
396             // The amount of demerit is somewhat arbitrarily chosen.
397             UChar32 c = ucnv_getNextUChar(conv, &source, sourceLimit, &status);
398             if (!U_SUCCESS(status)) {
399                 break;
400             }
401             if (c < 0x20 || (c >= 0x7f && c <= 0x009f)) {
402                 ALOGV("control character %x", c);
403                 demerit += 100;
404             } else if ((c == 0xa0)                      // no-break space
405                     || (c >= 0xa2 && c <= 0xbe)         // symbols, superscripts
406                     || (c == 0xd7) || (c == 0xf7)       // multiplication and division signs
407                     || (c >= 0x2000 && c <= 0x209f)) {  // punctuation, superscripts
408                 ALOGV("unlikely character %x", c);
409                 demerit += 10;
410             } else if (c >= 0xe000 && c <= 0xf8ff) {
411                 ALOGV("private use character %x", c);
412                 demerit += 30;
413             } else if (c >= 0x2190 && c <= 0x2bff) {
414                 // this range comprises various symbol ranges that are unlikely to appear in
415                 // music file metadata.
416                 ALOGV("symbol %x", c);
417                 demerit += 10;
418             } else if (c == 0xfffd) {
419                 ALOGV("replacement character");
420                 demerit += 50;
421             } else if (c >= 0xfff0 && c <= 0xfffc) {
422                 ALOGV("unicode special %x", c);
423                 demerit += 50;
424             } else if (freqdata != NULL) {
425                 totalchars++;
426                 if (isFrequent(freqdata, c)) {
427                     frequentchars++;
428                 }
429             }
430         }
431         if (freqdata != NULL && totalchars != 0) {
432             int myconfidence = 10 + float((100 * frequentchars) / totalchars) / freqcoverage;
433             ALOGV("ICU confidence: %d, my confidence: %d (%d %d)", confidence, myconfidence,
434                     totalchars, frequentchars);
435             if (myconfidence > 100) myconfidence = 100;
436             if (myconfidence < 0) myconfidence = 0;
437             confidence = myconfidence;
438         }
439         ALOGV("%d-%d=%d", confidence, demerit, confidence - demerit);
440         newconfidence.push_back(confidence - demerit);
441         ucnv_close(conv);
442         if (i == 0 && (confidence - demerit) == 100) {
443             // no need to check any further, we'll end up using this match anyway
444             break;
445         }
446     }
447 
448     // find match with highest confidence after adjusting for unlikely characters
449     int highest = newconfidence[0];
450     size_t highestidx = 0;
451     int runnerup = -10000;
452     int runnerupidx = -10000;
453     num = newconfidence.size();
454     for (size_t i = 1; i < num; i++) {
455         if (newconfidence[i] > highest) {
456             runnerup = highest;
457             runnerupidx = highestidx;
458             highest = newconfidence[i];
459             highestidx = i;
460         } else if (newconfidence[i] > runnerup){
461             runnerup = newconfidence[i];
462             runnerupidx = i;
463         }
464     }
465     status = U_ZERO_ERROR;
466     ALOGV("selecting: '%s' w/ %d confidence",
467             ucsdet_getName(matches[highestidx], &status), highest);
468     if (runnerupidx < 0) {
469         ALOGV("no runner up");
470         if (highest > 15) {
471             *goodmatch = true;
472         }
473     } else {
474         ALOGV("runner up: '%s' w/ %d confidence",
475                 ucsdet_getName(matches[runnerupidx], &status), runnerup);
476         if (runnerup < 0) {
477             runnerup = 0;
478         }
479         if ((highest - runnerup) > 15) {
480             *goodmatch = true;
481         }
482     }
483     *highestmatch = highest;
484     return matches[highestidx];
485 }
486 
487 
isFrequent(const uint16_t * values,uint32_t c)488 bool CharacterEncodingDetector::isFrequent(const uint16_t *values, uint32_t c) {
489 
490     int start = 0;
491     int end = 511; // All the tables have 512 entries
492     int mid = (start+end)/2;
493 
494     while(start <= end) {
495         if(c == values[mid]) {
496             return true;
497         } else if (c > values[mid]) {
498             start = mid + 1;
499         } else {
500             end = mid - 1;
501         }
502 
503         mid = (start + end) / 2;
504     }
505 
506     return false;
507 }
508 
509 
510 }  // namespace android
511