summaryrefslogtreecommitdiff
path: root/image/SurfacePipe.h
blob: 616062dd62b772cc7260444e2a602a99cf5c3ede (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * A SurfacePipe is a pipeline that consists of a series of SurfaceFilters
 * terminating in a SurfaceSink. Each SurfaceFilter transforms the image data in
 * some way before the SurfaceSink ultimately writes it to the surface. This
 * design allows for each transformation to be tested independently, for the
 * transformations to be combined as needed to meet the needs of different
 * situations, and for all image decoders to share the same code for these
 * transformations.
 *
 * Writing to the SurfacePipe is done using lambdas that act as generator
 * functions. Because the SurfacePipe machinery controls where the writes take
 * place, a bug in an image decoder cannot cause a buffer overflow of the
 * underlying surface.
 */

#ifndef mozilla_image_SurfacePipe_h
#define mozilla_image_SurfacePipe_h

#include <stdint.h>

#include "nsDebug.h"

#include "mozilla/Likely.h"
#include "mozilla/Maybe.h"
#include "mozilla/Move.h"
#include "mozilla/Tuple.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "mozilla/Variant.h"
#include "mozilla/gfx/2D.h"

#include "AnimationParams.h"

namespace mozilla {
namespace image {

class Decoder;

/**
 * An invalid rect for a surface. Results are given both in the space of the
 * input image (i.e., before any SurfaceFilters are applied) and in the space
 * of the output surface (after all SurfaceFilters).
 */
struct SurfaceInvalidRect
{
  gfx::IntRect mInputSpaceRect;   /// The invalid rect in pre-SurfacePipe space.
  gfx::IntRect mOutputSpaceRect;  /// The invalid rect in post-SurfacePipe space.
};

/**
 * An enum used to allow the lambdas passed to WritePixels() to communicate
 * their state to the caller.
 */
enum class WriteState : uint8_t
{
  NEED_MORE_DATA,  /// The lambda ran out of data.

  FINISHED,        /// The lambda is done writing to the surface; future writes
                   /// will fail.

  FAILURE          /// The lambda encountered an error. The caller may recover
                   /// if possible and continue to write. (This never indicates
                   /// an error in the SurfacePipe machinery itself; it's only
                   /// generated by the lambdas.)
};

/**
 * A template alias used to make the return value of WritePixels() lambdas
 * (which may return either a pixel value or a WriteState) easier to specify.
 */
template <typename PixelType>
using NextPixel = Variant<PixelType, WriteState>;

/**
 * SurfaceFilter is the abstract superclass of SurfacePipe pipeline stages.  It
 * implements the the code that actually writes to the surface - WritePixels()
 * and the other Write*() methods - which are non-virtual for efficiency.
 *
 * SurfaceFilter's API is nonpublic; only SurfacePipe and other SurfaceFilters
 * should use it. Non-SurfacePipe code should use the methods on SurfacePipe.
 *
 * To implement a SurfaceFilter, it's necessary to subclass SurfaceFilter and
 * implement, at a minimum, the pure virtual methods. It's also necessary to
 * define a Config struct with a Filter typedef member that identifies the
 * matching SurfaceFilter class, and a Configure() template method. See an
 * existing SurfaceFilter subclass, such as RemoveFrameRectFilter, for an
 * example of how the Configure() method must be implemented. It takes a list of
 * Config structs, passes the tail of the list to the next filter in the chain's
 * Configure() method, and then uses the head of the list to configure itself. A
 * SurfaceFilter's Configure() method must also call
 * SurfaceFilter::ConfigureFilter() to provide the Write*() methods with the
 * information they need to do their jobs.
 */
class SurfaceFilter
{
public:
  SurfaceFilter()
    : mRowPointer(nullptr)
    , mCol(0)
    , mPixelSize(0)
  { }

  virtual ~SurfaceFilter() { }

  /**
   * Reset this surface to the first row. It's legal for this filter to throw
   * away any previously written data at this point, as all rows must be written
   * to on every pass.
   *
   * @return a pointer to the buffer for the first row.
   */
  uint8_t* ResetToFirstRow()
  {
    mCol = 0;
    mRowPointer = DoResetToFirstRow();
    return mRowPointer;
  }

  /**
   * Called by WritePixels() to advance this filter to the next row.
   *
   * @return a pointer to the buffer for the next row, or nullptr to indicate
   *         that we've finished the entire surface.
   */
  uint8_t* AdvanceRow()
  {
    mCol = 0;
    mRowPointer = DoAdvanceRow();
    return mRowPointer;
  }

  /// @return a pointer to the buffer for the current row.
  uint8_t* CurrentRowPointer() const { return mRowPointer; }

  /// @return true if we've finished writing to the surface.
  bool IsSurfaceFinished() const { return mRowPointer == nullptr; }

  /// @return the input size this filter expects.
  gfx::IntSize InputSize() const { return mInputSize; }

  /**
   * Write pixels to the surface one at a time by repeatedly calling a lambda
   * that yields pixels. WritePixels() is completely memory safe.
   *
   * Writing continues until every pixel in the surface has been written to
   * (i.e., IsSurfaceFinished() returns true) or the lambda returns a WriteState
   * which WritePixels() will return to the caller.
   *
   * The template parameter PixelType must be uint8_t (for paletted surfaces) or
   * uint32_t (for BGRA/BGRX surfaces) and must be in agreement with the pixel
   * size passed to ConfigureFilter().
   *
   * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
   * which means we can remove the PixelType template parameter from this
   * method.
   *
   * @param aFunc A lambda that functions as a generator, yielding the next
   *              pixel in the surface each time it's called. The lambda must
   *              return a NextPixel<PixelType> value.
   *
   * @return A WriteState value indicating the lambda generator's state.
   *         WritePixels() itself will return WriteState::FINISHED if writing
   *         has finished, regardless of the lambda's internal state.
   */
  template <typename PixelType, typename Func>
  WriteState WritePixels(Func aFunc)
  {
    Maybe<WriteState> result;
    while (!(result = DoWritePixelsToRow<PixelType>(Forward<Func>(aFunc)))) { }

    return *result;
  }

  /**
   * Write pixels to the surface by calling a lambda which may write as many
   * pixels as there is remaining to complete the row. It is not completely
   * memory safe as it trusts the underlying decoder not to overrun the given
   * buffer, however it is an acceptable tradeoff for performance.
   *
   * Writing continues until every pixel in the surface has been written to
   * (i.e., IsSurfaceFinished() returns true) or the lambda returns a WriteState
   * which WritePixelBlocks() will return to the caller.
   *
   * The template parameter PixelType must be uint8_t (for paletted surfaces) or
   * uint32_t (for BGRA/BGRX surfaces) and must be in agreement with the pixel
   * size passed to ConfigureFilter().
   *
   * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
   * which means we can remove the PixelType template parameter from this
   * method.
   *
   * @param aFunc A lambda that functions as a generator, yielding at most the
   *              maximum number of pixels requested. The lambda must accept a
   *              pointer argument to the first pixel to write, a maximum
   *              number of pixels to write as part of the block, and return a
   *              NextPixel<PixelType> value.
   *
   * @return A WriteState value indicating the lambda generator's state.
   *         WritePixelBlocks() itself will return WriteState::FINISHED if
   *         writing has finished, regardless of the lambda's internal state.
   */
  template <typename PixelType, typename Func>
  WriteState WritePixelBlocks(Func aFunc)
  {
    Maybe<WriteState> result;
    while (!(result = DoWritePixelBlockToRow<PixelType>(Forward<Func>(aFunc)))) { }

    return *result;
  }

  /**
   * A variant of WritePixels() that writes a single row of pixels to the
   * surface one at a time by repeatedly calling a lambda that yields pixels.
   * WritePixelsToRow() is completely memory safe.
   *
   * Writing continues until every pixel in the row has been written to. If the
   * surface is complete at that pointer, WriteState::FINISHED is returned;
   * otherwise, WritePixelsToRow() returns WriteState::NEED_MORE_DATA. The
   * lambda can terminate writing early by returning a WriteState itself, which
   * WritePixelsToRow() will return to the caller.
   *
   * The template parameter PixelType must be uint8_t (for paletted surfaces) or
   * uint32_t (for BGRA/BGRX surfaces) and must be in agreement with the pixel
   * size passed to ConfigureFilter().
   *
   * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
   * which means we can remove the PixelType template parameter from this
   * method.
   *
   * @param aFunc A lambda that functions as a generator, yielding the next
   *              pixel in the surface each time it's called. The lambda must
   *              return a NextPixel<PixelType> value.
   *
   * @return A WriteState value indicating the lambda generator's state.
   *         WritePixels() itself will return WriteState::FINISHED if writing
   *         the entire surface has finished, or WriteState::NEED_MORE_DATA if
   *         writing the row has finished, regardless of the lambda's internal
   *         state.
   */
  template <typename PixelType, typename Func>
  WriteState WritePixelsToRow(Func aFunc)
  {
    return DoWritePixelsToRow<PixelType>(Forward<Func>(aFunc))
           .valueOr(WriteState::NEED_MORE_DATA);
  }

  /**
   * Write a row to the surface by copying from a buffer. This is bounds checked
   * and memory safe with respect to the surface, but care must still be taken
   * by the caller not to overread the source buffer. This variant of
   * WriteBuffer() requires a source buffer which contains |mInputSize.width|
   * pixels.
   *
   * The template parameter PixelType must be uint8_t (for paletted surfaces) or
   * uint32_t (for BGRA/BGRX surfaces) and must be in agreement with the pixel
   * size passed to ConfigureFilter().
   *
   * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
   * which means we can remove the PixelType template parameter from this
   * method.
   *
   * @param aSource A buffer to copy from. This buffer must be
   *                |mInputSize.width| pixels wide,  which means
   *                |mInputSize.width * sizeof(PixelType)| bytes. May not be
   *                null.
   *
   * @return WriteState::FINISHED if the entire surface has been written to.
   *         Otherwise, returns WriteState::NEED_MORE_DATA. If a null |aSource|
   *         value is passed, returns WriteState::FAILURE.
   */
  template <typename PixelType>
  WriteState WriteBuffer(const PixelType* aSource)
  {
    return WriteBuffer(aSource, 0, mInputSize.width);
  }

  /**
   * Write a row to the surface by copying from a buffer. This is bounds checked
   * and memory safe with respect to the surface, but care must still be taken
   * by the caller not to overread the source buffer. This variant of
   * WriteBuffer() reads at most @aLength pixels from the buffer and writes them
   * to the row starting at @aStartColumn. Any pixels in columns before
   * @aStartColumn or after the pixels copied from the buffer are cleared.
   *
   * Bounds checking failures produce warnings in debug builds because although
   * the bounds checking maintains safety, this kind of failure could indicate a
   * bug in the calling code.
   *
   * The template parameter PixelType must be uint8_t (for paletted surfaces) or
   * uint32_t (for BGRA/BGRX surfaces) and must be in agreement with the pixel
   * size passed to ConfigureFilter().
   *
   * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
   * which means we can remove the PixelType template parameter from this
   * method.
   *
   * @param aSource A buffer to copy from. This buffer must be @aLength pixels
   *                wide, which means |aLength * sizeof(PixelType)| bytes. May
   *                not be null.
   * @param aStartColumn The column to start writing to in the row. Columns
   *                     before this are cleared.
   * @param aLength The number of bytes, at most, which may be copied from
   *                @aSource. Fewer bytes may be copied in practice due to
   *                bounds checking.
   *
   * @return WriteState::FINISHED if the entire surface has been written to.
   *         Otherwise, returns WriteState::NEED_MORE_DATA. If a null |aSource|
   *         value is passed, returns WriteState::FAILURE.
   */
  template <typename PixelType>
  WriteState WriteBuffer(const PixelType* aSource,
                         const size_t aStartColumn,
                         const size_t aLength)
  {
    MOZ_ASSERT(mPixelSize == 1 || mPixelSize == 4);
    MOZ_ASSERT_IF(mPixelSize == 1, sizeof(PixelType) == sizeof(uint8_t));
    MOZ_ASSERT_IF(mPixelSize == 4, sizeof(PixelType) == sizeof(uint32_t));

    if (IsSurfaceFinished()) {
      return WriteState::FINISHED;  // Already done.
    }

    if (MOZ_UNLIKELY(!aSource)) {
      NS_WARNING("Passed a null pointer to WriteBuffer");
      return WriteState::FAILURE;
    }

    PixelType* dest = reinterpret_cast<PixelType*>(mRowPointer);

    // Clear the area before |aStartColumn|.
    const size_t prefixLength = std::min<size_t>(mInputSize.width, aStartColumn);
    if (MOZ_UNLIKELY(prefixLength != aStartColumn)) {
      NS_WARNING("Provided starting column is out-of-bounds in WriteBuffer");
    }

    memset(dest, 0, mInputSize.width * sizeof(PixelType));
    dest += prefixLength;

    // Write |aLength| pixels from |aSource| into the row, with bounds checking.
    const size_t bufferLength =
      std::min<size_t>(mInputSize.width - prefixLength, aLength);
    if (MOZ_UNLIKELY(bufferLength != aLength)) {
      NS_WARNING("Provided buffer length is out-of-bounds in WriteBuffer");
    }

    memcpy(dest, aSource, bufferLength * sizeof(PixelType));
    dest += bufferLength;

    // Clear the rest of the row.
    const size_t suffixLength = mInputSize.width - (prefixLength + bufferLength);
    memset(dest, 0, suffixLength * sizeof(PixelType));

    AdvanceRow();

    return IsSurfaceFinished() ? WriteState::FINISHED
                               : WriteState::NEED_MORE_DATA;
  }

  /**
   * Write an empty row to the surface. If some pixels have already been written
   * to this row, they'll be discarded.
   *
   * @return WriteState::FINISHED if the entire surface has been written to.
   *         Otherwise, returns WriteState::NEED_MORE_DATA.
   */
  WriteState WriteEmptyRow()
  {
    if (IsSurfaceFinished()) {
      return WriteState::FINISHED;  // Already done.
    }

    memset(mRowPointer, 0, mInputSize.width * mPixelSize);
    AdvanceRow();

    return IsSurfaceFinished() ? WriteState::FINISHED
                               : WriteState::NEED_MORE_DATA;
  }

  /**
   * Write a row to the surface by calling a lambda that uses a pointer to
   * directly write to the row. This is unsafe because SurfaceFilter can't
   * provide any bounds checking; that's up to the lambda itself. For this
   * reason, the other Write*() methods should be preferred whenever it's
   * possible to use them; WriteUnsafeComputedRow() should be used only when
   * it's absolutely necessary to avoid extra copies or other performance
   * penalties.
   *
   * This method should never be exposed to SurfacePipe consumers; it's strictly
   * for use in SurfaceFilters. If external code needs this method, it should
   * probably be turned into a SurfaceFilter.
   *
   * The template parameter PixelType must be uint8_t (for paletted surfaces) or
   * uint32_t (for BGRA/BGRX surfaces) and must be in agreement with the pixel
   * size passed to ConfigureFilter().
   *
   * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
   * which means we can remove the PixelType template parameter from this
   * method.
   *
   * @param aFunc A lambda that writes directly to the row.
   *
   * @return WriteState::FINISHED if the entire surface has been written to.
   *         Otherwise, returns WriteState::NEED_MORE_DATA.
   */
  template <typename PixelType, typename Func>
  WriteState WriteUnsafeComputedRow(Func aFunc)
  {
    MOZ_ASSERT(mPixelSize == 1 || mPixelSize == 4);
    MOZ_ASSERT_IF(mPixelSize == 1, sizeof(PixelType) == sizeof(uint8_t));
    MOZ_ASSERT_IF(mPixelSize == 4, sizeof(PixelType) == sizeof(uint32_t));

    if (IsSurfaceFinished()) {
      return WriteState::FINISHED;  // Already done.
    }

    // Call the provided lambda with a pointer to the buffer for the current
    // row. This is unsafe because we can't do any bounds checking; the lambda
    // itself has to be responsible for that.
    PixelType* rowPtr = reinterpret_cast<PixelType*>(mRowPointer);
    aFunc(rowPtr, mInputSize.width);
    AdvanceRow();

    return IsSurfaceFinished() ? WriteState::FINISHED
                               : WriteState::NEED_MORE_DATA;
  }

  //////////////////////////////////////////////////////////////////////////////
  // Methods Subclasses Should Override
  //////////////////////////////////////////////////////////////////////////////

  /// @return true if this SurfaceFilter can be used with paletted surfaces.
  virtual bool IsValidPalettedPipe() const { return false; }

  /**
   * @return a SurfaceInvalidRect representing the region of the surface that
   *         has been written to since the last time TakeInvalidRect() was
   *         called, or Nothing() if the region is empty (i.e. nothing has been
   *         written).
   */
  virtual Maybe<SurfaceInvalidRect> TakeInvalidRect() = 0;

protected:

  /**
   * Called by ResetToFirstRow() to actually perform the reset. It's legal to
   * throw away any previously written data at this point, as all rows must be
   * written to on every pass.
   */
  virtual uint8_t* DoResetToFirstRow() = 0;

  /**
   * Called by AdvanceRow() to actually advance this filter to the next row.
   *
   * @return a pointer to the buffer for the next row, or nullptr to indicate
   *         that we've finished the entire surface.
   */
  virtual uint8_t* DoAdvanceRow() = 0;


  //////////////////////////////////////////////////////////////////////////////
  // Methods For Internal Use By Subclasses
  //////////////////////////////////////////////////////////////////////////////

  /**
   * Called by subclasses' Configure() methods to initialize the configuration
   * of this filter. After the filter is configured, calls ResetToFirstRow().
   *
   * @param aInputSize The input size of this filter, in pixels. The previous
   *                   filter in the chain will expect to write into rows
   *                   |aInputSize.width| pixels wide.
   * @param aPixelSize How large, in bytes, each pixel in the surface is. This
   *                   should be either 1 for paletted images or 4 for BGRA/BGRX
   *                   images.
   */
  void ConfigureFilter(gfx::IntSize aInputSize, uint8_t aPixelSize)
  {
    mInputSize = aInputSize;
    mPixelSize = aPixelSize;

    ResetToFirstRow();
  }

private:

  /**
   * An internal method used to implement WritePixelBlocks. This method writes
   * up to the number of pixels necessary to complete the row and returns Some()
   * if we either finished the entire surface or the lambda returned a
   * WriteState indicating that we should return to the caller. If the row was
   * successfully written without either of those things happening, it returns
   * Nothing(), allowing WritePixelBlocks() to iterate to fill as many rows as
   * possible.
   */
  template <typename PixelType, typename Func>
  Maybe<WriteState> DoWritePixelBlockToRow(Func aFunc)
  {
    MOZ_ASSERT(mPixelSize == 1 || mPixelSize == 4);
    MOZ_ASSERT_IF(mPixelSize == 1, sizeof(PixelType) == sizeof(uint8_t));
    MOZ_ASSERT_IF(mPixelSize == 4, sizeof(PixelType) == sizeof(uint32_t));

    if (IsSurfaceFinished()) {
      return Some(WriteState::FINISHED);  // We're already done.
    }

    PixelType* rowPtr = reinterpret_cast<PixelType*>(mRowPointer);
    int32_t remainder = mInputSize.width - mCol;
    int32_t written;
    Maybe<WriteState> result;
    Tie(written, result) = aFunc(&rowPtr[mCol], remainder);
    if (written == remainder) {
      MOZ_ASSERT(result.isNothing());
      mCol = mInputSize.width;
      AdvanceRow();  // We've finished the row.
      return IsSurfaceFinished() ? Some(WriteState::FINISHED)
                                 : Nothing();
    }

    MOZ_ASSERT(written >= 0 && written < remainder);
    MOZ_ASSERT(result.isSome());

    mCol += written;
    if (*result == WriteState::FINISHED) {
      ZeroOutRestOfSurface<PixelType>();
    }

    return result;
  }

  /**
   * An internal method used to implement both WritePixels() and
   * WritePixelsToRow(). Those methods differ only in their behavior after a row
   * is successfully written - WritePixels() continues to write another row,
   * while WritePixelsToRow() returns to the caller. This method writes a single
   * row and returns Some() if we either finished the entire surface or the
   * lambda returned a WriteState indicating that we should return to the
   * caller. If the row was successfully written without either of those things
   * happening, it returns Nothing(), allowing WritePixels() and
   * WritePixelsToRow() to implement their respective behaviors.
   */
  template <typename PixelType, typename Func>
  Maybe<WriteState> DoWritePixelsToRow(Func aFunc)
  {
    MOZ_ASSERT(mPixelSize == 1 || mPixelSize == 4);
    MOZ_ASSERT_IF(mPixelSize == 1, sizeof(PixelType) == sizeof(uint8_t));
    MOZ_ASSERT_IF(mPixelSize == 4, sizeof(PixelType) == sizeof(uint32_t));

    if (IsSurfaceFinished()) {
      return Some(WriteState::FINISHED);  // We're already done.
    }

    PixelType* rowPtr = reinterpret_cast<PixelType*>(mRowPointer);

    for (; mCol < mInputSize.width; ++mCol) {
      NextPixel<PixelType> result = aFunc();
      if (result.template is<PixelType>()) {
        rowPtr[mCol] = result.template as<PixelType>();
        continue;
      }

      switch (result.template as<WriteState>()) {
        case WriteState::NEED_MORE_DATA:
          return Some(WriteState::NEED_MORE_DATA);

        case WriteState::FINISHED:
          ZeroOutRestOfSurface<PixelType>();
          return Some(WriteState::FINISHED);

        case WriteState::FAILURE:
          // Note that we don't need to record this anywhere, because this
          // indicates an error in aFunc, and there's nothing wrong with our
          // machinery. The caller can recover as needed and continue writing to
          // the row.
          return Some(WriteState::FAILURE);
      }
    }

    AdvanceRow();  // We've finished the row.

    return IsSurfaceFinished() ? Some(WriteState::FINISHED)
                               : Nothing();
  }

  template <typename PixelType>
  void ZeroOutRestOfSurface()
  {
    WritePixels<PixelType>([]{ return AsVariant(PixelType(0)); });
  }

  gfx::IntSize mInputSize;  /// The size of the input this filter expects.
  uint8_t* mRowPointer;     /// Pointer to the current row or null if finished.
  int32_t mCol;             /// The current column we're writing to. (0-indexed)
  uint8_t  mPixelSize;      /// How large each pixel in the surface is, in bytes.
};

class NullSurfaceSink;

/// A trivial configuration struct for NullSurfaceSink.
struct NullSurfaceConfig
{
  using Filter = NullSurfaceSink;
};

/**
 * NullSurfaceSink is a trivial SurfaceFilter implementation that behaves as if
 * it were a zero-size SurfaceSink. It's used as the default filter chain for an
 * uninitialized SurfacePipe.
 *
 * To avoid unnecessary allocations when creating SurfacePipe objects,
 * NullSurfaceSink is a singleton. (This implies that the implementation must be
 * stateless.)
 */
class NullSurfaceSink final : public SurfaceFilter
{
public:
  /// Returns the singleton instance of NullSurfaceSink.
  static NullSurfaceSink* Singleton();

  virtual ~NullSurfaceSink() { }

  nsresult Configure(const NullSurfaceConfig& aConfig);

  Maybe<SurfaceInvalidRect> TakeInvalidRect() override { return Nothing(); }

protected:
  uint8_t* DoResetToFirstRow() override { return nullptr; }
  uint8_t* DoAdvanceRow() override { return nullptr; }

private:
  static UniquePtr<NullSurfaceSink> sSingleton;  /// The singleton instance.
};


/**
 * SurfacePipe is the public API that decoders should use to interact with a
 * SurfaceFilter pipeline.
 */
class SurfacePipe
{
public:
  /// Initialize global state used by all SurfacePipes.
  static void Initialize() { NullSurfaceSink::Singleton(); }

  SurfacePipe()
    : mHead(NullSurfaceSink::Singleton())
  { }

  SurfacePipe(SurfacePipe&& aOther)
    : mHead(Move(aOther.mHead))
  { }

  ~SurfacePipe()
  {
    // Ensure that we don't free the NullSurfaceSink singleton.
    if (mHead.get() == NullSurfaceSink::Singleton()) {
      Unused << mHead.release();
    }
  }

  SurfacePipe& operator=(SurfacePipe&& aOther)
  {
    MOZ_ASSERT(this != &aOther);

    // Ensure that we don't free the NullSurfaceSink singleton.
    if (mHead.get() == NullSurfaceSink::Singleton()) {
      Unused << mHead.release();
    }

    mHead = Move(aOther.mHead);
    return *this;
  }

  /// Begins a new pass, seeking to the first row of the surface.
  void ResetToFirstRow() { mHead->ResetToFirstRow(); }

  /**
   * Write pixels to the surface one at a time by repeatedly calling a lambda
   * that yields pixels. WritePixels() is completely memory safe.
   *
   * @see SurfaceFilter::WritePixels() for the canonical documentation.
   */
  template <typename PixelType, typename Func>
  WriteState WritePixels(Func aFunc)
  {
    return mHead->WritePixels<PixelType>(Forward<Func>(aFunc));
  }

  /**
   * A variant of WritePixels() that writes up to a single row of pixels to the
   * surface in blocks by repeatedly calling a lambda that yields up to the
   * requested number of pixels.
   *
   * @see SurfaceFilter::WritePixelBlocks() for the canonical documentation.
   */
  template <typename PixelType, typename Func>
  WriteState WritePixelBlocks(Func aFunc)
  {
    MOZ_ASSERT(mHead, "Use before configured!");
    return mHead->WritePixelBlocks<PixelType>(Forward<Func>(aFunc));
  }

  /**
   * A variant of WritePixels() that writes a single row of pixels to the
   * surface one at a time by repeatedly calling a lambda that yields pixels.
   * WritePixelsToRow() is completely memory safe.
   *
   * @see SurfaceFilter::WritePixelsToRow() for the canonical documentation.
   */
  template <typename PixelType, typename Func>
  WriteState WritePixelsToRow(Func aFunc)
  {
    return mHead->WritePixelsToRow<PixelType>(Forward<Func>(aFunc));
  }

  /**
   * Write a row to the surface by copying from a buffer. This is bounds checked
   * and memory safe with respect to the surface, but care must still be taken
   * by the caller not to overread the source buffer. This variant of
   * WriteBuffer() requires a source buffer which contains |mInputSize.width|
   * pixels.
   *
   * @see SurfaceFilter::WriteBuffer() for the canonical documentation.
   */
  template <typename PixelType>
  WriteState WriteBuffer(const PixelType* aSource)
  {
    return mHead->WriteBuffer<PixelType>(aSource);
  }

  /**
   * Write a row to the surface by copying from a buffer. This is bounds checked
   * and memory safe with respect to the surface, but care must still be taken
   * by the caller not to overread the source buffer. This variant of
   * WriteBuffer() reads at most @aLength pixels from the buffer and writes them
   * to the row starting at @aStartColumn. Any pixels in columns before
   * @aStartColumn or after the pixels copied from the buffer are cleared.
   *
   * @see SurfaceFilter::WriteBuffer() for the canonical documentation.
   */
  template <typename PixelType>
  WriteState WriteBuffer(const PixelType* aSource,
                         const size_t aStartColumn,
                         const size_t aLength)
  {
    return mHead->WriteBuffer<PixelType>(aSource, aStartColumn, aLength);
  }

  /**
   * Write an empty row to the surface. If some pixels have already been written
   * to this row, they'll be discarded.
   *
   * @see SurfaceFilter::WriteEmptyRow() for the canonical documentation.
   */
  WriteState WriteEmptyRow()
  {
    return mHead->WriteEmptyRow();
  }

  /// @return true if we've finished writing to the surface.
  bool IsSurfaceFinished() const { return mHead->IsSurfaceFinished(); }

  /// @see SurfaceFilter::TakeInvalidRect() for the canonical documentation.
  Maybe<SurfaceInvalidRect> TakeInvalidRect() const
  {
    return mHead->TakeInvalidRect();
  }

private:
  friend class SurfacePipeFactory;
  friend class TestSurfacePipeFactory;

  explicit SurfacePipe(UniquePtr<SurfaceFilter>&& aHead)
    : mHead(Move(aHead))
  { }

  SurfacePipe(const SurfacePipe&) = delete;
  SurfacePipe& operator=(const SurfacePipe&) = delete;

  UniquePtr<SurfaceFilter> mHead;  /// The first filter in the chain.
};

/**
 * AbstractSurfaceSink contains shared implementation for both SurfaceSink and
 * PalettedSurfaceSink.
 */
class AbstractSurfaceSink : public SurfaceFilter
{
public:
  AbstractSurfaceSink()
    : mImageData(nullptr)
    , mImageDataLength(0)
    , mRow(0)
    , mFlipVertically(false)
  { }

  Maybe<SurfaceInvalidRect> TakeInvalidRect() override final;

protected:
  uint8_t* DoResetToFirstRow() override final;
  uint8_t* DoAdvanceRow() override final;
  virtual uint8_t* GetRowPointer() const = 0;

  gfx::IntRect mInvalidRect;  /// The region of the surface that has been written
                              /// to since the last call to TakeInvalidRect().
  uint8_t*  mImageData;       /// A pointer to the beginning of the surface data.
  uint32_t  mImageDataLength; /// The length of the surface data.
  uint32_t  mRow;             /// The row to which we're writing. (0-indexed)
  bool      mFlipVertically;  /// If true, write the rows from top to bottom.
};

class SurfaceSink;

/// A configuration struct for SurfaceSink.
struct SurfaceConfig
{
  using Filter = SurfaceSink;
  Decoder* mDecoder;           /// Which Decoder to use to allocate the surface.
  gfx::IntSize mOutputSize;    /// The size of the surface.
  gfx::SurfaceFormat mFormat;  /// The surface format (BGRA or BGRX).
  bool mFlipVertically;        /// If true, write the rows from bottom to top.
  Maybe<AnimationParams> mAnimParams; /// Given for animated images.
};

/**
 * A sink for normal (i.e., non-paletted) surfaces. It handles the allocation of
 * the surface and protects against buffer overflow. This sink should be used
 * for all non-animated images and for the first frame of animated images.
 *
 * Sinks must always be at the end of the SurfaceFilter chain.
 */
class SurfaceSink final : public AbstractSurfaceSink
{
public:
  nsresult Configure(const SurfaceConfig& aConfig);

protected:
  uint8_t* GetRowPointer() const override;
};

class PalettedSurfaceSink;

struct PalettedSurfaceConfig
{
  using Filter = PalettedSurfaceSink;
  Decoder* mDecoder;           /// Which Decoder to use to allocate the surface.
  gfx::IntSize mOutputSize;    /// The logical size of the surface.
  gfx::IntRect mFrameRect;     /// The surface subrect which contains data.
  gfx::SurfaceFormat mFormat;  /// The surface format (BGRA or BGRX).
  uint8_t mPaletteDepth;       /// The palette depth of this surface.
  bool mFlipVertically;        /// If true, write the rows from bottom to top.
  Maybe<AnimationParams> mAnimParams; /// Given for animated images.
};

/**
 * A sink for paletted surfaces. It handles the allocation of the surface and
 * protects against buffer overflow. This sink can be used for frames of
 * animated images except the first.
 *
 * Sinks must always be at the end of the SurfaceFilter chain.
 *
 * XXX(seth): We'll remove all support for paletted surfaces in bug 1247520,
 * which means we can remove PalettedSurfaceSink entirely.
 */
class PalettedSurfaceSink final : public AbstractSurfaceSink
{
public:
  bool IsValidPalettedPipe() const override { return true; }

  nsresult Configure(const PalettedSurfaceConfig& aConfig);

protected:
  uint8_t* GetRowPointer() const override;

private:
  /**
   * The surface subrect which contains data. Note that the surface size we
   * actually allocate is the size of the frame rect, not the logical size of
   * the surface.
   */
  gfx::IntRect mFrameRect;
};

} // namespace image
} // namespace mozilla

#endif // mozilla_image_SurfacePipe_h