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.

audio-base.hpp 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  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. const uint32_t framesUpToPoolEnd = numPoolFrames - fRingBufferFramePos;
  289. if (fRingBufferR.getReadableDataSize() / sizeof(float) >= framesUpToPoolEnd)
  290. {
  291. fRingBufferL.skipRead(framesUpToPoolEnd * sizeof(float));
  292. fRingBufferR.skipRead(framesUpToPoolEnd * sizeof(float));
  293. fRingBufferFramePos = numPoolFrames;
  294. }
  295. return true;
  296. }
  297. uint32_t totalFramesAvailable = fRingBufferR.getReadableDataSize() / sizeof(float);
  298. if (framePos != fRingBufferFramePos)
  299. {
  300. // unaligned position, see if we need to relocate too
  301. if (framePos < fRingBufferFramePos || framePos >= fRingBufferFramePos + totalFramesAvailable - frames)
  302. {
  303. carla_zeroFloats(outL, frames);
  304. carla_zeroFloats(outR, frames);
  305. carla_zeroFloats(playCV, frames);
  306. // wait until the previous relocation is done
  307. if (fNextFileReadPos == -1)
  308. fNextFileReadPos = framePos - frames;
  309. return true;
  310. }
  311. // oh nice, we can skip a few frames and be in sync
  312. const uint32_t diffFrames = framePos - fRingBufferFramePos;
  313. fRingBufferL.skipRead(diffFrames * sizeof(float));
  314. fRingBufferR.skipRead(diffFrames * sizeof(float));
  315. totalFramesAvailable -= diffFrames;
  316. fRingBufferFramePos = framePos;
  317. }
  318. usableFrames = std::min<uint32_t>(frames, totalFramesAvailable);
  319. if (usableFrames == 0)
  320. {
  321. carla_zeroFloats(outL, frames);
  322. carla_zeroFloats(outR, frames);
  323. carla_zeroFloats(playCV, frames);
  324. return framePos < fTotalResampledFrames;
  325. }
  326. fRingBufferL.readCustomData(outL, usableFrames * sizeof(float));
  327. fRingBufferR.readCustomData(outR, usableFrames * sizeof(float));
  328. carla_fillFloatsWithSingleValue(playCV, 10.f, usableFrames);
  329. fRingBufferFramePos += usableFrames;
  330. totalFramesAvailable -= usableFrames;
  331. if (frames != usableFrames)
  332. {
  333. if (loopingMode)
  334. {
  335. bufferOffset += usableFrames;
  336. framePos += usableFrames;
  337. frames -= usableFrames;
  338. return tickFrames(buffers, bufferOffset, frames, framePos, loopingMode, isOffline);
  339. }
  340. carla_zeroFloats(outL + usableFrames, frames - usableFrames);
  341. carla_zeroFloats(outR + usableFrames, frames - usableFrames);
  342. carla_zeroFloats(playCV + usableFrames, frames - usableFrames);
  343. }
  344. return totalFramesAvailable <= fSampleRate * 2;
  345. }
  346. void readFilePreview(uint32_t previewDataSize, float* const previewData)
  347. {
  348. carla_zeroFloats(previewData, previewDataSize);
  349. if (fFileNfo.can_seek == 0)
  350. return;
  351. const uint fileNumFrames = static_cast<uint>(fFileNfo.frames);
  352. const float fileNumFramesF = static_cast<float>(fileNumFrames);
  353. const float previewDataSizeF = static_cast<float>(previewDataSize);
  354. const uint channels = fFileNfo.channels;
  355. const uint samplesPerRun = channels * 4;
  356. const uint maxSampleToRead = fileNumFrames - samplesPerRun;
  357. const uint8_t quadoffs = fQuadMode == kQuad3and4 ? 2 : 0;
  358. float tmp[16] = {};
  359. for (uint i=0; i<previewDataSize; ++i)
  360. {
  361. const float posF = static_cast<float>(i)/previewDataSizeF * fileNumFramesF;
  362. const uint pos = carla_fixedValue(0U, maxSampleToRead, static_cast<uint>(posF));
  363. ad_seek(fFilePtr, pos);
  364. ad_read(fFilePtr, tmp, samplesPerRun);
  365. switch (channels)
  366. {
  367. case 1:
  368. previewData[i] = max4f(std::fabs(tmp[0]),
  369. std::fabs(tmp[1]),
  370. std::fabs(tmp[2]),
  371. std::fabs(tmp[3]));
  372. break;
  373. case 2:
  374. previewData[i] = max4f(std::fabs(tmp[0]),
  375. std::fabs(tmp[2]),
  376. std::fabs(tmp[4]),
  377. std::fabs(tmp[6]));
  378. previewData[i] = std::max(previewData[i], max4f(std::fabs(tmp[1]),
  379. std::fabs(tmp[3]),
  380. std::fabs(tmp[5]),
  381. std::fabs(tmp[7])));
  382. break;
  383. case 4:
  384. if (fQuadMode == kQuadAll)
  385. {
  386. previewData[i] = max4f(std::fabs(tmp[0]) + std::fabs(tmp[4])
  387. + std::fabs(tmp[8]) + std::fabs(tmp[12]),
  388. std::fabs(tmp[1]) + std::fabs(tmp[5])
  389. + std::fabs(tmp[9]) + std::fabs(tmp[13]),
  390. std::fabs(tmp[2]) + std::fabs(tmp[6])
  391. + std::fabs(tmp[10]) + std::fabs(tmp[14]),
  392. std::fabs(tmp[3]) + std::fabs(tmp[7])
  393. + std::fabs(tmp[11]) + std::fabs(tmp[15]));
  394. }
  395. else
  396. {
  397. previewData[i] = max4f(std::fabs(tmp[quadoffs+0]),
  398. std::fabs(tmp[quadoffs+4]),
  399. std::fabs(tmp[quadoffs+8]),
  400. std::fabs(tmp[quadoffs+12]));
  401. previewData[i] = std::max(previewData[i], max4f(std::fabs(tmp[quadoffs+1]),
  402. std::fabs(tmp[quadoffs+5]),
  403. std::fabs(tmp[quadoffs+9]),
  404. std::fabs(tmp[quadoffs+13])));
  405. }
  406. break;
  407. }
  408. }
  409. }
  410. void readPoll()
  411. {
  412. const CarlaMutexLocker cml(fReaderMutex);
  413. const uint channels = fFileNfo.channels;
  414. if (channels == 0 || fFilePtr == nullptr)
  415. {
  416. carla_debug("R: no song loaded");
  417. return;
  418. }
  419. fCurrentBitRate = ad_get_bitrate(fFilePtr);
  420. const bool needsResample = carla_isNotEqual(fResampleRatio, 1.0);
  421. const uint8_t quadoffs = fQuadMode == kQuad3and4 ? 2 : 0;
  422. const int64_t nextFileReadPos = fNextFileReadPos;
  423. if (nextFileReadPos != -1)
  424. {
  425. fRingBufferL.flush();
  426. fRingBufferR.flush();
  427. fPreviousResampledBuffer.frames = 0;
  428. fRingBufferFramePos = nextFileReadPos;
  429. ad_seek(fFilePtr, nextFileReadPos / fResampleRatio);
  430. if (needsResample)
  431. fResampler.reset();
  432. }
  433. if (needsResample)
  434. {
  435. float buffer[kFileReaderBufferSize];
  436. float rbuffer[kFileReaderBufferSize];
  437. ssize_t r;
  438. uint prev_inp_count = 0;
  439. while (fRingBufferR.getWritableDataSize() >= sizeof(rbuffer))
  440. {
  441. if (const uint32_t oldframes = fPreviousResampledBuffer.frames)
  442. {
  443. prev_inp_count = oldframes;
  444. fPreviousResampledBuffer.frames = 0;
  445. std::memcpy(buffer, fPreviousResampledBuffer.buffer, sizeof(float) * oldframes * channels);
  446. }
  447. else if (prev_inp_count != 0)
  448. {
  449. std::memmove(buffer,
  450. buffer + (sizeof(buffer) / sizeof(float) - prev_inp_count * channels),
  451. sizeof(float) * prev_inp_count * channels);
  452. }
  453. r = ad_read(fFilePtr,
  454. buffer + (prev_inp_count * channels),
  455. sizeof(buffer) / sizeof(float) - (prev_inp_count * channels));
  456. if (r < 0)
  457. {
  458. carla_stderr("R: ad_read failed");
  459. break;
  460. }
  461. if (r == 0)
  462. break;
  463. fResampler.inp_count = prev_inp_count + r / channels;
  464. fResampler.out_count = sizeof(rbuffer) / sizeof(float) / channels;
  465. fResampler.inp_data = buffer;
  466. fResampler.out_data = rbuffer;
  467. fResampler.process();
  468. r = sizeof(rbuffer) / sizeof(float) - fResampler.out_count * channels;
  469. if (fResampleRatio > 1.0)
  470. {
  471. if (fResampler.out_count == 0)
  472. {
  473. CARLA_SAFE_ASSERT_UINT(fResampler.inp_count != 0, fResampler.inp_count);
  474. }
  475. else
  476. {
  477. CARLA_SAFE_ASSERT_UINT(fResampler.inp_count == 0, fResampler.inp_count);
  478. }
  479. }
  480. else
  481. {
  482. CARLA_SAFE_ASSERT(fResampler.inp_count == 0);
  483. }
  484. prev_inp_count = fResampler.inp_count;
  485. if (r == 0)
  486. break;
  487. switch (channels)
  488. {
  489. case 1:
  490. fRingBufferL.writeCustomData(rbuffer, r * sizeof(float));
  491. fRingBufferR.writeCustomData(rbuffer, r * sizeof(float));
  492. break;
  493. case 2:
  494. for (ssize_t i=0; i < r;)
  495. {
  496. fRingBufferL.writeCustomData(&rbuffer[i++], sizeof(float));
  497. fRingBufferR.writeCustomData(&rbuffer[i++], sizeof(float));
  498. }
  499. break;
  500. case 4:
  501. if (fQuadMode == kQuadAll)
  502. {
  503. float v;
  504. for (ssize_t i=0; i < r; i += 4)
  505. {
  506. v = rbuffer[i] + rbuffer[i+1] + rbuffer[i+2] + rbuffer[i+3];
  507. fRingBufferL.writeCustomData(&v, sizeof(float));
  508. fRingBufferR.writeCustomData(&v, sizeof(float));
  509. }
  510. }
  511. else
  512. {
  513. for (ssize_t i=quadoffs; i < r; i += 4)
  514. {
  515. fRingBufferL.writeCustomData(&rbuffer[i], sizeof(float));
  516. fRingBufferR.writeCustomData(&rbuffer[i+1], sizeof(float));
  517. }
  518. }
  519. break;
  520. }
  521. fRingBufferL.commitWrite();
  522. fRingBufferR.commitWrite();
  523. }
  524. if (prev_inp_count != 0)
  525. {
  526. fPreviousResampledBuffer.frames = prev_inp_count;
  527. std::memcpy(fPreviousResampledBuffer.buffer,
  528. buffer + (sizeof(buffer) / sizeof(float) - prev_inp_count * channels),
  529. sizeof(float) * prev_inp_count * channels);
  530. }
  531. }
  532. else
  533. {
  534. float buffer[kFileReaderBufferSize];
  535. ssize_t r;
  536. while (fRingBufferR.getWritableDataSize() >= sizeof(buffer))
  537. {
  538. r = ad_read(fFilePtr, buffer, sizeof(buffer)/sizeof(float));
  539. if (r < 0)
  540. {
  541. carla_stderr("R: ad_read failed");
  542. break;
  543. }
  544. if (r == 0)
  545. break;
  546. switch (channels)
  547. {
  548. case 1:
  549. fRingBufferL.writeCustomData(buffer, r * sizeof(float));
  550. fRingBufferR.writeCustomData(buffer, r * sizeof(float));
  551. break;
  552. case 2:
  553. for (ssize_t i=0; i < r;)
  554. {
  555. fRingBufferL.writeCustomData(&buffer[i++], sizeof(float));
  556. fRingBufferR.writeCustomData(&buffer[i++], sizeof(float));
  557. }
  558. break;
  559. case 4:
  560. if (fQuadMode == kQuadAll)
  561. {
  562. float v;
  563. for (ssize_t i=0; i < r; i += 4)
  564. {
  565. v = buffer[i] + buffer[i+1] + buffer[i+2] + buffer[i+3];
  566. fRingBufferL.writeCustomData(&v, sizeof(float));
  567. fRingBufferR.writeCustomData(&v, sizeof(float));
  568. }
  569. }
  570. else
  571. {
  572. for (ssize_t i=quadoffs; i < r; i += 4)
  573. {
  574. fRingBufferL.writeCustomData(&buffer[i], sizeof(float));
  575. fRingBufferR.writeCustomData(&buffer[i+1], sizeof(float));
  576. }
  577. }
  578. break;
  579. }
  580. fRingBufferL.commitWrite();
  581. fRingBufferR.commitWrite();
  582. }
  583. }
  584. if (nextFileReadPos != -1)
  585. fNextFileReadPos = -1;
  586. }
  587. private:
  588. bool fEntireFileLoaded = false;
  589. QuadMode fQuadMode = kQuad1and2;
  590. int fCurrentBitRate = 0;
  591. float fLastPlayPosition = 0.f;
  592. int64_t fNextFileReadPos = -1;
  593. uint64_t fTotalResampledFrames = 0;
  594. void* fFilePtr = nullptr;
  595. ADInfo fFileNfo = {};
  596. uint32_t fSampleRate = 0;
  597. double fResampleRatio = 1.0;
  598. AudioMemoryPool fInitialMemoryPool;
  599. Resampler fResampler;
  600. CarlaMutex fReaderMutex;
  601. struct PreviousResampledBuffer {
  602. float* buffer = nullptr;
  603. uint32_t frames = 0;
  604. } fPreviousResampledBuffer;
  605. CarlaHeapRingBuffer fRingBufferL, fRingBufferR;
  606. uint64_t fRingBufferFramePos = 0;
  607. // assumes reader lock is active
  608. void cleanup()
  609. {
  610. fEntireFileLoaded = false;
  611. fCurrentBitRate = 0;
  612. fLastPlayPosition = 0.f;
  613. fNextFileReadPos = -1;
  614. fTotalResampledFrames = 0;
  615. fSampleRate = 0;
  616. fRingBufferFramePos = 0;
  617. fResampleRatio = 1.0;
  618. fResampler.clear();
  619. fInitialMemoryPool.destroy();
  620. fRingBufferL.deleteBuffer();
  621. fRingBufferR.deleteBuffer();
  622. if (fFilePtr != nullptr)
  623. {
  624. ad_close(fFilePtr);
  625. fFilePtr = nullptr;
  626. }
  627. delete[] fPreviousResampledBuffer.buffer;
  628. fPreviousResampledBuffer.buffer = nullptr;
  629. fPreviousResampledBuffer.frames = 0;
  630. }
  631. void readIntoInitialMemoryPool(const uint numFrames, const uint numResampledFrames)
  632. {
  633. const uint channels = fFileNfo.channels;
  634. const uint fileBufferSize = numFrames * channels;
  635. float* const fileBuffer = (float*)std::malloc(fileBufferSize * sizeof(float));
  636. CARLA_SAFE_ASSERT_RETURN(fileBuffer != nullptr,);
  637. ad_seek(fFilePtr, 0);
  638. ssize_t rv = ad_read(fFilePtr, fileBuffer, fileBufferSize);
  639. CARLA_SAFE_ASSERT_INT2_RETURN(rv == static_cast<ssize_t>(fileBufferSize),
  640. rv, fileBufferSize,
  641. std::free(fileBuffer));
  642. fCurrentBitRate = ad_get_bitrate(fFilePtr);
  643. float* resampledBuffer;
  644. if (numFrames != numResampledFrames)
  645. {
  646. resampledBuffer = (float*)std::malloc(numResampledFrames * channels * sizeof(float));
  647. CARLA_SAFE_ASSERT_RETURN(resampledBuffer != nullptr, std::free(fileBuffer););
  648. fResampler.inp_count = numFrames;
  649. fResampler.out_count = numResampledFrames;
  650. fResampler.inp_data = fileBuffer;
  651. fResampler.out_data = resampledBuffer;
  652. fResampler.process();
  653. fInitialMemoryPool.numFrames = numResampledFrames - fResampler.out_count;
  654. rv = fInitialMemoryPool.numFrames * channels;
  655. }
  656. else
  657. {
  658. resampledBuffer = fileBuffer;
  659. }
  660. {
  661. // lock, and put data asap
  662. const CarlaMutexLocker cml(fInitialMemoryPool.mutex);
  663. switch (channels)
  664. {
  665. case 1:
  666. for (ssize_t i=0; i < rv; ++i)
  667. fInitialMemoryPool.buffer[0][i] = fInitialMemoryPool.buffer[1][i] = resampledBuffer[i];
  668. break;
  669. case 2:
  670. for (ssize_t i=0, j=0; i < rv; ++j)
  671. {
  672. fInitialMemoryPool.buffer[0][j] = resampledBuffer[i++];
  673. fInitialMemoryPool.buffer[1][j] = resampledBuffer[i++];
  674. }
  675. break;
  676. case 4:
  677. if (fQuadMode == kQuadAll)
  678. {
  679. for (ssize_t i=0, j=0; i < rv; ++j)
  680. {
  681. fInitialMemoryPool.buffer[0][j] = fInitialMemoryPool.buffer[1][j]
  682. = resampledBuffer[i] + resampledBuffer[i+1] + resampledBuffer[i+2] + resampledBuffer[i+3];
  683. i += 4;
  684. }
  685. }
  686. else
  687. {
  688. for (ssize_t i = fQuadMode == kQuad3and4 ? 2 : 0, j = 0; i < rv; ++j)
  689. {
  690. fInitialMemoryPool.buffer[0][j] = resampledBuffer[i];
  691. fInitialMemoryPool.buffer[1][j] = resampledBuffer[i+1];
  692. i += 4;
  693. }
  694. }
  695. break;
  696. }
  697. }
  698. if (resampledBuffer != fileBuffer)
  699. std::free(resampledBuffer);
  700. std::free(fileBuffer);
  701. }
  702. CARLA_DECLARE_NON_COPYABLE(AudioFileReader)
  703. };
  704. // --------------------------------------------------------------------------------------------------------------------
  705. #endif // AUDIO_BASE_HPP_INCLUDED