LedOutput.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. #include "LedOutput.h"
  2. #include <algorithm>
  3. #include <chrono>
  4. #include <cerrno>
  5. #include <netdb.h>
  6. #include <netinet/tcp.h>
  7. #include <poll.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #include "WallpaperEngine/Logging/Log.h"
  11. #include "WallpaperEngine/Logging/ThreadGuard.h"
  12. namespace WallpaperEngine::Led {
  13. using namespace std::chrono_literals;
  14. namespace {
  15. struct Socket {
  16. int fd = -1;
  17. ~Socket () {
  18. if (this->fd >= 0) {
  19. close (this->fd);
  20. }
  21. }
  22. bool open (const std::string& host, const uint16_t port) {
  23. addrinfo hints = {};
  24. addrinfo* found = nullptr;
  25. hints.ai_family = AF_UNSPEC;
  26. hints.ai_socktype = SOCK_STREAM;
  27. if (getaddrinfo (host.c_str (), std::to_string (port).c_str (), &hints, &found) != 0) {
  28. return false;
  29. }
  30. for (const auto* it = found; it != nullptr && this->fd < 0; it = it->ai_next) {
  31. const int candidate
  32. = socket (it->ai_family, it->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC, it->ai_protocol);
  33. if (candidate < 0) {
  34. continue;
  35. }
  36. bool connected = connect (candidate, it->ai_addr, it->ai_addrlen) == 0;
  37. if (!connected && errno == EINPROGRESS) {
  38. pollfd wait = { .fd = candidate, .events = POLLOUT };
  39. int error = 0;
  40. socklen_t length = sizeof (error);
  41. connected = poll (&wait, 1, 2000) == 1
  42. && getsockopt (candidate, SOL_SOCKET, SO_ERROR, &error, &length) == 0 && error == 0;
  43. }
  44. if (connected) {
  45. this->fd = candidate;
  46. } else {
  47. close (candidate);
  48. }
  49. }
  50. freeaddrinfo (found);
  51. if (this->fd >= 0) {
  52. const int on = 1;
  53. setsockopt (this->fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof (on));
  54. }
  55. return this->fd >= 0;
  56. }
  57. [[nodiscard]] bool writeAll (std::span<const uint8_t> bytes) const {
  58. while (!bytes.empty ()) {
  59. const ssize_t sent = send (this->fd, bytes.data (), bytes.size (), MSG_NOSIGNAL);
  60. if (sent < 0 && errno == EINTR) {
  61. continue;
  62. }
  63. if (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
  64. pollfd wait = { .fd = this->fd, .events = POLLOUT };
  65. if (poll (&wait, 1, 2000) != 1) {
  66. return false;
  67. }
  68. continue;
  69. }
  70. if (sent <= 0) {
  71. return false;
  72. }
  73. bytes = bytes.subspan (static_cast<size_t> (sent));
  74. }
  75. return true;
  76. }
  77. [[nodiscard]] bool readAll (std::span<uint8_t> bytes, const int timeoutMs) const {
  78. while (!bytes.empty ()) {
  79. pollfd wait = { .fd = this->fd, .events = POLLIN };
  80. if (poll (&wait, 1, timeoutMs) != 1) {
  81. return false;
  82. }
  83. const ssize_t got = recv (this->fd, bytes.data (), bytes.size (), 0);
  84. if (got < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) {
  85. continue;
  86. }
  87. if (got <= 0) {
  88. return false;
  89. }
  90. bytes = bytes.subspan (static_cast<size_t> (got));
  91. }
  92. return true;
  93. }
  94. [[nodiscard]] bool readable () const {
  95. pollfd wait = { .fd = this->fd, .events = POLLIN };
  96. return poll (&wait, 1, 0) == 1;
  97. }
  98. bool readPacket (OpenRgb::Header& header, std::vector<uint8_t>& payload, const int timeoutMs) const {
  99. uint8_t raw[OpenRgb::kHeaderSize];
  100. if (!this->readAll (raw, timeoutMs)) {
  101. return false;
  102. }
  103. const auto parsed = OpenRgb::parseHeader (raw);
  104. if (!parsed || parsed->size > (1u << 24)) {
  105. return false;
  106. }
  107. header = *parsed;
  108. payload.resize (header.size);
  109. return this->readAll (payload, 5000);
  110. }
  111. };
  112. struct Target {
  113. OpenRgb::Device device;
  114. std::vector<LedPixel> layout;
  115. std::vector<uint8_t> last;
  116. std::chrono::steady_clock::time_point lastSent;
  117. };
  118. }
  119. LedOutput::~LedOutput () { this->stop (); }
  120. void LedOutput::start (const Options& options) {
  121. if (this->m_running.exchange (true)) {
  122. return;
  123. }
  124. this->m_options = options;
  125. this->m_thread = std::thread ([this] { Logging::guardThread ("LED output", [this] { this->run (); }); });
  126. }
  127. void LedOutput::stop () {
  128. if (!this->m_running.exchange (false)) {
  129. return;
  130. }
  131. this->m_wake.notify_all ();
  132. if (this->m_thread.joinable ()) {
  133. this->m_thread.join ();
  134. }
  135. }
  136. void LedOutput::submit (const std::span<const uint8_t> rgb) {
  137. if (!this->m_running.load () || rgb.size () != kFrameBytes) {
  138. return;
  139. }
  140. {
  141. const Debugging::LockGuard lock (this->m_mutex);
  142. this->m_frame.assign (rgb.begin (), rgb.end ());
  143. this->m_fresh = true;
  144. }
  145. this->m_wake.notify_one ();
  146. }
  147. void LedOutput::run () {
  148. bool reported = false;
  149. while (this->m_running.load ()) {
  150. if (this->connectAndServe (this->m_options)) {
  151. reported = false;
  152. } else if (!reported) {
  153. sLog.error (
  154. "LED output: no OpenRGB server at ", this->m_options.host, ":", this->m_options.port,
  155. ", trying again every few seconds (start OpenRGB with --server)"
  156. );
  157. reported = true;
  158. }
  159. Debugging::UniqueLock lock (this->m_mutex);
  160. this->m_wake.wait_for (lock, 3s, [this] () LWE_REQUIRES (this->m_mutex) { return !this->m_running.load (); });
  161. }
  162. }
  163. bool LedOutput::connectAndServe (const Options& options) {
  164. Socket socket;
  165. if (!socket.open (options.host, options.port)) {
  166. return false;
  167. }
  168. std::vector<uint8_t> payload;
  169. OpenRgb::Header header;
  170. uint32_t protocol = 0;
  171. {
  172. std::vector<uint8_t> ask;
  173. OpenRgb::put32 (ask, OpenRgb::kProtocolVersion);
  174. if (!socket.writeAll (OpenRgb::makePacket (0, OpenRgb::RequestProtocolVersion, ask))) {
  175. return false;
  176. }
  177. if (socket.readPacket (header, payload, 1500) && header.id == OpenRgb::RequestProtocolVersion
  178. && payload.size () >= 4) {
  179. const uint32_t server
  180. = payload[0] | (payload[1] << 8) | (payload[2] << 16) | (static_cast<uint32_t> (payload[3]) << 24);
  181. protocol = std::min (server, OpenRgb::kProtocolVersion);
  182. }
  183. }
  184. if (protocol < OpenRgb::kProtocolVersion) {
  185. if (!this->m_protocolReported) {
  186. sLog.error (
  187. "LED output: the OpenRGB server speaks protocol ", protocol, ", needs ", OpenRgb::kProtocolVersion,
  188. " (OpenRGB 0.9 or newer)"
  189. );
  190. this->m_protocolReported = true;
  191. }
  192. return true;
  193. }
  194. this->m_protocolReported = false;
  195. const std::string name = "linux-wallpaperengine";
  196. if (!socket.writeAll (
  197. OpenRgb::makePacket (
  198. 0, OpenRgb::SetClientName, { reinterpret_cast<const uint8_t*> (name.c_str ()), name.size () + 1 }
  199. )
  200. )) {
  201. return false;
  202. }
  203. std::vector<Target> targets;
  204. const auto listDevices = [&] () -> bool {
  205. targets.clear ();
  206. if (!socket.writeAll (OpenRgb::makePacket (0, OpenRgb::RequestControllerCount))) {
  207. return false;
  208. }
  209. do {
  210. if (!socket.readPacket (header, payload, 3000)) {
  211. return false;
  212. }
  213. } while (header.id != OpenRgb::RequestControllerCount);
  214. if (payload.size () < 4) {
  215. return false;
  216. }
  217. const uint32_t count
  218. = payload[0] | (payload[1] << 8) | (payload[2] << 16) | (static_cast<uint32_t> (payload[3]) << 24);
  219. for (uint32_t index = 0; index < count; index++) {
  220. std::vector<uint8_t> ask;
  221. OpenRgb::put32 (ask, OpenRgb::kProtocolVersion);
  222. if (!socket.writeAll (OpenRgb::makePacket (index, OpenRgb::RequestControllerData, ask))) {
  223. return false;
  224. }
  225. do {
  226. if (!socket.readPacket (header, payload, 3000)) {
  227. return false;
  228. }
  229. } while (header.id != OpenRgb::RequestControllerData);
  230. auto device = OpenRgb::parseController (payload, index);
  231. if (!device || device->ledCount == 0) {
  232. continue;
  233. }
  234. sLog.out ("LED output: ", device->name, " with ", device->ledCount, " leds");
  235. if (!socket.writeAll (OpenRgb::makePacket (index, OpenRgb::SetCustomMode))) {
  236. continue;
  237. }
  238. targets.push_back ({ .device = *device, .layout = layoutDevice (*device) });
  239. }
  240. this->m_devices.store (targets.size ());
  241. return true;
  242. };
  243. if (!listDevices ()) {
  244. return false;
  245. }
  246. if (targets.empty ()) {
  247. sLog.out ("LED output: the OpenRGB server has no devices");
  248. }
  249. std::vector<uint8_t> frame (kFrameBytes);
  250. std::vector<uint8_t> processed (kFrameBytes);
  251. std::vector<uint8_t> colors;
  252. auto lastRound = std::chrono::steady_clock::now () - 1h;
  253. while (this->m_running.load ()) {
  254. {
  255. Debugging::UniqueLock lock (this->m_mutex);
  256. this->m_wake.wait_for (lock, 250ms, [this] () LWE_REQUIRES (this->m_mutex) {
  257. return this->m_fresh || !this->m_running.load ();
  258. });
  259. if (this->m_fresh) {
  260. frame = this->m_frame;
  261. this->m_fresh = false;
  262. } else {
  263. frame.clear ();
  264. }
  265. }
  266. while (socket.readable ()) {
  267. if (!socket.readPacket (header, payload, 1000)) {
  268. return true;
  269. }
  270. if (header.id == OpenRgb::DeviceListUpdated && !listDevices ()) {
  271. return true;
  272. }
  273. }
  274. if (frame.size () != kFrameBytes) {
  275. continue;
  276. }
  277. const auto now = std::chrono::steady_clock::now ();
  278. if (options.reduceFps && now - lastRound < 66ms) {
  279. continue;
  280. }
  281. lastRound = now;
  282. applyBrightness (frame, processed, options.brightness);
  283. for (auto& target : targets) {
  284. sampleDevice (processed, target.layout, colors);
  285. // devices keep their colors, so an unchanged frame only goes out now and then
  286. if (colors == target.last && now - target.lastSent < 2s) {
  287. continue;
  288. }
  289. if (!socket.writeAll (OpenRgb::makeUpdateLeds (target.device.index, colors))) {
  290. return true;
  291. }
  292. target.last = colors;
  293. target.lastSent = now;
  294. }
  295. }
  296. return true;
  297. }
  298. }