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.

366 lines
10KB

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