SurfacePipe.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. /**
  6. * A SurfacePipe is a pipeline that consists of a series of SurfaceFilters
  7. * terminating in a SurfaceSink. Each SurfaceFilter transforms the image data in
  8. * some way before the SurfaceSink ultimately writes it to the surface. This
  9. * design allows for each transformation to be tested independently, for the
  10. * transformations to be combined as needed to meet the needs of different
  11. * situations, and for all image decoders to share the same code for these
  12. * transformations.
  13. *
  14. * Writing to the SurfacePipe is done using lambdas that act as generator
  15. * functions. Because the SurfacePipe machinery controls where the writes take
  16. * place, a bug in an image decoder cannot cause a buffer overflow of the
  17. * underlying surface.
  18. */
  19. #ifndef mozilla_image_SurfacePipe_h
  20. #define mozilla_image_SurfacePipe_h
  21. #include <stdint.h>
  22. #include "nsDebug.h"
  23. #include "mozilla/Likely.h"
  24. #include "mozilla/Maybe.h"
  25. #include "mozilla/Move.h"
  26. #include "mozilla/UniquePtr.h"
  27. #include "mozilla/Unused.h"
  28. #include "mozilla/Variant.h"
  29. #include "mozilla/gfx/2D.h"
  30. #include "AnimationParams.h"
  31. namespace mozilla {
  32. namespace image {
  33. class Decoder;
  34. /**
  35. * An invalid rect for a surface. Results are given both in the space of the
  36. * input image (i.e., before any SurfaceFilters are applied) and in the space
  37. * of the output surface (after all SurfaceFilters).
  38. */
  39. struct SurfaceInvalidRect
  40. {
  41. gfx::IntRect mInputSpaceRect; /// The invalid rect in pre-SurfacePipe space.
  42. gfx::IntRect mOutputSpaceRect; /// The invalid rect in post-SurfacePipe space.
  43. };
  44. /**
  45. * An enum used to allow the lambdas passed to WritePixels() to communicate
  46. * their state to the caller.
  47. */
  48. enum class WriteState : uint8_t
  49. {
  50. NEED_MORE_DATA, /// The lambda ran out of data.
  51. FINISHED, /// The lambda is done writing to the surface; future writes
  52. /// will fail.
  53. FAILURE /// The lambda encountered an error. The caller may recover
  54. /// if possible and continue to write. (This never indicates
  55. /// an error in the SurfacePipe machinery itself; it's only
  56. /// generated by the lambdas.)
  57. };
  58. /**
  59. * A template alias used to make the return value of WritePixels() lambdas
  60. * (which may return either a pixel value or a WriteState) easier to specify.
  61. */
  62. template <typename PixelType>
  63. using NextPixel = Variant<PixelType, WriteState>;
  64. /**
  65. * SurfaceFilter is the abstract superclass of SurfacePipe pipeline stages. It
  66. * implements the the code that actually writes to the surface - WritePixels()
  67. * and the other Write*() methods - which are non-virtual for efficiency.
  68. *
  69. * SurfaceFilter's API is nonpublic; only SurfacePipe and other SurfaceFilters
  70. * should use it. Non-SurfacePipe code should use the methods on SurfacePipe.
  71. *
  72. * To implement a SurfaceFilter, it's necessary to subclass SurfaceFilter and
  73. * implement, at a minimum, the pure virtual methods. It's also necessary to
  74. * define a Config struct with a Filter typedef member that identifies the
  75. * matching SurfaceFilter class, and a Configure() template method. See an
  76. * existing SurfaceFilter subclass, such as RemoveFrameRectFilter, for an
  77. * example of how the Configure() method must be implemented. It takes a list of
  78. * Config structs, passes the tail of the list to the next filter in the chain's
  79. * Configure() method, and then uses the head of the list to configure itself. A
  80. * SurfaceFilter's Configure() method must also call
  81. * SurfaceFilter::ConfigureFilter() to provide the Write*() methods with the
  82. * information they need to do their jobs.
  83. */
  84. class SurfaceFilter
  85. {
  86. public:
  87. SurfaceFilter()
  88. : mRowPointer(nullptr)
  89. , mCol(0)
  90. , mPixelSize(0)
  91. { }
  92. virtual ~SurfaceFilter() { }
  93. /**
  94. * Reset this surface to the first row. It's legal for this filter to throw
  95. * away any previously written data at this point, as all rows must be written
  96. * to on every pass.
  97. *
  98. * @return a pointer to the buffer for the first row.
  99. */
  100. uint8_t* ResetToFirstRow()
  101. {
  102. mCol = 0;
  103. mRowPointer = DoResetToFirstRow();
  104. return mRowPointer;
  105. }
  106. /**
  107. * Called by WritePixels() to advance this filter to the next row.
  108. *
  109. * @return a pointer to the buffer for the next row, or nullptr to indicate
  110. * that we've finished the entire surface.
  111. */
  112. uint8_t* AdvanceRow()
  113. {
  114. mCol = 0;
  115. mRowPointer = DoAdvanceRow();
  116. return mRowPointer;
  117. }
  118. /// @return a pointer to the buffer for the current row.
  119. uint8_t* CurrentRowPointer() const { return mRowPointer; }
  120. /// @return true if we've finished writing to the surface.
  121. bool IsSurfaceFinished() const { return mRowPointer == nullptr; }
  122. /// @return the input size this filter expects.
  123. gfx::IntSize InputSize() const { return mInputSize; }
  124. /**
  125. * Write pixels to the surface one at a time by repeatedly calling a lambda
  126. * that yields pixels. WritePixels() is completely memory safe.
  127. *
  128. * Writing continues until every pixel in the surface has been written to
  129. * (i.e., IsSurfaceFinished() returns true) or the lambda returns a WriteState
  130. * which WritePixels() will return to the caller.
  131. *
  132. * The template parameter PixelType must be uint8_t (for paletted surfaces) or
  133. * uint32_t (for BGRA/BGRX surfaces) and must be in agreement with the pixel
  134. * size passed to ConfigureFilter().
  135. *
  136. * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
  137. * which means we can remove the PixelType template parameter from this
  138. * method.
  139. *
  140. * @param aFunc A lambda that functions as a generator, yielding the next
  141. * pixel in the surface each time it's called. The lambda must
  142. * return a NextPixel<PixelType> value.
  143. *
  144. * @return A WriteState value indicating the lambda generator's state.
  145. * WritePixels() itself will return WriteState::FINISHED if writing
  146. * has finished, regardless of the lambda's internal state.
  147. */
  148. template <typename PixelType, typename Func>
  149. WriteState WritePixels(Func aFunc)
  150. {
  151. Maybe<WriteState> result;
  152. while (!(result = DoWritePixelsToRow<PixelType>(Forward<Func>(aFunc)))) { }
  153. return *result;
  154. }
  155. /**
  156. * A variant of WritePixels() that writes a single row of pixels to the
  157. * surface one at a time by repeatedly calling a lambda that yields pixels.
  158. * WritePixelsToRow() is completely memory safe.
  159. *
  160. * Writing continues until every pixel in the row has been written to. If the
  161. * surface is complete at that pointer, WriteState::FINISHED is returned;
  162. * otherwise, WritePixelsToRow() returns WriteState::NEED_MORE_DATA. The
  163. * lambda can terminate writing early by returning a WriteState itself, which
  164. * WritePixelsToRow() will return to the caller.
  165. *
  166. * The template parameter PixelType must be uint8_t (for paletted surfaces) or
  167. * uint32_t (for BGRA/BGRX surfaces) and must be in agreement with the pixel
  168. * size passed to ConfigureFilter().
  169. *
  170. * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
  171. * which means we can remove the PixelType template parameter from this
  172. * method.
  173. *
  174. * @param aFunc A lambda that functions as a generator, yielding the next
  175. * pixel in the surface each time it's called. The lambda must
  176. * return a NextPixel<PixelType> value.
  177. *
  178. * @return A WriteState value indicating the lambda generator's state.
  179. * WritePixels() itself will return WriteState::FINISHED if writing
  180. * the entire surface has finished, or WriteState::NEED_MORE_DATA if
  181. * writing the row has finished, regardless of the lambda's internal
  182. * state.
  183. */
  184. template <typename PixelType, typename Func>
  185. WriteState WritePixelsToRow(Func aFunc)
  186. {
  187. return DoWritePixelsToRow<PixelType>(Forward<Func>(aFunc))
  188. .valueOr(WriteState::NEED_MORE_DATA);
  189. }
  190. /**
  191. * Write a row to the surface by copying from a buffer. This is bounds checked
  192. * and memory safe with respect to the surface, but care must still be taken
  193. * by the caller not to overread the source buffer. This variant of
  194. * WriteBuffer() requires a source buffer which contains |mInputSize.width|
  195. * pixels.
  196. *
  197. * The template parameter PixelType must be uint8_t (for paletted surfaces) or
  198. * uint32_t (for BGRA/BGRX surfaces) and must be in agreement with the pixel
  199. * size passed to ConfigureFilter().
  200. *
  201. * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
  202. * which means we can remove the PixelType template parameter from this
  203. * method.
  204. *
  205. * @param aSource A buffer to copy from. This buffer must be
  206. * |mInputSize.width| pixels wide, which means
  207. * |mInputSize.width * sizeof(PixelType)| bytes. May not be
  208. * null.
  209. *
  210. * @return WriteState::FINISHED if the entire surface has been written to.
  211. * Otherwise, returns WriteState::NEED_MORE_DATA. If a null |aSource|
  212. * value is passed, returns WriteState::FAILURE.
  213. */
  214. template <typename PixelType>
  215. WriteState WriteBuffer(const PixelType* aSource)
  216. {
  217. return WriteBuffer(aSource, 0, mInputSize.width);
  218. }
  219. /**
  220. * Write a row to the surface by copying from a buffer. This is bounds checked
  221. * and memory safe with respect to the surface, but care must still be taken
  222. * by the caller not to overread the source buffer. This variant of
  223. * WriteBuffer() reads at most @aLength pixels from the buffer and writes them
  224. * to the row starting at @aStartColumn. Any pixels in columns before
  225. * @aStartColumn or after the pixels copied from the buffer are cleared.
  226. *
  227. * Bounds checking failures produce warnings in debug builds because although
  228. * the bounds checking maintains safety, this kind of failure could indicate a
  229. * bug in the calling code.
  230. *
  231. * The template parameter PixelType must be uint8_t (for paletted surfaces) or
  232. * uint32_t (for BGRA/BGRX surfaces) and must be in agreement with the pixel
  233. * size passed to ConfigureFilter().
  234. *
  235. * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
  236. * which means we can remove the PixelType template parameter from this
  237. * method.
  238. *
  239. * @param aSource A buffer to copy from. This buffer must be @aLength pixels
  240. * wide, which means |aLength * sizeof(PixelType)| bytes. May
  241. * not be null.
  242. * @param aStartColumn The column to start writing to in the row. Columns
  243. * before this are cleared.
  244. * @param aLength The number of bytes, at most, which may be copied from
  245. * @aSource. Fewer bytes may be copied in practice due to
  246. * bounds checking.
  247. *
  248. * @return WriteState::FINISHED if the entire surface has been written to.
  249. * Otherwise, returns WriteState::NEED_MORE_DATA. If a null |aSource|
  250. * value is passed, returns WriteState::FAILURE.
  251. */
  252. template <typename PixelType>
  253. WriteState WriteBuffer(const PixelType* aSource,
  254. const size_t aStartColumn,
  255. const size_t aLength)
  256. {
  257. MOZ_ASSERT(mPixelSize == 1 || mPixelSize == 4);
  258. MOZ_ASSERT_IF(mPixelSize == 1, sizeof(PixelType) == sizeof(uint8_t));
  259. MOZ_ASSERT_IF(mPixelSize == 4, sizeof(PixelType) == sizeof(uint32_t));
  260. if (IsSurfaceFinished()) {
  261. return WriteState::FINISHED; // Already done.
  262. }
  263. if (MOZ_UNLIKELY(!aSource)) {
  264. NS_WARNING("Passed a null pointer to WriteBuffer");
  265. return WriteState::FAILURE;
  266. }
  267. PixelType* dest = reinterpret_cast<PixelType*>(mRowPointer);
  268. // Clear the area before |aStartColumn|.
  269. const size_t prefixLength = std::min<size_t>(mInputSize.width, aStartColumn);
  270. if (MOZ_UNLIKELY(prefixLength != aStartColumn)) {
  271. NS_WARNING("Provided starting column is out-of-bounds in WriteBuffer");
  272. }
  273. memset(dest, 0, mInputSize.width * sizeof(PixelType));
  274. dest += prefixLength;
  275. // Write |aLength| pixels from |aSource| into the row, with bounds checking.
  276. const size_t bufferLength =
  277. std::min<size_t>(mInputSize.width - prefixLength, aLength);
  278. if (MOZ_UNLIKELY(bufferLength != aLength)) {
  279. NS_WARNING("Provided buffer length is out-of-bounds in WriteBuffer");
  280. }
  281. memcpy(dest, aSource, bufferLength * sizeof(PixelType));
  282. dest += bufferLength;
  283. // Clear the rest of the row.
  284. const size_t suffixLength = mInputSize.width - (prefixLength + bufferLength);
  285. memset(dest, 0, suffixLength * sizeof(PixelType));
  286. AdvanceRow();
  287. return IsSurfaceFinished() ? WriteState::FINISHED
  288. : WriteState::NEED_MORE_DATA;
  289. }
  290. /**
  291. * Write an empty row to the surface. If some pixels have already been written
  292. * to this row, they'll be discarded.
  293. *
  294. * @return WriteState::FINISHED if the entire surface has been written to.
  295. * Otherwise, returns WriteState::NEED_MORE_DATA.
  296. */
  297. WriteState WriteEmptyRow()
  298. {
  299. if (IsSurfaceFinished()) {
  300. return WriteState::FINISHED; // Already done.
  301. }
  302. memset(mRowPointer, 0, mInputSize.width * mPixelSize);
  303. AdvanceRow();
  304. return IsSurfaceFinished() ? WriteState::FINISHED
  305. : WriteState::NEED_MORE_DATA;
  306. }
  307. /**
  308. * Write a row to the surface by calling a lambda that uses a pointer to
  309. * directly write to the row. This is unsafe because SurfaceFilter can't
  310. * provide any bounds checking; that's up to the lambda itself. For this
  311. * reason, the other Write*() methods should be preferred whenever it's
  312. * possible to use them; WriteUnsafeComputedRow() should be used only when
  313. * it's absolutely necessary to avoid extra copies or other performance
  314. * penalties.
  315. *
  316. * This method should never be exposed to SurfacePipe consumers; it's strictly
  317. * for use in SurfaceFilters. If external code needs this method, it should
  318. * probably be turned into a SurfaceFilter.
  319. *
  320. * The template parameter PixelType must be uint8_t (for paletted surfaces) or
  321. * uint32_t (for BGRA/BGRX surfaces) and must be in agreement with the pixel
  322. * size passed to ConfigureFilter().
  323. *
  324. * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
  325. * which means we can remove the PixelType template parameter from this
  326. * method.
  327. *
  328. * @param aFunc A lambda that writes directly to the row.
  329. *
  330. * @return WriteState::FINISHED if the entire surface has been written to.
  331. * Otherwise, returns WriteState::NEED_MORE_DATA.
  332. */
  333. template <typename PixelType, typename Func>
  334. WriteState WriteUnsafeComputedRow(Func aFunc)
  335. {
  336. MOZ_ASSERT(mPixelSize == 1 || mPixelSize == 4);
  337. MOZ_ASSERT_IF(mPixelSize == 1, sizeof(PixelType) == sizeof(uint8_t));
  338. MOZ_ASSERT_IF(mPixelSize == 4, sizeof(PixelType) == sizeof(uint32_t));
  339. if (IsSurfaceFinished()) {
  340. return WriteState::FINISHED; // Already done.
  341. }
  342. // Call the provided lambda with a pointer to the buffer for the current
  343. // row. This is unsafe because we can't do any bounds checking; the lambda
  344. // itself has to be responsible for that.
  345. PixelType* rowPtr = reinterpret_cast<PixelType*>(mRowPointer);
  346. aFunc(rowPtr, mInputSize.width);
  347. AdvanceRow();
  348. return IsSurfaceFinished() ? WriteState::FINISHED
  349. : WriteState::NEED_MORE_DATA;
  350. }
  351. //////////////////////////////////////////////////////////////////////////////
  352. // Methods Subclasses Should Override
  353. //////////////////////////////////////////////////////////////////////////////
  354. /// @return true if this SurfaceFilter can be used with paletted surfaces.
  355. virtual bool IsValidPalettedPipe() const { return false; }
  356. /**
  357. * @return a SurfaceInvalidRect representing the region of the surface that
  358. * has been written to since the last time TakeInvalidRect() was
  359. * called, or Nothing() if the region is empty (i.e. nothing has been
  360. * written).
  361. */
  362. virtual Maybe<SurfaceInvalidRect> TakeInvalidRect() = 0;
  363. protected:
  364. /**
  365. * Called by ResetToFirstRow() to actually perform the reset. It's legal to
  366. * throw away any previously written data at this point, as all rows must be
  367. * written to on every pass.
  368. */
  369. virtual uint8_t* DoResetToFirstRow() = 0;
  370. /**
  371. * Called by AdvanceRow() to actually advance this filter to the next row.
  372. *
  373. * @return a pointer to the buffer for the next row, or nullptr to indicate
  374. * that we've finished the entire surface.
  375. */
  376. virtual uint8_t* DoAdvanceRow() = 0;
  377. //////////////////////////////////////////////////////////////////////////////
  378. // Methods For Internal Use By Subclasses
  379. //////////////////////////////////////////////////////////////////////////////
  380. /**
  381. * Called by subclasses' Configure() methods to initialize the configuration
  382. * of this filter. After the filter is configured, calls ResetToFirstRow().
  383. *
  384. * @param aInputSize The input size of this filter, in pixels. The previous
  385. * filter in the chain will expect to write into rows
  386. * |aInputSize.width| pixels wide.
  387. * @param aPixelSize How large, in bytes, each pixel in the surface is. This
  388. * should be either 1 for paletted images or 4 for BGRA/BGRX
  389. * images.
  390. */
  391. void ConfigureFilter(gfx::IntSize aInputSize, uint8_t aPixelSize)
  392. {
  393. mInputSize = aInputSize;
  394. mPixelSize = aPixelSize;
  395. ResetToFirstRow();
  396. }
  397. private:
  398. /**
  399. * An internal method used to implement both WritePixels() and
  400. * WritePixelsToRow(). Those methods differ only in their behavior after a row
  401. * is successfully written - WritePixels() continues to write another row,
  402. * while WritePixelsToRow() returns to the caller. This method writes a single
  403. * row and returns Some() if we either finished the entire surface or the
  404. * lambda returned a WriteState indicating that we should return to the
  405. * caller. If the row was successfully written without either of those things
  406. * happening, it returns Nothing(), allowing WritePixels() and
  407. * WritePixelsToRow() to implement their respective behaviors.
  408. */
  409. template <typename PixelType, typename Func>
  410. Maybe<WriteState> DoWritePixelsToRow(Func aFunc)
  411. {
  412. MOZ_ASSERT(mPixelSize == 1 || mPixelSize == 4);
  413. MOZ_ASSERT_IF(mPixelSize == 1, sizeof(PixelType) == sizeof(uint8_t));
  414. MOZ_ASSERT_IF(mPixelSize == 4, sizeof(PixelType) == sizeof(uint32_t));
  415. if (IsSurfaceFinished()) {
  416. return Some(WriteState::FINISHED); // We're already done.
  417. }
  418. PixelType* rowPtr = reinterpret_cast<PixelType*>(mRowPointer);
  419. for (; mCol < mInputSize.width; ++mCol) {
  420. NextPixel<PixelType> result = aFunc();
  421. if (result.template is<PixelType>()) {
  422. rowPtr[mCol] = result.template as<PixelType>();
  423. continue;
  424. }
  425. switch (result.template as<WriteState>()) {
  426. case WriteState::NEED_MORE_DATA:
  427. return Some(WriteState::NEED_MORE_DATA);
  428. case WriteState::FINISHED:
  429. ZeroOutRestOfSurface<PixelType>();
  430. return Some(WriteState::FINISHED);
  431. case WriteState::FAILURE:
  432. // Note that we don't need to record this anywhere, because this
  433. // indicates an error in aFunc, and there's nothing wrong with our
  434. // machinery. The caller can recover as needed and continue writing to
  435. // the row.
  436. return Some(WriteState::FAILURE);
  437. }
  438. }
  439. AdvanceRow(); // We've finished the row.
  440. return IsSurfaceFinished() ? Some(WriteState::FINISHED)
  441. : Nothing();
  442. }
  443. template <typename PixelType>
  444. void ZeroOutRestOfSurface()
  445. {
  446. WritePixels<PixelType>([]{ return AsVariant(PixelType(0)); });
  447. }
  448. gfx::IntSize mInputSize; /// The size of the input this filter expects.
  449. uint8_t* mRowPointer; /// Pointer to the current row or null if finished.
  450. int32_t mCol; /// The current column we're writing to. (0-indexed)
  451. uint8_t mPixelSize; /// How large each pixel in the surface is, in bytes.
  452. };
  453. class NullSurfaceSink;
  454. /// A trivial configuration struct for NullSurfaceSink.
  455. struct NullSurfaceConfig
  456. {
  457. using Filter = NullSurfaceSink;
  458. };
  459. /**
  460. * NullSurfaceSink is a trivial SurfaceFilter implementation that behaves as if
  461. * it were a zero-size SurfaceSink. It's used as the default filter chain for an
  462. * uninitialized SurfacePipe.
  463. *
  464. * To avoid unnecessary allocations when creating SurfacePipe objects,
  465. * NullSurfaceSink is a singleton. (This implies that the implementation must be
  466. * stateless.)
  467. */
  468. class NullSurfaceSink final : public SurfaceFilter
  469. {
  470. public:
  471. /// Returns the singleton instance of NullSurfaceSink.
  472. static NullSurfaceSink* Singleton();
  473. virtual ~NullSurfaceSink() { }
  474. nsresult Configure(const NullSurfaceConfig& aConfig);
  475. Maybe<SurfaceInvalidRect> TakeInvalidRect() override { return Nothing(); }
  476. protected:
  477. uint8_t* DoResetToFirstRow() override { return nullptr; }
  478. uint8_t* DoAdvanceRow() override { return nullptr; }
  479. private:
  480. static UniquePtr<NullSurfaceSink> sSingleton; /// The singleton instance.
  481. };
  482. /**
  483. * SurfacePipe is the public API that decoders should use to interact with a
  484. * SurfaceFilter pipeline.
  485. */
  486. class SurfacePipe
  487. {
  488. public:
  489. /// Initialize global state used by all SurfacePipes.
  490. static void Initialize() { NullSurfaceSink::Singleton(); }
  491. SurfacePipe()
  492. : mHead(NullSurfaceSink::Singleton())
  493. { }
  494. SurfacePipe(SurfacePipe&& aOther)
  495. : mHead(Move(aOther.mHead))
  496. { }
  497. ~SurfacePipe()
  498. {
  499. // Ensure that we don't free the NullSurfaceSink singleton.
  500. if (mHead.get() == NullSurfaceSink::Singleton()) {
  501. Unused << mHead.release();
  502. }
  503. }
  504. SurfacePipe& operator=(SurfacePipe&& aOther)
  505. {
  506. MOZ_ASSERT(this != &aOther);
  507. // Ensure that we don't free the NullSurfaceSink singleton.
  508. if (mHead.get() == NullSurfaceSink::Singleton()) {
  509. Unused << mHead.release();
  510. }
  511. mHead = Move(aOther.mHead);
  512. return *this;
  513. }
  514. /// Begins a new pass, seeking to the first row of the surface.
  515. void ResetToFirstRow() { mHead->ResetToFirstRow(); }
  516. /**
  517. * Write pixels to the surface one at a time by repeatedly calling a lambda
  518. * that yields pixels. WritePixels() is completely memory safe.
  519. *
  520. * @see SurfaceFilter::WritePixels() for the canonical documentation.
  521. */
  522. template <typename PixelType, typename Func>
  523. WriteState WritePixels(Func aFunc)
  524. {
  525. return mHead->WritePixels<PixelType>(Forward<Func>(aFunc));
  526. }
  527. /**
  528. * A variant of WritePixels() that writes a single row of pixels to the
  529. * surface one at a time by repeatedly calling a lambda that yields pixels.
  530. * WritePixelsToRow() is completely memory safe.
  531. *
  532. * @see SurfaceFilter::WritePixelsToRow() for the canonical documentation.
  533. */
  534. template <typename PixelType, typename Func>
  535. WriteState WritePixelsToRow(Func aFunc)
  536. {
  537. return mHead->WritePixelsToRow<PixelType>(Forward<Func>(aFunc));
  538. }
  539. /**
  540. * Write a row to the surface by copying from a buffer. This is bounds checked
  541. * and memory safe with respect to the surface, but care must still be taken
  542. * by the caller not to overread the source buffer. This variant of
  543. * WriteBuffer() requires a source buffer which contains |mInputSize.width|
  544. * pixels.
  545. *
  546. * @see SurfaceFilter::WriteBuffer() for the canonical documentation.
  547. */
  548. template <typename PixelType>
  549. WriteState WriteBuffer(const PixelType* aSource)
  550. {
  551. return mHead->WriteBuffer<PixelType>(aSource);
  552. }
  553. /**
  554. * Write a row to the surface by copying from a buffer. This is bounds checked
  555. * and memory safe with respect to the surface, but care must still be taken
  556. * by the caller not to overread the source buffer. This variant of
  557. * WriteBuffer() reads at most @aLength pixels from the buffer and writes them
  558. * to the row starting at @aStartColumn. Any pixels in columns before
  559. * @aStartColumn or after the pixels copied from the buffer are cleared.
  560. *
  561. * @see SurfaceFilter::WriteBuffer() for the canonical documentation.
  562. */
  563. template <typename PixelType>
  564. WriteState WriteBuffer(const PixelType* aSource,
  565. const size_t aStartColumn,
  566. const size_t aLength)
  567. {
  568. return mHead->WriteBuffer<PixelType>(aSource, aStartColumn, aLength);
  569. }
  570. /**
  571. * Write an empty row to the surface. If some pixels have already been written
  572. * to this row, they'll be discarded.
  573. *
  574. * @see SurfaceFilter::WriteEmptyRow() for the canonical documentation.
  575. */
  576. WriteState WriteEmptyRow()
  577. {
  578. return mHead->WriteEmptyRow();
  579. }
  580. /// @return true if we've finished writing to the surface.
  581. bool IsSurfaceFinished() const { return mHead->IsSurfaceFinished(); }
  582. /// @see SurfaceFilter::TakeInvalidRect() for the canonical documentation.
  583. Maybe<SurfaceInvalidRect> TakeInvalidRect() const
  584. {
  585. return mHead->TakeInvalidRect();
  586. }
  587. private:
  588. friend class SurfacePipeFactory;
  589. friend class TestSurfacePipeFactory;
  590. explicit SurfacePipe(UniquePtr<SurfaceFilter>&& aHead)
  591. : mHead(Move(aHead))
  592. { }
  593. SurfacePipe(const SurfacePipe&) = delete;
  594. SurfacePipe& operator=(const SurfacePipe&) = delete;
  595. UniquePtr<SurfaceFilter> mHead; /// The first filter in the chain.
  596. };
  597. /**
  598. * AbstractSurfaceSink contains shared implementation for both SurfaceSink and
  599. * PalettedSurfaceSink.
  600. */
  601. class AbstractSurfaceSink : public SurfaceFilter
  602. {
  603. public:
  604. AbstractSurfaceSink()
  605. : mImageData(nullptr)
  606. , mImageDataLength(0)
  607. , mRow(0)
  608. , mFlipVertically(false)
  609. { }
  610. Maybe<SurfaceInvalidRect> TakeInvalidRect() override final;
  611. protected:
  612. uint8_t* DoResetToFirstRow() override final;
  613. uint8_t* DoAdvanceRow() override final;
  614. virtual uint8_t* GetRowPointer() const = 0;
  615. gfx::IntRect mInvalidRect; /// The region of the surface that has been written
  616. /// to since the last call to TakeInvalidRect().
  617. uint8_t* mImageData; /// A pointer to the beginning of the surface data.
  618. uint32_t mImageDataLength; /// The length of the surface data.
  619. uint32_t mRow; /// The row to which we're writing. (0-indexed)
  620. bool mFlipVertically; /// If true, write the rows from top to bottom.
  621. };
  622. class SurfaceSink;
  623. /// A configuration struct for SurfaceSink.
  624. struct SurfaceConfig
  625. {
  626. using Filter = SurfaceSink;
  627. Decoder* mDecoder; /// Which Decoder to use to allocate the surface.
  628. gfx::IntSize mOutputSize; /// The size of the surface.
  629. gfx::SurfaceFormat mFormat; /// The surface format (BGRA or BGRX).
  630. bool mFlipVertically; /// If true, write the rows from bottom to top.
  631. Maybe<AnimationParams> mAnimParams; /// Given for animated images.
  632. };
  633. /**
  634. * A sink for normal (i.e., non-paletted) surfaces. It handles the allocation of
  635. * the surface and protects against buffer overflow. This sink should be used
  636. * for all non-animated images and for the first frame of animated images.
  637. *
  638. * Sinks must always be at the end of the SurfaceFilter chain.
  639. */
  640. class SurfaceSink final : public AbstractSurfaceSink
  641. {
  642. public:
  643. nsresult Configure(const SurfaceConfig& aConfig);
  644. protected:
  645. uint8_t* GetRowPointer() const override;
  646. };
  647. class PalettedSurfaceSink;
  648. struct PalettedSurfaceConfig
  649. {
  650. using Filter = PalettedSurfaceSink;
  651. Decoder* mDecoder; /// Which Decoder to use to allocate the surface.
  652. gfx::IntSize mOutputSize; /// The logical size of the surface.
  653. gfx::IntRect mFrameRect; /// The surface subrect which contains data.
  654. gfx::SurfaceFormat mFormat; /// The surface format (BGRA or BGRX).
  655. uint8_t mPaletteDepth; /// The palette depth of this surface.
  656. bool mFlipVertically; /// If true, write the rows from bottom to top.
  657. Maybe<AnimationParams> mAnimParams; /// Given for animated images.
  658. };
  659. /**
  660. * A sink for paletted surfaces. It handles the allocation of the surface and
  661. * protects against buffer overflow. This sink can be used for frames of
  662. * animated images except the first.
  663. *
  664. * Sinks must always be at the end of the SurfaceFilter chain.
  665. *
  666. * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
  667. * which means we can remove PalettedSurfaceSink entirely.
  668. */
  669. class PalettedSurfaceSink final : public AbstractSurfaceSink
  670. {
  671. public:
  672. bool IsValidPalettedPipe() const override { return true; }
  673. nsresult Configure(const PalettedSurfaceConfig& aConfig);
  674. protected:
  675. uint8_t* GetRowPointer() const override;
  676. private:
  677. /**
  678. * The surface subrect which contains data. Note that the surface size we
  679. * actually allocate is the size of the frame rect, not the logical size of
  680. * the surface.
  681. */
  682. gfx::IntRect mFrameRect;
  683. };
  684. } // namespace image
  685. } // namespace mozilla
  686. #endif // mozilla_image_SurfacePipe_h