{"id":3972,"date":"2012-11-28T22:49:45","date_gmt":"2012-11-29T06:49:45","guid":{"rendered":"http:\/\/multimedia.cx\/eggs\/?p=3972"},"modified":"2020-07-25T23:01:04","modified_gmt":"2020-07-26T06:01:04","slug":"adventures-in-unicode","status":"publish","type":"post","link":"https:\/\/multimedia.cx\/eggs\/adventures-in-unicode\/","title":{"rendered":"Adventures in Unicode"},"content":{"rendered":"<p>Tangential to multimedia hacking is proper metadata handling. Recently, I have gathered an interest in processing a large corpus of multimedia files which are likely to contain metadata strings which do not fall into the lower ASCII set. This is significant because the lower ASCII set intersects perfectly with my own programming comfort zone. Indeed, all of my programming life, I have insisted on covering my ears and loudly asserting <strong>&#8220;LA LA LA LA LA! ALL TEXT EVERYWHERE IS ASCII!&#8221;<\/strong> I suspect I&#8217;m not alone in this.<\/p>\n<p>Thus, I took this as an opportunity to conquer my longstanding fear of Unicode. I developed a self-learning course comprised of a series of exercises which add up to this diagram:<\/p>\n<p><center><br \/>\n<img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2012\/11\/Unicode-Processing-Pipeline.png\" alt=\"\" title=\"Proposed Unicode processing pipeline\" width=\"498\" height=\"190\" class=\"aligncenter size-full wp-image-3977\" srcset=\"https:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2012\/11\/Unicode-Processing-Pipeline.png 498w, https:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2012\/11\/Unicode-Processing-Pipeline-300x114.png 300w\" sizes=\"auto, (max-width: 498px) 100vw, 498px\" \/><br \/>\n<\/center><\/p>\n<p><strong>Part 1: Understanding Text Encoding<\/strong><br \/>\nPython has regular strings by default and then it has Unicode strings. The latter are prefixed by the letter &#8216;u&#8217;. This is what &#8216;\u00f6&#8217; looks like encoded in each type.<\/p>\n<pre>\r\n>>> '\u00f6', u'\u00f6'\r\n('\\xc3\\xb6', u'\\xf6')\r\n<\/pre>\n<p>A large part of my frustration with Unicode comes from Python yelling at me about UnicodeDecodeErrors and an inability to handle the number 0xc3 for some reason. This usually comes when I&#8217;m trying to wrap my head around an unrelated problem and don&#8217;t care to get sidetracked by text encoding issues. However, when I studied the above output, I finally understood where the 0xc3 comes from. I just didn&#8217;t understand what the encoding represents exactly.<br \/>\n<!--more--><\/p>\n<p>I can see from assorted tables that &#8216;\u00f6&#8217; is character 0xF6 in various encodings (in Unicode and Latin-1), so u&#8217;\\xf6&#8242; makes sense. But what does &#8216;\\xc3\\xb6&#8217; mean? It&#8217;s my style to excavate straight down to the lowest levels, and I wanted to understand exactly how characters are represented in memory. The <a href=\"http:\/\/en.wikipedia.org\/wiki\/UTF-8\">UTF-8<\/a> encoding tables inform us that any Unicode code point above 0x7F but less than 0x800 will be encoded with 2 bytes:<\/p>\n<pre>\r\n 110xxxxx 10xxxxxx\r\n<\/pre>\n<p>Applying this pattern to the \\xc3\\xb6 encoding:<\/p>\n<pre>\r\n            hex: 0xc3      0xb6\r\n           bits: 11000011  10110110\r\n important bits: ---00011  --110110\r\n      assembled: 00011110110\r\n     code point: 0xf6\r\n<\/pre>\n<p>I was elated when I drew that out and made the connection. Maybe I&#8217;m the last programmer to figure this stuff out. But I&#8217;m still happy that I actually <em>understand<\/em> those Python errors pertaining to the number 0xc3 and that I won&#8217;t have to apply canned solutions without understanding the core problem.<\/p>\n<p>I&#8217;m cheating on this part of this exercise just a little bit since the diagram implied that the Unicode text needs to come from a binary file. I&#8217;ll return to that in a bit. For now, I&#8217;ll just contrive the following Unicode string from the Python REPL:<\/p>\n<pre>\r\n>>> u = u'\u00dc\u00f1\u00ec\u00e7\u00f4?\u00e9'\r\n>>> u\r\nu'\\xdc\\xf1\\xec\\xe7\\xf4\\u0111\\xe9'\r\n<\/pre>\n<p><strong>Part 2: From Python To SQLite3<\/strong><br \/>\nThe next step is to see what happens when I use <a href=\"http:\/\/docs.python.org\/2\/library\/sqlite3.html\">Python&#8217;s SQLite3 module<\/a> to dump the string into a new database. Will the Unicode encoding be preserved on disk? What will UTF-8 look like on disk anyway?<\/p>\n<pre>\r\n>>> import sqlite3\r\n>>> conn = sqlite3.connect('unicode.db')\r\n>>> conn.execute(\"CREATE TABLE t (t text)\")\r\n>>> conn.execute(\"INSERT INTO t VALUES (?)\", (u, ))\r\n>>> conn.commit()\r\n>>> conn.close()\r\n<\/pre>\n<p>Next, I manually view the resulting database file (unicode.db) using a hex editor and look for strings. Here we go:<\/p>\n<pre>\r\n000007F0   02 29 C3 9C  C3 B1 C3 AC  C3 A7 C3 B4  C4 91 C3 A9\r\n<\/pre>\n<p>Look at that! It&#8217;s just like the \\xc3\\xf6 encoding we see in the regular Python strings.<\/p>\n<p><strong>Part 3: From SQLite3 To A Web Page Via PHP<\/strong><br \/>\nFinally, use PHP (love it or hate it, but it&#8217;s what&#8217;s most convenient on my hosting provider) to query the string from the database and display it on a web page, completing the outlined processing pipeline.<\/p>\n<p><script src=\"https:\/\/gist.github.com\/multimediamike\/447bec64933f16c4f349d318f05c2fc4.js\"><\/script><\/p>\n<p>I tested the foregoing PHP script on 3 separate browsers that I had handy (Firefox, Internet Explorer, and Chrome):<\/p>\n<p><center><br \/>\n<img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2012\/11\/unicode-in-3-browsers.png\" alt=\"\" title=\"Correct Unicode rendering in 3 different browsers\" width=\"369\" height=\"425\" class=\"aligncenter size-full wp-image-3978\" srcset=\"https:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2012\/11\/unicode-in-3-browsers.png 369w, https:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2012\/11\/unicode-in-3-browsers-260x300.png 260w\" sizes=\"auto, (max-width: 369px) 100vw, 369px\" \/><br \/>\n<\/center><\/p>\n<p>I&#8217;d say that counts as success! It&#8217;s important to note that the &#8220;meta http-equiv&#8221; tag is absolutely necessary. Omit and see something like this:<\/p>\n<p><center><br \/>\n<img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2012\/11\/no-meta-http-equiv.png\" alt=\"\" title=\"Unicode without the meta http-equiv tag\" width=\"305\" height=\"144\" class=\"aligncenter size-full wp-image-3983\" srcset=\"https:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2012\/11\/no-meta-http-equiv.png 305w, https:\/\/multimedia.cx\/eggs\/wp-content\/uploads\/2012\/11\/no-meta-http-equiv-300x141.png 300w\" sizes=\"auto, (max-width: 305px) 100vw, 305px\" \/><br \/>\n<\/center><\/p>\n<p>Since we know what the UTF-8 stream looks like, it&#8217;s pretty obvious how the mapping is operating here: 0xc3 and 0xc4 correspond to &#8216;\u00c3&#8217; and &#8216;\u00c4&#8217;, respectively. This corresponds to an encoding named <a href=\"http:\/\/en.wikipedia.org\/wiki\/ISO\/IEC_8859-1\">ISO\/IEC 8859-1, a.k.a. Latin-1<\/a>. Speaking of which&#8230;<\/p>\n<p><strong>Part 4: Converting Binary Data To Unicode<\/strong><br \/>\nAt the start of the experiment, I was trying to extract metadata strings from these binary multimedia files and I noticed characters like our friend &#8216;\u00f6&#8217; from above. In the bytestream, this was represented simply with 0xf6. I mistakenly believed that this was the on-disk representation of UTF-8. Wrong. Turns out it&#8217;s Latin-1.<\/p>\n<p>However, I still need to solve the problem of transforming such strings into Unicode to be shoved through the pipeline diagrammed above. For this experiment, I created a 9-byte file with the Latin-1 string &#8216;\u00dc\u00f1\u00ec\u00e7\u00f4d\u00e9&#8217; couched by 0&#8217;s, to simulate yanking a string out of a binary file. Here&#8217;s unicode.file:<\/p>\n<pre>\r\n00000000   00 DC F1 EC  E7 F4 64 E9  00         ......d..\r\n<\/pre>\n<p>(Aside: this experiment uses plain &#8216;d&#8217; since the &#8216;?&#8217; with a bar through it doesn&#8217;t occur in Latin-1; shows up <a href=\"http:\/\/vi.wikipedia.org\">all over the place in Vietnamese<\/a>, at least.)<\/p>\n<p>I&#8217;ve been mashing around Python code via the REPL, trying to get this string into a Unicode-friendly format. This is a successful method but it&#8217;s probably not the best:<\/p>\n<p><script src=\"https:\/\/gist.github.com\/multimediamike\/847176bdebb59ed743fa77ae471f3fd8.js\"><\/script><\/p>\n<p><strong>Conclusion<\/strong><br \/>\nDealing with text encoding matters reminds me of <a href=\"http:\/\/multimedia.cx\/eggs\/on-portable-programs\/\">dealing with integer endian-ness concerns<\/a>. When you&#8217;re just dealing with one system, you probably don&#8217;t need to think too much about it because the system is usually handling everything consistently underneath the covers.<\/p>\n<p>However, when the data leaves one system and will be interpreted by another system, that&#8217;s when a programmer needs to be cognizant of matters such as integer endianness or text encoding.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I finally force myself to conquer my dread of Unicode by developing some experiments to teach me what I need to know<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[28],"tags":[274,285,275,273],"class_list":["post-3972","post","type-post","status-publish","format-standard","hentry","category-programming","tag-php","tag-python","tag-sqlite3","tag-unicode"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/posts\/3972","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/comments?post=3972"}],"version-history":[{"count":18,"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/posts\/3972\/revisions"}],"predecessor-version":[{"id":4608,"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/posts\/3972\/revisions\/4608"}],"wp:attachment":[{"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/media?parent=3972"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/categories?post=3972"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/multimedia.cx\/eggs\/wp-json\/wp\/v2\/tags?post=3972"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}