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.

1110 lines
38KB

  1. /*
  2. ==============================================================================
  3. This file is part of the dRowAudio JUCE module
  4. Copyright 2004-13 by dRowAudio.
  5. ------------------------------------------------------------------------------
  6. dRowAudio is provided under the terms of The MIT License (MIT):
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in all
  14. copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. SOFTWARE.
  22. ==============================================================================
  23. */
  24. #undef min
  25. #undef max
  26. using ::std::numeric_limits;
  27. //==============================================================================
  28. namespace
  29. {
  30. //==============================================================================
  31. template <typename SampleType>
  32. static void getStereoMinAndMax (SampleType* const* channels, const int numChannels, const int numSamples,
  33. SampleType& lmin, SampleType& lmax, SampleType& rmin, SampleType& rmax)
  34. {
  35. SampleType bufMin, bufMax;
  36. findMinAndMax (channels[0], numSamples, bufMin, bufMax);
  37. lmax = jmax (lmax, bufMax);
  38. lmin = jmin (lmin, bufMin);
  39. if (numChannels > 1)
  40. {
  41. findMinAndMax (channels[1], numSamples, bufMin, bufMax);
  42. rmax = jmax (rmax, bufMax);
  43. rmin = jmin (rmin, bufMin);
  44. }
  45. else
  46. {
  47. rmax = lmax;
  48. rmin = lmin;
  49. }
  50. }
  51. }
  52. //==============================================================================
  53. struct ColouredAudioThumbnail::MinMaxColourValue
  54. {
  55. char minValue;
  56. char maxValue;
  57. Colour colour; //drow
  58. MinMaxColourValue() : minValue (0), maxValue (0), colour(Colour::fromHSV(0.0, 1.0f, 1.0f, 1.0f))
  59. {
  60. }
  61. inline void set (const char newMin, const char newMax) throw()
  62. {
  63. minValue = newMin;
  64. maxValue = newMax;
  65. }
  66. inline void setFloat (const float newMin, const float newMax) throw()
  67. {
  68. minValue = (char) jlimit (-128, 127, roundFloatToInt (newMin * 127.0f));
  69. maxValue = (char) jlimit (-128, 127, roundFloatToInt (newMax * 127.0f));
  70. if (maxValue == minValue)
  71. maxValue = (char) jmin (127, maxValue + 1);
  72. }
  73. inline void setColour(const Colour& newColour) throw()
  74. {
  75. colour = newColour.withBrightness(1.0f);
  76. }
  77. inline char getMinValue() const noexcept { return minValue; }
  78. inline char getMaxValue() const noexcept { return maxValue; }
  79. inline bool isNonZero() const throw()
  80. {
  81. return maxValue > minValue;
  82. }
  83. inline int getPeak() const throw()
  84. {
  85. return jmax (::std::abs ((int) minValue),
  86. ::std::abs ((int) maxValue));
  87. }
  88. inline void read (InputStream& input)
  89. {
  90. //DBG("read from MinMaxColourValue");
  91. minValue = input.readByte();
  92. maxValue = input.readByte();
  93. input.read ((void*)&colour, sizeof(Colour));
  94. }
  95. inline void write (OutputStream& output)
  96. {
  97. output.writeByte (minValue);
  98. output.writeByte (maxValue);
  99. output.write ((void*)&colour, sizeof(Colour));
  100. }
  101. };
  102. //==============================================================================
  103. class ColouredAudioThumbnail::LevelDataSource : public TimeSliceClient,
  104. public Timer
  105. {
  106. public:
  107. LevelDataSource (ColouredAudioThumbnail& owner_, AudioFormatReader* newReader, int64 hash)
  108. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  109. hashCode (hash), owner (owner_), reader (newReader),
  110. tempSampleBufferSize (0), tempFilteredBufferSize (0)
  111. {
  112. }
  113. LevelDataSource (ColouredAudioThumbnail& owner_, InputSource* source_)
  114. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  115. hashCode (source_->hashCode()), owner (owner_), source (source_),
  116. tempSampleBufferSize (0), tempFilteredBufferSize (0)
  117. {
  118. }
  119. ~LevelDataSource()
  120. {
  121. owner.cache.getTimeSliceThread().removeTimeSliceClient (this);
  122. }
  123. enum { timeBeforeDeletingReader = 2000 };
  124. void initialise (int64 numSamplesFinished_)
  125. {
  126. const ScopedLock sl (readerLock);
  127. numSamplesFinished = numSamplesFinished_;
  128. createReader();
  129. if (reader != 0)
  130. {
  131. lengthInSamples = reader->lengthInSamples;
  132. numChannels = reader->numChannels;
  133. sampleRate = reader->sampleRate;
  134. filterLow.makeBandPass (reader->sampleRate, 130.0, 2);
  135. filterLowMid.makeBandPass (reader->sampleRate, 650.0, 2.0);
  136. filterHighMid.makeBandPass (reader->sampleRate, 1300.0, 2.0);
  137. filterHigh.makeHighPass (reader->sampleRate, 2700.0, 0.5);
  138. filterLow.reset();
  139. filterLowMid.reset();
  140. filterHighMid.reset();
  141. filterHigh.reset();
  142. if (lengthInSamples <= 0)
  143. reader = 0;
  144. else if (! isFullyLoaded())
  145. owner.cache.getTimeSliceThread().addTimeSliceClient (this);
  146. }
  147. }
  148. void getLevels (int64 startSample, int numSamples, Array<float>& levels, Array<Colour>& colours)
  149. {
  150. const ScopedLock sl (readerLock);
  151. createReader();
  152. if (reader != 0)
  153. {
  154. float l[4] = { 0 };
  155. Colour colourLeft, colourRight;
  156. readMaxLevelsFilteringWithColour (startSample, numSamples,
  157. l[0], l[1], l[2], l[3], colourLeft, colourRight);
  158. levels.clearQuick();
  159. levels.addArray ((const float*) l, 4);
  160. //*** not finding colour here
  161. colours.clearQuick();
  162. colours.add (colourLeft);
  163. colours.add (colourRight);
  164. }
  165. }
  166. void releaseResources()
  167. {
  168. const ScopedLock sl (readerLock);
  169. reader = 0;
  170. }
  171. int useTimeSlice()
  172. {
  173. if (isFullyLoaded())
  174. {
  175. if (reader != 0 && source != 0)
  176. startTimer (timeBeforeDeletingReader);
  177. owner.cache.getTimeSliceThread().removeTimeSliceClient (this);
  178. return false;
  179. }
  180. stopTimer();
  181. bool justFinished = false;
  182. {
  183. const ScopedLock sl (readerLock);
  184. createReader();
  185. if (reader != 0)
  186. {
  187. if (! readNextBlock())
  188. return true;
  189. justFinished = true;
  190. }
  191. }
  192. if (justFinished)
  193. owner.cache.storeThumb (owner, hashCode);
  194. return false;
  195. }
  196. void timerCallback()
  197. {
  198. stopTimer();
  199. releaseResources();
  200. }
  201. bool isFullyLoaded() const throw()
  202. {
  203. return numSamplesFinished >= lengthInSamples;
  204. }
  205. inline int sampleToThumbSample (const int64 originalSample) const throw()
  206. {
  207. return (int) (originalSample / owner.samplesPerThumbSample);
  208. }
  209. int64 lengthInSamples, numSamplesFinished;
  210. double sampleRate;
  211. int numChannels;
  212. int64 hashCode;
  213. private:
  214. ColouredAudioThumbnail& owner;
  215. ScopedPointer <InputSource> source;
  216. ScopedPointer <AudioFormatReader> reader;
  217. CriticalSection readerLock;
  218. BiquadFilter filterLow, filterLowMid, filterHighMid, filterHigh;
  219. HeapBlock<int> tempSampleBuffer, tempFilteredBuffer;
  220. int tempSampleBufferSize, tempFilteredBufferSize;
  221. void createReader()
  222. {
  223. if (reader == 0 && source != 0)
  224. {
  225. InputStream* audioFileStream = source->createInputStream();
  226. if (audioFileStream != 0)
  227. reader = owner.formatManagerToUse.createReaderFor (audioFileStream);
  228. }
  229. }
  230. bool readNextBlock()
  231. {
  232. jassert (reader != 0);
  233. if (! isFullyLoaded())
  234. {
  235. const int numToDo = (int) jmin (256 * (int64) owner.samplesPerThumbSample, lengthInSamples - numSamplesFinished);
  236. if (numToDo > 0)
  237. {
  238. int64 startSample = numSamplesFinished;
  239. const int firstThumbIndex = sampleToThumbSample (startSample);
  240. const int lastThumbIndex = sampleToThumbSample (startSample + numToDo);
  241. const int numThumbSamps = lastThumbIndex - firstThumbIndex;
  242. HeapBlock<MinMaxColourValue> levelData (numThumbSamps * 2);
  243. MinMaxColourValue* levels[2] = { levelData, levelData + numThumbSamps };
  244. for (int i = 0; i < numThumbSamps; ++i)
  245. {
  246. float lowestLeft, highestLeft, lowestRight, highestRight;
  247. Colour colourLeft, colourRight;
  248. readMaxLevelsFilteringWithColour ((firstThumbIndex + i) * owner.samplesPerThumbSample, owner.samplesPerThumbSample,
  249. lowestLeft, highestLeft, lowestRight, highestRight,
  250. colourLeft, colourRight);
  251. levels[0][i].setFloat (lowestLeft, highestLeft);
  252. levels[1][i].setFloat (lowestRight, highestRight);
  253. levels[0][i].setColour(colourLeft);
  254. levels[1][i].setColour(colourRight);
  255. }
  256. {
  257. const ScopedUnlock su (readerLock);
  258. owner.setLevels (levels, firstThumbIndex, 2, numThumbSamps);
  259. }
  260. numSamplesFinished += numToDo;
  261. }
  262. }
  263. return isFullyLoaded();
  264. }
  265. void readMaxLevelsFilteringWithColour (int64 startSampleInFile,
  266. int64 numSamples,
  267. float& lowestLeft, float& highestLeft,
  268. float& lowestRight, float& highestRight,
  269. Colour &colourLeft, Colour &colourRight)
  270. {
  271. if (numSamples <= 0)
  272. {
  273. lowestLeft = 0;
  274. lowestRight = 0;
  275. highestLeft = 0;
  276. highestRight = 0;
  277. colourLeft = Colours::white;
  278. colourRight = Colours::white;
  279. return;
  280. }
  281. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  282. const int newTempSampleBufferSize = bufferSize * 2 + 64;
  283. if (tempSampleBufferSize < newTempSampleBufferSize)
  284. {
  285. tempSampleBuffer.malloc (newTempSampleBufferSize);
  286. tempSampleBufferSize = newTempSampleBufferSize;
  287. }
  288. int* tempSpace = tempSampleBuffer.getData();
  289. int* tempBuffer[3] = {&tempSpace[0],
  290. &tempSpace[bufferSize],
  291. nullptr};
  292. const int filteredBlockSize = bufferSize * 4;
  293. if (tempFilteredBufferSize < filteredBlockSize)
  294. {
  295. tempFilteredBuffer.malloc (filteredBlockSize);
  296. tempFilteredBufferSize = filteredBlockSize;
  297. }
  298. int* filteredBlock = tempFilteredBuffer.getData();
  299. int* filteredArray[4] = {&filteredBlock[0],
  300. &filteredBlock[bufferSize],
  301. &filteredBlock[bufferSize * 2],
  302. &filteredBlock[bufferSize * 3]};
  303. float avgLow = 0.0f, avgMid = 0.0f, avgHigh = 0.0f;
  304. if (reader->usesFloatingPointData)
  305. {
  306. float lmin = std::numeric_limits<float>::max();
  307. float lmax = -lmin;
  308. float rmin = lmin;
  309. float rmax = lmax;
  310. while (numSamples > 0)
  311. {
  312. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  313. if (! reader->read (tempBuffer, 2, startSampleInFile, numToDo, false))
  314. break;
  315. // copy samples to buffers ready to be filtered
  316. memcpy (filteredArray[0], tempBuffer[0], sizeof (int) * numToDo);
  317. memcpy (filteredArray[1], tempBuffer[0], sizeof (int) * numToDo);
  318. memcpy (filteredArray[2], tempBuffer[0], sizeof (int) * numToDo);
  319. memcpy (filteredArray[3], tempBuffer[0], sizeof (int) * numToDo);
  320. // filter buffers
  321. filterLow.processSamples (reinterpret_cast<float*> (filteredArray[0]), numToDo);
  322. filterLowMid.processSamples (reinterpret_cast<float*> (filteredArray[1]), numToDo);
  323. filterHighMid.processSamples (reinterpret_cast<float*> (filteredArray[2]), numToDo);
  324. filterHigh.processSamples (reinterpret_cast<float*> (filteredArray[3]), numToDo);
  325. // calculate colour
  326. for (int i = 0; i < numToDo; i++)
  327. {
  328. float low = fabsf ((reinterpret_cast<float*> (filteredArray[0]))[i]);
  329. float mid = fabsf ((reinterpret_cast<float*> (filteredArray[1]))[i])
  330. + fabsf ((reinterpret_cast<float*> (filteredArray[2]))[i]);
  331. float high = fabsf ((reinterpret_cast<float*> (filteredArray[3]))[i]);
  332. if (low > avgLow) avgLow = low;
  333. if (mid > avgMid) avgMid = mid;
  334. if (high > avgHigh) avgHigh = high;
  335. }
  336. numSamples -= numToDo;
  337. startSampleInFile += numToDo;
  338. getStereoMinAndMax (reinterpret_cast<float**> (&tempBuffer[0]), reader->numChannels, numToDo,
  339. lmin, lmax, rmin, rmax);
  340. }
  341. lowestLeft = lmin;
  342. highestLeft = lmax;
  343. lowestRight = rmin;
  344. highestRight = rmax;
  345. }
  346. else
  347. {
  348. int lmax = std::numeric_limits<int>::min();
  349. int lmin = std::numeric_limits<int>::max();
  350. int rmax = std::numeric_limits<int>::min();
  351. int rmin = std::numeric_limits<int>::max();
  352. while (numSamples > 0)
  353. {
  354. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  355. if (! reader->read (tempBuffer, 2, startSampleInFile, numToDo, false))
  356. break;
  357. // copy samples to buffers ready to be filtered
  358. memcpy (filteredArray[0], tempBuffer[0], sizeof (int) * numToDo);
  359. memcpy (filteredArray[1], tempBuffer[0], sizeof (int) * numToDo);
  360. memcpy (filteredArray[2], tempBuffer[0], sizeof (int) * numToDo);
  361. memcpy (filteredArray[3], tempBuffer[0], sizeof (int) * numToDo);
  362. // filter buffers
  363. filterLow.processSamples ((filteredArray[0]), numToDo);
  364. filterLowMid.processSamples ((filteredArray[1]), numToDo);
  365. filterHighMid.processSamples ((filteredArray[2]), numToDo);
  366. filterHigh.processSamples ((filteredArray[3]), numToDo);
  367. // calculate colour
  368. for (int i = 0; i < numToDo; i++)
  369. {
  370. int low = abs (filteredArray[0][i]);
  371. int mid = abs (filteredArray[1][i]) + abs (filteredArray[2][i]);
  372. int high = abs (filteredArray[3][i]);
  373. if (low > avgLow) avgLow = (float) low;
  374. if (mid > avgMid) avgMid = (float) mid;
  375. if (high > avgHigh) avgHigh = (float) high;
  376. }
  377. numSamples -= numToDo;
  378. startSampleInFile += numToDo;
  379. getStereoMinAndMax (reinterpret_cast<int**> (&tempBuffer[0]), reader->numChannels, numToDo,
  380. lmin, lmax, rmin, rmax);
  381. }
  382. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  383. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  384. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  385. highestRight = rmax / (float) std::numeric_limits<int>::max();
  386. avgLow = avgLow / (float) ::std::numeric_limits<int>::max();
  387. avgMid = avgMid / (float) ::std::numeric_limits<int>::max();
  388. avgHigh = avgHigh / (float) ::std::numeric_limits<int>::max();
  389. }
  390. uint8 maxSize = ::std::numeric_limits<uint8>::max();
  391. colourLeft = Colour::fromRGB ((uint8) (avgLow * maxSize),
  392. (uint8) (avgMid * maxSize * 0.66f),
  393. (uint8) (avgHigh * maxSize * 0.33f));
  394. colourRight = colourLeft;
  395. }
  396. };
  397. //==============================================================================
  398. /* Holds the data for 1 cache sample and the methods required to rescale those.
  399. */
  400. class ColouredAudioThumbnail::ThumbData
  401. {
  402. public:
  403. ThumbData (const int numThumbSamples)
  404. : peakLevel (-1)
  405. {
  406. ensureSize (numThumbSamples);
  407. }
  408. inline MinMaxColourValue* getData (const int thumbSampleIndex) throw()
  409. {
  410. jassert (thumbSampleIndex < data.size());
  411. return data.getRawDataPointer() + thumbSampleIndex;
  412. }
  413. int getSize() const throw()
  414. {
  415. return data.size();
  416. }
  417. void getMinMax (int startSample, int endSample, MinMaxColourValue& result) const noexcept
  418. {
  419. if (startSample >= 0)
  420. {
  421. endSample = jmin (endSample, data.size() - 1);
  422. char mx = -128;
  423. char mn = 127;
  424. while (startSample <= endSample)
  425. {
  426. const MinMaxColourValue& v = data.getReference (startSample);
  427. if (v.minValue < mn) mn = v.minValue;
  428. if (v.maxValue > mx) mx = v.maxValue;
  429. ++startSample;
  430. }
  431. if (mn <= mx)
  432. {
  433. result.set (mn, mx);
  434. return;
  435. }
  436. }
  437. result.set (1, 0);
  438. }
  439. void getColour (int startSample, int endSample, MinMaxColourValue& result) throw()
  440. {
  441. const int numSamples = endSample - startSample;
  442. uint8 red = 0, green = 0, blue = 0;
  443. if (startSample >= 0)
  444. {
  445. endSample = jmin (endSample, data.size() - 1);
  446. while (startSample <= endSample)
  447. {
  448. const MinMaxColourValue& v = data.getReference (startSample);
  449. if (numSamples == 1)
  450. {
  451. result.colour = v.colour;
  452. return;
  453. }
  454. if (v.colour.getRed() > red) {
  455. red = v.colour.getRed();
  456. }
  457. if (v.colour.getGreen() > green) {
  458. green = v.colour.getGreen();
  459. }
  460. if (v.colour.getBlue() > blue) {
  461. blue = v.colour.getBlue();
  462. }
  463. ++startSample;
  464. }
  465. }
  466. result.colour = Colour(red, green, blue);
  467. }
  468. void write (const MinMaxColourValue* const source, const int startIndex, const int numValues)
  469. {
  470. resetPeak();
  471. if (startIndex + numValues > data.size())
  472. ensureSize (startIndex + numValues);
  473. MinMaxColourValue* const dest = getData (startIndex);
  474. for (int i = 0; i < numValues; ++i)
  475. dest[i] = source[i];
  476. }
  477. void resetPeak()
  478. {
  479. peakLevel = -1;
  480. }
  481. int getPeak()
  482. {
  483. if (peakLevel < 0)
  484. {
  485. for (int i = 0; i < data.size(); ++i)
  486. {
  487. const int peak = data[i].getPeak();
  488. if (peak > peakLevel)
  489. peakLevel = peak;
  490. }
  491. }
  492. return peakLevel;
  493. }
  494. private:
  495. Array <MinMaxColourValue> data;
  496. int peakLevel;
  497. void ensureSize (const int thumbSamples)
  498. {
  499. const int extraNeeded = thumbSamples - data.size();
  500. if (extraNeeded > 0)
  501. data.insertMultiple (-1, MinMaxColourValue(), extraNeeded);
  502. }
  503. };
  504. //==============================================================================
  505. class ColouredAudioThumbnail::CachedWindow
  506. {
  507. public:
  508. CachedWindow()
  509. : cachedStart (0), cachedTimePerPixel (0),
  510. numChannelsCached (0), numSamplesCached (0),
  511. cacheNeedsRefilling (true)
  512. {
  513. }
  514. void invalidate()
  515. {
  516. cacheNeedsRefilling = true;
  517. }
  518. void drawChannel (Graphics& g, const Rectangle<int>& area,
  519. const double startTime, const double endTime,
  520. const int channelNum, const float verticalZoomFactor,
  521. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  522. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  523. {
  524. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  525. numChannels, samplesPerThumbSample, levelData, channels);
  526. if (isPositiveAndBelow (channelNum, numChannelsCached))
  527. {
  528. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  529. if (! clip.isEmpty())
  530. {
  531. const float topY = (float) area.getY();
  532. const float bottomY = (float) area.getBottom();
  533. const float midY = (topY + bottomY) * 0.5f;
  534. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  535. const MinMaxColourValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  536. int x = clip.getX();
  537. for (int w = clip.getWidth(); --w >= 0;)
  538. {
  539. if (cacheData->isNonZero())
  540. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  541. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  542. ++x;
  543. ++cacheData;
  544. }
  545. }
  546. }
  547. }
  548. void drawColouredChannel (Graphics& g, const Rectangle<int>& area,
  549. const double startTime, const double endTime,
  550. const int channelNum, const float verticalZoomFactor,
  551. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  552. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  553. {
  554. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  555. numChannels, samplesPerThumbSample, levelData, channels);
  556. if (isPositiveAndBelow (channelNum, numChannelsCached))
  557. {
  558. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  559. if (! clip.isEmpty())
  560. {
  561. const float topY = (float) area.getY();
  562. const float bottomY = (float) area.getBottom();
  563. const float midY = (topY + bottomY) * 0.5f;
  564. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  565. const MinMaxColourValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  566. int x = clip.getX();
  567. for (int w = clip.getWidth(); --w >= 0;)
  568. {
  569. if (cacheData->isNonZero())
  570. {
  571. // set colour of line //drow
  572. g.setColour (cacheData->colour);
  573. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  574. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  575. }
  576. ++x;
  577. ++cacheData;
  578. }
  579. }
  580. }
  581. }
  582. private:
  583. Array <MinMaxColourValue> data;
  584. double cachedStart, cachedTimePerPixel;
  585. int numChannelsCached, numSamplesCached;
  586. bool cacheNeedsRefilling;
  587. void refillCache (const int numSamples, double startTime, const double endTime,
  588. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  589. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  590. {
  591. const double timePerPixel = (endTime - startTime) / numSamples;
  592. if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0)
  593. {
  594. invalidate();
  595. return;
  596. }
  597. if (numSamples == numSamplesCached
  598. && numChannelsCached == numChannels
  599. && startTime == cachedStart
  600. && timePerPixel == cachedTimePerPixel
  601. && ! cacheNeedsRefilling)
  602. {
  603. return;
  604. }
  605. numSamplesCached = numSamples;
  606. numChannelsCached = numChannels;
  607. cachedStart = startTime;
  608. cachedTimePerPixel = timePerPixel;
  609. cacheNeedsRefilling = false;
  610. ensureSize (numSamples);
  611. if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != 0)
  612. {
  613. int sample = roundToInt (startTime * sampleRate);
  614. Array<float> levels;
  615. Array<Colour> colours;
  616. int i;
  617. for (i = 0; i < numSamples; ++i)
  618. {
  619. const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate);
  620. if (sample >= 0)
  621. {
  622. if (sample >= levelData->lengthInSamples)
  623. break;
  624. levelData->getLevels (sample, jmax (1, nextSample - sample), levels, colours);
  625. const int numChans = jmin (levels.size() / 2, numChannelsCached);
  626. for (int chan = 0; chan < numChans; ++chan)
  627. {
  628. getData (chan, i)->setFloat (levels.getUnchecked (chan * 2),
  629. levels.getUnchecked (chan * 2 + 1));
  630. getData (chan, i)->setColour(colours.getUnchecked(chan));
  631. }
  632. }
  633. startTime += timePerPixel;
  634. sample = nextSample;
  635. }
  636. numSamplesCached = i;
  637. }
  638. else
  639. {
  640. jassert (channels.size() == numChannelsCached);
  641. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  642. {
  643. ThumbData* channelData = channels.getUnchecked (channelNum);
  644. MinMaxColourValue* cacheData = getData (channelNum, 0);
  645. const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample;
  646. startTime = cachedStart;
  647. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  648. for (int i = numSamples; --i >= 0;)
  649. {
  650. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  651. channelData->getMinMax (sample, nextSample, *cacheData);
  652. channelData->getColour(sample, nextSample, *cacheData);
  653. ++cacheData;
  654. startTime += timePerPixel;
  655. sample = nextSample;
  656. }
  657. }
  658. }
  659. }
  660. MinMaxColourValue* getData (const int channelNum, const int cacheIndex) throw()
  661. {
  662. jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));
  663. return data.getRawDataPointer() + channelNum * numSamplesCached
  664. + cacheIndex;
  665. }
  666. void ensureSize (const int numSamples)
  667. {
  668. const int itemsRequired = numSamples * numChannelsCached;
  669. if (data.size() < itemsRequired)
  670. data.insertMultiple (-1, MinMaxColourValue(), itemsRequired - data.size());
  671. }
  672. };
  673. //==============================================================================
  674. ColouredAudioThumbnail::ColouredAudioThumbnail (const int originalSamplesPerThumbnailSample,
  675. AudioFormatManager& formatManagerToUse_,
  676. AudioThumbnailCache& cacheToUse)
  677. : formatManagerToUse (formatManagerToUse_),
  678. cache (cacheToUse),
  679. window (new CachedWindow()),
  680. samplesPerThumbSample (originalSamplesPerThumbnailSample),
  681. totalSamples (0),
  682. numChannels (0),
  683. sampleRate (0)
  684. {
  685. }
  686. ColouredAudioThumbnail::~ColouredAudioThumbnail()
  687. {
  688. clear();
  689. }
  690. void ColouredAudioThumbnail::clear()
  691. {
  692. source = 0;
  693. const ScopedLock sl (lock);
  694. window->invalidate();
  695. channels.clear();
  696. totalSamples = numSamplesFinished = 0;
  697. numChannels = 0;
  698. sampleRate = 0;
  699. sendChangeMessage();
  700. }
  701. void ColouredAudioThumbnail::reset (int newNumChannels, double newSampleRate, int64 totalSamplesInSource)
  702. {
  703. clear();
  704. numChannels = newNumChannels;
  705. sampleRate = newSampleRate;
  706. totalSamples = totalSamplesInSource;
  707. createChannels (1 + (int) (totalSamplesInSource / samplesPerThumbSample));
  708. }
  709. void ColouredAudioThumbnail::createChannels (const int length)
  710. {
  711. while (channels.size() < numChannels)
  712. channels.add (new ThumbData (length));
  713. }
  714. //==============================================================================
  715. bool ColouredAudioThumbnail::loadFrom (InputStream& input)
  716. {
  717. clear();
  718. if (input.readByte() != 'j' || input.readByte() != 'a' || input.readByte() != 't' || input.readByte() != 'm')
  719. return false;
  720. samplesPerThumbSample = input.readInt();
  721. totalSamples = input.readInt64(); // Total number of source samples.
  722. numSamplesFinished = input.readInt64(); // Number of valid source samples that have been read into the thumbnail.
  723. int32 numThumbnailSamples = input.readInt(); // Number of samples in the thumbnail data.
  724. numChannels = input.readInt(); // Number of audio channels.
  725. sampleRate = input.readInt(); // Source sample rate.
  726. input.skipNextBytes (16); // reserved area
  727. createChannels (numThumbnailSamples);
  728. for (int i = 0; i < numThumbnailSamples; ++i)
  729. for (int chan = 0; chan < numChannels; ++chan)
  730. channels.getUnchecked(chan)->getData(i)->read (input);
  731. return true;
  732. }
  733. void ColouredAudioThumbnail::saveTo (OutputStream& output) const
  734. {
  735. const ScopedLock sl (lock);
  736. const int numThumbnailSamples = channels.size() == 0 ? 0 : channels.getUnchecked(0)->getSize();
  737. output.write ("jatm", 4);
  738. output.writeInt (samplesPerThumbSample);
  739. output.writeInt64 (totalSamples);
  740. output.writeInt64 (numSamplesFinished);
  741. output.writeInt (numThumbnailSamples);
  742. output.writeInt (numChannels);
  743. output.writeInt ((int) sampleRate);
  744. output.writeInt64 (0);
  745. output.writeInt64 (0);
  746. for (int i = 0; i < numThumbnailSamples; ++i)
  747. for (int chan = 0; chan < numChannels; ++chan)
  748. channels.getUnchecked(chan)->getData(i)->write (output);
  749. }
  750. //==============================================================================
  751. bool ColouredAudioThumbnail::setDataSource (LevelDataSource* newSource)
  752. {
  753. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  754. numSamplesFinished = 0;
  755. if (cache.loadThumb (*this, newSource->hashCode) && isFullyLoaded())
  756. {
  757. source = newSource; // (make sure this isn't done before loadThumb is called)
  758. source->lengthInSamples = totalSamples;
  759. source->sampleRate = sampleRate;
  760. source->numChannels = numChannels;
  761. source->numSamplesFinished = numSamplesFinished;
  762. }
  763. else
  764. {
  765. source = newSource; // (make sure this isn't done before loadThumb is called)
  766. const ScopedLock sl (lock);
  767. source->initialise (numSamplesFinished);
  768. totalSamples = source->lengthInSamples;
  769. sampleRate = source->sampleRate;
  770. numChannels = source->numChannels;
  771. createChannels (1 + (int) (totalSamples / samplesPerThumbSample));
  772. }
  773. return sampleRate > 0 && totalSamples > 0;
  774. }
  775. bool ColouredAudioThumbnail::setSource (InputSource* const newSource)
  776. {
  777. clear();
  778. return newSource != 0 && setDataSource (new LevelDataSource (*this, newSource));
  779. }
  780. void ColouredAudioThumbnail::setReader (AudioFormatReader* newReader, int64 hash)
  781. {
  782. clear();
  783. if (newReader != 0)
  784. setDataSource (new LevelDataSource (*this, newReader, hash));
  785. }
  786. int64 ColouredAudioThumbnail::getHashCode() const
  787. {
  788. return source == 0 ? 0 : source->hashCode;
  789. }
  790. void ColouredAudioThumbnail::addBlock (const int64 startSample, const AudioSampleBuffer& incoming,
  791. int startOffsetInBuffer, int numSamples)
  792. {
  793. jassert (startSample >= 0);
  794. const int firstThumbIndex = (int) (startSample / samplesPerThumbSample);
  795. const int lastThumbIndex = (int) ((startSample + numSamples + (samplesPerThumbSample - 1)) / samplesPerThumbSample);
  796. const int numToDo = lastThumbIndex - firstThumbIndex;
  797. if (numToDo > 0)
  798. {
  799. const int numChans = jmin (channels.size(), incoming.getNumChannels());
  800. const HeapBlock<MinMaxColourValue> thumbData (numToDo * numChans);
  801. const HeapBlock<MinMaxColourValue*> thumbChannels (numChans);
  802. for (int chan = 0; chan < numChans; ++chan)
  803. {
  804. const float* const sourceData = incoming.getReadPointer (chan, startOffsetInBuffer);
  805. MinMaxColourValue* const dest = thumbData + numToDo * chan;
  806. thumbChannels [chan] = dest;
  807. for (int i = 0; i < numToDo; ++i)
  808. {
  809. float low, high;
  810. const int start = i * samplesPerThumbSample;
  811. findMinAndMax (sourceData + start, jmin (samplesPerThumbSample, numSamples - start), low, high);
  812. dest[i].setFloat (low, high);
  813. }
  814. }
  815. setLevels (thumbChannels, firstThumbIndex, numChans, numToDo);
  816. }
  817. }
  818. void ColouredAudioThumbnail::setLevels (const MinMaxColourValue* const* values, int thumbIndex, int numChans, int numValues)
  819. {
  820. const ScopedLock sl (lock);
  821. for (int i = jmin (numChans, channels.size()); --i >= 0;)
  822. channels.getUnchecked(i)->write (values[i], thumbIndex, numValues);
  823. numSamplesFinished = jmax (numSamplesFinished, (thumbIndex + numValues) * (int64) samplesPerThumbSample);
  824. totalSamples = jmax (numSamplesFinished, totalSamples);
  825. window->invalidate();
  826. sendChangeMessage();
  827. }
  828. //==============================================================================
  829. int ColouredAudioThumbnail::getNumChannels() const throw()
  830. {
  831. return numChannels;
  832. }
  833. double ColouredAudioThumbnail::getTotalLength() const throw()
  834. {
  835. return totalSamples / sampleRate;
  836. }
  837. bool ColouredAudioThumbnail::isFullyLoaded() const throw()
  838. {
  839. return numSamplesFinished >= totalSamples - samplesPerThumbSample;
  840. }
  841. int64 ColouredAudioThumbnail::getNumSamplesFinished() const throw()
  842. {
  843. return numSamplesFinished;
  844. }
  845. float ColouredAudioThumbnail::getApproximatePeak() const
  846. {
  847. int peak = 0;
  848. for (int i = channels.size(); --i >= 0;)
  849. peak = jmax (peak, channels.getUnchecked(i)->getPeak());
  850. return jlimit (0, 127, peak) / 127.0f;
  851. }
  852. void ColouredAudioThumbnail::getApproximateMinMax (const double startTime, const double endTime, const int channelIndex,
  853. float& minValue, float& maxValue) const noexcept
  854. {
  855. const ScopedLock sl (lock);
  856. MinMaxColourValue result;
  857. const ThumbData* const data = channels [channelIndex];
  858. if (data != nullptr && sampleRate > 0)
  859. {
  860. const int firstThumbIndex = (int) ((startTime * sampleRate) / samplesPerThumbSample);
  861. const int lastThumbIndex = (int) (((endTime * sampleRate) + samplesPerThumbSample - 1) / samplesPerThumbSample);
  862. data->getMinMax (jmax (0, firstThumbIndex), lastThumbIndex, result);
  863. }
  864. minValue = result.getMinValue() / 128.0f;
  865. maxValue = result.getMaxValue() / 128.0f;
  866. }
  867. void ColouredAudioThumbnail::drawChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  868. double endTime, int channelNum, float verticalZoomFactor)
  869. {
  870. const ScopedLock sl (lock);
  871. drawColouredChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor);
  872. }
  873. void ColouredAudioThumbnail::drawColouredChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  874. double endTime, int channelNum, float verticalZoomFactor)
  875. {
  876. const ScopedLock sl (lock);
  877. window->drawColouredChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor,
  878. sampleRate, numChannels, samplesPerThumbSample, source, channels);
  879. }
  880. void ColouredAudioThumbnail::drawChannels (Graphics& g, const Rectangle<int>& area, double startTimeSeconds,
  881. double endTimeSeconds, float verticalZoomFactor)
  882. {
  883. for (int i = 0; i < numChannels; ++i)
  884. {
  885. const int y1 = roundToInt ((i * area.getHeight()) / numChannels);
  886. const int y2 = roundToInt (((i + 1) * area.getHeight()) / numChannels);
  887. drawChannel (g, Rectangle<int> (area.getX(), area.getY() + y1, area.getWidth(), y2 - y1),
  888. startTimeSeconds, endTimeSeconds, i, verticalZoomFactor);
  889. }
  890. }