Debian Codegraph @

xbmc/games/addons/GameClient.cpp

raw
1 /*
2 * Copyright (C) 2012-2018 Team Kodi
3 * This file is part of Kodi - https://kodi.tv
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSES/README.md for more information.
7 */
8
9 #include "GameClient.h"
10
11 #include "FileItem.h"
12 #include "GameClientCallbacks.h"
13 #include "GameClientInGameSaves.h"
14 #include "GameClientProperties.h"
15 #include "GameClientTranslator.h"
16 #include "ServiceBroker.h"
17 #include "URL.h"
18 #include "addons/AddonManager.h"
19 #include "addons/BinaryAddonCache.h"
20 #include "addons/addoninfo/AddonInfo.h"
21 #include "addons/addoninfo/AddonType.h"
22 #include "filesystem/Directory.h"
23 #include "filesystem/SpecialProtocol.h"
24 #include "games/GameServices.h"
25 #include "games/addons/cheevos/GameClientCheevos.h"
26 #include "games/addons/input/GameClientInput.h"
27 #include "games/addons/streams/GameClientStreams.h"
28 #include "games/addons/streams/IGameClientStream.h"
29 #include "guilib/GUIWindowManager.h"
30 #include "guilib/LocalizeStrings.h"
31 #include "guilib/WindowIDs.h"
32 #include "input/actions/Action.h"
33 #include "input/actions/ActionIDs.h"
34 #include "messaging/ApplicationMessenger.h"
35 #include "messaging/helpers/DialogOKHelper.h"
36 #include "utils/FileUtils.h"
37 #include "utils/StringUtils.h"
38 #include "utils/URIUtils.h"
39 #include "utils/log.h"
40
41 #include <algorithm>
42 #include <cstring>
43 #include <iterator>
44 #include <memory>
45 #include <mutex>
46 #include <utility>
47
48 using namespace KODI;
49 using namespace GAME;
50
51 #define EXTENSION_SEPARATOR "|"
52 #define EXTENSION_WILDCARD "*"
53
54 #define GAME_PROPERTY_EXTENSIONS "extensions"
55 #define GAME_PROPERTY_SUPPORTS_VFS "supports_vfs"
56 #define GAME_PROPERTY_SUPPORTS_STANDALONE "supports_standalone"
57
58 // --- NormalizeExtension ------------------------------------------------------
59
60 namespace
61 {
62 /*
63 * \brief Convert to lower case and canonicalize with a leading "."
64 */
65 std::string NormalizeExtension(const std::string& strExtension)
66 {
67 std::string ext = strExtension;
68
69 if (!ext.empty() && ext != EXTENSION_WILDCARD)
70 {
71 StringUtils::ToLower(ext);
72
73 if (ext[0] != '.')
74 ext.insert(0, ".");
75 }
76
77 return ext;
78 }
79 } // namespace
80
81 // --- CGameClient -------------------------------------------------------------
82
83 CGameClient::CGameClient(const ADDON::AddonInfoPtr& addonInfo)
84 : CAddonDll(addonInfo, ADDON::AddonType::GAMEDLL),
85 m_subsystems(CGameClientSubsystem::CreateSubsystems(*this, *m_ifc.game, m_critSection)),
86 m_bIsPlaying(false)
87 {
88 using namespace ADDON;
89
90 std::vector<std::string> extensions = StringUtils::Split(
91 Type(AddonType::GAMEDLL)->GetValue(GAME_PROPERTY_EXTENSIONS).asString(), EXTENSION_SEPARATOR);
92 std::transform(extensions.begin(), extensions.end(),
93 std::inserter(m_extensions, m_extensions.begin()), NormalizeExtension);
94
95 // Check for wildcard extension
96 if (m_extensions.find(EXTENSION_WILDCARD) != m_extensions.end())
97 {
98 m_bSupportsAllExtensions = true;
99 m_extensions.clear();
100 }
101
102 m_bSupportsVFS =
103 addonInfo->Type(AddonType::GAMEDLL)->GetValue(GAME_PROPERTY_SUPPORTS_VFS).asBoolean();
104 m_bSupportsStandalone =
105 addonInfo->Type(AddonType::GAMEDLL)->GetValue(GAME_PROPERTY_SUPPORTS_STANDALONE).asBoolean();
106
107 std::tie(m_emulatorName, m_platforms) = ParseLibretroName(Name());
108 }
109
110 CGameClient::~CGameClient(void)
111 {
112 CloseFile();
113 CGameClientSubsystem::DestroySubsystems(m_subsystems);
114 }
115
116 std::string CGameClient::LibPath() const
117 {
118 // If the game client requires a proxy, load its DLL instead
119 if (m_ifc.game->props->proxy_dll_count > 0)
120 return GetDllPath(m_ifc.game->props->proxy_dll_paths[0]);
121
122 return CAddonDll::LibPath();
123 }
124
125 ADDON::AddonPtr CGameClient::GetRunningInstance() const
126 {
127 using namespace ADDON;
128
129 CBinaryAddonCache& addonCache = CServiceBroker::GetBinaryAddonCache();
130 return addonCache.GetAddonInstance(ID(), Type());
131 }
132
133 bool CGameClient::SupportsPath() const
134 {
135 return !m_extensions.empty() || m_bSupportsAllExtensions;
136 }
137
138 bool CGameClient::IsExtensionValid(const std::string& strExtension) const
139 {
140 if (strExtension.empty())
141 return false;
142
143 if (SupportsAllExtensions())
144 return true;
145
146 return m_extensions.find(NormalizeExtension(strExtension)) != m_extensions.end();
147 }
148
149 bool CGameClient::Initialize(void)
150 {
151 using namespace XFILE;
152
153 // Ensure user profile directory exists for add-on
154 if (!CDirectory::Exists(Profile()))
155 CDirectory::Create(Profile());
156
157 // Ensure directory exists for savestates
158 const CGameServices& gameServices = CServiceBroker::GetGameServices();
159 std::string savestatesDir = URIUtils::AddFileToFolder(gameServices.GetSavestatesFolder(), ID());
160 if (!CDirectory::Exists(savestatesDir))
161 CDirectory::Create(savestatesDir);
162
163 if (!AddonProperties().InitializeProperties())
164 return false;
165
166 m_ifc.game->toKodi->kodiInstance = this;
167 m_ifc.game->toKodi->CloseGame = cb_close_game;
168 m_ifc.game->toKodi->OpenStream = cb_open_stream;
169 m_ifc.game->toKodi->GetStreamBuffer = cb_get_stream_buffer;
170 m_ifc.game->toKodi->AddStreamData = cb_add_stream_data;
171 m_ifc.game->toKodi->ReleaseStreamBuffer = cb_release_stream_buffer;
172 m_ifc.game->toKodi->CloseStream = cb_close_stream;
173 m_ifc.game->toKodi->HwGetProcAddress = cb_hw_get_proc_address;
174 m_ifc.game->toKodi->InputEvent = cb_input_event;
175
176 memset(m_ifc.game->toAddon, 0, sizeof(KodiToAddonFuncTable_Game));
177
178 if (CreateInstance(&m_ifc) == ADDON_STATUS_OK)
179 {
180 Input().Initialize();
181 LogAddonProperties();
182 return true;
183 }
184
185 return false;
186 }
187
188 void CGameClient::Unload()
189 {
190 Input().Deinitialize();
191
192 DestroyInstance(&m_ifc);
193 }
194
195 bool CGameClient::OpenFile(const CFileItem& file,
196 RETRO::IStreamManager& streamManager,
197 IGameInputCallback* input)
198 {
199 // Check if we should open in standalone mode
200 if (file.GetPath().empty())
201 return false;
202
203 // Some cores "succeed" to load the file even if it doesn't exist
204 if (!CFileUtils::Exists(file.GetPath()))
205 {
206
207 // Failed to play game
208 // The required files can't be found.
209 MESSAGING::HELPERS::ShowOKDialogText(CVariant{35210}, CVariant{g_localizeStrings.Get(35219)});
210 return false;
211 }
212
213 // Resolve special:// URLs
214 CURL translatedUrl(CSpecialProtocol::TranslatePath(file.GetPath()));
215
216 // Remove file:// from URLs if add-on doesn't support VFS
217 if (!m_bSupportsVFS)
218 {
219 if (translatedUrl.GetProtocol() == "file")
220 translatedUrl.SetProtocol("");
221 }
222
223 std::string path = translatedUrl.Get();
224 CLog::Log(LOGDEBUG, "GameClient: Loading {}", CURL::GetRedacted(path));
225
226 std::unique_lock<CCriticalSection> lock(m_critSection);
227
228 if (!Initialized())
229 return false;
230
231 CloseFile();
232
233 GAME_ERROR error = GAME_ERROR_FAILED;
234
235 // Loading the game might require the stream subsystem to be initialized
236 Streams().Initialize(streamManager);
237
238 try
239 {
240 LogError(error = m_ifc.game->toAddon->LoadGame(m_ifc.game, path.c_str()), "LoadGame()");
241 }
242 catch (...)
243 {
244 LogException("LoadGame()");
245 }
246
247 if (error != GAME_ERROR_NO_ERROR)
248 {
249 NotifyError(error);
250 Streams().Deinitialize();
251 return false;
252 }
253
254 if (!InitializeGameplay(file.GetPath(), streamManager, input))
255 {
256 Streams().Deinitialize();
257 return false;
258 }
259
260 return true;
261 }
262
263 bool CGameClient::OpenStandalone(RETRO::IStreamManager& streamManager, IGameInputCallback* input)
264 {
265 CLog::Log(LOGDEBUG, "GameClient: Loading {} in standalone mode", ID());
266
267 std::unique_lock<CCriticalSection> lock(m_critSection);
268
269 if (!Initialized())
270 return false;
271
272 CloseFile();
273
274 GAME_ERROR error = GAME_ERROR_FAILED;
275
276 // Loading the game might require the stream subsystem to be initialized
277 Streams().Initialize(streamManager);
278
279 try
280 {
281 LogError(error = m_ifc.game->toAddon->LoadStandalone(m_ifc.game), "LoadStandalone()");
282 }
283 catch (...)
284 {
285 LogException("LoadStandalone()");
286 }
287
288 if (error != GAME_ERROR_NO_ERROR)
289 {
290 NotifyError(error);
291 Streams().Deinitialize();
292 return false;
293 }
294
295 if (!InitializeGameplay("", streamManager, input))
296 {
297 Streams().Deinitialize();
298 return false;
299 }
300
301 return true;
302 }
303
304 bool CGameClient::InitializeGameplay(const std::string& gamePath,
305 RETRO::IStreamManager& streamManager,
306 IGameInputCallback* input)
307 {
308 if (LoadGameInfo())
309 {
310 Input().Start(input);
311
312 m_bIsPlaying = true;
313 m_gamePath = gamePath;
314 m_input = input;
315
316 m_inGameSaves = std::make_unique<CGameClientInGameSaves>(this, m_ifc.game);
317 m_inGameSaves->Load();
318
319 return true;
320 }
321
322 return false;
323 }
324
325 bool CGameClient::LoadGameInfo()
326 {
327 bool bRequiresGameLoop;
328 try
329 {
330 bRequiresGameLoop = m_ifc.game->toAddon->RequiresGameLoop(m_ifc.game);
331 }
332 catch (...)
333 {
334 LogException("RequiresGameLoop()");
335 return false;
336 }
337
338 // Get information about system timings
339 // Can be called only after retro_load_game()
340 game_system_timing timingInfo = {};
341
342 bool bSuccess = false;
343 try
344 {
345 bSuccess =
346 LogError(m_ifc.game->toAddon->GetGameTiming(m_ifc.game, &timingInfo), "GetGameTiming()");
347 }
348 catch (...)
349 {
350 LogException("GetGameTiming()");
351 }
352
353 if (!bSuccess)
354 {
355 CLog::Log(LOGERROR, "GameClient: Failed to get timing info");
356 return false;
357 }
358
359 GAME_REGION region;
360 try
361 {
362 region = m_ifc.game->toAddon->GetRegion(m_ifc.game);
363 }
364 catch (...)
365 {
366 LogException("GetRegion()");
367 return false;
368 }
369
370 size_t serializeSize;
371 try
372 {
373 serializeSize = m_ifc.game->toAddon->SerializeSize(m_ifc.game);
374 }
375 catch (...)
376 {
377 LogException("SerializeSize()");
378 return false;
379 }
380
381 CLog::Log(LOGINFO, "GAME: ---------------------------------------");
382 CLog::Log(LOGINFO, "GAME: Game loop: {}", bRequiresGameLoop ? "true" : "false");
383 CLog::Log(LOGINFO, "GAME: FPS: {:f}", timingInfo.fps);
384 CLog::Log(LOGINFO, "GAME: Sample Rate: {:f}", timingInfo.sample_rate);
385 CLog::Log(LOGINFO, "GAME: Region: {}", CGameClientTranslator::TranslateRegion(region));
386 CLog::Log(LOGINFO, "GAME: Savestate size: {}", serializeSize);
387 CLog::Log(LOGINFO, "GAME: ---------------------------------------");
388
389 m_bRequiresGameLoop = bRequiresGameLoop;
390 m_serializeSize = serializeSize;
391 m_framerate = timingInfo.fps;
392 m_samplerate = timingInfo.sample_rate;
393 m_region = region;
394
395 return true;
396 }
397
398 void CGameClient::NotifyError(GAME_ERROR error)
399 {
400 std::string missingResource;
401
402 if (error == GAME_ERROR_RESTRICTED)
403 missingResource = GetMissingResource();
404
405 if (!missingResource.empty())
406 {
407 // Failed to play game
408 // This game requires the following add-on: %s
409 MESSAGING::HELPERS::ShowOKDialogText(
410 CVariant{35210},
411 CVariant{StringUtils::Format(g_localizeStrings.Get(35211), missingResource)});
412 }
413 else
414 {
415 // Failed to play game
416 // The emulator "%s" had an internal error.
417 MESSAGING::HELPERS::ShowOKDialogText(
418 CVariant{35210}, CVariant{StringUtils::Format(g_localizeStrings.Get(35213), Name())});
419 }
420 }
421
422 std::string CGameClient::GetMissingResource()
423 {
424 using namespace ADDON;
425
426 std::string strAddonId;
427
428 const auto& dependencies = GetDependencies();
429 for (auto it = dependencies.begin(); it != dependencies.end(); ++it)
430 {
431 const std::string& strDependencyId = it->id;
432 if (StringUtils::StartsWith(strDependencyId, "resource.games"))
433 {
434 AddonPtr addon;
435 const bool bInstalled =
436 CServiceBroker::GetAddonMgr().GetAddon(strDependencyId, addon, OnlyEnabled::CHOICE_YES);
437 if (!bInstalled)
438 {
439 strAddonId = strDependencyId;
440 break;
441 }
442 }
443 }
444
445 return strAddonId;
446 }
447
448 void CGameClient::Reset()
449 {
450 std::unique_lock<CCriticalSection> lock(m_critSection);
451
452 if (m_bIsPlaying)
453 {
454 try
455 {
456 LogError(m_ifc.game->toAddon->Reset(m_ifc.game), "Reset()");
457 }
458 catch (...)
459 {
460 LogException("Reset()");
461 }
462 }
463 }
464
465 void CGameClient::CloseFile()
466 {
467 std::unique_lock<CCriticalSection> lock(m_critSection);
468
469 if (m_bIsPlaying)
470 {
471 m_inGameSaves->Save();
472 m_inGameSaves.reset();
473
474 m_bIsPlaying = false;
475 m_gamePath.clear();
476 m_serializeSize = 0;
477 m_input = nullptr;
478
479 Input().Stop();
480
481 try
482 {
483 LogError(m_ifc.game->toAddon->UnloadGame(m_ifc.game), "UnloadGame()");
484 }
485 catch (...)
486 {
487 LogException("UnloadGame()");
488 }
489
490 Streams().Deinitialize();
491 }
492 }
493
494 void CGameClient::RunFrame()
495 {
496 IGameInputCallback* input;
497
498 {
499 std::unique_lock<CCriticalSection> lock(m_critSection);
500 input = m_input;
501 }
502
503 if (input)
504 input->PollInput();
505
506 std::unique_lock<CCriticalSection> lock(m_critSection);
507
508 if (m_bIsPlaying)
509 {
510 try
511 {
512 LogError(m_ifc.game->toAddon->RunFrame(m_ifc.game), "RunFrame()");
513 }
514 catch (...)
515 {
516 LogException("RunFrame()");
517 }
518 }
519 }
520
521 bool CGameClient::Serialize(uint8_t* data, size_t size)
522 {
523 if (data == nullptr || size == 0)
524 return false;
525
526 std::unique_lock<CCriticalSection> lock(m_critSection);
527
528 bool bSuccess = false;
529 if (m_bIsPlaying)
530 {
531 try
532 {
533 bSuccess = LogError(m_ifc.game->toAddon->Serialize(m_ifc.game, data, size), "Serialize()");
534 }
535 catch (...)
536 {
537 LogException("Serialize()");
538 }
539 }
540
541 return bSuccess;
542 }
543
544 bool CGameClient::Deserialize(const uint8_t* data, size_t size)
545 {
546 if (data == nullptr || size == 0)
547 return false;
548
549 std::unique_lock<CCriticalSection> lock(m_critSection);
550
551 bool bSuccess = false;
552 if (m_bIsPlaying)
553 {
554 try
555 {
556 bSuccess =
557 LogError(m_ifc.game->toAddon->Deserialize(m_ifc.game, data, size), "Deserialize()");
558 }
559 catch (...)
560 {
561 LogException("Deserialize()");
562 }
563 }
564
565 return bSuccess;
566 }
567
568 void CGameClient::LogAddonProperties(void) const
569 {
570 CLog::Log(LOGINFO, "GAME: ------------------------------------");
571 CLog::Log(LOGINFO, "GAME: Loaded DLL for {}", ID());
572 CLog::Log(LOGINFO, "GAME: Client: {}", Name());
573 CLog::Log(LOGINFO, "GAME: Version: {}", Version().asString());
574 CLog::Log(LOGINFO, "GAME: Valid extensions: {}", StringUtils::Join(m_extensions, " "));
575 CLog::Log(LOGINFO, "GAME: Supports VFS: {}", m_bSupportsVFS);
576 CLog::Log(LOGINFO, "GAME: Supports standalone: {}", m_bSupportsStandalone);
577 CLog::Log(LOGINFO, "GAME: ------------------------------------");
578 }
579
580 bool CGameClient::LogError(GAME_ERROR error, const char* strMethod) const
581 {
582 if (error != GAME_ERROR_NO_ERROR)
583 {
584 CLog::Log(LOGERROR, "GAME - {} - addon '{}' returned an error: {}", strMethod, ID(),
585 CGameClientTranslator::ToString(error));
586 return false;
587 }
588 return true;
589 }
590
591 void CGameClient::LogException(const char* strFunctionName) const
592 {
593 CLog::Log(LOGERROR, "GAME: exception caught while trying to call '{}' on add-on {}",
594 strFunctionName, ID());
595 CLog::Log(LOGERROR, "Please contact the developer of this add-on: {}", Author());
596 }
597
598 void CGameClient::cb_close_game(KODI_HANDLE kodiInstance)
599 {
600 CServiceBroker::GetAppMessenger()->PostMsg(TMSG_GUI_ACTION, WINDOW_INVALID, -1,
601 static_cast<void*>(new CAction(ACTION_STOP)));
602 }
603
604 KODI_GAME_STREAM_HANDLE CGameClient::cb_open_stream(KODI_HANDLE kodiInstance,
605 const game_stream_properties* properties)
606 {
607 if (properties == nullptr)
608 return nullptr;
609
610 CGameClient* gameClient = static_cast<CGameClient*>(kodiInstance);
611 if (gameClient == nullptr)
612 return nullptr;
613
614 return gameClient->Streams().OpenStream(*properties);
615 }
616
617 bool CGameClient::cb_get_stream_buffer(KODI_HANDLE kodiInstance,
618 KODI_GAME_STREAM_HANDLE stream,
619 unsigned int width,
620 unsigned int height,
621 game_stream_buffer* buffer)
622 {
623 if (buffer == nullptr)
624 return false;
625
626 IGameClientStream* gameClientStream = static_cast<IGameClientStream*>(stream);
627 if (gameClientStream == nullptr)
628 return false;
629
630 return gameClientStream->GetBuffer(width, height, *buffer);
631 }
632
633 void CGameClient::cb_add_stream_data(KODI_HANDLE kodiInstance,
634 KODI_GAME_STREAM_HANDLE stream,
635 const game_stream_packet* packet)
636 {
637 if (packet == nullptr)
638 return;
639
640 IGameClientStream* gameClientStream = static_cast<IGameClientStream*>(stream);
641 if (gameClientStream == nullptr)
642 return;
643
644 gameClientStream->AddData(*packet);
645 }
646
647 void CGameClient::cb_release_stream_buffer(KODI_HANDLE kodiInstance,
648 KODI_GAME_STREAM_HANDLE stream,
649 game_stream_buffer* buffer)
650 {
651 if (buffer == nullptr)
652 return;
653
654 IGameClientStream* gameClientStream = static_cast<IGameClientStream*>(stream);
655 if (gameClientStream == nullptr)
656 return;
657
658 gameClientStream->ReleaseBuffer(*buffer);
659 }
660
661 void CGameClient::cb_close_stream(KODI_HANDLE kodiInstance, KODI_GAME_STREAM_HANDLE stream)
662 {
663 CGameClient* gameClient = static_cast<CGameClient*>(kodiInstance);
664 if (gameClient == nullptr)
665 return;
666
667 IGameClientStream* gameClientStream = static_cast<IGameClientStream*>(stream);
668 if (gameClientStream == nullptr)
669 return;
670
671 gameClient->Streams().CloseStream(gameClientStream);
672 }
673
674 game_proc_address_t CGameClient::cb_hw_get_proc_address(KODI_HANDLE kodiInstance, const char* sym)
675 {
676 CGameClient* gameClient = static_cast<CGameClient*>(kodiInstance);
677 if (!gameClient)
678 return nullptr;
679
680 //! @todo
681 return nullptr;
682 }
683
684 bool CGameClient::cb_input_event(KODI_HANDLE kodiInstance, const game_input_event* event)
685 {
686 CGameClient* gameClient = static_cast<CGameClient*>(kodiInstance);
687 if (!gameClient)
688 return false;
689
690 if (event == nullptr)
691 return false;
692
693 return gameClient->Input().ReceiveInputEvent(*event);
694 }
695
696 std::pair<std::string, std::string> CGameClient::ParseLibretroName(const std::string& addonName)
697 {
698 std::string emulatorName;
699 std::string platforms;
700
701 // libretro has a de-facto standard for naming their cores. If the
702 // core emulates one or more platforms, then the format is:
703 //
704 // "Platforms (Emulator name)"
705 //
706 // Otherwise, the format is just the name with no platforms:
707 //
708 // "Emulator name"
709 //
710 // The has been observed for all 130 cores we package.
711 //
712 size_t beginPos = addonName.find('(');
713 size_t endPos = addonName.find(')');
714
715 if (beginPos != std::string::npos && endPos != std::string::npos && beginPos < endPos)
716 {
717 emulatorName = addonName.substr(beginPos + 1, endPos - beginPos - 1);
718 platforms = addonName.substr(0, beginPos);
719 StringUtils::TrimRight(platforms);
720 }
721 else
722 {
723 emulatorName = addonName;
724 platforms.clear();
725 }
726
727 return std::make_pair(emulatorName, platforms);
728 }