]> git.sesse.net Git - vlc/blob - src/text/strings.c
A few sprintf()+n in text/strings.c
[vlc] / src / text / strings.c
1 /*****************************************************************************
2  * strings.c: String related functions
3  *****************************************************************************
4  * Copyright (C) 2006 the VideoLAN team
5  * Copyright (C) 2008-2009 Rémi Denis-Courmont
6  * $Id$
7  *
8  * Authors: Antoine Cellerier <dionoea at videolan dot org>
9  *          Daniel Stranger <vlc at schmaller dot de>
10  *          Rémi Denis-Courmont <rem # videolan org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <vlc_common.h>
35 #include <assert.h>
36
37 /* Needed by str_format_time */
38 #include <time.h>
39 #include <limits.h>
40
41 /* Needed by str_format_meta */
42 #include <vlc_input.h>
43 #include <vlc_meta.h>
44 #include <vlc_playlist.h>
45 #include <vlc_aout.h>
46
47 #include <vlc_strings.h>
48 #include <vlc_url.h>
49 #include <vlc_charset.h>
50
51 /**
52  * Decode encoded URI component. See also decode_URI().
53  * \return decoded duplicated string
54  */
55 char *decode_URI_duplicate( const char *psz )
56 {
57     char *psz_dup = strdup( psz );
58     decode_URI( psz_dup );
59     return psz_dup;
60 }
61
62 /**
63  * Decode an encoded URI component in place.
64  * <b>This function does NOT decode entire URIs.</b>
65  * It decodes components (e.g. host name, directory, file name).
66  * Decoded URIs do not exist in the real world (see RFC3986 §2.4).
67  * Complete URIs are always "encoded" (or they are syntaxically invalid).
68  *
69  * Note that URI encoding is different from Javascript escaping. Especially,
70  * white spaces and Unicode non-ASCII code points are encoded differently.
71  *
72  * \return psz on success, NULL if it was not properly encoded
73  */
74 char *decode_URI( char *psz )
75 {
76     unsigned char *in = (unsigned char *)psz, *out = in, c;
77
78     if( psz == NULL )
79         return NULL;
80
81     while( ( c = *in++ ) != '\0' )
82     {
83         switch( c )
84         {
85             case '%':
86             {
87                 char hex[3];
88
89                 if( ( ( hex[0] = *in++ ) == 0 )
90                  || ( ( hex[1] = *in++ ) == 0 ) )
91                     return NULL;
92
93                 hex[2] = '\0';
94                 *out++ = (unsigned char)strtoul( hex, NULL, 0x10 );
95                 break;
96             }
97
98             case '+': /* This is HTTP forms, not URI decoding... */
99                 *out++ = ' ';
100                 break;
101
102             default:
103                 /* Inserting non-ASCII or non-printable characters is unsafe,
104                  * and no sane browser will send these unencoded */
105                 if( ( c < 32 ) || ( c > 127 ) )
106                     *out++ = '?';
107                 else
108                     *out++ = c;
109         }
110     }
111     *out = '\0';
112     EnsureUTF8( psz );
113     return psz;
114 }
115
116 static inline bool isurisafe( int c )
117 {
118     /* These are the _unreserved_ URI characters (RFC3986 §2.3) */
119     return ( (unsigned char)( c - 'a' ) < 26 )
120             || ( (unsigned char)( c - 'A' ) < 26 )
121             || ( (unsigned char)( c - '0' ) < 10 )
122             || ( strchr( "-._~", c ) != NULL );
123 }
124
125 static char *encode_URI_bytes (const char *psz_uri, size_t len)
126 {
127     char *psz_enc = malloc (3 * len + 1), *out = psz_enc;
128     if (psz_enc == NULL)
129         return NULL;
130
131     for (size_t i = 0; i < len; i++)
132     {
133         static const char hex[16] = "0123456789ABCDEF";
134         uint8_t c = *psz_uri;
135
136         if( isurisafe( c ) )
137             *out++ = c;
138         /* This is URI encoding, not HTTP forms:
139          * Space is encoded as '%20', not '+'. */
140         else
141         {
142             *out++ = '%';
143             *out++ = hex[c >> 4];
144             *out++ = hex[c & 0xf];
145         }
146         psz_uri++;
147     }
148     *out++ = '\0';
149
150     out = realloc (psz_enc, out - psz_enc);
151     return out ? out : psz_enc; /* realloc() can fail (safe) */
152 }
153
154 /**
155  * Encodes an URI component (RFC3986 §2).
156  *
157  * @param psz_uri nul-terminated UTF-8 representation of the component.
158  * Obviously, you can't pass an URI containing a nul character, but you don't
159  * want to do that, do you?
160  *
161  * @return encoded string (must be free()'d), or NULL for ENOMEM.
162  */
163 char *encode_URI_component( const char *psz_uri )
164 {
165     return encode_URI_bytes (psz_uri, strlen (psz_uri));
166 }
167
168
169 static const struct xml_entity_s
170 {
171     char    psz_entity[8];
172     char    psz_char[4];
173 } xml_entities[] = {
174     /* Important: this list has to be in alphabetical order (psz_entity-wise) */
175     { "AElig;",  "Æ" },
176     { "Aacute;", "Á" },
177     { "Acirc;",  "Â" },
178     { "Agrave;", "À" },
179     { "Aring;",  "Å" },
180     { "Atilde;", "Ã" },
181     { "Auml;",   "Ä" },
182     { "Ccedil;", "Ç" },
183     { "Dagger;", "‡" },
184     { "ETH;",    "Ð" },
185     { "Eacute;", "É" },
186     { "Ecirc;",  "Ê" },
187     { "Egrave;", "È" },
188     { "Euml;",   "Ë" },
189     { "Iacute;", "Í" },
190     { "Icirc;",  "Î" },
191     { "Igrave;", "Ì" },
192     { "Iuml;",   "Ï" },
193     { "Ntilde;", "Ñ" },
194     { "OElig;",  "Œ" },
195     { "Oacute;", "Ó" },
196     { "Ocirc;",  "Ô" },
197     { "Ograve;", "Ò" },
198     { "Oslash;", "Ø" },
199     { "Otilde;", "Õ" },
200     { "Ouml;",   "Ö" },
201     { "Scaron;", "Š" },
202     { "THORN;",  "Þ" },
203     { "Uacute;", "Ú" },
204     { "Ucirc;",  "Û" },
205     { "Ugrave;", "Ù" },
206     { "Uuml;",   "Ü" },
207     { "Yacute;", "Ý" },
208     { "Yuml;",   "Ÿ" },
209     { "aacute;", "á" },
210     { "acirc;",  "â" },
211     { "acute;",  "´" },
212     { "aelig;",  "æ" },
213     { "agrave;", "à" },
214     { "amp;",    "&" },
215     { "apos;",   "'" },
216     { "aring;",  "å" },
217     { "atilde;", "ã" },
218     { "auml;",   "ä" },
219     { "bdquo;",  "„" },
220     { "brvbar;", "¦" },
221     { "ccedil;", "ç" },
222     { "cedil;",  "¸" },
223     { "cent;",   "¢" },
224     { "circ;",   "ˆ" },
225     { "copy;",   "©" },
226     { "curren;", "¤" },
227     { "dagger;", "†" },
228     { "deg;",    "°" },
229     { "divide;", "÷" },
230     { "eacute;", "é" },
231     { "ecirc;",  "ê" },
232     { "egrave;", "è" },
233     { "eth;",    "ð" },
234     { "euml;",   "ë" },
235     { "euro;",   "€" },
236     { "frac12;", "½" },
237     { "frac14;", "¼" },
238     { "frac34;", "¾" },
239     { "gt;",     ">" },
240     { "hellip;", "…" },
241     { "iacute;", "í" },
242     { "icirc;",  "î" },
243     { "iexcl;",  "¡" },
244     { "igrave;", "ì" },
245     { "iquest;", "¿" },
246     { "iuml;",   "ï" },
247     { "laquo;",  "«" },
248     { "ldquo;",  "“" },
249     { "lsaquo;", "‹" },
250     { "lsquo;",  "‘" },
251     { "lt;",     "<" },
252     { "macr;",   "¯" },
253     { "mdash;",  "—" },
254     { "micro;",  "µ" },
255     { "middot;", "·" },
256     { "nbsp;",   "\xc2\xa0" },
257     { "ndash;",  "–" },
258     { "not;",    "¬" },
259     { "ntilde;", "ñ" },
260     { "oacute;", "ó" },
261     { "ocirc;",  "ô" },
262     { "oelig;",  "œ" },
263     { "ograve;", "ò" },
264     { "ordf;",   "ª" },
265     { "ordm;",   "º" },
266     { "oslash;", "ø" },
267     { "otilde;", "õ" },
268     { "ouml;",   "ö" },
269     { "para;",   "¶" },
270     { "permil;", "‰" },
271     { "plusmn;", "±" },
272     { "pound;",  "£" },
273     { "quot;",   "\"" },
274     { "raquo;",  "»" },
275     { "rdquo;",  "”" },
276     { "reg;",    "®" },
277     { "rsaquo;", "›" },
278     { "rsquo;",  "’" },
279     { "sbquo;",  "‚" },
280     { "scaron;", "š" },
281     { "sect;",   "§" },
282     { "shy;",    "­" },
283     { "sup1;",   "¹" },
284     { "sup2;",   "²" },
285     { "sup3;",   "³" },
286     { "szlig;",  "ß" },
287     { "thorn;",  "þ" },
288     { "tilde;",  "˜" },
289     { "times;",  "×" },
290     { "trade;",  "™" },
291     { "uacute;", "ú" },
292     { "ucirc;",  "û" },
293     { "ugrave;", "ù" },
294     { "uml;",    "¨" },
295     { "uuml;",   "ü" },
296     { "yacute;", "ý" },
297     { "yen;",    "¥" },
298     { "yuml;",   "ÿ" },
299 };
300
301 static int cmp_entity (const void *key, const void *elem)
302 {
303     const struct xml_entity_s *ent = elem;
304     const char *name = key;
305
306     return strncmp (name, ent->psz_entity, strlen (ent->psz_entity));
307 }
308
309 /**
310  * Converts "&lt;", "&gt;" and "&amp;" to "<", ">" and "&"
311  * \param string to convert
312  */
313 void resolve_xml_special_chars( char *psz_value )
314 {
315     char *p_pos = psz_value;
316
317     while ( *psz_value )
318     {
319         if( *psz_value == '&' )
320         {
321             if( psz_value[1] == '#' )
322             {   /* &#xxx; Unicode code point */
323                 char *psz_end;
324                 unsigned long cp = strtoul( psz_value+2, &psz_end, 10 );
325                 if( *psz_end == ';' )
326                 {
327                     psz_value = psz_end + 1;
328                     if( cp == 0 )
329                         (void)0; /* skip nuls */
330                     else
331                     if( cp <= 0x7F )
332                     {
333                         *p_pos =            cp;
334                     }
335                     else
336                     /* Unicode code point outside ASCII.
337                      * &#xxx; representation is longer than UTF-8 :) */
338                     if( cp <= 0x7FF )
339                     {
340                         *p_pos++ = 0xC0 |  (cp >>  6);
341                         *p_pos   = 0x80 |  (cp        & 0x3F);
342                     }
343                     else
344                     if( cp <= 0xFFFF )
345                     {
346                         *p_pos++ = 0xE0 |  (cp >> 12);
347                         *p_pos++ = 0x80 | ((cp >>  6) & 0x3F);
348                         *p_pos   = 0x80 |  (cp        & 0x3F);
349                     }
350                     else
351                     if( cp <= 0x1FFFFF ) /* Outside the BMP */
352                     {   /* Unicode stops at 10FFFF, but who cares? */
353                         *p_pos++ = 0xF0 |  (cp >> 18);
354                         *p_pos++ = 0x80 | ((cp >> 12) & 0x3F);
355                         *p_pos++ = 0x80 | ((cp >>  6) & 0x3F);
356                         *p_pos   = 0x80 |  (cp        & 0x3F);
357                     }
358                 }
359                 else
360                 {
361                     /* Invalid entity number */
362                     *p_pos = *psz_value;
363                     psz_value++;
364                 }
365             }
366             else
367             {   /* Well-known XML entity */
368                 const struct xml_entity_s *ent;
369
370                 ent = bsearch (psz_value + 1, xml_entities,
371                                sizeof (xml_entities) / sizeof (*ent),
372                                sizeof (*ent), cmp_entity);
373                 if (ent != NULL)
374                 {
375                     size_t olen = strlen (ent->psz_char);
376                     memcpy (p_pos, ent->psz_char, olen);
377                     p_pos += olen - 1;
378                     psz_value += strlen (ent->psz_entity) + 1;
379                 }
380                 else
381                 {   /* No match */
382                     *p_pos = *psz_value;
383                     psz_value++;
384                 }
385             }
386         }
387         else
388         {
389             *p_pos = *psz_value;
390             psz_value++;
391         }
392
393         p_pos++;
394     }
395
396     *p_pos = '\0';
397 }
398
399 /**
400  * Converts '<', '>', '\"', '\'' and '&' to their html entities
401  * \param psz_content simple element content that is to be converted
402  */
403 char *convert_xml_special_chars( const char *psz_content )
404 {
405     char *psz_temp = malloc( 6 * strlen( psz_content ) + 1 );
406     const char *p_from = psz_content;
407     char *p_to   = psz_temp;
408
409     while ( *p_from )
410     {
411         if ( *p_from == '<' )
412         {
413             strcpy( p_to, "&lt;" );
414             p_to += 4;
415         }
416         else if ( *p_from == '>' )
417         {
418             strcpy( p_to, "&gt;" );
419             p_to += 4;
420         }
421         else if ( *p_from == '&' )
422         {
423             strcpy( p_to, "&amp;" );
424             p_to += 5;
425         }
426         else if( *p_from == '\"' )
427         {
428             strcpy( p_to, "&quot;" );
429             p_to += 6;
430         }
431         else if( *p_from == '\'' )
432         {
433             strcpy( p_to, "&#039;" );
434             p_to += 6;
435         }
436         else
437         {
438             *p_to = *p_from;
439             p_to++;
440         }
441         p_from++;
442     }
443     *p_to = '\0';
444
445     return psz_temp;
446 }
447
448 /* Base64 encoding */
449 char *vlc_b64_encode_binary( const uint8_t *src, size_t i_src )
450 {
451     static const char b64[] =
452            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
453
454     char *ret = malloc( ( i_src + 4 ) * 4 / 3 );
455     char *dst = ret;
456
457     if( dst == NULL )
458         return NULL;
459
460     while( i_src > 0 )
461     {
462         /* pops (up to) 3 bytes of input, push 4 bytes */
463         uint32_t v;
464
465         /* 1/3 -> 1/4 */
466         v = *src++ << 24;
467         *dst++ = b64[v >> 26];
468         v = v << 6;
469
470         /* 2/3 -> 2/4 */
471         if( i_src >= 2 )
472             v |= *src++ << 22;
473         *dst++ = b64[v >> 26];
474         v = v << 6;
475
476         /* 3/3 -> 3/4 */
477         if( i_src >= 3 )
478             v |= *src++ << 20; // 3/3
479         *dst++ = ( i_src >= 2 ) ? b64[v >> 26] : '='; // 3/4
480         v = v << 6;
481
482         /* -> 4/4 */
483         *dst++ = ( i_src >= 3 ) ? b64[v >> 26] : '='; // 4/4
484
485         if( i_src <= 3 )
486             break;
487         i_src -= 3;
488     }
489
490     *dst = '\0';
491
492     return ret;
493 }
494
495 char *vlc_b64_encode( const char *src )
496 {
497     if( src )
498         return vlc_b64_encode_binary( (const uint8_t*)src, strlen(src) );
499     else
500         return vlc_b64_encode_binary( (const uint8_t*)"", 0 );
501 }
502
503 /* Base64 decoding */
504 size_t vlc_b64_decode_binary_to_buffer( uint8_t *p_dst, size_t i_dst, const char *p_src )
505 {
506     static const int b64[256] = {
507         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
508         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
509         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
510         52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
511         -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
512         15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
513         -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
514         41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
515         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
516         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
517         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
518         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
519         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
520         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
521         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
522         -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
523     };
524     uint8_t *p_start = p_dst;
525     uint8_t *p = (uint8_t *)p_src;
526
527     int i_level;
528     int i_last;
529
530     for( i_level = 0, i_last = 0; (size_t)( p_dst - p_start ) < i_dst && *p != '\0'; p++ )
531     {
532         const int c = b64[(unsigned int)*p];
533         if( c == -1 )
534             continue;
535
536         switch( i_level )
537         {
538             case 0:
539                 i_level++;
540                 break;
541             case 1:
542                 *p_dst++ = ( i_last << 2 ) | ( ( c >> 4)&0x03 );
543                 i_level++;
544                 break;
545             case 2:
546                 *p_dst++ = ( ( i_last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
547                 i_level++;
548                 break;
549             case 3:
550                 *p_dst++ = ( ( i_last &0x03 ) << 6 ) | c;
551                 i_level = 0;
552         }
553         i_last = c;
554     }
555
556     return p_dst - p_start;
557 }
558 size_t vlc_b64_decode_binary( uint8_t **pp_dst, const char *psz_src )
559 {
560     const int i_src = strlen( psz_src );
561     uint8_t   *p_dst;
562
563     *pp_dst = p_dst = malloc( i_src );
564     if( !p_dst )
565         return 0;
566     return  vlc_b64_decode_binary_to_buffer( p_dst, i_src, psz_src );
567 }
568 char *vlc_b64_decode( const char *psz_src )
569 {
570     const int i_src = strlen( psz_src );
571     char *p_dst = malloc( i_src + 1 );
572     size_t i_dst;
573     if( !p_dst )
574         return NULL;
575
576     i_dst = vlc_b64_decode_binary_to_buffer( (uint8_t*)p_dst, i_src, psz_src );
577     p_dst[i_dst] = '\0';
578
579     return p_dst;
580 }
581
582 /**
583  * Formats current time into a heap-allocated string.
584  * @param tformat time format (as with C strftime())
585  * @return an allocated string (must be free()'d), or NULL on memory error.
586  */
587 char *str_format_time( const char *tformat )
588 {
589     time_t curtime;
590     struct tm loctime;
591
592     if (strcmp (tformat, "") == 0)
593         return strdup (""); /* corner case w.r.t. strftime() return value */
594
595     /* Get the current time.  */
596     time( &curtime );
597
598     /* Convert it to local time representation.  */
599     localtime_r( &curtime, &loctime );
600     for (size_t buflen = strlen (tformat) + 32;; buflen += 32)
601     {
602         char *str = malloc (buflen);
603         if (str == NULL)
604             return NULL;
605
606         size_t len = strftime (str, buflen, tformat, &loctime);
607         if (len > 0)
608         {
609             char *ret = realloc (str, len + 1);
610             return ret ? ret : str; /* <- this cannot fail */
611         }
612     }
613     assert (0);
614 }
615
616 #define INSERT_STRING( string )                                     \
617                     if( string != NULL )                            \
618                     {                                               \
619                         int len = strlen( string );                 \
620                         dst = realloc( dst, i_size = i_size + len );\
621                         memcpy( (dst+d), string, len );             \
622                         d += len;                                   \
623                         free( string );                             \
624                     }                                               \
625                     else if( !b_empty_if_na )                       \
626                     {                                               \
627                         *(dst+d) = '-';                             \
628                         d++;                                        \
629                     }                                               \
630
631 /* same than INSERT_STRING, except that string won't be freed */
632 #define INSERT_STRING_NO_FREE( string )                             \
633                     {                                               \
634                         int len = strlen( string );                 \
635                         dst = realloc( dst, i_size = i_size + len );\
636                         memcpy( dst+d, string, len );               \
637                         d += len;                                   \
638                     }
639 char *__str_format_meta( vlc_object_t *p_object, const char *string )
640 {
641     const char *s = string;
642     bool b_is_format = false;
643     bool b_empty_if_na = false;
644     char buf[10];
645     int i_size = strlen( string ) + 1; /* +1 to store '\0' */
646     char *dst = strdup( string );
647     if( !dst ) return NULL;
648     int d = 0;
649
650     playlist_t *p_playlist = pl_Hold( p_object );
651     input_thread_t *p_input = playlist_CurrentInput( p_playlist );
652     input_item_t *p_item = NULL;
653     pl_Release( p_object );
654     if( p_input )
655     {
656         p_item = input_GetItem(p_input);
657     }
658
659     while( *s )
660     {
661         if( b_is_format )
662         {
663             switch( *s )
664             {
665                 case 'a':
666                     if( p_item )
667                     {
668                         INSERT_STRING( input_item_GetArtist( p_item ) );
669                     }
670                     break;
671                 case 'b':
672                     if( p_item )
673                     {
674                         INSERT_STRING( input_item_GetAlbum( p_item ) );
675                     }
676                     break;
677                 case 'c':
678                     if( p_item )
679                     {
680                         INSERT_STRING( input_item_GetCopyright( p_item ) );
681                     }
682                     break;
683                 case 'd':
684                     if( p_item )
685                     {
686                         INSERT_STRING( input_item_GetDescription( p_item ) );
687                     }
688                     break;
689                 case 'e':
690                     if( p_item )
691                     {
692                         INSERT_STRING( input_item_GetEncodedBy( p_item ) );
693                     }
694                     break;
695                 case 'f':
696                     if( p_item && p_item->p_stats )
697                     {
698                         vlc_mutex_lock( &p_item->p_stats->lock );
699                         snprintf( buf, 10, "%d",
700                                   p_item->p_stats->i_displayed_pictures );
701                         vlc_mutex_unlock( &p_item->p_stats->lock );
702                     }
703                     else
704                     {
705                         sprintf( buf, b_empty_if_na ? "" : "-" );
706                     }
707                     INSERT_STRING_NO_FREE( buf );
708                     break;
709                 case 'g':
710                     if( p_item )
711                     {
712                         INSERT_STRING( input_item_GetGenre( p_item ) );
713                     }
714                     break;
715                 case 'l':
716                     if( p_item )
717                     {
718                         INSERT_STRING( input_item_GetLanguage( p_item ) );
719                     }
720                     break;
721                 case 'n':
722                     if( p_item )
723                     {
724                         INSERT_STRING( input_item_GetTrackNum( p_item ) );
725                     }
726                     break;
727                 case 'p':
728                     if( p_item )
729                     {
730                         INSERT_STRING( input_item_GetNowPlaying( p_item ) );
731                     }
732                     break;
733                 case 'r':
734                     if( p_item )
735                     {
736                         INSERT_STRING( input_item_GetRating( p_item ) );
737                     }
738                     break;
739                 case 's':
740                 {
741                     char *lang = NULL;
742                     if( p_input )
743                         lang = var_GetNonEmptyString( p_input, "sub-language" );
744                     if( lang == NULL )
745                         lang = strdup( b_empty_if_na ? "" : "-" );
746                     INSERT_STRING( lang );
747                     break;
748                 }
749                 case 't':
750                     if( p_item )
751                     {
752                         INSERT_STRING( input_item_GetTitle( p_item ) );
753                     }
754                     break;
755                 case 'u':
756                     if( p_item )
757                     {
758                         INSERT_STRING( input_item_GetURL( p_item ) );
759                     }
760                     break;
761                 case 'A':
762                     if( p_item )
763                     {
764                         INSERT_STRING( input_item_GetDate( p_item ) );
765                     }
766                     break;
767                 case 'B':
768                     if( p_input )
769                     {
770                         snprintf( buf, 10, "%d",
771                                   var_GetInteger( p_input, "bit-rate" )/1000 );
772                     }
773                     else
774                     {
775                         sprintf( buf, b_empty_if_na ? "" : "-" );
776                     }
777                     INSERT_STRING_NO_FREE( buf );
778                     break;
779                 case 'C':
780                     if( p_input )
781                     {
782                         snprintf( buf, 10, "%d",
783                                   var_GetInteger( p_input, "chapter" ) );
784                     }
785                     else
786                     {
787                         sprintf( buf, b_empty_if_na ? "" : "-" );
788                     }
789                     INSERT_STRING_NO_FREE( buf );
790                     break;
791                 case 'D':
792                     if( p_item )
793                     {
794                         mtime_t i_duration = input_item_GetDuration( p_item );
795                         snprintf( buf, 10, "%02d:%02d:%02d",
796                                  (int)(i_duration/(3600000000)),
797                                  (int)((i_duration/(60000000))%60),
798                                  (int)((i_duration/1000000)%60) );
799                     }
800                     else
801                     {
802                         snprintf( buf, 10, b_empty_if_na ? "" : "--:--:--" );
803                     }
804                     INSERT_STRING_NO_FREE( buf );
805                     break;
806                 case 'F':
807                     if( p_item )
808                     {
809                         INSERT_STRING( input_item_GetURI( p_item ) );
810                     }
811                     break;
812                 case 'I':
813                     if( p_input )
814                     {
815                         snprintf( buf, 10, "%d",
816                                   var_GetInteger( p_input, "title" ) );
817                     }
818                     else
819                     {
820                         sprintf( buf, b_empty_if_na ? "" : "-" );
821                     }
822                     INSERT_STRING_NO_FREE( buf );
823                     break;
824                 case 'L':
825                     if( p_item && p_input )
826                     {
827                         mtime_t i_duration = input_item_GetDuration( p_item );
828                         int64_t i_time = var_GetInteger( p_input, "time" );
829                         snprintf( buf, 10, "%02d:%02d:%02d",
830                      (int)( ( i_duration - i_time ) / 3600000000 ),
831                      (int)( ( ( i_duration - i_time ) / 60000000 ) % 60 ),
832                      (int)( ( ( i_duration - i_time ) / 1000000 ) % 60 ) );
833                     }
834                     else
835                     {
836                         snprintf( buf, 10, b_empty_if_na ? "" : "--:--:--" );
837                     }
838                     INSERT_STRING_NO_FREE( buf );
839                     break;
840                 case 'N':
841                     if( p_item )
842                     {
843                         INSERT_STRING( input_item_GetName( p_item ) );
844                     }
845                     break;
846                 case 'O':
847                 {
848                     char *lang = NULL;
849                     if( p_input )
850                         lang = var_GetNonEmptyString( p_input,
851                                                       "audio-language" );
852                     if( lang == NULL )
853                         lang = strdup( b_empty_if_na ? "" : "-" );
854                     INSERT_STRING( lang );
855                     break;
856                 }
857                 case 'P':
858                     if( p_input )
859                     {
860                         snprintf( buf, 10, "%2.1lf",
861                                   var_GetFloat( p_input, "position" ) * 100. );
862                     }
863                     else
864                     {
865                         snprintf( buf, 10, b_empty_if_na ? "" : "--.-%%" );
866                     }
867                     INSERT_STRING_NO_FREE( buf );
868                     break;
869                 case 'R':
870                     if( p_input )
871                     {
872                         int r = var_GetInteger( p_input, "rate" );
873                         snprintf( buf, 10, "%d.%d", r/1000, r%1000 );
874                     }
875                     else
876                     {
877                         sprintf( buf, b_empty_if_na ? "" : "-" );
878                     }
879                     INSERT_STRING_NO_FREE( buf );
880                     break;
881                 case 'S':
882                     if( p_input )
883                     {
884                         int r = var_GetInteger( p_input, "sample-rate" );
885                         snprintf( buf, 10, "%d.%d", r/1000, (r/100)%10 );
886                     }
887                     else
888                     {
889                         sprintf( buf, b_empty_if_na ? "" : "-" );
890                     }
891                     INSERT_STRING_NO_FREE( buf );
892                     break;
893                 case 'T':
894                     if( p_input )
895                     {
896                         int64_t i_time = var_GetInteger( p_input, "time" );
897                         snprintf( buf, 10, "%02d:%02d:%02d",
898                             (int)( i_time / ( 3600000000 ) ),
899                             (int)( ( i_time / ( 60000000 ) ) % 60 ),
900                             (int)( ( i_time / 1000000 ) % 60 ) );
901                     }
902                     else
903                     {
904                         snprintf( buf, 10, b_empty_if_na ? "" :  "--:--:--" );
905                     }
906                     INSERT_STRING_NO_FREE( buf );
907                     break;
908                 case 'U':
909                     if( p_item )
910                     {
911                         INSERT_STRING( input_item_GetPublisher( p_item ) );
912                     }
913                     break;
914                 case 'V':
915                 {
916                     audio_volume_t volume;
917                     aout_VolumeGet( p_object, &volume );
918                     snprintf( buf, 10, "%d", volume );
919                     INSERT_STRING_NO_FREE( buf );
920                     break;
921                 }
922                 case '_':
923                     *(dst+d) = '\n';
924                     d++;
925                     break;
926
927                 case ' ':
928                     b_empty_if_na = true;
929                     break;
930
931                 default:
932                     *(dst+d) = *s;
933                     d++;
934                     break;
935             }
936             if( *s != ' ' )
937                 b_is_format = false;
938         }
939         else if( *s == '$' )
940         {
941             b_is_format = true;
942             b_empty_if_na = false;
943         }
944         else
945         {
946             *(dst+d) = *s;
947             d++;
948         }
949         s++;
950     }
951     *(dst+d) = '\0';
952
953     if( p_input )
954         vlc_object_release( p_input );
955
956     return dst;
957 }
958 #undef INSERT_STRING
959 #undef INSERT_STRING_NO_FREE
960
961 /**
962  * Apply str format time and str format meta
963  */
964 char *__str_format( vlc_object_t *p_this, const char *psz_src )
965 {
966     char *psz_buf1, *psz_buf2;
967     psz_buf1 = str_format_time( psz_src );
968     psz_buf2 = str_format_meta( p_this, psz_buf1 );
969     free( psz_buf1 );
970     return psz_buf2;
971 }
972
973 /**
974  * Remove forbidden characters from filenames (including slashes)
975  */
976 char* filename_sanitize( const char *str_origin )
977 {
978     char *str = strdup( str_origin );
979     char *str_base = str;
980     if( *str == '.' && (str[1] == '\0' || (str[1] == '.' && str[2] == '\0' ) ) )
981     {
982         while( *str )
983         {
984             *str = '_';
985             str++;
986         }
987         return str_base;
988     }
989
990 #if defined( WIN32 )
991     // Change leading spaces into underscores
992     while( *str && *str == ' ' )
993         *str++ = '_';
994 #endif
995
996     while( *str )
997     {
998         switch( *str )
999         {
1000             case '/':
1001 #if defined( __APPLE__ )
1002             case ':':
1003 #elif defined( WIN32 )
1004             case '\\':
1005             case '*':
1006             case '"':
1007             case '?':
1008             case ':':
1009             case '|':
1010             case '<':
1011             case '>':
1012 #endif
1013                 *str = '_';
1014         }
1015         str++;
1016     }
1017
1018 #if defined( WIN32 )
1019     // Change trailing spaces into underscores
1020     str--;
1021     while( str != str_base )
1022     {
1023         if( *str != ' ' )
1024             break;
1025         *str-- = '_';
1026     }
1027 #endif
1028
1029     return str_base;
1030 }
1031
1032 /**
1033  * Remove forbidden characters from full paths (leaves slashes)
1034  */
1035 void path_sanitize( char *str )
1036 {
1037 #ifdef WIN32
1038     /* check drive prefix if path is absolute */
1039     if( (((unsigned char)(str[0] - 'A') < 26)
1040       || ((unsigned char)(str[0] - 'a') < 26)) && (':' == str[1]) )
1041         str += 2;
1042 #endif
1043     while( *str )
1044     {
1045 #if defined( __APPLE__ )
1046         if( *str == ':' )
1047             *str = '_';
1048 #elif defined( WIN32 )
1049         if( strchr( "*\"?:|<>", *str ) )
1050             *str = '_';
1051         if( *str == '/' )
1052             *str = DIR_SEP_CHAR;
1053 #endif
1054         str++;
1055     }
1056 }
1057
1058 #include <vlc_url.h>
1059
1060 /**
1061  * Convert a file path to an URI. If already an URI, do nothing.
1062  */
1063 char *make_URI (const char *path)
1064 {
1065     if (path == NULL)
1066         return NULL;
1067     if (strstr (path, "://") != NULL)
1068         return strdup (path); /* Already an URI */
1069     /* Note: VLC cannot handle URI schemes without double slash after the
1070      * scheme name (such as mailto: or news:). */
1071
1072     char *buf;
1073 #ifdef WIN32
1074     if (isalpha (path[0]) && (path[1] == ':'))
1075     {
1076         if (asprintf (&buf, "file:///%c:", path[0]) == -1)
1077             buf = NULL;
1078         path += 2;
1079     }
1080     else
1081 #endif
1082 #if 0
1083     /* Windows UNC paths (file://host/share/path instead of file:///path) */
1084     if (!strncmp (path, "\\\\", 2))
1085     {
1086         path += 2;
1087         buf = strdup ("file://");
1088     }
1089     else
1090 #endif
1091     if (path[0] != DIR_SEP_CHAR)
1092     {   /* Relative path: prepend the current working directory */
1093         char cwd[PATH_MAX];
1094
1095         if (getcwd (cwd, sizeof (cwd)) == NULL) /* FIXME: UTF8? */
1096             return NULL;
1097         if (asprintf (&buf, "%s/%s", cwd, path) == -1)
1098             return NULL;
1099         char *ret = make_URI (buf);
1100         free (buf);
1101         return ret;
1102     }
1103     else
1104         buf = strdup ("file://");
1105     if (buf == NULL)
1106         return NULL;
1107
1108     assert (path[0] == DIR_SEP_CHAR);
1109
1110     /* Absolute file path */
1111     for (const char *ptr = path + 1;; ptr++)
1112     {
1113         size_t len = strcspn (ptr, DIR_SEP);
1114         char *component = encode_URI_bytes (ptr, len);
1115         if (component == NULL)
1116         {
1117             free (buf);
1118             return NULL;
1119         }
1120         char *uri;
1121         int val = asprintf (&uri, "%s/%s", buf, component);
1122         free (component);
1123         free (buf);
1124         if (val == -1)
1125             return NULL;
1126         buf = uri;
1127         ptr += len;
1128         if (*ptr == '\0')
1129             return buf;
1130     }
1131 }