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.

853 lines
30KB

  1. /*
  2. * Carla Native Plugins
  3. * Copyright (C) 2013-2023 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. #include "CarlaMemUtils.hpp"
  21. #include "CarlaRingBuffer.hpp"
  22. extern "C" {
  23. #include "audio_decoder/ad.h"
  24. }
  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. typedef struct adinfo ADInfo;
  34. // --------------------------------------------------------------------------------------------------------------------
  35. // tuning
  36. // disk streaming buffer size
  37. static constexpr const uint16_t kFileReaderBufferSize = 1024;
  38. // if reading a file smaller than this, load it all in memory
  39. static constexpr const uint16_t kMinLengthSeconds = 30;
  40. // size of the audio file ring buffer
  41. static constexpr const uint16_t kRingBufferLengthSeconds = 6;
  42. static inline
  43. constexpr float max4f(const float a, const float b, const float c, const float d) noexcept
  44. {
  45. return a > b && a > c && a > d ? a :
  46. b > a && b > c && b > d ? b :
  47. c > a && c > b && c > d ? c :
  48. d;
  49. }
  50. // --------------------------------------------------------------------------------------------------------------------
  51. struct AudioMemoryPool {
  52. float* buffer[2] = {};
  53. uint32_t numFrames = 0;
  54. CarlaMutex mutex;
  55. AudioMemoryPool() noexcept {}
  56. ~AudioMemoryPool() noexcept
  57. {
  58. destroy();
  59. }
  60. void create(const uint32_t desiredNumFrames)
  61. {
  62. CARLA_ASSERT(buffer[0] == nullptr);
  63. CARLA_ASSERT(buffer[1] == nullptr);
  64. CARLA_ASSERT(numFrames == 0);
  65. buffer[0] = new float[desiredNumFrames];
  66. buffer[1] = new float[desiredNumFrames];
  67. carla_mlock(buffer[0], sizeof(float)*desiredNumFrames);
  68. carla_mlock(buffer[1], sizeof(float)*desiredNumFrames);
  69. const CarlaMutexLocker cml(mutex);
  70. numFrames = desiredNumFrames;
  71. }
  72. void destroy() noexcept
  73. {
  74. {
  75. const CarlaMutexLocker cml(mutex);
  76. numFrames = 0;
  77. }
  78. if (buffer[0] != nullptr)
  79. {
  80. delete[] buffer[0];
  81. buffer[0] = nullptr;
  82. }
  83. if (buffer[1] != nullptr)
  84. {
  85. delete[] buffer[1];
  86. buffer[1] = nullptr;
  87. }
  88. }
  89. CARLA_DECLARE_NON_COPYABLE(AudioMemoryPool)
  90. };
  91. // --------------------------------------------------------------------------------------------------------------------
  92. class AudioFileReader
  93. {
  94. public:
  95. enum QuadMode {
  96. kQuad1and2,
  97. kQuad3and4,
  98. kQuadAll
  99. };
  100. AudioFileReader()
  101. {
  102. ad_clear_nfo(&fFileNfo);
  103. }
  104. ~AudioFileReader()
  105. {
  106. destroy();
  107. }
  108. void destroy()
  109. {
  110. const CarlaMutexLocker cml(fReaderMutex);
  111. cleanup();
  112. }
  113. int getCurrentBitRate() const noexcept
  114. {
  115. return fCurrentBitRate;
  116. }
  117. float getLastPlayPosition() const noexcept
  118. {
  119. return fLastPlayPosition;
  120. }
  121. float getReadableBufferFill() const noexcept
  122. {
  123. if (fFileNfo.channels == 0)
  124. return 0.f;
  125. if (fEntireFileLoaded)
  126. return 1.f;
  127. return 1.f - (static_cast<float>(fRingBufferR.getReadableDataSize() / sizeof(float))
  128. / static_cast<float>(fRingBufferR.getSize() / sizeof(float)));
  129. }
  130. ADInfo getFileInfo() const noexcept
  131. {
  132. return fFileNfo;
  133. }
  134. bool loadFilename(const char* const filename, const uint32_t sampleRate, const QuadMode quadMode,
  135. const uint32_t previewDataSize, float* previewData)
  136. {
  137. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && *filename != '\0', false);
  138. const CarlaMutexLocker cml(fReaderMutex);
  139. cleanup();
  140. ad_clear_nfo(&fFileNfo);
  141. // open new
  142. fFilePtr = ad_open(filename, &fFileNfo);
  143. if (fFilePtr == nullptr)
  144. return false;
  145. ad_dump_nfo(99, &fFileNfo);
  146. // invalid
  147. if ((fFileNfo.channels != 1 && fFileNfo.channels != 2 && fFileNfo.channels != 4) || fFileNfo.frames <= 0)
  148. {
  149. if (fFileNfo.channels != 1 && fFileNfo.channels != 2 && fFileNfo.channels != 4)
  150. carla_stderr("loadFilename(\"%s\", ...) has not 1, 2 or 4 channels", filename);
  151. if (fFileNfo.frames <= 0)
  152. carla_stderr("loadFilename(\"%s\", ...) has 0 frames", filename);
  153. ad_clear_nfo(&fFileNfo);
  154. ad_close(fFilePtr);
  155. fFilePtr = nullptr;
  156. return false;
  157. }
  158. const uint64_t numFileFrames = static_cast<uint64_t>(fFileNfo.frames);
  159. const bool needsResample = fFileNfo.sample_rate != sampleRate;
  160. uint64_t numResampledFrames;
  161. if (needsResample)
  162. {
  163. if (! fResampler.setup(fFileNfo.sample_rate, sampleRate, fFileNfo.channels, 32))
  164. {
  165. ad_clear_nfo(&fFileNfo);
  166. ad_close(fFilePtr);
  167. fFilePtr = nullptr;
  168. carla_stderr2("loadFilename(\"%s\", ...) error, resampler setup failed");
  169. return false;
  170. }
  171. fResampleRatio = static_cast<double>(sampleRate) / static_cast<double>(fFileNfo.sample_rate);
  172. numResampledFrames = static_cast<uint64_t>(static_cast<double>(numFileFrames) * fResampleRatio + 0.5);
  173. if (fPreviousResampledBuffer.buffer == nullptr)
  174. fPreviousResampledBuffer.buffer = new float[kFileReaderBufferSize];
  175. }
  176. else
  177. {
  178. numResampledFrames = numFileFrames;
  179. }
  180. fQuadMode = quadMode;
  181. if (fFileNfo.can_seek == 0 || numResampledFrames <= sampleRate * kMinLengthSeconds)
  182. {
  183. // read and cache the first few seconds of the file if seekable
  184. const uint64_t initialFrames = fFileNfo.can_seek == 0
  185. ? numFileFrames
  186. : std::min<uint64_t>(numFileFrames, fFileNfo.sample_rate * kMinLengthSeconds);
  187. const uint64_t initialResampledFrames = fFileNfo.can_seek == 0
  188. ? numResampledFrames
  189. : std::min<uint64_t>(numResampledFrames,
  190. sampleRate * kMinLengthSeconds);
  191. fInitialMemoryPool.create(initialResampledFrames);
  192. readIntoInitialMemoryPool(initialFrames, initialResampledFrames);
  193. // file is no longer needed, we have it all in memory
  194. ad_close(fFilePtr);
  195. fFilePtr = nullptr;
  196. const float resampledFramesF = static_cast<float>(numResampledFrames);
  197. const float previewDataSizeF = static_cast<float>(previewDataSize);
  198. for (uint i=0; i<previewDataSize; ++i)
  199. {
  200. const float stepF = static_cast<float>(i)/previewDataSizeF * resampledFramesF;
  201. const uint step = carla_fixedValue<uint64_t>(0, numResampledFrames-1, static_cast<uint>(stepF + 0.5f));
  202. previewData[i] = std::max(std::fabs(fInitialMemoryPool.buffer[0][step]),
  203. std::fabs(fInitialMemoryPool.buffer[1][step]));
  204. }
  205. fEntireFileLoaded = true;
  206. }
  207. else
  208. {
  209. readFilePreview(previewDataSize, previewData);
  210. // cache only the first few initial seconds, let disk streaming handle the rest
  211. const uint64_t initialFrames = std::min<uint64_t>(numFileFrames,
  212. fFileNfo.sample_rate * kRingBufferLengthSeconds / 2);
  213. const uint64_t initialResampledFrames = std::min<uint64_t>(numResampledFrames,
  214. sampleRate * kRingBufferLengthSeconds / 2);
  215. fRingBufferL.createBuffer(sampleRate * kRingBufferLengthSeconds * sizeof(float), true);
  216. fRingBufferR.createBuffer(sampleRate * kRingBufferLengthSeconds * sizeof(float), true);
  217. fInitialMemoryPool.create(initialResampledFrames);
  218. readIntoInitialMemoryPool(initialFrames, initialResampledFrames);
  219. fRingBufferL.writeCustomData(fInitialMemoryPool.buffer[0], fInitialMemoryPool.numFrames * sizeof(float));
  220. fRingBufferR.writeCustomData(fInitialMemoryPool.buffer[1], fInitialMemoryPool.numFrames * sizeof(float));
  221. fRingBufferL.commitWrite();
  222. fRingBufferR.commitWrite();
  223. fEntireFileLoaded = false;
  224. }
  225. fTotalResampledFrames = numResampledFrames;
  226. fSampleRate = sampleRate;
  227. return true;
  228. }
  229. bool tickFrames(float* const buffers[],
  230. uint32_t bufferOffset, uint32_t frames, uint64_t framePos,
  231. const bool loopingMode, const bool isOffline)
  232. {
  233. float* outL = buffers[0] + bufferOffset;
  234. float* outR = buffers[1] + bufferOffset;
  235. float* playCV = buffers[2] + bufferOffset;
  236. if (loopingMode && framePos >= fTotalResampledFrames)
  237. framePos %= fTotalResampledFrames;
  238. if (framePos >= fTotalResampledFrames)
  239. {
  240. carla_zeroFloats(outL, frames);
  241. carla_zeroFloats(outR, frames);
  242. carla_zeroFloats(playCV, frames);
  243. fLastPlayPosition = 1.f;
  244. return false;
  245. }
  246. uint32_t numPoolFrames, usableFrames;
  247. {
  248. const CarlaMutexTryLocker cmtl(fInitialMemoryPool.mutex, isOffline);
  249. numPoolFrames = fInitialMemoryPool.numFrames;
  250. if (numPoolFrames == 0 || ! cmtl.wasLocked())
  251. {
  252. carla_zeroFloats(outL, frames);
  253. carla_zeroFloats(outR, frames);
  254. carla_zeroFloats(playCV, frames);
  255. return false;
  256. }
  257. if (framePos < numPoolFrames)
  258. {
  259. usableFrames = std::min(frames, numPoolFrames - static_cast<uint32_t>(framePos));
  260. carla_copyFloats(outL, fInitialMemoryPool.buffer[0] + framePos, usableFrames);
  261. carla_copyFloats(outR, fInitialMemoryPool.buffer[1] + framePos, usableFrames);
  262. carla_fillFloatsWithSingleValue(playCV, 10.f, usableFrames);
  263. outL += usableFrames;
  264. outR += usableFrames;
  265. playCV += usableFrames;
  266. bufferOffset += usableFrames;
  267. framePos += usableFrames;
  268. frames -= usableFrames;
  269. }
  270. if (fEntireFileLoaded && frames != 0)
  271. return tickFrames(buffers, bufferOffset, frames, framePos, loopingMode, isOffline);
  272. }
  273. fLastPlayPosition = static_cast<float>(framePos / 64) / static_cast<float>(fTotalResampledFrames / 64);
  274. if (fEntireFileLoaded)
  275. return false;
  276. if (frames == 0)
  277. {
  278. // ring buffer is good, waiting for data reads
  279. if (fRingBufferFramePos == numPoolFrames)
  280. return false;
  281. // out of bounds, host likely has repositioned transport
  282. if (fRingBufferFramePos > numPoolFrames)
  283. {
  284. fNextFileReadPos = 0;
  285. return true;
  286. }
  287. // within bounds, skip frames until we reach the end of the memory pool
  288. if (fRingBufferR.getReadableDataSize() >= numPoolFrames * sizeof(float))
  289. {
  290. fRingBufferL.skipRead(numPoolFrames * sizeof(float));
  291. fRingBufferR.skipRead(numPoolFrames * sizeof(float));
  292. fRingBufferFramePos = numPoolFrames;
  293. }
  294. return true;
  295. }
  296. uint32_t totalFramesAvailable = fRingBufferR.getReadableDataSize() / sizeof(float);
  297. if (framePos != fRingBufferFramePos)
  298. {
  299. // unaligned position, see if we need to relocate too
  300. if (framePos < fRingBufferFramePos || framePos >= fRingBufferFramePos + totalFramesAvailable - frames)
  301. {
  302. carla_zeroFloats(outL, frames);
  303. carla_zeroFloats(outR, frames);
  304. carla_zeroFloats(playCV, frames);
  305. // wait until there previous relocation is done
  306. if (fNextFileReadPos == -1)
  307. fNextFileReadPos = framePos;
  308. return true;
  309. }
  310. // oh nice, we can skip a few frames and be in sync
  311. const uint32_t diffFrames = framePos - fRingBufferFramePos;
  312. fRingBufferL.skipRead(diffFrames * sizeof(float));
  313. fRingBufferR.skipRead(diffFrames * sizeof(float));
  314. totalFramesAvailable -= diffFrames;
  315. fRingBufferFramePos = framePos;
  316. }
  317. usableFrames = std::min<uint32_t>(frames, totalFramesAvailable);
  318. if (usableFrames == 0)
  319. {
  320. carla_zeroFloats(outL, frames);
  321. carla_zeroFloats(outR, frames);
  322. carla_zeroFloats(playCV, frames);
  323. return framePos < fTotalResampledFrames;
  324. }
  325. fRingBufferL.readCustomData(outL, sizeof(float) * usableFrames);
  326. fRingBufferR.readCustomData(outR, sizeof(float) * usableFrames);
  327. carla_fillFloatsWithSingleValue(playCV, 10.f, usableFrames);
  328. fRingBufferFramePos += usableFrames;
  329. totalFramesAvailable -= usableFrames;
  330. if (frames != usableFrames)
  331. {
  332. if (loopingMode)
  333. {
  334. bufferOffset += usableFrames;
  335. framePos += usableFrames;
  336. frames -= usableFrames;
  337. return tickFrames(buffers, bufferOffset, frames, framePos, loopingMode, isOffline);
  338. }
  339. carla_zeroFloats(outL + usableFrames, frames - usableFrames);
  340. carla_zeroFloats(outR + usableFrames, frames - usableFrames);
  341. carla_zeroFloats(playCV + usableFrames, frames - usableFrames);
  342. }
  343. return totalFramesAvailable <= fSampleRate * 2;
  344. }
  345. void readFilePreview(uint32_t previewDataSize, float* const previewData)
  346. {
  347. carla_zeroFloats(previewData, previewDataSize);
  348. if (fFileNfo.can_seek == 0)
  349. return;
  350. const uint fileNumFrames = static_cast<uint>(fFileNfo.frames);
  351. const float fileNumFramesF = static_cast<float>(fileNumFrames);
  352. const float previewDataSizeF = static_cast<float>(previewDataSize);
  353. const uint channels = fFileNfo.channels;
  354. const uint samplesPerRun = channels * 4;
  355. const uint maxSampleToRead = fileNumFrames - samplesPerRun;
  356. const uint8_t quadoffs = fQuadMode == kQuad3and4 ? 2 : 0;
  357. float tmp[16] = {};
  358. for (uint i=0; i<previewDataSize; ++i)
  359. {
  360. const float posF = static_cast<float>(i)/previewDataSizeF * fileNumFramesF;
  361. const uint pos = carla_fixedValue(0U, maxSampleToRead, static_cast<uint>(posF));
  362. ad_seek(fFilePtr, pos);
  363. ad_read(fFilePtr, tmp, samplesPerRun);
  364. switch (channels)
  365. {
  366. case 1:
  367. previewData[i] = max4f(std::fabs(tmp[0]),
  368. std::fabs(tmp[1]),
  369. std::fabs(tmp[2]),
  370. std::fabs(tmp[3]));
  371. break;
  372. case 2:
  373. previewData[i] = max4f(std::fabs(tmp[0]),
  374. std::fabs(tmp[2]),
  375. std::fabs(tmp[4]),
  376. std::fabs(tmp[6]));
  377. previewData[i] = std::max(previewData[i], max4f(std::fabs(tmp[1]),
  378. std::fabs(tmp[3]),
  379. std::fabs(tmp[5]),
  380. std::fabs(tmp[7])));
  381. break;
  382. case 4:
  383. if (fQuadMode == kQuadAll)
  384. {
  385. previewData[i] = max4f(std::fabs(tmp[0]) + std::fabs(tmp[4])
  386. + std::fabs(tmp[8]) + std::fabs(tmp[12]),
  387. std::fabs(tmp[1]) + std::fabs(tmp[5])
  388. + std::fabs(tmp[9]) + std::fabs(tmp[13]),
  389. std::fabs(tmp[2]) + std::fabs(tmp[6])
  390. + std::fabs(tmp[10]) + std::fabs(tmp[14]),
  391. std::fabs(tmp[3]) + std::fabs(tmp[7])
  392. + std::fabs(tmp[11]) + std::fabs(tmp[15]));
  393. }
  394. else
  395. {
  396. previewData[i] = max4f(std::fabs(tmp[quadoffs+0]),
  397. std::fabs(tmp[quadoffs+4]),
  398. std::fabs(tmp[quadoffs+8]),
  399. std::fabs(tmp[quadoffs+12]));
  400. previewData[i] = std::max(previewData[i], max4f(std::fabs(tmp[quadoffs+1]),
  401. std::fabs(tmp[quadoffs+5]),
  402. std::fabs(tmp[quadoffs+9]),
  403. std::fabs(tmp[quadoffs+13])));
  404. }
  405. break;
  406. }
  407. }
  408. }
  409. void readPoll()
  410. {
  411. const CarlaMutexLocker cml(fReaderMutex);
  412. const uint channels = fFileNfo.channels;
  413. if (channels == 0 || fFilePtr == nullptr)
  414. {
  415. carla_debug("R: no song loaded");
  416. return;
  417. }
  418. fCurrentBitRate = ad_get_bitrate(fFilePtr);
  419. const bool needsResample = carla_isNotEqual(fResampleRatio, 1.0);
  420. const uint8_t quadoffs = fQuadMode == kQuad3and4 ? 2 : 0;
  421. const int64_t nextFileReadPos = fNextFileReadPos;
  422. if (nextFileReadPos != -1)
  423. {
  424. fRingBufferL.flush();
  425. fRingBufferR.flush();
  426. fPreviousResampledBuffer.frames = 0;
  427. fRingBufferFramePos = nextFileReadPos;
  428. ad_seek(fFilePtr, nextFileReadPos / fResampleRatio);
  429. if (needsResample)
  430. fResampler.reset();
  431. }
  432. if (needsResample)
  433. {
  434. float buffer[kFileReaderBufferSize];
  435. float rbuffer[kFileReaderBufferSize];
  436. ssize_t r;
  437. uint prev_inp_count = 0;
  438. while (fRingBufferR.getWritableDataSize() >= sizeof(rbuffer))
  439. {
  440. if (const uint32_t oldframes = fPreviousResampledBuffer.frames)
  441. {
  442. prev_inp_count = oldframes;
  443. fPreviousResampledBuffer.frames = 0;
  444. std::memcpy(buffer, fPreviousResampledBuffer.buffer, sizeof(float) * oldframes * channels);
  445. }
  446. else if (prev_inp_count != 0)
  447. {
  448. std::memmove(buffer,
  449. buffer + (sizeof(buffer) / sizeof(float) - prev_inp_count * channels),
  450. sizeof(float) * prev_inp_count * channels);
  451. }
  452. r = ad_read(fFilePtr,
  453. buffer + (prev_inp_count * channels),
  454. sizeof(buffer) / sizeof(float) - (prev_inp_count * channels));
  455. if (r < 0)
  456. {
  457. carla_stderr("R: ad_read failed");
  458. break;
  459. }
  460. if (r == 0)
  461. break;
  462. fResampler.inp_count = prev_inp_count + r / channels;
  463. fResampler.out_count = sizeof(rbuffer) / sizeof(float) / channels;
  464. fResampler.inp_data = buffer;
  465. fResampler.out_data = rbuffer;
  466. fResampler.process();
  467. r = sizeof(rbuffer) / sizeof(float) - fResampler.out_count * channels;
  468. if (fResampleRatio > 1.0)
  469. {
  470. if (fResampler.out_count == 0)
  471. {
  472. CARLA_SAFE_ASSERT_UINT(fResampler.inp_count != 0, fResampler.inp_count);
  473. }
  474. else
  475. {
  476. CARLA_SAFE_ASSERT_UINT(fResampler.inp_count == 0, fResampler.inp_count);
  477. }
  478. }
  479. else
  480. {
  481. CARLA_SAFE_ASSERT(fResampler.inp_count == 0);
  482. }
  483. prev_inp_count = fResampler.inp_count;
  484. if (r == 0)
  485. break;
  486. switch (channels)
  487. {
  488. case 1:
  489. fRingBufferL.writeCustomData(rbuffer, r * sizeof(float));
  490. fRingBufferR.writeCustomData(rbuffer, r * sizeof(float));
  491. break;
  492. case 2:
  493. for (ssize_t i=0; i < r;)
  494. {
  495. fRingBufferL.writeCustomData(&rbuffer[i++], sizeof(float));
  496. fRingBufferR.writeCustomData(&rbuffer[i++], sizeof(float));
  497. }
  498. break;
  499. case 4:
  500. if (fQuadMode == kQuadAll)
  501. {
  502. float v;
  503. for (ssize_t i=0; i < r; i += 4)
  504. {
  505. v = rbuffer[i] + rbuffer[i+1] + rbuffer[i+2] + rbuffer[i+3];
  506. fRingBufferL.writeCustomData(&v, sizeof(float));
  507. fRingBufferR.writeCustomData(&v, sizeof(float));
  508. }
  509. }
  510. else
  511. {
  512. for (ssize_t i=quadoffs; i < r; i += 4)
  513. {
  514. fRingBufferL.writeCustomData(&rbuffer[i], sizeof(float));
  515. fRingBufferR.writeCustomData(&rbuffer[i+1], sizeof(float));
  516. }
  517. }
  518. break;
  519. }
  520. fRingBufferL.commitWrite();
  521. fRingBufferR.commitWrite();
  522. }
  523. if (prev_inp_count != 0)
  524. {
  525. fPreviousResampledBuffer.frames = prev_inp_count;
  526. std::memcpy(fPreviousResampledBuffer.buffer,
  527. buffer + (sizeof(buffer) / sizeof(float) - prev_inp_count * channels),
  528. sizeof(float) * prev_inp_count * channels);
  529. }
  530. }
  531. else
  532. {
  533. float buffer[kFileReaderBufferSize];
  534. ssize_t r;
  535. while (fRingBufferR.getWritableDataSize() >= sizeof(buffer))
  536. {
  537. r = ad_read(fFilePtr, buffer, sizeof(buffer)/sizeof(float));
  538. if (r < 0)
  539. {
  540. carla_stderr("R: ad_read failed");
  541. break;
  542. }
  543. if (r == 0)
  544. break;
  545. switch (channels)
  546. {
  547. case 1:
  548. fRingBufferL.writeCustomData(buffer, r * sizeof(float));
  549. fRingBufferR.writeCustomData(buffer, r * sizeof(float));
  550. break;
  551. case 2:
  552. for (ssize_t i=0; i < r;)
  553. {
  554. fRingBufferL.writeCustomData(&buffer[i++], sizeof(float));
  555. fRingBufferR.writeCustomData(&buffer[i++], sizeof(float));
  556. }
  557. break;
  558. case 4:
  559. if (fQuadMode == kQuadAll)
  560. {
  561. float v;
  562. for (ssize_t i=0; i < r; i += 4)
  563. {
  564. v = buffer[i] + buffer[i+1] + buffer[i+2] + buffer[i+3];
  565. fRingBufferL.writeCustomData(&v, sizeof(float));
  566. fRingBufferR.writeCustomData(&v, sizeof(float));
  567. }
  568. }
  569. else
  570. {
  571. for (ssize_t i=quadoffs; i < r; i += 4)
  572. {
  573. fRingBufferL.writeCustomData(&buffer[i], sizeof(float));
  574. fRingBufferR.writeCustomData(&buffer[i+1], sizeof(float));
  575. }
  576. }
  577. break;
  578. }
  579. fRingBufferL.commitWrite();
  580. fRingBufferR.commitWrite();
  581. }
  582. }
  583. if (nextFileReadPos != -1)
  584. fNextFileReadPos = -1;
  585. }
  586. private:
  587. bool fEntireFileLoaded = false;
  588. QuadMode fQuadMode = kQuad1and2;
  589. int fCurrentBitRate = 0;
  590. float fLastPlayPosition = 0.f;
  591. int64_t fNextFileReadPos = -1;
  592. uint64_t fTotalResampledFrames = 0;
  593. void* fFilePtr = nullptr;
  594. ADInfo fFileNfo = {};
  595. uint32_t fSampleRate = 0;
  596. double fResampleRatio = 1.0;
  597. AudioMemoryPool fInitialMemoryPool;
  598. Resampler fResampler;
  599. CarlaMutex fReaderMutex;
  600. struct PreviousResampledBuffer {
  601. float* buffer = nullptr;
  602. uint32_t frames = 0;
  603. } fPreviousResampledBuffer;
  604. CarlaHeapRingBuffer fRingBufferL, fRingBufferR;
  605. uint64_t fRingBufferFramePos = 0;
  606. // assumes reader lock is active
  607. void cleanup()
  608. {
  609. fEntireFileLoaded = false;
  610. fCurrentBitRate = 0;
  611. fLastPlayPosition = 0.f;
  612. fNextFileReadPos = -1;
  613. fTotalResampledFrames = 0;
  614. fSampleRate = 0;
  615. fRingBufferFramePos = 0;
  616. fResampleRatio = 1.0;
  617. fResampler.clear();
  618. fInitialMemoryPool.destroy();
  619. fRingBufferL.deleteBuffer();
  620. fRingBufferR.deleteBuffer();
  621. if (fFilePtr != nullptr)
  622. {
  623. ad_close(fFilePtr);
  624. fFilePtr = nullptr;
  625. }
  626. delete[] fPreviousResampledBuffer.buffer;
  627. fPreviousResampledBuffer.buffer = nullptr;
  628. fPreviousResampledBuffer.frames = 0;
  629. }
  630. void readIntoInitialMemoryPool(const uint numFrames, const uint numResampledFrames)
  631. {
  632. const uint channels = fFileNfo.channels;
  633. const uint fileBufferSize = numFrames * channels;
  634. float* const fileBuffer = (float*)std::malloc(fileBufferSize * sizeof(float));
  635. CARLA_SAFE_ASSERT_RETURN(fileBuffer != nullptr,);
  636. ad_seek(fFilePtr, 0);
  637. ssize_t rv = ad_read(fFilePtr, fileBuffer, fileBufferSize);
  638. CARLA_SAFE_ASSERT_INT2_RETURN(rv == static_cast<ssize_t>(fileBufferSize),
  639. rv, fileBufferSize,
  640. std::free(fileBuffer));
  641. fCurrentBitRate = ad_get_bitrate(fFilePtr);
  642. float* resampledBuffer;
  643. if (numFrames != numResampledFrames)
  644. {
  645. resampledBuffer = (float*)std::malloc(numResampledFrames * channels * sizeof(float));
  646. CARLA_SAFE_ASSERT_RETURN(resampledBuffer != nullptr, std::free(fileBuffer););
  647. fResampler.inp_count = numFrames;
  648. fResampler.out_count = numResampledFrames;
  649. fResampler.inp_data = fileBuffer;
  650. fResampler.out_data = resampledBuffer;
  651. fResampler.process();
  652. fInitialMemoryPool.numFrames = numResampledFrames - fResampler.out_count;
  653. rv = fInitialMemoryPool.numFrames * channels;
  654. }
  655. else
  656. {
  657. resampledBuffer = fileBuffer;
  658. }
  659. {
  660. // lock, and put data asap
  661. const CarlaMutexLocker cml(fInitialMemoryPool.mutex);
  662. switch (channels)
  663. {
  664. case 1:
  665. for (ssize_t i=0; i < rv; ++i)
  666. fInitialMemoryPool.buffer[0][i] = fInitialMemoryPool.buffer[1][i] = resampledBuffer[i];
  667. break;
  668. case 2:
  669. for (ssize_t i=0, j=0; i < rv; ++j)
  670. {
  671. fInitialMemoryPool.buffer[0][j] = resampledBuffer[i++];
  672. fInitialMemoryPool.buffer[1][j] = resampledBuffer[i++];
  673. }
  674. break;
  675. case 4:
  676. if (fQuadMode == kQuadAll)
  677. {
  678. for (ssize_t i=0, j=0; i < rv; ++j)
  679. {
  680. fInitialMemoryPool.buffer[0][j] = fInitialMemoryPool.buffer[1][j]
  681. = resampledBuffer[i] + resampledBuffer[i+1] + resampledBuffer[i+2] + resampledBuffer[i+3];
  682. i += 4;
  683. }
  684. }
  685. else
  686. {
  687. for (ssize_t i = fQuadMode == kQuad3and4 ? 2 : 0, j = 0; i < rv; ++j)
  688. {
  689. fInitialMemoryPool.buffer[0][j] = resampledBuffer[i];
  690. fInitialMemoryPool.buffer[1][j] = resampledBuffer[i+1];
  691. i += 4;
  692. }
  693. }
  694. break;
  695. }
  696. }
  697. if (resampledBuffer != fileBuffer)
  698. std::free(resampledBuffer);
  699. std::free(fileBuffer);
  700. }
  701. CARLA_DECLARE_NON_COPYABLE(AudioFileReader)
  702. };
  703. // --------------------------------------------------------------------------------------------------------------------
  704. #endif // AUDIO_BASE_HPP_INCLUDED