summaryrefslogtreecommitdiff
path: root/Source/Core/Common/LibusbContext.cpp
blob: a2ed128200c2ec4b50608d54f8af10117bec3573 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Copyright 2017 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

#include <libusb.h>
#include <memory>
#include <mutex>

#include "Common/LibusbContext.h"
#include "Common/MsgHandler.h"

namespace LibusbContext
{
static std::shared_ptr<libusb_context> s_libusb_context;
static std::once_flag s_context_initialized;

static libusb_context* Create()
{
  libusb_context* context;
  const int ret = libusb_init(&context);
  if (ret < LIBUSB_SUCCESS)
  {
    bool is_windows = false;
#ifdef _WIN32
    is_windows = true;
#endif
    if (is_windows && ret == LIBUSB_ERROR_NOT_FOUND)
      PanicAlertT("Failed to initialize libusb because usbdk is not installed.");
    else
      PanicAlertT("Failed to initialize libusb: %s", libusb_error_name(ret));
    return nullptr;
  }
  return context;
}

std::shared_ptr<libusb_context> Get()
{
  std::call_once(s_context_initialized, []() {
    s_libusb_context.reset(Create(), [](auto* context) {
      if (context != nullptr)
        libusb_exit(context);
    });
  });
  return s_libusb_context;
}
}