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.

869 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 = static_cast<jack_position_bits_t>(JackPositionBBT|JackTickDouble);
  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->tick_double = timeInfo.bbt.tick;
  222. pos->bar_start_tick = timeInfo.bbt.barStartTick;
  223. pos->beats_per_bar = timeInfo.bbt.beatsPerBar;
  224. pos->beat_type = timeInfo.bbt.beatType;
  225. pos->ticks_per_beat = kTicksPerBeat;
  226. pos->beats_per_minute = beatsPerMinute;
  227. }
  228. void EngineInternalTime::preProcess(const uint32_t numFrames)
  229. {
  230. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  231. if (hylia.enabled)
  232. {
  233. hylia_process(hylia.instance, numFrames, &hylia.timeInfo);
  234. const double new_bpb = hylia.timeInfo.beatsPerBar;
  235. const double new_bpm = hylia.timeInfo.beatsPerMinute;
  236. if (new_bpb >= 1.0 && carla_isNotEqual(beatsPerBar, new_bpb))
  237. {
  238. beatsPerBar = new_bpb;
  239. needsReset = true;
  240. }
  241. if (new_bpm > 0.0 && carla_isNotEqual(beatsPerMinute, new_bpm))
  242. {
  243. beatsPerMinute = new_bpm;
  244. needsReset = true;
  245. }
  246. }
  247. #endif
  248. if (transportMode == ENGINE_TRANSPORT_MODE_INTERNAL)
  249. fillEngineTimeInfo(numFrames);
  250. }
  251. // -----------------------------------------------------------------------
  252. // EngineInternalTime::Hylia
  253. #ifndef BUILD_BRIDGE
  254. EngineInternalTime::Hylia::Hylia()
  255. : enabled(false),
  256. instance(nullptr),
  257. timeInfo()
  258. {
  259. carla_zeroStruct(timeInfo);
  260. # ifdef HAVE_HYLIA
  261. instance = hylia_create();
  262. # endif
  263. }
  264. EngineInternalTime::Hylia::~Hylia()
  265. {
  266. # ifdef HAVE_HYLIA
  267. hylia_cleanup(instance);
  268. # endif
  269. }
  270. #endif
  271. // -----------------------------------------------------------------------
  272. // NextAction
  273. EngineNextAction::EngineNextAction() noexcept
  274. : opcode(kEnginePostActionNull),
  275. pluginId(0),
  276. value(0),
  277. mutex(),
  278. needsPost(false),
  279. postDone(false),
  280. sem(carla_sem_create(false)) {}
  281. EngineNextAction::~EngineNextAction() noexcept
  282. {
  283. CARLA_SAFE_ASSERT(opcode == kEnginePostActionNull);
  284. if (sem != nullptr)
  285. {
  286. carla_sem_destroy(sem);
  287. sem = nullptr;
  288. }
  289. }
  290. void EngineNextAction::clearAndReset() noexcept
  291. {
  292. mutex.lock();
  293. CARLA_SAFE_ASSERT(opcode == kEnginePostActionNull);
  294. opcode = kEnginePostActionNull;
  295. pluginId = 0;
  296. value = 0;
  297. needsPost = false;
  298. postDone = false;
  299. mutex.unlock();
  300. }
  301. // -----------------------------------------------------------------------
  302. // Helper functions
  303. EngineEvent* CarlaEngine::getInternalEventBuffer(const bool isInput) const noexcept
  304. {
  305. return isInput ? pData->events.in : pData->events.out;
  306. }
  307. // -----------------------------------------------------------------------
  308. // CarlaEngine::ProtectedData
  309. CarlaEngine::ProtectedData::ProtectedData(CarlaEngine* const engine)
  310. : thread(engine),
  311. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  312. osc(engine),
  313. #endif
  314. callback(nullptr),
  315. callbackPtr(nullptr),
  316. fileCallback(nullptr),
  317. fileCallbackPtr(nullptr),
  318. actionCanceled(false),
  319. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  320. loadingProject(false),
  321. ignoreClientPrefix(false),
  322. currentProjectFilename(),
  323. currentProjectFolder(),
  324. #endif
  325. bufferSize(0),
  326. sampleRate(0.0),
  327. aboutToClose(false),
  328. isIdling(0),
  329. curPluginCount(0),
  330. maxPluginNumber(0),
  331. nextPluginId(0),
  332. envMutex(),
  333. lastError(),
  334. name(),
  335. options(),
  336. timeInfo(),
  337. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  338. plugins(nullptr),
  339. xruns(0),
  340. dspLoad(0.0f),
  341. #endif
  342. pluginsToDelete(),
  343. events(),
  344. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  345. graph(engine),
  346. #endif
  347. time(timeInfo, options.transportMode),
  348. nextAction()
  349. {
  350. #ifdef BUILD_BRIDGE_ALTERNATIVE_ARCH
  351. plugins[0].plugin = nullptr;
  352. carla_zeroStructs(plugins[0].peaks, 1);
  353. #endif
  354. }
  355. CarlaEngine::ProtectedData::~ProtectedData()
  356. {
  357. CARLA_SAFE_ASSERT(curPluginCount == 0);
  358. CARLA_SAFE_ASSERT(maxPluginNumber == 0);
  359. CARLA_SAFE_ASSERT(nextPluginId == 0);
  360. CARLA_SAFE_ASSERT(isIdling == 0);
  361. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  362. CARLA_SAFE_ASSERT(plugins == nullptr);
  363. #endif
  364. if (pluginsToDelete.size() != 0)
  365. {
  366. for (std::vector<CarlaPluginPtr>::iterator it = pluginsToDelete.begin(); it != pluginsToDelete.end(); ++it)
  367. {
  368. carla_stderr2("Plugin not yet deleted, name: '%s', usage count: '%u'",
  369. (*it)->getName(), it->use_count());
  370. }
  371. }
  372. pluginsToDelete.clear();
  373. }
  374. // -----------------------------------------------------------------------
  375. bool CarlaEngine::ProtectedData::init(const char* const clientName)
  376. {
  377. CARLA_SAFE_ASSERT_RETURN_INTERNAL_ERR(name.isEmpty(), "Invalid engine internal data (err #1)");
  378. CARLA_SAFE_ASSERT_RETURN_INTERNAL_ERR(events.in == nullptr, "Invalid engine internal data (err #4)");
  379. CARLA_SAFE_ASSERT_RETURN_INTERNAL_ERR(events.out == nullptr, "Invalid engine internal data (err #5)");
  380. CARLA_SAFE_ASSERT_RETURN_INTERNAL_ERR(clientName != nullptr && clientName[0] != '\0', "Invalid client name");
  381. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  382. CARLA_SAFE_ASSERT_RETURN_INTERNAL_ERR(plugins == nullptr, "Invalid engine internal data (err #3)");
  383. #endif
  384. aboutToClose = false;
  385. curPluginCount = 0;
  386. nextPluginId = 0;
  387. switch (options.processMode)
  388. {
  389. case ENGINE_PROCESS_MODE_CONTINUOUS_RACK:
  390. maxPluginNumber = MAX_RACK_PLUGINS;
  391. options.forceStereo = true;
  392. break;
  393. case ENGINE_PROCESS_MODE_PATCHBAY:
  394. maxPluginNumber = MAX_PATCHBAY_PLUGINS;
  395. break;
  396. case ENGINE_PROCESS_MODE_BRIDGE:
  397. maxPluginNumber = 1;
  398. break;
  399. default:
  400. maxPluginNumber = MAX_DEFAULT_PLUGINS;
  401. break;
  402. }
  403. switch (options.processMode)
  404. {
  405. case ENGINE_PROCESS_MODE_CONTINUOUS_RACK:
  406. case ENGINE_PROCESS_MODE_PATCHBAY:
  407. case ENGINE_PROCESS_MODE_BRIDGE:
  408. events.in = new EngineEvent[kMaxEngineEventInternalCount];
  409. events.out = new EngineEvent[kMaxEngineEventInternalCount];
  410. carla_zeroStructs(events.in, kMaxEngineEventInternalCount);
  411. carla_zeroStructs(events.out, kMaxEngineEventInternalCount);
  412. break;
  413. default:
  414. break;
  415. }
  416. nextPluginId = maxPluginNumber;
  417. name = clientName;
  418. name.toBasic();
  419. timeInfo.clear();
  420. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  421. if (options.oscEnabled)
  422. osc.init(clientName, options.oscPortTCP, options.oscPortUDP);
  423. #endif
  424. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  425. plugins = new EnginePluginData[maxPluginNumber];
  426. xruns = 0;
  427. dspLoad = 0.0f;
  428. #endif
  429. nextAction.clearAndReset();
  430. thread.startThread();
  431. return true;
  432. }
  433. void CarlaEngine::ProtectedData::close()
  434. {
  435. CARLA_SAFE_ASSERT(name.isNotEmpty());
  436. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  437. CARLA_SAFE_ASSERT(plugins != nullptr);
  438. CARLA_SAFE_ASSERT(nextPluginId == maxPluginNumber);
  439. #endif
  440. aboutToClose = true;
  441. thread.stopThread(500);
  442. nextAction.clearAndReset();
  443. #if defined(HAVE_LIBLO) && !defined(BUILD_BRIDGE)
  444. osc.close();
  445. #endif
  446. aboutToClose = false;
  447. curPluginCount = 0;
  448. maxPluginNumber = 0;
  449. nextPluginId = 0;
  450. deletePluginsAsNeeded();
  451. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  452. if (plugins != nullptr)
  453. {
  454. delete[] plugins;
  455. plugins = nullptr;
  456. }
  457. #endif
  458. events.clear();
  459. name.clear();
  460. }
  461. void CarlaEngine::ProtectedData::initTime(const char* const features)
  462. {
  463. time.init(bufferSize, sampleRate);
  464. #if defined(HAVE_HYLIA) && !defined(BUILD_BRIDGE)
  465. const bool linkEnabled = features != nullptr && std::strstr(features, ":link:") != nullptr;
  466. time.enableLink(linkEnabled);
  467. #else
  468. return;
  469. // unused
  470. (void)features;
  471. #endif
  472. }
  473. // -----------------------------------------------------------------------
  474. void CarlaEngine::ProtectedData::deletePluginsAsNeeded()
  475. {
  476. for (bool stop;;)
  477. {
  478. stop = true;
  479. for (std::vector<CarlaPluginPtr>::iterator it = pluginsToDelete.begin(); it != pluginsToDelete.end(); ++it)
  480. {
  481. if (it->use_count() == 1)
  482. {
  483. stop = false;
  484. pluginsToDelete.erase(it);
  485. break;
  486. }
  487. }
  488. if (stop)
  489. break;
  490. }
  491. }
  492. // -----------------------------------------------------------------------
  493. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  494. void CarlaEngine::ProtectedData::doPluginRemove(const uint pluginId) noexcept
  495. {
  496. CARLA_SAFE_ASSERT_RETURN(curPluginCount > 0,);
  497. CARLA_SAFE_ASSERT_RETURN(pluginId < curPluginCount,);
  498. --curPluginCount;
  499. // move all plugins 1 spot backwards
  500. for (uint i=pluginId; i < curPluginCount; ++i)
  501. {
  502. const CarlaPluginPtr plugin = plugins[i+1].plugin;
  503. CARLA_SAFE_ASSERT_BREAK(plugin.get() != nullptr);
  504. plugin->setId(i);
  505. plugins[i].plugin = plugin;
  506. carla_zeroStruct(plugins[i].peaks);
  507. }
  508. const uint id = curPluginCount;
  509. // reset last plugin (now removed)
  510. plugins[id].plugin.reset();
  511. carla_zeroFloats(plugins[id].peaks, 4);
  512. }
  513. void CarlaEngine::ProtectedData::doPluginsSwitch(const uint idA, const uint idB) noexcept
  514. {
  515. CARLA_SAFE_ASSERT_RETURN(curPluginCount >= 2,);
  516. CARLA_SAFE_ASSERT_RETURN(idA < curPluginCount,);
  517. CARLA_SAFE_ASSERT_RETURN(idB < curPluginCount,);
  518. const CarlaPluginPtr pluginA = plugins[idA].plugin;
  519. CARLA_SAFE_ASSERT_RETURN(pluginA.get() != nullptr,);
  520. const CarlaPluginPtr pluginB = plugins[idB].plugin;
  521. CARLA_SAFE_ASSERT_RETURN(pluginB.get() != nullptr,);
  522. pluginA->setId(idB);
  523. plugins[idA].plugin = pluginB;
  524. pluginB->setId(idA);
  525. plugins[idB].plugin = pluginA;
  526. }
  527. #endif
  528. void CarlaEngine::ProtectedData::doNextPluginAction() noexcept
  529. {
  530. if (! nextAction.mutex.tryLock())
  531. return;
  532. const EnginePostAction opcode = nextAction.opcode;
  533. const bool needsPost = nextAction.needsPost;
  534. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  535. const uint pluginId = nextAction.pluginId;
  536. const uint value = nextAction.value;
  537. #endif
  538. nextAction.opcode = kEnginePostActionNull;
  539. nextAction.pluginId = 0;
  540. nextAction.value = 0;
  541. nextAction.needsPost = false;
  542. nextAction.mutex.unlock();
  543. switch (opcode)
  544. {
  545. case kEnginePostActionNull:
  546. break;
  547. case kEnginePostActionZeroCount:
  548. curPluginCount = 0;
  549. break;
  550. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  551. case kEnginePostActionRemovePlugin:
  552. doPluginRemove(pluginId);
  553. break;
  554. case kEnginePostActionSwitchPlugins:
  555. doPluginsSwitch(pluginId, value);
  556. break;
  557. #endif
  558. }
  559. if (needsPost)
  560. {
  561. if (nextAction.sem != nullptr)
  562. carla_sem_post(*nextAction.sem);
  563. nextAction.postDone = true;
  564. }
  565. }
  566. // -----------------------------------------------------------------------
  567. // PendingRtEventsRunner
  568. static int64_t getTimeInMicroseconds() noexcept
  569. {
  570. #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  571. struct timeval tv;
  572. gettimeofday(&tv, nullptr);
  573. return (tv.tv_sec * 1000000) + tv.tv_usec;
  574. #else
  575. struct timespec ts;
  576. # ifdef CLOCK_MONOTONIC_RAW
  577. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  578. # else
  579. clock_gettime(CLOCK_MONOTONIC, &ts);
  580. # endif
  581. return (ts.tv_sec * 1000000) + (ts.tv_nsec / 1000);
  582. #endif
  583. }
  584. PendingRtEventsRunner::PendingRtEventsRunner(CarlaEngine* const engine,
  585. const uint32_t frames,
  586. const bool calcDSPLoad) noexcept
  587. : pData(engine->pData),
  588. prevTime(calcDSPLoad ? getTimeInMicroseconds() : 0)
  589. {
  590. pData->time.preProcess(frames);
  591. }
  592. PendingRtEventsRunner::~PendingRtEventsRunner() noexcept
  593. {
  594. pData->doNextPluginAction();
  595. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  596. if (prevTime > 0)
  597. {
  598. const int64_t newTime = getTimeInMicroseconds();
  599. if (newTime < prevTime)
  600. return;
  601. const double timeDiff = static_cast<double>(newTime - prevTime) / 1000000.0;
  602. const double maxTime = pData->bufferSize / pData->sampleRate;
  603. const float dspLoad = static_cast<float>(timeDiff / maxTime) * 100.0f;
  604. if (dspLoad > pData->dspLoad)
  605. pData->dspLoad = std::min(100.0f, dspLoad);
  606. else
  607. pData->dspLoad *= static_cast<float>(1.0 - maxTime) + 1e-12f;
  608. }
  609. #endif
  610. }
  611. // -----------------------------------------------------------------------
  612. // ScopedActionLock
  613. ScopedActionLock::ScopedActionLock(CarlaEngine* const engine,
  614. const EnginePostAction action,
  615. const uint pluginId,
  616. const uint value) noexcept
  617. : pData(engine->pData)
  618. {
  619. CARLA_SAFE_ASSERT_RETURN(action != kEnginePostActionNull,);
  620. {
  621. const CarlaMutexLocker cml(pData->nextAction.mutex);
  622. CARLA_SAFE_ASSERT_RETURN(pData->nextAction.opcode == kEnginePostActionNull,);
  623. pData->nextAction.opcode = action;
  624. pData->nextAction.pluginId = pluginId;
  625. pData->nextAction.value = value;
  626. pData->nextAction.needsPost = engine->isRunning();
  627. pData->nextAction.postDone = false;
  628. }
  629. #ifdef BUILD_BRIDGE
  630. #define ACTION_MSG_PREFIX "Bridge: "
  631. #else
  632. #define ACTION_MSG_PREFIX ""
  633. #endif
  634. if (pData->nextAction.needsPost)
  635. {
  636. #if defined(DEBUG) || defined(BUILD_BRIDGE)
  637. // block wait for unlock on processing side
  638. carla_stdout(ACTION_MSG_PREFIX "ScopedPluginAction(%i) - blocking START", pluginId);
  639. #endif
  640. bool engineStoppedWhileWaiting = false;
  641. if (! pData->nextAction.postDone)
  642. {
  643. for (int i = 10; --i >= 0;)
  644. {
  645. if (pData->nextAction.sem != nullptr)
  646. {
  647. if (carla_sem_timedwait(*pData->nextAction.sem, 200))
  648. break;
  649. }
  650. else
  651. {
  652. carla_msleep(200);
  653. }
  654. if (! engine->isRunning())
  655. {
  656. engineStoppedWhileWaiting = true;
  657. break;
  658. }
  659. }
  660. }
  661. #if defined(DEBUG) || defined(BUILD_BRIDGE)
  662. carla_stdout(ACTION_MSG_PREFIX "ScopedPluginAction(%i) - blocking DONE", pluginId);
  663. #endif
  664. // check if anything went wrong...
  665. if (! pData->nextAction.postDone)
  666. {
  667. bool needsCorrection = false;
  668. {
  669. const CarlaMutexLocker cml(pData->nextAction.mutex);
  670. if (pData->nextAction.opcode != kEnginePostActionNull)
  671. {
  672. needsCorrection = true;
  673. pData->nextAction.needsPost = false;
  674. }
  675. }
  676. if (needsCorrection)
  677. {
  678. pData->doNextPluginAction();
  679. if (! engineStoppedWhileWaiting)
  680. carla_stderr2(ACTION_MSG_PREFIX "Failed to wait for engine, is audio not running?");
  681. }
  682. }
  683. }
  684. else
  685. {
  686. pData->doNextPluginAction();
  687. }
  688. }
  689. ScopedActionLock::~ScopedActionLock() noexcept
  690. {
  691. CARLA_SAFE_ASSERT(pData->nextAction.opcode == kEnginePostActionNull);
  692. }
  693. // -----------------------------------------------------------------------
  694. // ScopedThreadStopper
  695. ScopedThreadStopper::ScopedThreadStopper(CarlaEngine* const e) noexcept
  696. : engine(e),
  697. pData(e->pData)
  698. {
  699. pData->thread.stopThread(500);
  700. }
  701. ScopedThreadStopper::~ScopedThreadStopper() noexcept
  702. {
  703. if (engine->isRunning() && ! pData->aboutToClose)
  704. pData->thread.startThread();
  705. }
  706. // -----------------------------------------------------------------------
  707. // ScopedEngineEnvironmentLocker
  708. ScopedEngineEnvironmentLocker::ScopedEngineEnvironmentLocker(CarlaEngine* const engine) noexcept
  709. : pData(engine->pData)
  710. {
  711. pData->envMutex.lock();
  712. }
  713. ScopedEngineEnvironmentLocker::~ScopedEngineEnvironmentLocker() noexcept
  714. {
  715. pData->envMutex.unlock();
  716. }
  717. // -----------------------------------------------------------------------
  718. CARLA_BACKEND_END_NAMESPACE