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.

740 lines
21KB

  1. /*
  2. * Carla Native Plugins
  3. * Copyright (C) 2013-2019 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 GPL.txt file
  16. */
  17. #ifndef AUDIO_BASE_HPP_INCLUDED
  18. #define AUDIO_BASE_HPP_INCLUDED
  19. #include "CarlaThread.hpp"
  20. #include "CarlaMathUtils.hpp"
  21. extern "C" {
  22. #include "audio_decoder/ad.h"
  23. }
  24. #include "water/threads/ScopedLock.h"
  25. #include "water/threads/SpinLock.h"
  26. #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  27. # pragma GCC diagnostic push
  28. # pragma GCC diagnostic ignored "-Weffc++"
  29. #endif
  30. #include "zita-resampler/resampler.h"
  31. #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  32. # pragma GCC diagnostic pop
  33. #endif
  34. #ifdef CARLA_OS_WIN
  35. # include <windows.h>
  36. # define CARLA_MLOCK(ptr, size) VirtualLock((ptr), (size))
  37. #else
  38. # include <sys/mman.h>
  39. # define CARLA_MLOCK(ptr, size) mlock((ptr), (size))
  40. #endif
  41. typedef struct adinfo ADInfo;
  42. struct AudioFilePool {
  43. float* buffer[2];
  44. float* tmpbuf[2];
  45. uint32_t numFrames;
  46. volatile uint64_t startFrame;
  47. water::SpinLock mutex;
  48. #ifdef CARLA_PROPER_CPP11_SUPPORT
  49. AudioFilePool() noexcept
  50. : buffer{nullptr},
  51. tmpbuf{nullptr},
  52. numFrames(0),
  53. startFrame(0),
  54. mutex() {}
  55. #else
  56. AudioFilePool() noexcept
  57. : numFrames(0),
  58. startFrame(0),
  59. mutex()
  60. {
  61. buffer[0] = buffer[1] = nullptr;
  62. tmpbuf[0] = tmpbuf[1] = nullptr;
  63. }
  64. #endif
  65. ~AudioFilePool()
  66. {
  67. destroy();
  68. }
  69. void create(const uint32_t desiredNumFrames, const bool withTempBuffers)
  70. {
  71. CARLA_ASSERT(buffer[0] == nullptr);
  72. CARLA_ASSERT(buffer[1] == nullptr);
  73. CARLA_ASSERT(tmpbuf[0] == nullptr);
  74. CARLA_ASSERT(tmpbuf[1] == nullptr);
  75. CARLA_ASSERT(startFrame == 0);
  76. CARLA_ASSERT(numFrames == 0);
  77. buffer[0] = new float[desiredNumFrames];
  78. buffer[1] = new float[desiredNumFrames];
  79. CARLA_MLOCK(buffer[0], sizeof(float)*desiredNumFrames);
  80. CARLA_MLOCK(buffer[1], sizeof(float)*desiredNumFrames);
  81. if (withTempBuffers)
  82. {
  83. tmpbuf[0] = new float[desiredNumFrames];
  84. tmpbuf[1] = new float[desiredNumFrames];
  85. CARLA_MLOCK(tmpbuf[0], sizeof(float)*desiredNumFrames);
  86. CARLA_MLOCK(tmpbuf[1], sizeof(float)*desiredNumFrames);
  87. }
  88. reset(desiredNumFrames);
  89. }
  90. void destroy() noexcept
  91. {
  92. {
  93. const water::GenericScopedLock<water::SpinLock> gsl(mutex);
  94. startFrame = 0;
  95. numFrames = 0;
  96. }
  97. if (buffer[0] != nullptr)
  98. {
  99. delete[] buffer[0];
  100. buffer[0] = nullptr;
  101. }
  102. if (buffer[1] != nullptr)
  103. {
  104. delete[] buffer[1];
  105. buffer[1] = nullptr;
  106. }
  107. if (tmpbuf[0] != nullptr)
  108. {
  109. delete[] tmpbuf[0];
  110. tmpbuf[0] = nullptr;
  111. }
  112. if (tmpbuf[1] != nullptr)
  113. {
  114. delete[] tmpbuf[1];
  115. tmpbuf[1] = nullptr;
  116. }
  117. }
  118. void reset(const uint32_t desiredNumFrames) noexcept
  119. {
  120. if (desiredNumFrames != 0)
  121. {
  122. carla_zeroFloats(buffer[0], desiredNumFrames);
  123. carla_zeroFloats(buffer[1], desiredNumFrames);
  124. if (tmpbuf[0] != nullptr)
  125. carla_zeroFloats(tmpbuf[0], desiredNumFrames);
  126. if (tmpbuf[1] != nullptr)
  127. carla_zeroFloats(tmpbuf[1], desiredNumFrames);
  128. }
  129. const water::GenericScopedLock<water::SpinLock> gsl(mutex);
  130. {
  131. startFrame = 0;
  132. numFrames = desiredNumFrames;
  133. }
  134. }
  135. CARLA_DECLARE_NON_COPY_STRUCT(AudioFilePool)
  136. };
  137. class AudioFileReader
  138. {
  139. public:
  140. AudioFileReader()
  141. : fEntireFileLoaded(false),
  142. fLoopingMode(true),
  143. fNeedsFrame(0),
  144. fNeedsRead(false),
  145. fFilePtr(nullptr),
  146. fFileNfo(),
  147. fMaxFrame(0),
  148. fResampleRatio(0.0),
  149. fPollTempData(nullptr),
  150. fPollTempSize(0),
  151. fResampleTempData(nullptr),
  152. fResampleTempSize(0),
  153. fPool(),
  154. fResampler(),
  155. fReaderMutex()
  156. {
  157. static bool adInitiated = false;
  158. if (! adInitiated)
  159. {
  160. ad_init();
  161. adInitiated = true;
  162. }
  163. ad_clear_nfo(&fFileNfo);
  164. }
  165. ~AudioFileReader()
  166. {
  167. cleanup();
  168. }
  169. void cleanup()
  170. {
  171. fPool.destroy();
  172. fEntireFileLoaded = false;
  173. if (fFilePtr != nullptr)
  174. {
  175. ad_close(fFilePtr);
  176. fFilePtr = nullptr;
  177. }
  178. if (fPollTempData != nullptr)
  179. {
  180. delete[] fPollTempData;
  181. fPollTempData = nullptr;
  182. fPollTempSize = 0;
  183. }
  184. if (fResampleTempData != nullptr)
  185. {
  186. delete[] fResampleTempData;
  187. fResampleTempData = nullptr;
  188. fResampleTempSize = 0;
  189. }
  190. }
  191. void destroy()
  192. {
  193. const CarlaMutexLocker cml(fReaderMutex);
  194. fPool.destroy();
  195. fNeedsFrame = 0;
  196. fNeedsRead = false;
  197. }
  198. bool isEntireFileLoaded() const noexcept
  199. {
  200. return fEntireFileLoaded;
  201. }
  202. uint32_t getMaxFrame() const noexcept
  203. {
  204. return fMaxFrame;
  205. }
  206. uint64_t getPoolStartFrame() const noexcept
  207. {
  208. return fPool.startFrame;
  209. }
  210. uint32_t getPoolNumFrames() const noexcept
  211. {
  212. return fPool.numFrames;
  213. }
  214. ADInfo getFileInfo() const noexcept
  215. {
  216. return fFileNfo;
  217. }
  218. void setLoopingMode(const bool on) noexcept
  219. {
  220. fLoopingMode = on;
  221. }
  222. void setNeedsRead(const uint64_t frame) noexcept
  223. {
  224. if (fEntireFileLoaded)
  225. return;
  226. fNeedsFrame = frame;
  227. fNeedsRead = true;
  228. }
  229. bool loadFilename(const char* const filename, const uint32_t sampleRate)
  230. {
  231. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && *filename != '\0', false);
  232. const CarlaMutexLocker cml(fReaderMutex);
  233. cleanup();
  234. ad_clear_nfo(&fFileNfo);
  235. // open new
  236. fFilePtr = ad_open(filename, &fFileNfo);
  237. if (fFilePtr == nullptr)
  238. return false;
  239. ad_dump_nfo(99, &fFileNfo);
  240. // Fix for misinformation using libsndfile
  241. if (fFileNfo.frames % fFileNfo.channels)
  242. --fFileNfo.frames;
  243. if (fFileNfo.frames <= 0)
  244. carla_stderr("L: filename \"%s\" has 0 frames", filename);
  245. if ((fFileNfo.channels == 1 || fFileNfo.channels == 2) && fFileNfo.frames > 0)
  246. {
  247. // valid
  248. const uint32_t fileNumFrames = static_cast<uint32_t>(fFileNfo.frames);
  249. const uint32_t maxPoolNumFrames = sampleRate * 30;
  250. const bool needsResample = fFileNfo.sample_rate != sampleRate;
  251. if (needsResample)
  252. {
  253. if (! fResampler.setup(fFileNfo.sample_rate, sampleRate, fFileNfo.channels, 32))
  254. {
  255. ad_clear_nfo(&fFileNfo);
  256. ad_close(fFilePtr);
  257. fFilePtr = nullptr;
  258. carla_stderr2("loadFilename error, resampler setup failed");
  259. return false;
  260. }
  261. fResampleRatio = static_cast<double>(sampleRate) / static_cast<double>(fFileNfo.sample_rate);
  262. }
  263. else
  264. {
  265. fResampler.clear();
  266. fResampleRatio = 0.0;
  267. }
  268. if (fileNumFrames <= maxPoolNumFrames)
  269. {
  270. // entire file fits in a small pool, lets read it now
  271. fPool.create(needsResample ? static_cast<uint32_t>(static_cast<double>(fileNumFrames) * fResampleRatio + 0.5)
  272. : fileNumFrames, false);
  273. readEntireFileIntoPool(needsResample);
  274. ad_close(fFilePtr);
  275. fFilePtr = nullptr;
  276. }
  277. else
  278. {
  279. // file is too big for our audio pool, we need an extra buffer
  280. const uint32_t poolNumFrames = sampleRate * 1;
  281. const uint pollTempSize = poolNumFrames * fFileNfo.channels;
  282. uint resampleTempSize = 0;
  283. fPool.create(poolNumFrames, true);
  284. try {
  285. fPollTempData = new float[pollTempSize];
  286. } catch (...) {
  287. ad_clear_nfo(&fFileNfo);
  288. ad_close(fFilePtr);
  289. fFilePtr = nullptr;
  290. carla_stderr2("loadFilename error, out of memory");
  291. return false;
  292. }
  293. CARLA_MLOCK(fPollTempData, sizeof(float)*pollTempSize);
  294. if (needsResample)
  295. {
  296. resampleTempSize = static_cast<uint32_t>(static_cast<double>(poolNumFrames) * fResampleRatio + 0.5);
  297. resampleTempSize *= fFileNfo.channels;
  298. try {
  299. fResampleTempData = new float[resampleTempSize];
  300. } catch (...) {
  301. delete[] fPollTempData;
  302. fPollTempData = nullptr;
  303. ad_clear_nfo(&fFileNfo);
  304. ad_close(fFilePtr);
  305. fFilePtr = nullptr;
  306. carla_stderr2("loadFilename error, out of memory");
  307. return false;
  308. }
  309. CARLA_MLOCK(fResampleTempData, sizeof(float)*resampleTempSize);
  310. }
  311. fPollTempSize = pollTempSize;
  312. fResampleTempSize = resampleTempSize;
  313. }
  314. fMaxFrame = carla_isNotZero(fResampleRatio)
  315. ? static_cast<uint32_t>(static_cast<double>(fileNumFrames) * fResampleRatio + 0.5)
  316. : fileNumFrames;
  317. fNeedsRead = true;
  318. return true;
  319. }
  320. else
  321. {
  322. // invalid
  323. ad_clear_nfo(&fFileNfo);
  324. ad_close(fFilePtr);
  325. fFilePtr = nullptr;
  326. return false;
  327. }
  328. }
  329. void putAllData(AudioFilePool& pool)
  330. {
  331. const water::GenericScopedLock<water::SpinLock> gsl(fPool.mutex);
  332. CARLA_SAFE_ASSERT_RETURN(pool.numFrames == fPool.numFrames,);
  333. pool.startFrame = fPool.startFrame;
  334. carla_copyFloats(pool.buffer[0], fPool.buffer[0], fPool.numFrames);
  335. carla_copyFloats(pool.buffer[1], fPool.buffer[1], fPool.numFrames);
  336. }
  337. bool tryPutData(float* const out1,
  338. float* const out2,
  339. uint64_t framePos,
  340. const uint32_t frames,
  341. const bool isOffline,
  342. bool& needsRead)
  343. {
  344. const water::GenericScopedLock<water::SpinLock> gsl(fPool.mutex);
  345. CARLA_SAFE_ASSERT_RETURN(fPool.numFrames != 0, false);
  346. if (framePos >= fMaxFrame)
  347. {
  348. if (fLoopingMode)
  349. framePos %= fMaxFrame;
  350. else
  351. return false;
  352. }
  353. uint64_t frameDiff;
  354. const uint64_t numFramesNearEnd = fPool.numFrames*3/5;
  355. if (framePos < fPool.startFrame)
  356. {
  357. if (fPool.startFrame + fPool.numFrames <= fMaxFrame)
  358. {
  359. needsRead = true;
  360. setNeedsRead(framePos);
  361. return false;
  362. }
  363. frameDiff = framePos + (fMaxFrame - fPool.startFrame);
  364. if (frameDiff + frames >= fPool.numFrames)
  365. {
  366. needsRead = true;
  367. setNeedsRead(framePos);
  368. return false;
  369. }
  370. carla_copyFloats(out1, fPool.buffer[0] + frameDiff, frames);
  371. carla_copyFloats(out2, fPool.buffer[1] + frameDiff, frames);
  372. }
  373. else
  374. {
  375. frameDiff = framePos - fPool.startFrame;
  376. if (frameDiff + frames >= fPool.numFrames)
  377. {
  378. needsRead = true;
  379. setNeedsRead(framePos);
  380. return false;
  381. }
  382. carla_copyFloats(out1, fPool.buffer[0] + frameDiff, frames);
  383. carla_copyFloats(out2, fPool.buffer[1] + frameDiff, frames);
  384. }
  385. if (frameDiff > numFramesNearEnd)
  386. {
  387. needsRead = true;
  388. setNeedsRead(framePos + (isOffline ? 0 : frames));
  389. }
  390. return true;
  391. }
  392. void readEntireFileIntoPool(const bool needsResample)
  393. {
  394. CARLA_SAFE_ASSERT_RETURN(fPool.numFrames > 0,);
  395. const uint numChannels = fFileNfo.channels;
  396. const uint fileNumFrames = static_cast<uint>(fFileNfo.frames);
  397. const uint bufferSize = fileNumFrames * numChannels;
  398. float* const buffer = (float*)std::calloc(bufferSize, sizeof(float));
  399. CARLA_SAFE_ASSERT_RETURN(buffer != nullptr,);
  400. ad_seek(fFilePtr, 0);
  401. ssize_t rv = ad_read(fFilePtr, buffer, bufferSize);
  402. CARLA_SAFE_ASSERT_INT2_RETURN(rv == static_cast<ssize_t>(bufferSize),
  403. static_cast<int>(rv),
  404. static_cast<int>(bufferSize),
  405. std::free(buffer));
  406. float* rbuffer;
  407. if (needsResample)
  408. {
  409. const uint rbufferSize = fPool.numFrames * numChannels;
  410. rbuffer = (float*)std::calloc(rbufferSize, sizeof(float));
  411. CARLA_SAFE_ASSERT_RETURN(rbuffer != nullptr, std::free(buffer););
  412. rv = static_cast<ssize_t>(rbufferSize);
  413. fResampler.inp_count = fileNumFrames;
  414. fResampler.out_count = fPool.numFrames;
  415. fResampler.inp_data = buffer;
  416. fResampler.out_data = rbuffer;
  417. fResampler.process();
  418. CARLA_SAFE_ASSERT_INT(fResampler.inp_count <= 2, fResampler.inp_count);
  419. }
  420. else
  421. {
  422. rbuffer = buffer;
  423. }
  424. {
  425. // lock, and put data asap
  426. const water::GenericScopedLock<water::SpinLock> gsl(fPool.mutex);
  427. if (numChannels == 1)
  428. {
  429. for (ssize_t i=0, j=0; j < rv; ++i, ++j)
  430. fPool.buffer[0][i] = fPool.buffer[1][i] = rbuffer[j];
  431. }
  432. else
  433. {
  434. for (ssize_t i=0, j=0; j < rv; ++j)
  435. {
  436. if (j % 2 == 0)
  437. {
  438. fPool.buffer[0][i] = rbuffer[j];
  439. }
  440. else
  441. {
  442. fPool.buffer[1][i] = rbuffer[j];
  443. ++i;
  444. }
  445. }
  446. }
  447. }
  448. if (rbuffer != buffer)
  449. std::free(rbuffer);
  450. std::free(buffer);
  451. fEntireFileLoaded = true;
  452. }
  453. void readPoll()
  454. {
  455. const CarlaMutexLocker cml(fReaderMutex);
  456. if (fMaxFrame == 0 || fFileNfo.channels == 0 || fFilePtr == nullptr)
  457. {
  458. carla_debug("R: no song loaded");
  459. fNeedsFrame = 0;
  460. fNeedsRead = false;
  461. return;
  462. }
  463. if (fPollTempData == nullptr)
  464. {
  465. carla_debug("R: nothing to poll");
  466. fNeedsFrame = 0;
  467. fNeedsRead = false;
  468. return;
  469. }
  470. uint64_t lastFrame = fNeedsFrame;
  471. int64_t readFrameCheck;
  472. if (lastFrame >= fMaxFrame)
  473. {
  474. if (fLoopingMode)
  475. {
  476. const uint64_t readFrameCheckLoop = lastFrame % fMaxFrame;
  477. CARLA_SAFE_ASSERT_RETURN(readFrameCheckLoop < INT32_MAX,);
  478. carla_debug("R: transport out of bounds for loop");
  479. readFrameCheck = static_cast<int64_t>(readFrameCheckLoop);
  480. }
  481. else
  482. {
  483. carla_debug("R: transport out of bounds");
  484. fNeedsFrame = 0;
  485. fNeedsRead = false;
  486. return;
  487. }
  488. }
  489. else
  490. {
  491. CARLA_SAFE_ASSERT_RETURN(lastFrame < INT32_MAX,);
  492. readFrameCheck = static_cast<int64_t>(lastFrame);
  493. }
  494. const int64_t readFrame = readFrameCheck;
  495. // temp data buffer
  496. carla_zeroFloats(fPollTempData, fPollTempSize);
  497. {
  498. #if 0
  499. const int32_t sampleRate = 44100;
  500. carla_debug("R: poll data - reading at frame %li, time %li:%02li, lastFrame %li",
  501. readFrame, readFrame/sampleRate/60, (readFrame/sampleRate) % 60, lastFrame);
  502. #endif
  503. const int64_t readFrameReal = carla_isNotZero(fResampleRatio)
  504. ? static_cast<int64_t>(static_cast<double>(readFrame) / fResampleRatio + 0.5)
  505. : readFrame;
  506. ad_seek(fFilePtr, readFrameReal);
  507. size_t i = 0;
  508. ssize_t j = 0;
  509. ssize_t rv = ad_read(fFilePtr, fPollTempData, fPollTempSize);
  510. if (rv < 0)
  511. {
  512. carla_stderr("R: ad_read1 failed");
  513. fNeedsFrame = 0;
  514. fNeedsRead = false;
  515. return;
  516. }
  517. const size_t urv = static_cast<size_t>(rv);
  518. // see if we can read more
  519. if (readFrameReal + rv >= static_cast<ssize_t>(fFileNfo.frames) && urv < fPollTempSize)
  520. {
  521. carla_debug("R: from start");
  522. ad_seek(fFilePtr, 0);
  523. j = ad_read(fFilePtr, fPollTempData+urv, fPollTempSize-urv);
  524. if (j < 0)
  525. {
  526. carla_stderr("R: ad_read2 failed");
  527. fNeedsFrame = 0;
  528. fNeedsRead = false;
  529. return;
  530. }
  531. rv += j;
  532. }
  533. carla_debug("R: reading %li frames at frame %lu", rv, readFrameCheck);
  534. // local copy
  535. const uint32_t poolNumFrames = fPool.numFrames;
  536. float* const pbuffer0 = fPool.tmpbuf[0];
  537. float* const pbuffer1 = fPool.tmpbuf[1];
  538. const float* tmpbuf = fPollTempData;
  539. // resample as needed
  540. if (fResampleTempSize != 0)
  541. {
  542. tmpbuf = fResampleTempData;
  543. fResampler.inp_count = static_cast<uint>(rv / fFileNfo.channels);
  544. fResampler.out_count = fResampleTempSize / fFileNfo.channels;
  545. fResampler.inp_data = fPollTempData;
  546. fResampler.out_data = fResampleTempData;
  547. fResampler.process();
  548. CARLA_ASSERT_INT(fResampler.inp_count <= 1, fResampler.inp_count);
  549. }
  550. j = 0;
  551. do {
  552. if (fFileNfo.channels == 1)
  553. {
  554. for (; i < poolNumFrames && j < rv; ++i, ++j)
  555. pbuffer0[i] = pbuffer1[i] = tmpbuf[j];
  556. }
  557. else
  558. {
  559. for (; i < poolNumFrames && j < rv; ++j)
  560. {
  561. if (j % 2 == 0)
  562. {
  563. pbuffer0[i] = tmpbuf[j];
  564. }
  565. else
  566. {
  567. pbuffer1[i] = tmpbuf[j];
  568. ++i;
  569. }
  570. }
  571. }
  572. if (i >= poolNumFrames)
  573. break;
  574. if (rv == fFileNfo.frames)
  575. {
  576. // full file read
  577. j = 0;
  578. carla_debug("R: full file was read, filling buffers again");
  579. }
  580. else
  581. {
  582. carla_debug("read break, not enough space");
  583. carla_zeroFloats(pbuffer0, poolNumFrames - i);
  584. carla_zeroFloats(pbuffer1, poolNumFrames - i);
  585. break;
  586. }
  587. } while (i < poolNumFrames);
  588. // lock, and put data asap
  589. const water::GenericScopedLock<water::SpinLock> gsl(fPool.mutex);
  590. std::memcpy(fPool.buffer[0], pbuffer0, sizeof(float)*poolNumFrames);
  591. std::memcpy(fPool.buffer[1], pbuffer1, sizeof(float)*poolNumFrames);
  592. fPool.startFrame = static_cast<uint64_t>(readFrame);
  593. }
  594. fNeedsRead = false;
  595. }
  596. private:
  597. bool fEntireFileLoaded;
  598. bool fLoopingMode;
  599. volatile uint64_t fNeedsFrame;
  600. volatile bool fNeedsRead;
  601. void* fFilePtr;
  602. ADInfo fFileNfo;
  603. uint32_t fMaxFrame;
  604. double fResampleRatio;
  605. float* fPollTempData;
  606. uint fPollTempSize;
  607. float* fResampleTempData;
  608. uint fResampleTempSize;
  609. AudioFilePool fPool;
  610. Resampler fResampler;
  611. CarlaMutex fReaderMutex;
  612. CARLA_DECLARE_NON_COPY_STRUCT(AudioFileReader)
  613. };
  614. #endif // AUDIO_BASE_HPP_INCLUDED