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.

271 lines
8.7KB

  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. enum { magicMastSlaveConnectionHeader = 0x712baf04 };
  24. static const char* startMessage = "__ipc_st";
  25. static const char* killMessage = "__ipc_k_";
  26. static const char* pingMessage = "__ipc_p_";
  27. enum { specialMessageSize = 8, defaultTimeoutMs = 8000 };
  28. static String getCommandLinePrefix (const String& commandLineUniqueID)
  29. {
  30. return "--" + commandLineUniqueID + ":";
  31. }
  32. //==============================================================================
  33. // This thread sends and receives ping messages every second, so that it
  34. // can find out if the other process has stopped running.
  35. struct ChildProcessPingThread : public Thread,
  36. private AsyncUpdater
  37. {
  38. ChildProcessPingThread (int timeout) : Thread ("IPC ping"), timeoutMs (timeout)
  39. {
  40. pingReceived();
  41. }
  42. static bool isPingMessage (const MemoryBlock& m) noexcept
  43. {
  44. return memcmp (m.getData(), pingMessage, specialMessageSize) == 0;
  45. }
  46. void pingReceived() noexcept { countdown = timeoutMs / 1000 + 1; }
  47. void triggerConnectionLostMessage() { triggerAsyncUpdate(); }
  48. virtual bool sendPingMessage (const MemoryBlock&) = 0;
  49. virtual void pingFailed() = 0;
  50. int timeoutMs;
  51. private:
  52. Atomic<int> countdown;
  53. void handleAsyncUpdate() override { pingFailed(); }
  54. void run() override
  55. {
  56. while (! threadShouldExit())
  57. {
  58. if (--countdown <= 0 || ! sendPingMessage (MemoryBlock (pingMessage, specialMessageSize)))
  59. {
  60. triggerConnectionLostMessage();
  61. break;
  62. }
  63. wait (1000);
  64. }
  65. }
  66. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcessPingThread)
  67. };
  68. //==============================================================================
  69. struct ChildProcessMaster::Connection : public InterprocessConnection,
  70. private ChildProcessPingThread
  71. {
  72. Connection (ChildProcessMaster& m, const String& pipeName, int timeout)
  73. : InterprocessConnection (false, magicMastSlaveConnectionHeader),
  74. ChildProcessPingThread (timeout),
  75. owner (m)
  76. {
  77. if (createPipe (pipeName, timeoutMs))
  78. startThread (4);
  79. }
  80. ~Connection()
  81. {
  82. stopThread (10000);
  83. }
  84. private:
  85. void connectionMade() override {}
  86. void connectionLost() override { owner.handleConnectionLost(); }
  87. bool sendPingMessage (const MemoryBlock& m) override { return owner.sendMessageToSlave (m); }
  88. void pingFailed() override { connectionLost(); }
  89. void messageReceived (const MemoryBlock& m) override
  90. {
  91. pingReceived();
  92. if (m.getSize() != specialMessageSize || ! isPingMessage (m))
  93. owner.handleMessageFromSlave (m);
  94. }
  95. ChildProcessMaster& owner;
  96. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Connection)
  97. };
  98. //==============================================================================
  99. ChildProcessMaster::ChildProcessMaster() {}
  100. ChildProcessMaster::~ChildProcessMaster()
  101. {
  102. if (connection != nullptr)
  103. {
  104. sendMessageToSlave (MemoryBlock (killMessage, specialMessageSize));
  105. connection->disconnect();
  106. connection = nullptr;
  107. }
  108. }
  109. void ChildProcessMaster::handleConnectionLost() {}
  110. bool ChildProcessMaster::sendMessageToSlave (const MemoryBlock& mb)
  111. {
  112. if (connection != nullptr)
  113. return connection->sendMessage (mb);
  114. jassertfalse; // this can only be used when the connection is active!
  115. return false;
  116. }
  117. bool ChildProcessMaster::launchSlaveProcess (const File& executable, const String& commandLineUniqueID, int timeoutMs, int streamFlags)
  118. {
  119. connection = nullptr;
  120. jassert (childProcess.kill());
  121. const String pipeName ("p" + String::toHexString (Random().nextInt64()));
  122. StringArray args;
  123. args.add (executable.getFullPathName());
  124. args.add (getCommandLinePrefix (commandLineUniqueID) + pipeName);
  125. if (childProcess.start (args, streamFlags))
  126. {
  127. connection = new Connection (*this, pipeName, timeoutMs <= 0 ? defaultTimeoutMs : timeoutMs);
  128. if (connection->isConnected())
  129. {
  130. sendMessageToSlave (MemoryBlock (startMessage, specialMessageSize));
  131. return true;
  132. }
  133. connection = nullptr;
  134. }
  135. return false;
  136. }
  137. //==============================================================================
  138. struct ChildProcessSlave::Connection : public InterprocessConnection,
  139. private ChildProcessPingThread
  140. {
  141. Connection (ChildProcessSlave& p, const String& pipeName, int timeout)
  142. : InterprocessConnection (false, magicMastSlaveConnectionHeader),
  143. ChildProcessPingThread (timeout),
  144. owner (p)
  145. {
  146. connectToPipe (pipeName, timeoutMs);
  147. startThread (4);
  148. }
  149. ~Connection()
  150. {
  151. stopThread (10000);
  152. }
  153. private:
  154. ChildProcessSlave& owner;
  155. void connectionMade() override {}
  156. void connectionLost() override { owner.handleConnectionLost(); }
  157. bool sendPingMessage (const MemoryBlock& m) override { return owner.sendMessageToMaster (m); }
  158. void pingFailed() override { connectionLost(); }
  159. void messageReceived (const MemoryBlock& m) override
  160. {
  161. pingReceived();
  162. if (m.getSize() == specialMessageSize)
  163. {
  164. if (isPingMessage (m))
  165. return;
  166. if (memcmp (m.getData(), killMessage, specialMessageSize) == 0)
  167. {
  168. triggerConnectionLostMessage();
  169. return;
  170. }
  171. if (memcmp (m.getData(), startMessage, specialMessageSize) == 0)
  172. {
  173. owner.handleConnectionMade();
  174. return;
  175. }
  176. }
  177. owner.handleMessageFromMaster (m);
  178. }
  179. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Connection)
  180. };
  181. //==============================================================================
  182. ChildProcessSlave::ChildProcessSlave() {}
  183. ChildProcessSlave::~ChildProcessSlave() {}
  184. void ChildProcessSlave::handleConnectionMade() {}
  185. void ChildProcessSlave::handleConnectionLost() {}
  186. bool ChildProcessSlave::sendMessageToMaster (const MemoryBlock& mb)
  187. {
  188. if (connection != nullptr)
  189. return connection->sendMessage (mb);
  190. jassertfalse; // this can only be used when the connection is active!
  191. return false;
  192. }
  193. bool ChildProcessSlave::initialiseFromCommandLine (const String& commandLine,
  194. const String& commandLineUniqueID,
  195. int timeoutMs)
  196. {
  197. String prefix (getCommandLinePrefix (commandLineUniqueID));
  198. if (commandLine.trim().startsWith (prefix))
  199. {
  200. String pipeName (commandLine.fromFirstOccurrenceOf (prefix, false, false)
  201. .upToFirstOccurrenceOf (" ", false, false).trim());
  202. if (pipeName.isNotEmpty())
  203. {
  204. connection = new Connection (*this, pipeName, timeoutMs <= 0 ? defaultTimeoutMs : timeoutMs);
  205. if (! connection->isConnected())
  206. connection = nullptr;
  207. }
  208. }
  209. return connection != nullptr;
  210. }