]> git.sesse.net Git - vlc/blob - src/extras/libc.c
Don't include config.h from the headers - refs #297.
[vlc] / src / extras / libc.c
1 /*****************************************************************************
2  * libc.c: Extra libc function for some systems.
3  *****************************************************************************
4  * Copyright (C) 2002-2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          Gildas Bazin <gbazin@videolan.org>
10  *          Derk-Jan Hartman <hartman at videolan dot org>
11  *          Christophe Massiot <massiot@via.ecp.fr>
12  *          Rémi Denis-Courmont <rem à videolan.org>
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
27  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc/vlc.h>
33
34 #include <ctype.h>
35
36
37 #undef iconv_t
38 #undef iconv_open
39 #undef iconv
40 #undef iconv_close
41
42 #if defined(HAVE_ICONV)
43 #   include <iconv.h>
44 #endif
45
46 #ifdef HAVE_DIRENT_H
47 #   include <dirent.h>
48 #endif
49
50 #ifdef HAVE_SIGNAL_H
51 #   include <signal.h>
52 #endif
53
54 #ifdef HAVE_FORK
55 #   include <sys/time.h>
56 #   include <unistd.h>
57 #   include <errno.h>
58 #   include <sys/wait.h>
59 #   include <fcntl.h>
60 #   include <sys/socket.h>
61 #   include <sys/poll.h>
62 #endif
63
64 #if defined(WIN32) || defined(UNDER_CE)
65 #   undef _wopendir
66 #   undef _wreaddir
67 #   undef _wclosedir
68 #   undef rewinddir
69 #   undef seekdir
70 #   undef telldir
71 #   define WIN32_LEAN_AND_MEAN
72 #   include <windows.h>
73 #endif
74
75 #ifdef UNDER_CE
76 #   define strcoll strcmp
77 #endif
78
79 /*****************************************************************************
80  * getenv: just in case, but it should never be called
81  *****************************************************************************/
82 #if !defined( HAVE_GETENV )
83 char *vlc_getenv( const char *name )
84 {
85     return NULL;
86 }
87 #endif
88
89 /*****************************************************************************
90  * strdup: returns a malloc'd copy of a string
91  *****************************************************************************/
92 #if !defined( HAVE_STRDUP )
93 char *vlc_strdup( const char *string )
94 {
95     return strndup( string, strlen( string ) );
96 }
97 #endif
98
99 /*****************************************************************************
100  * strndup: returns a malloc'd copy of at most n bytes of string
101  * Does anyone know whether or not it will be present in Jaguar?
102  *****************************************************************************/
103 #if !defined( HAVE_STRNDUP )
104 char *vlc_strndup( const char *string, size_t n )
105 {
106     char *psz;
107     size_t len = strlen( string );
108
109     len = __MIN( len, n );
110     psz = (char*)malloc( len + 1 );
111     if( psz != NULL )
112     {
113         memcpy( (void*)psz, (const void*)string, len );
114         psz[ len ] = 0;
115     }
116
117     return psz;
118 }
119 #endif
120
121 /*****************************************************************************
122  * strnlen:
123  *****************************************************************************/
124 #if !defined( HAVE_STRNLEN )
125 size_t vlc_strnlen( const char *psz, size_t n )
126 {
127     const char *psz_end = memchr( psz, 0, n );
128     return psz_end ? (size_t)( psz_end - psz ) : n;
129 }
130 #endif
131
132 /*****************************************************************************
133  * strcasecmp: compare two strings ignoring case
134  *****************************************************************************/
135 #if !defined( HAVE_STRCASECMP ) && !defined( HAVE_STRICMP )
136 int vlc_strcasecmp( const char *s1, const char *s2 )
137 {
138     int c1, c2;
139     if( !s1 || !s2 ) return  -1;
140
141     while( *s1 && *s2 )
142     {
143         c1 = tolower(*s1);
144         c2 = tolower(*s2);
145
146         if( c1 != c2 ) return (c1 < c2 ? -1 : 1);
147         s1++; s2++;
148     }
149
150     if( !*s1 && !*s2 ) return 0;
151     else return (*s1 ? 1 : -1);
152 }
153 #endif
154
155 /*****************************************************************************
156  * strncasecmp: compare n chars from two strings ignoring case
157  *****************************************************************************/
158 #if !defined( HAVE_STRNCASECMP ) && !defined( HAVE_STRNICMP )
159 int vlc_strncasecmp( const char *s1, const char *s2, size_t n )
160 {
161     int c1, c2;
162     if( !s1 || !s2 ) return  -1;
163
164     while( n > 0 && *s1 && *s2 )
165     {
166         c1 = tolower(*s1);
167         c2 = tolower(*s2);
168
169         if( c1 != c2 ) return (c1 < c2 ? -1 : 1);
170         s1++; s2++; n--;
171     }
172
173     if( !n || (!*s1 && !*s2) ) return 0;
174     else return (*s1 ? 1 : -1);
175 }
176 #endif
177
178 /******************************************************************************
179  * strcasestr: find a substring (little) in another substring (big)
180  * Case sensitive. Return NULL if not found, return big if little == null
181  *****************************************************************************/
182 #if !defined( HAVE_STRCASESTR ) && !defined( HAVE_STRISTR )
183 char * vlc_strcasestr( const char *psz_big, const char *psz_little )
184 {
185     char *p_pos = (char *)psz_big;
186
187     if( !psz_big || !psz_little || !*psz_little ) return p_pos;
188  
189     while( *p_pos )
190     {
191         if( toupper( *p_pos ) == toupper( *psz_little ) )
192         {
193             char * psz_cur1 = p_pos + 1;
194             char * psz_cur2 = (char *)psz_little + 1;
195             while( *psz_cur1 && *psz_cur2 &&
196                    toupper( *psz_cur1 ) == toupper( *psz_cur2 ) )
197             {
198                 psz_cur1++;
199                 psz_cur2++;
200             }
201             if( !*psz_cur2 ) return p_pos;
202         }
203         p_pos++;
204     }
205     return NULL;
206 }
207 #endif
208
209 /*****************************************************************************
210  * vasprintf:
211  *****************************************************************************/
212 #if !defined(HAVE_VASPRINTF) || defined(__APPLE__) || defined(SYS_BEOS)
213 int vlc_vasprintf(char **strp, const char *fmt, va_list ap)
214 {
215     /* Guess we need no more than 100 bytes. */
216     int     i_size = 100;
217     char    *p = malloc( i_size );
218     int     n;
219
220     if( p == NULL )
221     {
222         *strp = NULL;
223         return -1;
224     }
225
226     for( ;; )
227     {
228         /* Try to print in the allocated space. */
229         n = vsnprintf( p, i_size, fmt, ap );
230
231         /* If that worked, return the string. */
232         if (n > -1 && n < i_size)
233         {
234             *strp = p;
235             return strlen( p );
236         }
237         /* Else try again with more space. */
238         if (n > -1)    /* glibc 2.1 */
239         {
240            i_size = n+1; /* precisely what is needed */
241         }
242         else           /* glibc 2.0 */
243         {
244            i_size *= 2;  /* twice the old size */
245         }
246         if( (p = realloc( p, i_size ) ) == NULL)
247         {
248             *strp = NULL;
249             return -1;
250         }
251     }
252 }
253 #endif
254
255 /*****************************************************************************
256  * asprintf:
257  *****************************************************************************/
258 #if !defined(HAVE_ASPRINTF) || defined(__APPLE__) || defined(SYS_BEOS)
259 int vlc_asprintf( char **strp, const char *fmt, ... )
260 {
261     va_list args;
262     int i_ret;
263
264     va_start( args, fmt );
265     i_ret = vasprintf( strp, fmt, args );
266     va_end( args );
267
268     return i_ret;
269 }
270 #endif
271
272 /*****************************************************************************
273  * atof: convert a string to a double.
274  *****************************************************************************/
275 #if !defined( HAVE_ATOF )
276 double vlc_atof( const char *nptr )
277 {
278     double f_result;
279     wchar_t *psz_tmp = NULL;
280     int i_len = strlen( nptr ) + 1;
281
282     psz_tmp = malloc( i_len * sizeof(wchar_t) );
283     if( !psz_tmp )
284         return NULL;
285     MultiByteToWideChar( CP_ACP, 0, nptr, -1, psz_tmp, i_len );
286     f_result = wcstod( psz_tmp, NULL );
287     free( psz_tmp );
288
289     return f_result;
290 }
291 #endif
292
293 /*****************************************************************************
294  * strtoll: convert a string to a 64 bits int.
295  *****************************************************************************/
296 #if !defined( HAVE_STRTOLL )
297 int64_t vlc_strtoll( const char *nptr, char **endptr, int base )
298 {
299     int64_t i_value = 0;
300     int sign = 1, newbase = base ? base : 10;
301
302     while( isspace(*nptr) ) nptr++;
303
304     if( *nptr == '-' )
305     {
306         sign = -1;
307         nptr++;
308     }
309
310     /* Try to detect base */
311     if( *nptr == '0' )
312     {
313         newbase = 8;
314         nptr++;
315
316         if( *nptr == 'x' )
317         {
318             newbase = 16;
319             nptr++;
320         }
321     }
322
323     if( base && newbase != base )
324     {
325         if( endptr ) *endptr = (char *)nptr;
326         return i_value;
327     }
328
329     switch( newbase )
330     {
331         case 10:
332             while( *nptr >= '0' && *nptr <= '9' )
333             {
334                 i_value *= 10;
335                 i_value += ( *nptr++ - '0' );
336             }
337             if( endptr ) *endptr = (char *)nptr;
338             break;
339
340         case 16:
341             while( (*nptr >= '0' && *nptr <= '9') ||
342                    (*nptr >= 'a' && *nptr <= 'f') ||
343                    (*nptr >= 'A' && *nptr <= 'F') )
344             {
345                 int i_valc = 0;
346                 if(*nptr >= '0' && *nptr <= '9') i_valc = *nptr - '0';
347                 else if(*nptr >= 'a' && *nptr <= 'f') i_valc = *nptr - 'a' +10;
348                 else if(*nptr >= 'A' && *nptr <= 'F') i_valc = *nptr - 'A' +10;
349                 i_value *= 16;
350                 i_value += i_valc;
351                 nptr++;
352             }
353             if( endptr ) *endptr = (char *)nptr;
354             break;
355
356         default:
357             i_value = strtol( nptr, endptr, newbase );
358             break;
359     }
360
361     return i_value * sign;
362 }
363 #endif
364
365 /*****************************************************************************
366  * atoll: convert a string to a 64 bits int.
367  *****************************************************************************/
368 #if !defined( HAVE_ATOLL )
369 int64_t vlc_atoll( const char *nptr )
370 {
371     return strtoll( nptr, (char **)NULL, 10 );
372 }
373 #endif
374
375 /*****************************************************************************
376  * lldiv: returns quotient and remainder
377  *****************************************************************************/
378 #if defined(SYS_BEOS) \
379  || (defined (__FreeBSD__) && (__FreeBSD__ < 5))
380 lldiv_t vlc_lldiv( long long numer, long long denom )
381 {
382     lldiv_t d;
383     d.quot = numer / denom;
384     d.rem  = numer % denom;
385     return d;
386 }
387 #endif
388
389
390 /**
391  * Copy a string to a sized buffer. The result is always nul-terminated
392  * (contrary to strncpy()).
393  *
394  * @param dest destination buffer
395  * @param src string to be copied
396  * @param len maximum number of characters to be copied plus one for the
397  * terminating nul.
398  *
399  * @return strlen(src)
400  */
401 #ifndef HAVE_STRLCPY
402 extern size_t vlc_strlcpy (char *tgt, const char *src, size_t bufsize)
403 {
404     size_t length;
405
406     for (length = 1; (length < bufsize) && *src; length++)
407         *tgt++ = *src++;
408
409     if (bufsize)
410         *tgt = '\0';
411
412     while (*src++)
413         length++;
414
415     return length - 1;
416 }
417 #endif
418
419 /*****************************************************************************
420  * vlc_*dir_wrapper: wrapper under Windows to return the list of drive letters
421  * when called with an empty argument or just '\'
422  *****************************************************************************/
423 #if defined(WIN32) && !defined(UNDER_CE)
424 #   include <assert.h>
425
426 typedef struct vlc_DIR
427 {
428     _WDIR *p_real_dir;
429     int i_drives;
430     struct _wdirent dd_dir;
431     vlc_bool_t b_insert_back;
432 } vlc_DIR;
433
434 void *vlc_wopendir( const wchar_t *wpath )
435 {
436     vlc_DIR *p_dir = NULL;
437     _WDIR *p_real_dir = NULL;
438
439     if ( wpath == NULL || wpath[0] == '\0'
440           || (wcscmp (wpath, L"\\") == 0) )
441     {
442         /* Special mode to list drive letters */
443         p_dir = malloc( sizeof(vlc_DIR) );
444         if( !p_dir )
445             return NULL;
446         p_dir->p_real_dir = NULL;
447         p_dir->i_drives = GetLogicalDrives();
448         return (void *)p_dir;
449     }
450
451     p_real_dir = _wopendir( wpath );
452     if ( p_real_dir == NULL )
453         return NULL;
454
455     p_dir = malloc( sizeof(vlc_DIR) );
456     if( !p_dir )
457     {
458         _wclosedir( p_real_dir );
459         return NULL;
460     }
461     p_dir->p_real_dir = p_real_dir;
462
463     assert (wpath[0]); // wpath[1] is defined
464     p_dir->b_insert_back = !wcscmp (wpath + 1, L":\\");
465     return (void *)p_dir;
466 }
467
468 struct _wdirent *vlc_wreaddir( void *_p_dir )
469 {
470     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
471     unsigned int i;
472     DWORD i_drives;
473
474     if ( p_dir->p_real_dir != NULL )
475     {
476         if ( p_dir->b_insert_back )
477         {
478             /* Adds "..", gruik! */
479             p_dir->dd_dir.d_ino = 0;
480             p_dir->dd_dir.d_reclen = 0;
481             p_dir->dd_dir.d_namlen = 2;
482             wcscpy( p_dir->dd_dir.d_name, L".." );
483             p_dir->b_insert_back = VLC_FALSE;
484             return &p_dir->dd_dir;
485         }
486
487         return _wreaddir( p_dir->p_real_dir );
488     }
489
490     /* Drive letters mode */
491     i_drives = p_dir->i_drives;
492     if ( !i_drives )
493         return NULL; /* end */
494
495     for ( i = 0; i < sizeof(DWORD)*8; i++, i_drives >>= 1 )
496         if ( i_drives & 1 ) break;
497
498     if ( i >= 26 )
499         return NULL; /* this should not happen */
500
501     swprintf( p_dir->dd_dir.d_name, L"%c:\\", 'A' + i );
502     p_dir->dd_dir.d_namlen = wcslen(p_dir->dd_dir.d_name);
503     p_dir->i_drives &= ~(1UL << i);
504     return &p_dir->dd_dir;
505 }
506
507 int vlc_wclosedir( void *_p_dir )
508 {
509     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
510     int i_ret = 0;
511
512     if ( p_dir->p_real_dir != NULL )
513         i_ret = _wclosedir( p_dir->p_real_dir );
514
515     free( p_dir );
516     return i_ret;
517 }
518
519 void vlc_rewinddir( void *_p_dir )
520 {
521     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
522
523     if ( p_dir->p_real_dir != NULL )
524         _wrewinddir( p_dir->p_real_dir );
525 }
526
527 void vlc_seekdir( void *_p_dir, long loc)
528 {
529     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
530
531     if ( p_dir->p_real_dir != NULL )
532         _wseekdir( p_dir->p_real_dir, loc );
533 }
534
535 long vlc_telldir( void *_p_dir )
536 {
537     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
538
539     if ( p_dir->p_real_dir != NULL )
540         return _wtelldir( p_dir->p_real_dir );
541     return 0;
542 }
543 #endif
544
545 /*****************************************************************************
546  * scandir: scan a directory alpha-sorted
547  *****************************************************************************/
548 #if !defined( HAVE_SCANDIR )
549 /* FIXME: I suspect this is dead code -> utf8_scandir */
550 #ifdef WIN32
551 # undef opendir
552 # undef readdir
553 # undef closedir
554 #endif
555 int vlc_alphasort( const struct dirent **a, const struct dirent **b )
556 {
557     return strcoll( (*a)->d_name, (*b)->d_name );
558 }
559
560 int vlc_scandir( const char *name, struct dirent ***namelist,
561                     int (*filter) ( const struct dirent * ),
562                     int (*compar) ( const struct dirent **,
563                                     const struct dirent ** ) )
564 {
565     DIR            * p_dir;
566     struct dirent  * p_content;
567     struct dirent ** pp_list;
568     int              ret, size;
569
570     if( !namelist || !( p_dir = opendir( name ) ) ) return -1;
571
572     ret     = 0;
573     pp_list = NULL;
574     while( ( p_content = readdir( p_dir ) ) )
575     {
576         if( filter && !filter( p_content ) )
577         {
578             continue;
579         }
580         pp_list = realloc( pp_list, ( ret + 1 ) * sizeof( struct dirent * ) );
581         size = sizeof( struct dirent ) + strlen( p_content->d_name ) + 1;
582         pp_list[ret] = malloc( size );
583         if( pp_list[ret] )
584         {
585             memcpy( pp_list[ret], p_content, size );
586             ret++;
587         }
588         else
589         {
590             /* Continuing is useless when no more memory can be allocted,
591              * so better return what we have found.
592              */
593             ret = -1;
594             break;
595         }
596     }
597
598     closedir( p_dir );
599
600     if( compar )
601     {
602         qsort( pp_list, ret, sizeof( struct dirent * ),
603                (int (*)(const void *, const void *)) compar );
604     }
605
606     *namelist = pp_list;
607     return ret;
608 }
609 #endif
610
611 #ifdef WIN32
612 /*****************************************************************************
613  * dgettext: gettext for plugins.
614  *****************************************************************************/
615 char *vlc_dgettext( const char *package, const char *msgid )
616 {
617 #if defined( ENABLE_NLS ) \
618      && ( defined(HAVE_GETTEXT) || defined(HAVE_INCLUDED_GETTEXT) )
619     return dgettext( package, msgid );
620 #else
621     return (char *)msgid;
622 #endif
623 }
624 #endif
625
626 /*****************************************************************************
627  * count_utf8_string: returns the number of characters in the string.
628  *****************************************************************************/
629 static int count_utf8_string( const char *psz_string )
630 {
631     int i = 0, i_count = 0;
632     while( psz_string[ i ] != 0 )
633     {
634         if( ((unsigned char *)psz_string)[ i ] <  0x80UL ) i_count++;
635         i++;
636     }
637     return i_count;
638 }
639
640 /*****************************************************************************
641  * wraptext: inserts \n at convenient places to wrap the text.
642  *           Returns the modified string in a new buffer.
643  *****************************************************************************/
644 char *vlc_wraptext( const char *psz_text, int i_line )
645 {
646     int i_len;
647     char *psz_line, *psz_new_text;
648
649     psz_line = psz_new_text = strdup( psz_text );
650
651     i_len = count_utf8_string( psz_text );
652
653     while( i_len > i_line )
654     {
655         /* Look if there is a newline somewhere. */
656         char *psz_parser = psz_line;
657         int i_count = 0;
658         while( i_count <= i_line && *psz_parser != '\n' )
659         {
660             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
661             psz_parser++;
662             i_count++;
663         }
664         if( *psz_parser == '\n' )
665         {
666             i_len -= (i_count + 1);
667             psz_line = psz_parser + 1;
668             continue;
669         }
670
671         /* Find the furthest space. */
672         while( psz_parser > psz_line && *psz_parser != ' ' )
673         {
674             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser--;
675             psz_parser--;
676             i_count--;
677         }
678         if( *psz_parser == ' ' )
679         {
680             *psz_parser = '\n';
681             i_len -= (i_count + 1);
682             psz_line = psz_parser + 1;
683             continue;
684         }
685
686         /* Wrapping has failed. Find the first space or newline */
687         while( i_count < i_len && *psz_parser != ' ' && *psz_parser != '\n' )
688         {
689             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
690             psz_parser++;
691             i_count++;
692         }
693         if( i_count < i_len ) *psz_parser = '\n';
694         i_len -= (i_count + 1);
695         psz_line = psz_parser + 1;
696     }
697
698     return psz_new_text;
699 }
700
701 /*****************************************************************************
702  * iconv wrapper
703  *****************************************************************************/
704 vlc_iconv_t vlc_iconv_open( const char *tocode, const char *fromcode )
705 {
706 #if defined(HAVE_ICONV)
707     return iconv_open( tocode, fromcode );
708 #else
709     return NULL;
710 #endif
711 }
712
713 size_t vlc_iconv( vlc_iconv_t cd, const char **inbuf, size_t *inbytesleft,
714                   char **outbuf, size_t *outbytesleft )
715 {
716 #if defined(HAVE_ICONV)
717     return iconv( cd, (ICONV_CONST char **)inbuf, inbytesleft,
718                   outbuf, outbytesleft );
719 #else
720     int i_bytes;
721
722     if (inbytesleft == NULL || outbytesleft == NULL)
723     {
724         return 0;
725     }
726
727     i_bytes = __MIN(*inbytesleft, *outbytesleft);
728     if( !inbuf || !outbuf || !i_bytes ) return (size_t)(-1);
729     memcpy( *outbuf, *inbuf, i_bytes );
730     inbuf += i_bytes;
731     outbuf += i_bytes;
732     inbytesleft -= i_bytes;
733     outbytesleft -= i_bytes;
734     return i_bytes;
735 #endif
736 }
737
738 int vlc_iconv_close( vlc_iconv_t cd )
739 {
740 #if defined(HAVE_ICONV)
741     return iconv_close( cd );
742 #else
743     return 0;
744 #endif
745 }
746
747 /*****************************************************************************
748  * reduce a fraction
749  *   (adapted from libavcodec, author Michael Niedermayer <michaelni@gmx.at>)
750  *****************************************************************************/
751 vlc_bool_t vlc_ureduce( unsigned *pi_dst_nom, unsigned *pi_dst_den,
752                         uint64_t i_nom, uint64_t i_den, uint64_t i_max )
753 {
754     vlc_bool_t b_exact = 1;
755     uint64_t i_gcd;
756
757     if( i_den == 0 )
758     {
759         *pi_dst_nom = 0;
760         *pi_dst_den = 1;
761         return 1;
762     }
763
764     i_gcd = GCD( i_nom, i_den );
765     i_nom /= i_gcd;
766     i_den /= i_gcd;
767
768     if( i_max == 0 ) i_max = I64C(0xFFFFFFFF);
769
770     if( i_nom > i_max || i_den > i_max )
771     {
772         uint64_t i_a0_num = 0, i_a0_den = 1, i_a1_num = 1, i_a1_den = 0;
773         b_exact = 0;
774
775         for( ; ; )
776         {
777             uint64_t i_x = i_nom / i_den;
778             uint64_t i_a2n = i_x * i_a1_num + i_a0_num;
779             uint64_t i_a2d = i_x * i_a1_den + i_a0_den;
780
781             if( i_a2n > i_max || i_a2d > i_max ) break;
782
783             i_nom %= i_den;
784
785             i_a0_num = i_a1_num; i_a0_den = i_a1_den;
786             i_a1_num = i_a2n; i_a1_den = i_a2d;
787             if( i_nom == 0 ) break;
788             i_x = i_nom; i_nom = i_den; i_den = i_x;
789         }
790         i_nom = i_a1_num;
791         i_den = i_a1_den;
792     }
793
794     *pi_dst_nom = i_nom;
795     *pi_dst_den = i_den;
796
797     return b_exact;
798 }
799
800 /*************************************************************************
801  * vlc_parse_cmdline: Command line parsing into elements.
802  *
803  * The command line is composed of space/tab separated arguments.
804  * Quotes can be used as argument delimiters and a backslash can be used to
805  * escape a quote.
806  *************************************************************************/
807 static void find_end_quote( char **s, char **ppsz_parser, int i_quote )
808 {
809     int i_bcount = 0;
810
811     while( **s )
812     {
813         if( **s == '\\' )
814         {
815             **ppsz_parser = **s;
816             (*ppsz_parser)++; (*s)++;
817             i_bcount++;
818         }
819         else if( **s == '"' || **s == '\'' )
820         {
821             /* Preceeded by a number of '\' which we erase. */
822             *ppsz_parser -= i_bcount / 2;
823             if( i_bcount & 1 )
824             {
825                 /* '\\' followed by a '"' or '\'' */
826                 *ppsz_parser -= 1;
827                 **ppsz_parser = **s;
828                 (*ppsz_parser)++; (*s)++;
829                 i_bcount = 0;
830                 continue;
831             }
832
833             if( **s == i_quote )
834             {
835                 /* End */
836                 return;
837             }
838             else
839             {
840                 /* Different quoting */
841                 int i_quote = **s;
842                 **ppsz_parser = **s;
843                 (*ppsz_parser)++; (*s)++;
844                 find_end_quote( s, ppsz_parser, i_quote );
845                 **ppsz_parser = **s;
846                 (*ppsz_parser)++; (*s)++;
847             }
848
849             i_bcount = 0;
850         }
851         else
852         {
853             /* A regular character */
854             **ppsz_parser = **s;
855             (*ppsz_parser)++; (*s)++;
856             i_bcount = 0;
857         }
858     }
859 }
860
861 char **vlc_parse_cmdline( const char *psz_cmdline, int *i_args )
862 {
863     int argc = 0;
864     char **argv = 0;
865     char *s, *psz_parser, *psz_arg, *psz_orig;
866     int i_bcount = 0;
867
868     if( !psz_cmdline ) return 0;
869     psz_orig = strdup( psz_cmdline );
870     psz_arg = psz_parser = s = psz_orig;
871
872     while( *s )
873     {
874         if( *s == '\t' || *s == ' ' )
875         {
876             /* We have a complete argument */
877             *psz_parser = 0;
878             TAB_APPEND( argc, argv, strdup(psz_arg) );
879
880             /* Skip trailing spaces/tabs */
881             do{ s++; } while( *s == '\t' || *s == ' ' );
882
883             /* New argument */
884             psz_arg = psz_parser = s;
885             i_bcount = 0;
886         }
887         else if( *s == '\\' )
888         {
889             *psz_parser++ = *s++;
890             i_bcount++;
891         }
892         else if( *s == '"' || *s == '\'' )
893         {
894             if( ( i_bcount & 1 ) == 0 )
895             {
896                 /* Preceeded by an even number of '\', this is half that
897                  * number of '\', plus a quote which we erase. */
898                 int i_quote = *s;
899                 psz_parser -= i_bcount / 2;
900                 s++;
901                 find_end_quote( &s, &psz_parser, i_quote );
902                 s++;
903             }
904             else
905             {
906                 /* Preceeded by an odd number of '\', this is half that
907                  * number of '\' followed by a '"' */
908                 psz_parser = psz_parser - i_bcount/2 - 1;
909                 *psz_parser++ = '"';
910                 s++;
911             }
912             i_bcount = 0;
913         }
914         else
915         {
916             /* A regular character */
917             *psz_parser++ = *s++;
918             i_bcount = 0;
919         }
920     }
921
922     /* Take care of the last arg */
923     if( *psz_arg )
924     {
925         *psz_parser = '\0';
926         TAB_APPEND( argc, argv, strdup(psz_arg) );
927     }
928
929     if( i_args ) *i_args = argc;
930     free( psz_orig );
931     return argv;
932 }
933
934 /*************************************************************************
935  * vlc_execve: Execute an external program with a given environment,
936  * wait until it finishes and return its standard output
937  *************************************************************************/
938 int __vlc_execve( vlc_object_t *p_object, int i_argc, char *const *ppsz_argv,
939                   char *const *ppsz_env, const char *psz_cwd,
940                   const char *p_in, size_t i_in,
941                   char **pp_data, size_t *pi_data )
942 {
943     (void)i_argc; // <-- hmph
944 #ifdef HAVE_FORK
945 # define BUFSIZE 1024
946     int fds[2], i_status;
947
948     if (socketpair (AF_LOCAL, SOCK_STREAM, 0, fds))
949         return -1;
950
951     pid_t pid = -1;
952     if ((fds[0] > 2) && (fds[1] > 2))
953         pid = fork ();
954
955     switch (pid)
956     {
957         case -1:
958             msg_Err (p_object, "unable to fork (%m)");
959             close (fds[0]);
960             close (fds[1]);
961             return -1;
962
963         case 0:
964         {
965             sigset_t set;
966             sigemptyset (&set);
967             pthread_sigmask (SIG_SETMASK, &set, NULL);
968
969             /* NOTE:
970              * Like it or not, close can fail (and not only with EBADF)
971              */
972             if ((close (0) == 0) && (close (1) == 0) && (close (2) == 0)
973              && (dup (fds[1]) == 0) && (dup (fds[1]) == 1)
974              && (open ("/dev/null", O_RDONLY) == 2)
975              && ((psz_cwd == NULL) || (chdir (psz_cwd) == 0)))
976                 execve (ppsz_argv[0], ppsz_argv, ppsz_env);
977
978             exit (EXIT_FAILURE);
979         }
980     }
981
982     close (fds[1]);
983
984     *pi_data = 0;
985     if (*pp_data)
986         free (*pp_data);
987     *pp_data = NULL;
988
989     if (i_in == 0)
990         shutdown (fds[0], SHUT_WR);
991
992     while (!p_object->b_die)
993     {
994         struct pollfd ufd[1];
995         memset (ufd, 0, sizeof (ufd));
996         ufd[0].fd = fds[0];
997         ufd[0].events = POLLIN;
998
999         if (i_in > 0)
1000             ufd[0].events |= POLLOUT;
1001
1002         if (poll (ufd, 1, 10) <= 0)
1003             continue;
1004
1005         if (ufd[0].revents & ~POLLOUT)
1006         {
1007             char *ptr = realloc (*pp_data, *pi_data + BUFSIZE + 1);
1008             if (ptr == NULL)
1009                 break; /* safely abort */
1010
1011             *pp_data = ptr;
1012
1013             ssize_t val = read (fds[0], ptr + *pi_data, BUFSIZE);
1014             switch (val)
1015             {
1016                 case -1:
1017                 case 0:
1018                     shutdown (fds[0], SHUT_RD);
1019                     break;
1020
1021                 default:
1022                     *pi_data += val;
1023             }
1024         }
1025
1026         if (ufd[0].revents & POLLOUT)
1027         {
1028             ssize_t val = write (fds[0], p_in, i_in);
1029             switch (val)
1030             {
1031                 case -1:
1032                 case 0:
1033                     i_in = 0;
1034                     shutdown (fds[0], SHUT_WR);
1035                     break;
1036
1037                 default:
1038                     i_in -= val;
1039                     p_in += val;
1040             }
1041         }
1042     }
1043
1044     close (fds[0]);
1045
1046     while (waitpid (pid, &i_status, 0) == -1);
1047
1048     if (WIFEXITED (i_status))
1049     {
1050         i_status = WEXITSTATUS (i_status);
1051         if (i_status)
1052             msg_Warn (p_object,  "child %s (PID %d) exited with error code %d",
1053                       ppsz_argv[0], (int)pid, i_status);
1054     }
1055     else
1056     if (WIFSIGNALED (i_status)) // <-- this should be redumdant a check
1057     {
1058         i_status = WTERMSIG (i_status);
1059         msg_Warn (p_object, "child %s (PID %d) exited on signal %d (%s)",
1060                   ppsz_argv[0], (int)pid, i_status, strsignal (i_status));
1061     }
1062
1063 #elif defined( WIN32 ) && !defined( UNDER_CE )
1064     SECURITY_ATTRIBUTES saAttr;
1065     PROCESS_INFORMATION piProcInfo;
1066     STARTUPINFO siStartInfo;
1067     BOOL bFuncRetn = FALSE;
1068     HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr;
1069     DWORD i_status;
1070     char *psz_cmd = NULL, *p_env = NULL, *p = NULL;
1071     char **ppsz_parser;
1072     int i_size;
1073
1074     /* Set the bInheritHandle flag so pipe handles are inherited. */
1075     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1076     saAttr.bInheritHandle = TRUE;
1077     saAttr.lpSecurityDescriptor = NULL;
1078
1079     /* Create a pipe for the child process's STDOUT. */
1080     if ( !CreatePipe( &hChildStdoutRd, &hChildStdoutWr, &saAttr, 0 ) )
1081     {
1082         msg_Err( p_object, "stdout pipe creation failed" );
1083         return -1;
1084     }
1085
1086     /* Ensure the read handle to the pipe for STDOUT is not inherited. */
1087     SetHandleInformation( hChildStdoutRd, HANDLE_FLAG_INHERIT, 0 );
1088
1089     /* Create a pipe for the child process's STDIN. */
1090     if ( !CreatePipe( &hChildStdinRd, &hChildStdinWr, &saAttr, 0 ) )
1091     {
1092         msg_Err( p_object, "stdin pipe creation failed" );
1093         return -1;
1094     }
1095
1096     /* Ensure the write handle to the pipe for STDIN is not inherited. */
1097     SetHandleInformation( hChildStdinWr, HANDLE_FLAG_INHERIT, 0 );
1098
1099     /* Set up members of the PROCESS_INFORMATION structure. */
1100     ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
1101
1102     /* Set up members of the STARTUPINFO structure. */
1103     ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
1104     siStartInfo.cb = sizeof(STARTUPINFO);
1105     siStartInfo.hStdError = hChildStdoutWr;
1106     siStartInfo.hStdOutput = hChildStdoutWr;
1107     siStartInfo.hStdInput = hChildStdinRd;
1108     siStartInfo.wShowWindow = SW_HIDE;
1109     siStartInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1110
1111     /* Set up the command line. */
1112     psz_cmd = malloc(32768);
1113     if( !psz_cmd )
1114         return -1;
1115     psz_cmd[0] = '\0';
1116     i_size = 32768;
1117     ppsz_parser = &ppsz_argv[0];
1118     while ( ppsz_parser[0] != NULL && i_size > 0 )
1119     {
1120         /* Protect the last argument with quotes ; the other arguments
1121          * are supposed to be already protected because they have been
1122          * passed as a command-line option. */
1123         if ( ppsz_parser[1] == NULL )
1124         {
1125             strncat( psz_cmd, "\"", i_size );
1126             i_size--;
1127         }
1128         strncat( psz_cmd, *ppsz_parser, i_size );
1129         i_size -= strlen( *ppsz_parser );
1130         if ( ppsz_parser[1] == NULL )
1131         {
1132             strncat( psz_cmd, "\"", i_size );
1133             i_size--;
1134         }
1135         strncat( psz_cmd, " ", i_size );
1136         i_size--;
1137         ppsz_parser++;
1138     }
1139
1140     /* Set up the environment. */
1141     p = p_env = malloc(32768);
1142     if( !p )
1143     {
1144         free( psz_cmd );
1145         return -1;
1146     }
1147
1148     i_size = 32768;
1149     ppsz_parser = &ppsz_env[0];
1150     while ( *ppsz_parser != NULL && i_size > 0 )
1151     {
1152         memcpy( p, *ppsz_parser,
1153                 __MIN((int)(strlen(*ppsz_parser) + 1), i_size) );
1154         p += strlen(*ppsz_parser) + 1;
1155         i_size -= strlen(*ppsz_parser) + 1;
1156         ppsz_parser++;
1157     }
1158     *p = '\0';
1159
1160     /* Create the child process. */
1161     bFuncRetn = CreateProcess( NULL,
1162           psz_cmd,       // command line
1163           NULL,          // process security attributes
1164           NULL,          // primary thread security attributes
1165           TRUE,          // handles are inherited
1166           0,             // creation flags
1167           p_env,
1168           psz_cwd,
1169           &siStartInfo,  // STARTUPINFO pointer
1170           &piProcInfo ); // receives PROCESS_INFORMATION
1171
1172     free( psz_cmd );
1173     free( p_env );
1174
1175     if ( bFuncRetn == 0 )
1176     {
1177         msg_Err( p_object, "child creation failed" );
1178         return -1;
1179     }
1180
1181     /* Read from a file and write its contents to a pipe. */
1182     while ( i_in > 0 && !p_object->b_die )
1183     {
1184         DWORD i_written;
1185         if ( !WriteFile( hChildStdinWr, p_in, i_in, &i_written, NULL ) )
1186             break;
1187         i_in -= i_written;
1188         p_in += i_written;
1189     }
1190
1191     /* Close the pipe handle so the child process stops reading. */
1192     CloseHandle(hChildStdinWr);
1193
1194     /* Close the write end of the pipe before reading from the
1195      * read end of the pipe. */
1196     CloseHandle(hChildStdoutWr);
1197
1198     /* Read output from the child process. */
1199     *pi_data = 0;
1200     if( *pp_data )
1201         free( pp_data );
1202     *pp_data = NULL;
1203     *pp_data = malloc( 1025 );  /* +1 for \0 */
1204
1205     while ( !p_object->b_die )
1206     {
1207         DWORD i_read;
1208         if ( !ReadFile( hChildStdoutRd, &(*pp_data)[*pi_data], 1024, &i_read,
1209                         NULL )
1210               || i_read == 0 )
1211             break;
1212         *pi_data += i_read;
1213         *pp_data = realloc( *pp_data, *pi_data + 1025 );
1214     }
1215
1216     while ( !p_object->b_die
1217              && !GetExitCodeProcess( piProcInfo.hProcess, &i_status )
1218              && i_status != STILL_ACTIVE )
1219         msleep( 10000 );
1220
1221     CloseHandle(piProcInfo.hProcess);
1222     CloseHandle(piProcInfo.hThread);
1223
1224     if ( i_status )
1225         msg_Warn( p_object,
1226                   "child %s returned with error code %ld",
1227                   ppsz_argv[0], i_status );
1228
1229 #else
1230     msg_Err( p_object, "vlc_execve called but no implementation is available" );
1231     return -1;
1232
1233 #endif
1234
1235     if (*pp_data == NULL)
1236         return -1;
1237
1238     (*pp_data)[*pi_data] = '\0';
1239     return 0;
1240 }