helpers.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 2011 by authors.
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Library General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Library General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Library General Public
  15. * License along with this library; if not, write to the
  16. * Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. * Or go to http://www.gnu.org/copyleft/lgpl.html
  19. */
  20. #ifdef _WIN32
  21. #ifdef __MINGW32__
  22. #define _WIN32_IE 0x501
  23. #else
  24. #define _WIN32_IE 0x400
  25. #endif
  26. #endif
  27. #include "config.h"
  28. #include <stdlib.h>
  29. #include <time.h>
  30. #include <errno.h>
  31. #include <stdarg.h>
  32. #include <ctype.h>
  33. #ifdef HAVE_MALLOC_H
  34. #include <malloc.h>
  35. #endif
  36. #ifdef HAVE_DIRENT_H
  37. #include <dirent.h>
  38. #endif
  39. #ifdef __FreeBSD__
  40. #include <sys/types.h>
  41. #include <sys/sysctl.h>
  42. #endif
  43. #ifndef AL_NO_UID_DEFS
  44. #if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H)
  45. #define INITGUID
  46. #include <windows.h>
  47. #ifdef HAVE_GUIDDEF_H
  48. #include <guiddef.h>
  49. #else
  50. #include <initguid.h>
  51. #endif
  52. DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
  53. DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71);
  54. DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16);
  55. DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e);
  56. DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6);
  57. DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2);
  58. DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2);
  59. DEFINE_GUID(IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4,0xde, 0x18,0x5c,0x39,0x5c,0xd3,0x17);
  60. #ifdef HAVE_MMDEVAPI
  61. #include <wtypes.h>
  62. #include <devpropdef.h>
  63. #include <propkeydef.h>
  64. DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
  65. DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
  66. DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
  67. #endif
  68. #endif
  69. #endif /* AL_NO_UID_DEFS */
  70. #ifdef HAVE_DLFCN_H
  71. #include <dlfcn.h>
  72. #endif
  73. #ifdef HAVE_INTRIN_H
  74. #include <intrin.h>
  75. #endif
  76. #ifdef HAVE_CPUID_H
  77. #include <cpuid.h>
  78. #endif
  79. #ifdef HAVE_SYS_SYSCONF_H
  80. #include <sys/sysconf.h>
  81. #endif
  82. #ifdef HAVE_FLOAT_H
  83. #include <float.h>
  84. #endif
  85. #ifdef HAVE_IEEEFP_H
  86. #include <ieeefp.h>
  87. #endif
  88. #ifndef _WIN32
  89. #include <sys/types.h>
  90. #include <sys/stat.h>
  91. #include <sys/mman.h>
  92. #include <fcntl.h>
  93. #include <unistd.h>
  94. #elif defined(_WIN32_IE)
  95. #include <shlobj.h>
  96. #endif
  97. #include "alMain.h"
  98. #include "alu.h"
  99. #include "atomic.h"
  100. #include "uintmap.h"
  101. #include "vector.h"
  102. #include "alstring.h"
  103. #include "compat.h"
  104. #include "threads.h"
  105. extern inline ALuint NextPowerOf2(ALuint value);
  106. extern inline size_t RoundUp(size_t value, size_t r);
  107. extern inline ALuint64 ScaleRound(ALuint64 val, ALuint64 new_scale, ALuint64 old_scale);
  108. extern inline ALuint64 ScaleFloor(ALuint64 val, ALuint64 new_scale, ALuint64 old_scale);
  109. extern inline ALuint64 ScaleCeil(ALuint64 val, ALuint64 new_scale, ALuint64 old_scale);
  110. extern inline ALint fastf2i(ALfloat f);
  111. ALuint CPUCapFlags = 0;
  112. void FillCPUCaps(ALuint capfilter)
  113. {
  114. ALuint caps = 0;
  115. /* FIXME: We really should get this for all available CPUs in case different
  116. * CPUs have different caps (is that possible on one machine?). */
  117. #if defined(HAVE_GCC_GET_CPUID) && (defined(__i386__) || defined(__x86_64__) || \
  118. defined(_M_IX86) || defined(_M_X64))
  119. union {
  120. unsigned int regs[4];
  121. char str[sizeof(unsigned int[4])];
  122. } cpuinf[3];
  123. if(!__get_cpuid(0, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
  124. ERR("Failed to get CPUID\n");
  125. else
  126. {
  127. unsigned int maxfunc = cpuinf[0].regs[0];
  128. unsigned int maxextfunc = 0;
  129. if(__get_cpuid(0x80000000, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
  130. maxextfunc = cpuinf[0].regs[0];
  131. TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
  132. TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
  133. if(maxextfunc >= 0x80000004 &&
  134. __get_cpuid(0x80000002, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]) &&
  135. __get_cpuid(0x80000003, &cpuinf[1].regs[0], &cpuinf[1].regs[1], &cpuinf[1].regs[2], &cpuinf[1].regs[3]) &&
  136. __get_cpuid(0x80000004, &cpuinf[2].regs[0], &cpuinf[2].regs[1], &cpuinf[2].regs[2], &cpuinf[2].regs[3]))
  137. TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
  138. if(maxfunc >= 1 &&
  139. __get_cpuid(1, &cpuinf[0].regs[0], &cpuinf[0].regs[1], &cpuinf[0].regs[2], &cpuinf[0].regs[3]))
  140. {
  141. if((cpuinf[0].regs[3]&(1<<25)))
  142. {
  143. caps |= CPU_CAP_SSE;
  144. if((cpuinf[0].regs[3]&(1<<26)))
  145. {
  146. caps |= CPU_CAP_SSE2;
  147. if((cpuinf[0].regs[2]&(1<<0)))
  148. {
  149. caps |= CPU_CAP_SSE3;
  150. if((cpuinf[0].regs[2]&(1<<19)))
  151. caps |= CPU_CAP_SSE4_1;
  152. }
  153. }
  154. }
  155. }
  156. }
  157. #elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
  158. defined(_M_IX86) || defined(_M_X64))
  159. union {
  160. int regs[4];
  161. char str[sizeof(int[4])];
  162. } cpuinf[3];
  163. (__cpuid)(cpuinf[0].regs, 0);
  164. if(cpuinf[0].regs[0] == 0)
  165. ERR("Failed to get CPUID\n");
  166. else
  167. {
  168. unsigned int maxfunc = cpuinf[0].regs[0];
  169. unsigned int maxextfunc;
  170. (__cpuid)(cpuinf[0].regs, 0x80000000);
  171. maxextfunc = cpuinf[0].regs[0];
  172. TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
  173. TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
  174. if(maxextfunc >= 0x80000004)
  175. {
  176. (__cpuid)(cpuinf[0].regs, 0x80000002);
  177. (__cpuid)(cpuinf[1].regs, 0x80000003);
  178. (__cpuid)(cpuinf[2].regs, 0x80000004);
  179. TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
  180. }
  181. if(maxfunc >= 1)
  182. {
  183. (__cpuid)(cpuinf[0].regs, 1);
  184. if((cpuinf[0].regs[3]&(1<<25)))
  185. {
  186. caps |= CPU_CAP_SSE;
  187. if((cpuinf[0].regs[3]&(1<<26)))
  188. {
  189. caps |= CPU_CAP_SSE2;
  190. if((cpuinf[0].regs[2]&(1<<0)))
  191. {
  192. caps |= CPU_CAP_SSE3;
  193. if((cpuinf[0].regs[2]&(1<<19)))
  194. caps |= CPU_CAP_SSE4_1;
  195. }
  196. }
  197. }
  198. }
  199. }
  200. #else
  201. /* Assume support for whatever's supported if we can't check for it */
  202. #if defined(HAVE_SSE4_1)
  203. #warning "Assuming SSE 4.1 run-time support!"
  204. caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
  205. #elif defined(HAVE_SSE3)
  206. #warning "Assuming SSE 3 run-time support!"
  207. caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
  208. #elif defined(HAVE_SSE2)
  209. #warning "Assuming SSE 2 run-time support!"
  210. caps |= CPU_CAP_SSE | CPU_CAP_SSE2;
  211. #elif defined(HAVE_SSE)
  212. #warning "Assuming SSE run-time support!"
  213. caps |= CPU_CAP_SSE;
  214. #endif
  215. #endif
  216. #ifdef HAVE_NEON
  217. FILE *file = fopen("/proc/cpuinfo", "rt");
  218. if(!file)
  219. ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
  220. else
  221. {
  222. char buf[256];
  223. while(fgets(buf, sizeof(buf), file) != NULL)
  224. {
  225. size_t len;
  226. char *str;
  227. if(strncmp(buf, "Features\t:", 10) != 0)
  228. continue;
  229. len = strlen(buf);
  230. while(len > 0 && isspace(buf[len-1]))
  231. buf[--len] = 0;
  232. TRACE("Got features string:%s\n", buf+10);
  233. str = buf;
  234. while((str=strstr(str, "neon")) != NULL)
  235. {
  236. if(isspace(*(str-1)) && (str[4] == 0 || isspace(str[4])))
  237. {
  238. caps |= CPU_CAP_NEON;
  239. break;
  240. }
  241. str++;
  242. }
  243. break;
  244. }
  245. fclose(file);
  246. file = NULL;
  247. }
  248. #endif
  249. TRACE("Extensions:%s%s%s%s%s%s\n",
  250. ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
  251. ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
  252. ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
  253. ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
  254. ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
  255. ((!capfilter) ? " -none-" : "")
  256. );
  257. CPUCapFlags = caps & capfilter;
  258. }
  259. void SetMixerFPUMode(FPUCtl *ctl)
  260. {
  261. #ifdef HAVE_FENV_H
  262. fegetenv(STATIC_CAST(fenv_t, ctl));
  263. #ifdef _WIN32
  264. /* HACK: A nasty bug in MinGW-W64 causes fegetenv and fesetenv to not save
  265. * and restore the FPU rounding mode, so we have to do it manually. Don't
  266. * know if this also applies to MSVC.
  267. */
  268. ctl->round_mode = fegetround();
  269. #endif
  270. #if defined(__GNUC__) && defined(HAVE_SSE)
  271. /* FIXME: Some fegetenv implementations can get the SSE environment too?
  272. * How to tell when it does? */
  273. if((CPUCapFlags&CPU_CAP_SSE))
  274. __asm__ __volatile__("stmxcsr %0" : "=m" (*&ctl->sse_state));
  275. #endif
  276. #ifdef FE_TOWARDZERO
  277. fesetround(FE_TOWARDZERO);
  278. #endif
  279. #if defined(__GNUC__) && defined(HAVE_SSE)
  280. if((CPUCapFlags&CPU_CAP_SSE))
  281. {
  282. int sseState = ctl->sse_state;
  283. sseState |= 0x6000; /* set round-to-zero */
  284. sseState |= 0x8000; /* set flush-to-zero */
  285. if((CPUCapFlags&CPU_CAP_SSE2))
  286. sseState |= 0x0040; /* set denormals-are-zero */
  287. __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
  288. }
  289. #endif
  290. #elif defined(HAVE___CONTROL87_2)
  291. int mode;
  292. __control87_2(0, 0, &ctl->state, NULL);
  293. __control87_2(_RC_CHOP, _MCW_RC, &mode, NULL);
  294. #ifdef HAVE_SSE
  295. if((CPUCapFlags&CPU_CAP_SSE))
  296. {
  297. __control87_2(0, 0, NULL, &ctl->sse_state);
  298. __control87_2(_RC_CHOP|_DN_FLUSH, _MCW_RC|_MCW_DN, NULL, &mode);
  299. }
  300. #endif
  301. #elif defined(HAVE__CONTROLFP)
  302. ctl->state = _controlfp(0, 0);
  303. (void)_controlfp(_RC_CHOP, _MCW_RC);
  304. #endif
  305. }
  306. void RestoreFPUMode(const FPUCtl *ctl)
  307. {
  308. #ifdef HAVE_FENV_H
  309. fesetenv(STATIC_CAST(fenv_t, ctl));
  310. #ifdef _WIN32
  311. fesetround(ctl->round_mode);
  312. #endif
  313. #if defined(__GNUC__) && defined(HAVE_SSE)
  314. if((CPUCapFlags&CPU_CAP_SSE))
  315. __asm__ __volatile__("ldmxcsr %0" : : "m" (*&ctl->sse_state));
  316. #endif
  317. #elif defined(HAVE___CONTROL87_2)
  318. int mode;
  319. __control87_2(ctl->state, _MCW_RC, &mode, NULL);
  320. #ifdef HAVE_SSE
  321. if((CPUCapFlags&CPU_CAP_SSE))
  322. __control87_2(ctl->sse_state, _MCW_RC|_MCW_DN, NULL, &mode);
  323. #endif
  324. #elif defined(HAVE__CONTROLFP)
  325. _controlfp(ctl->state, _MCW_RC);
  326. #endif
  327. }
  328. static int StringSortCompare(const void *str1, const void *str2)
  329. {
  330. return alstr_cmp(*(const_al_string*)str1, *(const_al_string*)str2);
  331. }
  332. #ifdef _WIN32
  333. static WCHAR *strrchrW(WCHAR *str, WCHAR ch)
  334. {
  335. WCHAR *ret = NULL;
  336. while(*str)
  337. {
  338. if(*str == ch)
  339. ret = str;
  340. ++str;
  341. }
  342. return ret;
  343. }
  344. al_string GetProcPath(void)
  345. {
  346. al_string ret = AL_STRING_INIT_STATIC();
  347. WCHAR *pathname, *sep;
  348. DWORD pathlen;
  349. DWORD len;
  350. pathlen = 256;
  351. pathname = malloc(pathlen * sizeof(pathname[0]));
  352. while(pathlen > 0 && (len=GetModuleFileNameW(NULL, pathname, pathlen)) == pathlen)
  353. {
  354. free(pathname);
  355. pathlen <<= 1;
  356. pathname = malloc(pathlen * sizeof(pathname[0]));
  357. }
  358. if(len == 0)
  359. {
  360. free(pathname);
  361. ERR("Failed to get process name: error %lu\n", GetLastError());
  362. return ret;
  363. }
  364. pathname[len] = 0;
  365. if((sep = strrchrW(pathname, '\\')))
  366. {
  367. WCHAR *sep2 = strrchrW(pathname, '/');
  368. if(sep2) *sep2 = 0;
  369. else *sep = 0;
  370. }
  371. else if((sep = strrchrW(pathname, '/')))
  372. *sep = 0;
  373. alstr_copy_wcstr(&ret, pathname);
  374. free(pathname);
  375. TRACE("Got: %s\n", alstr_get_cstr(ret));
  376. return ret;
  377. }
  378. static WCHAR *FromUTF8(const char *str)
  379. {
  380. WCHAR *out = NULL;
  381. int len;
  382. if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
  383. {
  384. out = calloc(sizeof(WCHAR), len);
  385. MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
  386. }
  387. return out;
  388. }
  389. void *LoadLib(const char *name)
  390. {
  391. HANDLE hdl = NULL;
  392. WCHAR *wname;
  393. wname = FromUTF8(name);
  394. if(!wname)
  395. ERR("Failed to convert UTF-8 filename: \"%s\"\n", name);
  396. else
  397. {
  398. hdl = LoadLibraryW(wname);
  399. free(wname);
  400. }
  401. return hdl;
  402. }
  403. void CloseLib(void *handle)
  404. { FreeLibrary((HANDLE)handle); }
  405. void *GetSymbol(void *handle, const char *name)
  406. {
  407. void *ret;
  408. ret = (void*)GetProcAddress((HANDLE)handle, name);
  409. if(ret == NULL)
  410. ERR("Failed to load %s\n", name);
  411. return ret;
  412. }
  413. WCHAR *strdupW(const WCHAR *str)
  414. {
  415. const WCHAR *n;
  416. WCHAR *ret;
  417. size_t len;
  418. n = str;
  419. while(*n) n++;
  420. len = n - str;
  421. ret = calloc(sizeof(WCHAR), len+1);
  422. if(ret != NULL)
  423. memcpy(ret, str, sizeof(WCHAR)*len);
  424. return ret;
  425. }
  426. FILE *al_fopen(const char *fname, const char *mode)
  427. {
  428. WCHAR *wname=NULL, *wmode=NULL;
  429. FILE *file = NULL;
  430. wname = FromUTF8(fname);
  431. wmode = FromUTF8(mode);
  432. if(!wname)
  433. ERR("Failed to convert UTF-8 filename: \"%s\"\n", fname);
  434. else if(!wmode)
  435. ERR("Failed to convert UTF-8 mode: \"%s\"\n", mode);
  436. else
  437. file = _wfopen(wname, wmode);
  438. free(wname);
  439. free(wmode);
  440. return file;
  441. }
  442. void al_print(const char *type, const char *func, const char *fmt, ...)
  443. {
  444. char str[1024];
  445. WCHAR *wstr;
  446. va_list ap;
  447. va_start(ap, fmt);
  448. vsnprintf(str, sizeof(str), fmt, ap);
  449. va_end(ap);
  450. str[sizeof(str)-1] = 0;
  451. wstr = FromUTF8(str);
  452. if(!wstr)
  453. fprintf(LogFile, "AL lib: %s %s: <UTF-8 error> %s", type, func, str);
  454. else
  455. {
  456. fprintf(LogFile, "AL lib: %s %s: %ls", type, func, wstr);
  457. free(wstr);
  458. wstr = NULL;
  459. }
  460. fflush(LogFile);
  461. }
  462. static inline int is_slash(int c)
  463. { return (c == '\\' || c == '/'); }
  464. static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
  465. {
  466. al_string pathstr = AL_STRING_INIT_STATIC();
  467. WIN32_FIND_DATAW fdata;
  468. WCHAR *wpath;
  469. HANDLE hdl;
  470. alstr_copy_cstr(&pathstr, path);
  471. alstr_append_cstr(&pathstr, "\\*");
  472. alstr_append_cstr(&pathstr, ext);
  473. TRACE("Searching %s\n", alstr_get_cstr(pathstr));
  474. wpath = FromUTF8(alstr_get_cstr(pathstr));
  475. hdl = FindFirstFileW(wpath, &fdata);
  476. if(hdl != INVALID_HANDLE_VALUE)
  477. {
  478. size_t base = VECTOR_SIZE(*results);
  479. do {
  480. al_string str = AL_STRING_INIT_STATIC();
  481. alstr_copy_cstr(&str, path);
  482. alstr_append_char(&str, '\\');
  483. alstr_append_wcstr(&str, fdata.cFileName);
  484. TRACE("Got result %s\n", alstr_get_cstr(str));
  485. VECTOR_PUSH_BACK(*results, str);
  486. } while(FindNextFileW(hdl, &fdata));
  487. FindClose(hdl);
  488. if(VECTOR_SIZE(*results) > base)
  489. qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
  490. sizeof(VECTOR_FRONT(*results)), StringSortCompare);
  491. }
  492. free(wpath);
  493. alstr_reset(&pathstr);
  494. }
  495. vector_al_string SearchDataFiles(const char *ext, const char *subdir)
  496. {
  497. static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
  498. static RefCount search_lock;
  499. vector_al_string results = VECTOR_INIT_STATIC();
  500. size_t i;
  501. while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
  502. althrd_yield();
  503. /* If the path is absolute, use it directly. */
  504. if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
  505. {
  506. al_string path = AL_STRING_INIT_STATIC();
  507. alstr_copy_cstr(&path, subdir);
  508. #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
  509. VECTOR_FOR_EACH(char, path, FIX_SLASH);
  510. #undef FIX_SLASH
  511. DirectorySearch(alstr_get_cstr(path), ext, &results);
  512. alstr_reset(&path);
  513. }
  514. else if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
  515. DirectorySearch(subdir, ext, &results);
  516. else
  517. {
  518. al_string path = AL_STRING_INIT_STATIC();
  519. WCHAR *cwdbuf;
  520. /* Search the app-local directory. */
  521. if((cwdbuf=_wgetenv(L"ALSOFT_LOCAL_PATH")) && *cwdbuf != '\0')
  522. {
  523. alstr_copy_wcstr(&path, cwdbuf);
  524. if(is_slash(VECTOR_BACK(path)))
  525. {
  526. VECTOR_POP_BACK(path);
  527. *VECTOR_END(path) = 0;
  528. }
  529. }
  530. else if(!(cwdbuf=_wgetcwd(NULL, 0)))
  531. alstr_copy_cstr(&path, ".");
  532. else
  533. {
  534. alstr_copy_wcstr(&path, cwdbuf);
  535. if(is_slash(VECTOR_BACK(path)))
  536. {
  537. VECTOR_POP_BACK(path);
  538. *VECTOR_END(path) = 0;
  539. }
  540. free(cwdbuf);
  541. }
  542. #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
  543. VECTOR_FOR_EACH(char, path, FIX_SLASH);
  544. #undef FIX_SLASH
  545. DirectorySearch(alstr_get_cstr(path), ext, &results);
  546. /* Search the local and global data dirs. */
  547. for(i = 0;i < COUNTOF(ids);i++)
  548. {
  549. WCHAR buffer[PATH_MAX];
  550. if(SHGetSpecialFolderPathW(NULL, buffer, ids[i], FALSE) != FALSE)
  551. {
  552. alstr_copy_wcstr(&path, buffer);
  553. if(!is_slash(VECTOR_BACK(path)))
  554. alstr_append_char(&path, '\\');
  555. alstr_append_cstr(&path, subdir);
  556. #define FIX_SLASH(i) do { if(*(i) == '/') *(i) = '\\'; } while(0)
  557. VECTOR_FOR_EACH(char, path, FIX_SLASH);
  558. #undef FIX_SLASH
  559. DirectorySearch(alstr_get_cstr(path), ext, &results);
  560. }
  561. }
  562. alstr_reset(&path);
  563. }
  564. ATOMIC_STORE_SEQ(&search_lock, 0);
  565. return results;
  566. }
  567. struct FileMapping MapFileToMem(const char *fname)
  568. {
  569. struct FileMapping ret = { NULL, NULL, NULL, 0 };
  570. MEMORY_BASIC_INFORMATION meminfo;
  571. HANDLE file, fmap;
  572. WCHAR *wname;
  573. void *ptr;
  574. wname = FromUTF8(fname);
  575. file = CreateFileW(wname, GENERIC_READ, FILE_SHARE_READ, NULL,
  576. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  577. if(file == INVALID_HANDLE_VALUE)
  578. {
  579. ERR("Failed to open %s: %lu\n", fname, GetLastError());
  580. free(wname);
  581. return ret;
  582. }
  583. free(wname);
  584. wname = NULL;
  585. fmap = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL);
  586. if(!fmap)
  587. {
  588. ERR("Failed to create map for %s: %lu\n", fname, GetLastError());
  589. CloseHandle(file);
  590. return ret;
  591. }
  592. ptr = MapViewOfFile(fmap, FILE_MAP_READ, 0, 0, 0);
  593. if(!ptr)
  594. {
  595. ERR("Failed to map %s: %lu\n", fname, GetLastError());
  596. CloseHandle(fmap);
  597. CloseHandle(file);
  598. return ret;
  599. }
  600. if(VirtualQuery(ptr, &meminfo, sizeof(meminfo)) != sizeof(meminfo))
  601. {
  602. ERR("Failed to get map size for %s: %lu\n", fname, GetLastError());
  603. UnmapViewOfFile(ptr);
  604. CloseHandle(fmap);
  605. CloseHandle(file);
  606. return ret;
  607. }
  608. ret.file = file;
  609. ret.fmap = fmap;
  610. ret.ptr = ptr;
  611. ret.len = meminfo.RegionSize;
  612. return ret;
  613. }
  614. void UnmapFileMem(const struct FileMapping *mapping)
  615. {
  616. UnmapViewOfFile(mapping->ptr);
  617. CloseHandle(mapping->fmap);
  618. CloseHandle(mapping->file);
  619. }
  620. #else
  621. al_string GetProcPath(void)
  622. {
  623. al_string ret = AL_STRING_INIT_STATIC();
  624. char *pathname, *sep;
  625. size_t pathlen;
  626. #ifdef __FreeBSD__
  627. int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
  628. mib[3] = getpid();
  629. if (sysctl(mib, 4, NULL, &pathlen, NULL, 0) == -1) {
  630. WARN("Failed to sysctl kern.proc.pathname.%d: %s\n", mib[3], strerror(errno));
  631. return ret;
  632. }
  633. pathname = malloc(pathlen + 1);
  634. sysctl(mib, 4, (void*)pathname, &pathlen, NULL, 0);
  635. pathname[pathlen] = 0;
  636. #else
  637. const char *fname;
  638. ssize_t len;
  639. pathlen = 256;
  640. pathname = malloc(pathlen);
  641. fname = "/proc/self/exe";
  642. len = readlink(fname, pathname, pathlen);
  643. if(len == -1 && errno == ENOENT)
  644. {
  645. fname = "/proc/self/file";
  646. len = readlink(fname, pathname, pathlen);
  647. }
  648. while(len > 0 && (size_t)len == pathlen)
  649. {
  650. free(pathname);
  651. pathlen <<= 1;
  652. pathname = malloc(pathlen);
  653. len = readlink(fname, pathname, pathlen);
  654. }
  655. if(len <= 0)
  656. {
  657. free(pathname);
  658. WARN("Failed to readlink %s: %s\n", fname, strerror(errno));
  659. return ret;
  660. }
  661. pathname[len] = 0;
  662. #endif
  663. sep = strrchr(pathname, '/');
  664. if(sep)
  665. alstr_copy_range(&ret, pathname, sep);
  666. else
  667. alstr_copy_cstr(&ret, pathname);
  668. free(pathname);
  669. TRACE("Got: %s\n", alstr_get_cstr(ret));
  670. return ret;
  671. }
  672. #ifdef HAVE_DLFCN_H
  673. void *LoadLib(const char *name)
  674. {
  675. const char *err;
  676. void *handle;
  677. dlerror();
  678. handle = dlopen(name, RTLD_NOW);
  679. if((err=dlerror()) != NULL)
  680. handle = NULL;
  681. return handle;
  682. }
  683. void CloseLib(void *handle)
  684. { dlclose(handle); }
  685. void *GetSymbol(void *handle, const char *name)
  686. {
  687. const char *err;
  688. void *sym;
  689. dlerror();
  690. sym = dlsym(handle, name);
  691. if((err=dlerror()) != NULL)
  692. {
  693. WARN("Failed to load %s: %s\n", name, err);
  694. sym = NULL;
  695. }
  696. return sym;
  697. }
  698. #endif /* HAVE_DLFCN_H */
  699. void al_print(const char *type, const char *func, const char *fmt, ...)
  700. {
  701. va_list ap;
  702. va_start(ap, fmt);
  703. fprintf(LogFile, "AL lib: %s %s: ", type, func);
  704. vfprintf(LogFile, fmt, ap);
  705. va_end(ap);
  706. fflush(LogFile);
  707. }
  708. static void DirectorySearch(const char *path, const char *ext, vector_al_string *results)
  709. {
  710. size_t extlen = strlen(ext);
  711. DIR *dir;
  712. TRACE("Searching %s for *%s\n", path, ext);
  713. dir = opendir(path);
  714. if(dir != NULL)
  715. {
  716. size_t base = VECTOR_SIZE(*results);
  717. struct dirent *dirent;
  718. while((dirent=readdir(dir)) != NULL)
  719. {
  720. al_string str;
  721. size_t len;
  722. if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
  723. continue;
  724. len = strlen(dirent->d_name);
  725. if(!(len > extlen))
  726. continue;
  727. if(strcasecmp(dirent->d_name+len-extlen, ext) != 0)
  728. continue;
  729. AL_STRING_INIT(str);
  730. alstr_copy_cstr(&str, path);
  731. if(VECTOR_BACK(str) != '/')
  732. alstr_append_char(&str, '/');
  733. alstr_append_cstr(&str, dirent->d_name);
  734. TRACE("Got result %s\n", alstr_get_cstr(str));
  735. VECTOR_PUSH_BACK(*results, str);
  736. }
  737. closedir(dir);
  738. if(VECTOR_SIZE(*results) > base)
  739. qsort(VECTOR_BEGIN(*results)+base, VECTOR_SIZE(*results)-base,
  740. sizeof(VECTOR_FRONT(*results)), StringSortCompare);
  741. }
  742. }
  743. vector_al_string SearchDataFiles(const char *ext, const char *subdir)
  744. {
  745. static RefCount search_lock;
  746. vector_al_string results = VECTOR_INIT_STATIC();
  747. while(ATOMIC_EXCHANGE_SEQ(&search_lock, 1) == 1)
  748. althrd_yield();
  749. if(subdir[0] == '/')
  750. DirectorySearch(subdir, ext, &results);
  751. else
  752. {
  753. al_string path = AL_STRING_INIT_STATIC();
  754. const char *str, *next;
  755. char cwdbuf[PATH_MAX];
  756. /* Search the app-local directory. */
  757. if((str=getenv("ALSOFT_LOCAL_PATH")) && *str != '\0')
  758. DirectorySearch(str, ext, &results);
  759. else if(getcwd(cwdbuf, sizeof(cwdbuf)))
  760. DirectorySearch(cwdbuf, ext, &results);
  761. else
  762. DirectorySearch(".", ext, &results);
  763. // Search local data dir
  764. if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
  765. {
  766. alstr_copy_cstr(&path, str);
  767. if(VECTOR_BACK(path) != '/')
  768. alstr_append_char(&path, '/');
  769. alstr_append_cstr(&path, subdir);
  770. DirectorySearch(alstr_get_cstr(path), ext, &results);
  771. }
  772. else if((str=getenv("HOME")) != NULL && str[0] != '\0')
  773. {
  774. alstr_copy_cstr(&path, str);
  775. if(VECTOR_BACK(path) == '/')
  776. {
  777. VECTOR_POP_BACK(path);
  778. *VECTOR_END(path) = 0;
  779. }
  780. alstr_append_cstr(&path, "/.local/share/");
  781. alstr_append_cstr(&path, subdir);
  782. DirectorySearch(alstr_get_cstr(path), ext, &results);
  783. }
  784. // Search global data dirs
  785. if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
  786. str = "/usr/local/share/:/usr/share/";
  787. next = str;
  788. while((str=next) != NULL && str[0] != '\0')
  789. {
  790. next = strchr(str, ':');
  791. if(!next)
  792. alstr_copy_cstr(&path, str);
  793. else
  794. {
  795. alstr_copy_range(&path, str, next);
  796. ++next;
  797. }
  798. if(!alstr_empty(path))
  799. {
  800. if(VECTOR_BACK(path) != '/')
  801. alstr_append_char(&path, '/');
  802. alstr_append_cstr(&path, subdir);
  803. DirectorySearch(alstr_get_cstr(path), ext, &results);
  804. }
  805. }
  806. alstr_reset(&path);
  807. }
  808. ATOMIC_STORE_SEQ(&search_lock, 0);
  809. return results;
  810. }
  811. struct FileMapping MapFileToMem(const char *fname)
  812. {
  813. struct FileMapping ret = { -1, NULL, 0 };
  814. struct stat sbuf;
  815. void *ptr;
  816. int fd;
  817. fd = open(fname, O_RDONLY, 0);
  818. if(fd == -1)
  819. {
  820. ERR("Failed to open %s: (%d) %s\n", fname, errno, strerror(errno));
  821. return ret;
  822. }
  823. if(fstat(fd, &sbuf) == -1)
  824. {
  825. ERR("Failed to stat %s: (%d) %s\n", fname, errno, strerror(errno));
  826. close(fd);
  827. return ret;
  828. }
  829. ptr = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
  830. if(ptr == MAP_FAILED)
  831. {
  832. ERR("Failed to map %s: (%d) %s\n", fname, errno, strerror(errno));
  833. close(fd);
  834. return ret;
  835. }
  836. ret.fd = fd;
  837. ret.ptr = ptr;
  838. ret.len = sbuf.st_size;
  839. return ret;
  840. }
  841. void UnmapFileMem(const struct FileMapping *mapping)
  842. {
  843. munmap(mapping->ptr, mapping->len);
  844. close(mapping->fd);
  845. }
  846. #endif
  847. void SetRTPriority(void)
  848. {
  849. ALboolean failed = AL_FALSE;
  850. #ifdef _WIN32
  851. if(RTPrioLevel > 0)
  852. failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  853. #elif defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
  854. if(RTPrioLevel > 0)
  855. {
  856. struct sched_param param;
  857. /* Use the minimum real-time priority possible for now (on Linux this
  858. * should be 1 for SCHED_RR) */
  859. param.sched_priority = sched_get_priority_min(SCHED_RR);
  860. failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, &param);
  861. }
  862. #else
  863. /* Real-time priority not available */
  864. failed = (RTPrioLevel>0);
  865. #endif
  866. if(failed)
  867. ERR("Failed to set priority level for thread\n");
  868. }
  869. extern inline void alstr_reset(al_string *str);
  870. extern inline size_t alstr_length(const_al_string str);
  871. extern inline ALboolean alstr_empty(const_al_string str);
  872. extern inline const al_string_char_type *alstr_get_cstr(const_al_string str);
  873. void alstr_clear(al_string *str)
  874. {
  875. if(!alstr_empty(*str))
  876. {
  877. /* Reserve one more character than the total size of the string. This
  878. * is to ensure we have space to add a null terminator in the string
  879. * data so it can be used as a C-style string.
  880. */
  881. VECTOR_RESIZE(*str, 0, 1);
  882. VECTOR_ELEM(*str, 0) = 0;
  883. }
  884. }
  885. static inline int alstr_compare(const al_string_char_type *str1, size_t str1len,
  886. const al_string_char_type *str2, size_t str2len)
  887. {
  888. size_t complen = (str1len < str2len) ? str1len : str2len;
  889. int ret = memcmp(str1, str2, complen);
  890. if(ret == 0)
  891. {
  892. if(str1len > str2len) return 1;
  893. if(str1len < str2len) return -1;
  894. }
  895. return ret;
  896. }
  897. int alstr_cmp(const_al_string str1, const_al_string str2)
  898. {
  899. return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
  900. &VECTOR_FRONT(str2), alstr_length(str2));
  901. }
  902. int alstr_cmp_cstr(const_al_string str1, const al_string_char_type *str2)
  903. {
  904. return alstr_compare(&VECTOR_FRONT(str1), alstr_length(str1),
  905. str2, strlen(str2));
  906. }
  907. void alstr_copy(al_string *str, const_al_string from)
  908. {
  909. size_t len = alstr_length(from);
  910. size_t i;
  911. VECTOR_RESIZE(*str, len, len+1);
  912. for(i = 0;i < len;i++)
  913. VECTOR_ELEM(*str, i) = VECTOR_ELEM(from, i);
  914. VECTOR_ELEM(*str, i) = 0;
  915. }
  916. void alstr_copy_cstr(al_string *str, const al_string_char_type *from)
  917. {
  918. size_t len = strlen(from);
  919. size_t i;
  920. VECTOR_RESIZE(*str, len, len+1);
  921. for(i = 0;i < len;i++)
  922. VECTOR_ELEM(*str, i) = from[i];
  923. VECTOR_ELEM(*str, i) = 0;
  924. }
  925. void alstr_copy_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
  926. {
  927. size_t len = to - from;
  928. size_t i;
  929. VECTOR_RESIZE(*str, len, len+1);
  930. for(i = 0;i < len;i++)
  931. VECTOR_ELEM(*str, i) = from[i];
  932. VECTOR_ELEM(*str, i) = 0;
  933. }
  934. void alstr_append_char(al_string *str, const al_string_char_type c)
  935. {
  936. size_t len = alstr_length(*str);
  937. VECTOR_RESIZE(*str, len, len+2);
  938. VECTOR_PUSH_BACK(*str, c);
  939. VECTOR_ELEM(*str, len+1) = 0;
  940. }
  941. void alstr_append_cstr(al_string *str, const al_string_char_type *from)
  942. {
  943. size_t len = strlen(from);
  944. if(len != 0)
  945. {
  946. size_t base = alstr_length(*str);
  947. size_t i;
  948. VECTOR_RESIZE(*str, base+len, base+len+1);
  949. for(i = 0;i < len;i++)
  950. VECTOR_ELEM(*str, base+i) = from[i];
  951. VECTOR_ELEM(*str, base+i) = 0;
  952. }
  953. }
  954. void alstr_append_range(al_string *str, const al_string_char_type *from, const al_string_char_type *to)
  955. {
  956. size_t len = to - from;
  957. if(len != 0)
  958. {
  959. size_t base = alstr_length(*str);
  960. size_t i;
  961. VECTOR_RESIZE(*str, base+len, base+len+1);
  962. for(i = 0;i < len;i++)
  963. VECTOR_ELEM(*str, base+i) = from[i];
  964. VECTOR_ELEM(*str, base+i) = 0;
  965. }
  966. }
  967. #ifdef _WIN32
  968. void alstr_copy_wcstr(al_string *str, const wchar_t *from)
  969. {
  970. int len;
  971. if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
  972. {
  973. VECTOR_RESIZE(*str, len-1, len);
  974. WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_FRONT(*str), len, NULL, NULL);
  975. VECTOR_ELEM(*str, len-1) = 0;
  976. }
  977. }
  978. void alstr_append_wcstr(al_string *str, const wchar_t *from)
  979. {
  980. int len;
  981. if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
  982. {
  983. size_t base = alstr_length(*str);
  984. VECTOR_RESIZE(*str, base+len-1, base+len);
  985. WideCharToMultiByte(CP_UTF8, 0, from, -1, &VECTOR_ELEM(*str, base), len, NULL, NULL);
  986. VECTOR_ELEM(*str, base+len-1) = 0;
  987. }
  988. }
  989. void alstr_append_wrange(al_string *str, const wchar_t *from, const wchar_t *to)
  990. {
  991. int len;
  992. if((len=WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), NULL, 0, NULL, NULL)) > 0)
  993. {
  994. size_t base = alstr_length(*str);
  995. VECTOR_RESIZE(*str, base+len, base+len+1);
  996. WideCharToMultiByte(CP_UTF8, 0, from, (int)(to-from), &VECTOR_ELEM(*str, base), len+1, NULL, NULL);
  997. VECTOR_ELEM(*str, base+len) = 0;
  998. }
  999. }
  1000. #endif