OSDN Git Service

Changed a log -> deep_log for markup processing.
[handbrake-jp/handbrake-jp-git.git] / libhb / ports.c
1 /* $Id: ports.c,v 1.15 2005/10/15 18:05:03 titer Exp $
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.fr/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #ifdef USE_PTHREAD
8 #ifdef SYS_LINUX
9 #define _GNU_SOURCE
10 #include <sched.h>
11 #endif
12 #include <pthread.h>
13 #endif
14
15 #ifdef SYS_BEOS
16 #include <kernel/OS.h>
17 #endif
18
19 #if defined(SYS_DARWIN) || defined(SYS_FREEBSD)
20 #include <sys/types.h>
21 #include <sys/sysctl.h>
22 #endif
23
24 #ifdef SYS_OPENBSD
25 #include <sys/param.h>
26 #include <sys/sysctl.h>
27 #include <machine/cpu.h>
28 #endif
29
30 #ifdef SYS_CYGWIN
31 #include <windows.h>
32 #endif
33
34 #ifdef SYS_MINGW
35 #include <pthread.h>
36 #include <windows.h>
37 #endif
38
39 #ifdef SYS_SunOS
40 #include <sys/processor.h>
41 #endif
42
43 #include <time.h>
44 #include <sys/time.h>
45
46
47 #ifdef SYS_MINGW
48 #include <winsock2.h>
49 #include <ws2tcpip.h>
50 #else
51 #include <sys/types.h>
52 #include <sys/socket.h>
53 #include <netdb.h>
54 #include <netinet/in.h>
55 #endif
56
57 #include <stddef.h>
58
59 #include "hb.h"
60
61 /************************************************************************
62  * hb_get_date()
63  ************************************************************************
64  * Returns the current date in milliseconds.
65  * On Win32, we implement a gettimeofday emulation here because
66  * libdvdread and libmp4v2 use it without checking.
67  ************************************************************************/
68 /*
69 #ifdef SYS_CYGWIN
70 struct timezone
71 {
72 };
73
74 int gettimeofday( struct timeval * tv, struct timezone * tz )
75 {
76     int tick;
77     tick        = GetTickCount();
78     tv->tv_sec  = tick / 1000;
79     tv->tv_usec = ( tick % 1000 ) * 1000;
80     return 0;
81 }
82 #endif
83 */
84
85 uint64_t hb_get_date()
86 {
87     struct timeval tv;
88     gettimeofday( &tv, NULL );
89     return( (uint64_t) tv.tv_sec * 1000 + (uint64_t) tv.tv_usec / 1000 );
90 }
91
92 /************************************************************************
93  * hb_snooze()
94  ************************************************************************
95  * Waits <delay> milliseconds.
96  ************************************************************************/
97 void hb_snooze( int delay )
98 {
99     if( delay < 1 )
100     {
101         return;
102     }
103 #if defined( SYS_BEOS )
104     snooze( 1000 * delay );
105 #elif defined( SYS_DARWIN ) || defined( SYS_LINUX ) || defined( SYS_FREEBSD) || defined( SYS_SunOS )
106     usleep( 1000 * delay );
107 #elif defined( SYS_CYGWIN ) || defined( SYS_MINGW )
108     Sleep( delay );
109 #endif
110 }
111
112 /************************************************************************
113  * hb_get_cpu_count()
114  ************************************************************************
115  * Whenever possible, returns the number of CPUs on the current
116  * computer. Returns 1 otherwise.
117  * The detection is actually only performed on the first call.
118  ************************************************************************/
119 int hb_get_cpu_count()
120 {
121     static int cpu_count = 0;
122
123     if( cpu_count )
124     {
125         return cpu_count;
126     }
127     cpu_count = 1;
128
129 #if defined(SYS_CYGWIN) || defined(SYS_MINGW)
130     SYSTEM_INFO cpuinfo;
131     GetSystemInfo( &cpuinfo );
132     cpu_count = cpuinfo.dwNumberOfProcessors;
133
134 #elif defined(SYS_LINUX)
135     unsigned int bit;
136     cpu_set_t p_aff;
137     memset( &p_aff, 0, sizeof(p_aff) );
138     sched_getaffinity( 0, sizeof(p_aff), &p_aff );
139     for( cpu_count = 0, bit = 0; bit < sizeof(p_aff); bit++ )
140          cpu_count += (((uint8_t *)&p_aff)[bit / 8] >> (bit % 8)) & 1;
141
142 #elif defined(SYS_BEOS)
143     system_info info;
144     get_system_info( &info );
145     cpu_count = info.cpu_count;
146
147 #elif defined(SYS_DARWIN) || defined(SYS_FREEBSD) || defined(SYS_OPENBSD)
148     size_t length = sizeof( cpu_count );
149 #ifdef SYS_OPENBSD
150     int mib[2] = { CTL_HW, HW_NCPU };
151     if( sysctl(mib, 2, &cpu_count, &length, NULL, 0) )
152 #else
153     if( sysctlbyname("hw.ncpu", &cpu_count, &length, NULL, 0) )
154 #endif
155     {
156         cpu_count = 1;
157     }
158
159 #elif defined( SYS_SunOS )
160     {
161         processorid_t cpumax;
162         int i,j=0;
163
164         cpumax = sysconf(_SC_CPUID_MAX);
165
166         for(i = 0; i <= cpumax; i++ )
167         {
168             if(p_online(i, P_STATUS) != -1)
169             {
170                 j++;
171             }
172         }
173         cpu_count=j;
174     }
175 #endif
176
177     cpu_count = MAX( 1, cpu_count );
178     cpu_count = MIN( cpu_count, 8 );
179
180     return cpu_count;
181 }
182
183 /************************************************************************
184  * Get a tempory directory for HB
185  ***********************************************************************/
186 void hb_get_tempory_directory( hb_handle_t * h, char path[512] )
187 {
188     char base[512];
189
190     /* Create the base */
191 #if defined( SYS_CYGWIN ) || defined( SYS_MINGW )
192     char *p;
193     int i_size = GetTempPath( 512, base );
194     if( i_size <= 0 || i_size >= 512 )
195     {
196         if( getcwd( base, 512 ) == NULL )
197             strcpy( base, "c:" ); /* Bad fallback but ... */
198     }
199
200     /* c:/path/ works like a charm under cygwin(win32?) so use it */
201     while( ( p = strchr( base, '\\' ) ) )
202         *p = '/';
203 #else
204     strcpy( base, "/tmp" );
205 #endif
206     /* I prefer to remove evntual last '/' (for cygwin) */
207     if( base[strlen(base)-1] == '/' )
208         base[strlen(base)-1] = '\0';
209
210     snprintf( path, 512, "%s/hb.%d", base, hb_get_pid( h ) );
211 }
212
213 /************************************************************************
214  * Get a tempory filename for HB
215  ***********************************************************************/
216 void hb_get_tempory_filename( hb_handle_t * h, char name[1024],
217                               char *fmt, ... )
218 {
219     va_list args;
220
221     hb_get_tempory_directory( h, name );
222     strcat( name, "/" );
223
224     va_start( args, fmt );
225     vsnprintf( &name[strlen(name)], 1024 - strlen(name), fmt, args );
226     va_end( args );
227 }
228
229 /************************************************************************
230  * hb_mkdir
231  ************************************************************************
232  * Wrapper to the real mkdir, needed only because it doesn't take a
233  * second argument on Win32. Grrr.
234  ***********************************************************************/
235 void hb_mkdir( char * name )
236 {
237 #ifdef SYS_MINGW
238     mkdir( name );
239 #else
240     mkdir( name, 0755 );
241 #endif
242 }
243
244 /************************************************************************
245  * Portable thread implementation
246  ***********************************************************************/
247 struct hb_thread_s
248 {
249     char       * name;
250     int          priority;
251     void      (* function) ( void * );
252     void       * arg;
253
254     hb_lock_t  * lock;
255     int          exited;
256
257 #if defined( SYS_BEOS )
258     thread_id    thread;
259 #elif USE_PTHREAD
260     pthread_t    thread;
261 //#elif defined( SYS_CYGWIN )
262 //    HANDLE       thread;
263 #endif
264 };
265
266 /* Get a unique identifier to thread and represent as 64-bit unsigned.
267  * If unsupported, the value 0 is be returned.
268  * Caller should use result only for display/log purposes.
269  */
270 static uint64_t hb_thread_to_integer( const hb_thread_t* t )
271 {
272 #if defined( USE_PTHREAD )
273     #if defined( _WIN32 ) || defined( __MINGW32__ )
274         return (uint64_t)(ptrdiff_t)t->thread.p;
275     #elif defined( SYS_DARWIN )
276         return (unsigned long)t->thread;
277     #else
278         return (uint64_t)t->thread;
279     #endif
280 #else
281     return 0;
282 #endif
283 }
284
285 /************************************************************************
286  * hb_thread_func()
287  ************************************************************************
288  * We use it as the root routine for any thread, for two reasons:
289  *  + To set the thread priority on OS X (pthread_setschedparam() could
290  *    be called from hb_thread_init(), but it's nicer to do it as we
291  *    are sure it is done before the real routine starts)
292  *  + Get informed when the thread exits, so we know whether
293  *    hb_thread_close() will block or not.
294  ***********************************************************************/
295 static void hb_thread_func( void * _t )
296 {
297     hb_thread_t * t = (hb_thread_t *) _t;
298
299 #if defined( SYS_DARWIN )
300     /* Set the thread priority */
301     struct sched_param param;
302     memset( &param, 0, sizeof( struct sched_param ) );
303     param.sched_priority = t->priority;
304     pthread_setschedparam( pthread_self(), SCHED_OTHER, &param );
305 #endif
306
307 #if defined( SYS_BEOS )
308     signal( SIGINT, SIG_IGN );
309 #endif
310
311     /* Start the actual routine */
312     t->function( t->arg );
313
314     /* Inform that the thread can be joined now */
315     hb_deep_log( 2, "thread %"PRIx64" exited (\"%s\")", hb_thread_to_integer( t ), t->name );
316     hb_lock( t->lock );
317     t->exited = 1;
318     hb_unlock( t->lock );
319 }
320
321 /************************************************************************
322  * hb_thread_init()
323  ************************************************************************
324  * name:     user-friendly name
325  * function: the thread routine
326  * arg:      argument of the routine
327  * priority: HB_LOW_PRIORITY or HB_NORMAL_PRIORITY
328  ***********************************************************************/
329 hb_thread_t * hb_thread_init( char * name, void (* function)(void *),
330                               void * arg, int priority )
331 {
332     hb_thread_t * t = calloc( sizeof( hb_thread_t ), 1 );
333
334     t->name     = strdup( name );
335     t->function = function;
336     t->arg      = arg;
337     t->priority = priority;
338
339     t->lock     = hb_lock_init();
340
341     /* Create and start the thread */
342 #if defined( SYS_BEOS )
343     t->thread = spawn_thread( (thread_func) hb_thread_func,
344                               name, priority, t );
345     resume_thread( t->thread );
346
347 #elif USE_PTHREAD
348     pthread_create( &t->thread, NULL,
349                     (void * (*)( void * )) hb_thread_func, t );
350
351 //#elif defined( SYS_CYGWIN )
352 //    t->thread = CreateThread( NULL, 0,
353 //        (LPTHREAD_START_ROUTINE) hb_thread_func, t, 0, NULL );
354 //
355 //    /* Maybe use THREAD_PRIORITY_LOWEST instead */
356 //    if( priority == HB_LOW_PRIORITY )
357 //        SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL );
358 #endif
359
360     hb_deep_log( 2, "thread %"PRIx64" started (\"%s\")", hb_thread_to_integer( t ), t->name );
361     return t;
362 }
363
364 /************************************************************************
365  * hb_thread_close()
366  ************************************************************************
367  * Joins the thread and frees memory.
368  ***********************************************************************/
369 void hb_thread_close( hb_thread_t ** _t )
370 {
371     hb_thread_t * t = *_t;
372
373     /* Join the thread */
374 #if defined( SYS_BEOS )
375     long exit_value;
376     wait_for_thread( t->thread, &exit_value );
377
378 #elif USE_PTHREAD
379     pthread_join( t->thread, NULL );
380
381 //#elif defined( SYS_CYGWIN )
382 //    WaitForSingleObject( t->thread, INFINITE );
383 #endif
384
385     hb_deep_log( 2, "thread %"PRIx64" joined (\"%s\")", hb_thread_to_integer( t ), t->name );
386
387     hb_lock_close( &t->lock );
388     free( t->name );
389     free( t );
390     *_t = NULL;
391 }
392
393 /************************************************************************
394  * hb_thread_has_exited()
395  ************************************************************************
396  * Returns 1 if the thread can be joined right away, 0 otherwise.
397  ***********************************************************************/
398 int hb_thread_has_exited( hb_thread_t * t )
399 {
400     int exited;
401
402     hb_lock( t->lock );
403     exited = t->exited;
404     hb_unlock( t->lock );
405
406     return exited;
407 }
408
409 /************************************************************************
410  * Portable mutex implementation
411  ***********************************************************************/
412 struct hb_lock_s
413 {
414 #if defined( SYS_BEOS )
415     sem_id          sem;
416 #elif USE_PTHREAD
417     pthread_mutex_t mutex;
418 //#elif defined( SYS_CYGWIN )
419 //    HANDLE          mutex;
420 #endif
421 };
422
423 /************************************************************************
424  * hb_lock_init()
425  * hb_lock_close()
426  * hb_lock()
427  * hb_unlock()
428  ************************************************************************
429  * Basic wrappers to OS-specific semaphore or mutex functions.
430  ***********************************************************************/
431 hb_lock_t * hb_lock_init()
432 {
433     hb_lock_t * l = calloc( sizeof( hb_lock_t ), 1 );
434
435 #if defined( SYS_BEOS )
436     l->sem = create_sem( 1, "sem" );
437 #elif USE_PTHREAD
438     pthread_mutexattr_t mta;
439
440     pthread_mutexattr_init(&mta);
441
442 #if defined( SYS_CYGWIN )
443     pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_NORMAL);
444 #endif
445
446     pthread_mutex_init( &l->mutex, &mta );
447 //#elif defined( SYS_CYGWIN )
448 //    l->mutex = CreateMutex( 0, FALSE, 0 );
449 #endif
450
451     return l;
452 }
453
454 void hb_lock_close( hb_lock_t ** _l )
455 {
456     hb_lock_t * l = *_l;
457
458 #if defined( SYS_BEOS )
459     delete_sem( l->sem );
460 #elif USE_PTHREAD
461     pthread_mutex_destroy( &l->mutex );
462 //#elif defined( SYS_CYGWIN )
463 //    CloseHandle( l->mutex );
464 #endif
465     free( l );
466
467     *_l = NULL;
468 }
469
470 void hb_lock( hb_lock_t * l )
471 {
472 #if defined( SYS_BEOS )
473     acquire_sem( l->sem );
474 #elif USE_PTHREAD
475     pthread_mutex_lock( &l->mutex );
476 //#elif defined( SYS_CYGWIN )
477 //    WaitForSingleObject( l->mutex, INFINITE );
478 #endif
479 }
480
481 void hb_unlock( hb_lock_t * l )
482 {
483 #if defined( SYS_BEOS )
484     release_sem( l->sem );
485 #elif USE_PTHREAD
486     pthread_mutex_unlock( &l->mutex );
487 //#elif defined( SYS_CYGWIN )
488 //    ReleaseMutex( l->mutex );
489 #endif
490 }
491
492 /************************************************************************
493  * Portable condition variable implementation
494  ***********************************************************************/
495 struct hb_cond_s
496 {
497 #if defined( SYS_BEOS )
498     int                 thread;
499 #elif USE_PTHREAD
500     pthread_cond_t      cond;
501 //#elif defined( SYS_CYGWIN )
502 //    HANDLE              event;
503 #endif
504 };
505
506 /************************************************************************
507  * hb_cond_init()
508  * hb_cond_close()
509  * hb_cond_wait()
510  * hb_cond_signal()
511  ************************************************************************
512  * Win9x is not supported by this implementation (SignalObjectAndWait()
513  * only available on Windows 2000/XP).
514  ***********************************************************************/
515 hb_cond_t * hb_cond_init()
516 {
517     hb_cond_t * c = calloc( sizeof( hb_cond_t ), 1 );
518
519 #if defined( SYS_BEOS )
520     c->thread = -1;
521 #elif USE_PTHREAD
522     pthread_cond_init( &c->cond, NULL );
523 //#elif defined( SYS_CYGWIN )
524 //    c->event = CreateEvent( NULL, FALSE, FALSE, NULL );
525 #endif
526
527     return c;
528 }
529
530 void hb_cond_close( hb_cond_t ** _c )
531 {
532     hb_cond_t * c = *_c;
533
534 #if defined( SYS_BEOS )
535 #elif USE_PTHREAD
536     pthread_cond_destroy( &c->cond );
537 //#elif defined( SYS_CYGWIN )
538 //    CloseHandle( c->event );
539 #endif
540     free( c );
541
542     *_c = NULL;
543 }
544
545 void hb_cond_wait( hb_cond_t * c, hb_lock_t * lock )
546 {
547 #if defined( SYS_BEOS )
548     c->thread = find_thread( NULL );
549     release_sem( lock->sem );
550     suspend_thread( c->thread );
551     acquire_sem( lock->sem );
552     c->thread = -1;
553 #elif USE_PTHREAD
554     pthread_cond_wait( &c->cond, &lock->mutex );
555 //#elif defined( SYS_CYGWIN )
556 //    SignalObjectAndWait( lock->mutex, c->event, INFINITE, FALSE );
557 //    WaitForSingleObject( lock->mutex, INFINITE );
558 #endif
559 }
560
561 void hb_cond_signal( hb_cond_t * c )
562 {
563 #if defined( SYS_BEOS )
564     while( c->thread != -1 )
565     {
566         thread_info info;
567         get_thread_info( c->thread, &info );
568         if( info.state == B_THREAD_SUSPENDED )
569         {
570             resume_thread( c->thread );
571             break;
572         }
573         /* Looks like we have been called between hb_cond_wait's
574            release_sem() and suspend_thread() lines. Wait until the
575            thread is actually suspended before we resume it */
576         snooze( 5000 );
577     }
578 #elif USE_PTHREAD
579     pthread_cond_signal( &c->cond );
580 //#elif defined( SYS_CYGWIN )
581 //    PulseEvent( c->event );
582 #endif
583 }
584
585 /************************************************************************
586  * Network
587  ***********************************************************************/
588
589 struct hb_net_s
590 {
591     int socket;
592 };
593
594 hb_net_t * hb_net_open( char * address, int port )
595 {
596     hb_net_t * n = calloc( sizeof( hb_net_t ), 1 );
597
598     struct sockaddr_in   sock;
599     struct hostent     * host;
600
601     /* TODO: find out why this doesn't work on Win32 */
602     if( !( host = gethostbyname( address ) ) )
603     {
604         hb_log( "gethostbyname failed (%s)", address );
605         free( n );
606         return NULL;
607     }
608
609     memset( &sock, 0, sizeof( struct sockaddr_in ) );
610     sock.sin_family = host->h_addrtype;
611     sock.sin_port   = htons( port );
612     memcpy( &sock.sin_addr, host->h_addr, host->h_length );
613
614     if( ( n->socket = socket( host->h_addrtype, SOCK_STREAM, 0 ) ) < 0 )
615     {
616         hb_log( "socket failed" );
617         free( n );
618         return NULL;
619     }
620
621     if( connect( n->socket, (struct sockaddr *) &sock,
622                  sizeof( struct sockaddr_in ) ) < 0 )
623     {
624         hb_log( "connect failed" );
625         free( n );
626         return NULL;
627     }
628
629     return n;
630 }
631
632 int hb_net_send( hb_net_t * n, char * buffer )
633 {
634     return send( n->socket, buffer, strlen( buffer ), 0 );
635 }
636
637 int hb_net_recv( hb_net_t * n, char * buffer, int size )
638 {
639     return recv( n->socket, buffer, size - 1, 0 );
640 }
641
642 void hb_net_close( hb_net_t ** _n )
643 {
644     hb_net_t * n = (hb_net_t *) *_n;
645     close( n->socket );
646     free( n );
647     *_n = NULL;
648 }
649