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.

872 lines
26KB

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