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.

868 lines
23KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2020 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #include "CarlaEngineInternal.hpp"
  18. #include "CarlaPlugin.hpp"
  19. #include "CarlaSemUtils.hpp"
  20. #include "jackbridge/JackBridge.hpp"
  21. #include <ctime>
  22. #include <sys/time.h>
  23. CARLA_BACKEND_START_NAMESPACE
  24. // -----------------------------------------------------------------------
  25. // Engine Internal helper macro, sets lastError and returns false/NULL
  26. #define CARLA_SAFE_ASSERT_RETURN_INTERNAL_ERR(cond, err) if (! (cond)) { carla_safe_assert(#cond, __FILE__, __LINE__); lastError = err; return false; }
  27. #define CARLA_SAFE_ASSERT_RETURN_INTERNAL_ERRN(cond, err) if (! (cond)) { carla_safe_assert(#cond, __FILE__, __LINE__); lastError = err; return nullptr; }
  28. // -----------------------------------------------------------------------
  29. // InternalEvents
  30. EngineInternalEvents::EngineInternalEvents() noexcept
  31. : in(nullptr),
  32. out(nullptr) {}
  33. EngineInternalEvents::~EngineInternalEvents() noexcept
  34. {
  35. CARLA_SAFE_ASSERT(in == nullptr);
  36. CARLA_SAFE_ASSERT(out == nullptr);
  37. }
  38. void EngineInternalEvents::clear() noexcept
  39. {
  40. if (in != nullptr)
  41. {
  42. delete[] in;
  43. in = nullptr;
  44. }
  45. if (out != nullptr)
  46. {
  47. delete[] out;
  48. out = nullptr;
  49. }
  50. }
  51. // -----------------------------------------------------------------------
  52. // InternalTime
  53. static const double kTicksPerBeat = 1920.0;
  54. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  55. static uint32_t calculate_link_latency(const double bufferSize, const double sampleRate) noexcept
  56. {
  57. CARLA_SAFE_ASSERT_RETURN(carla_isNotZero(sampleRate), 0);
  58. const long long int latency = llround(1.0e6 * bufferSize / sampleRate);
  59. CARLA_SAFE_ASSERT_RETURN(latency >= 0 && latency < UINT32_MAX, 0);
  60. return static_cast<uint32_t>(latency);
  61. }
  62. #endif
  63. EngineInternalTime::EngineInternalTime(EngineTimeInfo& ti, const EngineTransportMode& tm) noexcept
  64. : beatsPerBar(4.0),
  65. beatsPerMinute(120.0),
  66. bufferSize(0.0),
  67. sampleRate(0.0),
  68. needsReset(false),
  69. nextFrame(0),
  70. #ifndef BUILD_BRIDGE
  71. hylia(),
  72. #endif
  73. timeInfo(ti),
  74. transportMode(tm) {}
  75. void EngineInternalTime::init(const uint32_t bsize, const double srate)
  76. {
  77. bufferSize = bsize;
  78. sampleRate = srate;
  79. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  80. if (hylia.instance != nullptr)
  81. {
  82. hylia_set_beats_per_bar(hylia.instance, beatsPerBar);
  83. hylia_set_beats_per_minute(hylia.instance, beatsPerMinute);
  84. hylia_set_output_latency(hylia.instance, calculate_link_latency(bsize, srate));
  85. if (hylia.enabled)
  86. hylia_enable(hylia.instance, true);
  87. }
  88. #endif
  89. needsReset = true;
  90. }
  91. void EngineInternalTime::updateAudioValues(const uint32_t bsize, const double srate)
  92. {
  93. bufferSize = bsize;
  94. sampleRate = srate;
  95. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  96. if (hylia.instance != nullptr)
  97. hylia_set_output_latency(hylia.instance, calculate_link_latency(bsize, srate));
  98. #endif
  99. needsReset = true;
  100. }
  101. void EngineInternalTime::enableLink(const bool enable)
  102. {
  103. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  104. if (hylia.enabled == enable)
  105. return;
  106. if (hylia.instance != nullptr)
  107. {
  108. hylia.enabled = enable;
  109. hylia_enable(hylia.instance, enable);
  110. }
  111. #else
  112. // unused
  113. (void)enable;
  114. #endif
  115. needsReset = true;
  116. }
  117. void EngineInternalTime::setBPM(const double bpm)
  118. {
  119. beatsPerMinute = bpm;
  120. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  121. if (hylia.instance != nullptr)
  122. hylia_set_beats_per_minute(hylia.instance, bpm);
  123. #endif
  124. }
  125. void EngineInternalTime::setNeedsReset() noexcept
  126. {
  127. needsReset = true;
  128. }
  129. void EngineInternalTime::pause() noexcept
  130. {
  131. timeInfo.playing = false;
  132. nextFrame = timeInfo.frame;
  133. needsReset = true;
  134. }
  135. void EngineInternalTime::relocate(const uint64_t frame) noexcept
  136. {
  137. timeInfo.frame = frame;
  138. nextFrame = frame;
  139. needsReset = true;
  140. }
  141. void EngineInternalTime::fillEngineTimeInfo(const uint32_t newFrames) noexcept
  142. {
  143. CARLA_SAFE_ASSERT_RETURN(carla_isNotZero(sampleRate),);
  144. CARLA_SAFE_ASSERT_RETURN(newFrames > 0,);
  145. double ticktmp;
  146. if (transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  147. {
  148. timeInfo.usecs = 0;
  149. timeInfo.frame = nextFrame;
  150. }
  151. if (needsReset)
  152. {
  153. timeInfo.bbt.valid = true;
  154. timeInfo.bbt.beatType = 4.0f;
  155. timeInfo.bbt.ticksPerBeat = kTicksPerBeat;
  156. double abs_beat, abs_tick;
  157. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  158. if (hylia.enabled)
  159. {
  160. if (hylia.timeInfo.beat >= 0.0)
  161. {
  162. abs_beat = hylia.timeInfo.beat;
  163. abs_tick = abs_beat * kTicksPerBeat;
  164. }
  165. else
  166. {
  167. abs_beat = 0.0;
  168. abs_tick = 0.0;
  169. timeInfo.playing = false;
  170. }
  171. }
  172. else
  173. #endif
  174. {
  175. const double min = static_cast<double>(timeInfo.frame) / (sampleRate * 60.0);
  176. abs_beat = min * beatsPerMinute;
  177. abs_tick = abs_beat * kTicksPerBeat;
  178. needsReset = false;
  179. }
  180. const double bar = std::floor(abs_beat / beatsPerBar);
  181. const double beat = std::floor(std::fmod(abs_beat, beatsPerBar));
  182. timeInfo.bbt.bar = static_cast<int32_t>(bar) + 1;
  183. timeInfo.bbt.beat = static_cast<int32_t>(beat) + 1;
  184. timeInfo.bbt.barStartTick = ((bar * beatsPerBar) + beat) * kTicksPerBeat;
  185. ticktmp = abs_tick - timeInfo.bbt.barStartTick;
  186. }
  187. else if (timeInfo.playing)
  188. {
  189. ticktmp = timeInfo.bbt.tick + (newFrames * kTicksPerBeat * beatsPerMinute / (sampleRate * 60));
  190. while (ticktmp >= kTicksPerBeat)
  191. {
  192. ticktmp -= kTicksPerBeat;
  193. if (++timeInfo.bbt.beat > beatsPerBar)
  194. {
  195. ++timeInfo.bbt.bar;
  196. timeInfo.bbt.beat = 1;
  197. timeInfo.bbt.barStartTick += beatsPerBar * kTicksPerBeat;
  198. }
  199. }
  200. }
  201. else
  202. {
  203. ticktmp = timeInfo.bbt.tick;
  204. }
  205. timeInfo.bbt.beatsPerBar = static_cast<float>(beatsPerBar);
  206. timeInfo.bbt.beatsPerMinute = beatsPerMinute;
  207. timeInfo.bbt.tick = ticktmp;
  208. if (transportMode == ENGINE_TRANSPORT_MODE_INTERNAL && timeInfo.playing)
  209. nextFrame += newFrames;
  210. }
  211. void EngineInternalTime::fillJackTimeInfo(jack_position_t* const pos, const uint32_t newFrames) noexcept
  212. {
  213. CARLA_SAFE_ASSERT_RETURN(carla_isNotZero(sampleRate),);
  214. CARLA_SAFE_ASSERT_RETURN(newFrames > 0,);
  215. CARLA_SAFE_ASSERT(transportMode == ENGINE_TRANSPORT_MODE_JACK);
  216. fillEngineTimeInfo(newFrames);
  217. pos->valid = JackPositionBBT;
  218. pos->bar = timeInfo.bbt.bar;
  219. pos->beat = timeInfo.bbt.beat;
  220. pos->tick = static_cast<int32_t>(timeInfo.bbt.tick + 0.5);
  221. pos->bar_start_tick = timeInfo.bbt.barStartTick;
  222. pos->beats_per_bar = timeInfo.bbt.beatsPerBar;
  223. pos->beat_type = timeInfo.bbt.beatType;
  224. pos->ticks_per_beat = kTicksPerBeat;
  225. pos->beats_per_minute = beatsPerMinute;
  226. }
  227. void EngineInternalTime::preProcess(const uint32_t numFrames)
  228. {
  229. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  230. if (hylia.enabled)
  231. {
  232. hylia_process(hylia.instance, numFrames, &hylia.timeInfo);
  233. const double new_bpb = hylia.timeInfo.beatsPerBar;
  234. const double new_bpm = hylia.timeInfo.beatsPerMinute;
  235. if (new_bpb >= 1.0 && carla_isNotEqual(beatsPerBar, new_bpb))
  236. {
  237. beatsPerBar = new_bpb;
  238. needsReset = true;
  239. }
  240. if (new_bpm > 0.0 && carla_isNotEqual(beatsPerMinute, new_bpm))
  241. {
  242. beatsPerMinute = new_bpm;
  243. needsReset = true;
  244. }
  245. }
  246. #endif
  247. if (transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  248. fillEngineTimeInfo(numFrames);
  249. }
  250. // -----------------------------------------------------------------------
  251. // EngineInternalTime::Hylia
  252. #ifndef BUILD_BRIDGE
  253. EngineInternalTime::Hylia::Hylia()
  254. : enabled(false),
  255. instance(nullptr),
  256. timeInfo()
  257. {
  258. carla_zeroStruct(timeInfo);
  259. # ifdef HAVE_HYLIA
  260. instance = hylia_create();
  261. # endif
  262. }
  263. EngineInternalTime::Hylia::~Hylia()
  264. {
  265. # ifdef HAVE_HYLIA
  266. hylia_cleanup(instance);
  267. # endif
  268. }
  269. #endif
  270. // -----------------------------------------------------------------------
  271. // NextAction
  272. EngineNextAction::EngineNextAction() noexcept
  273. : opcode(kEnginePostActionNull),
  274. pluginId(0),
  275. value(0),
  276. mutex(),
  277. needsPost(false),
  278. postDone(false),
  279. sem(carla_sem_create(false)) {}
  280. EngineNextAction::~EngineNextAction() noexcept
  281. {
  282. CARLA_SAFE_ASSERT(opcode == kEnginePostActionNull);
  283. if (sem != nullptr)
  284. {
  285. carla_sem_destroy(sem);
  286. sem = nullptr;
  287. }
  288. }
  289. void EngineNextAction::clearAndReset() noexcept
  290. {
  291. mutex.lock();
  292. CARLA_SAFE_ASSERT(opcode == kEnginePostActionNull);
  293. opcode = kEnginePostActionNull;
  294. pluginId = 0;
  295. value = 0;
  296. needsPost = false;
  297. postDone = false;
  298. mutex.unlock();
  299. }
  300. // -----------------------------------------------------------------------
  301. // Helper functions
  302. EngineEvent* CarlaEngine::getInternalEventBuffer(const bool isInput) const noexcept
  303. {
  304. return isInput ? pData->events.in : pData->events.out;
  305. }
  306. // -----------------------------------------------------------------------
  307. // CarlaEngine::ProtectedData
  308. CarlaEngine::ProtectedData::ProtectedData(CarlaEngine* const engine)
  309. : thread(engine),
  310. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  311. osc(engine),
  312. #endif
  313. callback(nullptr),
  314. callbackPtr(nullptr),
  315. fileCallback(nullptr),
  316. fileCallbackPtr(nullptr),
  317. actionCanceled(false),
  318. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  319. loadingProject(false),
  320. ignoreClientPrefix(false),
  321. currentProjectFilename(),
  322. currentProjectFolder(),
  323. #endif
  324. bufferSize(0),
  325. sampleRate(0.0),
  326. aboutToClose(false),
  327. isIdling(0),
  328. curPluginCount(0),
  329. maxPluginNumber(0),
  330. nextPluginId(0),
  331. envMutex(),
  332. lastError(),
  333. name(),
  334. options(),
  335. timeInfo(),
  336. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  337. plugins(nullptr),
  338. xruns(0),
  339. dspLoad(0.0f),
  340. #endif
  341. pluginsToDelete(),
  342. events(),
  343. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  344. graph(engine),
  345. #endif
  346. time(timeInfo, options.transportMode),
  347. nextAction()
  348. {
  349. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  350. plugins[0].plugin = nullptr;
  351. carla_zeroStructs(plugins[0].peaks, 1);
  352. #endif
  353. }
  354. CarlaEngine::ProtectedData::~ProtectedData()
  355. {
  356. CARLA_SAFE_ASSERT(curPluginCount == 0);
  357. CARLA_SAFE_ASSERT(maxPluginNumber == 0);
  358. CARLA_SAFE_ASSERT(nextPluginId == 0);
  359. CARLA_SAFE_ASSERT(isIdling == 0);
  360. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  361. CARLA_SAFE_ASSERT(plugins == nullptr);
  362. #endif
  363. if (pluginsToDelete.size() != 0)
  364. {
  365. for (std::vector<CarlaPluginPtr>::iterator it = pluginsToDelete.begin(); it != pluginsToDelete.end(); ++it)
  366. {
  367. carla_stderr2("Plugin not yet deleted, name: '%s', usage count: '%u'",
  368. (*it)->getName(), it->use_count());
  369. }
  370. }
  371. pluginsToDelete.clear();
  372. }
  373. // -----------------------------------------------------------------------
  374. bool CarlaEngine::ProtectedData::init(const char* const clientName)
  375. {
  376. CARLA_SAFE_ASSERT_RETURN_INTERNAL_ERR(name.isEmpty(), "Invalid engine internal data (err #1)");
  377. CARLA_SAFE_ASSERT_RETURN_INTERNAL_ERR(events.in == nullptr, "Invalid engine internal data (err #4)");
  378. CARLA_SAFE_ASSERT_RETURN_INTERNAL_ERR(events.out == nullptr, "Invalid engine internal data (err #5)");
  379. CARLA_SAFE_ASSERT_RETURN_INTERNAL_ERR(clientName != nullptr && clientName[0] != '\0', "Invalid client name");
  380. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  381. CARLA_SAFE_ASSERT_RETURN_INTERNAL_ERR(plugins == nullptr, "Invalid engine internal data (err #3)");
  382. #endif
  383. aboutToClose = false;
  384. curPluginCount = 0;
  385. nextPluginId = 0;
  386. switch (options.processMode)
  387. {
  388. case ENGINE_PROCESS_MODE_CONTINUOUS_RACK:
  389. maxPluginNumber = MAX_RACK_PLUGINS;
  390. options.forceStereo = true;
  391. break;
  392. case ENGINE_PROCESS_MODE_PATCHBAY:
  393. maxPluginNumber = MAX_PATCHBAY_PLUGINS;
  394. break;
  395. case ENGINE_PROCESS_MODE_BRIDGE:
  396. maxPluginNumber = 1;
  397. break;
  398. default:
  399. maxPluginNumber = MAX_DEFAULT_PLUGINS;
  400. break;
  401. }
  402. switch (options.processMode)
  403. {
  404. case ENGINE_PROCESS_MODE_CONTINUOUS_RACK:
  405. case ENGINE_PROCESS_MODE_PATCHBAY:
  406. case ENGINE_PROCESS_MODE_BRIDGE:
  407. events.in = new EngineEvent[kMaxEngineEventInternalCount];
  408. events.out = new EngineEvent[kMaxEngineEventInternalCount];
  409. carla_zeroStructs(events.in, kMaxEngineEventInternalCount);
  410. carla_zeroStructs(events.out, kMaxEngineEventInternalCount);
  411. break;
  412. default:
  413. break;
  414. }
  415. nextPluginId = maxPluginNumber;
  416. name = clientName;
  417. name.toBasic();
  418. timeInfo.clear();
  419. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  420. if (options.oscEnabled)
  421. osc.init(clientName, options.oscPortTCP, options.oscPortUDP);
  422. #endif
  423. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  424. plugins = new EnginePluginData[maxPluginNumber];
  425. xruns = 0;
  426. dspLoad = 0.0f;
  427. #endif
  428. nextAction.clearAndReset();
  429. thread.startThread();
  430. return true;
  431. }
  432. void CarlaEngine::ProtectedData::close()
  433. {
  434. CARLA_SAFE_ASSERT(name.isNotEmpty());
  435. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  436. CARLA_SAFE_ASSERT(plugins != nullptr);
  437. CARLA_SAFE_ASSERT(nextPluginId == maxPluginNumber);
  438. #endif
  439. aboutToClose = true;
  440. thread.stopThread(500);
  441. nextAction.clearAndReset();
  442. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  443. osc.close();
  444. #endif
  445. aboutToClose = false;
  446. curPluginCount = 0;
  447. maxPluginNumber = 0;
  448. nextPluginId = 0;
  449. deletePluginsAsNeeded();
  450. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  451. if (plugins != nullptr)
  452. {
  453. delete[] plugins;
  454. plugins = nullptr;
  455. }
  456. #endif
  457. events.clear();
  458. name.clear();
  459. }
  460. void CarlaEngine::ProtectedData::initTime(const char* const features)
  461. {
  462. time.init(bufferSize, sampleRate);
  463. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  464. const bool linkEnabled = features != nullptr && std::strstr(features, ":link:") != nullptr;
  465. time.enableLink(linkEnabled);
  466. #else
  467. return;
  468. // unused
  469. (void)features;
  470. #endif
  471. }
  472. // -----------------------------------------------------------------------
  473. void CarlaEngine::ProtectedData::deletePluginsAsNeeded()
  474. {
  475. for (bool stop;;)
  476. {
  477. stop = true;
  478. for (std::vector<CarlaPluginPtr>::iterator it = pluginsToDelete.begin(); it != pluginsToDelete.end(); ++it)
  479. {
  480. if (it->use_count() == 1)
  481. {
  482. stop = false;
  483. pluginsToDelete.erase(it);
  484. break;
  485. }
  486. }
  487. if (stop)
  488. break;
  489. }
  490. }
  491. // -----------------------------------------------------------------------
  492. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  493. void CarlaEngine::ProtectedData::doPluginRemove(const uint pluginId) noexcept
  494. {
  495. CARLA_SAFE_ASSERT_RETURN(curPluginCount > 0,);
  496. CARLA_SAFE_ASSERT_RETURN(pluginId < curPluginCount,);
  497. --curPluginCount;
  498. // move all plugins 1 spot backwards
  499. for (uint i=pluginId; i < curPluginCount; ++i)
  500. {
  501. const CarlaPluginPtr plugin = plugins[i+1].plugin;
  502. CARLA_SAFE_ASSERT_BREAK(plugin.get() != nullptr);
  503. plugin->setId(i);
  504. plugins[i].plugin = plugin;
  505. carla_zeroStruct(plugins[i].peaks);
  506. }
  507. const uint id = curPluginCount;
  508. // reset last plugin (now removed)
  509. plugins[id].plugin.reset();
  510. carla_zeroFloats(plugins[id].peaks, 4);
  511. }
  512. void CarlaEngine::ProtectedData::doPluginsSwitch(const uint idA, const uint idB) noexcept
  513. {
  514. CARLA_SAFE_ASSERT_RETURN(curPluginCount >= 2,);
  515. CARLA_SAFE_ASSERT_RETURN(idA < curPluginCount,);
  516. CARLA_SAFE_ASSERT_RETURN(idB < curPluginCount,);
  517. const CarlaPluginPtr pluginA = plugins[idA].plugin;
  518. CARLA_SAFE_ASSERT_RETURN(pluginA.get() != nullptr,);
  519. const CarlaPluginPtr pluginB = plugins[idB].plugin;
  520. CARLA_SAFE_ASSERT_RETURN(pluginB.get() != nullptr,);
  521. pluginA->setId(idB);
  522. plugins[idA].plugin = pluginB;
  523. pluginB->setId(idA);
  524. plugins[idB].plugin = pluginA;
  525. }
  526. #endif
  527. void CarlaEngine::ProtectedData::doNextPluginAction() noexcept
  528. {
  529. if (! nextAction.mutex.tryLock())
  530. return;
  531. const EnginePostAction opcode = nextAction.opcode;
  532. const bool needsPost = nextAction.needsPost;
  533. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  534. const uint pluginId = nextAction.pluginId;
  535. const uint value = nextAction.value;
  536. #endif
  537. nextAction.opcode = kEnginePostActionNull;
  538. nextAction.pluginId = 0;
  539. nextAction.value = 0;
  540. nextAction.needsPost = false;
  541. nextAction.mutex.unlock();
  542. switch (opcode)
  543. {
  544. case kEnginePostActionNull:
  545. break;
  546. case kEnginePostActionZeroCount:
  547. curPluginCount = 0;
  548. break;
  549. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  550. case kEnginePostActionRemovePlugin:
  551. doPluginRemove(pluginId);
  552. break;
  553. case kEnginePostActionSwitchPlugins:
  554. doPluginsSwitch(pluginId, value);
  555. break;
  556. #endif
  557. }
  558. if (needsPost)
  559. {
  560. if (nextAction.sem != nullptr)
  561. carla_sem_post(*nextAction.sem);
  562. nextAction.postDone = true;
  563. }
  564. }
  565. // -----------------------------------------------------------------------
  566. // PendingRtEventsRunner
  567. static int64_t getTimeInMicroseconds() noexcept
  568. {
  569. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  570. struct timeval tv;
  571. gettimeofday(&tv, nullptr);
  572. return (tv.tv_sec * 1000000) + tv.tv_usec;
  573. #else
  574. struct timespec ts;
  575. # ifdef CLOCK_MONOTONIC_RAW
  576. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  577. # else
  578. clock_gettime(CLOCK_MONOTONIC, &ts);
  579. # endif
  580. return (ts.tv_sec * 1000000) + (ts.tv_nsec / 1000);
  581. #endif
  582. }
  583. PendingRtEventsRunner::PendingRtEventsRunner(CarlaEngine* const engine,
  584. const uint32_t frames,
  585. const bool calcDSPLoad) noexcept
  586. : pData(engine->pData),
  587. prevTime(calcDSPLoad ? getTimeInMicroseconds() : 0)
  588. {
  589. pData->time.preProcess(frames);
  590. }
  591. PendingRtEventsRunner::~PendingRtEventsRunner() noexcept
  592. {
  593. pData->doNextPluginAction();
  594. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  595. if (prevTime > 0)
  596. {
  597. const int64_t newTime = getTimeInMicroseconds();
  598. if (newTime < prevTime)
  599. return;
  600. const double timeDiff = static_cast<double>(newTime - prevTime) / 1000000.0;
  601. const double maxTime = pData->bufferSize / pData->sampleRate;
  602. const float dspLoad = static_cast<float>(timeDiff / maxTime) * 100.0f;
  603. if (dspLoad > pData->dspLoad)
  604. pData->dspLoad = std::min(100.0f, dspLoad);
  605. else
  606. pData->dspLoad *= static_cast<float>(1.0 - maxTime) + 1e-12f;
  607. }
  608. #endif
  609. }
  610. // -----------------------------------------------------------------------
  611. // ScopedActionLock
  612. ScopedActionLock::ScopedActionLock(CarlaEngine* const engine,
  613. const EnginePostAction action,
  614. const uint pluginId,
  615. const uint value) noexcept
  616. : pData(engine->pData)
  617. {
  618. CARLA_SAFE_ASSERT_RETURN(action != kEnginePostActionNull,);
  619. {
  620. const CarlaMutexLocker cml(pData->nextAction.mutex);
  621. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull,);
  622. pData->nextAction.opcode = action;
  623. pData->nextAction.pluginId = pluginId;
  624. pData->nextAction.value = value;
  625. pData->nextAction.needsPost = engine->isRunning();
  626. pData->nextAction.postDone = false;
  627. }
  628. #ifdef BUILD_BRIDGE
  629. #define ACTION_MSG_PREFIX "Bridge: "
  630. #else
  631. #define ACTION_MSG_PREFIX ""
  632. #endif
  633. if (pData->nextAction.needsPost)
  634. {
  635. #if defined(DEBUG) || defined(BUILD_BRIDGE)
  636. // block wait for unlock on processing side
  637. carla_stdout(ACTION_MSG_PREFIX "ScopedPluginAction(%i) - blocking START", pluginId);
  638. #endif
  639. bool engineStoppedWhileWaiting = false;
  640. if (! pData->nextAction.postDone)
  641. {
  642. for (int i = 10; --i >= 0;)
  643. {
  644. if (pData->nextAction.sem != nullptr)
  645. {
  646. if (carla_sem_timedwait(*pData->nextAction.sem, 200))
  647. break;
  648. }
  649. else
  650. {
  651. carla_msleep(200);
  652. }
  653. if (! engine->isRunning())
  654. {
  655. engineStoppedWhileWaiting = true;
  656. break;
  657. }
  658. }
  659. }
  660. #if defined(DEBUG) || defined(BUILD_BRIDGE)
  661. carla_stdout(ACTION_MSG_PREFIX "ScopedPluginAction(%i) - blocking DONE", pluginId);
  662. #endif
  663. // check if anything went wrong...
  664. if (! pData->nextAction.postDone)
  665. {
  666. bool needsCorrection = false;
  667. {
  668. const CarlaMutexLocker cml(pData->nextAction.mutex);
  669. if (pData->nextAction.opcode != kEnginePostActionNull)
  670. {
  671. needsCorrection = true;
  672. pData->nextAction.needsPost = false;
  673. }
  674. }
  675. if (needsCorrection)
  676. {
  677. pData->doNextPluginAction();
  678. if (! engineStoppedWhileWaiting)
  679. carla_stderr2(ACTION_MSG_PREFIX "Failed to wait for engine, is audio not running?");
  680. }
  681. }
  682. }
  683. else
  684. {
  685. pData->doNextPluginAction();
  686. }
  687. }
  688. ScopedActionLock::~ScopedActionLock() noexcept
  689. {
  690. CARLA_SAFE_ASSERT(pData->nextAction.opcode == kEnginePostActionNull);
  691. }
  692. // -----------------------------------------------------------------------
  693. // ScopedThreadStopper
  694. ScopedThreadStopper::ScopedThreadStopper(CarlaEngine* const e) noexcept
  695. : engine(e),
  696. pData(e->pData)
  697. {
  698. pData->thread.stopThread(500);
  699. }
  700. ScopedThreadStopper::~ScopedThreadStopper() noexcept
  701. {
  702. if (engine->isRunning() && ! pData->aboutToClose)
  703. pData->thread.startThread();
  704. }
  705. // -----------------------------------------------------------------------
  706. // ScopedEngineEnvironmentLocker
  707. ScopedEngineEnvironmentLocker::ScopedEngineEnvironmentLocker(CarlaEngine* const engine) noexcept
  708. : pData(engine->pData)
  709. {
  710. pData->envMutex.lock();
  711. }
  712. ScopedEngineEnvironmentLocker::~ScopedEngineEnvironmentLocker() noexcept
  713. {
  714. pData->envMutex.unlock();
  715. }
  716. // -----------------------------------------------------------------------
  717. CARLA_BACKEND_END_NAMESPACE