]> git.sesse.net Git - vlc/blob - src/extras/libc.c
38c930cafe7cc86074271c44437786e73e8fe3ab
[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     bool 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 = 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 #if defined (WIN32)
611 /**
612  * gettext callbacks for plugins.
613  * LibVLC links libintl statically on Windows.
614  */
615 char *vlc_dgettext( const char *package, const char *msgid )
616 {
617     return dgettext( package, msgid );
618 }
619 #endif
620
621 /**
622  * In-tree plugins share their gettext domain with LibVLC.
623  */
624 char *vlc_gettext( const char *msgid )
625 {
626     return dgettext( PACKAGE_NAME, msgid );
627 }
628
629 /*****************************************************************************
630  * count_utf8_string: returns the number of characters in the string.
631  *****************************************************************************/
632 static int count_utf8_string( const char *psz_string )
633 {
634     int i = 0, i_count = 0;
635     while( psz_string[ i ] != 0 )
636     {
637         if( ((unsigned char *)psz_string)[ i ] <  0x80UL ) i_count++;
638         i++;
639     }
640     return i_count;
641 }
642
643 /*****************************************************************************
644  * wraptext: inserts \n at convenient places to wrap the text.
645  *           Returns the modified string in a new buffer.
646  *****************************************************************************/
647 char *vlc_wraptext( const char *psz_text, int i_line )
648 {
649     int i_len;
650     char *psz_line, *psz_new_text;
651
652     psz_line = psz_new_text = strdup( psz_text );
653
654     i_len = count_utf8_string( psz_text );
655
656     while( i_len > i_line )
657     {
658         /* Look if there is a newline somewhere. */
659         char *psz_parser = psz_line;
660         int i_count = 0;
661         while( i_count <= i_line && *psz_parser != '\n' )
662         {
663             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
664             psz_parser++;
665             i_count++;
666         }
667         if( *psz_parser == '\n' )
668         {
669             i_len -= (i_count + 1);
670             psz_line = psz_parser + 1;
671             continue;
672         }
673
674         /* Find the furthest space. */
675         while( psz_parser > psz_line && *psz_parser != ' ' )
676         {
677             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser--;
678             psz_parser--;
679             i_count--;
680         }
681         if( *psz_parser == ' ' )
682         {
683             *psz_parser = '\n';
684             i_len -= (i_count + 1);
685             psz_line = psz_parser + 1;
686             continue;
687         }
688
689         /* Wrapping has failed. Find the first space or newline */
690         while( i_count < i_len && *psz_parser != ' ' && *psz_parser != '\n' )
691         {
692             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
693             psz_parser++;
694             i_count++;
695         }
696         if( i_count < i_len ) *psz_parser = '\n';
697         i_len -= (i_count + 1);
698         psz_line = psz_parser + 1;
699     }
700
701     return psz_new_text;
702 }
703
704 /*****************************************************************************
705  * iconv wrapper
706  *****************************************************************************/
707 vlc_iconv_t vlc_iconv_open( const char *tocode, const char *fromcode )
708 {
709 #if defined(HAVE_ICONV)
710     return iconv_open( tocode, fromcode );
711 #else
712     return NULL;
713 #endif
714 }
715
716 size_t vlc_iconv( vlc_iconv_t cd, const char **inbuf, size_t *inbytesleft,
717                   char **outbuf, size_t *outbytesleft )
718 {
719 #if defined(HAVE_ICONV)
720     return iconv( cd, (ICONV_CONST char **)inbuf, inbytesleft,
721                   outbuf, outbytesleft );
722 #else
723     int i_bytes;
724
725     if (inbytesleft == NULL || outbytesleft == NULL)
726     {
727         return 0;
728     }
729
730     i_bytes = __MIN(*inbytesleft, *outbytesleft);
731     if( !inbuf || !outbuf || !i_bytes ) return (size_t)(-1);
732     memcpy( *outbuf, *inbuf, i_bytes );
733     inbuf += i_bytes;
734     outbuf += i_bytes;
735     inbytesleft -= i_bytes;
736     outbytesleft -= i_bytes;
737     return i_bytes;
738 #endif
739 }
740
741 int vlc_iconv_close( vlc_iconv_t cd )
742 {
743 #if defined(HAVE_ICONV)
744     return iconv_close( cd );
745 #else
746     return 0;
747 #endif
748 }
749
750 /*****************************************************************************
751  * reduce a fraction
752  *   (adapted from libavcodec, author Michael Niedermayer <michaelni@gmx.at>)
753  *****************************************************************************/
754 bool vlc_ureduce( unsigned *pi_dst_nom, unsigned *pi_dst_den,
755                         uint64_t i_nom, uint64_t i_den, uint64_t i_max )
756 {
757     bool b_exact = 1;
758     uint64_t i_gcd;
759
760     if( i_den == 0 )
761     {
762         *pi_dst_nom = 0;
763         *pi_dst_den = 1;
764         return 1;
765     }
766
767     i_gcd = GCD( i_nom, i_den );
768     i_nom /= i_gcd;
769     i_den /= i_gcd;
770
771     if( i_max == 0 ) i_max = INT64_C(0xFFFFFFFF);
772
773     if( i_nom > i_max || i_den > i_max )
774     {
775         uint64_t i_a0_num = 0, i_a0_den = 1, i_a1_num = 1, i_a1_den = 0;
776         b_exact = 0;
777
778         for( ; ; )
779         {
780             uint64_t i_x = i_nom / i_den;
781             uint64_t i_a2n = i_x * i_a1_num + i_a0_num;
782             uint64_t i_a2d = i_x * i_a1_den + i_a0_den;
783
784             if( i_a2n > i_max || i_a2d > i_max ) break;
785
786             i_nom %= i_den;
787
788             i_a0_num = i_a1_num; i_a0_den = i_a1_den;
789             i_a1_num = i_a2n; i_a1_den = i_a2d;
790             if( i_nom == 0 ) break;
791             i_x = i_nom; i_nom = i_den; i_den = i_x;
792         }
793         i_nom = i_a1_num;
794         i_den = i_a1_den;
795     }
796
797     *pi_dst_nom = i_nom;
798     *pi_dst_den = i_den;
799
800     return b_exact;
801 }
802
803 /*************************************************************************
804  * vlc_parse_cmdline: Command line parsing into elements.
805  *
806  * The command line is composed of space/tab separated arguments.
807  * Quotes can be used as argument delimiters and a backslash can be used to
808  * escape a quote.
809  *************************************************************************/
810 static void find_end_quote( char **s, char **ppsz_parser, int i_quote )
811 {
812     int i_bcount = 0;
813
814     while( **s )
815     {
816         if( **s == '\\' )
817         {
818             **ppsz_parser = **s;
819             (*ppsz_parser)++; (*s)++;
820             i_bcount++;
821         }
822         else if( **s == '"' || **s == '\'' )
823         {
824             /* Preceeded by a number of '\' which we erase. */
825             *ppsz_parser -= i_bcount / 2;
826             if( i_bcount & 1 )
827             {
828                 /* '\\' followed by a '"' or '\'' */
829                 *ppsz_parser -= 1;
830                 **ppsz_parser = **s;
831                 (*ppsz_parser)++; (*s)++;
832                 i_bcount = 0;
833                 continue;
834             }
835
836             if( **s == i_quote )
837             {
838                 /* End */
839                 return;
840             }
841             else
842             {
843                 /* Different quoting */
844                 int i_quote = **s;
845                 **ppsz_parser = **s;
846                 (*ppsz_parser)++; (*s)++;
847                 find_end_quote( s, ppsz_parser, i_quote );
848                 **ppsz_parser = **s;
849                 (*ppsz_parser)++; (*s)++;
850             }
851
852             i_bcount = 0;
853         }
854         else
855         {
856             /* A regular character */
857             **ppsz_parser = **s;
858             (*ppsz_parser)++; (*s)++;
859             i_bcount = 0;
860         }
861     }
862 }
863
864 char **vlc_parse_cmdline( const char *psz_cmdline, int *i_args )
865 {
866     int argc = 0;
867     char **argv = 0;
868     char *s, *psz_parser, *psz_arg, *psz_orig;
869     int i_bcount = 0;
870
871     if( !psz_cmdline ) return 0;
872     psz_orig = strdup( psz_cmdline );
873     psz_arg = psz_parser = s = psz_orig;
874
875     while( *s )
876     {
877         if( *s == '\t' || *s == ' ' )
878         {
879             /* We have a complete argument */
880             *psz_parser = 0;
881             TAB_APPEND( argc, argv, strdup(psz_arg) );
882
883             /* Skip trailing spaces/tabs */
884             do{ s++; } while( *s == '\t' || *s == ' ' );
885
886             /* New argument */
887             psz_arg = psz_parser = s;
888             i_bcount = 0;
889         }
890         else if( *s == '\\' )
891         {
892             *psz_parser++ = *s++;
893             i_bcount++;
894         }
895         else if( *s == '"' || *s == '\'' )
896         {
897             if( ( i_bcount & 1 ) == 0 )
898             {
899                 /* Preceeded by an even number of '\', this is half that
900                  * number of '\', plus a quote which we erase. */
901                 int i_quote = *s;
902                 psz_parser -= i_bcount / 2;
903                 s++;
904                 find_end_quote( &s, &psz_parser, i_quote );
905                 s++;
906             }
907             else
908             {
909                 /* Preceeded by an odd number of '\', this is half that
910                  * number of '\' followed by a '"' */
911                 psz_parser = psz_parser - i_bcount/2 - 1;
912                 *psz_parser++ = '"';
913                 s++;
914             }
915             i_bcount = 0;
916         }
917         else
918         {
919             /* A regular character */
920             *psz_parser++ = *s++;
921             i_bcount = 0;
922         }
923     }
924
925     /* Take care of the last arg */
926     if( *psz_arg )
927     {
928         *psz_parser = '\0';
929         TAB_APPEND( argc, argv, strdup(psz_arg) );
930     }
931
932     if( i_args ) *i_args = argc;
933     free( psz_orig );
934     return argv;
935 }
936
937 /*************************************************************************
938  * vlc_execve: Execute an external program with a given environment,
939  * wait until it finishes and return its standard output
940  *************************************************************************/
941 int __vlc_execve( vlc_object_t *p_object, int i_argc, char *const *ppsz_argv,
942                   char *const *ppsz_env, const char *psz_cwd,
943                   const char *p_in, size_t i_in,
944                   char **pp_data, size_t *pi_data )
945 {
946     (void)i_argc; // <-- hmph
947 #ifdef HAVE_FORK
948 # define BUFSIZE 1024
949     int fds[2], i_status;
950
951     if (socketpair (AF_LOCAL, SOCK_STREAM, 0, fds))
952         return -1;
953
954     pid_t pid = -1;
955     if ((fds[0] > 2) && (fds[1] > 2))
956         pid = fork ();
957
958     switch (pid)
959     {
960         case -1:
961             msg_Err (p_object, "unable to fork (%m)");
962             close (fds[0]);
963             close (fds[1]);
964             return -1;
965
966         case 0:
967         {
968             sigset_t set;
969             sigemptyset (&set);
970             pthread_sigmask (SIG_SETMASK, &set, NULL);
971
972             /* NOTE:
973              * Like it or not, close can fail (and not only with EBADF)
974              */
975             if ((close (0) == 0) && (close (1) == 0) && (close (2) == 0)
976              && (dup (fds[1]) == 0) && (dup (fds[1]) == 1)
977              && (open ("/dev/null", O_RDONLY) == 2)
978              && ((psz_cwd == NULL) || (chdir (psz_cwd) == 0)))
979                 execve (ppsz_argv[0], ppsz_argv, ppsz_env);
980
981             exit (EXIT_FAILURE);
982         }
983     }
984
985     close (fds[1]);
986
987     *pi_data = 0;
988     if (*pp_data)
989         free (*pp_data);
990     *pp_data = NULL;
991
992     if (i_in == 0)
993         shutdown (fds[0], SHUT_WR);
994
995     while (!p_object->b_die)
996     {
997         struct pollfd ufd[1];
998         memset (ufd, 0, sizeof (ufd));
999         ufd[0].fd = fds[0];
1000         ufd[0].events = POLLIN;
1001
1002         if (i_in > 0)
1003             ufd[0].events |= POLLOUT;
1004
1005         if (poll (ufd, 1, 10) <= 0)
1006             continue;
1007
1008         if (ufd[0].revents & ~POLLOUT)
1009         {
1010             char *ptr = realloc (*pp_data, *pi_data + BUFSIZE + 1);
1011             if (ptr == NULL)
1012                 break; /* safely abort */
1013
1014             *pp_data = ptr;
1015
1016             ssize_t val = read (fds[0], ptr + *pi_data, BUFSIZE);
1017             switch (val)
1018             {
1019                 case -1:
1020                 case 0:
1021                     shutdown (fds[0], SHUT_RD);
1022                     break;
1023
1024                 default:
1025                     *pi_data += val;
1026             }
1027         }
1028
1029         if (ufd[0].revents & POLLOUT)
1030         {
1031             ssize_t val = write (fds[0], p_in, i_in);
1032             switch (val)
1033             {
1034                 case -1:
1035                 case 0:
1036                     i_in = 0;
1037                     shutdown (fds[0], SHUT_WR);
1038                     break;
1039
1040                 default:
1041                     i_in -= val;
1042                     p_in += val;
1043             }
1044         }
1045     }
1046
1047     close (fds[0]);
1048
1049     while (waitpid (pid, &i_status, 0) == -1);
1050
1051     if (WIFEXITED (i_status))
1052     {
1053         i_status = WEXITSTATUS (i_status);
1054         if (i_status)
1055             msg_Warn (p_object,  "child %s (PID %d) exited with error code %d",
1056                       ppsz_argv[0], (int)pid, i_status);
1057     }
1058     else
1059     if (WIFSIGNALED (i_status)) // <-- this should be redumdant a check
1060     {
1061         i_status = WTERMSIG (i_status);
1062         msg_Warn (p_object, "child %s (PID %d) exited on signal %d (%s)",
1063                   ppsz_argv[0], (int)pid, i_status, strsignal (i_status));
1064     }
1065
1066 #elif defined( WIN32 ) && !defined( UNDER_CE )
1067     SECURITY_ATTRIBUTES saAttr;
1068     PROCESS_INFORMATION piProcInfo;
1069     STARTUPINFO siStartInfo;
1070     BOOL bFuncRetn = FALSE;
1071     HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr;
1072     DWORD i_status;
1073     char *psz_cmd = NULL, *p_env = NULL, *p = NULL;
1074     char **ppsz_parser;
1075     int i_size;
1076
1077     /* Set the bInheritHandle flag so pipe handles are inherited. */
1078     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1079     saAttr.bInheritHandle = TRUE;
1080     saAttr.lpSecurityDescriptor = NULL;
1081
1082     /* Create a pipe for the child process's STDOUT. */
1083     if ( !CreatePipe( &hChildStdoutRd, &hChildStdoutWr, &saAttr, 0 ) )
1084     {
1085         msg_Err( p_object, "stdout pipe creation failed" );
1086         return -1;
1087     }
1088
1089     /* Ensure the read handle to the pipe for STDOUT is not inherited. */
1090     SetHandleInformation( hChildStdoutRd, HANDLE_FLAG_INHERIT, 0 );
1091
1092     /* Create a pipe for the child process's STDIN. */
1093     if ( !CreatePipe( &hChildStdinRd, &hChildStdinWr, &saAttr, 0 ) )
1094     {
1095         msg_Err( p_object, "stdin pipe creation failed" );
1096         return -1;
1097     }
1098
1099     /* Ensure the write handle to the pipe for STDIN is not inherited. */
1100     SetHandleInformation( hChildStdinWr, HANDLE_FLAG_INHERIT, 0 );
1101
1102     /* Set up members of the PROCESS_INFORMATION structure. */
1103     ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
1104
1105     /* Set up members of the STARTUPINFO structure. */
1106     ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
1107     siStartInfo.cb = sizeof(STARTUPINFO);
1108     siStartInfo.hStdError = hChildStdoutWr;
1109     siStartInfo.hStdOutput = hChildStdoutWr;
1110     siStartInfo.hStdInput = hChildStdinRd;
1111     siStartInfo.wShowWindow = SW_HIDE;
1112     siStartInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1113
1114     /* Set up the command line. */
1115     psz_cmd = malloc(32768);
1116     if( !psz_cmd )
1117         return -1;
1118     psz_cmd[0] = '\0';
1119     i_size = 32768;
1120     ppsz_parser = &ppsz_argv[0];
1121     while ( ppsz_parser[0] != NULL && i_size > 0 )
1122     {
1123         /* Protect the last argument with quotes ; the other arguments
1124          * are supposed to be already protected because they have been
1125          * passed as a command-line option. */
1126         if ( ppsz_parser[1] == NULL )
1127         {
1128             strncat( psz_cmd, "\"", i_size );
1129             i_size--;
1130         }
1131         strncat( psz_cmd, *ppsz_parser, i_size );
1132         i_size -= strlen( *ppsz_parser );
1133         if ( ppsz_parser[1] == NULL )
1134         {
1135             strncat( psz_cmd, "\"", i_size );
1136             i_size--;
1137         }
1138         strncat( psz_cmd, " ", i_size );
1139         i_size--;
1140         ppsz_parser++;
1141     }
1142
1143     /* Set up the environment. */
1144     p = p_env = malloc(32768);
1145     if( !p )
1146     {
1147         free( psz_cmd );
1148         return -1;
1149     }
1150
1151     i_size = 32768;
1152     ppsz_parser = &ppsz_env[0];
1153     while ( *ppsz_parser != NULL && i_size > 0 )
1154     {
1155         memcpy( p, *ppsz_parser,
1156                 __MIN((int)(strlen(*ppsz_parser) + 1), i_size) );
1157         p += strlen(*ppsz_parser) + 1;
1158         i_size -= strlen(*ppsz_parser) + 1;
1159         ppsz_parser++;
1160     }
1161     *p = '\0';
1162
1163     /* Create the child process. */
1164     bFuncRetn = CreateProcess( NULL,
1165           psz_cmd,       // command line
1166           NULL,          // process security attributes
1167           NULL,          // primary thread security attributes
1168           TRUE,          // handles are inherited
1169           0,             // creation flags
1170           p_env,
1171           psz_cwd,
1172           &siStartInfo,  // STARTUPINFO pointer
1173           &piProcInfo ); // receives PROCESS_INFORMATION
1174
1175     free( psz_cmd );
1176     free( p_env );
1177
1178     if ( bFuncRetn == 0 )
1179     {
1180         msg_Err( p_object, "child creation failed" );
1181         return -1;
1182     }
1183
1184     /* Read from a file and write its contents to a pipe. */
1185     while ( i_in > 0 && !p_object->b_die )
1186     {
1187         DWORD i_written;
1188         if ( !WriteFile( hChildStdinWr, p_in, i_in, &i_written, NULL ) )
1189             break;
1190         i_in -= i_written;
1191         p_in += i_written;
1192     }
1193
1194     /* Close the pipe handle so the child process stops reading. */
1195     CloseHandle(hChildStdinWr);
1196
1197     /* Close the write end of the pipe before reading from the
1198      * read end of the pipe. */
1199     CloseHandle(hChildStdoutWr);
1200
1201     /* Read output from the child process. */
1202     *pi_data = 0;
1203     if( *pp_data )
1204         free( pp_data );
1205     *pp_data = NULL;
1206     *pp_data = malloc( 1025 );  /* +1 for \0 */
1207
1208     while ( !p_object->b_die )
1209     {
1210         DWORD i_read;
1211         if ( !ReadFile( hChildStdoutRd, &(*pp_data)[*pi_data], 1024, &i_read,
1212                         NULL )
1213               || i_read == 0 )
1214             break;
1215         *pi_data += i_read;
1216         *pp_data = realloc( *pp_data, *pi_data + 1025 );
1217     }
1218
1219     while ( !p_object->b_die
1220              && !GetExitCodeProcess( piProcInfo.hProcess, &i_status )
1221              && i_status != STILL_ACTIVE )
1222         msleep( 10000 );
1223
1224     CloseHandle(piProcInfo.hProcess);
1225     CloseHandle(piProcInfo.hThread);
1226
1227     if ( i_status )
1228         msg_Warn( p_object,
1229                   "child %s returned with error code %ld",
1230                   ppsz_argv[0], i_status );
1231
1232 #else
1233     msg_Err( p_object, "vlc_execve called but no implementation is available" );
1234     return -1;
1235
1236 #endif
1237
1238     if (*pp_data == NULL)
1239         return -1;
1240
1241     (*pp_data)[*pi_data] = '\0';
1242     return 0;
1243 }