LedOutput.cpp 9.0 KB

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