Debian Codegraph @

sys/qsv/libmfx/dispatcher/vpl/mfx_dispatcher_vpl_loader.cpp

raw
1 /*############################################################################
2 # Copyright (C) Intel Corporation
3 #
4 # SPDX-License-Identifier: MIT
5 ############################################################################*/
6
7 #include <algorithm>
8
9 #include "vpl/mfx_dispatcher_vpl.h"
10
11 #if defined(_WIN32) || defined(_WIN64)
12 #include "vpl/mfx_dispatcher_vpl_win.h"
13 #endif
14
15 // leave table formatting alone
16 // clang-format off
17
18 // new functions for API >= 2.0
19 static const VPLFunctionDesc FunctionDesc2[NumVPLFunctions] = {
20 { "MFXQueryImplsDescription", { { 0, 2 } } },
21 { "MFXReleaseImplDescription", { { 0, 2 } } },
22 { "MFXMemory_GetSurfaceForVPP", { { 0, 2 } } },
23 { "MFXMemory_GetSurfaceForEncode", { { 0, 2 } } },
24 { "MFXMemory_GetSurfaceForDecode", { { 0, 2 } } },
25 { "MFXInitialize", { { 0, 2 } } },
26
27 { "MFXMemory_GetSurfaceForVPPOut", { { 1, 2 } } },
28 { "MFXVideoDECODE_VPP_Init", { { 1, 2 } } },
29 { "MFXVideoDECODE_VPP_DecodeFrameAsync", { { 1, 2 } } },
30 { "MFXVideoDECODE_VPP_Reset", { { 1, 2 } } },
31 { "MFXVideoDECODE_VPP_GetChannelParam", { { 1, 2 } } },
32 { "MFXVideoDECODE_VPP_Close", { { 1, 2 } } },
33 { "MFXVideoVPP_ProcessFrameAsync", { { 1, 2 } } },
34 };
35
36 static const VPLFunctionDesc MSDKCompatFunctions[NumMSDKFunctions] = {
37 { "MFXInitEx", { { 14, 1 } } },
38 { "MFXClose" , { { 0, 1 } } },
39 };
40
41 // end table formatting
42 // clang-format on
43
44 // implementation of loader context (mfxLoader)
45 // each loader instance will build a list of valid runtimes and allow
46 // application to create sessions with them
47 LoaderCtxVPL::LoaderCtxVPL()
48 : m_libInfoList(),
49 m_implInfoList(),
50 m_configCtxList(),
51 m_gpuAdapterInfo(),
52 m_specialConfig(),
53 m_implIdxNext(0),
54 m_bKeepCapsUntilUnload(true),
55 m_envVar(),
56 m_dispLog() {
57 // allow loader to distinguish between property value of 0
58 // and property not set
59 m_specialConfig.bIsSet_deviceHandleType = false;
60 m_specialConfig.bIsSet_deviceHandle = false;
61 m_specialConfig.bIsSet_accelerationMode = false;
62 m_specialConfig.bIsSet_ApiVersion = false;
63 m_specialConfig.bIsSet_dxgiAdapterIdx = false;
64 m_specialConfig.bIsSet_NumThread = false;
65 m_specialConfig.bIsSet_DeviceCopy = false;
66 m_specialConfig.bIsSet_ExtBuffer = false;
67
68 // initial state
69 m_bLowLatency = false;
70 m_bNeedUpdateValidImpls = true;
71 m_bNeedFullQuery = true;
72 m_bNeedLowLatencyQuery = true;
73 m_bPriorityPathEnabled = false;
74
75 return;
76 }
77
78 LoaderCtxVPL::~LoaderCtxVPL() {
79 return;
80 }
81
82 mfxStatus LoaderCtxVPL::FullLoadAndQuery() {
83 // disable low latency mode
84 m_bLowLatency = false;
85
86 // search directories for candidate implementations based on search order in
87 // spec
88 mfxStatus sts = BuildListOfCandidateLibs();
89 if (MFX_ERR_NONE != sts)
90 return sts;
91
92 // prune libraries which are not actually implementations, filling function
93 // ptr table for each library which is
94 mfxU32 numLibs = CheckValidLibraries();
95 if (numLibs == 0)
96 return MFX_ERR_UNSUPPORTED;
97
98 // query capabilities of each implementation
99 // may be more than one implementation per library
100 sts = QueryLibraryCaps();
101 if (MFX_ERR_NONE != sts)
102 return MFX_ERR_NOT_FOUND;
103
104 m_bNeedFullQuery = false;
105 m_bNeedUpdateValidImpls = true;
106
107 return MFX_ERR_NONE;
108 }
109
110 // creates ordered list of user-specified directories to search
111 mfxU32 LoaderCtxVPL::ParseEnvSearchPaths(const CHAR_TYPE *envVarName,
112 std::list<STRING_TYPE> &searchDirs) {
113 searchDirs.clear();
114
115 #if defined(_WIN32) || defined(_WIN64)
116 DWORD err;
117 m_envVar[0] = 0;
118
119 err = GetEnvironmentVariableW(envVarName, m_envVar, MAX_ENV_VAR_LEN);
120 if (err == 0 || err >= MAX_ENV_VAR_LEN)
121 return 0; // environment variable not defined or string too long
122
123 // parse env variable into individual directories
124 std::wstringstream envPath((CHAR_TYPE *)m_envVar);
125 STRING_TYPE s;
126 while (std::getline(envPath, s, L';')) {
127 searchDirs.push_back(s);
128 }
129 #else
130 CHAR_TYPE *envVar = getenv(envVarName);
131 if (!envVar)
132 return 0; // environment variable not defined
133
134 // parse env variable into individual directories
135 std::stringstream envPath((CHAR_TYPE *)envVar);
136 STRING_TYPE s;
137 while (std::getline(envPath, s, ':')) {
138 searchDirs.push_back(s);
139 }
140 #endif
141
142 return (mfxU32)searchDirs.size();
143 }
144
145 #define NUM_LIB_PREFIXES 3
146
147 mfxStatus LoaderCtxVPL::SearchDirForLibs(STRING_TYPE searchDir,
148 std::list<LibInfo *> &libInfoList,
149 mfxU32 priority,
150 bool bLoadVPLOnly) {
151 // okay to call with empty searchDir
152 if (searchDir.empty())
153 return MFX_ERR_NONE;
154
155 #if defined(_WIN32) || defined(_WIN64)
156 HANDLE hTestFile = nullptr;
157 WIN32_FIND_DATAW testFileData;
158 DWORD err;
159 STRING_TYPE testFileName[NUM_LIB_PREFIXES] = {
160 searchDir + MAKE_STRING("/libvpl*.dll"),
161 #if defined _M_IX86
162 // 32-bit GPU RT names
163 searchDir + MAKE_STRING("/libmfx32-gen.dll"),
164 searchDir + MAKE_STRING("/libmfxhw32.dll")
165 #else
166 // 64-bit GPU RT names
167 searchDir + MAKE_STRING("/libmfx64-gen.dll"),
168 searchDir + MAKE_STRING("/libmfxhw64.dll")
169 #endif
170 };
171
172 CHAR_TYPE currDir[MAX_VPL_SEARCH_PATH] = L"";
173 if (GetCurrentDirectoryW(MAX_VPL_SEARCH_PATH, currDir))
174 SetCurrentDirectoryW(searchDir.c_str());
175
176 // skip search for MSDK runtime (last entry) if bLoadVPLOnly is set
177 mfxU32 numLibPrefixes = NUM_LIB_PREFIXES;
178 if (bLoadVPLOnly)
179 numLibPrefixes--;
180
181 // iterate over all candidate files in directory
182 for (mfxU32 i = 0; i < numLibPrefixes; i++) {
183 hTestFile = FindFirstFileW(testFileName[i].c_str(), &testFileData);
184 if (hTestFile != INVALID_HANDLE_VALUE) {
185 do {
186 wchar_t libNameFull[MAX_VPL_SEARCH_PATH];
187 wchar_t *libNameBase;
188
189 // special case: do not include dispatcher itself (libmfx.dll, libvpl.dll)
190 if (wcsstr(testFileData.cFileName, L"libmfx.dll") ||
191 wcsstr(testFileData.cFileName, L"libvpl.dll") ||
192 wcsstr(testFileData.cFileName, L"libvpld.dll"))
193 continue;
194
195 err = GetFullPathNameW(testFileData.cFileName,
196 MAX_VPL_SEARCH_PATH,
197 libNameFull,
198 &libNameBase);
199 // unknown error - skip it and move on to next file
200 if (!err)
201 continue;
202
203 // skip duplicates
204 auto libFound =
205 std::find_if(libInfoList.begin(), libInfoList.end(), [&](LibInfo *li) {
206 return (li->libNameFull == libNameFull);
207 });
208 if (libFound != libInfoList.end())
209 continue;
210
211 LibInfo *libInfo = new LibInfo;
212 if (!libInfo)
213 return MFX_ERR_MEMORY_ALLOC;
214
215 libInfo->libNameFull = libNameFull;
216 libInfo->libPriority = priority;
217
218 // add to list
219 libInfoList.push_back(libInfo);
220 } while (FindNextFileW(hTestFile, &testFileData));
221
222 FindClose(hTestFile);
223 }
224 }
225
226 // restore current directory
227 if (currDir[0])
228 SetCurrentDirectoryW(currDir);
229
230 #else
231 DIR *pSearchDir;
232 struct dirent *currFile;
233
234 pSearchDir = opendir(searchDir.c_str());
235 if (pSearchDir) {
236 while (1) {
237 currFile = readdir(pSearchDir);
238 if (!currFile)
239 break;
240
241 // save files with ".so" (including .so.1, etc.)
242 if (strstr(currFile->d_name, ".so")) {
243 // library names must begin with "libvpl*" or "libmfx*"
244 if ((strstr(currFile->d_name, "libvpl") != currFile->d_name) &&
245 (strcmp(currFile->d_name, "libmfx-gen.so.1.2") != 0) &&
246 (strcmp(currFile->d_name, "libmfxhw64.so.1") != 0))
247 continue;
248
249 // special case: do not include dispatcher itself (libmfx.so*, libvpl.so*) or tracer library
250 if (strstr(currFile->d_name, "libmfx.so") ||
251 strstr(currFile->d_name, "libvpl.so") ||
252 strstr(currFile->d_name, "libmfx-tracer"))
253 continue;
254
255 char filePathC[MAX_VPL_SEARCH_PATH];
256
257 // get full path to found library
258 snprintf(filePathC,
259 MAX_VPL_SEARCH_PATH,
260 "%s/%s",
261 searchDir.c_str(),
262 currFile->d_name);
263 char *fullPath = realpath(filePathC, NULL);
264
265 // unknown error - skip it and move on to next file
266 if (!fullPath)
267 continue;
268
269 // skip duplicates
270 auto libFound =
271 std::find_if(libInfoList.begin(), libInfoList.end(), [&](LibInfo *li) {
272 return (li->libNameFull == fullPath);
273 });
274 if (libFound != libInfoList.end()) {
275 free(fullPath);
276 continue;
277 }
278
279 LibInfo *libInfo = new LibInfo;
280 if (!libInfo)
281 return MFX_ERR_MEMORY_ALLOC;
282
283 libInfo->libNameFull = fullPath;
284 libInfo->libPriority = priority;
285 free(fullPath);
286
287 // add to list
288 libInfoList.push_back(libInfo);
289 }
290 }
291 closedir(pSearchDir);
292 }
293 #endif
294
295 return MFX_ERR_NONE;
296 }
297
298 // fill in m_gpuAdapterInfo before calling
299 mfxU32 LoaderCtxVPL::GetSearchPathsDriverStore(std::list<STRING_TYPE> &searchDirs,
300 LibType libType) {
301 searchDirs.clear();
302
303 #if defined(_WIN32) || defined(_WIN64)
304 mfxStatus sts = MFX_ERR_UNSUPPORTED;
305 STRING_TYPE vplPath;
306
307 int storageID = MFX::MFX_DRIVER_STORE_ONEVPL;
308 if (libType == LibTypeMSDK)
309 storageID = MFX::MFX_DRIVER_STORE;
310
311 // get path to Windows driver store (if any) for each adapter
312 for (mfxU32 adapterID = 0; adapterID < (mfxU32)m_gpuAdapterInfo.size(); adapterID++) {
313 vplPath.clear();
314 sts = MFX::MFXLibraryIterator::GetDriverStoreDir(vplPath,
315 MAX_VPL_SEARCH_PATH,
316 m_gpuAdapterInfo[adapterID].deviceID,
317 storageID);
318 if (sts == MFX_ERR_NONE)
319 searchDirs.push_back(vplPath);
320 }
321 #endif
322
323 return (mfxU32)searchDirs.size();
324 }
325
326 mfxU32 LoaderCtxVPL::GetSearchPathsCurrentExe(std::list<STRING_TYPE> &searchDirs) {
327 searchDirs.clear();
328
329 #if defined(_WIN32) || defined(_WIN64)
330 // get path to location of current executable
331 wchar_t implPath[MFX::msdk_disp_path_len];
332 MFX::GetImplPath(MFX::MFX_APP_FOLDER, implPath);
333 STRING_TYPE exePath = implPath;
334
335 // strip trailing backslash
336 size_t exePathLen = exePath.find_last_of(L"\\");
337 if (exePathLen > 0)
338 exePath.erase(exePathLen);
339
340 if (!exePath.empty())
341 searchDirs.push_back(exePath);
342
343 #endif
344
345 return (mfxU32)searchDirs.size();
346 }
347
348 mfxU32 LoaderCtxVPL::GetSearchPathsCurrentDir(std::list<STRING_TYPE> &searchDirs) {
349 searchDirs.clear();
350
351 #if defined(_WIN32) || defined(_WIN64)
352 CHAR_TYPE currDir[MAX_VPL_SEARCH_PATH] = L"";
353 if (GetCurrentDirectoryW(MAX_VPL_SEARCH_PATH, currDir)) {
354 searchDirs.push_back(currDir);
355 }
356 #else
357 CHAR_TYPE currDir[MAX_VPL_SEARCH_PATH] = "";
358 if (getcwd(currDir, MAX_VPL_SEARCH_PATH)) {
359 searchDirs.push_back(currDir);
360 }
361 #endif
362
363 return (mfxU32)searchDirs.size();
364 }
365
366 // get legacy MSDK dispatcher search paths
367 // see "oneVPL Session" section in spec
368 mfxU32 LoaderCtxVPL::GetSearchPathsLegacy(std::list<STRING_TYPE> &searchDirs) {
369 searchDirs.clear();
370
371 #if defined(_WIN32) || defined(_WIN64)
372 mfxStatus sts = MFX_ERR_UNSUPPORTED;
373 STRING_TYPE msdkPath;
374
375 // get path via dispatcher regkey - HKCU
376 msdkPath.clear();
377 sts = MFX::MFXLibraryIterator::GetRegkeyDir(msdkPath,
378 MAX_VPL_SEARCH_PATH,
379 MFX::MFX_CURRENT_USER_KEY);
380 if (sts == MFX_ERR_NONE)
381 searchDirs.push_back(msdkPath);
382
383 // get path via dispatcher regkey - HKLM
384 msdkPath.clear();
385 sts = MFX::MFXLibraryIterator::GetRegkeyDir(msdkPath,
386 MAX_VPL_SEARCH_PATH,
387 MFX::MFX_LOCAL_MACHINE_KEY);
388 if (sts == MFX_ERR_NONE)
389 searchDirs.push_back(msdkPath);
390
391 // get path to %windir%\system32 and %windir%\syswow64
392 std::list<STRING_TYPE> winSysDir;
393 ParseEnvSearchPaths(L"windir", winSysDir);
394
395 // should resolve to a single directory, otherwise something went wrong
396 if (winSysDir.size() == 1) {
397 msdkPath = winSysDir.front() + L"\\system32";
398 searchDirs.push_back(msdkPath);
399
400 msdkPath = winSysDir.front() + L"\\syswow64";
401 searchDirs.push_back(msdkPath);
402 }
403
404 #else
405 // MSDK open-source installation directories
406 searchDirs.push_back("/opt/intel/mediasdk/lib");
407 searchDirs.push_back("/opt/intel/mediasdk/lib64");
408 #endif
409
410 return (mfxU32)searchDirs.size();
411 }
412
413 mfxU32 LoaderCtxVPL::GetSearchPathsSystemDefault(std::list<STRING_TYPE> &searchDirs) {
414 searchDirs.clear();
415
416 #ifdef __linux__
417 // Add the standard path for libmfx1 install in Ubuntu
418 searchDirs.push_back("/usr/lib/x86_64-linux-gnu");
419
420 // Add other default paths
421 searchDirs.push_back("/lib");
422 searchDirs.push_back("/usr/lib");
423 searchDirs.push_back("/lib64");
424 searchDirs.push_back("/usr/lib64");
425 #endif
426
427 return (mfxU32)searchDirs.size();
428 }
429
430 // search for implementations of oneAPI Video Processing Library (oneVPL)
431 // according to the rules in the spec
432 mfxStatus LoaderCtxVPL::BuildListOfCandidateLibs() {
433 DISP_LOG_FUNCTION(&m_dispLog);
434
435 mfxStatus sts = MFX_ERR_NONE;
436
437 STRING_TYPE emptyPath; // default construction = empty
438 std::list<STRING_TYPE> searchDirList;
439 std::list<STRING_TYPE>::iterator it;
440
441 // special case: ONEVPL_PRIORITY_PATH may be used to specify user-defined path
442 // and bypass priority sorting (API >= 2.6)
443 searchDirList.clear();
444 ParseEnvSearchPaths(ONEVPL_PRIORITY_PATH_VAR, searchDirList);
445 it = searchDirList.begin();
446 while (it != searchDirList.end()) {
447 STRING_TYPE nextDir = (*it);
448 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_SPECIAL);
449 it++;
450 }
451
452 if (searchDirList.size() > 0)
453 m_bPriorityPathEnabled = true;
454
455 #if defined(_WIN32) || defined(_WIN64)
456 // retrieve list of DX11 graphics adapters (lightweight)
457 // used for both VPL and legacy driver store search
458 m_gpuAdapterInfo.clear();
459 bool bEnumSuccess = MFX::DXGI1Device::GetAdapterList(m_gpuAdapterInfo);
460
461 // unknown error or no adapters found - clear list
462 if (!bEnumSuccess)
463 m_gpuAdapterInfo.clear();
464
465 // first priority: Windows driver store
466 searchDirList.clear();
467 GetSearchPathsDriverStore(searchDirList, LibTypeVPL);
468 it = searchDirList.begin();
469 while (it != searchDirList.end()) {
470 STRING_TYPE nextDir = (*it);
471 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_01, true);
472 it++;
473 }
474
475 // second priority: path to current executable
476 searchDirList.clear();
477 GetSearchPathsCurrentExe(searchDirList);
478 it = searchDirList.begin();
479 while (it != searchDirList.end()) {
480 STRING_TYPE nextDir = (*it);
481 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_02);
482 it++;
483 }
484
485 // third priority: current working directory
486 searchDirList.clear();
487 GetSearchPathsCurrentDir(searchDirList);
488 it = searchDirList.begin();
489 while (it != searchDirList.end()) {
490 STRING_TYPE nextDir = (*it);
491 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_03);
492 it++;
493 }
494
495 // fourth priority: PATH environment variable
496 searchDirList.clear();
497 ParseEnvSearchPaths(L"PATH", searchDirList);
498 it = searchDirList.begin();
499 while (it != searchDirList.end()) {
500 STRING_TYPE nextDir = (*it);
501 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_04);
502 it++;
503 }
504
505 // fifth priority: ONEVPL_SEARCH_PATH environment variable
506 searchDirList.clear();
507 ParseEnvSearchPaths(L"ONEVPL_SEARCH_PATH", searchDirList);
508 it = searchDirList.begin();
509 while (it != searchDirList.end()) {
510 STRING_TYPE nextDir = (*it);
511 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_05);
512 it++;
513 }
514
515 // legacy MSDK installation: DriverStore has priority
516 searchDirList.clear();
517 GetSearchPathsDriverStore(searchDirList, LibTypeMSDK);
518 it = searchDirList.begin();
519 while (it != searchDirList.end()) {
520 STRING_TYPE nextDir = (*it);
521 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_LEGACY_DRIVERSTORE);
522 it++;
523 }
524
525 // lowest priority: other legacy search paths
526 searchDirList.clear();
527 GetSearchPathsLegacy(searchDirList);
528 it = searchDirList.begin();
529 while (it != searchDirList.end()) {
530 STRING_TYPE nextDir = (*it);
531 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_LEGACY);
532 it++;
533 }
534 #else
535 // first priority: LD_LIBRARY_PATH environment variable
536 searchDirList.clear();
537 ParseEnvSearchPaths("LD_LIBRARY_PATH", searchDirList);
538 it = searchDirList.begin();
539 while (it != searchDirList.end()) {
540 STRING_TYPE nextDir = (*it);
541 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_01);
542 it++;
543 }
544
545 // second priority: Linux default paths
546 searchDirList.clear();
547 GetSearchPathsSystemDefault(searchDirList);
548 it = searchDirList.begin();
549 while (it != searchDirList.end()) {
550 STRING_TYPE nextDir = (*it);
551 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_03);
552 it++;
553 }
554
555 // third priority: current working directory
556 searchDirList.clear();
557 GetSearchPathsCurrentDir(searchDirList);
558 it = searchDirList.begin();
559 while (it != searchDirList.end()) {
560 STRING_TYPE nextDir = (*it);
561 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_04);
562 it++;
563 }
564
565 // fourth priority: ONEVPL_SEARCH_PATH environment variable
566 searchDirList.clear();
567 ParseEnvSearchPaths("ONEVPL_SEARCH_PATH", searchDirList);
568 it = searchDirList.begin();
569 while (it != searchDirList.end()) {
570 STRING_TYPE nextDir = (*it);
571 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_05);
572 it++;
573 }
574
575 // lowest priority: legacy MSDK installation
576 searchDirList.clear();
577 GetSearchPathsLegacy(searchDirList);
578 it = searchDirList.begin();
579 while (it != searchDirList.end()) {
580 STRING_TYPE nextDir = (*it);
581 sts = SearchDirForLibs(nextDir, m_libInfoList, LIB_PRIORITY_LEGACY);
582 it++;
583 }
584 #endif
585
586 return sts;
587 }
588
589 // return number of valid libraries found
590 mfxU32 LoaderCtxVPL::CheckValidLibraries() {
591 DISP_LOG_FUNCTION(&m_dispLog);
592
593 LibInfo *msdkLibBest = nullptr;
594 LibInfo *msdkLibBestDS = nullptr;
595
596 // load all libraries
597 std::list<LibInfo *>::iterator it = m_libInfoList.begin();
598 while (it != m_libInfoList.end()) {
599 LibInfo *libInfo = (*it);
600 mfxStatus sts = MFX_ERR_NONE;
601
602 // load DLL
603 sts = LoadSingleLibrary(libInfo);
604
605 // load video functions: pointers to exposed functions
606 // not all function pointers may be filled in (depends on API version)
607 if (sts == MFX_ERR_NONE && libInfo->hModuleVPL)
608 LoadAPIExports(libInfo, LibTypeVPL);
609
610 // all runtime libraries with API >= 2.0 must export MFXInitialize()
611 // validation of additional functions vs. API version takes place
612 // during UpdateValidImplList() since the minimum API version requested
613 // by application is not known yet (use SetConfigFilterProperty)
614 if (libInfo->vplFuncTable[IdxMFXInitialize] &&
615 libInfo->libPriority < LIB_PRIORITY_LEGACY_DRIVERSTORE) {
616 libInfo->libType = LibTypeVPL;
617 it++;
618 continue;
619 }
620
621 // not a valid 2.x runtime - check for 1.x API (legacy caps query)
622 mfxU32 numFunctions = 0;
623 if (sts == MFX_ERR_NONE && libInfo->hModuleVPL) {
624 if (libInfo->libNameFull.find(MSDK_LIB_NAME) != std::string::npos) {
625 // legacy runtime must be named libmfxhw64 (or 32)
626 // MSDK must export all of the required functions
627 numFunctions = LoadAPIExports(libInfo, LibTypeMSDK);
628 }
629 }
630
631 // check if all of the required MSDK functions were found
632 // and this is valid library (can create session, query version)
633 if (numFunctions == NumMSDKFunctions) {
634 sts = LoaderCtxMSDK::QueryAPIVersion(libInfo->libNameFull, &(libInfo->msdkVersion));
635
636 if (sts == MFX_ERR_NONE) {
637 libInfo->libType = LibTypeMSDK;
638 if (msdkLibBest == nullptr ||
639 (libInfo->msdkVersion.Version > msdkLibBest->msdkVersion.Version)) {
640 msdkLibBest = libInfo;
641 }
642
643 if (libInfo->libPriority == LIB_PRIORITY_LEGACY_DRIVERSTORE) {
644 if (msdkLibBestDS == nullptr ||
645 (libInfo->msdkVersion.Version > msdkLibBestDS->msdkVersion.Version)) {
646 msdkLibBestDS = libInfo;
647 }
648 }
649
650 #if defined(_WIN32) || defined(_WIN64)
651 // workaround for double-init issue in old versions of MSDK runtime
652 // (allow DLL to be fully unloaded after each call to MFXClose)
653 // apply to MSDK with API version <= 1.27
654 if (libInfo->hModuleVPL && (libInfo->msdkVersion.Major == 1) &&
655 (libInfo->msdkVersion.Minor <= 27)) {
656 MFX::mfx_dll_free(libInfo->hModuleVPL);
657 libInfo->hModuleVPL = nullptr;
658 }
659 #endif
660
661 it++;
662 continue;
663 }
664 }
665
666 // required functions missing from DLL, or DLL failed to load
667 // remove this library from the list of options
668 UnloadSingleLibrary(libInfo);
669 it = m_libInfoList.erase(it);
670 }
671
672 if (msdkLibBestDS)
673 msdkLibBest = msdkLibBestDS;
674
675 // prune duplicate MSDK libraries (only keep one with highest API version)
676 it = m_libInfoList.begin();
677 while (it != m_libInfoList.end()) {
678 LibInfo *libInfo = (*it);
679
680 if (libInfo->libType == LibTypeMSDK && libInfo != msdkLibBest) {
681 UnloadSingleLibrary(libInfo);
682 it = m_libInfoList.erase(it);
683 }
684 else {
685 it++;
686 }
687 }
688
689 // number of valid oneVPL libs
690 return (mfxU32)m_libInfoList.size();
691 }
692
693 VPLFunctionPtr LoaderCtxVPL::GetFunctionAddr(void *hModuleVPL, const char *pName) {
694 VPLFunctionPtr pProc = nullptr;
695
696 if (hModuleVPL) {
697 #if defined(_WIN32) || defined(_WIN64)
698 pProc = (VPLFunctionPtr)MFX::mfx_dll_get_addr(hModuleVPL, pName);
699 #else
700 pProc = (VPLFunctionPtr)dlsym(hModuleVPL, pName);
701 #endif
702 }
703
704 return pProc;
705 }
706
707 // load single runtime
708 mfxStatus LoaderCtxVPL::LoadSingleLibrary(LibInfo *libInfo) {
709 if (!libInfo)
710 return MFX_ERR_NULL_PTR;
711
712 #if defined(_WIN32) || defined(_WIN64)
713 libInfo->hModuleVPL = MFX::mfx_dll_load(libInfo->libNameFull.c_str());
714 #else
715 libInfo->hModuleVPL = dlopen(libInfo->libNameFull.c_str(), RTLD_LOCAL | RTLD_NOW);
716 #endif
717
718 if (!libInfo->hModuleVPL)
719 return MFX_ERR_NOT_FOUND;
720
721 return MFX_ERR_NONE;
722 }
723
724 // unload single runtime
725 mfxStatus LoaderCtxVPL::UnloadSingleLibrary(LibInfo *libInfo) {
726 if (libInfo) {
727 if (libInfo->hModuleVPL) {
728 #if defined(_WIN32) || defined(_WIN64)
729 MFX::mfx_dll_free(libInfo->hModuleVPL);
730 #else
731 dlclose(libInfo->hModuleVPL);
732 #endif
733 }
734 delete libInfo;
735 return MFX_ERR_NONE;
736 }
737 else {
738 return MFX_ERR_INVALID_HANDLE;
739 }
740 }
741
742 // iterate over all implementation runtimes
743 // unload DLL's and free memory
744 mfxStatus LoaderCtxVPL::UnloadAllLibraries() {
745 DISP_LOG_FUNCTION(&m_dispLog);
746
747 std::list<ImplInfo *>::iterator it2 = m_implInfoList.begin();
748 while (it2 != m_implInfoList.end()) {
749 ImplInfo *implInfo = (*it2);
750
751 if (implInfo) {
752 UnloadSingleImplementation(implInfo);
753 }
754 it2++;
755 }
756
757 // lastly, unload and destroy LibInfo for each library
758 std::list<LibInfo *>::iterator it = m_libInfoList.begin();
759 while (it != m_libInfoList.end()) {
760 LibInfo *libInfo = (*it);
761
762 if (libInfo) {
763 UnloadSingleLibrary(libInfo);
764 }
765 it++;
766 }
767
768 m_implInfoList.clear();
769 m_libInfoList.clear();
770 m_implIdxNext = 0;
771
772 return MFX_ERR_NONE;
773 }
774
775 // unload single implementation
776 // each runtime library may contain 1 or more implementations
777 mfxStatus LoaderCtxVPL::UnloadSingleImplementation(ImplInfo *implInfo) {
778 if (implInfo && implInfo->libInfo) {
779 LibInfo *libInfo = implInfo->libInfo;
780 VPLFunctionPtr pFunc = libInfo->vplFuncTable[IdxMFXReleaseImplDescription];
781
782 // call MFXReleaseImplDescription() for this implementation if it
783 // was never called by the application
784 // this is a valid scenario, e.g. app did not call MFXEnumImplementations()
785 // and just used the first available implementation provided by dispatcher
786 if (libInfo->libType == LibTypeVPL) {
787 if (implInfo->implDesc) {
788 // MFX_IMPLCAPS_IMPLDESCSTRUCTURE;
789 (*(mfxStatus(MFX_CDECL *)(mfxHDL))pFunc)(implInfo->implDesc);
790 implInfo->implDesc = nullptr;
791 }
792
793 if (implInfo->implFuncs) {
794 // MFX_IMPLCAPS_IMPLEMENTEDFUNCTIONS;
795 (*(mfxStatus(MFX_CDECL *)(mfxHDL))pFunc)(implInfo->implFuncs);
796 implInfo->implFuncs = nullptr;
797 }
798 #ifdef ONEVPL_EXPERIMENTAL
799 if (implInfo->implExtDeviceID) {
800 // MFX_IMPLCAPS_DEVICE_ID_EXTENDED;
801 (*(mfxStatus(MFX_CDECL *)(mfxHDL))pFunc)(implInfo->implExtDeviceID);
802 implInfo->implExtDeviceID = nullptr;
803 }
804 #endif
805
806 // nothing to do if (capsFormat == MFX_IMPLCAPS_IMPLPATH) since no new memory was allocated
807 }
808 delete implInfo;
809 return MFX_ERR_NONE;
810 }
811 else {
812 return MFX_ERR_INVALID_HANDLE;
813 }
814 }
815
816 // return number of functions loaded
817 mfxU32 LoaderCtxVPL::LoadAPIExports(LibInfo *libInfo, LibType libType) {
818 mfxU32 i, numFunctions = 0;
819
820 if (libType == LibTypeVPL) {
821 for (i = 0; i < NumVPLFunctions; i += 1) {
822 VPLFunctionPtr pProc =
823 (VPLFunctionPtr)GetFunctionAddr(libInfo->hModuleVPL, FunctionDesc2[i].pName);
824 if (pProc) {
825 libInfo->vplFuncTable[i] = pProc;
826 numFunctions++;
827 }
828 }
829 }
830 else if (libType == LibTypeMSDK) {
831 // don't actually need to save the function pointers for MSDK, just check if they are defined
832 for (i = 0; i < NumMSDKFunctions; i += 1) {
833 VPLFunctionPtr pProc =
834 (VPLFunctionPtr)GetFunctionAddr(libInfo->hModuleVPL, MSDKCompatFunctions[i].pName);
835 if (pProc) {
836 numFunctions++;
837 }
838 }
839 }
840
841 return numFunctions;
842 }
843
844 // check that all functions for this API version are available in library
845 mfxStatus LoaderCtxVPL::ValidateAPIExports(VPLFunctionPtr *vplFuncTable,
846 mfxVersion reportedVersion) {
847 for (mfxU32 i = 0; i < NumVPLFunctions; i += 1) {
848 if (!vplFuncTable[i] && (FunctionDesc2[i].apiVersion.Version <= reportedVersion.Version))
849 return MFX_ERR_UNSUPPORTED;
850 }
851
852 return MFX_ERR_NONE;
853 }
854
855 // convert full path into char* for MFX_IMPLCAPS_IMPLPATH query
856 mfxStatus LoaderCtxVPL::UpdateImplPath(LibInfo *libInfo) {
857 #if defined(_WIN32) || defined(_WIN64)
858 // Windows - strings are 16-bit
859 size_t nCvt = 0;
860 if (wcstombs_s(&nCvt,
861 libInfo->implCapsPath,
862 sizeof(libInfo->implCapsPath),
863 libInfo->libNameFull.c_str(),
864 _TRUNCATE)) {
865 // unknown error - set to empty string
866 libInfo->implCapsPath[0] = 0;
867 return MFX_ERR_UNSUPPORTED;
868 }
869 #else
870 // Linux - strings are 8-bit
871 strncpy(libInfo->implCapsPath, libInfo->libNameFull.c_str(), sizeof(libInfo->implCapsPath) - 1);
872 #endif
873
874 return MFX_ERR_NONE;
875 }
876
877 bool LoaderCtxVPL::IsValidX86GPU(ImplInfo *implInfo, mfxU32 &deviceID, mfxU32 &adapterIdx) {
878 mfxImplDescription *implDesc = (mfxImplDescription *)(implInfo->implDesc);
879
880 // may be null in low-latency mode, ID unknown
881 if (!implDesc)
882 return false;
883
884 if (implInfo->validImplIdx >= 0 && implDesc->VendorID == 0x8086 &&
885 implDesc->Impl == MFX_IMPL_TYPE_HARDWARE) {
886 // verify that DeviceID is a valid format for x86 GPU
887 // either "DeviceID" (hex) or "DeviceID/AdapterIdx" (hex/dec)
888 return ConfigCtxVPL::ParseDeviceIDx86(implDesc->Dev.DeviceID, deviceID, adapterIdx);
889 }
890
891 return false;
892 }
893
894 // query capabilities of all valid libraries
895 // and add to list for future calls to EnumImplementations()
896 // as well as filtering by functionality
897 // assume MFX_IMPLCAPS_IMPLDESCSTRUCTURE is the only format supported
898 mfxStatus LoaderCtxVPL::QueryLibraryCaps() {
899 DISP_LOG_FUNCTION(&m_dispLog);
900
901 mfxStatus sts = MFX_ERR_NONE;
902
903 std::list<LibInfo *>::iterator it = m_libInfoList.begin();
904 while (it != m_libInfoList.end()) {
905 LibInfo *libInfo = (*it);
906
907 if (libInfo->libType == LibTypeVPL) {
908 VPLFunctionPtr pFunc = libInfo->vplFuncTable[IdxMFXQueryImplsDescription];
909
910 // handle to implDesc structure, null in low-latency mode (no query)
911 mfxHDL *hImpl = nullptr;
912 mfxU32 numImpls = 0;
913
914 #ifdef ONEVPL_EXPERIMENTAL
915 mfxHDL *hImplExtDeviceID = nullptr;
916 mfxU32 numImplsExtDeviceID = 0;
917 #endif
918
919 if (m_bLowLatency == false) {
920 // call MFXQueryImplsDescription() for this implementation
921 // return handle to description in requested format
922 hImpl = (*(mfxHDL * (MFX_CDECL *)(mfxImplCapsDeliveryFormat, mfxU32 *))
923 pFunc)(MFX_IMPLCAPS_IMPLDESCSTRUCTURE, &numImpls);
924
925 // validate description pointer for each implementation
926 bool b_isValidDesc = true;
927 if (!hImpl) {
928 b_isValidDesc = false;
929 }
930 else {
931 for (mfxU32 i = 0; i < numImpls; i++) {
932 if (!hImpl[i]) {
933 b_isValidDesc = false;
934 break;
935 }
936 }
937 }
938
939 if (!b_isValidDesc) {
940 // the required function is implemented incorrectly
941 // remove this library from the list of valid libraries
942 UnloadSingleLibrary(libInfo);
943 it = m_libInfoList.erase(it);
944 continue;
945 }
946
947 #ifdef ONEVPL_EXPERIMENTAL
948 hImplExtDeviceID =
949 (*(mfxHDL * (MFX_CDECL *)(mfxImplCapsDeliveryFormat, mfxU32 *))
950 pFunc)(MFX_IMPLCAPS_DEVICE_ID_EXTENDED, &numImplsExtDeviceID);
951 #endif
952 }
953
954 // query for list of implemented functions
955 // prior to API 2.2, this will return null since the format was not defined yet
956 // so we need to check whether the returned handle is valid before attempting to use it
957 mfxHDL *hImplFuncs = nullptr;
958 mfxU32 numImplsFuncs = 0;
959 hImplFuncs = (*(mfxHDL * (MFX_CDECL *)(mfxImplCapsDeliveryFormat, mfxU32 *))
960 pFunc)(MFX_IMPLCAPS_IMPLEMENTEDFUNCTIONS, &numImplsFuncs);
961
962 // only report single impl, but application may still attempt to create session using
963 // any of VendorImplID via the DXGIAdapterIndex filter property
964 if (m_bLowLatency == true)
965 numImpls = 1;
966
967 // save user-friendly path for MFX_IMPLCAPS_IMPLPATH query (API >= 2.4)
968 UpdateImplPath(libInfo);
969
970 for (mfxU32 i = 0; i < numImpls; i++) {
971 ImplInfo *implInfo = new ImplInfo;
972 if (!implInfo)
973 return MFX_ERR_MEMORY_ALLOC;
974
975 // library which contains this implementation
976 implInfo->libInfo = libInfo;
977
978 #ifdef ONEVPL_EXPERIMENTAL
979 if (hImplExtDeviceID && i < numImplsExtDeviceID)
980 implInfo->implExtDeviceID = hImplExtDeviceID[i];
981 #endif
982
983 // implemented function description, if available
984 if (hImplFuncs && i < numImplsFuncs)
985 implInfo->implFuncs = hImplFuncs[i];
986
987 // fill out mfxInitializationParam for use in CreateSession (MFXInitialize path)
988 memset(&(implInfo->vplParam), 0, sizeof(mfxInitializationParam));
989
990 if (m_bLowLatency == false) {
991 // implementation descriptor returned from runtime
992 implInfo->implDesc = hImpl[i];
993
994 // fill out mfxInitParam struct for when we call MFXInitEx
995 // in CreateSession()
996 mfxImplDescription *implDesc = reinterpret_cast<mfxImplDescription *>(hImpl[i]);
997
998 // default mode for this impl
999 // this may be changed later by MFXSetConfigFilterProperty(AccelerationMode)
1000 implInfo->vplParam.AccelerationMode = implDesc->AccelerationMode;
1001
1002 implInfo->version = implDesc->ApiVersion;
1003 }
1004 else {
1005 implInfo->implDesc = nullptr;
1006
1007 // application must set requested mode using MFXSetConfigFilterProperty()
1008 // will be updated during CreateSession
1009 implInfo->vplParam.AccelerationMode = MFX_ACCEL_MODE_NA;
1010
1011 mfxVersion queryVersion = {};
1012
1013 // create test session to get API version
1014 sts = QuerySessionLowLatency(libInfo, i, &queryVersion);
1015 if (sts != MFX_ERR_NONE) {
1016 UnloadSingleImplementation(implInfo);
1017 continue;
1018 }
1019 implInfo->version.Version = queryVersion.Version;
1020 }
1021
1022 // save local index for this library
1023 implInfo->libImplIdx = i;
1024
1025 // validate that library exports all required functions for the reported API version
1026 if (ValidateAPIExports(libInfo->vplFuncTable, implInfo->version)) {
1027 UnloadSingleImplementation(implInfo);
1028 continue;
1029 }
1030
1031 // initially all libraries have a valid, sequential value (>= 0)
1032 // list of valid libraries is updated with every call to MFXSetConfigFilterProperty()
1033 // (see UpdateValidImplList)
1034 // libraries that do not support all the required props get a value of -1, and
1035 // indexing of the valid libs is recalculated from 0,1,...
1036 implInfo->validImplIdx = m_implIdxNext++;
1037
1038 // add implementation to overall list
1039 m_implInfoList.push_back(implInfo);
1040 }
1041 }
1042 else if (libInfo->libType == LibTypeMSDK) {
1043 // save user-friendly path for MFX_IMPLCAPS_IMPLPATH query (API >= 2.4)
1044 UpdateImplPath(libInfo);
1045
1046 mfxU32 maxImplMSDK = MAX_NUM_IMPL_MSDK;
1047
1048 // call once on adapter 0 to get MSDK API version (same for any adapter)
1049 mfxVersion queryVersion = {};
1050 if (m_bLowLatency) {
1051 sts = LoaderCtxMSDK::QueryAPIVersion(libInfo->libNameFull, &queryVersion);
1052 if (sts != MFX_ERR_NONE)
1053 queryVersion.Version = 0;
1054
1055 // only report single impl, but application may still attempt to create session using
1056 // any of MFX_IMPL_HARDWAREx via the DXGIAdapterIndex filter property
1057 maxImplMSDK = 1;
1058 }
1059
1060 mfxU32 numImplMSDK = 0;
1061 for (mfxU32 i = 0; i < maxImplMSDK; i++) {
1062 mfxImplDescription *implDesc = nullptr;
1063 mfxImplementedFunctions *implFuncs = nullptr;
1064 #ifdef ONEVPL_EXPERIMENTAL
1065 mfxExtendedDeviceId *implExtDeviceID = nullptr;
1066 #endif
1067
1068 LoaderCtxMSDK *msdkCtx = &(libInfo->msdkCtx[i]);
1069 if (m_bLowLatency == false) {
1070 // perf. optimization: if app requested bIsSet_accelerationMode other than D3D9, don't test whether MSDK supports D3D9
1071 bool bSkipD3D9Check = false;
1072 if (m_specialConfig.bIsSet_accelerationMode &&
1073 m_specialConfig.accelerationMode != MFX_ACCEL_MODE_VIA_D3D9) {
1074 bSkipD3D9Check = true;
1075 }
1076
1077 sts = msdkCtx->QueryMSDKCaps(libInfo->libNameFull,
1078 &implDesc,
1079 &implFuncs,
1080 i,
1081 bSkipD3D9Check);
1082
1083 if (sts || !implDesc || !implFuncs) {
1084 // this adapter (i) is not supported
1085 continue;
1086 }
1087
1088 #ifdef ONEVPL_EXPERIMENTAL
1089 sts = LoaderCtxMSDK::QueryExtDeviceID(&(msdkCtx->m_extDeviceID),
1090 i,
1091 msdkCtx->m_deviceID,
1092 msdkCtx->m_luid);
1093 if (sts == MFX_ERR_NONE)
1094 implExtDeviceID = &(msdkCtx->m_extDeviceID);
1095
1096 #endif
1097 }
1098 else {
1099 // unknown API - unable to create session on any adapter
1100 if (queryVersion.Version == 0)
1101 continue;
1102
1103 // these are the only values filled in for msdkCtx in low latency mode
1104 // used during CreateSession
1105 msdkCtx->m_msdkAdapter = msdkImplTab[i];
1106 msdkCtx->m_msdkAdapterD3D9 = msdkImplTab[i];
1107 }
1108
1109 ImplInfo *implInfo = new ImplInfo;
1110 if (!implInfo)
1111 return MFX_ERR_MEMORY_ALLOC;
1112
1113 // library which contains this implementation
1114 implInfo->libInfo = libInfo;
1115
1116 // implemented function description, if available
1117 implInfo->implFuncs = implFuncs;
1118
1119 #ifdef ONEVPL_EXPERIMENTAL
1120 // extended device ID description, if available
1121 implInfo->implExtDeviceID = implExtDeviceID;
1122 #endif
1123 // fill out mfxInitializationParam for use in CreateSession (MFXInitialize path)
1124 memset(&(implInfo->vplParam), 0, sizeof(mfxInitializationParam));
1125
1126 if (m_bLowLatency == false) {
1127 // implementation descriptor returned from runtime
1128 implInfo->implDesc = implDesc;
1129
1130 // default mode for this impl
1131 // this may be changed later by MFXSetConfigFilterProperty(AccelerationMode)
1132 implInfo->vplParam.AccelerationMode = implDesc->AccelerationMode;
1133
1134 implInfo->version = implDesc->ApiVersion;
1135 }
1136 else {
1137 implInfo->implDesc = nullptr;
1138
1139 // application must set requested mode using MFXSetConfigFilterProperty()
1140 // will be updated during CreateSession
1141 implInfo->vplParam.AccelerationMode = MFX_ACCEL_MODE_NA;
1142
1143 // save API version from creating test MSDK session above
1144 implInfo->version.Version = queryVersion.Version;
1145 }
1146
1147 // adapter number
1148 implInfo->msdkImplIdx = i;
1149
1150 // save local index for this library
1151 implInfo->libImplIdx = 0;
1152
1153 // initially all libraries have a valid, sequential value (>= 0)
1154 // list of valid libraries is updated with every call to MFXSetConfigFilterProperty()
1155 // (see UpdateValidImplList)
1156 // libraries that do not support all the required props get a value of -1, and
1157 // indexing of the valid libs is recalculated from 0,1,...
1158 implInfo->validImplIdx = m_implIdxNext++;
1159
1160 // add implementation to overall list
1161 m_implInfoList.push_back(implInfo);
1162
1163 // update number of valid MSDK adapters
1164 numImplMSDK++;
1165 }
1166
1167 if (numImplMSDK == 0) {
1168 // error loading MSDK library in compatibility mode - remove from list
1169 UnloadSingleLibrary(libInfo);
1170 it = m_libInfoList.erase(it);
1171 continue;
1172 }
1173 }
1174 it++;
1175 }
1176
1177 if (m_bLowLatency == false && !m_implInfoList.empty()) {
1178 bool bD3D9Requested = (m_specialConfig.bIsSet_accelerationMode &&
1179 m_specialConfig.accelerationMode == MFX_ACCEL_MODE_VIA_D3D9);
1180
1181 std::list<ImplInfo *>::iterator it2 = m_implInfoList.begin();
1182 while (it2 != m_implInfoList.end()) {
1183 ImplInfo *implInfo = (*it2);
1184
1185 mfxU32 deviceID = 0;
1186 mfxU32 adapterIdx = 0;
1187 if (IsValidX86GPU(implInfo, deviceID, adapterIdx)) {
1188 // save the adapterIdx for any x86 GPU devices (may be used later for filtering)
1189 implInfo->adapterIdx = adapterIdx;
1190 }
1191
1192 // per spec: if both VPL (HW) and MSDK are installed for the same accelerator, only load
1193 // the VPL implementation (mark MSDK as invalid)
1194 // exception: if application requests D3D9, load MSDK if available
1195 if (implInfo->libInfo->libType == LibTypeMSDK) {
1196 mfxImplDescription *msdkImplDesc = (mfxImplDescription *)(implInfo->implDesc);
1197 std::string msdkDeviceID = (msdkImplDesc ? msdkImplDesc->Dev.DeviceID : "");
1198
1199 // check if VPL impl also exists for this deviceID
1200 auto vplIdx = std::find_if(
1201 m_implInfoList.begin(),
1202 m_implInfoList.end(),
1203
1204 [&](const ImplInfo *t) {
1205 mfxImplDescription *implDesc = (mfxImplDescription *)(t->implDesc);
1206
1207 bool bMatchingDeviceID = false;
1208 if (implDesc) {
1209 std::string vplDeviceID = implDesc->Dev.DeviceID;
1210 if (vplDeviceID == msdkDeviceID)
1211 bMatchingDeviceID = true;
1212 }
1213
1214 return (t->libInfo->libType == LibTypeVPL && implDesc != nullptr &&
1215 implDesc->Impl == MFX_IMPL_TYPE_HARDWARE && bMatchingDeviceID);
1216 });
1217
1218 if (vplIdx != m_implInfoList.end() && bD3D9Requested == false)
1219 implInfo->validImplIdx = -1;
1220
1221 // avoid loading VPL RT via compatibility entrypoint
1222 if (msdkImplDesc && msdkImplDesc->ApiVersion.Major == 1 &&
1223 msdkImplDesc->ApiVersion.Minor == 255)
1224 implInfo->validImplIdx = -1;
1225 }
1226
1227 if (implInfo->libInfo->libType == LibTypeVPL && !implInfo->implDesc) {
1228 //library was loaded in low-delay mode, need to query caps for it
1229 mfxU32 numImpls = 0;
1230 VPLFunctionPtr pFunc = implInfo->libInfo->vplFuncTable[IdxMFXQueryImplsDescription];
1231 mfxHDL *hImpl = (*(mfxHDL * (MFX_CDECL *)(mfxImplCapsDeliveryFormat, mfxU32 *))
1232 pFunc)(MFX_IMPLCAPS_IMPLDESCSTRUCTURE, &numImpls);
1233
1234 //only single impl was reported
1235 implInfo->implDesc = reinterpret_cast<mfxImplDescription *>(hImpl[0]);
1236 }
1237 else if (implInfo->libInfo->libType == LibTypeMSDK && !implInfo->implDesc) {
1238 mfxImplDescription *implDesc = nullptr;
1239 mfxImplementedFunctions *implFuncs = nullptr;
1240
1241 LoaderCtxMSDK *msdkCtx = &(implInfo->libInfo->msdkCtx[0]);
1242
1243 // perf. optimization: if app requested bIsSet_accelerationMode other than D3D9, don't test whether MSDK supports D3D9
1244 bool bSkipD3D9Check = false;
1245 if (m_specialConfig.bIsSet_accelerationMode &&
1246 m_specialConfig.accelerationMode != MFX_ACCEL_MODE_VIA_D3D9) {
1247 bSkipD3D9Check = true;
1248 }
1249
1250 sts = msdkCtx->QueryMSDKCaps(implInfo->libInfo->libNameFull,
1251 &implDesc,
1252 &implFuncs,
1253 0,
1254 bSkipD3D9Check);
1255
1256 if (sts || !implDesc || !implFuncs) {
1257 // this adapter (i) is not supported
1258 continue;
1259 }
1260 implInfo->implDesc = implDesc;
1261 implInfo->implFuncs = implFuncs;
1262 }
1263
1264 it2++;
1265 }
1266
1267 // sort valid implementations according to priority rules in spec
1268 PrioritizeImplList();
1269 }
1270
1271 return m_implInfoList.empty() ? MFX_ERR_UNSUPPORTED : MFX_ERR_NONE;
1272 }
1273
1274 // query implementation i
1275 mfxStatus LoaderCtxVPL::QueryImpl(mfxU32 idx, mfxImplCapsDeliveryFormat format, mfxHDL *idesc) {
1276 DISP_LOG_FUNCTION(&m_dispLog);
1277
1278 *idesc = nullptr;
1279
1280 std::list<ImplInfo *>::iterator it = m_implInfoList.begin();
1281 while (it != m_implInfoList.end()) {
1282 ImplInfo *implInfo = (*it);
1283 if (implInfo->validImplIdx == (mfxI32)idx) {
1284 if (format == MFX_IMPLCAPS_IMPLDESCSTRUCTURE) {
1285 *idesc = implInfo->implDesc;
1286 }
1287 else if (format == MFX_IMPLCAPS_IMPLEMENTEDFUNCTIONS) {
1288 *idesc = implInfo->implFuncs;
1289 }
1290 else if (format == MFX_IMPLCAPS_IMPLPATH) {
1291 *idesc = implInfo->libInfo->implCapsPath;
1292 }
1293 #ifdef ONEVPL_EXPERIMENTAL
1294 else if (format == MFX_IMPLCAPS_DEVICE_ID_EXTENDED) {
1295 *idesc = implInfo->implExtDeviceID;
1296 }
1297 #endif
1298
1299 // implementation found, but requested query format is not supported
1300 if (*idesc == nullptr)
1301 return MFX_ERR_UNSUPPORTED;
1302
1303 return MFX_ERR_NONE;
1304 }
1305 it++;
1306 }
1307
1308 // invalid idx
1309 return MFX_ERR_NOT_FOUND;
1310 }
1311
1312 mfxStatus LoaderCtxVPL::ReleaseImpl(mfxHDL idesc) {
1313 DISP_LOG_FUNCTION(&m_dispLog);
1314
1315 mfxStatus sts = MFX_ERR_NONE;
1316
1317 if (idesc == nullptr)
1318 return MFX_ERR_NULL_PTR;
1319
1320 // all we get from the application is a handle to the descriptor,
1321 // not the implementation associated with it, so we search
1322 // through the full list until we find a match
1323 std::list<ImplInfo *>::iterator it = m_implInfoList.begin();
1324 while (it != m_implInfoList.end()) {
1325 ImplInfo *implInfo = (*it);
1326 mfxImplCapsDeliveryFormat capsFormat = (mfxImplCapsDeliveryFormat)0; // unknown format
1327
1328 // in low latency mode implDesc will be empty
1329 if (implInfo->implDesc == nullptr)
1330 continue;
1331
1332 // determine type of descriptor so we know which handle to
1333 // invalidate in the Loader context
1334 if (implInfo->implDesc == idesc) {
1335 capsFormat = MFX_IMPLCAPS_IMPLDESCSTRUCTURE;
1336 }
1337 else if (implInfo->implFuncs == idesc) {
1338 capsFormat = MFX_IMPLCAPS_IMPLEMENTEDFUNCTIONS;
1339 }
1340 else if (implInfo->libInfo->implCapsPath == idesc) {
1341 capsFormat = MFX_IMPLCAPS_IMPLPATH;
1342 }
1343 #ifdef ONEVPL_EXPERIMENTAL
1344 else if (implInfo->implExtDeviceID == idesc) {
1345 capsFormat = MFX_IMPLCAPS_DEVICE_ID_EXTENDED;
1346 }
1347 #endif
1348 else {
1349 // no match - try next implementation
1350 it++;
1351 continue;
1352 }
1353
1354 // if true, do not actually call ReleaseImplDescription() until
1355 // MFXUnload() --> UnloadAllLibraries()
1356 // this permits the application to call Enum/CreateSession/DispRelease multiple
1357 // times on the same implementation
1358 if (m_bKeepCapsUntilUnload)
1359 return MFX_ERR_NONE;
1360
1361 // LibTypeMSDK does not require calling a release function
1362 if (implInfo->libInfo->libType == LibTypeVPL) {
1363 // call MFXReleaseImplDescription() for this implementation
1364 VPLFunctionPtr pFunc = implInfo->libInfo->vplFuncTable[IdxMFXReleaseImplDescription];
1365
1366 if (capsFormat == MFX_IMPLCAPS_IMPLDESCSTRUCTURE) {
1367 sts = (*(mfxStatus(MFX_CDECL *)(mfxHDL))pFunc)(implInfo->implDesc);
1368 implInfo->implDesc = nullptr;
1369 }
1370 else if (capsFormat == MFX_IMPLCAPS_IMPLEMENTEDFUNCTIONS) {
1371 sts = (*(mfxStatus(MFX_CDECL *)(mfxHDL))pFunc)(implInfo->implFuncs);
1372 implInfo->implFuncs = nullptr;
1373 }
1374 #ifdef ONEVPL_EXPERIMENTAL
1375 else if (capsFormat == MFX_IMPLCAPS_DEVICE_ID_EXTENDED) {
1376 sts = (*(mfxStatus(MFX_CDECL *)(mfxHDL))pFunc)(implInfo->implExtDeviceID);
1377 implInfo->implExtDeviceID = nullptr;
1378 }
1379 #endif
1380
1381 // nothing to do if (capsFormat == MFX_IMPLCAPS_IMPLPATH) since no new memory was allocated
1382 }
1383
1384 return sts;
1385 }
1386
1387 // did not find a matching handle - should not happen
1388 return MFX_ERR_INVALID_HANDLE;
1389 }
1390
1391 mfxStatus LoaderCtxVPL::UpdateLowLatency() {
1392 m_bLowLatency = false;
1393
1394 m_bLowLatency = ConfigCtxVPL::CheckLowLatencyConfig(m_configCtxList, &m_specialConfig);
1395
1396 return MFX_ERR_NONE;
1397 }
1398
1399 mfxStatus LoaderCtxVPL::UpdateValidImplList(void) {
1400 DISP_LOG_FUNCTION(&m_dispLog);
1401
1402 mfxStatus sts = MFX_ERR_NONE;
1403
1404 mfxI32 validImplIdx = 0;
1405
1406 // iterate over all libraries and update list of those that
1407 // meet current current set of config props
1408 std::list<ImplInfo *>::iterator it = m_implInfoList.begin();
1409 while (it != m_implInfoList.end()) {
1410 ImplInfo *implInfo = (*it);
1411
1412 // already invalidated by previous filter
1413 if (implInfo->validImplIdx == -1) {
1414 it++;
1415 continue;
1416 }
1417
1418 // compare caps from this library vs. config filters
1419 sts = ConfigCtxVPL::ValidateConfig((mfxImplDescription *)implInfo->implDesc,
1420 (mfxImplementedFunctions *)implInfo->implFuncs,
1421 #ifdef ONEVPL_EXPERIMENTAL
1422 (mfxExtendedDeviceId *)implInfo->implExtDeviceID,
1423 #endif
1424 m_configCtxList,
1425 implInfo->libInfo->libType,
1426 &m_specialConfig);
1427
1428 // check special filter properties which are not part of mfxImplDescription
1429 if (m_specialConfig.bIsSet_dxgiAdapterIdx &&
1430 (m_specialConfig.dxgiAdapterIdx != implInfo->adapterIdx)) {
1431 sts = MFX_ERR_UNSUPPORTED;
1432 }
1433
1434 if (sts == MFX_ERR_NONE) {
1435 // library supports all required properties
1436 implInfo->validImplIdx = validImplIdx++;
1437 }
1438 else {
1439 // library does not support required props, do not include in list for
1440 // MFXEnumImplementations() or MFXCreateSession()
1441 implInfo->validImplIdx = -1;
1442 }
1443
1444 it++;
1445 }
1446
1447 // re-sort valid implementations according to priority rules in spec
1448 PrioritizeImplList();
1449
1450 m_bNeedUpdateValidImpls = false;
1451
1452 return MFX_ERR_NONE;
1453 }
1454
1455 // From specification section "oneVPL Session":
1456 //
1457 // When the dispatcher searches for the implementation, it uses the following priority rules
1458 // 1) Hardware implementation has priority over software implementation.
1459 // 2) General hardware implementation has priority over VSI hardware implementation.
1460 // 3) Highest API version has higher priority over lower API version.
1461 // 4) Search path priority: lower values = higher priority
1462 mfxStatus LoaderCtxVPL::PrioritizeImplList(void) {
1463 DISP_LOG_FUNCTION(&m_dispLog);
1464
1465 // API 2.6 introduced special search location ONEVPL_PRIORITY_PATH
1466 // Libs here always have highest priority = LIB_PRIORITY_SPECIAL
1467 // and are not sorted by the other priority rules,
1468 // so we move them to a temporary list before priority sorting and
1469 // then add back to the full implementation list at the end.
1470 std::list<ImplInfo *> implInfoListPriority;
1471 if (m_bPriorityPathEnabled) {
1472 auto it = m_implInfoList.begin();
1473 while (it != m_implInfoList.end()) {
1474 ImplInfo *implInfo = (*it);
1475
1476 auto it2 = std::next(it, 1);
1477 if (implInfo->libInfo->libPriority == LIB_PRIORITY_SPECIAL)
1478 implInfoListPriority.splice(implInfoListPriority.end(), m_implInfoList, it);
1479
1480 it = it2;
1481 }
1482 }
1483
1484 // stable sort - work from lowest to highest priority conditions
1485
1486 // 4 - sort by search path priority
1487 m_implInfoList.sort([](const ImplInfo *impl1, const ImplInfo *impl2) {
1488 // prioritize lowest value for libPriority (1 = highest priority)
1489 return (impl1->libInfo->libPriority < impl2->libInfo->libPriority);
1490 });
1491
1492 // 3 - sort by API version
1493 m_implInfoList.sort([](const ImplInfo *impl1, const ImplInfo *impl2) {
1494 mfxImplDescription *implDesc1 = (mfxImplDescription *)(impl1->implDesc);
1495 mfxImplDescription *implDesc2 = (mfxImplDescription *)(impl2->implDesc);
1496
1497 // prioritize greatest API version
1498 return (implDesc1->ApiVersion.Version > implDesc2->ApiVersion.Version);
1499 });
1500
1501 // 2 - sort by general HW vs. VSI
1502 m_implInfoList.sort([](const ImplInfo *impl1, const ImplInfo *impl2) {
1503 mfxImplDescription *implDesc1 = (mfxImplDescription *)(impl1->implDesc);
1504 mfxImplDescription *implDesc2 = (mfxImplDescription *)(impl2->implDesc);
1505
1506 // prioritize general HW accelerator over VSI (if none, i.e. SW, will be sorted in final step)
1507 return (implDesc1->AccelerationMode != MFX_ACCEL_MODE_VIA_HDDLUNITE &&
1508 implDesc2->AccelerationMode == MFX_ACCEL_MODE_VIA_HDDLUNITE);
1509 });
1510
1511 // 1 - sort by implementation type (HW > SW)
1512 m_implInfoList.sort([](const ImplInfo *impl1, const ImplInfo *impl2) {
1513 mfxImplDescription *implDesc1 = (mfxImplDescription *)(impl1->implDesc);
1514 mfxImplDescription *implDesc2 = (mfxImplDescription *)(impl2->implDesc);
1515
1516 // prioritize greatest Impl value (HW = 2, SW = 1)
1517 return (implDesc1->Impl > implDesc2->Impl);
1518 });
1519
1520 if (m_bPriorityPathEnabled) {
1521 // add back unsorted ONEVPL_PRIORITY_PATH libs to beginning of list
1522 m_implInfoList.splice(m_implInfoList.begin(), implInfoListPriority);
1523 }
1524
1525 // final pass - update index to match new priority order
1526 // validImplIdx will be the index associated with MFXEnumImplememntations()
1527 mfxI32 validImplIdx = 0;
1528 std::list<ImplInfo *>::iterator it = m_implInfoList.begin();
1529 while (it != m_implInfoList.end()) {
1530 ImplInfo *implInfo = (*it);
1531
1532 if (implInfo->validImplIdx >= 0) {
1533 implInfo->validImplIdx = validImplIdx++;
1534 }
1535 it++;
1536 }
1537
1538 return MFX_ERR_NONE;
1539 }
1540
1541 mfxStatus LoaderCtxVPL::CreateSession(mfxU32 idx, mfxSession *session) {
1542 DISP_LOG_FUNCTION(&m_dispLog);
1543
1544 mfxStatus sts = MFX_ERR_NONE;
1545
1546 // find library with given implementation index
1547 // list of valid implementations (and associated indices) is updated
1548 // every time a filter property is added/modified
1549 std::list<ImplInfo *>::iterator it = m_implInfoList.begin();
1550 while (it != m_implInfoList.end()) {
1551 ImplInfo *implInfo = (*it);
1552
1553 if (implInfo->validImplIdx == (mfxI32)idx) {
1554 LibInfo *libInfo = implInfo->libInfo;
1555 mfxU16 deviceID = 0;
1556
1557 // pass VendorImplID for this implementation (disambiguate if one
1558 // library contains multiple implementations)
1559 // NOTE: implDesc may be null in low latency mode (RT query not called)
1560 // so this value will not be available
1561 mfxImplDescription *implDesc = (mfxImplDescription *)(implInfo->implDesc);
1562 if (implDesc) {
1563 implInfo->vplParam.VendorImplID = implDesc->VendorImplID;
1564 }
1565
1566 // set any special parameters passed in via SetConfigProperty
1567 // if application did not specify accelerationMode, use default
1568 if (m_specialConfig.bIsSet_accelerationMode)
1569 implInfo->vplParam.AccelerationMode = m_specialConfig.accelerationMode;
1570
1571 #ifdef ONEVPL_EXPERIMENTAL
1572 if (m_specialConfig.bIsSet_DeviceCopy)
1573 implInfo->vplParam.DeviceCopy = m_specialConfig.DeviceCopy;
1574 #endif
1575
1576 // in low latency mode there was no implementation filtering, so check here
1577 // for minimum API version
1578 if (m_bLowLatency && m_specialConfig.bIsSet_ApiVersion) {
1579 if (implInfo->version.Version < m_specialConfig.ApiVersion.Version)
1580 return MFX_ERR_NOT_FOUND;
1581 }
1582
1583 mfxIMPL msdkImpl = 0;
1584 if (libInfo->libType == LibTypeMSDK) {
1585 if (implInfo->vplParam.AccelerationMode == MFX_ACCEL_MODE_VIA_D3D9)
1586 msdkImpl = libInfo->msdkCtx[implInfo->msdkImplIdx].m_msdkAdapterD3D9;
1587 else
1588 msdkImpl = libInfo->msdkCtx[implInfo->msdkImplIdx].m_msdkAdapter;
1589 }
1590
1591 // in low latency mode implDesc is not available, but application may set adapter number via DXGIAdapterIndex filter
1592 if (m_bLowLatency) {
1593 if (m_specialConfig.bIsSet_dxgiAdapterIdx && libInfo->libType == LibTypeVPL)
1594 implInfo->vplParam.VendorImplID = m_specialConfig.dxgiAdapterIdx;
1595 else if (m_specialConfig.bIsSet_dxgiAdapterIdx && libInfo->libType == LibTypeMSDK)
1596 msdkImpl = msdkImplTab[m_specialConfig.dxgiAdapterIdx];
1597 }
1598
1599 // add any extension buffers set via special filter properties
1600 std::vector<mfxExtBuffer *> extBufs;
1601
1602 // pass NumThread via mfxExtThreadsParam
1603 mfxExtThreadsParam extThreadsParam = {};
1604 if (m_specialConfig.bIsSet_NumThread) {
1605 DISP_LOG_MESSAGE(&m_dispLog,
1606 "message: extBuf enabled -- NumThread (%d)",
1607 m_specialConfig.NumThread);
1608
1609 extThreadsParam.Header.BufferId = MFX_EXTBUFF_THREADS_PARAM;
1610 extThreadsParam.Header.BufferSz = sizeof(mfxExtThreadsParam);
1611 extThreadsParam.NumThread = m_specialConfig.NumThread;
1612
1613 extBufs.push_back((mfxExtBuffer *)&extThreadsParam);
1614 }
1615
1616 // add extBufs provided via mfxConfig filter property "ExtBuffer"
1617 if (m_specialConfig.bIsSet_ExtBuffer) {
1618 for (auto extBuf : m_specialConfig.ExtBuffers) {
1619 extBufs.push_back((mfxExtBuffer *)extBuf);
1620 }
1621 }
1622
1623 // attach vector of extBufs to mfxInitializationParam
1624 implInfo->vplParam.NumExtParam = static_cast<mfxU16>(extBufs.size());
1625 implInfo->vplParam.ExtParam =
1626 (implInfo->vplParam.NumExtParam ? extBufs.data() : nullptr);
1627
1628 // initialize this library via MFXInitialize or else fail
1629 // (specify full path to library)
1630 sts = MFXInitEx2(implInfo->version,
1631 implInfo->vplParam,
1632 msdkImpl,
1633 session,
1634 &deviceID,
1635 (CHAR_TYPE *)libInfo->libNameFull.c_str());
1636
1637 // optionally call MFXSetHandle() if present via SetConfigProperty
1638 if (sts == MFX_ERR_NONE && m_specialConfig.bIsSet_deviceHandleType &&
1639 m_specialConfig.bIsSet_deviceHandle && m_specialConfig.deviceHandleType &&
1640 m_specialConfig.deviceHandle) {
1641 sts = MFXVideoCORE_SetHandle(*session,
1642 m_specialConfig.deviceHandleType,
1643 m_specialConfig.deviceHandle);
1644 }
1645
1646 return sts;
1647 }
1648 it++;
1649 }
1650
1651 // invalid idx
1652 return MFX_ERR_NOT_FOUND;
1653 }
1654
1655 ConfigCtxVPL *LoaderCtxVPL::AddConfigFilter() {
1656 DISP_LOG_FUNCTION(&m_dispLog);
1657
1658 // create new config filter context and add
1659 // to list associated with this loader
1660 std::unique_ptr<ConfigCtxVPL> configCtx;
1661 try {
1662 configCtx.reset(new ConfigCtxVPL{});
1663 }
1664 catch (...) {
1665 return nullptr;
1666 }
1667
1668 ConfigCtxVPL *config = (ConfigCtxVPL *)(configCtx.release());
1669 config->m_parentLoader = this;
1670
1671 m_configCtxList.push_back(config);
1672
1673 return config;
1674 }
1675
1676 mfxStatus LoaderCtxVPL::FreeConfigFilters() {
1677 DISP_LOG_FUNCTION(&m_dispLog);
1678
1679 std::list<ConfigCtxVPL *>::iterator it = m_configCtxList.begin();
1680
1681 while (it != m_configCtxList.end()) {
1682 ConfigCtxVPL *config = (*it);
1683 if (config)
1684 delete config;
1685 it++;
1686 }
1687
1688 return MFX_ERR_NONE;
1689 }
1690
1691 mfxStatus LoaderCtxVPL::InitDispatcherLog() {
1692 std::string strLogEnabled, strLogFile;
1693
1694 #if defined(_WIN32) || defined(_WIN64)
1695 DWORD err;
1696
1697 char logEnabled[MAX_VPL_SEARCH_PATH] = "";
1698 err = GetEnvironmentVariableA("ONEVPL_DISPATCHER_LOG", logEnabled, MAX_VPL_SEARCH_PATH);
1699 if (err == 0 || err >= MAX_VPL_SEARCH_PATH)
1700 return MFX_ERR_UNSUPPORTED; // environment variable not defined or string too long
1701
1702 strLogEnabled = logEnabled;
1703
1704 char logFile[MAX_VPL_SEARCH_PATH] = "";
1705 err = GetEnvironmentVariableA("ONEVPL_DISPATCHER_LOG_FILE", logFile, MAX_VPL_SEARCH_PATH);
1706 if (err == 0 || err >= MAX_VPL_SEARCH_PATH) {
1707 // nothing to do - strLogFile is an empty string
1708 }
1709 else {
1710 strLogFile = logFile;
1711 }
1712
1713 #else
1714 const char *logEnabled = std::getenv("ONEVPL_DISPATCHER_LOG");
1715 if (!logEnabled)
1716 return MFX_ERR_UNSUPPORTED;
1717
1718 strLogEnabled = logEnabled;
1719
1720 const char *logFile = std::getenv("ONEVPL_DISPATCHER_LOG_FILE");
1721 if (logFile)
1722 strLogFile = logFile;
1723 #endif
1724
1725 if (strLogEnabled != "ON")
1726 return MFX_ERR_UNSUPPORTED;
1727
1728 // currently logLevel is either 0 or non-zero
1729 // additional levels will be added with future API updates
1730 return m_dispLog.Init(1, strLogFile);
1731 }
1732
1733 // public function to return logger object
1734 // allows logging from C API functions outside of loaderCtx
1735 DispatcherLogVPL *LoaderCtxVPL::GetLogger() {
1736 return &m_dispLog;
1737 }