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.

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