]> git.sesse.net Git - vlc/blob - src/extras/libc.c
update module LIST file.
[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( HAVE_LLDIV )
379 lldiv_t vlc_lldiv( long long numer, long long denom )
380 {
381     lldiv_t d;
382     d.quot = numer / denom;
383     d.rem  = numer % denom;
384     return d;
385 }
386 #endif
387
388
389 /**
390  * Copy a string to a sized buffer. The result is always nul-terminated
391  * (contrary to strncpy()).
392  *
393  * @param dest destination buffer
394  * @param src string to be copied
395  * @param len maximum number of characters to be copied plus one for the
396  * terminating nul.
397  *
398  * @return strlen(src)
399  */
400 #ifndef HAVE_STRLCPY
401 extern size_t vlc_strlcpy (char *tgt, const char *src, size_t bufsize)
402 {
403     size_t length;
404
405     for (length = 1; (length < bufsize) && *src; length++)
406         *tgt++ = *src++;
407
408     if (bufsize)
409         *tgt = '\0';
410
411     while (*src++)
412         length++;
413
414     return length - 1;
415 }
416 #endif
417
418 /*****************************************************************************
419  * vlc_*dir_wrapper: wrapper under Windows to return the list of drive letters
420  * when called with an empty argument or just '\'
421  *****************************************************************************/
422 #if defined(WIN32) && !defined(UNDER_CE)
423 #   include <assert.h>
424
425 typedef struct vlc_DIR
426 {
427     _WDIR *p_real_dir;
428     int i_drives;
429     struct _wdirent dd_dir;
430     vlc_bool_t b_insert_back;
431 } vlc_DIR;
432
433 void *vlc_wopendir( const wchar_t *wpath )
434 {
435     vlc_DIR *p_dir = NULL;
436     _WDIR *p_real_dir = NULL;
437
438     if ( wpath == NULL || wpath[0] == '\0'
439           || (wcscmp (wpath, L"\\") == 0) )
440     {
441         /* Special mode to list drive letters */
442         p_dir = malloc( sizeof(vlc_DIR) );
443         if( !p_dir )
444             return NULL;
445         p_dir->p_real_dir = NULL;
446         p_dir->i_drives = GetLogicalDrives();
447         return (void *)p_dir;
448     }
449
450     p_real_dir = _wopendir( wpath );
451     if ( p_real_dir == NULL )
452         return NULL;
453
454     p_dir = malloc( sizeof(vlc_DIR) );
455     if( !p_dir )
456     {
457         _wclosedir( p_real_dir );
458         return NULL;
459     }
460     p_dir->p_real_dir = p_real_dir;
461
462     assert (wpath[0]); // wpath[1] is defined
463     p_dir->b_insert_back = !wcscmp (wpath + 1, L":\\");
464     return (void *)p_dir;
465 }
466
467 struct _wdirent *vlc_wreaddir( void *_p_dir )
468 {
469     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
470     unsigned int i;
471     DWORD i_drives;
472
473     if ( p_dir->p_real_dir != NULL )
474     {
475         if ( p_dir->b_insert_back )
476         {
477             /* Adds "..", gruik! */
478             p_dir->dd_dir.d_ino = 0;
479             p_dir->dd_dir.d_reclen = 0;
480             p_dir->dd_dir.d_namlen = 2;
481             wcscpy( p_dir->dd_dir.d_name, L".." );
482             p_dir->b_insert_back = VLC_FALSE;
483             return &p_dir->dd_dir;
484         }
485
486         return _wreaddir( p_dir->p_real_dir );
487     }
488
489     /* Drive letters mode */
490     i_drives = p_dir->i_drives;
491     if ( !i_drives )
492         return NULL; /* end */
493
494     for ( i = 0; i < sizeof(DWORD)*8; i++, i_drives >>= 1 )
495         if ( i_drives & 1 ) break;
496
497     if ( i >= 26 )
498         return NULL; /* this should not happen */
499
500     swprintf( p_dir->dd_dir.d_name, L"%c:\\", 'A' + i );
501     p_dir->dd_dir.d_namlen = wcslen(p_dir->dd_dir.d_name);
502     p_dir->i_drives &= ~(1UL << i);
503     return &p_dir->dd_dir;
504 }
505
506 int vlc_wclosedir( void *_p_dir )
507 {
508     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
509     int i_ret = 0;
510
511     if ( p_dir->p_real_dir != NULL )
512         i_ret = _wclosedir( p_dir->p_real_dir );
513
514     free( p_dir );
515     return i_ret;
516 }
517
518 void vlc_rewinddir( void *_p_dir )
519 {
520     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
521
522     if ( p_dir->p_real_dir != NULL )
523         _wrewinddir( p_dir->p_real_dir );
524 }
525
526 void vlc_seekdir( void *_p_dir, long loc)
527 {
528     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
529
530     if ( p_dir->p_real_dir != NULL )
531         _wseekdir( p_dir->p_real_dir, loc );
532 }
533
534 long vlc_telldir( void *_p_dir )
535 {
536     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
537
538     if ( p_dir->p_real_dir != NULL )
539         return _wtelldir( p_dir->p_real_dir );
540     return 0;
541 }
542 #endif
543
544 /*****************************************************************************
545  * scandir: scan a directory alpha-sorted
546  *****************************************************************************/
547 #if !defined( HAVE_SCANDIR )
548 /* FIXME: I suspect this is dead code -> utf8_scandir */
549 #ifdef WIN32
550 # undef opendir
551 # undef readdir
552 # undef closedir
553 #endif
554 int vlc_alphasort( const struct dirent **a, const struct dirent **b )
555 {
556     return strcoll( (*a)->d_name, (*b)->d_name );
557 }
558
559 int vlc_scandir( const char *name, struct dirent ***namelist,
560                     int (*filter) ( const struct dirent * ),
561                     int (*compar) ( const struct dirent **,
562                                     const struct dirent ** ) )
563 {
564     DIR            * p_dir;
565     struct dirent  * p_content;
566     struct dirent ** pp_list;
567     int              ret, size;
568
569     if( !namelist || !( p_dir = opendir( name ) ) ) return -1;
570
571     ret     = 0;
572     pp_list = NULL;
573     while( ( p_content = readdir( p_dir ) ) )
574     {
575         if( filter && !filter( p_content ) )
576         {
577             continue;
578         }
579         pp_list = realloc( pp_list, ( ret + 1 ) * sizeof( struct dirent * ) );
580         size = sizeof( struct dirent ) + strlen( p_content->d_name ) + 1;
581         pp_list[ret] = malloc( size );
582         if( pp_list[ret] )
583         {
584             memcpy( pp_list[ret], p_content, size );
585             ret++;
586         }
587         else
588         {
589             /* Continuing is useless when no more memory can be allocted,
590              * so better return what we have found.
591              */
592             ret = -1;
593             break;
594         }
595     }
596
597     closedir( p_dir );
598
599     if( compar )
600     {
601         qsort( pp_list, ret, sizeof( struct dirent * ),
602                (int (*)(const void *, const void *)) compar );
603     }
604
605     *namelist = pp_list;
606     return ret;
607 }
608 #endif
609
610 #ifdef WIN32
611 /*****************************************************************************
612  * dgettext: gettext for plugins.
613  *****************************************************************************/
614 char *vlc_dgettext( const char *package, const char *msgid )
615 {
616 #if defined( ENABLE_NLS ) \
617      && ( defined(HAVE_GETTEXT) || defined(HAVE_INCLUDED_GETTEXT) )
618     return dgettext( package, msgid );
619 #else
620     return (char *)msgid;
621 #endif
622 }
623 #endif
624
625 /*****************************************************************************
626  * count_utf8_string: returns the number of characters in the string.
627  *****************************************************************************/
628 static int count_utf8_string( const char *psz_string )
629 {
630     int i = 0, i_count = 0;
631     while( psz_string[ i ] != 0 )
632     {
633         if( ((unsigned char *)psz_string)[ i ] <  0x80UL ) i_count++;
634         i++;
635     }
636     return i_count;
637 }
638
639 /*****************************************************************************
640  * wraptext: inserts \n at convenient places to wrap the text.
641  *           Returns the modified string in a new buffer.
642  *****************************************************************************/
643 char *vlc_wraptext( const char *psz_text, int i_line )
644 {
645     int i_len;
646     char *psz_line, *psz_new_text;
647
648     psz_line = psz_new_text = strdup( psz_text );
649
650     i_len = count_utf8_string( psz_text );
651
652     while( i_len > i_line )
653     {
654         /* Look if there is a newline somewhere. */
655         char *psz_parser = psz_line;
656         int i_count = 0;
657         while( i_count <= i_line && *psz_parser != '\n' )
658         {
659             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
660             psz_parser++;
661             i_count++;
662         }
663         if( *psz_parser == '\n' )
664         {
665             i_len -= (i_count + 1);
666             psz_line = psz_parser + 1;
667             continue;
668         }
669
670         /* Find the furthest space. */
671         while( psz_parser > psz_line && *psz_parser != ' ' )
672         {
673             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser--;
674             psz_parser--;
675             i_count--;
676         }
677         if( *psz_parser == ' ' )
678         {
679             *psz_parser = '\n';
680             i_len -= (i_count + 1);
681             psz_line = psz_parser + 1;
682             continue;
683         }
684
685         /* Wrapping has failed. Find the first space or newline */
686         while( i_count < i_len && *psz_parser != ' ' && *psz_parser != '\n' )
687         {
688             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
689             psz_parser++;
690             i_count++;
691         }
692         if( i_count < i_len ) *psz_parser = '\n';
693         i_len -= (i_count + 1);
694         psz_line = psz_parser + 1;
695     }
696
697     return psz_new_text;
698 }
699
700 /*****************************************************************************
701  * iconv wrapper
702  *****************************************************************************/
703 vlc_iconv_t vlc_iconv_open( const char *tocode, const char *fromcode )
704 {
705 #if defined(HAVE_ICONV)
706     return iconv_open( tocode, fromcode );
707 #else
708     return NULL;
709 #endif
710 }
711
712 size_t vlc_iconv( vlc_iconv_t cd, const char **inbuf, size_t *inbytesleft,
713                   char **outbuf, size_t *outbytesleft )
714 {
715 #if defined(HAVE_ICONV)
716     return iconv( cd, (ICONV_CONST char **)inbuf, inbytesleft,
717                   outbuf, outbytesleft );
718 #else
719     int i_bytes;
720
721     if (inbytesleft == NULL || outbytesleft == NULL)
722     {
723         return 0;
724     }
725
726     i_bytes = __MIN(*inbytesleft, *outbytesleft);
727     if( !inbuf || !outbuf || !i_bytes ) return (size_t)(-1);
728     memcpy( *outbuf, *inbuf, i_bytes );
729     inbuf += i_bytes;
730     outbuf += i_bytes;
731     inbytesleft -= i_bytes;
732     outbytesleft -= i_bytes;
733     return i_bytes;
734 #endif
735 }
736
737 int vlc_iconv_close( vlc_iconv_t cd )
738 {
739 #if defined(HAVE_ICONV)
740     return iconv_close( cd );
741 #else
742     return 0;
743 #endif
744 }
745
746 /*****************************************************************************
747  * reduce a fraction
748  *   (adapted from libavcodec, author Michael Niedermayer <michaelni@gmx.at>)
749  *****************************************************************************/
750 vlc_bool_t vlc_ureduce( unsigned *pi_dst_nom, unsigned *pi_dst_den,
751                         uint64_t i_nom, uint64_t i_den, uint64_t i_max )
752 {
753     vlc_bool_t b_exact = 1;
754     uint64_t i_gcd;
755
756     if( i_den == 0 )
757     {
758         *pi_dst_nom = 0;
759         *pi_dst_den = 1;
760         return 1;
761     }
762
763     i_gcd = GCD( i_nom, i_den );
764     i_nom /= i_gcd;
765     i_den /= i_gcd;
766
767     if( i_max == 0 ) i_max = I64C(0xFFFFFFFF);
768
769     if( i_nom > i_max || i_den > i_max )
770     {
771         uint64_t i_a0_num = 0, i_a0_den = 1, i_a1_num = 1, i_a1_den = 0;
772         b_exact = 0;
773
774         for( ; ; )
775         {
776             uint64_t i_x = i_nom / i_den;
777             uint64_t i_a2n = i_x * i_a1_num + i_a0_num;
778             uint64_t i_a2d = i_x * i_a1_den + i_a0_den;
779
780             if( i_a2n > i_max || i_a2d > i_max ) break;
781
782             i_nom %= i_den;
783
784             i_a0_num = i_a1_num; i_a0_den = i_a1_den;
785             i_a1_num = i_a2n; i_a1_den = i_a2d;
786             if( i_nom == 0 ) break;
787             i_x = i_nom; i_nom = i_den; i_den = i_x;
788         }
789         i_nom = i_a1_num;
790         i_den = i_a1_den;
791     }
792
793     *pi_dst_nom = i_nom;
794     *pi_dst_den = i_den;
795
796     return b_exact;
797 }
798
799 /*************************************************************************
800  * vlc_parse_cmdline: Command line parsing into elements.
801  *
802  * The command line is composed of space/tab separated arguments.
803  * Quotes can be used as argument delimiters and a backslash can be used to
804  * escape a quote.
805  *************************************************************************/
806 static void find_end_quote( char **s, char **ppsz_parser, int i_quote )
807 {
808     int i_bcount = 0;
809
810     while( **s )
811     {
812         if( **s == '\\' )
813         {
814             **ppsz_parser = **s;
815             (*ppsz_parser)++; (*s)++;
816             i_bcount++;
817         }
818         else if( **s == '"' || **s == '\'' )
819         {
820             /* Preceeded by a number of '\' which we erase. */
821             *ppsz_parser -= i_bcount / 2;
822             if( i_bcount & 1 )
823             {
824                 /* '\\' followed by a '"' or '\'' */
825                 *ppsz_parser -= 1;
826                 **ppsz_parser = **s;
827                 (*ppsz_parser)++; (*s)++;
828                 i_bcount = 0;
829                 continue;
830             }
831
832             if( **s == i_quote )
833             {
834                 /* End */
835                 return;
836             }
837             else
838             {
839                 /* Different quoting */
840                 int i_quote = **s;
841                 **ppsz_parser = **s;
842                 (*ppsz_parser)++; (*s)++;
843                 find_end_quote( s, ppsz_parser, i_quote );
844                 **ppsz_parser = **s;
845                 (*ppsz_parser)++; (*s)++;
846             }
847
848             i_bcount = 0;
849         }
850         else
851         {
852             /* A regular character */
853             **ppsz_parser = **s;
854             (*ppsz_parser)++; (*s)++;
855             i_bcount = 0;
856         }
857     }
858 }
859
860 char **vlc_parse_cmdline( const char *psz_cmdline, int *i_args )
861 {
862     int argc = 0;
863     char **argv = 0;
864     char *s, *psz_parser, *psz_arg, *psz_orig;
865     int i_bcount = 0;
866
867     if( !psz_cmdline ) return 0;
868     psz_orig = strdup( psz_cmdline );
869     psz_arg = psz_parser = s = psz_orig;
870
871     while( *s )
872     {
873         if( *s == '\t' || *s == ' ' )
874         {
875             /* We have a complete argument */
876             *psz_parser = 0;
877             TAB_APPEND( argc, argv, strdup(psz_arg) );
878
879             /* Skip trailing spaces/tabs */
880             do{ s++; } while( *s == '\t' || *s == ' ' );
881
882             /* New argument */
883             psz_arg = psz_parser = s;
884             i_bcount = 0;
885         }
886         else if( *s == '\\' )
887         {
888             *psz_parser++ = *s++;
889             i_bcount++;
890         }
891         else if( *s == '"' || *s == '\'' )
892         {
893             if( ( i_bcount & 1 ) == 0 )
894             {
895                 /* Preceeded by an even number of '\', this is half that
896                  * number of '\', plus a quote which we erase. */
897                 int i_quote = *s;
898                 psz_parser -= i_bcount / 2;
899                 s++;
900                 find_end_quote( &s, &psz_parser, i_quote );
901                 s++;
902             }
903             else
904             {
905                 /* Preceeded by an odd number of '\', this is half that
906                  * number of '\' followed by a '"' */
907                 psz_parser = psz_parser - i_bcount/2 - 1;
908                 *psz_parser++ = '"';
909                 s++;
910             }
911             i_bcount = 0;
912         }
913         else
914         {
915             /* A regular character */
916             *psz_parser++ = *s++;
917             i_bcount = 0;
918         }
919     }
920
921     /* Take care of the last arg */
922     if( *psz_arg )
923     {
924         *psz_parser = '\0';
925         TAB_APPEND( argc, argv, strdup(psz_arg) );
926     }
927
928     if( i_args ) *i_args = argc;
929     free( psz_orig );
930     return argv;
931 }
932
933 /*************************************************************************
934  * vlc_execve: Execute an external program with a given environment,
935  * wait until it finishes and return its standard output
936  *************************************************************************/
937 int __vlc_execve( vlc_object_t *p_object, int i_argc, char *const *ppsz_argv,
938                   char *const *ppsz_env, const char *psz_cwd,
939                   const char *p_in, size_t i_in,
940                   char **pp_data, size_t *pi_data )
941 {
942     (void)i_argc; // <-- hmph
943 #ifdef HAVE_FORK
944 # define BUFSIZE 1024
945     int fds[2], i_status;
946
947     if (socketpair (AF_LOCAL, SOCK_STREAM, 0, fds))
948         return -1;
949
950     pid_t pid = -1;
951     if ((fds[0] > 2) && (fds[1] > 2))
952         pid = fork ();
953
954     switch (pid)
955     {
956         case -1:
957             msg_Err (p_object, "unable to fork (%m)");
958             close (fds[0]);
959             close (fds[1]);
960             return -1;
961
962         case 0:
963         {
964             sigset_t set;
965             sigemptyset (&set);
966             pthread_sigmask (SIG_SETMASK, &set, NULL);
967
968             /* NOTE:
969              * Like it or not, close can fail (and not only with EBADF)
970              */
971             if ((close (0) == 0) && (close (1) == 0) && (close (2) == 0)
972              && (dup (fds[1]) == 0) && (dup (fds[1]) == 1)
973              && (open ("/dev/null", O_RDONLY) == 2)
974              && ((psz_cwd == NULL) || (chdir (psz_cwd) == 0)))
975                 execve (ppsz_argv[0], ppsz_argv, ppsz_env);
976
977             exit (EXIT_FAILURE);
978         }
979     }
980
981     close (fds[1]);
982
983     *pi_data = 0;
984     if (*pp_data)
985         free (*pp_data);
986     *pp_data = NULL;
987
988     if (i_in == 0)
989         shutdown (fds[0], SHUT_WR);
990
991     while (!p_object->b_die)
992     {
993         struct pollfd ufd[1];
994         memset (ufd, 0, sizeof (ufd));
995         ufd[0].fd = fds[0];
996         ufd[0].events = POLLIN;
997
998         if (i_in > 0)
999             ufd[0].events |= POLLOUT;
1000
1001         if (poll (ufd, 1, 10) <= 0)
1002             continue;
1003
1004         if (ufd[0].revents & ~POLLOUT)
1005         {
1006             char *ptr = realloc (*pp_data, *pi_data + BUFSIZE + 1);
1007             if (ptr == NULL)
1008                 break; /* safely abort */
1009
1010             *pp_data = ptr;
1011
1012             ssize_t val = read (fds[0], ptr + *pi_data, BUFSIZE);
1013             switch (val)
1014             {
1015                 case -1:
1016                 case 0:
1017                     shutdown (fds[0], SHUT_RD);
1018                     break;
1019
1020                 default:
1021                     *pi_data += val;
1022             }
1023         }
1024
1025         if (ufd[0].revents & POLLOUT)
1026         {
1027             ssize_t val = write (fds[0], p_in, i_in);
1028             switch (val)
1029             {
1030                 case -1:
1031                 case 0:
1032                     i_in = 0;
1033                     shutdown (fds[0], SHUT_WR);
1034                     break;
1035
1036                 default:
1037                     i_in -= val;
1038                     p_in += val;
1039             }
1040         }
1041     }
1042
1043     close (fds[0]);
1044
1045     while (waitpid (pid, &i_status, 0) == -1);
1046
1047     if (WIFEXITED (i_status))
1048     {
1049         i_status = WEXITSTATUS (i_status);
1050         if (i_status)
1051             msg_Warn (p_object,  "child %s (PID %d) exited with error code %d",
1052                       ppsz_argv[0], (int)pid, i_status);
1053     }
1054     else
1055     if (WIFSIGNALED (i_status)) // <-- this should be redumdant a check
1056     {
1057         i_status = WTERMSIG (i_status);
1058         msg_Warn (p_object, "child %s (PID %d) exited on signal %d (%s)",
1059                   ppsz_argv[0], (int)pid, i_status, strsignal (i_status));
1060     }
1061
1062 #elif defined( WIN32 ) && !defined( UNDER_CE )
1063     SECURITY_ATTRIBUTES saAttr;
1064     PROCESS_INFORMATION piProcInfo;
1065     STARTUPINFO siStartInfo;
1066     BOOL bFuncRetn = FALSE;
1067     HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr;
1068     DWORD i_status;
1069     char *psz_cmd = NULL, *p_env = NULL, *p = NULL;
1070     char **ppsz_parser;
1071     int i_size;
1072
1073     /* Set the bInheritHandle flag so pipe handles are inherited. */
1074     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1075     saAttr.bInheritHandle = TRUE;
1076     saAttr.lpSecurityDescriptor = NULL;
1077
1078     /* Create a pipe for the child process's STDOUT. */
1079     if ( !CreatePipe( &hChildStdoutRd, &hChildStdoutWr, &saAttr, 0 ) )
1080     {
1081         msg_Err( p_object, "stdout pipe creation failed" );
1082         return -1;
1083     }
1084
1085     /* Ensure the read handle to the pipe for STDOUT is not inherited. */
1086     SetHandleInformation( hChildStdoutRd, HANDLE_FLAG_INHERIT, 0 );
1087
1088     /* Create a pipe for the child process's STDIN. */
1089     if ( !CreatePipe( &hChildStdinRd, &hChildStdinWr, &saAttr, 0 ) )
1090     {
1091         msg_Err( p_object, "stdin pipe creation failed" );
1092         return -1;
1093     }
1094
1095     /* Ensure the write handle to the pipe for STDIN is not inherited. */
1096     SetHandleInformation( hChildStdinWr, HANDLE_FLAG_INHERIT, 0 );
1097
1098     /* Set up members of the PROCESS_INFORMATION structure. */
1099     ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
1100
1101     /* Set up members of the STARTUPINFO structure. */
1102     ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
1103     siStartInfo.cb = sizeof(STARTUPINFO);
1104     siStartInfo.hStdError = hChildStdoutWr;
1105     siStartInfo.hStdOutput = hChildStdoutWr;
1106     siStartInfo.hStdInput = hChildStdinRd;
1107     siStartInfo.wShowWindow = SW_HIDE;
1108     siStartInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1109
1110     /* Set up the command line. */
1111     psz_cmd = malloc(32768);
1112     if( !psz_cmd )
1113         return -1;
1114     psz_cmd[0] = '\0';
1115     i_size = 32768;
1116     ppsz_parser = &ppsz_argv[0];
1117     while ( ppsz_parser[0] != NULL && i_size > 0 )
1118     {
1119         /* Protect the last argument with quotes ; the other arguments
1120          * are supposed to be already protected because they have been
1121          * passed as a command-line option. */
1122         if ( ppsz_parser[1] == NULL )
1123         {
1124             strncat( psz_cmd, "\"", i_size );
1125             i_size--;
1126         }
1127         strncat( psz_cmd, *ppsz_parser, i_size );
1128         i_size -= strlen( *ppsz_parser );
1129         if ( ppsz_parser[1] == NULL )
1130         {
1131             strncat( psz_cmd, "\"", i_size );
1132             i_size--;
1133         }
1134         strncat( psz_cmd, " ", i_size );
1135         i_size--;
1136         ppsz_parser++;
1137     }
1138
1139     /* Set up the environment. */
1140     p = p_env = malloc(32768);
1141     if( !p )
1142     {
1143         free( psz_cmd );
1144         return -1;
1145     }
1146
1147     i_size = 32768;
1148     ppsz_parser = &ppsz_env[0];
1149     while ( *ppsz_parser != NULL && i_size > 0 )
1150     {
1151         memcpy( p, *ppsz_parser,
1152                 __MIN((int)(strlen(*ppsz_parser) + 1), i_size) );
1153         p += strlen(*ppsz_parser) + 1;
1154         i_size -= strlen(*ppsz_parser) + 1;
1155         ppsz_parser++;
1156     }
1157     *p = '\0';
1158
1159     /* Create the child process. */
1160     bFuncRetn = CreateProcess( NULL,
1161           psz_cmd,       // command line
1162           NULL,          // process security attributes
1163           NULL,          // primary thread security attributes
1164           TRUE,          // handles are inherited
1165           0,             // creation flags
1166           p_env,
1167           psz_cwd,
1168           &siStartInfo,  // STARTUPINFO pointer
1169           &piProcInfo ); // receives PROCESS_INFORMATION
1170
1171     free( psz_cmd );
1172     free( p_env );
1173
1174     if ( bFuncRetn == 0 )
1175     {
1176         msg_Err( p_object, "child creation failed" );
1177         return -1;
1178     }
1179
1180     /* Read from a file and write its contents to a pipe. */
1181     while ( i_in > 0 && !p_object->b_die )
1182     {
1183         DWORD i_written;
1184         if ( !WriteFile( hChildStdinWr, p_in, i_in, &i_written, NULL ) )
1185             break;
1186         i_in -= i_written;
1187         p_in += i_written;
1188     }
1189
1190     /* Close the pipe handle so the child process stops reading. */
1191     CloseHandle(hChildStdinWr);
1192
1193     /* Close the write end of the pipe before reading from the
1194      * read end of the pipe. */
1195     CloseHandle(hChildStdoutWr);
1196
1197     /* Read output from the child process. */
1198     *pi_data = 0;
1199     if( *pp_data )
1200         free( pp_data );
1201     *pp_data = NULL;
1202     *pp_data = malloc( 1025 );  /* +1 for \0 */
1203
1204     while ( !p_object->b_die )
1205     {
1206         DWORD i_read;
1207         if ( !ReadFile( hChildStdoutRd, &(*pp_data)[*pi_data], 1024, &i_read,
1208                         NULL )
1209               || i_read == 0 )
1210             break;
1211         *pi_data += i_read;
1212         *pp_data = realloc( *pp_data, *pi_data + 1025 );
1213     }
1214
1215     while ( !p_object->b_die
1216              && !GetExitCodeProcess( piProcInfo.hProcess, &i_status )
1217              && i_status != STILL_ACTIVE )
1218         msleep( 10000 );
1219
1220     CloseHandle(piProcInfo.hProcess);
1221     CloseHandle(piProcInfo.hThread);
1222
1223     if ( i_status )
1224         msg_Warn( p_object,
1225                   "child %s returned with error code %ld",
1226                   ppsz_argv[0], i_status );
1227
1228 #else
1229     msg_Err( p_object, "vlc_execve called but no implementation is available" );
1230     return -1;
1231
1232 #endif
1233
1234     if (*pp_data == NULL)
1235         return -1;
1236
1237     (*pp_data)[*pi_data] = '\0';
1238     return 0;
1239 }