1 /*****************************************************************************
2 * unicode.c: Unicode <-> locale functions
3 *****************************************************************************
4 * Copyright (C) 2005-2006 the VideoLAN team
5 * Copyright © 2005-2008 Rémi Denis-Courmont
7 * Authors: Rémi Denis-Courmont <rem # videolan.org>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
31 #include <vlc_common.h>
32 #include <vlc_charset.h>
39 #include <sys/types.h>
45 #if defined (__APPLE__) || defined (HAVE_MAEMO)
46 /* Define this if the OS always use UTF-8 internally */
47 # define ASSUME_UTF8 1
50 #if defined (ASSUME_UTF8)
52 #elif defined (WIN32) || defined (UNDER_CE)
54 #elif defined (HAVE_ICONV)
57 # error No UTF8 charset conversion implemented on this platform!
60 #if defined (USE_ICONV)
61 # include <langinfo.h>
62 static char charset[sizeof ("CSISO11SWEDISHFORNAMES")] = "";
64 static void find_charset_once (void)
66 strlcpy (charset, nl_langinfo (CODESET), sizeof (charset));
67 if (!strcasecmp (charset, "ASCII")
68 || !strcasecmp (charset, "ANSI_X3.4-1968"))
69 strcpy (charset, "UTF-8"); /* superset... */
72 static int find_charset (void)
74 static pthread_once_t once = PTHREAD_ONCE_INIT;
75 pthread_once (&once, find_charset_once);
76 return !strcasecmp (charset, "UTF-8");
81 static char *locale_fast (const char *string, bool from)
86 #if defined (USE_ICONV)
88 return (char *)string;
90 vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : charset,
91 from ? charset : "UTF-8");
92 if (hd == (vlc_iconv_t)(-1))
93 return NULL; /* Uho! */
95 const char *iptr = string;
96 size_t inb = strlen (string);
97 size_t outb = inb * 6 + 1;
98 char output[outb], *optr = output;
100 while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
106 vlc_iconv (hd, NULL, NULL, NULL, NULL); /* reset */
109 vlc_iconv_close (hd);
112 assert (*iptr == '\0');
113 assert (*optr == '\0');
114 assert (strlen (output) == (size_t)(optr - output));
115 return strdup (output);
116 #elif defined (USE_MB2MB)
120 len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
121 0, string, -1, NULL, 0);
122 wchar_t *wide = malloc (len * sizeof (wchar_t));
126 MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
127 len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1,
128 NULL, 0, NULL, NULL);
131 WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len,
137 return (char *)string;
142 static inline char *locale_dup (const char *string, bool from)
146 #if defined (USE_ICONV)
148 return strdup (string);
149 return locale_fast (string, from);
150 #elif defined (USE_MB2MB)
151 return locale_fast (string, from);
154 return strdup (string);
159 * Releases (if needed) a localized or uniformized string.
160 * @param str non-NULL return value from FromLocale() or ToLocale().
162 void LocaleFree (const char *str)
164 #if defined (USE_ICONV)
165 if (!find_charset ())
167 #elif defined (USE_MB2MB)
176 * Converts a string from the system locale character encoding to UTF-8.
178 * @param locale nul-terminated string to convert
180 * @return a nul-terminated UTF-8 string, or NULL in case of error.
181 * To avoid memory leak, you have to pass the result to LocaleFree()
182 * when it is no longer needed.
184 char *FromLocale (const char *locale)
186 return locale_fast (locale, true);
190 * converts a string from the system locale character encoding to utf-8,
191 * the result is always allocated on the heap.
193 * @param locale nul-terminated string to convert
195 * @return a nul-terminated utf-8 string, or null in case of error.
196 * The result must be freed using free() - as with the strdup() function.
198 char *FromLocaleDup (const char *locale)
200 return locale_dup (locale, true);
205 * ToLocale: converts an UTF-8 string to local system encoding.
207 * @param utf8 nul-terminated string to be converted
209 * @return a nul-terminated string, or NULL in case of error.
210 * To avoid memory leak, you have to pass the result to LocaleFree()
211 * when it is no longer needed.
213 char *ToLocale (const char *utf8)
215 return locale_fast (utf8, false);
220 * converts a string from UTF-8 to the system locale character encoding,
221 * the result is always allocated on the heap.
223 * @param utf8 nul-terminated string to convert
225 * @return a nul-terminated string, or null in case of error.
226 * The result must be freed using free() - as with the strdup() function.
228 char *ToLocaleDup (const char *utf8)
230 return locale_dup (utf8, false);
234 * Formats an UTF-8 string as vasprintf(), then print it to stdout, with
235 * appropriate conversion to local encoding.
237 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
240 int res = vasprintf( &utf8, fmt, ap );
244 *str = ToLocaleDup( utf8 );
250 * Formats an UTF-8 string as vfprintf(), then print it, with
251 * appropriate conversion to local encoding.
253 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
256 int res = utf8_vasprintf( &str, fmt, ap );
260 fputs( str, stream );
266 * Formats an UTF-8 string as fprintf(), then print it, with
267 * appropriate conversion to local encoding.
269 int utf8_fprintf( FILE *stream, const char *fmt, ... )
275 res = utf8_vfprintf( stream, fmt, ap );
281 static char *CheckUTF8( char *str, char rep )
283 uint8_t *ptr = (uint8_t *)str;
284 assert (str != NULL);
296 int charlen = clz8 (c ^ 0xFF);
299 case 0: // 7-bit ASCII character -> OK
303 case 1: // continuation byte -> error
307 assert (charlen >= 2 && charlen <= 4);
309 uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
310 for (int i = 1; i < charlen; i++)
312 assert (cp < (1 << 26));
315 if ((c >> 6) != 2) // not a continuation byte
318 cp = (cp << 6) | (ptr[i] & 0x3f);
324 if (cp > 0x10FFFF) // beyond Unicode
327 if (cp >= 0xD800 && cp < 0xC000) // UTF-16 surrogate
330 if (cp < 128) // ASCII overlong
332 if (cp < (1u << (5 * charlen - 3))) // overlong
349 * Replaces invalid/overlong UTF-8 sequences with question marks.
350 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
351 * so we don't try that, even though it would be less disruptive.
353 * @return str if it was valid UTF-8, NULL if not.
355 char *EnsureUTF8( char *str )
357 return CheckUTF8( str, '?' );
362 * Checks whether a string is a valid UTF-8 byte sequence.
364 * @param str nul-terminated string to be checked
366 * @return str if it was valid UTF-8, NULL if not.
368 const char *IsUTF8( const char *str )
370 return CheckUTF8( (char *)str, 0 );
374 * Converts a string from the given character encoding to utf-8.
376 * @return a nul-terminated utf-8 string, or null in case of error.
377 * The result must be freed using free().
379 char *FromCharset(const char *charset, const void *data, size_t data_size)
381 vlc_iconv_t handle = vlc_iconv_open ("UTF-8", charset);
382 if (handle == (vlc_iconv_t)(-1))
386 for(unsigned mul = 4; mul < 8; mul++ )
388 size_t in_size = data_size;
389 const char *in = data;
390 size_t out_max = mul * data_size;
391 char *tmp = out = malloc (1 + out_max);
395 if (vlc_iconv (handle, &in, &in_size, &tmp, &out_max) != (size_t)(-1)) {
405 vlc_iconv_close(handle);