WaveformView.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. #include "ui/WaveformView.h"
  2. #include "platform/Paths.h"
  3. #include <algorithm>
  4. #include <atomic>
  5. #include <cmath>
  6. #include <mutex>
  7. #include "core/Sha256.h"
  8. #include "engine/FileSort.h"
  9. #include "core/Mp3Decoder.h"
  10. #include "engine/Mp3Format.h"
  11. #include "engine/WavPackFormat.h"
  12. #include "ui/I18n.h"
  13. #include "ui/Theme.h"
  14. namespace lynx::ui
  15. {
  16. namespace
  17. {
  18. constexpr double longestDecodedSeconds = 20.0 * 60.0; // files decoded here (Browser): longer ones are skipped
  19. constexpr int diskCacheMaxFiles = 600;
  20. // path + size + modification time: a changed file gets a new entry
  21. juce::String diskKey (const juce::File& file)
  22. {
  23. const auto text = (file.getFullPathName() + "|" + juce::String (file.getSize()) + "|" + juce::String (file.getLastModificationTime().toMilliseconds())
  24. + "|" + juce::String ((int) wave::formatVersion)
  25. // MP3s: waveforms drawn from JUCE's decoder (before round 157b) are drawn again
  26. + (file.hasFileExtension ("mp3;mp2;mpga") ? juce::String ("|") + mp3::decoderId : juce::String()))
  27. .toStdString();
  28. return juce::String (sha256Hex (reinterpret_cast<const std::uint8_t*> (text.data()), text.size())).substring (0, 40);
  29. }
  30. void pruneDiskCache (const juce::File& folder)
  31. {
  32. // one prune at a time (the pool's threads finish waveforms together), and not after every single new file
  33. static std::mutex pruning;
  34. static std::atomic<int> writes { 0 };
  35. if (writes.fetch_add (1) % 16 != 0)
  36. return;
  37. const std::lock_guard<std::mutex> guard (pruning);
  38. auto files = folder.findChildFiles (juce::File::findFiles, false, "*.lwv");
  39. if (files.size() <= diskCacheMaxFiles)
  40. return;
  41. filesort::byTime (files, filesort::By::accessTime); // (times read once: issue #12's crash)
  42. for (int i = 0; i < files.size() - diskCacheMaxFiles * 3 / 4; ++i)
  43. files.getReference (i).deleteFile();
  44. }
  45. } // namespace
  46. // --- cache ---------------------------------------------------------------------------------------
  47. class WaveformCache::Job final : public juce::ThreadPoolJob
  48. {
  49. public:
  50. Job (WaveformCache& c, juce::String p, std::shared_ptr<const SampleData> d)
  51. : juce::ThreadPoolJob ("waveform"),
  52. cache (c),
  53. path (std::move (p)),
  54. data (std::move (d))
  55. {
  56. }
  57. JobStatus runJob() override
  58. {
  59. cache.finished (path, build());
  60. return jobHasFinished;
  61. }
  62. private:
  63. std::shared_ptr<const wave::Summary> build()
  64. {
  65. const juce::File file (path);
  66. const auto onDisk = file.existsAsFile();
  67. const auto folder = diskFolder();
  68. const auto cacheFile = onDisk ? folder.getChildFile (diskKey (file) + ".lwv") : juce::File();
  69. // 1. the disk cache
  70. if (onDisk && cacheFile.existsAsFile())
  71. {
  72. juce::MemoryBlock block;
  73. wave::Summary s;
  74. if (cacheFile.loadFileAsData (block) && wave::deserialise (static_cast<const std::uint8_t*> (block.getData()), block.getSize(), s))
  75. {
  76. cacheFile.setLastAccessTime (juce::Time::getCurrentTime());
  77. return std::make_shared<const wave::Summary> (std::move (s));
  78. }
  79. cacheFile.deleteFile();
  80. }
  81. // 2. the audio: from the engine, or decoded here
  82. if (data == nullptr && onDisk)
  83. data = decode (file);
  84. if (data == nullptr || data->frames() == 0 || cache.cancel.load())
  85. return nullptr;
  86. auto s = wave::analyse (data->leftData(), data->isStereo() ? data->rightData() : nullptr, data->frames(), data->sampleRate, &cache.cancel);
  87. data.reset();
  88. if (s.levels.empty())
  89. return nullptr;
  90. // 3. kept for the next session
  91. if (onDisk && folder.createDirectory())
  92. {
  93. const auto bytes = wave::serialise (s);
  94. const auto temp = cacheFile.withFileExtension ("tmp");
  95. if (temp.replaceWithData (bytes.data(), bytes.size()))
  96. temp.moveFileTo (cacheFile);
  97. pruneDiskCache (folder);
  98. }
  99. return std::make_shared<const wave::Summary> (std::move (s));
  100. }
  101. std::shared_ptr<const SampleData> decode (const juce::File& file)
  102. {
  103. std::unique_ptr<juce::AudioFormatReader> reader (cache.formats.createReaderFor (file));
  104. if (reader == nullptr || reader->sampleRate <= 0.0 || reader->lengthInSamples <= 0
  105. || (double) reader->lengthInSamples / reader->sampleRate > longestDecodedSeconds)
  106. return nullptr;
  107. const auto frames = (int) reader->lengthInSamples;
  108. const auto stereo = reader->numChannels > 1;
  109. juce::AudioBuffer<float> buffer (stereo ? 2 : 1, frames);
  110. if (! reader->read (&buffer, 0, frames, 0, true, stereo))
  111. return nullptr;
  112. auto out = std::make_shared<SampleData>();
  113. out->sampleRate = reader->sampleRate;
  114. out->left.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + frames);
  115. if (stereo)
  116. out->right.assign (buffer.getReadPointer (1), buffer.getReadPointer (1) + frames);
  117. return out;
  118. }
  119. WaveformCache& cache;
  120. juce::String path;
  121. std::shared_ptr<const SampleData> data;
  122. };
  123. WaveformCache::WaveformCache()
  124. {
  125. registerAudioFormats (formats); // LYNX's MP3 reader first (round 157b)
  126. formats.registerFormat (new WavPackAudioFormat(), false);
  127. }
  128. WaveformCache::~WaveformCache()
  129. {
  130. cancel = true;
  131. pool.removeAllJobs (true, 10000);
  132. clearSingletonInstance();
  133. }
  134. juce::File WaveformCache::diskFolder()
  135. {
  136. return lynx::platform::cacheFolder ("wavecache");
  137. }
  138. std::shared_ptr<const wave::Summary> WaveformCache::find (const juce::String& path, const Source& source)
  139. {
  140. if (path.isEmpty())
  141. return nullptr;
  142. {
  143. std::lock_guard<std::mutex> guard (lock);
  144. if (auto it = ready.find (path); it != ready.end())
  145. return it->second;
  146. if (state.count (path) != 0)
  147. return nullptr;
  148. state[path] = true;
  149. }
  150. // UI thread: the engine's copy (usually already loaded, so no decoding here)
  151. auto data = source ? source() : nullptr;
  152. pool.addJob (new Job (*this, path, std::move (data)), true);
  153. return nullptr;
  154. }
  155. bool WaveformCache::isPending (const juce::String& path) const
  156. {
  157. std::lock_guard<std::mutex> guard (lock);
  158. const auto it = state.find (path);
  159. return it != state.end() && it->second;
  160. }
  161. bool WaveformCache::hasFailed (const juce::String& path) const
  162. {
  163. std::lock_guard<std::mutex> guard (lock);
  164. const auto it = state.find (path);
  165. return it != state.end() && ! it->second;
  166. }
  167. void WaveformCache::finished (const juce::String& path, std::shared_ptr<const wave::Summary> summary)
  168. {
  169. {
  170. std::lock_guard<std::mutex> guard (lock);
  171. if (summary != nullptr)
  172. {
  173. ready[path] = std::move (summary);
  174. state.erase (path);
  175. }
  176. else
  177. state[path] = false;
  178. }
  179. if (! cancel.load())
  180. sendChangeMessage(); // any thread; delivered on the message thread
  181. }
  182. bool WaveformCache::waitUntilIdle (int timeoutMs)
  183. {
  184. const auto until = juce::Time::getMillisecondCounter() + (juce::uint32) timeoutMs;
  185. while (pool.getNumJobs() > 0)
  186. {
  187. if (juce::Time::getMillisecondCounter() > until)
  188. return false;
  189. juce::Thread::sleep (5);
  190. }
  191. return true;
  192. }
  193. // --- drawing -------------------------------------------------------------------------------------
  194. WaveStyle currentWaveStyle (juce::Colour classic, float gain)
  195. {
  196. WaveStyle s;
  197. s.classic = classic;
  198. s.spectral = WaveformCache::spectral;
  199. s.stereo = WaveformCache::stereo;
  200. s.gain = gain;
  201. return s;
  202. }
  203. float normalisingGain (const wave::Summary& summary)
  204. {
  205. return summary.peak > 0.0f ? std::min (1.0f / summary.peak, 15.85f) : 1.0f;
  206. }
  207. namespace
  208. {
  209. // The clean style: per lane, the peak envelope mirrored around the centre and filled as one anti-aliased
  210. // path in a single colour; no RMS layer, no outline, so it reads calmly at any zoom. The envelope is computed
  211. // per physical pixel and lightly smoothed (a 1-2-1 blend that never goes below the true peak), which removes
  212. // one-pixel spikes without hiding transients.
  213. void appendCleanWaveform (juce::Path& wave, float scale, juce::Rectangle<float> body, juce::Rectangle<float> visible, const wave::Summary& summary,
  214. double startFrame, double framesPerPixel, const WaveStyle& style)
  215. {
  216. const auto columns = (int) std::ceil (visible.getWidth() * scale) + 1;
  217. const auto framesPerColumn = framesPerPixel / scale;
  218. const auto firstFrame = startFrame + (double) (visible.getX() - body.getX()) * framesPerPixel;
  219. const auto lanes = style.stereo && summary.channels > 1 ? 2 : 1;
  220. const auto laneHeight = body.getHeight() / (float) lanes;
  221. std::vector<float> peak ((std::size_t) columns), smooth ((std::size_t) columns);
  222. std::vector<char> valid ((std::size_t) columns);
  223. for (int lane = 0; lane < lanes; ++lane)
  224. {
  225. for (int x = 0; x < columns; ++x)
  226. {
  227. auto from = firstFrame + (double) x * framesPerColumn;
  228. auto to = from + framesPerColumn;
  229. if (to < from)
  230. std::swap (from, to);
  231. // zoomed in closer than the summary's finest columns: look at least one column wide, centred, so the
  232. // envelope stays a smooth outline instead of beading along single cycles
  233. if (const auto minWidth = (double) summary.bucket * 1.5; to - from < minWidth)
  234. {
  235. const auto centre = (from + to) * 0.5;
  236. const auto end = (double) summary.frames;
  237. const auto inside = centre >= 0.0 && centre < end;
  238. from = std::max (0.0, centre - minWidth * 0.5);
  239. to = std::min (end, centre + minWidth * 0.5);
  240. if (! inside)
  241. from = to = -1.0;
  242. }
  243. const auto p = from < 0.0 ? wave::Point {} : summary.query (from, to, lanes == 2 ? lane : -1);
  244. valid[(std::size_t) x] = p.valid ? 1 : 0;
  245. peak[(std::size_t) x] = p.valid ? std::min (1.0f, std::max (std::abs (p.hi), std::abs (p.lo)) * style.gain) : 0.0f;
  246. }
  247. for (int x = 0; x < columns; ++x)
  248. {
  249. const auto l = peak[(std::size_t) std::max (0, x - 1)], c = peak[(std::size_t) x], r = peak[(std::size_t) std::min (columns - 1, x + 1)];
  250. smooth[(std::size_t) x] = std::max (c, (l + 2.0f * c + r) * 0.25f);
  251. }
  252. const auto centre = body.getY() + laneHeight * ((float) lane + 0.5f);
  253. const auto half = laneHeight * 0.5f - 1.0f;
  254. const auto minHalf = 0.5f; // silence still shows as a hairline
  255. // one closed path per run of valid columns: the top edge left to right, the bottom edge back
  256. int x = 0;
  257. while (x < columns)
  258. {
  259. while (x < columns && ! valid[(std::size_t) x])
  260. ++x;
  261. if (x >= columns)
  262. break;
  263. const auto runStart = x;
  264. while (x < columns && valid[(std::size_t) x])
  265. ++x;
  266. const auto runEnd = x; // exclusive
  267. auto px = [&] (int i) { return visible.getX() + (float) i / scale; };
  268. wave.startNewSubPath (px (runStart), centre - std::max (minHalf, smooth[(std::size_t) runStart] * half));
  269. for (int i = runStart + 1; i < runEnd; ++i)
  270. wave.lineTo (px (i), centre - std::max (minHalf, smooth[(std::size_t) i] * half));
  271. wave.lineTo (px (runEnd), centre - std::max (minHalf, smooth[(std::size_t) (runEnd - 1)] * half));
  272. wave.lineTo (px (runEnd), centre + std::max (minHalf, smooth[(std::size_t) (runEnd - 1)] * half));
  273. for (int i = runEnd - 1; i >= runStart; --i)
  274. wave.lineTo (px (i), centre + std::max (minHalf, smooth[(std::size_t) i] * half));
  275. wave.closeSubPath();
  276. }
  277. }
  278. }
  279. void paintCleanWaveform (juce::Graphics& g, juce::Rectangle<float> body, juce::Rectangle<float> visible, const wave::Summary& summary,
  280. double startFrame, double framesPerPixel, const WaveStyle& style)
  281. {
  282. const auto scale = juce::jlimit (1.0f, 4.0f, g.getInternalContext().getPhysicalPixelScaleFactor());
  283. juce::Path wave;
  284. appendCleanWaveform (wave, scale, body, visible, summary, startFrame, framesPerPixel, style);
  285. g.setColour (style.classic);
  286. g.fillPath (wave);
  287. }
  288. } // namespace
  289. bool appendWaveformPath (juce::Path& out, float scale, juce::Rectangle<float> body, juce::Rectangle<float> clip, const wave::Summary& summary,
  290. double startFrame, double framesPerPixel, const WaveStyle& style)
  291. {
  292. if (style.spectral)
  293. return false;
  294. const auto visible = body.getIntersection (clip);
  295. if (! visible.isEmpty() && ! summary.levels.empty() && framesPerPixel != 0.0 && body.getHeight() >= 2.0f)
  296. appendCleanWaveform (out, juce::jlimit (1.0f, 4.0f, scale), body, visible, summary, startFrame, framesPerPixel, style);
  297. return true;
  298. }
  299. void paintWaveform (juce::Graphics& g, juce::Rectangle<float> body, const wave::Summary& summary, double startFrame, double framesPerPixel,
  300. const WaveStyle& style)
  301. {
  302. auto visible = body.getIntersection (g.getClipBounds().toFloat());
  303. if (visible.isEmpty() || summary.levels.empty() || framesPerPixel == 0.0 || body.getHeight() < 2.0f)
  304. return;
  305. // the columns on the body's own pixel grid, two more on each side (the clean style smooths over neighbours): a
  306. // repaint of part of the body (a scrolled strip, round 174f) draws the same pixels as a paint of the whole body
  307. {
  308. const auto gridScale = juce::jlimit (1.0f, 4.0f, g.getInternalContext().getPhysicalPixelScaleFactor());
  309. const auto first = juce::jmax (0.0f, std::floor ((visible.getX() - body.getX()) * gridScale) - 2.0f);
  310. const auto last = juce::jmin (std::ceil (body.getWidth() * gridScale), std::ceil ((visible.getRight() - body.getX()) * gridScale) + 2.0f);
  311. visible = visible.withX (body.getX() + first / gridScale).withWidth (juce::jmax (0.0f, last - first) / gridScale);
  312. if (visible.isEmpty())
  313. return;
  314. }
  315. if (! style.spectral)
  316. {
  317. juce::Graphics::ScopedSaveState save (g);
  318. g.reduceClipRegion (body.getSmallestIntegerContainer());
  319. paintCleanWaveform (g, body, visible, summary, startFrame, framesPerPixel, style);
  320. return;
  321. }
  322. // one pixel buffer at physical resolution (sharp on high-DPI screens), reused between calls
  323. const auto scale = juce::jlimit (1.0f, 4.0f, g.getInternalContext().getPhysicalPixelScaleFactor());
  324. const auto width = (int) std::ceil (visible.getWidth() * scale);
  325. const auto height = (int) std::ceil (body.getHeight() * scale);
  326. auto& scratch = WaveformCache::getInstance()->scratchImage();
  327. if (! scratch.isValid() || scratch.getWidth() < width || scratch.getHeight() < height)
  328. scratch = juce::Image (juce::Image::ARGB, std::max (width, scratch.isValid() ? scratch.getWidth() : 0),
  329. std::max (height, scratch.isValid() ? scratch.getHeight() : 0), false, juce::SoftwareImageType());
  330. const auto lanes = style.stereo && summary.channels > 1 ? 2 : 1;
  331. const auto laneHeight = (float) height / (float) lanes;
  332. const auto framesPerColumn = framesPerPixel / scale;
  333. const auto firstFrame = startFrame + (double) (visible.getX() - body.getX()) * framesPerPixel;
  334. const auto classic = style.classic;
  335. bool drewAny = false;
  336. {
  337. juce::Image::BitmapData pixels (scratch, 0, 0, width, height, juce::Image::BitmapData::writeOnly);
  338. for (int x = 0; x < width; ++x)
  339. {
  340. auto from = firstFrame + (double) x * framesPerColumn;
  341. auto to = from + framesPerColumn;
  342. if (to < from)
  343. std::swap (from, to);
  344. for (int lane = 0; lane < lanes; ++lane)
  345. {
  346. const auto top = (int) std::round ((float) lane * laneHeight);
  347. const auto bottom = (int) std::round ((float) (lane + 1) * laneHeight);
  348. const auto p = summary.query (from, to, lanes == 2 ? lane : -1);
  349. if (! p.valid)
  350. {
  351. for (int y = top; y < bottom; ++y)
  352. reinterpret_cast<juce::PixelARGB*> (pixels.getPixelPointer (x, y))->setARGB (0, 0, 0, 0);
  353. continue;
  354. }
  355. drewAny = true;
  356. float r, gr, b;
  357. if (style.spectral)
  358. {
  359. const auto c = wave::spectralColour (p);
  360. r = c.r;
  361. gr = c.g;
  362. b = c.b;
  363. }
  364. else
  365. {
  366. r = classic.getFloatRed();
  367. gr = classic.getFloatGreen();
  368. b = classic.getFloatBlue();
  369. }
  370. // louder = a little brighter
  371. const auto level = std::min (1.0f, p.rms * style.gain * 2.5f);
  372. const auto shade = 0.72f + 0.28f * level;
  373. const auto half = (float) (bottom - top) * 0.5f - 0.5f;
  374. const auto centre = (float) top + (float) (bottom - top) * 0.5f;
  375. const auto hi = std::clamp (p.hi * style.gain, -1.0f, 1.0f), lo = std::clamp (p.lo * style.gain, -1.0f, 1.0f);
  376. auto peakTop = centre - hi * half, peakBottom = centre - lo * half;
  377. if (peakBottom - peakTop < 1.0f) // never thinner than one pixel (the centre line)
  378. {
  379. const auto mid = (peakTop + peakBottom) * 0.5f;
  380. peakTop = mid - 0.5f;
  381. peakBottom = mid + 0.5f;
  382. }
  383. const auto rms = std::min (p.rms * style.gain, 1.0f) * half;
  384. const auto rmsTop = std::max (peakTop, centre - rms), rmsBottom = std::min (peakBottom, centre + rms);
  385. auto cover = [] (float y, float a, float b2) { return std::clamp (std::min (y + 1.0f, b2) - std::max (y, a), 0.0f, 1.0f); };
  386. for (int y = top; y < bottom; ++y)
  387. {
  388. const auto fy = (float) y;
  389. const auto hull = cover (fy, peakTop, peakBottom);
  390. auto* px = reinterpret_cast<juce::PixelARGB*> (pixels.getPixelPointer (x, y));
  391. if (hull <= 0.0f)
  392. {
  393. px->setARGB (0, 0, 0, 0);
  394. continue;
  395. }
  396. const auto body2 = rmsBottom > rmsTop ? cover (fy, rmsTop, rmsBottom) : 0.0f;
  397. const auto edge = std::min (1.0f, cover (fy, peakTop, peakTop + 1.0f) + cover (fy, peakBottom - 1.0f, peakBottom));
  398. // RMS body opaque; the peak hull translucent with a brighter one-pixel outline
  399. const auto hullAlpha = (hull - body2) * (0.42f + 0.4f * edge);
  400. const auto alpha = std::min (1.0f, body2 + hullAlpha);
  401. const auto lift = 1.0f + 0.25f * edge * (1.0f - body2); // the outline is lighter
  402. const auto k = alpha * shade;
  403. px->setARGB ((juce::uint8) std::lround (alpha * 255.0f),
  404. (juce::uint8) std::lround (std::min (alpha, r * k * lift) * 255.0f),
  405. (juce::uint8) std::lround (std::min (alpha, gr * k * lift) * 255.0f),
  406. (juce::uint8) std::lround (std::min (alpha, b * k * lift) * 255.0f));
  407. }
  408. }
  409. }
  410. }
  411. if (! drewAny)
  412. return;
  413. juce::Graphics::ScopedSaveState save (g);
  414. g.setImageResamplingQuality (juce::Graphics::lowResamplingQuality);
  415. g.drawImage (scratch, visible.getX(), body.getY(), visible.getWidth(), body.getHeight(), 0, 0, width, height);
  416. }
  417. // --- display component ---------------------------------------------------------------------------
  418. WaveformDisplay::WaveformDisplay()
  419. {
  420. setOpaque (true);
  421. WaveformCache::getInstance()->addChangeListener (this);
  422. }
  423. WaveformDisplay::~WaveformDisplay()
  424. {
  425. if (auto* cache = WaveformCache::getInstanceWithoutCreating())
  426. cache->removeChangeListener (this);
  427. }
  428. void WaveformDisplay::setFile (const juce::String& newPath, WaveformCache::Source newSource)
  429. {
  430. if (newPath == path)
  431. return;
  432. path = newPath;
  433. source = std::move (newSource);
  434. repaint();
  435. }
  436. void WaveformDisplay::setRegion (float start, float end)
  437. {
  438. if (start == regionStart && end == regionEnd)
  439. return;
  440. regionStart = start;
  441. regionEnd = end;
  442. repaint();
  443. }
  444. void WaveformDisplay::setReversed (bool r)
  445. {
  446. if (r != reversed)
  447. {
  448. reversed = r;
  449. repaint();
  450. }
  451. }
  452. void WaveformDisplay::setCaption (const juce::String& text)
  453. {
  454. caption = text;
  455. repaint();
  456. }
  457. void WaveformDisplay::setEmptyText (const juce::String& text)
  458. {
  459. emptyText = text;
  460. repaint();
  461. }
  462. void WaveformDisplay::paint (juce::Graphics& g)
  463. {
  464. using namespace theme;
  465. const auto bounds = getLocalBounds().toFloat();
  466. g.fillAll (colour::bg0);
  467. g.setColour (colour::border);
  468. g.drawRect (getLocalBounds());
  469. const auto inner = bounds.reduced (1.0f);
  470. g.setColour (colour::gridBeat);
  471. g.fillRect (inner.getX(), inner.getCentreY() - 0.5f, inner.getWidth(), 1.0f);
  472. auto& cache = *WaveformCache::getInstance();
  473. const auto summary = cache.find (path, source);
  474. g.setFont (font (type::small));
  475. if (summary == nullptr)
  476. {
  477. g.setColour (colour::textDisabled);
  478. const auto text = path.isEmpty() ? emptyText
  479. : cache.hasFailed (path) ? tr ("Could not read this audio file")
  480. : tr ("Analysing...");
  481. g.drawText (text, getLocalBounds(), juce::Justification::centred);
  482. return;
  483. }
  484. const auto frames = (double) summary->frames;
  485. const auto perPixel = frames / (double) inner.getWidth();
  486. paintWaveform (g, inner, *summary, reversed ? frames : 0.0, reversed ? -perPixel : perPixel,
  487. currentWaveStyle (colour::audioClip.brighter (0.3f), normalisingGain (*summary)));
  488. // the part outside the region is dimmed; its edges are marked in the accent colour
  489. if (regionStart > 0.0f || regionEnd < 1.0f)
  490. {
  491. const auto x0 = inner.getX() + inner.getWidth() * juce::jlimit (0.0f, 1.0f, reversed ? 1.0f - regionEnd : regionStart);
  492. const auto x1 = inner.getX() + inner.getWidth() * juce::jlimit (0.0f, 1.0f, reversed ? 1.0f - regionStart : regionEnd);
  493. g.setColour (colour::bg0.withAlpha (0.7f));
  494. g.fillRect (juce::Rectangle<float>::leftTopRightBottom (inner.getX(), inner.getY(), x0, inner.getBottom()));
  495. g.fillRect (juce::Rectangle<float>::leftTopRightBottom (x1, inner.getY(), inner.getRight(), inner.getBottom()));
  496. g.setColour (colour::accent);
  497. g.fillRect (x0 - 0.5f, inner.getY(), 1.5f, inner.getHeight());
  498. g.fillRect (x1 - 1.0f, inner.getY(), 1.5f, inner.getHeight());
  499. }
  500. // caption: the file name and its length
  501. auto text = caption;
  502. if (text.isEmpty())
  503. text = juce::File (path).getFileName() + " " + juce::String (frames / summary->sampleRate, 2) + " s"
  504. + (summary->channels > 1 ? " " + tr ("stereo") : " " + tr ("mono"));
  505. const auto band = getLocalBounds().reduced (6, 3).removeFromTop (16);
  506. g.setColour (colour::bg0.withAlpha (0.6f));
  507. g.fillRect (band.withWidth (juce::jmin (band.getWidth(), juce::roundToInt (juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), text)) + 8)));
  508. g.setColour (colour::textSecondary);
  509. g.drawText (text, band.withTrimmedLeft (4), juce::Justification::centredLeft, true);
  510. }
  511. } // namespace lynx::ui