1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
|
/* ports.c
Copyright (c) 2003-2013 HandBrake Team
This file is part of the HandBrake source code
Homepage: <http://handbrake.fr/>.
It may be used under the terms of the GNU General Public License v2.
For full terms see the file COPYING file or visit http://www.gnu.org/licenses/gpl-2.0.html
*/
#ifdef USE_PTHREAD
#ifdef SYS_LINUX
#define _GNU_SOURCE
#include <sched.h>
#endif
#include <pthread.h>
#endif
#ifdef SYS_BEOS
#include <kernel/OS.h>
#endif
#if defined(SYS_DARWIN) || defined(SYS_FREEBSD)
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#ifdef SYS_OPENBSD
#include <sys/param.h>
#include <sys/sysctl.h>
#include <machine/cpu.h>
#endif
#ifdef SYS_MINGW
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#endif
#ifdef SYS_CYGWIN
#include <windows.h>
#endif
#ifdef SYS_MINGW
#include <pthread.h>
#include <windows.h>
#include <wchar.h>
#include <mbctype.h>
#include <locale.h>
#endif
#ifdef SYS_SunOS
#include <sys/processor.h>
#endif
#include <time.h>
#include <sys/time.h>
#if defined( SYS_LINUX )
#include <linux/cdrom.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#elif defined( SYS_OPENBSD )
#include <sys/dvdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#endif
#ifdef __APPLE__
#include <IOKit/pwr_mgt/IOPMLib.h>
#endif
#include <stddef.h>
#include <unistd.h>
#include "hb.h"
#include "libavutil/cpu.h"
/************************************************************************
* hb_get_date()
************************************************************************
* Returns the current date in milliseconds.
* On Win32, we implement a gettimeofday emulation here because
* libdvdread and libmp4v2 use it without checking.
************************************************************************/
/*
#ifdef SYS_CYGWIN
struct timezone
{
};
int gettimeofday( struct timeval * tv, struct timezone * tz )
{
int tick;
tick = GetTickCount();
tv->tv_sec = tick / 1000;
tv->tv_usec = ( tick % 1000 ) * 1000;
return 0;
}
#endif
*/
// Convert utf8 string to current code page.
// The internal string representation in hb is utf8. But some
// libraries (libmkv, and mp4v2) expect filenames in the current
// code page. So we must convert.
char * hb_utf8_to_cp(const char *src)
{
char *dst = NULL;
#if defined( SYS_MINGW )
int num_chars = MultiByteToWideChar(CP_UTF8, 0, src, -1, NULL, 0);
if (num_chars <= 0)
return NULL;
wchar_t * tmp = calloc(num_chars, sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, src, -1, tmp, num_chars);
int len = WideCharToMultiByte(GetACP(), 0, tmp, num_chars, NULL, 0, NULL, NULL);
if (len <= 0)
return NULL;
dst = calloc(len, sizeof(char));
WideCharToMultiByte(GetACP(), 0, tmp, num_chars, dst, len, NULL, NULL);
free(tmp);
#else
// Other platforms don't have code pages
dst = strdup(src);
#endif
return dst;
}
int hb_dvd_region(char *device, int *region_mask)
{
#if defined( DVD_LU_SEND_RPC_STATE ) && defined( DVD_AUTH )
struct stat st;
dvd_authinfo ai;
int fd, ret;
fd = open( device, O_RDONLY );
if ( fd < 0 )
return -1;
if ( fstat( fd, &st ) < 0 )
{
close( fd );
return -1;
}
if ( !( S_ISBLK( st.st_mode ) || S_ISCHR( st.st_mode ) ) )
{
close( fd );
return -1;
}
ai.type = DVD_LU_SEND_RPC_STATE;
ret = ioctl(fd, DVD_AUTH, &ai);
close( fd );
if ( ret < 0 )
return ret;
*region_mask = ai.lrpcs.region_mask;
return 0;
#else
return -1;
#endif
}
uint64_t hb_get_date()
{
struct timeval tv;
gettimeofday( &tv, NULL );
return( (uint64_t) tv.tv_sec * 1000 + (uint64_t) tv.tv_usec / 1000 );
}
uint64_t hb_get_time_us()
{
#ifdef SYS_MINGW
static LARGE_INTEGER frequency;
LARGE_INTEGER cur_time;
if (frequency.QuadPart == 0)
{
QueryPerformanceFrequency(&frequency);
}
QueryPerformanceCounter(&cur_time);
return (uint64_t)(1000000 * cur_time.QuadPart / frequency.QuadPart);
#else
struct timeval tv;
gettimeofday(&tv, NULL);
return ((uint64_t)tv.tv_sec * 1000000 + (uint64_t)tv.tv_usec);
#endif
}
/************************************************************************
* hb_snooze()
************************************************************************
* Waits <delay> milliseconds.
************************************************************************/
void hb_snooze( int delay )
{
if( delay < 1 )
{
return;
}
#if defined( SYS_BEOS )
snooze( 1000 * delay );
#elif defined( SYS_DARWIN ) || defined( SYS_LINUX ) || defined( SYS_FREEBSD) || defined( SYS_SunOS )
usleep( 1000 * delay );
#elif defined( SYS_CYGWIN ) || defined( SYS_MINGW )
Sleep( delay );
#endif
}
/************************************************************************
* Get information about the CPU (number of cores, name, platform name)
************************************************************************/
static void init_cpu_info();
static int init_cpu_count();
struct
{
enum hb_cpu_platform platform;
const char *name;
char buf[48];
int count;
} hb_cpu_info;
int hb_get_cpu_count()
{
return hb_cpu_info.count;
}
int hb_get_cpu_platform()
{
return hb_cpu_info.platform;
}
const char* hb_get_cpu_name()
{
return hb_cpu_info.name;
}
const char* hb_get_cpu_platform_name()
{
switch (hb_cpu_info.platform)
{
// Intel 64 and IA-32 Architectures Software Developer's Manual, Vol. 3C
// Table 35-1: CPUID Signature Values of DisplayFamily_DisplayModel
case HB_CPU_PLATFORM_INTEL_SNB:
return "Intel microarchitecture Sandy Bridge";
case HB_CPU_PLATFORM_INTEL_IVB:
return "Intel microarchitecture Ivy Bridge";
case HB_CPU_PLATFORM_INTEL_HSW:
return "Intel microarchitecture Haswell";
default:
return NULL;
}
}
static void init_cpu_info()
{
hb_cpu_info.name = NULL;
hb_cpu_info.count = init_cpu_count();
hb_cpu_info.platform = HB_CPU_PLATFORM_UNSPECIFIED;
if (av_get_cpu_flags() & AV_CPU_FLAG_SSE)
{
int eax, ebx, ecx, edx, family, model;
ff_cpu_cpuid(1, &eax, &ebx, &ecx, &edx);
family = ((eax >> 8) & 0xf) + ((eax >> 20) & 0xff);
model = ((eax >> 4) & 0xf) + ((eax >> 12) & 0xf0);
// Intel 64 and IA-32 Architectures Software Developer's Manual, Vol. 3C
// Table 35-1: CPUID Signature Values of DisplayFamily_DisplayModel
switch (family)
{
case 0x06:
{
switch (model)
{
case 0x2A:
case 0x2D:
hb_cpu_info.platform = HB_CPU_PLATFORM_INTEL_SNB;
break;
case 0x3A:
case 0x3E:
hb_cpu_info.platform = HB_CPU_PLATFORM_INTEL_IVB;
break;
case 0x3C:
case 0x45:
case 0x46:
hb_cpu_info.platform = HB_CPU_PLATFORM_INTEL_HSW;
break;
default:
break;
}
} break;
default:
break;
}
// Intel 64 and IA-32 Architectures Software Developer's Manual, Vol. 2A
// Figure 3-8: Determination of Support for the Processor Brand String
// Table 3-17: Information Returned by CPUID Instruction
ff_cpu_cpuid(0x80000000, &eax, &ebx, &ecx, &edx);
if ((eax & 0x80000004) < 0x80000004)
{
ff_cpu_cpuid(0x80000002,
(int*)&hb_cpu_info.buf[ 0],
(int*)&hb_cpu_info.buf[ 4],
(int*)&hb_cpu_info.buf[ 8],
(int*)&hb_cpu_info.buf[12]);
ff_cpu_cpuid(0x80000003,
(int*)&hb_cpu_info.buf[16],
(int*)&hb_cpu_info.buf[20],
(int*)&hb_cpu_info.buf[24],
(int*)&hb_cpu_info.buf[28]);
ff_cpu_cpuid(0x80000004,
(int*)&hb_cpu_info.buf[32],
(int*)&hb_cpu_info.buf[36],
(int*)&hb_cpu_info.buf[40],
(int*)&hb_cpu_info.buf[44]);
hb_cpu_info.name = hb_cpu_info.buf;
hb_cpu_info.buf[47] = '\0'; // just in case
while (isspace(*hb_cpu_info.name))
{
// skip leading whitespace to prettify
hb_cpu_info.name++;
}
}
}
}
/*
* Whenever possible, returns the number of CPUs on the current computer.
* Returns 1 otherwise.
*/
static int init_cpu_count()
{
int cpu_count = 1;
#if defined(SYS_CYGWIN) || defined(SYS_MINGW)
SYSTEM_INFO cpuinfo;
GetSystemInfo( &cpuinfo );
cpu_count = cpuinfo.dwNumberOfProcessors;
#elif defined(SYS_LINUX)
unsigned int bit;
cpu_set_t p_aff;
memset( &p_aff, 0, sizeof(p_aff) );
sched_getaffinity( 0, sizeof(p_aff), &p_aff );
for( cpu_count = 0, bit = 0; bit < sizeof(p_aff); bit++ )
cpu_count += (((uint8_t *)&p_aff)[bit / 8] >> (bit % 8)) & 1;
#elif defined(SYS_BEOS)
system_info info;
get_system_info( &info );
cpu_count = info.cpu_count;
#elif defined(SYS_DARWIN) || defined(SYS_FREEBSD) || defined(SYS_OPENBSD)
size_t length = sizeof( cpu_count );
#ifdef SYS_OPENBSD
int mib[2] = { CTL_HW, HW_NCPU };
if( sysctl(mib, 2, &cpu_count, &length, NULL, 0) )
#else
if( sysctlbyname("hw.ncpu", &cpu_count, &length, NULL, 0) )
#endif
{
cpu_count = 1;
}
#elif defined( SYS_SunOS )
{
processorid_t cpumax;
int i,j=0;
cpumax = sysconf(_SC_CPUID_MAX);
for(i = 0; i <= cpumax; i++ )
{
if(p_online(i, P_STATUS) != -1)
{
j++;
}
}
cpu_count=j;
}
#endif
cpu_count = MAX( 1, cpu_count );
cpu_count = MIN( cpu_count, 64 );
return cpu_count;
}
int hb_platform_init()
{
int result = 0;
#if defined(SYS_MINGW) && defined(PTW32_STATIC_LIB)
result = !pthread_win32_process_attach_np();
if (result)
{
hb_error("pthread_win32_process_attach_np() failed!");
return -1;
}
#endif
#if defined(_WIN32) || defined(__MINGW32__)
/*
* win32 _IOLBF (line-buffering) is the same as _IOFBF (full-buffering).
* force it to unbuffered otherwise informative output is not easily parsed.
*/
result = setvbuf(stdout, NULL, _IONBF, 0);
if (result)
{
hb_error("setvbuf(stdout, NULL, _IONBF, 0) failed!");
return -1;
}
result = setvbuf(stderr, NULL, _IONBF, 0);
if (result)
{
hb_error("setvbuf(stderr, NULL, _IONBF, 0) failed!");
return -1;
}
#endif
init_cpu_info();
return result;
}
/************************************************************************
* Get a temporary directory for HB
***********************************************************************/
void hb_get_temporary_directory( char path[512] )
{
char base[512];
char *p;
/* Create the base */
#if defined( SYS_CYGWIN ) || defined( SYS_MINGW )
int i_size = GetTempPath( 512, base );
if( i_size <= 0 || i_size >= 512 )
{
if( getcwd( base, 512 ) == NULL )
strcpy( base, "c:" ); /* Bad fallback but ... */
}
/* c:/path/ works like a charm under cygwin(win32?) so use it */
while( ( p = strchr( base, '\\' ) ) )
*p = '/';
#else
if( (p = getenv( "TMPDIR" ) ) != NULL ||
(p = getenv( "TEMP" ) ) != NULL )
strcpy( base, p );
else
strcpy( base, "/tmp" );
#endif
/* I prefer to remove evntual last '/' (for cygwin) */
if( base[strlen(base)-1] == '/' )
base[strlen(base)-1] = '\0';
snprintf(path, 512, "%s/hb.%d", base, (int)getpid());
}
/************************************************************************
* Get a tempory filename for HB
***********************************************************************/
void hb_get_tempory_filename( hb_handle_t * h, char name[1024],
char *fmt, ... )
{
va_list args;
hb_get_temporary_directory( name );
strcat( name, "/" );
va_start( args, fmt );
vsnprintf( &name[strlen(name)], 1024 - strlen(name), fmt, args );
va_end( args );
}
/************************************************************************
* hb_stat
************************************************************************
* Wrapper to the real stat, needed to handle utf8 filenames on
* windows.
***********************************************************************/
int hb_stat(const char *path, hb_stat_t *sb)
{
#ifdef SYS_MINGW
wchar_t path_utf16[MAX_PATH];
if (!MultiByteToWideChar(CP_UTF8, 0, path, -1, path_utf16, MAX_PATH))
return -1;
return _wstat64( path_utf16, sb );
#else
return stat(path, sb);
#endif
}
/************************************************************************
* hb_fopen
************************************************************************
* Wrapper to the real fopen, needed to handle utf8 filenames on
* windows.
***********************************************************************/
FILE * hb_fopen(const char *path, const char *mode)
{
#ifdef SYS_MINGW
FILE *f;
wchar_t path_utf16[MAX_PATH];
wchar_t mode_utf16[16];
if (!MultiByteToWideChar(CP_UTF8, 0, path, -1, path_utf16, MAX_PATH))
return NULL;
if (!MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_utf16, 16))
return NULL;
errno_t ret = _wfopen_s(&f, path_utf16, mode_utf16);
if (ret)
return NULL;
return f;
#else
return fopen(path, mode);
#endif
}
HB_DIR* hb_opendir(char *path)
{
#ifdef SYS_MINGW
HB_DIR *dir;
wchar_t path_utf16[MAX_PATH];
if (!MultiByteToWideChar(CP_UTF8, 0, path, -1, path_utf16, MAX_PATH))
return NULL;
dir = malloc(sizeof(HB_DIR));
if (dir == NULL)
return NULL;
dir->wdir = _wopendir(path_utf16);
if (dir->wdir == NULL)
{
free(dir);
return NULL;
}
return dir;
#else
return opendir(path);
#endif
}
int hb_closedir(HB_DIR *dir)
{
#ifdef SYS_MINGW
int ret;
ret = _wclosedir(dir->wdir);
free(dir);
return ret;
#else
return closedir(dir);
#endif
}
struct dirent * hb_readdir(HB_DIR *dir)
{
#ifdef SYS_MINGW
struct _wdirent *entry;
entry = _wreaddir(dir->wdir);
if (entry == NULL)
return NULL;
int len = WideCharToMultiByte(CP_UTF8, 0, entry->d_name, -1,
dir->entry.d_name, sizeof(dir->entry.d_name),
NULL, NULL );
dir->entry.d_ino = entry->d_ino;
dir->entry.d_reclen = entry->d_reclen;
dir->entry.d_namlen = len - 1;
return &dir->entry;
#else
return readdir(dir);
#endif
}
/************************************************************************
* hb_mkdir
************************************************************************
* Wrapper to the real mkdir, needed only because it doesn't take a
* second argument on Win32. Grrr.
***********************************************************************/
int hb_mkdir(char * path)
{
#ifdef SYS_MINGW
wchar_t path_utf16[MAX_PATH];
if (!MultiByteToWideChar(CP_UTF8, 0, path, -1, path_utf16, MAX_PATH))
return -1;
return _wmkdir(path_utf16);
#else
return mkdir(path, 0755);
#endif
}
/************************************************************************
* Portable thread implementation
***********************************************************************/
struct hb_thread_s
{
char * name;
int priority;
thread_func_t * function;
void * arg;
hb_lock_t * lock;
int exited;
#if defined( SYS_BEOS )
thread_id thread;
#elif USE_PTHREAD
pthread_t thread;
//#elif defined( SYS_CYGWIN )
// HANDLE thread;
#endif
};
/* Get a unique identifier to thread and represent as 64-bit unsigned.
* If unsupported, the value 0 is be returned.
* Caller should use result only for display/log purposes.
*/
static uint64_t hb_thread_to_integer( const hb_thread_t* t )
{
#if defined( USE_PTHREAD )
#if defined( SYS_CYGWIN )
return (uint64_t)t->thread;
#elif defined( _WIN32 ) || defined( __MINGW32__ )
return (uint64_t)(ptrdiff_t)t->thread.p;
#elif defined( SYS_DARWIN )
return (unsigned long)t->thread;
#else
return (uint64_t)t->thread;
#endif
#else
return 0;
#endif
}
/************************************************************************
* hb_thread_func()
************************************************************************
* We use it as the root routine for any thread, for two reasons:
* + To set the thread priority on OS X (pthread_setschedparam() could
* be called from hb_thread_init(), but it's nicer to do it as we
* are sure it is done before the real routine starts)
* + Get informed when the thread exits, so we know whether
* hb_thread_close() will block or not.
***********************************************************************/
static void attribute_align_thread hb_thread_func( void * _t )
{
hb_thread_t * t = (hb_thread_t *) _t;
#if defined( SYS_DARWIN ) || defined( SYS_FREEBSD )
/* Set the thread priority */
struct sched_param param;
memset( ¶m, 0, sizeof( struct sched_param ) );
param.sched_priority = t->priority;
pthread_setschedparam( pthread_self(), SCHED_OTHER, ¶m );
#endif
#if defined( SYS_BEOS )
signal( SIGINT, SIG_IGN );
#endif
/* Start the actual routine */
t->function( t->arg );
/* Inform that the thread can be joined now */
hb_deep_log( 2, "thread %"PRIx64" exited (\"%s\")", hb_thread_to_integer( t ), t->name );
hb_lock( t->lock );
t->exited = 1;
hb_unlock( t->lock );
}
/************************************************************************
* hb_thread_init()
************************************************************************
* name: user-friendly name
* function: the thread routine
* arg: argument of the routine
* priority: HB_LOW_PRIORITY or HB_NORMAL_PRIORITY
***********************************************************************/
hb_thread_t * hb_thread_init( const char * name, void (* function)(void *),
void * arg, int priority )
{
hb_thread_t * t = calloc( sizeof( hb_thread_t ), 1 );
t->name = strdup( name );
t->function = function;
t->arg = arg;
t->priority = priority;
t->lock = hb_lock_init();
/* Create and start the thread */
#if defined( SYS_BEOS )
t->thread = spawn_thread( (thread_func) hb_thread_func,
name, priority, t );
resume_thread( t->thread );
#elif USE_PTHREAD
pthread_create( &t->thread, NULL,
(void * (*)( void * )) hb_thread_func, t );
//#elif defined( SYS_CYGWIN )
// t->thread = CreateThread( NULL, 0,
// (LPTHREAD_START_ROUTINE) hb_thread_func, t, 0, NULL );
//
// /* Maybe use THREAD_PRIORITY_LOWEST instead */
// if( priority == HB_LOW_PRIORITY )
// SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL );
#endif
hb_deep_log( 2, "thread %"PRIx64" started (\"%s\")", hb_thread_to_integer( t ), t->name );
return t;
}
/************************************************************************
* hb_thread_close()
************************************************************************
* Joins the thread and frees memory.
***********************************************************************/
void hb_thread_close( hb_thread_t ** _t )
{
hb_thread_t * t = *_t;
/* Join the thread */
#if defined( SYS_BEOS )
long exit_value;
wait_for_thread( t->thread, &exit_value );
#elif USE_PTHREAD
pthread_join( t->thread, NULL );
//#elif defined( SYS_CYGWIN )
// WaitForSingleObject( t->thread, INFINITE );
#endif
hb_deep_log( 2, "thread %"PRIx64" joined (\"%s\")", hb_thread_to_integer( t ), t->name );
hb_lock_close( &t->lock );
free( t->name );
free( t );
*_t = NULL;
}
/************************************************************************
* hb_thread_has_exited()
************************************************************************
* Returns 1 if the thread can be joined right away, 0 otherwise.
***********************************************************************/
int hb_thread_has_exited( hb_thread_t * t )
{
int exited;
hb_lock( t->lock );
exited = t->exited;
hb_unlock( t->lock );
return exited;
}
/************************************************************************
* Portable mutex implementation
***********************************************************************/
struct hb_lock_s
{
#if defined( SYS_BEOS )
sem_id sem;
#elif USE_PTHREAD
pthread_mutex_t mutex;
//#elif defined( SYS_CYGWIN )
// HANDLE mutex;
#endif
};
/************************************************************************
* hb_lock_init()
* hb_lock_close()
* hb_lock()
* hb_unlock()
************************************************************************
* Basic wrappers to OS-specific semaphore or mutex functions.
***********************************************************************/
hb_lock_t * hb_lock_init()
{
hb_lock_t * l = calloc( sizeof( hb_lock_t ), 1 );
#if defined( SYS_BEOS )
l->sem = create_sem( 1, "sem" );
#elif USE_PTHREAD
pthread_mutexattr_t mta;
pthread_mutexattr_init(&mta);
#if defined( SYS_CYGWIN ) || defined( SYS_FREEBSD )
pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_NORMAL);
#endif
pthread_mutex_init( &l->mutex, &mta );
//#elif defined( SYS_CYGWIN )
// l->mutex = CreateMutex( 0, FALSE, 0 );
#endif
return l;
}
void hb_lock_close( hb_lock_t ** _l )
{
hb_lock_t * l = *_l;
#if defined( SYS_BEOS )
delete_sem( l->sem );
#elif USE_PTHREAD
pthread_mutex_destroy( &l->mutex );
//#elif defined( SYS_CYGWIN )
// CloseHandle( l->mutex );
#endif
free( l );
*_l = NULL;
}
void hb_lock( hb_lock_t * l )
{
#if defined( SYS_BEOS )
acquire_sem( l->sem );
#elif USE_PTHREAD
pthread_mutex_lock( &l->mutex );
//#elif defined( SYS_CYGWIN )
// WaitForSingleObject( l->mutex, INFINITE );
#endif
}
void hb_unlock( hb_lock_t * l )
{
#if defined( SYS_BEOS )
release_sem( l->sem );
#elif USE_PTHREAD
pthread_mutex_unlock( &l->mutex );
//#elif defined( SYS_CYGWIN )
// ReleaseMutex( l->mutex );
#endif
}
/************************************************************************
* Portable condition variable implementation
***********************************************************************/
struct hb_cond_s
{
#if defined( SYS_BEOS )
int thread;
#elif USE_PTHREAD
pthread_cond_t cond;
//#elif defined( SYS_CYGWIN )
// HANDLE event;
#endif
};
/************************************************************************
* hb_cond_init()
* hb_cond_close()
* hb_cond_wait()
* hb_cond_signal()
************************************************************************
* Win9x is not supported by this implementation (SignalObjectAndWait()
* only available on Windows 2000/XP).
***********************************************************************/
hb_cond_t * hb_cond_init()
{
hb_cond_t * c = calloc( sizeof( hb_cond_t ), 1 );
if( c == NULL )
return NULL;
#if defined( SYS_BEOS )
c->thread = -1;
#elif USE_PTHREAD
pthread_cond_init( &c->cond, NULL );
//#elif defined( SYS_CYGWIN )
// c->event = CreateEvent( NULL, FALSE, FALSE, NULL );
#endif
return c;
}
void hb_cond_close( hb_cond_t ** _c )
{
hb_cond_t * c = *_c;
#if defined( SYS_BEOS )
#elif USE_PTHREAD
pthread_cond_destroy( &c->cond );
//#elif defined( SYS_CYGWIN )
// CloseHandle( c->event );
#endif
free( c );
*_c = NULL;
}
void hb_cond_wait( hb_cond_t * c, hb_lock_t * lock )
{
#if defined( SYS_BEOS )
c->thread = find_thread( NULL );
release_sem( lock->sem );
suspend_thread( c->thread );
acquire_sem( lock->sem );
c->thread = -1;
#elif USE_PTHREAD
pthread_cond_wait( &c->cond, &lock->mutex );
//#elif defined( SYS_CYGWIN )
// SignalObjectAndWait( lock->mutex, c->event, INFINITE, FALSE );
// WaitForSingleObject( lock->mutex, INFINITE );
#endif
}
void hb_clock_gettime( struct timespec *tp )
{
struct timeval tv;
gettimeofday( &tv, NULL );
tp->tv_sec = tv.tv_sec;
tp->tv_nsec = tv.tv_usec * 1000;
}
void hb_cond_timedwait( hb_cond_t * c, hb_lock_t * lock, int msec )
{
#if defined( SYS_BEOS )
c->thread = find_thread( NULL );
release_sem( lock->sem );
suspend_thread( c->thread );
acquire_sem( lock->sem );
c->thread = -1;
#elif USE_PTHREAD
struct timespec ts;
hb_clock_gettime(&ts);
ts.tv_nsec += (msec % 1000) * 1000000;
ts.tv_sec += msec / 1000 + (ts.tv_nsec / 1000000000);
ts.tv_nsec %= 1000000000;
pthread_cond_timedwait( &c->cond, &lock->mutex, &ts );
#endif
}
void hb_cond_signal( hb_cond_t * c )
{
#if defined( SYS_BEOS )
while( c->thread != -1 )
{
thread_info info;
get_thread_info( c->thread, &info );
if( info.state == B_THREAD_SUSPENDED )
{
resume_thread( c->thread );
break;
}
/* Looks like we have been called between hb_cond_wait's
release_sem() and suspend_thread() lines. Wait until the
thread is actually suspended before we resume it */
snooze( 5000 );
}
#elif USE_PTHREAD
pthread_cond_signal( &c->cond );
//#elif defined( SYS_CYGWIN )
// PulseEvent( c->event );
#endif
}
void hb_cond_broadcast( hb_cond_t * c )
{
#if USE_PTHREAD
pthread_cond_broadcast( &c->cond );
#endif
}
/************************************************************************
* Network
***********************************************************************/
struct hb_net_s
{
int socket;
};
hb_net_t * hb_net_open( char * address, int port )
{
hb_net_t * n = calloc( sizeof( hb_net_t ), 1 );
struct sockaddr_in sock;
struct hostent * host;
#ifdef SYS_MINGW
WSADATA wsaData;
int iResult, winsock_init = 0;
// Initialize Winsock
if (!winsock_init)
{
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0)
{
hb_log("WSAStartup failed: %d", iResult);
free(n);
return NULL;
}
winsock_init = 1;
}
#endif
/* TODO: find out why this doesn't work on Win32 */
if( !( host = gethostbyname( address ) ) )
{
hb_log( "gethostbyname failed (%s)", address );
free( n );
return NULL;
}
memset( &sock, 0, sizeof( struct sockaddr_in ) );
sock.sin_family = host->h_addrtype;
sock.sin_port = htons( port );
memcpy( &sock.sin_addr, host->h_addr, host->h_length );
if( ( n->socket = socket( host->h_addrtype, SOCK_STREAM, 0 ) ) < 0 )
{
hb_log( "socket failed" );
free( n );
return NULL;
}
if( connect( n->socket, (struct sockaddr *) &sock,
sizeof( struct sockaddr_in ) ) < 0 )
{
hb_log( "connect failed" );
free( n );
return NULL;
}
return n;
}
int hb_net_send( hb_net_t * n, char * buffer )
{
return send( n->socket, buffer, strlen( buffer ), 0 );
}
int hb_net_recv( hb_net_t * n, char * buffer, int size )
{
return recv( n->socket, buffer, size - 1, 0 );
}
void hb_net_close( hb_net_t ** _n )
{
hb_net_t * n = (hb_net_t *) *_n;
close( n->socket );
free( n );
*_n = NULL;
}
#ifdef SYS_MINGW
char *strtok_r(char *s, const char *delim, char **save_ptr)
{
char *token;
if (s == NULL) s = *save_ptr;
/* Scan leading delimiters. */
s += strspn(s, delim);
if (*s == '\0') return NULL;
/* Find the end of the token. */
token = s;
s = strpbrk(token, delim);
if (s == NULL)
/* This token finishes the string. */
*save_ptr = strchr(token, '\0');
else {
/* Terminate the token and make *SAVE_PTR point past it. */
*s = '\0';
*save_ptr = s + 1;
}
return token;
}
#endif
/************************************************************************
* OS Sleep Allow / Prevent
***********************************************************************/
#ifdef __APPLE__
// 128 chars limit for IOPMAssertionCreateWithName
static CFStringRef reasonForActivity =
CFSTR("HandBrake is currently scanning and/or encoding");
#endif
void* hb_system_sleep_opaque_init()
{
void *opaque = NULL;
#ifdef __APPLE__
opaque = calloc(sizeof(IOPMAssertionID), 1);
if (opaque == NULL)
{
hb_error("hb_system_sleep: failed to allocate opaque");
return NULL;
}
IOPMAssertionID *assertionID = (IOPMAssertionID*)opaque;
*assertionID = -1;
#endif
return opaque;
}
void hb_system_sleep_opaque_close(void **opaque)
{
if (*opaque != NULL)
{
hb_system_sleep_private_enable(*opaque);
}
#ifdef __APPLE__
if (*opaque != NULL)
{
IOPMAssertionID *assertionID = (IOPMAssertionID*)*opaque;
free(assertionID);
}
#endif
*opaque = NULL;
}
void hb_system_sleep_private_enable(void *opaque)
{
#ifdef __APPLE__
if (opaque == NULL)
{
hb_error("hb_system_sleep: opaque is NULL");
}
IOPMAssertionID *assertionID = (IOPMAssertionID*)opaque;
if (*assertionID == -1)
{
// nothing to do
return;
}
IOReturn success = IOPMAssertionRelease(*assertionID);
if (success == kIOReturnSuccess)
{
hb_deep_log(3,
"hb_system_sleep: assertion %d released, sleep allowed",
*assertionID);
*assertionID = -1;
}
else
{
hb_log("hb_system_sleep: failed to allow system sleep");
}
#endif
}
void hb_system_sleep_private_disable(void *opaque)
{
#ifdef __APPLE__
if (opaque == NULL)
{
hb_error("hb_system_sleep: opaque is NULL");
}
IOPMAssertionID *assertionID = (IOPMAssertionID*)opaque;
if (*assertionID != -1)
{
// nothing to do
return;
}
IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep,
kIOPMAssertionLevelOn,
reasonForActivity,
assertionID);
if (success == kIOReturnSuccess)
{
hb_deep_log(3,
"hb_system_sleep: assertion %d created, sleep prevented",
*assertionID);
}
else
{
hb_log("hb_system_sleep: failed to prevent system sleep");
}
#endif
}
|