TextEncodingDetect.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. namespace Emby.Server.Implementations.TextEncoding
  2. {
  3. // Copyright 2015-2016 Jonathan Bennett <jon@autoitscript.com>
  4. //
  5. // https://www.autoitscript.com
  6. //
  7. // Licensed under the Apache License, Version 2.0 (the "License");
  8. // you may not use this file except in compliance with the License.
  9. // You may obtain a copy of the License at
  10. //
  11. // http://www.apache.org/licenses/LICENSE-2.0
  12. //
  13. // Unless required by applicable law or agreed to in writing, software
  14. // distributed under the License is distributed on an "AS IS" BASIS,
  15. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. // See the License for the specific language governing permissions and
  17. // limitations under the License.
  18. /// <summary>
  19. /// Credit: https://github.com/AutoIt/text-encoding-detect
  20. /// </summary>
  21. public class TextEncodingDetect
  22. {
  23. private readonly byte[] _utf16BeBom =
  24. {
  25. 0xFE,
  26. 0xFF
  27. };
  28. private readonly byte[] _utf16LeBom =
  29. {
  30. 0xFF,
  31. 0xFE
  32. };
  33. private readonly byte[] _utf8Bom =
  34. {
  35. 0xEF,
  36. 0xBB,
  37. 0xBF
  38. };
  39. private bool _nullSuggestsBinary = true;
  40. private double _utf16ExpectedNullPercent = 70;
  41. private double _utf16UnexpectedNullPercent = 10;
  42. public enum CharacterEncoding
  43. {
  44. None, // Unknown or binary
  45. Ansi, // 0-255
  46. Ascii, // 0-127
  47. Utf8Bom, // UTF8 with BOM
  48. Utf8Nobom, // UTF8 without BOM
  49. Utf16LeBom, // UTF16 LE with BOM
  50. Utf16LeNoBom, // UTF16 LE without BOM
  51. Utf16BeBom, // UTF16-BE with BOM
  52. Utf16BeNoBom // UTF16-BE without BOM
  53. }
  54. /// <summary>
  55. /// Sets if the presence of nulls in a buffer indicate the buffer is binary data rather than text.
  56. /// </summary>
  57. public bool NullSuggestsBinary
  58. {
  59. set => _nullSuggestsBinary = value;
  60. }
  61. public double Utf16ExpectedNullPercent
  62. {
  63. set
  64. {
  65. if (value > 0 && value < 100)
  66. {
  67. _utf16ExpectedNullPercent = value;
  68. }
  69. }
  70. }
  71. public double Utf16UnexpectedNullPercent
  72. {
  73. set
  74. {
  75. if (value > 0 && value < 100)
  76. {
  77. _utf16UnexpectedNullPercent = value;
  78. }
  79. }
  80. }
  81. /// <summary>
  82. /// Gets the BOM length for a given Encoding mode.
  83. /// </summary>
  84. /// <param name="encoding"></param>
  85. /// <returns>The BOM length.</returns>
  86. public static int GetBomLengthFromEncodingMode(CharacterEncoding encoding)
  87. {
  88. int length;
  89. switch (encoding)
  90. {
  91. case CharacterEncoding.Utf16BeBom:
  92. case CharacterEncoding.Utf16LeBom:
  93. length = 2;
  94. break;
  95. case CharacterEncoding.Utf8Bom:
  96. length = 3;
  97. break;
  98. default:
  99. length = 0;
  100. break;
  101. }
  102. return length;
  103. }
  104. /// <summary>
  105. /// Checks for a BOM sequence in a byte buffer.
  106. /// </summary>
  107. /// <param name="buffer"></param>
  108. /// <param name="size"></param>
  109. /// <returns>Encoding type or Encoding.None if no BOM.</returns>
  110. public CharacterEncoding CheckBom(byte[] buffer, int size)
  111. {
  112. // Check for BOM
  113. if (size >= 2 && buffer[0] == _utf16LeBom[0] && buffer[1] == _utf16LeBom[1])
  114. {
  115. return CharacterEncoding.Utf16LeBom;
  116. }
  117. if (size >= 2 && buffer[0] == _utf16BeBom[0] && buffer[1] == _utf16BeBom[1])
  118. {
  119. return CharacterEncoding.Utf16BeBom;
  120. }
  121. if (size >= 3 && buffer[0] == _utf8Bom[0] && buffer[1] == _utf8Bom[1] && buffer[2] == _utf8Bom[2])
  122. {
  123. return CharacterEncoding.Utf8Bom;
  124. }
  125. return CharacterEncoding.None;
  126. }
  127. /// <summary>
  128. /// Automatically detects the Encoding type of a given byte buffer.
  129. /// </summary>
  130. /// <param name="buffer">The byte buffer.</param>
  131. /// <param name="size">The size of the byte buffer.</param>
  132. /// <returns>The Encoding type or Encoding.None if unknown.</returns>
  133. public CharacterEncoding DetectEncoding(byte[] buffer, int size)
  134. {
  135. // First check if we have a BOM and return that if so
  136. var encoding = CheckBom(buffer, size);
  137. if (encoding != CharacterEncoding.None)
  138. {
  139. return encoding;
  140. }
  141. // Now check for valid UTF8
  142. encoding = CheckUtf8(buffer, size);
  143. if (encoding != CharacterEncoding.None)
  144. {
  145. return encoding;
  146. }
  147. // Now try UTF16
  148. encoding = CheckUtf16NewlineChars(buffer, size);
  149. if (encoding != CharacterEncoding.None)
  150. {
  151. return encoding;
  152. }
  153. encoding = CheckUtf16Ascii(buffer, size);
  154. if (encoding != CharacterEncoding.None)
  155. {
  156. return encoding;
  157. }
  158. // ANSI or None (binary) then
  159. if (!DoesContainNulls(buffer, size))
  160. {
  161. return CharacterEncoding.Ansi;
  162. }
  163. // Found a null, return based on the preference in null_suggests_binary_
  164. return _nullSuggestsBinary ? CharacterEncoding.None : CharacterEncoding.Ansi;
  165. }
  166. /// <summary>
  167. /// Checks if a buffer contains text that looks like utf16 by scanning for
  168. /// newline chars that would be present even in non-english text.
  169. /// </summary>
  170. /// <param name="buffer">The byte buffer.</param>
  171. /// <param name="size">The size of the byte buffer.</param>
  172. /// <returns>Encoding.none, Encoding.Utf16LeNoBom or Encoding.Utf16BeNoBom.</returns>
  173. private static CharacterEncoding CheckUtf16NewlineChars(byte[] buffer, int size)
  174. {
  175. if (size < 2)
  176. {
  177. return CharacterEncoding.None;
  178. }
  179. // Reduce size by 1 so we don't need to worry about bounds checking for pairs of bytes
  180. size--;
  181. var leControlChars = 0;
  182. var beControlChars = 0;
  183. uint pos = 0;
  184. while (pos < size)
  185. {
  186. byte ch1 = buffer[pos++];
  187. byte ch2 = buffer[pos++];
  188. if (ch1 == 0)
  189. {
  190. if (ch2 == 0x0a || ch2 == 0x0d)
  191. {
  192. ++beControlChars;
  193. }
  194. }
  195. else if (ch2 == 0)
  196. {
  197. if (ch1 == 0x0a || ch1 == 0x0d)
  198. {
  199. ++leControlChars;
  200. }
  201. }
  202. // If we are getting both LE and BE control chars then this file is not utf16
  203. if (leControlChars > 0 && beControlChars > 0)
  204. {
  205. return CharacterEncoding.None;
  206. }
  207. }
  208. if (leControlChars > 0)
  209. {
  210. return CharacterEncoding.Utf16LeNoBom;
  211. }
  212. return beControlChars > 0 ? CharacterEncoding.Utf16BeNoBom : CharacterEncoding.None;
  213. }
  214. /// <summary>
  215. /// Checks if a buffer contains any nulls. Used to check for binary vs text data.
  216. /// </summary>
  217. /// <param name="buffer">The byte buffer.</param>
  218. /// <param name="size">The size of the byte buffer.</param>
  219. private static bool DoesContainNulls(byte[] buffer, int size)
  220. {
  221. uint pos = 0;
  222. while (pos < size)
  223. {
  224. if (buffer[pos++] == 0)
  225. {
  226. return true;
  227. }
  228. }
  229. return false;
  230. }
  231. /// <summary>
  232. /// Checks if a buffer contains text that looks like utf16. This is done based
  233. /// on the use of nulls which in ASCII/script like text can be useful to identify.
  234. /// </summary>
  235. /// <param name="buffer">The byte buffer.</param>
  236. /// <param name="size">The size of the byte buffer.</param>
  237. /// <returns>Encoding.none, Encoding.Utf16LeNoBom or Encoding.Utf16BeNoBom.</returns>
  238. private CharacterEncoding CheckUtf16Ascii(byte[] buffer, int size)
  239. {
  240. var numOddNulls = 0;
  241. var numEvenNulls = 0;
  242. // Get even nulls
  243. uint pos = 0;
  244. while (pos < size)
  245. {
  246. if (buffer[pos] == 0)
  247. {
  248. numEvenNulls++;
  249. }
  250. pos += 2;
  251. }
  252. // Get odd nulls
  253. pos = 1;
  254. while (pos < size)
  255. {
  256. if (buffer[pos] == 0)
  257. {
  258. numOddNulls++;
  259. }
  260. pos += 2;
  261. }
  262. double evenNullThreshold = numEvenNulls * 2.0 / size;
  263. double oddNullThreshold = numOddNulls * 2.0 / size;
  264. double expectedNullThreshold = _utf16ExpectedNullPercent / 100.0;
  265. double unexpectedNullThreshold = _utf16UnexpectedNullPercent / 100.0;
  266. // Lots of odd nulls, low number of even nulls
  267. if (evenNullThreshold < unexpectedNullThreshold && oddNullThreshold > expectedNullThreshold)
  268. {
  269. return CharacterEncoding.Utf16LeNoBom;
  270. }
  271. // Lots of even nulls, low number of odd nulls
  272. if (oddNullThreshold < unexpectedNullThreshold && evenNullThreshold > expectedNullThreshold)
  273. {
  274. return CharacterEncoding.Utf16BeNoBom;
  275. }
  276. // Don't know
  277. return CharacterEncoding.None;
  278. }
  279. /// <summary>
  280. /// Checks if a buffer contains valid utf8.
  281. /// </summary>
  282. /// <param name="buffer">The byte buffer.</param>
  283. /// <param name="size">The size of the byte buffer.</param>
  284. /// <returns>
  285. /// Encoding type of Encoding.None (invalid UTF8), Encoding.Utf8NoBom (valid utf8 multibyte strings) or
  286. /// Encoding.ASCII (data in 0.127 range).
  287. /// </returns>
  288. /// <returns>2</returns>
  289. private CharacterEncoding CheckUtf8(byte[] buffer, int size)
  290. {
  291. // UTF8 Valid sequences
  292. // 0xxxxxxx ASCII
  293. // 110xxxxx 10xxxxxx 2-byte
  294. // 1110xxxx 10xxxxxx 10xxxxxx 3-byte
  295. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 4-byte
  296. //
  297. // Width in UTF8
  298. // Decimal Width
  299. // 0-127 1 byte
  300. // 194-223 2 bytes
  301. // 224-239 3 bytes
  302. // 240-244 4 bytes
  303. //
  304. // Subsequent chars are in the range 128-191
  305. var onlySawAsciiRange = true;
  306. uint pos = 0;
  307. while (pos < size)
  308. {
  309. byte ch = buffer[pos++];
  310. if (ch == 0 && _nullSuggestsBinary)
  311. {
  312. return CharacterEncoding.None;
  313. }
  314. int moreChars;
  315. if (ch <= 127)
  316. {
  317. // 1 byte
  318. moreChars = 0;
  319. }
  320. else if (ch >= 194 && ch <= 223)
  321. {
  322. // 2 Byte
  323. moreChars = 1;
  324. }
  325. else if (ch >= 224 && ch <= 239)
  326. {
  327. // 3 Byte
  328. moreChars = 2;
  329. }
  330. else if (ch >= 240 && ch <= 244)
  331. {
  332. // 4 Byte
  333. moreChars = 3;
  334. }
  335. else
  336. {
  337. return CharacterEncoding.None; // Not utf8
  338. }
  339. // Check secondary chars are in range if we are expecting any
  340. while (moreChars > 0 && pos < size)
  341. {
  342. onlySawAsciiRange = false; // Seen non-ascii chars now
  343. ch = buffer[pos++];
  344. if (ch < 128 || ch > 191)
  345. {
  346. return CharacterEncoding.None; // Not utf8
  347. }
  348. --moreChars;
  349. }
  350. }
  351. // If we get to here then only valid UTF-8 sequences have been processed
  352. // If we only saw chars in the range 0-127 then we can't assume UTF8 (the caller will need to decide)
  353. return onlySawAsciiRange ? CharacterEncoding.Ascii : CharacterEncoding.Utf8Nobom;
  354. }
  355. }
  356. }