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.

372 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. struct InterprocessConnection::ConnectionThread : public Thread
  24. {
  25. ConnectionThread (InterprocessConnection& c) : Thread ("JUCE IPC"), owner (c) {}
  26. void run() override { owner.runThread(); }
  27. private:
  28. InterprocessConnection& owner;
  29. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionThread)
  30. };
  31. //==============================================================================
  32. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  33. const uint32 magicMessageHeaderNumber)
  34. : callbackConnectionState (false),
  35. useMessageThread (callbacksOnMessageThread),
  36. magicMessageHeader (magicMessageHeaderNumber),
  37. pipeReceiveMessageTimeout (-1)
  38. {
  39. thread = new ConnectionThread (*this);
  40. }
  41. InterprocessConnection::~InterprocessConnection()
  42. {
  43. callbackConnectionState = false;
  44. disconnect();
  45. masterReference.clear();
  46. thread = nullptr;
  47. }
  48. //==============================================================================
  49. bool InterprocessConnection::connectToSocket (const String& hostName,
  50. const int portNumber,
  51. const int timeOutMillisecs)
  52. {
  53. disconnect();
  54. const ScopedLock sl (pipeAndSocketLock);
  55. socket = new StreamingSocket();
  56. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  57. {
  58. connectionMadeInt();
  59. thread->startThread();
  60. return true;
  61. }
  62. socket = nullptr;
  63. return false;
  64. }
  65. bool InterprocessConnection::connectToPipe (const String& pipeName, const int timeoutMs)
  66. {
  67. disconnect();
  68. ScopedPointer<NamedPipe> newPipe (new NamedPipe());
  69. if (newPipe->openExisting (pipeName))
  70. {
  71. const ScopedLock sl (pipeAndSocketLock);
  72. pipeReceiveMessageTimeout = timeoutMs;
  73. initialiseWithPipe (newPipe.release());
  74. return true;
  75. }
  76. return false;
  77. }
  78. bool InterprocessConnection::createPipe (const String& pipeName, const int timeoutMs, bool mustNotExist)
  79. {
  80. disconnect();
  81. ScopedPointer<NamedPipe> newPipe (new NamedPipe());
  82. if (newPipe->createNewPipe (pipeName, mustNotExist))
  83. {
  84. const ScopedLock sl (pipeAndSocketLock);
  85. pipeReceiveMessageTimeout = timeoutMs;
  86. initialiseWithPipe (newPipe.release());
  87. return true;
  88. }
  89. return false;
  90. }
  91. void InterprocessConnection::disconnect()
  92. {
  93. thread->signalThreadShouldExit();
  94. {
  95. const ScopedLock sl (pipeAndSocketLock);
  96. if (socket != nullptr) socket->close();
  97. if (pipe != nullptr) pipe->close();
  98. }
  99. thread->stopThread (4000);
  100. deletePipeAndSocket();
  101. connectionLostInt();
  102. }
  103. void InterprocessConnection::deletePipeAndSocket()
  104. {
  105. const ScopedLock sl (pipeAndSocketLock);
  106. socket = nullptr;
  107. pipe = nullptr;
  108. }
  109. bool InterprocessConnection::isConnected() const
  110. {
  111. const ScopedLock sl (pipeAndSocketLock);
  112. return ((socket != nullptr && socket->isConnected())
  113. || (pipe != nullptr && pipe->isOpen()))
  114. && thread->isThreadRunning();
  115. }
  116. String InterprocessConnection::getConnectedHostName() const
  117. {
  118. {
  119. const ScopedLock sl (pipeAndSocketLock);
  120. if (pipe == nullptr && socket == nullptr)
  121. return String();
  122. if (socket != nullptr && ! socket->isLocal())
  123. return socket->getHostName();
  124. }
  125. return IPAddress::local().toString();
  126. }
  127. //==============================================================================
  128. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  129. {
  130. uint32 messageHeader[2] = { ByteOrder::swapIfBigEndian (magicMessageHeader),
  131. ByteOrder::swapIfBigEndian ((uint32) message.getSize()) };
  132. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  133. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  134. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  135. return writeData (messageData.getData(), (int) messageData.getSize()) == (int) messageData.getSize();
  136. }
  137. int InterprocessConnection::writeData (void* data, int dataSize)
  138. {
  139. const ScopedLock sl (pipeAndSocketLock);
  140. if (socket != nullptr)
  141. return socket->write (data, dataSize);
  142. if (pipe != nullptr)
  143. return pipe->write (data, dataSize, pipeReceiveMessageTimeout);
  144. return 0;
  145. }
  146. //==============================================================================
  147. void InterprocessConnection::initialiseWithSocket (StreamingSocket* newSocket)
  148. {
  149. jassert (socket == nullptr && pipe == nullptr);
  150. socket = newSocket;
  151. connectionMadeInt();
  152. thread->startThread();
  153. }
  154. void InterprocessConnection::initialiseWithPipe (NamedPipe* newPipe)
  155. {
  156. jassert (socket == nullptr && pipe == nullptr);
  157. pipe = newPipe;
  158. connectionMadeInt();
  159. thread->startThread();
  160. }
  161. //==============================================================================
  162. struct ConnectionStateMessage : public MessageManager::MessageBase
  163. {
  164. ConnectionStateMessage (InterprocessConnection* ipc, bool connected) noexcept
  165. : owner (ipc), connectionMade (connected)
  166. {}
  167. void messageCallback() override
  168. {
  169. if (InterprocessConnection* const ipc = owner)
  170. {
  171. if (connectionMade)
  172. ipc->connectionMade();
  173. else
  174. ipc->connectionLost();
  175. }
  176. }
  177. WeakReference<InterprocessConnection> owner;
  178. bool connectionMade;
  179. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectionStateMessage)
  180. };
  181. void InterprocessConnection::connectionMadeInt()
  182. {
  183. if (! callbackConnectionState)
  184. {
  185. callbackConnectionState = true;
  186. if (useMessageThread)
  187. (new ConnectionStateMessage (this, true))->post();
  188. else
  189. connectionMade();
  190. }
  191. }
  192. void InterprocessConnection::connectionLostInt()
  193. {
  194. if (callbackConnectionState)
  195. {
  196. callbackConnectionState = false;
  197. if (useMessageThread)
  198. (new ConnectionStateMessage (this, false))->post();
  199. else
  200. connectionLost();
  201. }
  202. }
  203. struct DataDeliveryMessage : public Message
  204. {
  205. DataDeliveryMessage (InterprocessConnection* ipc, const MemoryBlock& d)
  206. : owner (ipc), data (d)
  207. {}
  208. void messageCallback() override
  209. {
  210. if (InterprocessConnection* const ipc = owner)
  211. ipc->messageReceived (data);
  212. }
  213. WeakReference<InterprocessConnection> owner;
  214. MemoryBlock data;
  215. };
  216. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  217. {
  218. jassert (callbackConnectionState);
  219. if (useMessageThread)
  220. (new DataDeliveryMessage (this, data))->post();
  221. else
  222. messageReceived (data);
  223. }
  224. //==============================================================================
  225. bool InterprocessConnection::readNextMessageInt()
  226. {
  227. uint32 messageHeader[2];
  228. const int bytes = socket != nullptr ? socket->read (messageHeader, sizeof (messageHeader), true)
  229. : pipe ->read (messageHeader, sizeof (messageHeader), -1);
  230. if (bytes == sizeof (messageHeader)
  231. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  232. {
  233. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  234. if (bytesInMessage > 0)
  235. {
  236. MemoryBlock messageData ((size_t) bytesInMessage, true);
  237. int bytesRead = 0;
  238. while (bytesInMessage > 0)
  239. {
  240. if (thread->threadShouldExit())
  241. return false;
  242. const int numThisTime = jmin (bytesInMessage, 65536);
  243. void* const data = addBytesToPointer (messageData.getData(), bytesRead);
  244. const int bytesIn = socket != nullptr ? socket->read (data, numThisTime, true)
  245. : pipe ->read (data, numThisTime, -1);
  246. if (bytesIn <= 0)
  247. break;
  248. bytesRead += bytesIn;
  249. bytesInMessage -= bytesIn;
  250. }
  251. if (bytesRead >= 0)
  252. deliverDataInt (messageData);
  253. }
  254. }
  255. else if (bytes < 0)
  256. {
  257. if (socket != nullptr)
  258. deletePipeAndSocket();
  259. connectionLostInt();
  260. return false;
  261. }
  262. return true;
  263. }
  264. void InterprocessConnection::runThread()
  265. {
  266. while (! thread->threadShouldExit())
  267. {
  268. if (socket != nullptr)
  269. {
  270. const int ready = socket->waitUntilReady (true, 0);
  271. if (ready < 0)
  272. {
  273. deletePipeAndSocket();
  274. connectionLostInt();
  275. break;
  276. }
  277. if (ready == 0)
  278. {
  279. thread->wait (1);
  280. continue;
  281. }
  282. }
  283. else if (pipe != nullptr)
  284. {
  285. if (! pipe->isOpen())
  286. {
  287. deletePipeAndSocket();
  288. connectionLostInt();
  289. break;
  290. }
  291. }
  292. else
  293. {
  294. break;
  295. }
  296. if (thread->threadShouldExit() || ! readNextMessageInt())
  297. break;
  298. }
  299. }