Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_InterprocessConnection.cpp 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. struct InterprocessConnection::ConnectionThread : public Thread
  20. {
  21. ConnectionThread (InterprocessConnection& c) : Thread ("JUCE IPC"), owner (c) {}
  22. void run() override { owner.runThread(); }
  23. InterprocessConnection& owner;
  24. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionThread)
  25. };
  26. class SafeActionImpl
  27. {
  28. public:
  29. explicit SafeActionImpl (InterprocessConnection& p)
  30. : ref (p) {}
  31. template <typename Fn>
  32. void ifSafe (Fn&& fn)
  33. {
  34. const ScopedLock lock (mutex);
  35. if (safe)
  36. fn (ref);
  37. }
  38. void setSafe (bool s)
  39. {
  40. const ScopedLock lock (mutex);
  41. safe = s;
  42. }
  43. bool isSafe()
  44. {
  45. const ScopedLock lock (mutex);
  46. return safe;
  47. }
  48. private:
  49. CriticalSection mutex;
  50. InterprocessConnection& ref;
  51. bool safe = false;
  52. };
  53. class InterprocessConnection::SafeAction : public SafeActionImpl
  54. {
  55. using SafeActionImpl::SafeActionImpl;
  56. };
  57. //==============================================================================
  58. InterprocessConnection::InterprocessConnection (bool callbacksOnMessageThread, uint32 magicMessageHeaderNumber)
  59. : useMessageThread (callbacksOnMessageThread),
  60. magicMessageHeader (magicMessageHeaderNumber),
  61. safeAction (std::make_shared<SafeAction> (*this))
  62. {
  63. thread.reset (new ConnectionThread (*this));
  64. }
  65. InterprocessConnection::~InterprocessConnection()
  66. {
  67. // You *must* call `disconnect` in the destructor of your derived class to ensure
  68. // that any pending messages are not delivered. If the messages were delivered after
  69. // destroying the derived class, we'd end up calling the pure virtual implementations
  70. // of `messageReceived`, `connectionMade` and `connectionLost` which is definitely
  71. // not a good idea!
  72. jassert (! safeAction->isSafe());
  73. callbackConnectionState = false;
  74. disconnect (4000, Notify::no);
  75. thread.reset();
  76. }
  77. //==============================================================================
  78. bool InterprocessConnection::connectToSocket (const String& hostName,
  79. int portNumber, int timeOutMillisecs)
  80. {
  81. disconnect();
  82. auto s = std::make_unique<StreamingSocket>();
  83. if (s->connect (hostName, portNumber, timeOutMillisecs))
  84. {
  85. const ScopedWriteLock sl (pipeAndSocketLock);
  86. initialiseWithSocket (std::move (s));
  87. return true;
  88. }
  89. return false;
  90. }
  91. bool InterprocessConnection::connectToPipe (const String& pipeName, int timeoutMs)
  92. {
  93. disconnect();
  94. auto newPipe = std::make_unique<NamedPipe>();
  95. if (newPipe->openExisting (pipeName))
  96. {
  97. const ScopedWriteLock sl (pipeAndSocketLock);
  98. pipeReceiveMessageTimeout = timeoutMs;
  99. initialiseWithPipe (std::move (newPipe));
  100. return true;
  101. }
  102. return false;
  103. }
  104. bool InterprocessConnection::createPipe (const String& pipeName, int timeoutMs, bool mustNotExist)
  105. {
  106. disconnect();
  107. auto newPipe = std::make_unique<NamedPipe>();
  108. if (newPipe->createNewPipe (pipeName, mustNotExist))
  109. {
  110. const ScopedWriteLock sl (pipeAndSocketLock);
  111. pipeReceiveMessageTimeout = timeoutMs;
  112. initialiseWithPipe (std::move (newPipe));
  113. return true;
  114. }
  115. return false;
  116. }
  117. void InterprocessConnection::disconnect (int timeoutMs, Notify notify)
  118. {
  119. thread->signalThreadShouldExit();
  120. {
  121. const ScopedReadLock sl (pipeAndSocketLock);
  122. if (socket != nullptr) socket->close();
  123. if (pipe != nullptr) pipe->close();
  124. }
  125. thread->stopThread (timeoutMs);
  126. deletePipeAndSocket();
  127. if (notify == Notify::yes)
  128. connectionLostInt();
  129. callbackConnectionState = false;
  130. safeAction->setSafe (false);
  131. }
  132. void InterprocessConnection::deletePipeAndSocket()
  133. {
  134. const ScopedWriteLock sl (pipeAndSocketLock);
  135. socket.reset();
  136. pipe.reset();
  137. }
  138. bool InterprocessConnection::isConnected() const
  139. {
  140. const ScopedReadLock sl (pipeAndSocketLock);
  141. return ((socket != nullptr && socket->isConnected())
  142. || (pipe != nullptr && pipe->isOpen()))
  143. && threadIsRunning;
  144. }
  145. String InterprocessConnection::getConnectedHostName() const
  146. {
  147. {
  148. const ScopedReadLock sl (pipeAndSocketLock);
  149. if (pipe == nullptr && socket == nullptr)
  150. return {};
  151. if (socket != nullptr && ! socket->isLocal())
  152. return socket->getHostName();
  153. }
  154. return IPAddress::local().toString();
  155. }
  156. //==============================================================================
  157. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  158. {
  159. uint32 messageHeader[2] = { ByteOrder::swapIfBigEndian (magicMessageHeader),
  160. ByteOrder::swapIfBigEndian ((uint32) message.getSize()) };
  161. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  162. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  163. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  164. return writeData (messageData.getData(), (int) messageData.getSize()) == (int) messageData.getSize();
  165. }
  166. int InterprocessConnection::writeData (void* data, int dataSize)
  167. {
  168. const ScopedReadLock sl (pipeAndSocketLock);
  169. if (socket != nullptr)
  170. return socket->write (data, dataSize);
  171. if (pipe != nullptr)
  172. return pipe->write (data, dataSize, pipeReceiveMessageTimeout);
  173. return 0;
  174. }
  175. //==============================================================================
  176. void InterprocessConnection::initialise()
  177. {
  178. safeAction->setSafe (true);
  179. threadIsRunning = true;
  180. connectionMadeInt();
  181. thread->startThread();
  182. }
  183. void InterprocessConnection::initialiseWithSocket (std::unique_ptr<StreamingSocket> newSocket)
  184. {
  185. jassert (socket == nullptr && pipe == nullptr);
  186. socket = std::move (newSocket);
  187. initialise();
  188. }
  189. void InterprocessConnection::initialiseWithPipe (std::unique_ptr<NamedPipe> newPipe)
  190. {
  191. jassert (socket == nullptr && pipe == nullptr);
  192. pipe = std::move (newPipe);
  193. initialise();
  194. }
  195. //==============================================================================
  196. struct ConnectionStateMessage : public MessageManager::MessageBase
  197. {
  198. ConnectionStateMessage (std::shared_ptr<SafeActionImpl> ipc, bool connected) noexcept
  199. : safeAction (ipc), connectionMade (connected)
  200. {}
  201. void messageCallback() override
  202. {
  203. safeAction->ifSafe ([this] (InterprocessConnection& owner)
  204. {
  205. if (connectionMade)
  206. owner.connectionMade();
  207. else
  208. owner.connectionLost();
  209. });
  210. }
  211. std::shared_ptr<SafeActionImpl> safeAction;
  212. bool connectionMade;
  213. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionStateMessage)
  214. };
  215. void InterprocessConnection::connectionMadeInt()
  216. {
  217. if (! callbackConnectionState)
  218. {
  219. callbackConnectionState = true;
  220. if (useMessageThread)
  221. (new ConnectionStateMessage (safeAction, true))->post();
  222. else
  223. connectionMade();
  224. }
  225. }
  226. void InterprocessConnection::connectionLostInt()
  227. {
  228. if (callbackConnectionState)
  229. {
  230. callbackConnectionState = false;
  231. if (useMessageThread)
  232. (new ConnectionStateMessage (safeAction, false))->post();
  233. else
  234. connectionLost();
  235. }
  236. }
  237. struct DataDeliveryMessage : public Message
  238. {
  239. DataDeliveryMessage (std::shared_ptr<SafeActionImpl> ipc, const MemoryBlock& d)
  240. : safeAction (ipc), data (d)
  241. {}
  242. void messageCallback() override
  243. {
  244. safeAction->ifSafe ([this] (InterprocessConnection& owner)
  245. {
  246. owner.messageReceived (data);
  247. });
  248. }
  249. std::shared_ptr<SafeActionImpl> safeAction;
  250. MemoryBlock data;
  251. };
  252. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  253. {
  254. jassert (callbackConnectionState);
  255. if (useMessageThread)
  256. (new DataDeliveryMessage (safeAction, data))->post();
  257. else
  258. messageReceived (data);
  259. }
  260. //==============================================================================
  261. int InterprocessConnection::readData (void* data, int num)
  262. {
  263. const ScopedReadLock sl (pipeAndSocketLock);
  264. if (socket != nullptr)
  265. return socket->read (data, num, true);
  266. if (pipe != nullptr)
  267. return pipe->read (data, num, pipeReceiveMessageTimeout);
  268. jassertfalse;
  269. return -1;
  270. }
  271. bool InterprocessConnection::readNextMessage()
  272. {
  273. uint32 messageHeader[2];
  274. auto bytes = readData (messageHeader, sizeof (messageHeader));
  275. if (bytes == (int) sizeof (messageHeader)
  276. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  277. {
  278. auto bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  279. if (bytesInMessage > 0)
  280. {
  281. MemoryBlock messageData ((size_t) bytesInMessage, true);
  282. int bytesRead = 0;
  283. while (bytesInMessage > 0)
  284. {
  285. if (thread->threadShouldExit())
  286. return false;
  287. auto numThisTime = jmin (bytesInMessage, 65536);
  288. auto bytesIn = readData (addBytesToPointer (messageData.getData(), bytesRead), numThisTime);
  289. if (bytesIn <= 0)
  290. break;
  291. bytesRead += bytesIn;
  292. bytesInMessage -= bytesIn;
  293. }
  294. if (bytesRead >= 0)
  295. deliverDataInt (messageData);
  296. }
  297. return true;
  298. }
  299. if (bytes < 0)
  300. {
  301. if (socket != nullptr)
  302. deletePipeAndSocket();
  303. connectionLostInt();
  304. }
  305. return false;
  306. }
  307. void InterprocessConnection::runThread()
  308. {
  309. while (! thread->threadShouldExit())
  310. {
  311. if (socket != nullptr)
  312. {
  313. auto ready = socket->waitUntilReady (true, 100);
  314. if (ready < 0)
  315. {
  316. deletePipeAndSocket();
  317. connectionLostInt();
  318. break;
  319. }
  320. if (ready == 0)
  321. {
  322. thread->wait (1);
  323. continue;
  324. }
  325. }
  326. else if (pipe != nullptr)
  327. {
  328. if (! pipe->isOpen())
  329. {
  330. deletePipeAndSocket();
  331. connectionLostInt();
  332. break;
  333. }
  334. }
  335. else
  336. {
  337. break;
  338. }
  339. if (thread->threadShouldExit() || ! readNextMessage())
  340. break;
  341. }
  342. threadIsRunning = false;
  343. }
  344. } // namespace juce