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

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. struct InterprocessConnection::ConnectionThread : public Thread
  18. {
  19. ConnectionThread (InterprocessConnection& c) : Thread ("JUCE IPC"), owner (c) {}
  20. void run() override { owner.runThread(); }
  21. private:
  22. InterprocessConnection& owner;
  23. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionThread)
  24. };
  25. //==============================================================================
  26. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  27. const uint32 magicMessageHeaderNumber)
  28. : callbackConnectionState (false),
  29. useMessageThread (callbacksOnMessageThread),
  30. magicMessageHeader (magicMessageHeaderNumber),
  31. pipeReceiveMessageTimeout (-1)
  32. {
  33. thread = new ConnectionThread (*this);
  34. }
  35. InterprocessConnection::~InterprocessConnection()
  36. {
  37. callbackConnectionState = false;
  38. disconnect();
  39. masterReference.clear();
  40. thread = nullptr;
  41. }
  42. //==============================================================================
  43. bool InterprocessConnection::connectToSocket (const String& hostName,
  44. const int portNumber,
  45. const int timeOutMillisecs)
  46. {
  47. disconnect();
  48. const ScopedLock sl (pipeAndSocketLock);
  49. socket = new StreamingSocket();
  50. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  51. {
  52. connectionMadeInt();
  53. thread->startThread();
  54. return true;
  55. }
  56. socket = nullptr;
  57. return false;
  58. }
  59. bool InterprocessConnection::connectToPipe (const String& pipeName, const int timeoutMs)
  60. {
  61. disconnect();
  62. ScopedPointer<NamedPipe> newPipe (new NamedPipe());
  63. if (newPipe->openExisting (pipeName))
  64. {
  65. const ScopedLock sl (pipeAndSocketLock);
  66. pipeReceiveMessageTimeout = timeoutMs;
  67. initialiseWithPipe (newPipe.release());
  68. return true;
  69. }
  70. return false;
  71. }
  72. bool InterprocessConnection::createPipe (const String& pipeName, const int timeoutMs)
  73. {
  74. disconnect();
  75. ScopedPointer<NamedPipe> newPipe (new NamedPipe());
  76. if (newPipe->createNewPipe (pipeName))
  77. {
  78. const ScopedLock sl (pipeAndSocketLock);
  79. pipeReceiveMessageTimeout = timeoutMs;
  80. initialiseWithPipe (newPipe.release());
  81. return true;
  82. }
  83. return false;
  84. }
  85. void InterprocessConnection::disconnect()
  86. {
  87. thread->signalThreadShouldExit();
  88. {
  89. const ScopedLock sl (pipeAndSocketLock);
  90. if (socket != nullptr) socket->close();
  91. if (pipe != nullptr) pipe->close();
  92. }
  93. thread->stopThread (4000);
  94. deletePipeAndSocket();
  95. connectionLostInt();
  96. }
  97. void InterprocessConnection::deletePipeAndSocket()
  98. {
  99. const ScopedLock sl (pipeAndSocketLock);
  100. socket = nullptr;
  101. pipe = nullptr;
  102. }
  103. bool InterprocessConnection::isConnected() const
  104. {
  105. const ScopedLock sl (pipeAndSocketLock);
  106. return ((socket != nullptr && socket->isConnected())
  107. || (pipe != nullptr && pipe->isOpen()))
  108. && thread->isThreadRunning();
  109. }
  110. String InterprocessConnection::getConnectedHostName() const
  111. {
  112. {
  113. const ScopedLock sl (pipeAndSocketLock);
  114. if (pipe == nullptr && socket == nullptr)
  115. return String();
  116. if (socket != nullptr && ! socket->isLocal())
  117. return socket->getHostName();
  118. }
  119. return IPAddress::local().toString();
  120. }
  121. //==============================================================================
  122. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  123. {
  124. uint32 messageHeader[2] = { ByteOrder::swapIfBigEndian (magicMessageHeader),
  125. ByteOrder::swapIfBigEndian ((uint32) message.getSize()) };
  126. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  127. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  128. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  129. return writeData (messageData.getData(), (int) messageData.getSize()) == (int) messageData.getSize();
  130. }
  131. int InterprocessConnection::writeData (void* data, int dataSize)
  132. {
  133. const ScopedLock sl (pipeAndSocketLock);
  134. if (socket != nullptr)
  135. return socket->write (data, dataSize);
  136. if (pipe != nullptr)
  137. return pipe->write (data, dataSize, pipeReceiveMessageTimeout);
  138. return 0;
  139. }
  140. //==============================================================================
  141. void InterprocessConnection::initialiseWithSocket (StreamingSocket* newSocket)
  142. {
  143. jassert (socket == nullptr && pipe == nullptr);
  144. socket = newSocket;
  145. connectionMadeInt();
  146. thread->startThread();
  147. }
  148. void InterprocessConnection::initialiseWithPipe (NamedPipe* newPipe)
  149. {
  150. jassert (socket == nullptr && pipe == nullptr);
  151. pipe = newPipe;
  152. connectionMadeInt();
  153. thread->startThread();
  154. }
  155. //==============================================================================
  156. struct ConnectionStateMessage : public MessageManager::MessageBase
  157. {
  158. ConnectionStateMessage (InterprocessConnection* ipc, bool connected) noexcept
  159. : owner (ipc), connectionMade (connected)
  160. {}
  161. void messageCallback() override
  162. {
  163. if (InterprocessConnection* const ipc = owner)
  164. {
  165. if (connectionMade)
  166. ipc->connectionMade();
  167. else
  168. ipc->connectionLost();
  169. }
  170. }
  171. WeakReference<InterprocessConnection> owner;
  172. bool connectionMade;
  173. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionStateMessage)
  174. };
  175. void InterprocessConnection::connectionMadeInt()
  176. {
  177. if (! callbackConnectionState)
  178. {
  179. callbackConnectionState = true;
  180. if (useMessageThread)
  181. (new ConnectionStateMessage (this, true))->post();
  182. else
  183. connectionMade();
  184. }
  185. }
  186. void InterprocessConnection::connectionLostInt()
  187. {
  188. if (callbackConnectionState)
  189. {
  190. callbackConnectionState = false;
  191. if (useMessageThread)
  192. (new ConnectionStateMessage (this, false))->post();
  193. else
  194. connectionLost();
  195. }
  196. }
  197. struct DataDeliveryMessage : public Message
  198. {
  199. DataDeliveryMessage (InterprocessConnection* ipc, const MemoryBlock& d)
  200. : owner (ipc), data (d)
  201. {}
  202. void messageCallback() override
  203. {
  204. if (InterprocessConnection* const ipc = owner)
  205. ipc->messageReceived (data);
  206. }
  207. WeakReference<InterprocessConnection> owner;
  208. MemoryBlock data;
  209. };
  210. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  211. {
  212. jassert (callbackConnectionState);
  213. if (useMessageThread)
  214. (new DataDeliveryMessage (this, data))->post();
  215. else
  216. messageReceived (data);
  217. }
  218. //==============================================================================
  219. bool InterprocessConnection::readNextMessageInt()
  220. {
  221. uint32 messageHeader[2];
  222. const int bytes = socket != nullptr ? socket->read (messageHeader, sizeof (messageHeader), true)
  223. : pipe ->read (messageHeader, sizeof (messageHeader), -1);
  224. if (bytes == sizeof (messageHeader)
  225. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  226. {
  227. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  228. if (bytesInMessage > 0)
  229. {
  230. MemoryBlock messageData ((size_t) bytesInMessage, true);
  231. int bytesRead = 0;
  232. while (bytesInMessage > 0)
  233. {
  234. if (thread->threadShouldExit())
  235. return false;
  236. const int numThisTime = jmin (bytesInMessage, 65536);
  237. void* const data = addBytesToPointer (messageData.getData(), bytesRead);
  238. const int bytesIn = socket != nullptr ? socket->read (data, numThisTime, true)
  239. : pipe ->read (data, numThisTime, -1);
  240. if (bytesIn <= 0)
  241. break;
  242. bytesRead += bytesIn;
  243. bytesInMessage -= bytesIn;
  244. }
  245. if (bytesRead >= 0)
  246. deliverDataInt (messageData);
  247. }
  248. }
  249. else if (bytes < 0)
  250. {
  251. if (socket != nullptr)
  252. deletePipeAndSocket();
  253. connectionLostInt();
  254. return false;
  255. }
  256. return true;
  257. }
  258. void InterprocessConnection::runThread()
  259. {
  260. while (! thread->threadShouldExit())
  261. {
  262. if (socket != nullptr)
  263. {
  264. const int ready = socket->waitUntilReady (true, 0);
  265. if (ready < 0)
  266. {
  267. deletePipeAndSocket();
  268. connectionLostInt();
  269. break;
  270. }
  271. if (ready == 0)
  272. {
  273. thread->wait (1);
  274. continue;
  275. }
  276. }
  277. else if (pipe != nullptr)
  278. {
  279. if (! pipe->isOpen())
  280. {
  281. deletePipeAndSocket();
  282. connectionLostInt();
  283. break;
  284. }
  285. }
  286. else
  287. {
  288. break;
  289. }
  290. if (thread->threadShouldExit() || ! readNextMessageInt())
  291. break;
  292. }
  293. }