]> git.sesse.net Git - vlc/blob - src/text/unicode.c
Win32: Remove quicktime from system codecs...
[vlc] / src / text / unicode.c
1 /*****************************************************************************
2  * unicode.c: Unicode <-> locale functions
3  *****************************************************************************
4  * Copyright (C) 2005-2006 the VideoLAN team
5  * Copyright © 2005-2008 Rémi Denis-Courmont
6  *
7  * Authors: Rémi Denis-Courmont <rem # videolan.org>
8  *
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.
13  *
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.
18  *
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  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_charset.h>
33
34 #include <assert.h>
35
36 #include <stdio.h>
37 #include <stdarg.h>
38 #include <stdlib.h>
39 #include <sys/types.h>
40 #ifdef UNDER_CE
41 #  include <tchar.h>
42 #endif
43 #include <errno.h>
44
45 #if defined (ASSUME_UTF8)
46 /* Cool */
47
48 #elif defined (WIN32) || defined (UNDER_CE)
49 # define USE_MB2MB 1
50
51 static char *locale_dup (const char *string, bool from)
52 {
53     char *out;
54     int len;
55
56     len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
57                                    0, string, -1, NULL, 0);
58     wchar_t *wide = malloc (len * sizeof (wchar_t));
59     if (wide == NULL)
60         return NULL;
61
62     MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
63     len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1,
64                                    NULL, 0, NULL, NULL);
65     out = malloc (len);
66     if (out != NULL)
67         WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len,
68                              NULL, NULL);
69     free (wide);
70     return out;
71 }
72
73 #elif defined (HAVE_ICONV)
74 # define USE_ICONV 1
75
76 static char *locale_dup (const char *string, bool from)
77 {
78     vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : "",
79                                      from ? "" : "UTF-8");
80     if (hd == (vlc_iconv_t)(-1))
81         return NULL; /* Uho! */
82
83     const char *iptr = string;
84     size_t inb = strlen (string);
85     size_t outb = inb * 6 + 1;
86     char output[outb], *optr = output;
87
88     while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
89     {
90         *optr++ = '?';
91         outb--;
92         iptr++;
93         inb--;
94         vlc_iconv (hd, NULL, NULL, NULL, NULL); /* reset */
95     }
96     *optr = '\0';
97     vlc_iconv_close (hd);
98
99     assert (inb == 0);
100     assert (*iptr == '\0');
101     assert (*optr == '\0');
102     assert (strlen (output) == (size_t)(optr - output));
103     return strdup (output);
104 }
105
106 #else
107 # error No UTF8 charset conversion implemented on this platform!
108 #endif
109
110
111 /**
112  * Releases (if needed) a localized or uniformized string.
113  * @param str non-NULL return value from FromLocale() or ToLocale().
114  */
115 void LocaleFree (const char *str)
116 {
117 #ifdef ASSUME_UTF8
118     (void) str;
119 #else
120     free ((char *)str);
121 #endif
122 }
123
124
125 /**
126  * Converts a string from the system locale character encoding to UTF-8.
127  *
128  * @param locale nul-terminated string to convert
129  *
130  * @return a nul-terminated UTF-8 string, or NULL in case of error.
131  * To avoid memory leak, you have to pass the result to LocaleFree()
132  * when it is no longer needed.
133  */
134 char *FromLocale (const char *locale)
135 {
136 #ifdef ASSUME_UTF8
137     return (char *)locale;
138 #else
139     return locale ? locale_dup (locale, true) : NULL;
140 #endif
141 }
142
143 /**
144  * converts a string from the system locale character encoding to utf-8,
145  * the result is always allocated on the heap.
146  *
147  * @param locale nul-terminated string to convert
148  *
149  * @return a nul-terminated utf-8 string, or null in case of error.
150  * The result must be freed using free() - as with the strdup() function.
151  */
152 char *FromLocaleDup (const char *locale)
153 {
154 #ifdef ASSUME_UTF8
155     return strdup (locale);
156 #else
157     return locale_dup (locale, true);
158 #endif
159 }
160
161
162 /**
163  * ToLocale: converts an UTF-8 string to local system encoding.
164  *
165  * @param utf8 nul-terminated string to be converted
166  *
167  * @return a nul-terminated string, or NULL in case of error.
168  * To avoid memory leak, you have to pass the result to LocaleFree()
169  * when it is no longer needed.
170  */
171 char *ToLocale (const char *utf8)
172 {
173 #ifdef ASSUME_UTF8
174     return (char *)utf8;
175 #else
176     return utf8 ? locale_fast (utf8, false) : NULL
177 #endif
178 }
179
180
181 /**
182  * converts a string from UTF-8 to the system locale character encoding,
183  * the result is always allocated on the heap.
184  *
185  * @param utf8 nul-terminated string to convert
186  *
187  * @return a nul-terminated string, or null in case of error.
188  * The result must be freed using free() - as with the strdup() function.
189  */
190 char *ToLocaleDup (const char *utf8)
191 {
192 #ifdef ASSUME_UTF8
193     return strdup (utf8);
194 #else
195     return locale_dup (utf8, false);
196 #endif
197 }
198
199 /**
200  * Formats an UTF-8 string as vasprintf(), then print it to stdout, with
201  * appropriate conversion to local encoding.
202  */
203 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
204 {
205     char *utf8;
206     int res = vasprintf( &utf8, fmt, ap );
207     if( res == -1 )
208         return -1;
209
210 #ifdef ASSUME_UTF8
211     *str = utf8;
212 #else
213     *str = ToLocaleDup( utf8 );
214     free( utf8 );
215 #endif
216     return res;
217 }
218
219 /**
220  * Formats an UTF-8 string as vfprintf(), then print it, with
221  * appropriate conversion to local encoding.
222  */
223 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
224 {
225     char *str;
226     int res = utf8_vasprintf( &str, fmt, ap );
227     if( res == -1 )
228         return -1;
229
230     fputs( str, stream );
231     free( str );
232     return res;
233 }
234
235 /**
236  * Formats an UTF-8 string as fprintf(), then print it, with
237  * appropriate conversion to local encoding.
238  */
239 int utf8_fprintf( FILE *stream, const char *fmt, ... )
240 {
241     va_list ap;
242     int res;
243
244     va_start( ap, fmt );
245     res = utf8_vfprintf( stream, fmt, ap );
246     va_end( ap );
247     return res;
248 }
249
250
251 static char *CheckUTF8( char *str, char rep )
252 {
253     uint8_t *ptr = (uint8_t *)str;
254     assert (str != NULL);
255
256     for (;;)
257     {
258         uint8_t c = ptr[0];
259
260         if (c == '\0')
261             break;
262
263         if (c > 0xF4)
264             goto error;
265
266         int charlen = clz8 (c ^ 0xFF);
267         switch (charlen)
268         {
269             case 0: // 7-bit ASCII character -> OK
270                 ptr++;
271                 continue;
272
273             case 1: // continuation byte -> error
274                 goto error;
275         }
276
277         assert (charlen >= 2 && charlen <= 4);
278
279         uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
280         for (int i = 1; i < charlen; i++)
281         {
282             assert (cp < (1 << 26));
283             c = ptr[i];
284
285             if ((c >> 6) != 2) // not a continuation byte
286                 goto error;
287
288             cp = (cp << 6) | (ptr[i] & 0x3f);
289         }
290
291         switch (charlen)
292         {
293             case 4:
294                 if (cp > 0x10FFFF) // beyond Unicode
295                     goto error;
296             case 3:
297                 if (cp >= 0xD800 && cp < 0xC000) // UTF-16 surrogate
298                     goto error;
299             case 2:
300                 if (cp < 128) // ASCII overlong
301                     goto error;
302                 if (cp < (1u << (5 * charlen - 3))) // overlong
303                     goto error;
304         }
305         ptr += charlen;
306         continue;
307
308     error:
309         if (rep == 0)
310             return NULL;
311         *ptr++ = rep;
312         str = NULL;
313     }
314
315     return str;
316 }
317
318 /**
319  * Replaces invalid/overlong UTF-8 sequences with question marks.
320  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
321  * so we don't try that, even though it would be less disruptive.
322  *
323  * @return str if it was valid UTF-8, NULL if not.
324  */
325 char *EnsureUTF8( char *str )
326 {
327     return CheckUTF8( str, '?' );
328 }
329
330
331 /**
332  * Checks whether a string is a valid UTF-8 byte sequence.
333  *
334  * @param str nul-terminated string to be checked
335  *
336  * @return str if it was valid UTF-8, NULL if not.
337  */
338 const char *IsUTF8( const char *str )
339 {
340     return CheckUTF8( (char *)str, 0 );
341 }
342
343 /**
344  * Converts a string from the given character encoding to utf-8.
345  *
346  * @return a nul-terminated utf-8 string, or null in case of error.
347  * The result must be freed using free().
348  */
349 char *FromCharset(const char *charset, const void *data, size_t data_size)
350 {
351     vlc_iconv_t handle = vlc_iconv_open ("UTF-8", charset);
352     if (handle == (vlc_iconv_t)(-1))
353         return NULL;
354
355     char *out = NULL;
356     for(unsigned mul = 4; mul < 8; mul++ )
357     {
358         size_t in_size = data_size;
359         const char *in = data;
360         size_t out_max = mul * data_size;
361         char *tmp = out = malloc (1 + out_max);
362         if (!out)
363             break;
364
365         if (vlc_iconv (handle, &in, &in_size, &tmp, &out_max) != (size_t)(-1)) {
366             *tmp = '\0';
367             break;
368         }
369         free(out);
370         out = NULL;
371
372         if (errno != E2BIG)
373             break;
374     }
375     vlc_iconv_close(handle);
376     return out;
377 }
378