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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  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. //==============================================================================
  27. InterprocessConnection::InterprocessConnection (bool callbacksOnMessageThread, uint32 magicMessageHeaderNumber)
  28. : useMessageThread (callbacksOnMessageThread),
  29. magicMessageHeader (magicMessageHeaderNumber)
  30. {
  31. thread = new ConnectionThread (*this);
  32. }
  33. InterprocessConnection::~InterprocessConnection()
  34. {
  35. callbackConnectionState = false;
  36. disconnect();
  37. masterReference.clear();
  38. thread = nullptr;
  39. }
  40. //==============================================================================
  41. bool InterprocessConnection::connectToSocket (const String& hostName,
  42. const int portNumber,
  43. const int timeOutMillisecs)
  44. {
  45. disconnect();
  46. const ScopedLock sl (pipeAndSocketLock);
  47. socket = new StreamingSocket();
  48. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  49. {
  50. connectionMadeInt();
  51. thread->startThread();
  52. return true;
  53. }
  54. socket = nullptr;
  55. return false;
  56. }
  57. bool InterprocessConnection::connectToPipe (const String& pipeName, const int timeoutMs)
  58. {
  59. disconnect();
  60. ScopedPointer<NamedPipe> newPipe (new NamedPipe());
  61. if (newPipe->openExisting (pipeName))
  62. {
  63. const ScopedLock sl (pipeAndSocketLock);
  64. pipeReceiveMessageTimeout = timeoutMs;
  65. initialiseWithPipe (newPipe.release());
  66. return true;
  67. }
  68. return false;
  69. }
  70. bool InterprocessConnection::createPipe (const String& pipeName, const int timeoutMs, bool mustNotExist)
  71. {
  72. disconnect();
  73. ScopedPointer<NamedPipe> newPipe (new NamedPipe());
  74. if (newPipe->createNewPipe (pipeName, mustNotExist))
  75. {
  76. const ScopedLock sl (pipeAndSocketLock);
  77. pipeReceiveMessageTimeout = timeoutMs;
  78. initialiseWithPipe (newPipe.release());
  79. return true;
  80. }
  81. return false;
  82. }
  83. void InterprocessConnection::disconnect()
  84. {
  85. thread->signalThreadShouldExit();
  86. {
  87. const ScopedLock sl (pipeAndSocketLock);
  88. if (socket != nullptr) socket->close();
  89. if (pipe != nullptr) pipe->close();
  90. }
  91. thread->stopThread (4000);
  92. deletePipeAndSocket();
  93. connectionLostInt();
  94. }
  95. void InterprocessConnection::deletePipeAndSocket()
  96. {
  97. const ScopedLock sl (pipeAndSocketLock);
  98. socket = nullptr;
  99. pipe = nullptr;
  100. }
  101. bool InterprocessConnection::isConnected() const
  102. {
  103. const ScopedLock sl (pipeAndSocketLock);
  104. return ((socket != nullptr && socket->isConnected())
  105. || (pipe != nullptr && pipe->isOpen()))
  106. && thread->isThreadRunning();
  107. }
  108. String InterprocessConnection::getConnectedHostName() const
  109. {
  110. {
  111. const ScopedLock sl (pipeAndSocketLock);
  112. if (pipe == nullptr && socket == nullptr)
  113. return {};
  114. if (socket != nullptr && ! socket->isLocal())
  115. return socket->getHostName();
  116. }
  117. return IPAddress::local().toString();
  118. }
  119. //==============================================================================
  120. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  121. {
  122. uint32 messageHeader[2] = { ByteOrder::swapIfBigEndian (magicMessageHeader),
  123. ByteOrder::swapIfBigEndian ((uint32) message.getSize()) };
  124. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  125. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  126. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  127. return writeData (messageData.getData(), (int) messageData.getSize()) == (int) messageData.getSize();
  128. }
  129. int InterprocessConnection::writeData (void* data, int dataSize)
  130. {
  131. const ScopedLock sl (pipeAndSocketLock);
  132. if (socket != nullptr)
  133. return socket->write (data, dataSize);
  134. if (pipe != nullptr)
  135. return pipe->write (data, dataSize, pipeReceiveMessageTimeout);
  136. return 0;
  137. }
  138. //==============================================================================
  139. void InterprocessConnection::initialiseWithSocket (StreamingSocket* newSocket)
  140. {
  141. jassert (socket == nullptr && pipe == nullptr);
  142. socket = newSocket;
  143. connectionMadeInt();
  144. thread->startThread();
  145. }
  146. void InterprocessConnection::initialiseWithPipe (NamedPipe* newPipe)
  147. {
  148. jassert (socket == nullptr && pipe == nullptr);
  149. pipe = newPipe;
  150. connectionMadeInt();
  151. thread->startThread();
  152. }
  153. //==============================================================================
  154. struct ConnectionStateMessage : public MessageManager::MessageBase
  155. {
  156. ConnectionStateMessage (InterprocessConnection* ipc, bool connected) noexcept
  157. : owner (ipc), connectionMade (connected)
  158. {}
  159. void messageCallback() override
  160. {
  161. if (auto* ipc = owner.get())
  162. {
  163. if (connectionMade)
  164. ipc->connectionMade();
  165. else
  166. ipc->connectionLost();
  167. }
  168. }
  169. WeakReference<InterprocessConnection> owner;
  170. bool connectionMade;
  171. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionStateMessage)
  172. };
  173. void InterprocessConnection::connectionMadeInt()
  174. {
  175. if (! callbackConnectionState)
  176. {
  177. callbackConnectionState = true;
  178. if (useMessageThread)
  179. (new ConnectionStateMessage (this, true))->post();
  180. else
  181. connectionMade();
  182. }
  183. }
  184. void InterprocessConnection::connectionLostInt()
  185. {
  186. if (callbackConnectionState)
  187. {
  188. callbackConnectionState = false;
  189. if (useMessageThread)
  190. (new ConnectionStateMessage (this, false))->post();
  191. else
  192. connectionLost();
  193. }
  194. }
  195. struct DataDeliveryMessage : public Message
  196. {
  197. DataDeliveryMessage (InterprocessConnection* ipc, const MemoryBlock& d)
  198. : owner (ipc), data (d)
  199. {}
  200. void messageCallback() override
  201. {
  202. if (auto* ipc = owner.get())
  203. ipc->messageReceived (data);
  204. }
  205. WeakReference<InterprocessConnection> owner;
  206. MemoryBlock data;
  207. };
  208. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  209. {
  210. jassert (callbackConnectionState);
  211. if (useMessageThread)
  212. (new DataDeliveryMessage (this, data))->post();
  213. else
  214. messageReceived (data);
  215. }
  216. //==============================================================================
  217. bool InterprocessConnection::readNextMessageInt()
  218. {
  219. uint32 messageHeader[2];
  220. const int bytes = socket != nullptr ? socket->read (messageHeader, sizeof (messageHeader), true)
  221. : pipe ->read (messageHeader, sizeof (messageHeader), -1);
  222. if (bytes == sizeof (messageHeader)
  223. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  224. {
  225. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  226. if (bytesInMessage > 0)
  227. {
  228. MemoryBlock messageData ((size_t) bytesInMessage, true);
  229. int bytesRead = 0;
  230. while (bytesInMessage > 0)
  231. {
  232. if (thread->threadShouldExit())
  233. return false;
  234. const int numThisTime = jmin (bytesInMessage, 65536);
  235. void* const data = addBytesToPointer (messageData.getData(), bytesRead);
  236. const int bytesIn = socket != nullptr ? socket->read (data, numThisTime, true)
  237. : pipe ->read (data, numThisTime, -1);
  238. if (bytesIn <= 0)
  239. break;
  240. bytesRead += bytesIn;
  241. bytesInMessage -= bytesIn;
  242. }
  243. if (bytesRead >= 0)
  244. deliverDataInt (messageData);
  245. }
  246. }
  247. else if (bytes < 0)
  248. {
  249. if (socket != nullptr)
  250. deletePipeAndSocket();
  251. connectionLostInt();
  252. return false;
  253. }
  254. return true;
  255. }
  256. void InterprocessConnection::runThread()
  257. {
  258. while (! thread->threadShouldExit())
  259. {
  260. if (socket != nullptr)
  261. {
  262. auto ready = socket->waitUntilReady (true, 0);
  263. if (ready < 0)
  264. {
  265. deletePipeAndSocket();
  266. connectionLostInt();
  267. break;
  268. }
  269. if (ready == 0)
  270. {
  271. thread->wait (1);
  272. continue;
  273. }
  274. }
  275. else if (pipe != nullptr)
  276. {
  277. if (! pipe->isOpen())
  278. {
  279. deletePipeAndSocket();
  280. connectionLostInt();
  281. break;
  282. }
  283. }
  284. else
  285. {
  286. break;
  287. }
  288. if (thread->threadShouldExit() || ! readNextMessageInt())
  289. break;
  290. }
  291. }
  292. } // namespace juce