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. 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)
  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. 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