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.

694 lines
21KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 7 technical preview.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For the technical preview this file cannot be licensed commercially.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. ImagePixelData::ImagePixelData (Image::PixelFormat format, int w, int h)
  16. : pixelFormat (format), width (w), height (h)
  17. {
  18. jassert (format == Image::RGB || format == Image::ARGB || format == Image::SingleChannel);
  19. jassert (w > 0 && h > 0); // It's illegal to create a zero-sized image!
  20. }
  21. ImagePixelData::~ImagePixelData()
  22. {
  23. listeners.call ([this] (Listener& l) { l.imageDataBeingDeleted (this); });
  24. }
  25. void ImagePixelData::sendDataChangeMessage()
  26. {
  27. listeners.call ([this] (Listener& l) { l.imageDataChanged (this); });
  28. }
  29. int ImagePixelData::getSharedCount() const noexcept
  30. {
  31. return getReferenceCount();
  32. }
  33. //==============================================================================
  34. ImageType::ImageType() {}
  35. ImageType::~ImageType() {}
  36. Image ImageType::convert (const Image& source) const
  37. {
  38. if (source.isNull() || getTypeID() == source.getPixelData()->createType()->getTypeID())
  39. return source;
  40. const Image::BitmapData src (source, Image::BitmapData::readOnly);
  41. Image newImage (create (src.pixelFormat, src.width, src.height, false));
  42. Image::BitmapData dest (newImage, Image::BitmapData::writeOnly);
  43. if (src.pixelStride == dest.pixelStride && src.pixelFormat == dest.pixelFormat)
  44. {
  45. for (int y = 0; y < dest.height; ++y)
  46. memcpy (dest.getLinePointer (y), src.getLinePointer (y), (size_t) dest.lineStride);
  47. }
  48. else
  49. {
  50. for (int y = 0; y < dest.height; ++y)
  51. for (int x = 0; x < dest.width; ++x)
  52. dest.setPixelColour (x, y, src.getPixelColour (x, y));
  53. }
  54. return newImage;
  55. }
  56. //==============================================================================
  57. class SoftwarePixelData : public ImagePixelData
  58. {
  59. public:
  60. SoftwarePixelData (Image::PixelFormat formatToUse, int w, int h, bool clearImage)
  61. : ImagePixelData (formatToUse, w, h),
  62. pixelStride (formatToUse == Image::RGB ? 3 : ((formatToUse == Image::ARGB) ? 4 : 1)),
  63. lineStride ((pixelStride * jmax (1, w) + 3) & ~3)
  64. {
  65. imageData.allocate ((size_t) lineStride * (size_t) jmax (1, h), clearImage);
  66. }
  67. std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() override
  68. {
  69. sendDataChangeMessage();
  70. return std::make_unique<LowLevelGraphicsSoftwareRenderer> (Image (*this));
  71. }
  72. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
  73. {
  74. const auto offset = (size_t) x * (size_t) pixelStride + (size_t) y * (size_t) lineStride;
  75. bitmap.data = imageData + offset;
  76. bitmap.size = (size_t) (height * lineStride) - offset;
  77. bitmap.pixelFormat = pixelFormat;
  78. bitmap.lineStride = lineStride;
  79. bitmap.pixelStride = pixelStride;
  80. if (mode != Image::BitmapData::readOnly)
  81. sendDataChangeMessage();
  82. }
  83. ImagePixelData::Ptr clone() override
  84. {
  85. auto s = new SoftwarePixelData (pixelFormat, width, height, false);
  86. memcpy (s->imageData, imageData, (size_t) lineStride * (size_t) height);
  87. return *s;
  88. }
  89. std::unique_ptr<ImageType> createType() const override { return std::make_unique<SoftwareImageType>(); }
  90. private:
  91. HeapBlock<uint8> imageData;
  92. const int pixelStride, lineStride;
  93. JUCE_LEAK_DETECTOR (SoftwarePixelData)
  94. };
  95. SoftwareImageType::SoftwareImageType() {}
  96. SoftwareImageType::~SoftwareImageType() {}
  97. ImagePixelData::Ptr SoftwareImageType::create (Image::PixelFormat format, int width, int height, bool clearImage) const
  98. {
  99. return *new SoftwarePixelData (format, width, height, clearImage);
  100. }
  101. int SoftwareImageType::getTypeID() const
  102. {
  103. return 2;
  104. }
  105. //==============================================================================
  106. NativeImageType::NativeImageType() {}
  107. NativeImageType::~NativeImageType() {}
  108. int NativeImageType::getTypeID() const
  109. {
  110. return 1;
  111. }
  112. #if JUCE_WINDOWS || JUCE_LINUX || JUCE_BSD
  113. ImagePixelData::Ptr NativeImageType::create (Image::PixelFormat format, int width, int height, bool clearImage) const
  114. {
  115. return new SoftwarePixelData (format, width, height, clearImage);
  116. }
  117. #endif
  118. //==============================================================================
  119. class SubsectionPixelData : public ImagePixelData
  120. {
  121. public:
  122. SubsectionPixelData (ImagePixelData::Ptr source, Rectangle<int> r)
  123. : ImagePixelData (source->pixelFormat, r.getWidth(), r.getHeight()),
  124. sourceImage (std::move (source)), area (r)
  125. {
  126. }
  127. std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() override
  128. {
  129. auto g = sourceImage->createLowLevelContext();
  130. g->clipToRectangle (area);
  131. g->setOrigin (area.getPosition());
  132. return g;
  133. }
  134. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
  135. {
  136. sourceImage->initialiseBitmapData (bitmap, x + area.getX(), y + area.getY(), mode);
  137. if (mode != Image::BitmapData::readOnly)
  138. sendDataChangeMessage();
  139. }
  140. ImagePixelData::Ptr clone() override
  141. {
  142. jassert (getReferenceCount() > 0); // (This method can't be used on an unowned pointer, as it will end up self-deleting)
  143. auto type = createType();
  144. Image newImage (type->create (pixelFormat, area.getWidth(), area.getHeight(), pixelFormat != Image::RGB));
  145. {
  146. Graphics g (newImage);
  147. g.drawImageAt (Image (*this), 0, 0);
  148. }
  149. return *newImage.getPixelData();
  150. }
  151. std::unique_ptr<ImageType> createType() const override { return sourceImage->createType(); }
  152. /* as we always hold a reference to image, don't double count */
  153. int getSharedCount() const noexcept override { return getReferenceCount() + sourceImage->getSharedCount() - 1; }
  154. private:
  155. friend class Image;
  156. const ImagePixelData::Ptr sourceImage;
  157. const Rectangle<int> area;
  158. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionPixelData)
  159. };
  160. Image Image::getClippedImage (const Rectangle<int>& area) const
  161. {
  162. if (area.contains (getBounds()))
  163. return *this;
  164. auto validArea = area.getIntersection (getBounds());
  165. if (validArea.isEmpty())
  166. return {};
  167. return Image (*new SubsectionPixelData (image, validArea));
  168. }
  169. //==============================================================================
  170. Image::Image() noexcept
  171. {
  172. }
  173. Image::Image (ReferenceCountedObjectPtr<ImagePixelData> instance) noexcept
  174. : image (std::move (instance))
  175. {
  176. }
  177. Image::Image (PixelFormat format, int width, int height, bool clearImage)
  178. : image (NativeImageType().create (format, width, height, clearImage))
  179. {
  180. }
  181. Image::Image (PixelFormat format, int width, int height, bool clearImage, const ImageType& type)
  182. : image (type.create (format, width, height, clearImage))
  183. {
  184. }
  185. Image::Image (const Image& other) noexcept
  186. : image (other.image)
  187. {
  188. }
  189. Image& Image::operator= (const Image& other)
  190. {
  191. image = other.image;
  192. return *this;
  193. }
  194. Image::Image (Image&& other) noexcept
  195. : image (std::move (other.image))
  196. {
  197. }
  198. Image& Image::operator= (Image&& other) noexcept
  199. {
  200. image = std::move (other.image);
  201. return *this;
  202. }
  203. Image::~Image()
  204. {
  205. }
  206. int Image::getReferenceCount() const noexcept { return image == nullptr ? 0 : image->getSharedCount(); }
  207. int Image::getWidth() const noexcept { return image == nullptr ? 0 : image->width; }
  208. int Image::getHeight() const noexcept { return image == nullptr ? 0 : image->height; }
  209. Rectangle<int> Image::getBounds() const noexcept { return image == nullptr ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  210. Image::PixelFormat Image::getFormat() const noexcept { return image == nullptr ? UnknownFormat : image->pixelFormat; }
  211. bool Image::isARGB() const noexcept { return getFormat() == ARGB; }
  212. bool Image::isRGB() const noexcept { return getFormat() == RGB; }
  213. bool Image::isSingleChannel() const noexcept { return getFormat() == SingleChannel; }
  214. bool Image::hasAlphaChannel() const noexcept { return getFormat() != RGB; }
  215. std::unique_ptr<LowLevelGraphicsContext> Image::createLowLevelContext() const
  216. {
  217. if (image != nullptr)
  218. return image->createLowLevelContext();
  219. return {};
  220. }
  221. void Image::duplicateIfShared()
  222. {
  223. if (getReferenceCount() > 1)
  224. image = image->clone();
  225. }
  226. Image Image::createCopy() const
  227. {
  228. if (image != nullptr)
  229. return Image (image->clone());
  230. return {};
  231. }
  232. Image Image::rescaled (int newWidth, int newHeight, Graphics::ResamplingQuality quality) const
  233. {
  234. if (image == nullptr || (image->width == newWidth && image->height == newHeight))
  235. return *this;
  236. auto type = image->createType();
  237. Image newImage (type->create (image->pixelFormat, newWidth, newHeight, hasAlphaChannel()));
  238. Graphics g (newImage);
  239. g.setImageResamplingQuality (quality);
  240. g.drawImageTransformed (*this, AffineTransform::scale ((float) newWidth / (float) image->width,
  241. (float) newHeight / (float) image->height), false);
  242. return newImage;
  243. }
  244. Image Image::convertedToFormat (PixelFormat newFormat) const
  245. {
  246. if (image == nullptr || newFormat == image->pixelFormat)
  247. return *this;
  248. auto w = image->width, h = image->height;
  249. auto type = image->createType();
  250. Image newImage (type->create (newFormat, w, h, false));
  251. if (newFormat == SingleChannel)
  252. {
  253. if (! hasAlphaChannel())
  254. {
  255. newImage.clear (getBounds(), Colours::black);
  256. }
  257. else
  258. {
  259. const BitmapData destData (newImage, 0, 0, w, h, BitmapData::writeOnly);
  260. const BitmapData srcData (*this, 0, 0, w, h);
  261. for (int y = 0; y < h; ++y)
  262. {
  263. auto src = reinterpret_cast<const PixelARGB*> (srcData.getLinePointer (y));
  264. auto dst = destData.getLinePointer (y);
  265. for (int x = 0; x < w; ++x)
  266. dst[x] = src[x].getAlpha();
  267. }
  268. }
  269. }
  270. else if (image->pixelFormat == SingleChannel && newFormat == Image::ARGB)
  271. {
  272. const BitmapData destData (newImage, 0, 0, w, h, BitmapData::writeOnly);
  273. const BitmapData srcData (*this, 0, 0, w, h);
  274. for (int y = 0; y < h; ++y)
  275. {
  276. auto src = reinterpret_cast<const PixelAlpha*> (srcData.getLinePointer (y));
  277. auto dst = reinterpret_cast<PixelARGB*> (destData.getLinePointer (y));
  278. for (int x = 0; x < w; ++x)
  279. dst[x].set (src[x]);
  280. }
  281. }
  282. else
  283. {
  284. if (hasAlphaChannel())
  285. newImage.clear (getBounds());
  286. Graphics g (newImage);
  287. g.drawImageAt (*this, 0, 0);
  288. }
  289. return newImage;
  290. }
  291. NamedValueSet* Image::getProperties() const
  292. {
  293. return image == nullptr ? nullptr : &(image->userData);
  294. }
  295. //==============================================================================
  296. Image::BitmapData::BitmapData (Image& im, int x, int y, int w, int h, BitmapData::ReadWriteMode mode)
  297. : width (w), height (h)
  298. {
  299. // The BitmapData class must be given a valid image, and a valid rectangle within it!
  300. jassert (im.image != nullptr);
  301. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= im.getWidth() && y + h <= im.getHeight());
  302. im.image->initialiseBitmapData (*this, x, y, mode);
  303. jassert (data != nullptr && pixelStride > 0 && lineStride != 0);
  304. }
  305. Image::BitmapData::BitmapData (const Image& im, int x, int y, int w, int h)
  306. : width (w), height (h)
  307. {
  308. // The BitmapData class must be given a valid image, and a valid rectangle within it!
  309. jassert (im.image != nullptr);
  310. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= im.getWidth() && y + h <= im.getHeight());
  311. im.image->initialiseBitmapData (*this, x, y, readOnly);
  312. jassert (data != nullptr && pixelStride > 0 && lineStride != 0);
  313. }
  314. Image::BitmapData::BitmapData (const Image& im, BitmapData::ReadWriteMode mode)
  315. : width (im.getWidth()),
  316. height (im.getHeight())
  317. {
  318. // The BitmapData class must be given a valid image!
  319. jassert (im.image != nullptr);
  320. im.image->initialiseBitmapData (*this, 0, 0, mode);
  321. jassert (data != nullptr && pixelStride > 0 && lineStride != 0);
  322. }
  323. Image::BitmapData::~BitmapData()
  324. {
  325. }
  326. Colour Image::BitmapData::getPixelColour (int x, int y) const noexcept
  327. {
  328. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  329. auto pixel = getPixelPointer (x, y);
  330. switch (pixelFormat)
  331. {
  332. case Image::ARGB: return Colour ( ((const PixelARGB*) pixel)->getUnpremultiplied());
  333. case Image::RGB: return Colour (*((const PixelRGB*) pixel));
  334. case Image::SingleChannel: return Colour (*((const PixelAlpha*) pixel));
  335. case Image::UnknownFormat:
  336. default: jassertfalse; break;
  337. }
  338. return {};
  339. }
  340. void Image::BitmapData::setPixelColour (int x, int y, Colour colour) const noexcept
  341. {
  342. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  343. auto pixel = getPixelPointer (x, y);
  344. auto col = colour.getPixelARGB();
  345. switch (pixelFormat)
  346. {
  347. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  348. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  349. case Image::SingleChannel: ((PixelAlpha*) pixel)->set (col); break;
  350. case Image::UnknownFormat:
  351. default: jassertfalse; break;
  352. }
  353. }
  354. //==============================================================================
  355. void Image::clear (const Rectangle<int>& area, Colour colourToClearTo)
  356. {
  357. if (image != nullptr)
  358. {
  359. auto g = image->createLowLevelContext();
  360. g->setFill (colourToClearTo);
  361. g->fillRect (area, true);
  362. }
  363. }
  364. //==============================================================================
  365. Colour Image::getPixelAt (int x, int y) const
  366. {
  367. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  368. {
  369. const BitmapData srcData (*this, x, y, 1, 1);
  370. return srcData.getPixelColour (0, 0);
  371. }
  372. return {};
  373. }
  374. void Image::setPixelAt (int x, int y, Colour colour)
  375. {
  376. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  377. {
  378. const BitmapData destData (*this, x, y, 1, 1, BitmapData::writeOnly);
  379. destData.setPixelColour (0, 0, colour);
  380. }
  381. }
  382. void Image::multiplyAlphaAt (int x, int y, float multiplier)
  383. {
  384. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  385. && hasAlphaChannel())
  386. {
  387. const BitmapData destData (*this, x, y, 1, 1, BitmapData::readWrite);
  388. if (isARGB())
  389. reinterpret_cast<PixelARGB*> (destData.data)->multiplyAlpha (multiplier);
  390. else
  391. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  392. }
  393. }
  394. template <class PixelType>
  395. struct PixelIterator
  396. {
  397. template <class PixelOperation>
  398. static void iterate (const Image::BitmapData& data, const PixelOperation& pixelOp)
  399. {
  400. for (int y = 0; y < data.height; ++y)
  401. {
  402. auto p = data.getLinePointer (y);
  403. for (int x = 0; x < data.width; ++x)
  404. {
  405. pixelOp (*reinterpret_cast<PixelType*> (p));
  406. p += data.pixelStride;
  407. }
  408. }
  409. }
  410. };
  411. template <class PixelOperation>
  412. static void performPixelOp (const Image::BitmapData& data, const PixelOperation& pixelOp)
  413. {
  414. switch (data.pixelFormat)
  415. {
  416. case Image::ARGB: PixelIterator<PixelARGB> ::iterate (data, pixelOp); break;
  417. case Image::RGB: PixelIterator<PixelRGB> ::iterate (data, pixelOp); break;
  418. case Image::SingleChannel: PixelIterator<PixelAlpha>::iterate (data, pixelOp); break;
  419. case Image::UnknownFormat:
  420. default: jassertfalse; break;
  421. }
  422. }
  423. struct AlphaMultiplyOp
  424. {
  425. float alpha;
  426. template <class PixelType>
  427. void operator() (PixelType& pixel) const
  428. {
  429. pixel.multiplyAlpha (alpha);
  430. }
  431. };
  432. void Image::multiplyAllAlphas (float amountToMultiplyBy)
  433. {
  434. jassert (hasAlphaChannel());
  435. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), BitmapData::readWrite);
  436. performPixelOp (destData, AlphaMultiplyOp { amountToMultiplyBy });
  437. }
  438. struct DesaturateOp
  439. {
  440. template <class PixelType>
  441. void operator() (PixelType& pixel) const
  442. {
  443. pixel.desaturate();
  444. }
  445. };
  446. void Image::desaturate()
  447. {
  448. if (isARGB() || isRGB())
  449. {
  450. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), BitmapData::readWrite);
  451. performPixelOp (destData, DesaturateOp());
  452. }
  453. }
  454. void Image::createSolidAreaMask (RectangleList<int>& result, float alphaThreshold) const
  455. {
  456. if (hasAlphaChannel())
  457. {
  458. auto threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  459. SparseSet<int> pixelsOnRow;
  460. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  461. for (int y = 0; y < srcData.height; ++y)
  462. {
  463. pixelsOnRow.clear();
  464. auto lineData = srcData.getLinePointer (y);
  465. if (isARGB())
  466. {
  467. for (int x = 0; x < srcData.width; ++x)
  468. {
  469. if (reinterpret_cast<const PixelARGB*> (lineData)->getAlpha() >= threshold)
  470. pixelsOnRow.addRange (Range<int> (x, x + 1));
  471. lineData += srcData.pixelStride;
  472. }
  473. }
  474. else
  475. {
  476. for (int x = 0; x < srcData.width; ++x)
  477. {
  478. if (*lineData >= threshold)
  479. pixelsOnRow.addRange (Range<int> (x, x + 1));
  480. lineData += srcData.pixelStride;
  481. }
  482. }
  483. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  484. {
  485. auto range = pixelsOnRow.getRange (i);
  486. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  487. }
  488. result.consolidate();
  489. }
  490. }
  491. else
  492. {
  493. result.add (0, 0, getWidth(), getHeight());
  494. }
  495. }
  496. void Image::moveImageSection (int dx, int dy,
  497. int sx, int sy,
  498. int w, int h)
  499. {
  500. if (dx < 0)
  501. {
  502. w += dx;
  503. sx -= dx;
  504. dx = 0;
  505. }
  506. if (dy < 0)
  507. {
  508. h += dy;
  509. sy -= dy;
  510. dy = 0;
  511. }
  512. if (sx < 0)
  513. {
  514. w += sx;
  515. dx -= sx;
  516. sx = 0;
  517. }
  518. if (sy < 0)
  519. {
  520. h += sy;
  521. dy -= sy;
  522. sy = 0;
  523. }
  524. const int minX = jmin (dx, sx);
  525. const int minY = jmin (dy, sy);
  526. w = jmin (w, getWidth() - jmax (sx, dx));
  527. h = jmin (h, getHeight() - jmax (sy, dy));
  528. if (w > 0 && h > 0)
  529. {
  530. auto maxX = jmax (dx, sx) + w;
  531. auto maxY = jmax (dy, sy) + h;
  532. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, BitmapData::readWrite);
  533. auto dst = destData.getPixelPointer (dx - minX, dy - minY);
  534. auto src = destData.getPixelPointer (sx - minX, sy - minY);
  535. auto lineSize = (size_t) destData.pixelStride * (size_t) w;
  536. if (dy > sy)
  537. {
  538. while (--h >= 0)
  539. {
  540. const int offset = h * destData.lineStride;
  541. memmove (dst + offset, src + offset, lineSize);
  542. }
  543. }
  544. else if (dst != src)
  545. {
  546. while (--h >= 0)
  547. {
  548. memmove (dst, src, lineSize);
  549. dst += destData.lineStride;
  550. src += destData.lineStride;
  551. }
  552. }
  553. }
  554. }
  555. //==============================================================================
  556. #if JUCE_ALLOW_STATIC_NULL_VARIABLES
  557. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  558. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4996)
  559. const Image Image::null;
  560. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  561. JUCE_END_IGNORE_WARNINGS_MSVC
  562. #endif
  563. } // namespace juce