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.

718 lines
20KB

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