]> git.sesse.net Git - vlc/blob - src/text/unicode.c
decoder: fix data race in sout
[vlc] / src / text / unicode.c
1 /*****************************************************************************
2  * unicode.c: Unicode <-> locale functions
3  *****************************************************************************
4  * Copyright (C) 2005-2006 VLC authors and VideoLAN
5  * Copyright © 2005-2010 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 it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * 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
33 #include "libvlc.h"
34 #include <vlc_charset.h>
35
36 #include <assert.h>
37
38 #include <stdio.h>
39 #include <stdarg.h>
40 #include <stdlib.h>
41 #include <sys/types.h>
42 #if defined(_WIN32)
43 #  include <io.h>
44 #endif
45 #include <errno.h>
46 #include <wctype.h>
47
48 /**
49  * Formats an UTF-8 string as vfprintf(), then print it, with
50  * appropriate conversion to local encoding.
51  */
52 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
53 {
54 #ifndef _WIN32
55     return vfprintf (stream, fmt, ap);
56 #else
57     char *str;
58     int res = vasprintf (&str, fmt, ap);
59     if (unlikely(res == -1))
60         return -1;
61
62 #if !VLC_WINSTORE_APP
63     /* Writing to the console is a lot of fun on Microsoft Windows.
64      * If you use the standard I/O functions, you must use the OEM code page,
65      * which is different from the usual ANSI code page. Or maybe not, if the
66      * user called "chcp". Anyway, we prefer Unicode. */
67     int fd = _fileno (stream);
68     if (likely(fd != -1) && _isatty (fd))
69     {
70         wchar_t *wide = ToWide (str);
71         if (likely(wide != NULL))
72         {
73             HANDLE h = (HANDLE)((uintptr_t)_get_osfhandle (fd));
74             DWORD out;
75             /* XXX: It is not clear whether WriteConsole() wants the number of
76              * Unicode characters or the size of the wchar_t array. */
77             BOOL ok = WriteConsoleW (h, wide, wcslen (wide), &out, NULL);
78             free (wide);
79             if (ok)
80                 goto out;
81         }
82     }
83 #endif
84     wchar_t *wide = ToWide(str);
85     if (likely(wide != NULL))
86     {
87         res = fputws(wide, stream);
88         free(wide);
89     }
90     else
91         res = -1;
92 out:
93     free (str);
94     return res;
95 #endif
96 }
97
98 /**
99  * Formats an UTF-8 string as fprintf(), then print it, with
100  * appropriate conversion to local encoding.
101  */
102 int utf8_fprintf( FILE *stream, const char *fmt, ... )
103 {
104     va_list ap;
105     int res;
106
107     va_start( ap, fmt );
108     res = utf8_vfprintf( stream, fmt, ap );
109     va_end( ap );
110     return res;
111 }
112
113
114 /**
115  * Converts the first character from a UTF-8 sequence into a code point.
116  *
117  * @param str an UTF-8 bytes sequence
118  * @return 0 if str points to an empty string, i.e. the first character is NUL;
119  * number of bytes that the first character occupies (from 1 to 4) otherwise;
120  * -1 if the byte sequence was not a valid UTF-8 sequence.
121  */
122 size_t vlc_towc (const char *str, uint32_t *restrict pwc)
123 {
124     uint8_t *ptr = (uint8_t *)str, c;
125     uint32_t cp;
126
127     assert (str != NULL);
128
129     c = *ptr;
130     if (unlikely(c > 0xF4))
131         return -1;
132
133     int charlen = clz8 (c ^ 0xFF);
134     switch (charlen)
135     {
136         case 0: // 7-bit ASCII character -> short cut
137             *pwc = c;
138             return c != '\0';
139
140         case 1: // continuation byte -> error
141             return -1;
142
143         case 2:
144             if (unlikely(c < 0xC2)) // ASCII overlong
145                 return -1;
146             cp = (c & 0x1F) << 6;
147             break;
148
149         case 3:
150             cp = (c & 0x0F) << 12;
151             break;
152
153         case 4:
154             cp = (c & 0x07) << 16;
155             break;
156
157         default:
158             vlc_assert_unreachable ();
159     }
160
161     /* Unrolled continuation bytes decoding */
162     switch (charlen)
163     {
164         case 4:
165             c = *++ptr;
166             if (unlikely((c >> 6) != 2)) // not a continuation byte
167                 return -1;
168             cp |= (c & 0x3f) << 12;
169
170             if (unlikely(cp >= 0x110000)) // beyond Unicode range
171                 return -1;
172             /* fall through */
173         case 3:
174             c = *++ptr;
175             if (unlikely((c >> 6) != 2)) // not a continuation byte
176                 return -1;
177             cp |= (c & 0x3f) << 6;
178
179             if (unlikely(cp >= 0xD800 && cp < 0xE000)) // UTF-16 surrogate
180                 return -1;
181             if (unlikely(cp < (1u << (5 * charlen - 4)))) // non-ASCII overlong
182                 return -1;
183             /* fall through */
184         case 2:
185             c = *++ptr;
186             if (unlikely((c >> 6) != 2)) // not a continuation byte
187                 return -1;
188             cp |= (c & 0x3f);
189             break;
190     }
191
192     *pwc = cp;
193     return charlen;
194 }
195
196 /**
197  * Look for an UTF-8 string within another one in a case-insensitive fashion.
198  * Beware that this is quite slow. Contrary to strcasestr(), this function
199  * works regardless of the system character encoding, and handles multibyte
200  * code points correctly.
201
202  * @param haystack string to look into
203  * @param needle string to look for
204  * @return a pointer to the first occurence of the needle within the haystack,
205  * or NULL if no occurence were found.
206  */
207 char *vlc_strcasestr (const char *haystack, const char *needle)
208 {
209     ssize_t s;
210
211     do
212     {
213         const char *h = haystack, *n = needle;
214
215         for (;;)
216         {
217             uint32_t cph, cpn;
218
219             s = vlc_towc (n, &cpn);
220             if (s == 0)
221                 return (char *)haystack;
222             if (unlikely(s < 0))
223                 return NULL;
224             n += s;
225
226             s = vlc_towc (h, &cph);
227             if (s <= 0 || towlower (cph) != towlower (cpn))
228                 break;
229             h += s;
230         }
231
232         s = vlc_towc (haystack, &(uint32_t) { 0 });
233         haystack += s;
234     }
235     while (s > 0);
236
237     return NULL;
238 }
239
240 /**
241  * Replaces invalid/overlong UTF-8 sequences with question marks.
242  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
243  * so we don't try that, even though it would be less disruptive.
244  *
245  * @return str if it was valid UTF-8, NULL if not.
246  */
247 char *EnsureUTF8( char *str )
248 {
249     char *ret = str;
250     size_t n;
251     uint32_t cp;
252
253     while ((n = vlc_towc (str, &cp)) != 0)
254         if (likely(n != (size_t)-1))
255             str += n;
256         else
257         {
258             *str++ = '?';
259             ret = NULL;
260         }
261     return ret;
262 }
263
264
265 /**
266  * Checks whether a string is a valid UTF-8 byte sequence.
267  *
268  * @param str nul-terminated string to be checked
269  *
270  * @return str if it was valid UTF-8, NULL if not.
271  */
272 const char *IsUTF8( const char *str )
273 {
274     size_t n;
275     uint32_t cp;
276
277     while ((n = vlc_towc (str, &cp)) != 0)
278         if (likely(n != (size_t)-1))
279             str += n;
280         else
281             return NULL;
282     return str;
283 }
284
285 /**
286  * Converts a string from the given character encoding to utf-8.
287  *
288  * @return a nul-terminated utf-8 string, or null in case of error.
289  * The result must be freed using free().
290  */
291 char *FromCharset(const char *charset, const void *data, size_t data_size)
292 {
293     vlc_iconv_t handle = vlc_iconv_open ("UTF-8", charset);
294     if (handle == (vlc_iconv_t)(-1))
295         return NULL;
296
297     char *out = NULL;
298     for(unsigned mul = 4; mul < 8; mul++ )
299     {
300         size_t in_size = data_size;
301         const char *in = data;
302         size_t out_max = mul * data_size;
303         char *tmp = out = malloc (1 + out_max);
304         if (!out)
305             break;
306
307         if (vlc_iconv (handle, &in, &in_size, &tmp, &out_max) != (size_t)(-1)) {
308             *tmp = '\0';
309             break;
310         }
311         free(out);
312         out = NULL;
313
314         if (errno != E2BIG)
315             break;
316     }
317     vlc_iconv_close(handle);
318     return out;
319 }
320
321 /**
322  * Converts a nul-terminated UTF-8 string to a given character encoding.
323  * @param charset iconv name of the character set
324  * @param in nul-terminated UTF-8 string
325  * @param outsize pointer to hold the byte size of result
326  *
327  * @return A pointer to the result, which must be released using free().
328  * The UTF-8 nul terminator is included in the conversion if the target
329  * character encoding supports it. However it is not included in the returned
330  * byte size.
331  * In case of error, NULL is returned and the byte size is undefined.
332  */
333 void *ToCharset(const char *charset, const char *in, size_t *outsize)
334 {
335     vlc_iconv_t hd = vlc_iconv_open (charset, "UTF-8");
336     if (hd == (vlc_iconv_t)(-1))
337         return NULL;
338
339     const size_t inlen = strlen (in);
340     void *res;
341
342     for (unsigned mul = 4; mul < 16; mul++)
343     {
344         size_t outlen = mul * (inlen + 1);
345         res = malloc (outlen);
346         if (unlikely(res == NULL))
347             break;
348
349         const char *inp = in;
350         char *outp = res;
351         size_t inb = inlen;
352         size_t outb = outlen - mul;
353
354         if (vlc_iconv (hd, &inp, &inb, &outp, &outb) != (size_t)(-1))
355         {
356             *outsize = outlen - mul - outb;
357             outb += mul;
358             inb = 1; /* append nul terminator if possible */
359             if (vlc_iconv (hd, &inp, &inb, &outp, &outb) != (size_t)(-1))
360                 break;
361             if (errno == EILSEQ) /* cannot translate nul terminator!? */
362                 break;
363         }
364
365         free (res);
366         res = NULL;
367         if (errno != E2BIG) /* conversion failure */
368             break;
369     }
370     vlc_iconv_close (hd);
371     return res;
372 }
373