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 const char *enc;
202
203 if (!allprintable && (!strcmp(name, "artist") ||
204 !strcmp(name, "albumartist") ||
205 !strcmp(name, "composer") ||
206 !strcmp(name, "genre") ||
207 !strcmp(name, "album") ||
208 !strcmp(name, "title"))) {
209 if (!goodmatch && highest < 0) {
210 // Give it one more chance if there is no good match.
211 ALOGV("Trying to detect %s separately", name);
212 int32_t matches;
213 bool goodmatchSingle = true;
214 int highestSingle = 0;
215 ucsdet_setText(csd, s, inputLength, &status);
216 const UCharsetMatch** ucma = ucsdet_detectAll(csd, &matches, &status);
217 const UCharsetMatch* bestSingleMatch = getPreferred(s, inputLength,
218 ucma, matches, &goodmatchSingle, &highestSingle);
219 if (goodmatchSingle || highestSingle > highest)
220 enc = ucsdet_getName(bestSingleMatch, &status);
221 else
222 enc = combinedenc;
223 } else {
224 // use encoding determined from the combination of artist/album/title etc.
225 enc = combinedenc;
226 }
227 } else {
228 if (isPrintableAscii(s, inputLength)) {
229 enc = "UTF-8";
230 ALOGV("@@@@ %s is ascii", mNames.getEntry(i));
231 } else {
232 ucsdet_setText(csd, s, inputLength, &status);
233 ucm = ucsdet_detect(csd, &status);
234 if (!ucm) {
235 mValues.setEntry(i, "???");
236 continue;
237 }
238 enc = ucsdet_getName(ucm, &status);
239 ALOGV("@@@@ recognized charset: %s for %s confidence %d",
240 enc, mNames.getEntry(i), ucsdet_getConfidence(ucm, &status));
241 }
242 }
243
244 if (strcmp(enc,"UTF-8") != 0) {
245 // only convert if the source encoding isn't already UTF-8
246 ALOGV("@@@ using converter %s for %s", enc, mNames.getEntry(i));
247 status = U_ZERO_ERROR;
248 UConverter *conv = ucnv_open(enc, &status);
249 if (U_FAILURE(status)) {
250 ALOGW("could not create UConverter for %s (%d), falling back to ISO-8859-1",
251 enc, status);
252 status = U_ZERO_ERROR;
253 conv = ucnv_open("ISO-8859-1", &status);
254 if (U_FAILURE(status)) {
255 ALOGW("could not create UConverter for ISO-8859-1 either");
256 continue;
257 }
258 }
259
260 // convert from native encoding to UTF-8
261 const char* source = mValues.getEntry(i);
262 int targetLength = len * 3 + 1;
263 char* buffer = new char[targetLength];
264 // don't normally check for NULL, but in this case targetLength may be large
265 if (!buffer)
266 break;
267 char* target = buffer;
268
269 ucnv_convertEx(mUtf8Conv, conv, &target, target + targetLength,
270 &source, source + strlen(source),
271 NULL, NULL, NULL, NULL, TRUE, TRUE, &status);
272
273 if (U_FAILURE(status)) {
274 ALOGE("ucnv_convertEx failed: %d", status);
275 mValues.setEntry(i, "???");
276 } else {
277 // zero terminate
278 *target = 0;
279 // strip trailing spaces
280 while (--target > buffer && *target == ' ') {
281 *target = 0;
282 }
283 // skip leading spaces
284 char *start = buffer;
285 while (*start == ' ') {
286 start++;
287 }
288 mValues.setEntry(i, start);
289 }
290
291 delete[] buffer;
292
293 ucnv_close(conv);
294 }
295 }
296
297 for (int i = size - 1; i >= 0; --i) {
298 if (strlen(mValues.getEntry(i)) == 0) {
299 ALOGV("erasing %s because entry is empty", mNames.getEntry(i));
300 mNames.erase(i);
301 mValues.erase(i);
302 }
303 }
304
305 ucsdet_close(csd);
306 }
307 }
308
309 /*
310 * When ICU detects multiple encoding matches, apply additional heuristics to determine
311 * which one is the best match, since ICU can't always be trusted to make the right choice.
312 *
313 * What this method does is:
314 * - decode the input using each of the matches found
315 * - recalculate the starting confidence level for multibyte encodings using a different
316 * algorithm and larger frequent character lists than ICU
317 * - devalue encoding where the conversion contains unlikely characters (symbols, reserved, etc)
318 * - pick the highest match
319 * - signal to the caller whether this match is considered good: confidence > 15, and confidence
320 * delta with the next runner up > 15
321 */
getPreferred(const char * input,size_t len,const UCharsetMatch ** ucma,size_t nummatches,bool * goodmatch,int * highestmatch)322 const UCharsetMatch *CharacterEncodingDetector::getPreferred(
323 const char *input, size_t len,
324 const UCharsetMatch** ucma, size_t nummatches,
325 bool *goodmatch, int *highestmatch) {
326
327 *goodmatch = false;
328 Vector<const UCharsetMatch*> matches;
329 UErrorCode status = U_ZERO_ERROR;
330
331 ALOGV("%zu matches", nummatches);
332 for (size_t i = 0; i < nummatches; i++) {
333 const char *encname = ucsdet_getName(ucma[i], &status);
334 int confidence = ucsdet_getConfidence(ucma[i], &status);
335 ALOGV("%zu: %s %d", i, encname, confidence);
336 matches.push_back(ucma[i]);
337 }
338
339 size_t num = matches.size();
340 if (num == 0) {
341 return NULL;
342 }
343 if (num == 1) {
344 int confidence = ucsdet_getConfidence(matches[0], &status);
345 if (confidence > 15) {
346 *goodmatch = true;
347 }
348 return matches[0];
349 }
350
351 ALOGV("considering %zu matches", num);
352
353 // keep track of how many "special" characters result when converting the input using each
354 // encoding
355 Vector<int> newconfidence;
356 for (size_t i = 0; i < num; i++) {
357 const uint16_t *freqdata = NULL;
358 float freqcoverage = 0;
359 status = U_ZERO_ERROR;
360 const char *encname = ucsdet_getName(matches[i], &status);
361 int confidence = ucsdet_getConfidence(matches[i], &status);
362 if (!strcmp("GB18030", encname)) {
363 freqdata = frequent_zhCN;
364 freqcoverage = frequent_zhCN_coverage;
365 } else if (!strcmp("Big5", encname)) {
366 freqdata = frequent_zhTW;
367 freqcoverage = frequent_zhTW_coverage;
368 } else if (!strcmp("EUC-KR", encname)) {
369 freqdata = frequent_ko;
370 freqcoverage = frequent_ko_coverage;
371 } else if (!strcmp("EUC-JP", encname)) {
372 freqdata = frequent_ja;
373 freqcoverage = frequent_ja_coverage;
374 } else if (!strcmp("Shift_JIS", encname)) {
375 freqdata = frequent_ja;
376 freqcoverage = frequent_ja_coverage;
377 }
378
379 ALOGV("%zu: %s %d", i, encname, confidence);
380 status = U_ZERO_ERROR;
381 UConverter *conv = ucnv_open(encname, &status);
382 int demerit = 0;
383 if (U_FAILURE(status)) {
384 ALOGV("failed to open %s: %d", encname, status);
385 confidence = 0;
386 demerit += 1000;
387 }
388 const char *source = input;
389 const char *sourceLimit = input + len;
390 status = U_ZERO_ERROR;
391 int frequentchars = 0;
392 int totalchars = 0;
393 while (true) {
394 // demerit the current encoding for each "special" character found after conversion.
395 // The amount of demerit is somewhat arbitrarily chosen.
396 int inchar;
397 if (source != sourceLimit) {
398 inchar = (source[0] << 8) + source[1];
399 }
400 UChar32 c = ucnv_getNextUChar(conv, &source, sourceLimit, &status);
401 if (!U_SUCCESS(status)) {
402 break;
403 }
404 if (c < 0x20 || (c >= 0x7f && c <= 0x009f)) {
405 ALOGV("control character %x", c);
406 demerit += 100;
407 } else if ((c == 0xa0) // no-break space
408 || (c >= 0xa2 && c <= 0xbe) // symbols, superscripts
409 || (c == 0xd7) || (c == 0xf7) // multiplication and division signs
410 || (c >= 0x2000 && c <= 0x209f)) { // punctuation, superscripts
411 ALOGV("unlikely character %x", c);
412 demerit += 10;
413 } else if (c >= 0xe000 && c <= 0xf8ff) {
414 ALOGV("private use character %x", c);
415 demerit += 30;
416 } else if (c >= 0x2190 && c <= 0x2bff) {
417 // this range comprises various symbol ranges that are unlikely to appear in
418 // music file metadata.
419 ALOGV("symbol %x", c);
420 demerit += 10;
421 } else if (c == 0xfffd) {
422 ALOGV("replacement character");
423 demerit += 50;
424 } else if (c >= 0xfff0 && c <= 0xfffc) {
425 ALOGV("unicode special %x", c);
426 demerit += 50;
427 } else if (freqdata != NULL) {
428 totalchars++;
429 if (isFrequent(freqdata, c)) {
430 frequentchars++;
431 }
432 }
433 }
434 if (freqdata != NULL && totalchars != 0) {
435 int myconfidence = 10 + float((100 * frequentchars) / totalchars) / freqcoverage;
436 ALOGV("ICU confidence: %d, my confidence: %d (%d %d)", confidence, myconfidence,
437 totalchars, frequentchars);
438 if (myconfidence > 100) myconfidence = 100;
439 if (myconfidence < 0) myconfidence = 0;
440 confidence = myconfidence;
441 }
442 ALOGV("%d-%d=%d", confidence, demerit, confidence - demerit);
443 newconfidence.push_back(confidence - demerit);
444 ucnv_close(conv);
445 if (i == 0 && (confidence - demerit) == 100) {
446 // no need to check any further, we'll end up using this match anyway
447 break;
448 }
449 }
450
451 // find match with highest confidence after adjusting for unlikely characters
452 int highest = newconfidence[0];
453 size_t highestidx = 0;
454 int runnerup = -10000;
455 int runnerupidx = -10000;
456 num = newconfidence.size();
457 for (size_t i = 1; i < num; i++) {
458 if (newconfidence[i] > highest) {
459 runnerup = highest;
460 runnerupidx = highestidx;
461 highest = newconfidence[i];
462 highestidx = i;
463 } else if (newconfidence[i] > runnerup){
464 runnerup = newconfidence[i];
465 runnerupidx = i;
466 }
467 }
468 status = U_ZERO_ERROR;
469 ALOGV("selecting: '%s' w/ %d confidence",
470 ucsdet_getName(matches[highestidx], &status), highest);
471 if (runnerupidx < 0) {
472 ALOGV("no runner up");
473 if (highest > 15) {
474 *goodmatch = true;
475 }
476 } else {
477 ALOGV("runner up: '%s' w/ %d confidence",
478 ucsdet_getName(matches[runnerupidx], &status), runnerup);
479 if (runnerup < 0) {
480 runnerup = 0;
481 }
482 if ((highest - runnerup) > 15) {
483 *goodmatch = true;
484 }
485 }
486 *highestmatch = highest;
487 return matches[highestidx];
488 }
489
490
isFrequent(const uint16_t * values,uint32_t c)491 bool CharacterEncodingDetector::isFrequent(const uint16_t *values, uint32_t c) {
492
493 int start = 0;
494 int end = 511; // All the tables have 512 entries
495 int mid = (start+end)/2;
496
497 while(start <= end) {
498 if(c == values[mid]) {
499 return true;
500 } else if (c > values[mid]) {
501 start = mid + 1;
502 } else {
503 end = mid - 1;
504 }
505
506 mid = (start + end) / 2;
507 }
508
509 return false;
510 }
511
512
513 } // namespace android
514