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.

298 lines
9.3KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  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. enum { magicCoordWorkerConnectionHeader = 0x712baf04 };
  20. static const char* startMessage = "__ipc_st";
  21. static const char* killMessage = "__ipc_k_";
  22. static const char* pingMessage = "__ipc_p_";
  23. enum { specialMessageSize = 8, defaultTimeoutMs = 8000 };
  24. static bool isMessageType (const MemoryBlock& mb, const char* messageType) noexcept
  25. {
  26. return mb.matches (messageType, (size_t) specialMessageSize);
  27. }
  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. void startPinging() { startThread (4); }
  43. void pingReceived() noexcept { countdown = timeoutMs / 1000 + 1; }
  44. void triggerConnectionLostMessage() { triggerAsyncUpdate(); }
  45. virtual bool sendPingMessage (const MemoryBlock&) = 0;
  46. virtual void pingFailed() = 0;
  47. int timeoutMs;
  48. using AsyncUpdater::cancelPendingUpdate;
  49. private:
  50. Atomic<int> countdown;
  51. void handleAsyncUpdate() override { pingFailed(); }
  52. void run() override
  53. {
  54. while (! threadShouldExit())
  55. {
  56. if (--countdown <= 0 || ! sendPingMessage ({ pingMessage, specialMessageSize }))
  57. {
  58. triggerConnectionLostMessage();
  59. break;
  60. }
  61. wait (1000);
  62. }
  63. }
  64. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcessPingThread)
  65. };
  66. //==============================================================================
  67. struct ChildProcessCoordinator::Connection : public InterprocessConnection,
  68. private ChildProcessPingThread
  69. {
  70. Connection (ChildProcessCoordinator& m, const String& pipeName, int timeout)
  71. : InterprocessConnection (false, magicCoordWorkerConnectionHeader),
  72. ChildProcessPingThread (timeout),
  73. owner (m)
  74. {
  75. createPipe (pipeName, timeoutMs);
  76. }
  77. ~Connection() override
  78. {
  79. cancelPendingUpdate();
  80. stopThread (10000);
  81. }
  82. using ChildProcessPingThread::startPinging;
  83. private:
  84. void connectionMade() override {}
  85. void connectionLost() override { owner.handleConnectionLost(); }
  86. bool sendPingMessage (const MemoryBlock& m) override { return owner.sendMessageToWorker (m); }
  87. void pingFailed() override { connectionLost(); }
  88. void messageReceived (const MemoryBlock& m) override
  89. {
  90. pingReceived();
  91. if (m.getSize() != specialMessageSize || ! isMessageType (m, pingMessage))
  92. owner.handleMessageFromWorker (m);
  93. }
  94. ChildProcessCoordinator& owner;
  95. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Connection)
  96. };
  97. //==============================================================================
  98. ChildProcessCoordinator::ChildProcessCoordinator() = default;
  99. ChildProcessCoordinator::~ChildProcessCoordinator()
  100. {
  101. killWorkerProcess();
  102. }
  103. void ChildProcessCoordinator::handleConnectionLost() {}
  104. void ChildProcessCoordinator::handleMessageFromWorker (const MemoryBlock& mb)
  105. {
  106. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  107. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4996)
  108. handleMessageFromSlave (mb);
  109. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  110. JUCE_END_IGNORE_WARNINGS_MSVC
  111. }
  112. bool ChildProcessCoordinator::sendMessageToWorker (const MemoryBlock& mb)
  113. {
  114. if (connection != nullptr)
  115. return connection->sendMessage (mb);
  116. jassertfalse; // this can only be used when the connection is active!
  117. return false;
  118. }
  119. bool ChildProcessCoordinator::launchWorkerProcess (const File& executable, const String& commandLineUniqueID,
  120. int timeoutMs, int streamFlags)
  121. {
  122. killWorkerProcess();
  123. auto pipeName = "p" + String::toHexString (Random().nextInt64());
  124. StringArray args;
  125. args.add (executable.getFullPathName());
  126. args.add (getCommandLinePrefix (commandLineUniqueID) + pipeName);
  127. childProcess.reset (new ChildProcess());
  128. if (childProcess->start (args, streamFlags))
  129. {
  130. connection.reset (new Connection (*this, pipeName, timeoutMs <= 0 ? defaultTimeoutMs : timeoutMs));
  131. if (connection->isConnected())
  132. {
  133. connection->startPinging();
  134. sendMessageToWorker ({ startMessage, specialMessageSize });
  135. return true;
  136. }
  137. connection.reset();
  138. }
  139. return false;
  140. }
  141. void ChildProcessCoordinator::killWorkerProcess()
  142. {
  143. if (connection != nullptr)
  144. {
  145. sendMessageToWorker ({ killMessage, specialMessageSize });
  146. connection->disconnect();
  147. connection.reset();
  148. }
  149. childProcess.reset();
  150. }
  151. //==============================================================================
  152. struct ChildProcessWorker::Connection : public InterprocessConnection,
  153. private ChildProcessPingThread
  154. {
  155. Connection (ChildProcessWorker& p, const String& pipeName, int timeout)
  156. : InterprocessConnection (false, magicCoordWorkerConnectionHeader),
  157. ChildProcessPingThread (timeout),
  158. owner (p)
  159. {
  160. connectToPipe (pipeName, timeoutMs);
  161. }
  162. ~Connection() override
  163. {
  164. cancelPendingUpdate();
  165. stopThread (10000);
  166. disconnect();
  167. }
  168. using ChildProcessPingThread::startPinging;
  169. private:
  170. ChildProcessWorker& owner;
  171. void connectionMade() override {}
  172. void connectionLost() override { owner.handleConnectionLost(); }
  173. bool sendPingMessage (const MemoryBlock& m) override { return owner.sendMessageToCoordinator (m); }
  174. void pingFailed() override { connectionLost(); }
  175. void messageReceived (const MemoryBlock& m) override
  176. {
  177. pingReceived();
  178. if (isMessageType (m, pingMessage))
  179. return;
  180. if (isMessageType (m, killMessage))
  181. return triggerConnectionLostMessage();
  182. if (isMessageType (m, startMessage))
  183. return owner.handleConnectionMade();
  184. owner.handleMessageFromCoordinator (m);
  185. }
  186. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Connection)
  187. };
  188. //==============================================================================
  189. ChildProcessWorker::ChildProcessWorker() = default;
  190. ChildProcessWorker::~ChildProcessWorker() = default;
  191. void ChildProcessWorker::handleConnectionMade() {}
  192. void ChildProcessWorker::handleConnectionLost() {}
  193. void ChildProcessWorker::handleMessageFromCoordinator (const MemoryBlock& mb)
  194. {
  195. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  196. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4996)
  197. handleMessageFromMaster (mb);
  198. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  199. JUCE_END_IGNORE_WARNINGS_MSVC
  200. }
  201. bool ChildProcessWorker::sendMessageToCoordinator (const MemoryBlock& mb)
  202. {
  203. if (connection != nullptr)
  204. return connection->sendMessage (mb);
  205. jassertfalse; // this can only be used when the connection is active!
  206. return false;
  207. }
  208. bool ChildProcessWorker::initialiseFromCommandLine (const String& commandLine,
  209. const String& commandLineUniqueID,
  210. int timeoutMs)
  211. {
  212. auto prefix = getCommandLinePrefix (commandLineUniqueID);
  213. if (commandLine.trim().startsWith (prefix))
  214. {
  215. auto pipeName = commandLine.fromFirstOccurrenceOf (prefix, false, false)
  216. .upToFirstOccurrenceOf (" ", false, false).trim();
  217. if (pipeName.isNotEmpty())
  218. {
  219. connection.reset (new Connection (*this, pipeName, timeoutMs <= 0 ? defaultTimeoutMs : timeoutMs));
  220. if (connection->isConnected())
  221. connection->startPinging();
  222. else
  223. connection.reset();
  224. }
  225. }
  226. return connection != nullptr;
  227. }
  228. } // namespace juce