Debian Codegraph @

components/encoder/coreaudioconnect/connector/dllinterface.cpp

raw symbols SCIP
1 /* BoCA - BonkEnc Component Architecture
2 * Copyright (C) 2007-2021 Robert Kausch <[email protected]>
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation, either version 2 of
7 * the License, or (at your option) any later version.
8 *
9 * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
10 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
11 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
12
13 #include "dllinterface.h"
14
15 #include <stdio.h>
16 #include <wchar.h>
17 #include <shlobj.h>
18
19 #ifdef __WINE__
20 # include <unistd.h>
21 # include <pwd.h>
22 # include <sys/stat.h>
23
24 # define wchar_t char
25 # define wstring(s) s
26
27 # define wcslen(x) strlen(x)
28 # define wcscpy(x, y) strcpy(x, y)
29 # define wcsncpy(x, y, z) strncpy(x, y, z)
30 # define wcscat(x, y) strcat(x, y)
31 # define wcscmp(x, y) strcmp(x, y)
32 # define wcsncmp(x, y, z) strncmp(x, y, z)
33 # define wcsrchr(x, y) strrchr(x, y)
34 # define wcsstr(x, y) strstr(x, y)
35
36 # define _wfopen(x, y) fopen(x, y)
37
38 # define _wmkdir(x) mkdir(x, 0777)
39
40 # define GetEnvironmentVariableW GetEnvironmentVariableA
41 # define SetEnvironmentVariableW SetEnvironmentVariableA
42
43 # define SHGetPathFromIDListW SHGetPathFromIDListA
44
45 # define SetDllDirectoryW SetDllDirectoryA
46 # define LoadLibraryW LoadLibraryA
47
48 # define FindFirstFileW FindFirstFileA
49 # define FindNextFileW FindNextFileA
50 # define DeleteFileW DeleteFileA
51
52 # define RegOpenKeyW RegOpenKeyA
53 # define RegEnumKeyW RegEnumKeyA
54 # define RegQueryValueExW RegQueryValueExA
55
56 # define WIN32_FIND_DATAW WIN32_FIND_DATAA
57 #else
58 # define wstring(s) L##s
59 #endif
60
61 namespace CA
62 {
63 AUDIOFILEINITIALIZEWITHCALLBACKS AudioFileInitializeWithCallbacks = NULL;
64 AUDIOFILECLOSE AudioFileClose = NULL;
65 AUDIOFILESETPROPERTY AudioFileSetProperty = NULL;
66 AUDIOFILEWRITEPACKETS AudioFileWritePackets = NULL;
67
68 AUDIOCONVERTERNEW AudioConverterNew = NULL;
69 AUDIOCONVERTERDISPOSE AudioConverterDispose = NULL;
70 AUDIOCONVERTERGETPROPERTY AudioConverterGetProperty = NULL;
71 AUDIOCONVERTERGETPROPERTYINFO AudioConverterGetPropertyInfo = NULL;
72 AUDIOCONVERTERSETPROPERTY AudioConverterSetProperty = NULL;
73 AUDIOCONVERTERFILLCOMPLEXBUFFER AudioConverterFillComplexBuffer = NULL;
74
75 AUDIOFORMATGETPROPERTY AudioFormatGetProperty = NULL;
76 AUDIOFORMATGETPROPERTYINFO AudioFormatGetPropertyInfo = NULL;
77 };
78
79 using namespace CA;
80
81 HINSTANCE coreaudiodll = NULL;
82
83 #define PATH_LENGTH 2048
84
85 static bool FileSystemEntryExists(const wchar_t *path)
86 {
87 WIN32_FIND_DATAW findData;
88 HANDLE handle = FindFirstFileW(path, &findData);
89
90 FindClose(handle);
91
92 return (handle != INVALID_HANDLE_VALUE);
93 }
94
95 static const wchar_t *GetSystemDirectory(int id)
96 {
97 static wchar_t commonFilesDir[PATH_LENGTH] = { 0 };
98
99 ITEMIDLIST *idlist;
100
101 SHGetSpecialFolderLocation(NULL, id, &idlist);
102 SHGetPathFromIDListW(idlist, commonFilesDir);
103
104 CoTaskMemFree(idlist);
105
106 if (wcslen(commonFilesDir) > 0 && commonFilesDir[wcslen(commonFilesDir) - 1] != '\\') wcscat(commonFilesDir, wstring("\\"));
107
108 return commonFilesDir;
109 }
110
111 static const wchar_t *GetCacheFolder(const char *applicationPrefix)
112 {
113 static wchar_t cacheFolder[PATH_LENGTH] = { 0 };
114
115 #ifdef __WINE__
116 char *cacheHome = getenv("XDG_CACHE_HOME");
117
118 if (cacheHome == NULL)
119 {
120 passwd *pw = getpwuid(getuid());
121
122 if (pw != NULL) strcpy(cacheFolder, pw->pw_dir);
123 else strcpy(cacheFolder, "~");
124
125 strcat(cacheFolder, "/.cache/");
126 }
127 else
128 {
129 strcpy(cacheFolder, cacheHome);
130
131 if (cacheFolder[strlen(cacheFolder) - 1] != '/') strcat(cacheFolder, "/");
132 }
133
134 strcat(cacheFolder, applicationPrefix);
135 strcat(cacheFolder, "/");
136 #else
137 GetModuleFileName(NULL, cacheFolder, PATH_LENGTH - 1);
138
139 if (cacheFolder[0] != 0) wcsrchr(cacheFolder, '\\')[1] = 0;
140
141 /* Don't use program files folder as cache folder.
142 */
143 static wchar_t programFilesFolder[PATH_LENGTH];
144
145 wcscpy(programFilesFolder, GetSystemDirectory(CSIDL_PROGRAM_FILES));
146
147 if (wcsncmp(cacheFolder, programFilesFolder, wcslen(programFilesFolder)) != 0)
148 {
149 /* Test if application folder is writable.
150 */
151 wcscat(cacheFolder, wstring("\\coreaudioconnect.cache"));
152
153 fclose(_wfopen(cacheFolder, wstring("w")));
154
155 if (FileSystemEntryExists(cacheFolder))
156 {
157 DeleteFileW(cacheFolder);
158
159 wcsrchr(cacheFolder, '\\')[1] = 0;
160
161 return cacheFolder;
162 }
163 }
164
165 /* Otherwise use application data folder.
166 */
167 wcscpy(cacheFolder, GetSystemDirectory(CSIDL_APPDATA));
168
169 for (unsigned int offset = wcslen(cacheFolder), i = 0; i < strlen(applicationPrefix) + 1; i++) cacheFolder[offset + i] = applicationPrefix[i];
170
171 wcscat(cacheFolder, wstring("\\"));
172 #endif
173
174 return cacheFolder;
175 }
176
177 static void CreateFolder(const wchar_t *path)
178 {
179 wchar_t folder[PATH_LENGTH] = { 0 };
180
181 for (unsigned int i = 0; i < wcslen(path); i++)
182 {
183 if (path[i] != '\\') continue;
184
185 wcsncpy(folder, path, i);
186
187 _wmkdir(folder);
188 }
189
190 _wmkdir(path);
191 }
192
193 static size_t GetFileSize(FILE *file)
194 {
195 fseek(file, 0, SEEK_END);
196
197 size_t size = ftell(file);
198
199 fseek(file, 0, SEEK_SET);
200
201 return size;
202 }
203
204 # if defined __i386__ || defined _M_IX86
205 static const wchar_t *architecture = wstring("x86");
206 #elif defined __x86_64__ || defined _M_AMD64
207 static const wchar_t *architecture = wstring("x64");
208 #elif defined __arm__ || defined _M_ARM
209 static const wchar_t *architecture = wstring("arm");
210 #elif defined __aarch64__ || defined _M_ARM64
211 static const wchar_t *architecture = wstring("arm64");
212 #endif
213
214 #define NUM_FOLDERS 32
215
216 static void GetPackageFolders(const wchar_t *, wchar_t **);
217
218 static void FindDependenciesFolders(const wchar_t *packageFolder, wchar_t **packageFolders)
219 {
220 wchar_t manifestPath[PATH_LENGTH];
221
222 wcscpy(manifestPath, packageFolder);
223 wcscat(manifestPath, wstring("AppxManifest.xml"));
224
225 if (!FileSystemEntryExists(manifestPath)) return;
226
227 /* Load app manifest.
228 */
229 FILE *manifest = _wfopen(manifestPath, wstring("r"));
230 size_t size = GetFileSize(manifest);
231
232 /* Find PackageDependency nodes.
233 */
234 char line[1024];
235
236 while (ftell(manifest) < (int) size)
237 {
238 if (!fgets(line, 1024, manifest)) break;
239 if (!strstr(line, "<PackageDependency ")) continue;
240
241 wchar_t name[256];
242 int start = (strstr(line, "Name=\"") + 6) - line;
243
244 for (int i = 0; i < 256; i++)
245 {
246 if (line[start + i] == '\"')
247 {
248 name[i] = 0;
249 break;
250 }
251
252 name[i] = line[start + i];
253 }
254
255 GetPackageFolders(name, packageFolders);
256 }
257
258 /* Close manifest.
259 */
260 fclose(manifest);
261 }
262
263 static void GetPackageFolders(const wchar_t *packageName, wchar_t **packageFolders)
264 {
265 /* Open Packages key.
266 */
267 HKEY packagesKey;
268
269 if (RegOpenKeyW(HKEY_CLASSES_ROOT, wstring("Local Settings\\Software\\Microsoft\\Windows\\CurrentVersion\\AppModel\\Repository\\Packages"), &packagesKey) != ERROR_SUCCESS) return;
270
271 /* Construct architecture search string.
272 */
273 wchar_t arch[16];
274
275 wcscpy(arch, wstring("_"));
276 wcscat(arch, architecture);
277 wcscat(arch, wstring("_"));
278
279 /* Enumerate registered packages.
280 */
281 int index = 0;
282 wchar_t name[256];
283
284 while (RegEnumKeyW(packagesKey, index++, name, sizeof(name) / sizeof(wchar_t)) == ERROR_SUCCESS)
285 {
286 if (wcsncmp(name, packageName, wcslen(packageName)) != 0) continue;
287 if (!wcsstr(name, arch)) continue;
288
289 /* Found package, open key.
290 */
291 HKEY packageKey;
292
293 if (RegOpenKeyW(packagesKey, name, &packageKey) != ERROR_SUCCESS) continue;
294
295 /* Query folder.
296 */
297 const DWORD size = 2048;
298 DWORD bytes = size * sizeof(wchar_t);
299 wchar_t *folder = (wchar_t *) malloc(bytes);
300
301 RegQueryValueExW(packageKey, wstring("PackageRootFolder"), 0, 0, (BYTE *) folder, &bytes);
302 RegCloseKey(packageKey);
303
304 /* Add folder and dependencies to list.
305 */
306 if (folder[wcslen(folder) - 1] != '\\') wcscat(folder, wstring("\\"));
307
308 for (int i = 0; i < NUM_FOLDERS; i++)
309 {
310 if (packageFolders[i] != NULL)
311 {
312 if (wcscmp(packageFolders[i], folder) == 0)
313 {
314 free(folder);
315
316 break;
317 }
318
319 continue;
320 }
321
322 packageFolders[i] = folder;
323
324 FindDependenciesFolders(folder, packageFolders);
325
326 break;
327 }
328
329 break;
330 }
331
332 RegCloseKey(packagesKey);
333 }
334
335 static void CopyLibrary(const wchar_t *libName, wchar_t **packageFolders, const wchar_t *cacheFolder)
336 {
337 /* Find source and target file names.
338 */
339 wchar_t sourceFile[PATH_LENGTH] = { 0 };
340 wchar_t targetFile[PATH_LENGTH] = { 0 };
341
342 wcscpy(targetFile, cacheFolder);
343 wcscat(targetFile, libName);
344
345 for (int i = 0; i < NUM_FOLDERS; i++)
346 {
347 if (packageFolders[i] == NULL) break;
348
349 wchar_t libFile[PATH_LENGTH];
350
351 wcscpy(libFile, packageFolders[i]);
352 wcscat(libFile, libName);
353
354 if (!FileSystemEntryExists(libFile)) continue;
355
356 wcscpy(sourceFile, libFile);
357 }
358
359 /* Check file existence and skip already existing files.
360 */
361 if (!FileSystemEntryExists(sourceFile) ||
362 FileSystemEntryExists(targetFile)) return;
363
364 /* Prepare input and output files.
365 */
366 FILE *in = _wfopen(sourceFile, wstring("rb"));
367 FILE *out = _wfopen(targetFile, wstring("wb"));
368
369 size_t inSize = GetFileSize(in);
370
371 /* Copy chunks of 128kB.
372 */
373 unsigned char buffer[131072];
374 int bufferSize = sizeof(buffer);
375
376 int overlap = 0;
377 bool foundSelf = false;
378
379 for (size_t i = 0; i < inSize; i += bufferSize - overlap)
380 {
381 memcpy(buffer, buffer + bufferSize - overlap, overlap);
382
383 int remaining = inSize - ftell(in);
384 int bytes = fread(buffer + overlap, 1, bufferSize - overlap < remaining ? bufferSize - overlap : remaining, in);
385
386 fwrite(buffer + overlap, bytes, 1, out);
387
388 /* Check for referenced DLLs.
389 */
390 for (int n = 0; n < overlap + bytes - 5; n++)
391 {
392 if (buffer[n] != '.' || buffer[n + 1] != 'd' || buffer[n + 2] != 'l' || buffer[n + 3] != 'l' || buffer[n + 4] != 0) continue;
393
394 for (int m = n; m >= 0; m--)
395 {
396 if (buffer[m] >= 0x20) continue;
397
398 /* Get DLL name and copy it if it looks like a reference.
399 */
400 char *dllName = (char *) buffer + m + 1;
401 wchar_t dllNameW[256] = { 0 };
402
403 for (unsigned int i = 0; i < strlen(dllName); i++) dllNameW[i] = dllName[i];
404
405 if (foundSelf) CopyLibrary(dllNameW, packageFolders, cacheFolder);
406 else if (wcscmp(dllNameW, libName) == 0) foundSelf = true;
407
408 break;
409 }
410 }
411
412 /* Overlap 128 bytes when wrapping around so we do not miss any relevant DLLs.
413 */
414 overlap = 128;
415 }
416
417 fclose(out);
418 fclose(in);
419 }
420
421 static void CacheCoreAudioLibraries(const wchar_t *cacheFolder)
422 {
423 wchar_t *iTunesFolders[NUM_FOLDERS] = { NULL };
424
425 GetPackageFolders(wstring("AppleInc.iTunes"), iTunesFolders);
426
427 if (iTunesFolders[0] == NULL) return;
428
429 /* Check if package ID has changed.
430 */
431 wchar_t packageFolder[PATH_LENGTH];
432
433 wcscpy(packageFolder, iTunesFolders[0]);
434 wcsrchr(packageFolder, '\\')[0] = 0;
435
436 wchar_t *packageIdW = wcsrchr(packageFolder, '\\') + 1;
437 char packageId[256] = { 0 };
438
439 for (unsigned int i = 0; i < wcslen(packageIdW); i++) packageId[i] = packageIdW[i];
440
441 wchar_t packageIdFile[PATH_LENGTH] = { 0 };
442
443 wcscpy(packageIdFile, cacheFolder);
444 wcscat(packageIdFile, wstring("PackageId"));
445
446 if (FileSystemEntryExists(packageIdFile))
447 {
448 FILE *in = _wfopen(packageIdFile, wstring("r"));
449 char line[256] = { 0 };
450
451 fgets(line, 256, in);
452 fclose(in);
453
454 if (strcmp(line, packageId) == 0) return;
455 }
456
457 /* Create cache folder and make sure it's empty.
458 */
459 CreateFolder(cacheFolder);
460
461 wchar_t pattern[PATH_LENGTH];
462
463 wcscpy(pattern, cacheFolder);
464 wcscat(pattern, wstring("*"));
465
466 WIN32_FIND_DATAW findData;
467 HANDLE handle = FindFirstFileW(pattern, &findData);
468
469 do
470 {
471 if (wcscmp(findData.cFileName, wstring(".")) == 0 || wcscmp(findData.cFileName, wstring("..")) == 0) continue;
472
473 DeleteFileW(findData.cFileName);
474 }
475 while (FindNextFileW(handle, &findData));
476
477 FindClose(handle);
478
479 /* Recursively copy CoreAudioToolbox.dll and referenced DLLs.
480 */
481 CopyLibrary(wstring("CoreAudioToolbox.dll"), iTunesFolders, cacheFolder);
482
483 for (int i = 0; i < NUM_FOLDERS; i++) free(iTunesFolders[i]);
484
485 /* Store package ID.
486 */
487 FILE *out = _wfopen(packageIdFile, wstring("w"));
488
489 fprintf(out, "%s\n", packageId);
490 fclose(out);
491 }
492
493 bool LoadCoreAudioDLL(const char *applicationPrefix)
494 {
495 wchar_t coreAudioDir[PATH_LENGTH];
496
497 wcscpy(coreAudioDir, GetSystemDirectory(CSIDL_PROGRAM_FILES_COMMON));
498 wcscat(coreAudioDir, wstring("Apple\\Apple Application Support\\"));
499
500 if (!FileSystemEntryExists(coreAudioDir))
501 {
502 wcscpy(coreAudioDir, GetSystemDirectory(CSIDL_PROGRAM_FILES));
503 wcscat(coreAudioDir, wstring("iTunes\\"));
504 }
505
506 if (!FileSystemEntryExists(coreAudioDir))
507 {
508 wcscpy(coreAudioDir, GetCacheFolder(applicationPrefix));
509 wcscat(coreAudioDir, wstring("boca.encoder.coreaudio\\"));
510 wcscat(coreAudioDir, architecture);
511 wcscat(coreAudioDir, wstring("\\"));
512
513 CacheCoreAudioLibraries(coreAudioDir);
514 }
515
516 /* Add Apple Application Services directory to DLL search path.
517 */
518 SetDllDirectoryW(coreAudioDir);
519
520 coreaudiodll = LoadLibraryW(wcscat(coreAudioDir, wstring("CoreAudioToolbox.dll")));
521
522 if (coreaudiodll == NULL) return false;
523
524 AudioFileInitializeWithCallbacks = (AUDIOFILEINITIALIZEWITHCALLBACKS) GetProcAddress(coreaudiodll, "AudioFileInitializeWithCallbacks");
525 AudioFileClose = (AUDIOFILECLOSE) GetProcAddress(coreaudiodll, "AudioFileClose");
526 AudioFileSetProperty = (AUDIOFILESETPROPERTY) GetProcAddress(coreaudiodll, "AudioFileSetProperty");
527 AudioFileWritePackets = (AUDIOFILEWRITEPACKETS) GetProcAddress(coreaudiodll, "AudioFileWritePackets");
528
529 AudioConverterNew = (AUDIOCONVERTERNEW) GetProcAddress(coreaudiodll, "AudioConverterNew");
530 AudioConverterDispose = (AUDIOCONVERTERDISPOSE) GetProcAddress(coreaudiodll, "AudioConverterDispose");
531 AudioConverterGetProperty = (AUDIOCONVERTERGETPROPERTY) GetProcAddress(coreaudiodll, "AudioConverterGetProperty");
532 AudioConverterGetPropertyInfo = (AUDIOCONVERTERGETPROPERTYINFO) GetProcAddress(coreaudiodll, "AudioConverterGetPropertyInfo");
533 AudioConverterSetProperty = (AUDIOCONVERTERSETPROPERTY) GetProcAddress(coreaudiodll, "AudioConverterSetProperty");
534 AudioConverterFillComplexBuffer = (AUDIOCONVERTERFILLCOMPLEXBUFFER) GetProcAddress(coreaudiodll, "AudioConverterFillComplexBuffer");
535
536 AudioFormatGetProperty = (AUDIOFORMATGETPROPERTY) GetProcAddress(coreaudiodll, "AudioFormatGetProperty");
537 AudioFormatGetPropertyInfo = (AUDIOFORMATGETPROPERTYINFO) GetProcAddress(coreaudiodll, "AudioFormatGetPropertyInfo");
538
539 if (AudioFileInitializeWithCallbacks == NULL ||
540 AudioFileClose == NULL ||
541 AudioFileSetProperty == NULL ||
542 AudioFileWritePackets == NULL ||
543
544 AudioConverterNew == NULL ||
545 AudioConverterDispose == NULL ||
546 AudioConverterGetProperty == NULL ||
547 AudioConverterGetPropertyInfo == NULL ||
548 AudioConverterSetProperty == NULL ||
549 AudioConverterFillComplexBuffer == NULL ||
550
551 AudioFormatGetProperty == NULL ||
552 AudioFormatGetPropertyInfo == NULL) { FreeCoreAudioDLL(); return false; }
553
554 return true;
555 }
556
557 void FreeCoreAudioDLL()
558 {
559 FreeLibrary(coreaudiodll);
560
561 coreaudiodll = NULL;
562 }