summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/platform/image-decoders/png/png_image_decoder_test.cc
blob: b4fa63f3c6696ff095df44b1dcaeb1e75fb77f90 (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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/platform/image-decoders/png/png_image_decoder.h"

#include <memory>
#include "png.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/image-decoders/image_decoder_test_helpers.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
#include "third_party/skia/include/core/SkImage.h"

// /LayoutTests/images/resources/png-animated-idat-part-of-animation.png
// is modified in multiple tests to simulate erroneous PNGs. As a reference,
// the table below shows how the file is structured.
//
// Offset | 8     33    95    133   172   210   241   279   314   352   422
// -------------------------------------------------------------------------
// Chunk  | IHDR  acTL  fcTL  IDAT  fcTL  fdAT  fcTL  fdAT  fcTL  fdAT  IEND
//
// In between the acTL and fcTL there are two other chunks, PLTE and tRNS, but
// those are not specifically used in this test suite. The same holds for a
// tEXT chunk in between the last fdAT and IEND.
//
// In the current behavior of PNG image decoders, the 4 frames are detected when
// respectively 141, 249, 322 and 430 bytes are received. The first frame should
// be detected when the IDAT has been received, and non-first frames when the
// next fcTL or IEND chunk has been received. Note that all offsets are +8,
// because a chunk is identified by byte 4-7.

namespace blink {

namespace {

std::unique_ptr<ImageDecoder> CreatePNGDecoder(
    ImageDecoder::AlphaOption alpha_option) {
  return std::make_unique<PNGImageDecoder>(
      alpha_option, ImageDecoder::kDefaultBitDepth,
      ColorBehavior::TransformToSRGB(), ImageDecoder::kNoDecodedImageByteLimit);
}

std::unique_ptr<ImageDecoder> CreatePNGDecoder() {
  return CreatePNGDecoder(ImageDecoder::kAlphaNotPremultiplied);
}

std::unique_ptr<ImageDecoder> Create16BitPNGDecoder() {
  return std::make_unique<PNGImageDecoder>(
      ImageDecoder::kAlphaNotPremultiplied,
      ImageDecoder::kHighBitDepthToHalfFloat, ColorBehavior::Tag(),
      ImageDecoder::kNoDecodedImageByteLimit);
}

std::unique_ptr<ImageDecoder> CreatePNGDecoderWithPngData(
    const char* png_file) {
  auto decoder = CreatePNGDecoder();
  scoped_refptr<SharedBuffer> data = ReadFile(png_file);
  EXPECT_FALSE(data->IsEmpty());
  decoder->SetData(data.get(), true);
  return decoder;
}

void TestSize(const char* png_file, IntSize expected_size) {
  auto decoder = CreatePNGDecoderWithPngData(png_file);
  EXPECT_TRUE(decoder->IsSizeAvailable());
  EXPECT_EQ(expected_size, decoder->Size());
}

// Test whether querying for the size of the image works if we present the
// data byte by byte.
void TestSizeByteByByte(const char* png_file,
                        size_t bytes_needed_to_decode_size,
                        IntSize expected_size) {
  auto decoder = CreatePNGDecoder();
  scoped_refptr<SharedBuffer> data = ReadFile(png_file);
  ASSERT_FALSE(data->IsEmpty());
  ASSERT_LT(bytes_needed_to_decode_size, data->size());

  const char* source = data->Data();
  scoped_refptr<SharedBuffer> partial_data = SharedBuffer::Create();
  for (size_t length = 1; length <= bytes_needed_to_decode_size; length++) {
    partial_data->Append(source++, 1u);
    decoder->SetData(partial_data.get(), false);

    if (length < bytes_needed_to_decode_size) {
      EXPECT_FALSE(decoder->IsSizeAvailable());
      EXPECT_TRUE(decoder->Size().IsEmpty());
      EXPECT_FALSE(decoder->Failed());
    } else {
      EXPECT_TRUE(decoder->IsSizeAvailable());
      EXPECT_EQ(expected_size, decoder->Size());
    }
  }
  EXPECT_FALSE(decoder->Failed());
}

void WriteUint32(uint32_t val, png_byte* data) {
  data[0] = val >> 24;
  data[1] = val >> 16;
  data[2] = val >> 8;
  data[3] = val;
}

void TestRepetitionCount(const char* png_file, int expected_repetition_count) {
  auto decoder = CreatePNGDecoderWithPngData(png_file);
  // Decoding the frame count sets the number of repetitions as well.
  decoder->FrameCount();
  EXPECT_FALSE(decoder->Failed());
  EXPECT_EQ(expected_repetition_count, decoder->RepetitionCount());
}

struct PublicFrameInfo {
  TimeDelta duration;
  IntRect frame_rect;
  ImageFrame::AlphaBlendSource alpha_blend;
  ImageFrame::DisposalMethod disposal_method;
};

// This is the frame data for the following PNG image:
// /LayoutTests/images/resources/png-animated-idat-part-of-animation.png
static PublicFrameInfo g_png_animated_frame_info[] = {
    {TimeDelta::FromMilliseconds(500),
     {IntPoint(0, 0), IntSize(5, 5)},
     ImageFrame::kBlendAtopBgcolor,
     ImageFrame::kDisposeKeep},
    {TimeDelta::FromMilliseconds(900),
     {IntPoint(1, 1), IntSize(3, 1)},
     ImageFrame::kBlendAtopBgcolor,
     ImageFrame::kDisposeOverwriteBgcolor},
    {TimeDelta::FromMilliseconds(2000),
     {IntPoint(1, 2), IntSize(3, 2)},
     ImageFrame::kBlendAtopPreviousFrame,
     ImageFrame::kDisposeKeep},
    {TimeDelta::FromMilliseconds(1500),
     {IntPoint(1, 2), IntSize(3, 1)},
     ImageFrame::kBlendAtopBgcolor,
     ImageFrame::kDisposeKeep},
};

void CompareFrameWithExpectation(const PublicFrameInfo& expected,
                                 ImageDecoder* decoder,
                                 size_t index) {
  EXPECT_EQ(expected.duration, decoder->FrameDurationAtIndex(index));

  const auto* frame = decoder->DecodeFrameBufferAtIndex(index);
  ASSERT_TRUE(frame);

  EXPECT_EQ(expected.duration, frame->Duration());
  EXPECT_EQ(expected.frame_rect, frame->OriginalFrameRect());
  EXPECT_EQ(expected.disposal_method, frame->GetDisposalMethod());
  EXPECT_EQ(expected.alpha_blend, frame->GetAlphaBlendSource());
}

// This function removes |length| bytes at |offset|, and then calls FrameCount.
// It assumes the missing bytes should result in a failed decode because the
// parser jumps |length| bytes too far in the next chunk.
void TestMissingDataBreaksDecoding(const char* png_file,
                                   size_t offset,
                                   size_t length) {
  auto decoder = CreatePNGDecoder();
  scoped_refptr<SharedBuffer> data = ReadFile(png_file);
  ASSERT_FALSE(data->IsEmpty());

  scoped_refptr<SharedBuffer> invalid_data =
      SharedBuffer::Create(data->Data(), offset);
  invalid_data->Append(data->Data() + offset + length,
                       data->size() - offset - length);
  ASSERT_EQ(data->size() - length, invalid_data->size());

  decoder->SetData(invalid_data, true);
  decoder->FrameCount();
  EXPECT_TRUE(decoder->Failed());
}

// Verify that a decoder with a parse error converts to a static image.
static void ExpectStatic(ImageDecoder* decoder) {
  EXPECT_EQ(1u, decoder->FrameCount());
  EXPECT_FALSE(decoder->Failed());

  ImageFrame* frame = decoder->DecodeFrameBufferAtIndex(0);
  ASSERT_NE(nullptr, frame);
  EXPECT_EQ(ImageFrame::kFrameComplete, frame->GetStatus());
  EXPECT_FALSE(decoder->Failed());
  EXPECT_EQ(kAnimationNone, decoder->RepetitionCount());
}

// Decode up to the indicated fcTL offset and then provide an fcTL with the
// wrong chunk size (20 instead of 26).
void TestInvalidFctlSize(const char* png_file,
                         size_t offset_fctl,
                         size_t expected_frame_count,
                         bool should_fail) {
  scoped_refptr<SharedBuffer> data = ReadFile(png_file);
  ASSERT_FALSE(data->IsEmpty());

  auto decoder = CreatePNGDecoder();
  scoped_refptr<SharedBuffer> invalid_data =
      SharedBuffer::Create(data->Data(), offset_fctl);

  // Test if this gives the correct frame count, before the fcTL is parsed.
  decoder->SetData(invalid_data, false);
  EXPECT_EQ(expected_frame_count, decoder->FrameCount());
  ASSERT_FALSE(decoder->Failed());

  // Append the wrong size to the data stream
  png_byte size_chunk[4];
  WriteUint32(20, size_chunk);
  invalid_data->Append(reinterpret_cast<char*>(size_chunk), 4u);

  // Skip the size in the original data, but provide a truncated fcTL,
  // which is 4B of tag, 20B of data and 4B of CRC, totalling 28B.
  invalid_data->Append(data->Data() + offset_fctl + 4, 28u);
  // Append the rest of the data
  const size_t offset_post_fctl = offset_fctl + 38;
  invalid_data->Append(data->Data() + offset_post_fctl,
                       data->size() - offset_post_fctl);

  decoder->SetData(invalid_data, false);
  if (should_fail) {
    EXPECT_EQ(expected_frame_count, decoder->FrameCount());
    EXPECT_EQ(true, decoder->Failed());
  } else {
    ExpectStatic(decoder.get());
  }
}

// Verify that the decoder can successfully decode the first frame when
// initially only half of the frame data is received, resulting in a partially
// decoded image, and then the rest of the image data is received. Verify that
// the bitmap hashes of the two stages are different. Also verify that the final
// bitmap hash is equivalent to the hash when all data is provided at once.
//
// This verifies that the decoder correctly keeps track of where it stopped
// decoding when the image was not yet fully received.
void TestProgressiveDecodingContinuesAfterFullData(
    const char* png_file,
    size_t offset_mid_first_frame) {
  scoped_refptr<SharedBuffer> full_data = ReadFile(png_file);
  ASSERT_FALSE(full_data->IsEmpty());

  auto decoder_upfront = CreatePNGDecoder();
  decoder_upfront->SetData(full_data.get(), true);
  EXPECT_GE(decoder_upfront->FrameCount(), 1u);
  const ImageFrame* const frame_upfront =
      decoder_upfront->DecodeFrameBufferAtIndex(0);
  ASSERT_EQ(ImageFrame::kFrameComplete, frame_upfront->GetStatus());
  const unsigned hash_upfront = HashBitmap(frame_upfront->Bitmap());

  auto decoder = CreatePNGDecoder();
  scoped_refptr<SharedBuffer> partial_data =
      SharedBuffer::Create(full_data->Data(), offset_mid_first_frame);
  decoder->SetData(partial_data, false);

  EXPECT_EQ(1u, decoder->FrameCount());
  const ImageFrame* frame = decoder->DecodeFrameBufferAtIndex(0);
  EXPECT_EQ(frame->GetStatus(), ImageFrame::kFramePartial);
  const unsigned hash_partial = HashBitmap(frame->Bitmap());

  decoder->SetData(full_data.get(), true);
  frame = decoder->DecodeFrameBufferAtIndex(0);
  EXPECT_EQ(frame->GetStatus(), ImageFrame::kFrameComplete);
  const unsigned hash_full = HashBitmap(frame->Bitmap());

  EXPECT_FALSE(decoder->Failed());
  EXPECT_NE(hash_full, hash_partial);
  EXPECT_EQ(hash_full, hash_upfront);
}

}  // Anonymous namespace

// Animated PNG Tests

TEST(AnimatedPNGTests, sizeTest) {
  TestSize(
      "/images/resources/"
      "png-animated-idat-part-of-animation.png",
      IntSize(5, 5));
  TestSize(
      "/images/resources/"
      "png-animated-idat-not-part-of-animation.png",
      IntSize(227, 35));
}

TEST(AnimatedPNGTests, repetitionCountTest) {
  TestRepetitionCount(
      "/images/resources/"
      "png-animated-idat-part-of-animation.png",
      6u);
  // This is an "animated" image with only one frame, that is, the IDAT is
  // ignored and there is one fdAT frame. so it should be considered
  // non-animated.
  TestRepetitionCount(
      "/images/resources/"
      "png-animated-idat-not-part-of-animation.png",
      kAnimationNone);
}

// Test if the decoded metdata corresponds to the defined expectations
TEST(AnimatedPNGTests, MetaDataTest) {
  const char* png_file =
      "/images/resources/"
      "png-animated-idat-part-of-animation.png";
  constexpr size_t kExpectedFrameCount = 4;

  auto decoder = CreatePNGDecoderWithPngData(png_file);
  ASSERT_EQ(kExpectedFrameCount, decoder->FrameCount());
  for (size_t i = 0; i < kExpectedFrameCount; i++) {
    CompareFrameWithExpectation(g_png_animated_frame_info[i], decoder.get(), i);
  }
}

TEST(AnimatedPNGTests, EmptyFrame) {
  const char* png_file = "/images/resources/empty-frame.png";
  auto decoder = CreatePNGDecoderWithPngData(png_file);
  // Frame 0 is empty. Ensure that decoding frame 1 (which depends on frame 0)
  // fails (rather than crashing).
  EXPECT_EQ(2u, decoder->FrameCount());
  EXPECT_FALSE(decoder->Failed());

  ImageFrame* frame = decoder->DecodeFrameBufferAtIndex(1);
  EXPECT_TRUE(decoder->Failed());
  ASSERT_NE(nullptr, frame);
  EXPECT_EQ(ImageFrame::kFrameEmpty, frame->GetStatus());
}

TEST(AnimatedPNGTests, ByteByByteSizeAvailable) {
  TestSizeByteByByte(
      "/images/resources/"
      "png-animated-idat-part-of-animation.png",
      141u, IntSize(5, 5));
  TestSizeByteByByte(
      "/images/resources/"
      "png-animated-idat-not-part-of-animation.png",
      79u, IntSize(227, 35));
}

TEST(AnimatedPNGTests, ByteByByteMetaData) {
  const char* png_file =
      "/images/resources/"
      "png-animated-idat-part-of-animation.png";
  constexpr size_t kExpectedFrameCount = 4;

  // These are the byte offsets where each frame should have been parsed.
  // It boils down to the offset of the first fcTL / IEND after the last
  // frame data chunk, plus 8 bytes for recognition. The exception on this is
  // the first frame, which is reported when its first framedata is seen.
  size_t frame_offsets[kExpectedFrameCount] = {141, 249, 322, 430};

  auto decoder = CreatePNGDecoder();
  scoped_refptr<SharedBuffer> data = ReadFile(png_file);
  ASSERT_FALSE(data->IsEmpty());
  size_t frames_parsed = 0;

  const char* source = data->Data();
  scoped_refptr<SharedBuffer> partial_data = SharedBuffer::Create();
  for (size_t length = 1; length <= frame_offsets[kExpectedFrameCount - 1];
       length++) {
    partial_data->Append(source++, 1u);
    decoder->SetData(partial_data.get(), false);
    EXPECT_FALSE(decoder->Failed());
    if (length < frame_offsets[frames_parsed]) {
      EXPECT_EQ(frames_parsed, decoder->FrameCount());
    } else {
      ASSERT_EQ(frames_parsed + 1, decoder->FrameCount());
      CompareFrameWithExpectation(g_png_animated_frame_info[frames_parsed],
                                  decoder.get(), frames_parsed);
      frames_parsed++;
    }
  }
  EXPECT_EQ(kExpectedFrameCount, decoder->FrameCount());
  EXPECT_FALSE(decoder->Failed());
}

TEST(AnimatedPNGTests, TestRandomFrameDecode) {
  TestRandomFrameDecode(&CreatePNGDecoder,
                        "/images/resources/"
                        "png-animated-idat-part-of-animation.png",
                        2u);
}

TEST(AnimatedPNGTests, TestDecodeAfterReallocation) {
  TestDecodeAfterReallocatingData(&CreatePNGDecoder,
                                  "/images/resources/"
                                  "png-animated-idat-part-of-animation.png");
}

TEST(AnimatedPNGTests, ProgressiveDecode) {
  TestProgressiveDecoding(&CreatePNGDecoder,
                          "/images/resources/"
                          "png-animated-idat-part-of-animation.png",
                          13u);
}

TEST(AnimatedPNGTests, ParseAndDecodeByteByByte) {
  TestByteByByteDecode(&CreatePNGDecoder,
                       "/images/resources/"
                       "png-animated-idat-part-of-animation.png",
                       4u, 6u);
}

TEST(AnimatedPNGTests, FailureDuringParsing) {
  // Test the first fcTL in the stream. Because no frame data has been set at
  // this point, the expected frame count is zero. 95 bytes is just before the
  // first fcTL chunk, at which the first frame is detected. This is before the
  // IDAT, so it should be treated as a static image.
  TestInvalidFctlSize(
      "/images/resources/"
      "png-animated-idat-part-of-animation.png",
      95u, 0u, false);

  // Test for the third fcTL in the stream. This should see 1 frame before the
  // fcTL, and then fail when parsing it.
  TestInvalidFctlSize(
      "/images/resources/"
      "png-animated-idat-part-of-animation.png",
      241u, 1u, true);
}

TEST(AnimatedPNGTests, ActlErrors) {
  const char* png_file =
      "/images/resources/"
      "png-animated-idat-part-of-animation.png";
  scoped_refptr<SharedBuffer> data = ReadFile(png_file);
  ASSERT_FALSE(data->IsEmpty());

  const size_t kOffsetActl = 33u;
  const size_t kAcTLSize = 20u;
  {
    // Remove the acTL chunk from the stream. This results in a static image.
    scoped_refptr<SharedBuffer> no_actl_data =
        SharedBuffer::Create(data->Data(), kOffsetActl);
    no_actl_data->Append(data->Data() + kOffsetActl + kAcTLSize,
                         data->size() - kOffsetActl - kAcTLSize);

    auto decoder = CreatePNGDecoder();
    decoder->SetData(no_actl_data, true);
    EXPECT_EQ(1u, decoder->FrameCount());
    EXPECT_FALSE(decoder->Failed());
    EXPECT_EQ(kAnimationNone, decoder->RepetitionCount());
  }

  // Store the acTL for more tests.
  char ac_tl[kAcTLSize];
  memcpy(ac_tl, data->Data() + kOffsetActl, kAcTLSize);

  // Insert an extra acTL at a couple of different offsets.
  // Prior to the IDAT, this should result in a static image. After, this
  // should fail.
  const struct {
    size_t offset;
    bool should_fail;
  } kGRecs[] = {{8u, false},
                {kOffsetActl, false},
                {133u, false},
                {172u, true},
                {422u, true}};
  for (const auto& rec : kGRecs) {
    const size_t offset = rec.offset;
    scoped_refptr<SharedBuffer> extra_actl_data =
        SharedBuffer::Create(data->Data(), offset);
    extra_actl_data->Append(ac_tl, kAcTLSize);
    extra_actl_data->Append(data->Data() + offset, data->size() - offset);
    auto decoder = CreatePNGDecoder();
    decoder->SetData(extra_actl_data, true);
    EXPECT_EQ(rec.should_fail ? 0u : 1u, decoder->FrameCount());
    EXPECT_EQ(rec.should_fail, decoder->Failed());
  }

  // An acTL after IDAT is ignored.
  png_file =
      "/images/resources/"
      "cHRM_color_spin.png";
  {
    scoped_refptr<SharedBuffer> data2 = ReadFile(png_file);
    ASSERT_FALSE(data2->IsEmpty());
    const size_t kPostIDATOffset = 30971u;
    for (size_t times = 0; times < 2; times++) {
      scoped_refptr<SharedBuffer> extra_actl_data =
          SharedBuffer::Create(data2->Data(), kPostIDATOffset);
      for (size_t i = 0; i < times; i++)
        extra_actl_data->Append(ac_tl, kAcTLSize);
      extra_actl_data->Append(data2->Data() + kPostIDATOffset,
                              data2->size() - kPostIDATOffset);

      auto decoder = CreatePNGDecoder();
      decoder->SetData(extra_actl_data, true);
      EXPECT_EQ(1u, decoder->FrameCount());
      EXPECT_FALSE(decoder->Failed());
      EXPECT_EQ(kAnimationNone, decoder->RepetitionCount());
      EXPECT_NE(nullptr, decoder->DecodeFrameBufferAtIndex(0));
      EXPECT_FALSE(decoder->Failed());
    }
  }
}

TEST(AnimatedPNGTests, fdatBeforeIdat) {
  const char* png_file =
      "/images/resources/"
      "png-animated-idat-not-part-of-animation.png";
  scoped_refptr<SharedBuffer> data = ReadFile(png_file);
  ASSERT_FALSE(data->IsEmpty());

  // Insert fcTL and fdAT prior to the IDAT
  const size_t kIdatOffset = 71u;
  scoped_refptr<SharedBuffer> modified_data =
      SharedBuffer::Create(data->Data(), kIdatOffset);
  // Copy fcTL and fdAT
  const size_t kFctlPlusFdatSize = 38u + 1566u;
  modified_data->Append(data->Data() + 2519u, kFctlPlusFdatSize);
  // Copy IDAT
  modified_data->Append(data->Data() + kIdatOffset, 2448u);
  // Copy the remaining
  modified_data->Append(data->Data() + 4123u, 39u + 12u);
  // Data has just been rearranged.
  ASSERT_EQ(data->size(), modified_data->size());

  {
    // This broken APNG will be treated as a static png.
    auto decoder = CreatePNGDecoder();
    decoder->SetData(modified_data.get(), true);
    ExpectStatic(decoder.get());
  }

  {
    // Remove the acTL from the modified image. It now has fdAT before
    // IDAT, but no acTL, so fdAT should be ignored.
    const size_t kOffsetActl = 33u;
    const size_t kAcTLSize = 20u;
    scoped_refptr<SharedBuffer> modified_data2 =
        SharedBuffer::Create(modified_data->Data(), kOffsetActl);
    modified_data2->Append(modified_data->Data() + kOffsetActl + kAcTLSize,
                           modified_data->size() - kOffsetActl - kAcTLSize);
    auto decoder = CreatePNGDecoder();
    decoder->SetData(modified_data2.get(), true);
    ExpectStatic(decoder.get());

    // Likewise, if an acTL follows the fdAT, it is ignored.
    const size_t kInsertionOffset = kIdatOffset + kFctlPlusFdatSize - kAcTLSize;
    scoped_refptr<SharedBuffer> modified_data3 =
        SharedBuffer::Create(modified_data2->Data(), kInsertionOffset);
    modified_data3->Append(data->Data() + kOffsetActl, kAcTLSize);
    modified_data3->Append(modified_data2->Data() + kInsertionOffset,
                           modified_data2->size() - kInsertionOffset);
    decoder = CreatePNGDecoder();
    decoder->SetData(modified_data3.get(), true);
    ExpectStatic(decoder.get());
  }
}

TEST(AnimatedPNGTests, IdatSizeMismatch) {
  // The default image must fill the image
  const char* png_file =
      "/images/resources/"
      "png-animated-idat-part-of-animation.png";
  scoped_refptr<SharedBuffer> data = ReadFile(png_file);
  ASSERT_FALSE(data->IsEmpty());

  const size_t kFctlOffset = 95u;
  scoped_refptr<SharedBuffer> modified_data =
      SharedBuffer::Create(data->Data(), kFctlOffset);
  const size_t kFctlSize = 38u;
  png_byte fctl[kFctlSize];
  memcpy(fctl, data->Data() + kFctlOffset, kFctlSize);
  // Set the height to a smaller value, so it does not fill the image.
  WriteUint32(3, fctl + 16);
  // Correct the crc
  WriteUint32(3210324191, fctl + 34);
  modified_data->Append((const char*)fctl, kFctlSize);
  const size_t kAfterFctl = kFctlOffset + kFctlSize;
  modified_data->Append(data->Data() + kAfterFctl, data->size() - kAfterFctl);

  auto decoder = CreatePNGDecoder();
  decoder->SetData(modified_data.get(), true);
  ExpectStatic(decoder.get());
}

// Originally, the third frame has an offset of (1,2) and a size of (3,2). By
// changing the offset to (4,4), the frame rect is no longer within the image
// size of 5x5. This results in a failure.
TEST(AnimatedPNGTests, VerifyFrameOutsideImageSizeFails) {
  const char* png_file =
      "/images/resources/"
      "png-animated-idat-part-of-animation.png";
  scoped_refptr<SharedBuffer> data = ReadFile(png_file);
  auto decoder = CreatePNGDecoder();
  ASSERT_FALSE(data->IsEmpty());

  const size_t kOffsetThirdFctl = 241;
  scoped_refptr<SharedBuffer> modified_data =
      SharedBuffer::Create(data->Data(), kOffsetThirdFctl);
  const size_t kFctlSize = 38u;
  png_byte fctl[kFctlSize];
  memcpy(fctl, data->Data() + kOffsetThirdFctl, kFctlSize);
  // Modify offset and crc.
  WriteUint32(4, fctl + 20u);
  WriteUint32(4, fctl + 24u);
  WriteUint32(3700322018, fctl + 34u);

  modified_data->Append(const_cast<const char*>(reinterpret_cast<char*>(fctl)),
                        kFctlSize);
  modified_data->Append(data->Data() + kOffsetThirdFctl + kFctlSize,
                        data->size() - kOffsetThirdFctl - kFctlSize);

  decoder->SetData(modified_data, true);

  IntSize expected_size(5, 5);
  EXPECT_TRUE(decoder->IsSizeAvailable());
  EXPECT_EQ(expected_size, decoder->Size());

  const size_t kExpectedFrameCount = 0;
  EXPECT_EQ(kExpectedFrameCount, decoder->FrameCount());
  EXPECT_TRUE(decoder->Failed());
}

TEST(AnimatedPNGTests, ProgressiveDecodingContinuesAfterFullData) {
  // 160u is a randomly chosen offset in the IDAT chunk of the first frame.
  TestProgressiveDecodingContinuesAfterFullData(
      "/images/resources/"
      "png-animated-idat-part-of-animation.png",
      160u);
}

TEST(AnimatedPNGTests, RandomDecodeAfterClearFrameBufferCache) {
  TestRandomDecodeAfterClearFrameBufferCache(
      &CreatePNGDecoder,
      "/images/resources/"
      "png-animated-idat-part-of-animation.png",
      2u);
}

TEST(AnimatedPNGTests, VerifyAlphaBlending) {
  TestAlphaBlending(&CreatePNGDecoder,
                    "/images/resources/"
                    "png-animated-idat-part-of-animation.png");
}

// This tests if the frame count gets set correctly when parsing FrameCount
// fails in one of the parsing queries.
//
// First, enough data is provided such that two frames should be registered.
// The decoder should at this point not be in the failed status.
//
// Then, we provide the rest of the data except for the last IEND chunk, but
// tell the decoder that this is all the data we have.  The frame count should
// be three, since one extra frame should be discovered. The fourth frame
// should *not* be registered since the reader should not be able to determine
// where the frame ends. The decoder should *not* be in the failed state since
// there are three frames which can be shown.
// Attempting to decode the third frame should fail, since the file is
// truncated.
TEST(AnimatedPNGTests, FailureMissingIendChunk) {
  scoped_refptr<SharedBuffer> full_data = ReadFile(
      "/images/resources/"
      "png-animated-idat-part-of-animation.png");
  ASSERT_FALSE(full_data->IsEmpty());
  auto decoder = CreatePNGDecoder();

  const size_t kOffsetTwoFrames = 249;
  const size_t kExpectedFramesAfter249Bytes = 2;
  scoped_refptr<SharedBuffer> temp_data =
      SharedBuffer::Create(full_data->Data(), kOffsetTwoFrames);
  decoder->SetData(temp_data.get(), false);
  EXPECT_EQ(kExpectedFramesAfter249Bytes, decoder->FrameCount());
  EXPECT_FALSE(decoder->Failed());

  // Provide the rest of the data except for the last IEND chunk.
  const size_t kExpectedFramesAfterAllExcept12Bytes = 3;
  temp_data = SharedBuffer::Create(full_data->Data(), full_data->size() - 12);
  decoder->SetData(temp_data.get(), true);
  ASSERT_EQ(kExpectedFramesAfterAllExcept12Bytes, decoder->FrameCount());

  for (size_t i = 0; i < kExpectedFramesAfterAllExcept12Bytes; i++) {
    EXPECT_FALSE(decoder->Failed());
    decoder->DecodeFrameBufferAtIndex(i);
  }

  EXPECT_TRUE(decoder->Failed());
}

// Verify that a malformatted PNG, where the IEND appears before any frame data
// (IDAT), invalidates the decoder.
TEST(AnimatedPNGTests, VerifyIENDBeforeIDATInvalidatesDecoder) {
  scoped_refptr<SharedBuffer> full_data = ReadFile(
      "/images/resources/"
      "png-animated-idat-part-of-animation.png");
  ASSERT_FALSE(full_data->IsEmpty());
  auto decoder = CreatePNGDecoder();

  const size_t kOffsetIDAT = 133;
  scoped_refptr<SharedBuffer> data =
      SharedBuffer::Create(full_data->Data(), kOffsetIDAT);
  data->Append(full_data->Data() + full_data->size() - 12u, 12u);
  data->Append(full_data->Data() + kOffsetIDAT,
               full_data->size() - kOffsetIDAT);
  decoder->SetData(data.get(), true);

  const size_t kExpectedFrameCount = 0u;
  EXPECT_EQ(kExpectedFrameCount, decoder->FrameCount());
  EXPECT_TRUE(decoder->Failed());
}

// All IDAT chunks must be before all fdAT chunks
TEST(AnimatedPNGTests, MixedDataChunks) {
  const char* png_file =
      "/images/resources/"
      "png-animated-idat-part-of-animation.png";
  scoped_refptr<SharedBuffer> full_data = ReadFile(png_file);
  ASSERT_FALSE(full_data->IsEmpty());

  // Add an extra fdAT after the first IDAT, skipping fcTL.
  const size_t kPostIDAT = 172u;
  scoped_refptr<SharedBuffer> data =
      SharedBuffer::Create(full_data->Data(), kPostIDAT);
  const size_t kFcTLSize = 38u;
  const size_t kFdATSize = 31u;
  png_byte fd_at[kFdATSize];
  memcpy(fd_at, full_data->Data() + kPostIDAT + kFcTLSize, kFdATSize);
  // Modify the sequence number
  WriteUint32(1u, fd_at + 8);
  data->Append((const char*)fd_at, kFdATSize);
  const size_t kIENDOffset = 422u;
  data->Append(full_data->Data() + kIENDOffset,
               full_data->size() - kIENDOffset);
  auto decoder = CreatePNGDecoder();
  decoder->SetData(data.get(), true);
  decoder->FrameCount();
  EXPECT_TRUE(decoder->Failed());

  // Insert an IDAT after an fdAT.
  const size_t kPostfdAT = kPostIDAT + kFcTLSize + kFdATSize;
  data = SharedBuffer::Create(full_data->Data(), kPostfdAT);
  const size_t kIDATOffset = 133u;
  data->Append(full_data->Data() + kIDATOffset, kPostIDAT - kIDATOffset);
  // Append the rest.
  data->Append(full_data->Data() + kPostIDAT, full_data->size() - kPostIDAT);
  decoder = CreatePNGDecoder();
  decoder->SetData(data.get(), true);
  decoder->FrameCount();
  EXPECT_TRUE(decoder->Failed());
}

// Verify that erroneous values for the disposal method and alpha blending
// cause the decoder to fail.
TEST(AnimatedPNGTests, VerifyInvalidDisposalAndBlending) {
  const char* png_file =
      "/images/resources/"
      "png-animated-idat-part-of-animation.png";
  scoped_refptr<SharedBuffer> full_data = ReadFile(png_file);
  ASSERT_FALSE(full_data->IsEmpty());
  auto decoder = CreatePNGDecoder();

  // The disposal byte in the frame control chunk is the 24th byte, alpha
  // blending the 25th. |kOffsetDisposalOp| is 241 bytes to get to the third
  // fctl chunk, 8 bytes to skip the length and tag bytes, and 24 bytes to get
  // to the disposal op.
  //
  // Write invalid values to the disposal and alpha blending byte, correct the
  // crc and append the rest of the buffer.
  const size_t kOffsetDisposalOp = 241 + 8 + 24;
  scoped_refptr<SharedBuffer> data =
      SharedBuffer::Create(full_data->Data(), kOffsetDisposalOp);
  png_byte disposal_and_blending[6u];
  disposal_and_blending[0] = 7;
  disposal_and_blending[1] = 9;
  WriteUint32(2408835439u, disposal_and_blending + 2u);
  data->Append(reinterpret_cast<char*>(disposal_and_blending), 6u);
  data->Append(full_data->Data() + kOffsetDisposalOp + 6u,
               full_data->size() - kOffsetDisposalOp - 6u);

  decoder->SetData(data.get(), true);
  decoder->FrameCount();
  ASSERT_TRUE(decoder->Failed());
}

// This test verifies that the following situation does not invalidate the
// decoder:
// - Frame 0 is decoded progressively, but there's not enough data to fully
//   decode it.
// - The rest of the image data is received.
// - Frame X, with X > 0, and X does not depend on frame 0, is decoded.
// - Frame 0 is decoded.
// This is a tricky case since the decoder resets the png struct for each frame,
// and this test verifies that it does not break the decoding of frame 0, even
// though it already started in the first call.
TEST(AnimatedPNGTests, VerifySuccessfulFirstFrameDecodeAfterLaterFrame) {
  const char* png_file =
      "/images/resources/"
      "png-animated-three-independent-frames.png";
  auto decoder = CreatePNGDecoder();
  scoped_refptr<SharedBuffer> full_data = ReadFile(png_file);
  ASSERT_FALSE(full_data->IsEmpty());

  // 160u is a randomly chosen offset in the IDAT chunk of the first frame.
  const size_t kMiddleFirstFrame = 160u;
  scoped_refptr<SharedBuffer> data =
      SharedBuffer::Create(full_data->Data(), kMiddleFirstFrame);
  decoder->SetData(data.get(), false);

  ASSERT_EQ(1u, decoder->FrameCount());
  ASSERT_EQ(ImageFrame::kFramePartial,
            decoder->DecodeFrameBufferAtIndex(0)->GetStatus());

  decoder->SetData(full_data.get(), true);
  ASSERT_EQ(3u, decoder->FrameCount());
  ASSERT_EQ(ImageFrame::kFrameComplete,
            decoder->DecodeFrameBufferAtIndex(1)->GetStatus());
  // The point is that this call does not decode frame 0, which it won't do if
  // it does not have it as its required previous frame.
  ASSERT_EQ(kNotFound,
            decoder->DecodeFrameBufferAtIndex(1)->RequiredPreviousFrameIndex());

  EXPECT_EQ(ImageFrame::kFrameComplete,
            decoder->DecodeFrameBufferAtIndex(0)->GetStatus());
  EXPECT_FALSE(decoder->Failed());
}

// If the decoder attempts to decode a non-first frame which is subset and
// independent, it needs to discard its png_struct so it can use a modified
// IHDR. Test this by comparing a decode of frame 1 after frame 0 to a decode
// of frame 1 without decoding frame 0.
TEST(AnimatedPNGTests, DecodeFromIndependentFrame) {
  const char* png_file =
      "/images/resources/"
      "png-animated-idat-part-of-animation.png";
  scoped_refptr<SharedBuffer> original_data = ReadFile(png_file);
  ASSERT_FALSE(original_data->IsEmpty());

  // This file almost fits the bill. Modify it to dispose frame 0, making
  // frame 1 independent.
  const size_t kDisposeOffset = 127u;
  auto data = SharedBuffer::Create(original_data->Data(), kDisposeOffset);
  // 1 Corresponds to APNG_DISPOSE_OP_BACKGROUND
  const char kOne = '\001';
  data->Append(&kOne, 1u);
  // No need to modify the blend op
  data->Append(original_data->Data() + kDisposeOffset + 1, 1u);
  // Modify the CRC
  png_byte crc[4];
  WriteUint32(2226670956, crc);
  data->Append(reinterpret_cast<const char*>(crc), 4u);
  data->Append(original_data->Data() + data->size(),
               original_data->size() - data->size());
  ASSERT_EQ(original_data->size(), data->size());

  auto decoder = CreatePNGDecoder();
  decoder->SetData(data.get(), true);

  ASSERT_EQ(4u, decoder->FrameCount());
  ASSERT_FALSE(decoder->Failed());

  auto* frame = decoder->DecodeFrameBufferAtIndex(0);
  ASSERT_TRUE(frame);
  ASSERT_EQ(ImageFrame::kDisposeOverwriteBgcolor, frame->GetDisposalMethod());

  frame = decoder->DecodeFrameBufferAtIndex(1);
  ASSERT_TRUE(frame);
  ASSERT_FALSE(decoder->Failed());
  ASSERT_NE(IntRect({}, decoder->Size()), frame->OriginalFrameRect());
  ASSERT_EQ(kNotFound, frame->RequiredPreviousFrameIndex());

  const auto hash = HashBitmap(frame->Bitmap());

  // Now decode starting from frame 1.
  decoder = CreatePNGDecoder();
  decoder->SetData(data.get(), true);

  frame = decoder->DecodeFrameBufferAtIndex(1);
  ASSERT_TRUE(frame);
  EXPECT_EQ(hash, HashBitmap(frame->Bitmap()));
}

// If the first frame is subset from IHDR (only allowed if the first frame is
// not the default image), the decoder has to destroy the png_struct it used
// for parsing so it can use a modified IHDR.
TEST(AnimatedPNGTests, SubsetFromIHDR) {
  const char* png_file =
      "/images/resources/"
      "png-animated-idat-not-part-of-animation.png";
  scoped_refptr<SharedBuffer> original_data = ReadFile(png_file);
  ASSERT_FALSE(original_data->IsEmpty());

  const size_t kFcTLOffset = 2519u;
  auto data = SharedBuffer::Create(original_data->Data(), kFcTLOffset);

  const size_t kFcTLSize = 38u;
  png_byte fc_tl[kFcTLSize];
  memcpy(fc_tl, original_data->Data() + kFcTLOffset, kFcTLSize);
  // Modify to have a subset frame (yOffset 1, height 34 out of 35).
  WriteUint32(34, fc_tl + 16u);
  WriteUint32(1, fc_tl + 24u);
  WriteUint32(3972842751, fc_tl + 34u);
  data->Append(reinterpret_cast<const char*>(fc_tl), kFcTLSize);

  // Append the rest of the data.
  // Note: If PNGImageDecoder changes to reject an image with too many
  // rows, the fdAT data will need to be modified as well.
  data->Append(original_data->Data() + kFcTLOffset + kFcTLSize,
               original_data->size() - data->size());
  ASSERT_EQ(original_data->size(), data->size());

  // This will test both byte by byte and using the full data, and compare.
  TestByteByByteDecode(CreatePNGDecoder, data.get(), 1, kAnimationNone);
}

TEST(AnimatedPNGTests, Offset) {
  const char* png_file = "/images/resources/apng18.png";
  scoped_refptr<SharedBuffer> original_data = ReadFile(png_file);
  ASSERT_FALSE(original_data->IsEmpty());

  Vector<unsigned> baseline_hashes;
  CreateDecodingBaseline(CreatePNGDecoder, original_data.get(),
                         &baseline_hashes);
  constexpr size_t kExpectedFrameCount = 13;
  ASSERT_EQ(kExpectedFrameCount, baseline_hashes.size());

  constexpr size_t kOffset = 37;
  char buffer[kOffset] = {};

  auto data = SharedBuffer::Create(buffer, kOffset);
  data->Append(*original_data.get());

  // Use the same defaults as CreatePNGDecoder, except use the (arbitrary)
  // non-zero offset.
  auto decoder = std::make_unique<PNGImageDecoder>(
      ImageDecoder::kAlphaNotPremultiplied, ImageDecoder::kDefaultBitDepth,
      ColorBehavior::TransformToSRGB(), ImageDecoder::kNoDecodedImageByteLimit,
      kOffset);
  decoder->SetData(data, true);
  ASSERT_EQ(kExpectedFrameCount, decoder->FrameCount());

  for (size_t i = 0; i < kExpectedFrameCount; ++i) {
    auto* frame = decoder->DecodeFrameBufferAtIndex(i);
    EXPECT_EQ(baseline_hashes[i], HashBitmap(frame->Bitmap()));
  }
}

TEST(AnimatedPNGTests, ExtraChunksBeforeIHDR) {
  const char* png_file = "/images/resources/apng18.png";
  scoped_refptr<SharedBuffer> original_data = ReadFile(png_file);
  ASSERT_FALSE(original_data->IsEmpty());

  Vector<unsigned> baseline_hashes;
  CreateDecodingBaseline(CreatePNGDecoder, original_data.get(),
                         &baseline_hashes);
  constexpr size_t kExpectedFrameCount = 13;
  ASSERT_EQ(kExpectedFrameCount, baseline_hashes.size());

  constexpr size_t kPngSignatureSize = 8;
  auto data = SharedBuffer::Create(original_data->Data(), kPngSignatureSize);

  // Arbitrary chunk of data.
  constexpr size_t kExtraChunkSize = 13;
  constexpr png_byte kExtraChunk[kExtraChunkSize] = {
      0, 0, 0, 1, 't', 'R', 'c', 'N', 68, 82, 0, 87, 10};
  data->Append(reinterpret_cast<const char*>(kExtraChunk), kExtraChunkSize);

  // Append the rest of the data from the original.
  data->Append(original_data->Data() + kPngSignatureSize,
               original_data->size() - kPngSignatureSize);
  ASSERT_EQ(original_data->size() + kExtraChunkSize, data->size());

  auto decoder = CreatePNGDecoder();
  decoder->SetData(data, true);
  ASSERT_EQ(kExpectedFrameCount, decoder->FrameCount());

  for (size_t i = 0; i < kExpectedFrameCount; ++i) {
    auto* frame = decoder->DecodeFrameBufferAtIndex(i);
    EXPECT_EQ(baseline_hashes[i], HashBitmap(frame->Bitmap()));
  }
}

// Static PNG tests

TEST(StaticPNGTests, repetitionCountTest) {
  TestRepetitionCount("/images/resources/png-simple.png", kAnimationNone);
}

TEST(StaticPNGTests, sizeTest) {
  TestSize("/images/resources/png-simple.png", IntSize(111, 29));
}

TEST(StaticPNGTests, MetaDataTest) {
  const size_t kExpectedFrameCount = 1;
  const TimeDelta kExpectedDuration;
  auto decoder =
      CreatePNGDecoderWithPngData("/images/resources/png-simple.png");
  EXPECT_EQ(kExpectedFrameCount, decoder->FrameCount());
  EXPECT_EQ(kExpectedDuration, decoder->FrameDurationAtIndex(0));
}

TEST(StaticPNGTests, InvalidIHDRChunk) {
  TestMissingDataBreaksDecoding("/images/resources/png-simple.png", 20u, 2u);
}

TEST(StaticPNGTests, ProgressiveDecoding) {
  TestProgressiveDecoding(&CreatePNGDecoder, "/images/resources/png-simple.png",
                          11u);
}

TEST(StaticPNGTests, ProgressiveDecodingContinuesAfterFullData) {
  TestProgressiveDecodingContinuesAfterFullData(
      "/images/resources/png-simple.png", 1000u);
}

struct PNGSample {
  String filename;
  String color_space;
  bool is_transparent;
  bool is_high_bit_depth;
  scoped_refptr<SharedBuffer> png_contents;
  std::vector<float> expected_pixels;
};

static void TestHighBitDepthPNGDecoding(const PNGSample& png_sample,
                                        ImageDecoder* decoder) {
  scoped_refptr<SharedBuffer> png = png_sample.png_contents;
  ASSERT_TRUE(png.get());
  decoder->SetData(png.get(), true);
  ASSERT_TRUE(decoder->IsSizeAvailable());
  ASSERT_TRUE(decoder->IsDecodedSizeAvailable());

  IntSize size(2, 2);
  ASSERT_EQ(size, decoder->Size());
  ASSERT_EQ(size, decoder->DecodedSize());
  ASSERT_EQ(true, decoder->ImageIsHighBitDepth());

  ASSERT_TRUE(decoder->FrameIsReceivedAtIndex(0));
  ASSERT_EQ(size, decoder->FrameSizeAtIndex(0));

  ASSERT_EQ(1u, decoder->FrameCount());
  ASSERT_EQ(kAnimationNone, decoder->RepetitionCount());

  auto* frame = decoder->DecodeFrameBufferAtIndex(0);
  ASSERT_TRUE(frame);
  ASSERT_EQ(ImageFrame::kFrameComplete, frame->GetStatus());
  ASSERT_EQ(ImageFrame::kRGBA_F16, frame->GetPixelFormat());

  sk_sp<SkImage> image = frame->FinalizePixelsAndGetImage();
  ASSERT_TRUE(image);

  ASSERT_EQ(2, image->width());
  ASSERT_EQ(2, image->height());
  ASSERT_EQ(kRGBA_F16_SkColorType, image->colorType());

  // Readback pixels and convert color components from half float to float.
  SkImageInfo info =
      SkImageInfo::Make(2, 2, kRGBA_F16_SkColorType, kUnpremul_SkAlphaType,
                        image->refColorSpace());
  std::unique_ptr<uint8_t[]> decoded_pixels(
      new uint8_t[info.computeMinByteSize()]());
  ASSERT_TRUE(
      image->readPixels(info, decoded_pixels.get(), info.minRowBytes(), 0, 0));

  float decoded_pixels_float_32[16];
  ASSERT_TRUE(skcms_Transform(
      decoded_pixels.get(), skcms_PixelFormat_RGBA_hhhh,
      skcms_AlphaFormat_Unpremul, nullptr, decoded_pixels_float_32,
      skcms_PixelFormat_RGBA_ffff, skcms_AlphaFormat_Unpremul, nullptr, 4));

  std::vector<float> expected_pixels = png_sample.expected_pixels;
  bool test_succeed = true;
  const float decoding_tolerance = 0.001;
  for (int i = 0; i < 16; i++) {
    if (fabs(decoded_pixels_float_32[i] - expected_pixels[i]) >
        decoding_tolerance) {
      DLOG(DCHECK) << "Pixel comparison failed. File: " << png_sample.filename
                   << ", component index: " << i
                   << ", actual: " << decoded_pixels_float_32[i]
                   << ", expected: " << expected_pixels[i]
                   << ", tolerance: " << decoding_tolerance;
      test_succeed = false;
    }
  }
  ASSERT_TRUE(test_succeed);
}

static void FillPNGSamplesSourcePixels(std::vector<PNGSample>& png_samples) {
  // Color components of opaque and transparent 16 bit PNG, read with libpng
  // in BigEndian and scaled to [0,1]. The values are read from non-interlaced
  // samples, but used for both interlaced and non-interlaced test cases.
  // The sample pngs were all created by color converting the 8 bit sRGB source
  // in Adobe Photoshop 18. The only exception is e-sRGB test case, for which
  // Adobe software created a non-matching color profile (see crbug.com/874939).
  // Hence, SkEncoder was used to generate the e-sRGB file (see the skia fiddle
  // here: https://fiddle.skia.org/c/17beedfd66dac1ec930f0c414c50f847).
  static const std::vector<float> source_pixels_opaque_srgb = {
      0.4986953536, 0.5826657511, 0.7013199054, 1,   // Top left pixel
      0.907988098,  0.8309605554, 0.492011902,  1,   // Top right pixel
      0.6233157855, 0.9726558328, 0.9766536965, 1,   // Bottom left pixel
      0.8946517128, 0.9663080797, 0.9053025101, 1};  // Bottom right pixel
  static const std::vector<float> source_pixels_opaque_adobe_rgb = {
      0.4448004883, 0.5216296635, 0.6506294347, 1,   // Top left pixel
      0.8830548562, 0.7978179599, 0.4323186084, 1,   // Top right pixel
      0.6841992828, 0.9704280156, 0.9711299306, 1,   // Bottom left pixel
      0.8874799725, 0.96099794,   0.8875715267, 1};  // Bottom right pixel
  static const std::vector<float> source_pixels_opaque_p3 = {
      0.515648127,  0.5802243076, 0.6912489509, 1,   // Top left pixel
      0.8954146639, 0.8337987335, 0.5691767758, 1,   // Top right pixel
      0.772121767,  0.9671625849, 0.973510338,  1,   // Bottom left pixel
      0.9118944076, 0.9645685512, 0.9110704204, 1};  // Bottom right pixel
  static const std::vector<float> source_pixels_opaque_e_srgb = {
      0.6977539062, 0.5839843750, 0.4978027344, 1,   // Top left pixel
      0.4899902344, 0.8310546875, 0.9096679688, 1,   // Top right pixel
      0.9760742188, 0.9721679688, 0.6230468750, 1,   // Bottom left pixel
      0.9057617188, 0.9643554688, 0.8940429688, 1};  // Bottom right pixel
  static const std::vector<float> source_pixels_opaque_prophoto = {
      0.5032883192, 0.5191271839, 0.6309147784, 1,   // Top left pixel
      0.8184176394, 0.8002899214, 0.5526970321, 1,   // Top right pixel
      0.842526894,  0.945616846,  0.9667048142, 1,   // Bottom left pixel
      0.9119554437, 0.9507133593, 0.9001754788, 1};  // Bottom right pixel
  static const std::vector<float> source_pixels_opaque_rec2020 = {
      0.5390554665, 0.5766842145, 0.6851758602, 1,   // Top left pixel
      0.871061265,  0.831326772,  0.5805294881, 1,   // Top right pixel
      0.8386205844, 0.9599603265, 0.9727168688, 1,   // Bottom left pixel
      0.9235217823, 0.9611200122, 0.9112840467, 1};  // Bottom right pixel

  static const std::vector<float> source_pixels_transparent_srgb = {
      0.3733272297,  0.4783093004, 0.6266422522, 0.8,   // Top left pixel
      0.8466468299,  0.7182879377, 0.153322652,  0.6,   // Top right pixel
      0.05831998169, 0.9316395819, 0.9416495003, 0.4,   // Bottom left pixel
      0.4733043412,  0.8316319524, 0.5266346227, 0.2};  // Bottom right pixel
  static const std::vector<float> source_pixels_transparent_adobe_rgb = {
      0.305943389,  0.4019836728, 0.5632867933,  0.8,   // Top left pixel
      0.8051117723, 0.6630197604, 0.05374227512, 0.6,   // Top right pixel
      0.210482948,  0.926115816,  0.9278248264,  0.4,   // Bottom left pixel
      0.4374456397, 0.8050812543, 0.4379644465,  0.2};  // Bottom right pixel
  static const std::vector<float> source_pixels_transparent_p3 = {
      0.3945372702, 0.475257496,  0.6140383001, 0.8,   // Top left pixel
      0.8257114519, 0.7230182345, 0.2819256886, 0.6,   // Top right pixel
      0.4302738994, 0.9179064622, 0.933806363,  0.4,   // Bottom left pixel
      0.5595330739, 0.8228122377, 0.5554436561, 0.2};  // Bottom right pixel
  static const std::vector<float> source_pixels_transparent_e_srgb = {
      0.6230468750, 0.4782714844, 0.3723144531, 0.8,   // Top left pixel
      0.1528320312, 0.7172851562, 0.8466796875, 0.6,   // Top right pixel
      0.9409179688, 0.9331054688, 0.0588073730, 0.4,   // Bottom left pixel
      0.5253906250, 0.8310546875, 0.4743652344, 0.2};  // Bottom right pixel
  static const std::vector<float> source_pixels_transparent_prophoto = {
      0.379064622,  0.3988708324, 0.5386282139, 0.8,   // Top left pixel
      0.6973525597, 0.6671396963, 0.2544289311, 0.6,   // Top right pixel
      0.6063477531, 0.864103151,  0.9168078126, 0.4,   // Bottom left pixel
      0.5598077363, 0.7536278325, 0.5009384298, 0.2};  // Bottom right pixel
  static const std::vector<float> source_pixels_transparent_rec2020 = {
      0.4237735561, 0.4708323796, 0.6064698253, 0.8,   // Top left pixel
      0.7851224537, 0.7188677806, 0.3008468757, 0.6,   // Top right pixel
      0.5965819791, 0.8999618524, 0.9318532082, 0.4,   // Bottom left pixel
      0.6176699474, 0.805600061,  0.5565117876, 0.2};  // Bottom right pixel

  for (PNGSample& png_sample : png_samples) {
    if (png_sample.color_space == "sRGB") {
      png_sample.expected_pixels = png_sample.is_transparent
                                       ? source_pixels_transparent_srgb
                                       : source_pixels_opaque_srgb;
    } else if (png_sample.color_space == "AdobeRGB") {
      png_sample.expected_pixels = png_sample.is_transparent
                                       ? source_pixels_transparent_adobe_rgb
                                       : source_pixels_opaque_adobe_rgb;
    } else if (png_sample.color_space == "DisplayP3") {
      png_sample.expected_pixels = png_sample.is_transparent
                                       ? source_pixels_transparent_p3
                                       : source_pixels_opaque_p3;
    } else if (png_sample.color_space == "e-sRGB") {
      png_sample.expected_pixels = png_sample.is_transparent
                                       ? source_pixels_transparent_e_srgb
                                       : source_pixels_opaque_e_srgb;
    } else if (png_sample.color_space == "ProPhoto") {
      png_sample.expected_pixels = png_sample.is_transparent
                                       ? source_pixels_transparent_prophoto
                                       : source_pixels_opaque_prophoto;
    } else if (png_sample.color_space == "Rec2020") {
      png_sample.expected_pixels = png_sample.is_transparent
                                       ? source_pixels_transparent_rec2020
                                       : source_pixels_opaque_rec2020;
    } else {
      NOTREACHED();
    }
  }
}

static std::vector<PNGSample> GetPNGSamplesInfo(bool include_8bit_pngs) {
  std::vector<PNGSample> png_samples;
  std::vector<String> interlace_status = {"", "_interlaced"};
  std::vector<String> color_spaces = {"sRGB",   "AdobeRGB", "DisplayP3",
                                      "e-sRGB", "ProPhoto", "Rec2020"};
  std::vector<String> alpha_status = {"_opaque", "_transparent"};

  for (String color_space : color_spaces) {
    for (String alpha : alpha_status) {
      PNGSample png_sample;
      png_sample.filename.append("_");
      png_sample.filename.append(color_space);
      png_sample.filename.append(alpha);
      png_sample.filename.append(".png");
      png_sample.color_space = color_space;
      png_sample.is_transparent = (alpha == "_transparent");

      for (String interlace : interlace_status) {
        PNGSample high_bit_depth_sample(png_sample);
        high_bit_depth_sample.filename.insert(interlace, 0);
        high_bit_depth_sample.filename.insert("2x2_16bit", 0);
        high_bit_depth_sample.is_high_bit_depth = true;
        png_samples.push_back(high_bit_depth_sample);
      }
      if (include_8bit_pngs) {
        PNGSample regular_bit_depth_sample(png_sample);
        regular_bit_depth_sample.filename.insert("2x2_8bit", 0);
        regular_bit_depth_sample.is_high_bit_depth = false;
        png_samples.push_back(regular_bit_depth_sample);
      }
    }
  }

  return png_samples;
}

TEST(StaticPNGTests, DecodeHighBitDepthPngToHalfFloat) {
  const bool include_8bit_pngs = false;
  std::vector<PNGSample> png_samples = GetPNGSamplesInfo(include_8bit_pngs);
  FillPNGSamplesSourcePixels(png_samples);
  String path = "/images/resources/png-16bit/";
  for (PNGSample& png_sample : png_samples) {
    String full_path = path;
    full_path.append(png_sample.filename);
    png_sample.png_contents = ReadFile(full_path.Ascii().data());
    auto decoder = Create16BitPNGDecoder();
    TestHighBitDepthPNGDecoding(png_sample, decoder.get());
  }
}

TEST(StaticPNGTests, ImageIsHighBitDepth) {
  const bool include_8bit_pngs = true;
  std::vector<PNGSample> png_samples = GetPNGSamplesInfo(include_8bit_pngs);
  IntSize size(2, 2);

  String path = "/images/resources/png-16bit/";
  for (PNGSample& png_sample : png_samples) {
    String full_path = path;
    full_path.append(png_sample.filename);
    png_sample.png_contents = ReadFile(full_path.Ascii().data());
    ASSERT_TRUE(png_sample.png_contents.get());

    std::unique_ptr<ImageDecoder> decoders[] = {CreatePNGDecoder(),
                                                Create16BitPNGDecoder()};
    for (auto& decoder : decoders) {
      decoder->SetData(png_sample.png_contents.get(), true);
      ASSERT_TRUE(decoder->IsSizeAvailable());
      ASSERT_TRUE(decoder->IsDecodedSizeAvailable());
      ASSERT_EQ(size, decoder->Size());
      ASSERT_EQ(size, decoder->DecodedSize());
      ASSERT_EQ(png_sample.is_high_bit_depth, decoder->ImageIsHighBitDepth());
    }
  }
}

TEST(PNGTests, VerifyFrameCompleteBehavior) {
  struct {
    const char* name;
    size_t expected_frame_count;
    size_t offset_in_first_frame;
  } g_recs[] = {
      {"/images/resources/"
       "png-animated-three-independent-frames.png",
       3u, 150u},
      {"/images/resources/"
       "png-animated-idat-part-of-animation.png",
       4u, 160u},

      {"/images/resources/png-simple.png", 1u, 700u},
      {"/images/resources/lenna.png", 1u, 40000u},
  };
  for (const auto& rec : g_recs) {
    scoped_refptr<SharedBuffer> full_data = ReadFile(rec.name);
    ASSERT_TRUE(full_data.get());

    // Create with enough data for part of the first frame.
    auto decoder = CreatePNGDecoder();
    auto data =
        SharedBuffer::Create(full_data->Data(), rec.offset_in_first_frame);
    decoder->SetData(data.get(), false);

    EXPECT_FALSE(decoder->FrameIsReceivedAtIndex(0));

    // Parsing the size is not enough to mark the frame as complete.
    EXPECT_TRUE(decoder->IsSizeAvailable());
    EXPECT_FALSE(decoder->FrameIsReceivedAtIndex(0));

    const auto partial_frame_count = decoder->FrameCount();
    EXPECT_EQ(1u, partial_frame_count);

    // Frame is not complete, even after decoding partially.
    EXPECT_FALSE(decoder->FrameIsReceivedAtIndex(0));
    auto* frame = decoder->DecodeFrameBufferAtIndex(0);
    ASSERT_TRUE(frame);
    EXPECT_NE(ImageFrame::kFrameComplete, frame->GetStatus());
    EXPECT_FALSE(decoder->FrameIsReceivedAtIndex(0));

    decoder->SetData(full_data.get(), true);

    // With full data, parsing the size still does not mark a frame as
    // complete for animated images.
    EXPECT_TRUE(decoder->IsSizeAvailable());
    if (rec.expected_frame_count > 1)
      EXPECT_FALSE(decoder->FrameIsReceivedAtIndex(0));
    else
      EXPECT_TRUE(decoder->FrameIsReceivedAtIndex(0));

    const auto frame_count = decoder->FrameCount();
    ASSERT_EQ(rec.expected_frame_count, frame_count);

    // After parsing (the full file), all frames are complete.
    for (size_t i = 0; i < frame_count; ++i)
      EXPECT_TRUE(decoder->FrameIsReceivedAtIndex(i));

    frame = decoder->DecodeFrameBufferAtIndex(0);
    ASSERT_TRUE(frame);
    EXPECT_EQ(ImageFrame::kFrameComplete, frame->GetStatus());
    EXPECT_TRUE(decoder->FrameIsReceivedAtIndex(0));
  }
}

TEST(PNGTests, sizeMayOverflow) {
  auto decoder =
      CreatePNGDecoderWithPngData("/images/resources/crbug702934.png");
  EXPECT_FALSE(decoder->IsSizeAvailable());
  EXPECT_TRUE(decoder->Failed());
}

TEST(PNGTests, truncated) {
  auto decoder =
      CreatePNGDecoderWithPngData("/images/resources/crbug807324.png");

  // An update to libpng (without using the libpng-provided workaround)
  // resulted in truncating this image. It has no transparency, so no pixel
  // should be transparent.
  auto* frame = decoder->DecodeFrameBufferAtIndex(0);
  auto size = decoder->Size();
  for (int i = 0; i < size.Width(); ++i) {
    for (int j = 0; j < size.Height(); ++j) {
      ASSERT_NE(SK_ColorTRANSPARENT, *frame->GetAddr(i, j));
    }
  }
}

TEST(PNGTests, crbug827754) {
  const char* png_file = "/images/resources/crbug827754.png";
  scoped_refptr<SharedBuffer> data = ReadFile(png_file);
  ASSERT_TRUE(data);

  auto decoder = CreatePNGDecoder();
  decoder->SetData(data.get(), true);
  auto* frame = decoder->DecodeFrameBufferAtIndex(0);
  ASSERT_TRUE(frame);
  ASSERT_FALSE(decoder->Failed());
}

};  // namespace blink