CodecTest.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  1. /*
  2. * Copyright 2015 Google Inc.
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #include "include/codec/SkAndroidCodec.h"
  8. #include "include/codec/SkCodec.h"
  9. #include "include/core/SkBitmap.h"
  10. #include "include/core/SkCanvas.h"
  11. #include "include/core/SkColor.h"
  12. #include "include/core/SkColorSpace.h"
  13. #include "include/core/SkData.h"
  14. #include "include/core/SkEncodedImageFormat.h"
  15. #include "include/core/SkImage.h"
  16. #include "include/core/SkImageEncoder.h"
  17. #include "include/core/SkImageGenerator.h"
  18. #include "include/core/SkImageInfo.h"
  19. #include "include/core/SkPixmap.h"
  20. #include "include/core/SkPngChunkReader.h"
  21. #include "include/core/SkRect.h"
  22. #include "include/core/SkRefCnt.h"
  23. #include "include/core/SkSize.h"
  24. #include "include/core/SkStream.h"
  25. #include "include/core/SkString.h"
  26. #include "include/core/SkTypes.h"
  27. #include "include/core/SkUnPreMultiply.h"
  28. #include "include/encode/SkJpegEncoder.h"
  29. #include "include/encode/SkPngEncoder.h"
  30. #include "include/encode/SkWebpEncoder.h"
  31. #include "include/private/SkMalloc.h"
  32. #include "include/private/SkTemplates.h"
  33. #include "include/third_party/skcms/skcms.h"
  34. #include "include/utils/SkFrontBufferedStream.h"
  35. #include "include/utils/SkRandom.h"
  36. #include "src/codec/SkCodecImageGenerator.h"
  37. #include "src/core/SkAutoMalloc.h"
  38. #include "src/core/SkColorSpacePriv.h"
  39. #include "src/core/SkMD5.h"
  40. #include "src/core/SkMakeUnique.h"
  41. #include "src/core/SkStreamPriv.h"
  42. #include "tests/FakeStreams.h"
  43. #include "tests/Test.h"
  44. #include "tools/Resources.h"
  45. #include "tools/ToolUtils.h"
  46. #include "png.h"
  47. #include <setjmp.h>
  48. #include <cstring>
  49. #include <initializer_list>
  50. #include <memory>
  51. #include <utility>
  52. #include <vector>
  53. #if PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR < 5
  54. // FIXME (scroggo): Google3 needs to be updated to use a newer version of libpng. In
  55. // the meantime, we had to break some pieces of SkPngCodec in order to support Google3.
  56. // The parts that are broken are likely not used by Google3.
  57. #define SK_PNG_DISABLE_TESTS
  58. #endif
  59. static SkMD5::Digest md5(const SkBitmap& bm) {
  60. SkASSERT(bm.getPixels());
  61. SkMD5 md5;
  62. size_t rowLen = bm.info().bytesPerPixel() * bm.width();
  63. for (int y = 0; y < bm.height(); ++y) {
  64. md5.write(bm.getAddr(0, y), rowLen);
  65. }
  66. return md5.finish();
  67. }
  68. /**
  69. * Compute the digest for bm and compare it to a known good digest.
  70. * @param r Reporter to assert that bm's digest matches goodDigest.
  71. * @param goodDigest The known good digest to compare to.
  72. * @param bm The bitmap to test.
  73. */
  74. static void compare_to_good_digest(skiatest::Reporter* r, const SkMD5::Digest& goodDigest,
  75. const SkBitmap& bm) {
  76. SkMD5::Digest digest = md5(bm);
  77. REPORTER_ASSERT(r, digest == goodDigest);
  78. }
  79. /**
  80. * Test decoding an SkCodec to a particular SkImageInfo.
  81. *
  82. * Calling getPixels(info) should return expectedResult, and if goodDigest is non nullptr,
  83. * the resulting decode should match.
  84. */
  85. template<typename Codec>
  86. static void test_info(skiatest::Reporter* r, Codec* codec, const SkImageInfo& info,
  87. SkCodec::Result expectedResult, const SkMD5::Digest* goodDigest) {
  88. SkBitmap bm;
  89. bm.allocPixels(info);
  90. SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes());
  91. REPORTER_ASSERT(r, result == expectedResult);
  92. if (goodDigest) {
  93. compare_to_good_digest(r, *goodDigest, bm);
  94. }
  95. }
  96. SkIRect generate_random_subset(SkRandom* rand, int w, int h) {
  97. SkIRect rect;
  98. do {
  99. rect.fLeft = rand->nextRangeU(0, w);
  100. rect.fTop = rand->nextRangeU(0, h);
  101. rect.fRight = rand->nextRangeU(0, w);
  102. rect.fBottom = rand->nextRangeU(0, h);
  103. rect.sort();
  104. } while (rect.isEmpty());
  105. return rect;
  106. }
  107. static void test_incremental_decode(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info,
  108. const SkMD5::Digest& goodDigest) {
  109. SkBitmap bm;
  110. bm.allocPixels(info);
  111. REPORTER_ASSERT(r, SkCodec::kSuccess == codec->startIncrementalDecode(info, bm.getPixels(),
  112. bm.rowBytes()));
  113. REPORTER_ASSERT(r, SkCodec::kSuccess == codec->incrementalDecode());
  114. compare_to_good_digest(r, goodDigest, bm);
  115. }
  116. // Test in stripes, similar to DM's kStripe_Mode
  117. static void test_in_stripes(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info,
  118. const SkMD5::Digest& goodDigest) {
  119. SkBitmap bm;
  120. bm.allocPixels(info);
  121. bm.eraseColor(SK_ColorYELLOW);
  122. const int height = info.height();
  123. // Note that if numStripes does not evenly divide height there will be an extra
  124. // stripe.
  125. const int numStripes = 4;
  126. if (numStripes > height) {
  127. // Image is too small.
  128. return;
  129. }
  130. const int stripeHeight = height / numStripes;
  131. // Iterate through the image twice. Once to decode odd stripes, and once for even.
  132. for (int oddEven = 1; oddEven >= 0; oddEven--) {
  133. for (int y = oddEven * stripeHeight; y < height; y += 2 * stripeHeight) {
  134. SkIRect subset = SkIRect::MakeLTRB(0, y, info.width(),
  135. SkTMin(y + stripeHeight, height));
  136. SkCodec::Options options;
  137. options.fSubset = &subset;
  138. if (SkCodec::kSuccess != codec->startIncrementalDecode(info, bm.getAddr(0, y),
  139. bm.rowBytes(), &options)) {
  140. ERRORF(r, "failed to start incremental decode!\ttop: %i\tbottom%i\n",
  141. subset.top(), subset.bottom());
  142. return;
  143. }
  144. if (SkCodec::kSuccess != codec->incrementalDecode()) {
  145. ERRORF(r, "failed incremental decode starting from line %i\n", y);
  146. return;
  147. }
  148. }
  149. }
  150. compare_to_good_digest(r, goodDigest, bm);
  151. }
  152. template<typename Codec>
  153. static void test_codec(skiatest::Reporter* r, const char* path, Codec* codec, SkBitmap& bm,
  154. const SkImageInfo& info, const SkISize& size, SkCodec::Result expectedResult,
  155. SkMD5::Digest* digest, const SkMD5::Digest* goodDigest) {
  156. REPORTER_ASSERT(r, info.dimensions() == size);
  157. bm.allocPixels(info);
  158. SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes());
  159. REPORTER_ASSERT(r, result == expectedResult);
  160. *digest = md5(bm);
  161. if (goodDigest) {
  162. REPORTER_ASSERT(r, *digest == *goodDigest);
  163. }
  164. {
  165. // Test decoding to 565
  166. SkImageInfo info565 = info.makeColorType(kRGB_565_SkColorType);
  167. if (info.alphaType() == kOpaque_SkAlphaType) {
  168. // Decoding to 565 should succeed.
  169. SkBitmap bm565;
  170. bm565.allocPixels(info565);
  171. // This will allow comparison even if the image is incomplete.
  172. bm565.eraseColor(SK_ColorBLACK);
  173. auto actualResult = codec->getPixels(info565, bm565.getPixels(), bm565.rowBytes());
  174. if (actualResult == expectedResult) {
  175. SkMD5::Digest digest565 = md5(bm565);
  176. // A request for non-opaque should also succeed.
  177. for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
  178. info565 = info565.makeAlphaType(alpha);
  179. test_info(r, codec, info565, expectedResult, &digest565);
  180. }
  181. } else {
  182. ERRORF(r, "Decoding %s to 565 failed with result \"%s\"\n\t\t\t\texpected:\"%s\"",
  183. path,
  184. SkCodec::ResultToString(actualResult),
  185. SkCodec::ResultToString(expectedResult));
  186. }
  187. } else {
  188. test_info(r, codec, info565, SkCodec::kInvalidConversion, nullptr);
  189. }
  190. }
  191. if (codec->getInfo().colorType() == kGray_8_SkColorType) {
  192. SkImageInfo grayInfo = codec->getInfo();
  193. SkBitmap grayBm;
  194. grayBm.allocPixels(grayInfo);
  195. grayBm.eraseColor(SK_ColorBLACK);
  196. REPORTER_ASSERT(r, expectedResult == codec->getPixels(grayInfo,
  197. grayBm.getPixels(), grayBm.rowBytes()));
  198. SkMD5::Digest grayDigest = md5(grayBm);
  199. for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
  200. grayInfo = grayInfo.makeAlphaType(alpha);
  201. test_info(r, codec, grayInfo, expectedResult, &grayDigest);
  202. }
  203. }
  204. // Verify that re-decoding gives the same result. It is interesting to check this after
  205. // a decode to 565, since choosing to decode to 565 may result in some of the decode
  206. // options being modified. These options should return to their defaults on another
  207. // decode to kN32, so the new digest should match the old digest.
  208. test_info(r, codec, info, expectedResult, digest);
  209. {
  210. // Check alpha type conversions
  211. if (info.alphaType() == kOpaque_SkAlphaType) {
  212. test_info(r, codec, info.makeAlphaType(kUnpremul_SkAlphaType),
  213. expectedResult, digest);
  214. test_info(r, codec, info.makeAlphaType(kPremul_SkAlphaType),
  215. expectedResult, digest);
  216. } else {
  217. // Decoding to opaque should fail
  218. test_info(r, codec, info.makeAlphaType(kOpaque_SkAlphaType),
  219. SkCodec::kInvalidConversion, nullptr);
  220. SkAlphaType otherAt = info.alphaType();
  221. if (kPremul_SkAlphaType == otherAt) {
  222. otherAt = kUnpremul_SkAlphaType;
  223. } else {
  224. otherAt = kPremul_SkAlphaType;
  225. }
  226. // The other non-opaque alpha type should always succeed, but not match.
  227. test_info(r, codec, info.makeAlphaType(otherAt), expectedResult, nullptr);
  228. }
  229. }
  230. }
  231. static bool supports_partial_scanlines(const char path[]) {
  232. static const char* const exts[] = {
  233. "jpg", "jpeg", "png", "webp"
  234. "JPG", "JPEG", "PNG", "WEBP"
  235. };
  236. for (uint32_t i = 0; i < SK_ARRAY_COUNT(exts); i++) {
  237. if (SkStrEndsWith(path, exts[i])) {
  238. return true;
  239. }
  240. }
  241. return false;
  242. }
  243. // FIXME: Break up this giant function
  244. static void check(skiatest::Reporter* r,
  245. const char path[],
  246. SkISize size,
  247. bool supportsScanlineDecoding,
  248. bool supportsSubsetDecoding,
  249. bool supportsIncomplete,
  250. bool supportsNewScanlineDecoding = false) {
  251. // If we're testing incomplete decodes, let's run the same test on full decodes.
  252. if (supportsIncomplete) {
  253. check(r, path, size, supportsScanlineDecoding, supportsSubsetDecoding, false,
  254. supportsNewScanlineDecoding);
  255. }
  256. std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
  257. if (!stream) {
  258. return;
  259. }
  260. std::unique_ptr<SkCodec> codec(nullptr);
  261. if (supportsIncomplete) {
  262. size_t size = stream->getLength();
  263. codec = SkCodec::MakeFromData(SkData::MakeFromStream(stream.get(), 2 * size / 3));
  264. } else {
  265. codec = SkCodec::MakeFromStream(std::move(stream));
  266. }
  267. if (!codec) {
  268. ERRORF(r, "Unable to decode '%s'", path);
  269. return;
  270. }
  271. // Test full image decodes with SkCodec
  272. SkMD5::Digest codecDigest;
  273. const SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
  274. SkBitmap bm;
  275. SkCodec::Result expectedResult =
  276. supportsIncomplete ? SkCodec::kIncompleteInput : SkCodec::kSuccess;
  277. test_codec(r, path, codec.get(), bm, info, size, expectedResult, &codecDigest, nullptr);
  278. // Scanline decoding follows.
  279. if (supportsNewScanlineDecoding && !supportsIncomplete) {
  280. test_incremental_decode(r, codec.get(), info, codecDigest);
  281. // This is only supported by codecs that use incremental decoding to
  282. // support subset decodes - png and jpeg (once SkJpegCodec is
  283. // converted).
  284. if (SkStrEndsWith(path, "png") || SkStrEndsWith(path, "PNG")) {
  285. test_in_stripes(r, codec.get(), info, codecDigest);
  286. }
  287. }
  288. // Need to call startScanlineDecode() first.
  289. REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0) == 0);
  290. REPORTER_ASSERT(r, !codec->skipScanlines(1));
  291. const SkCodec::Result startResult = codec->startScanlineDecode(info);
  292. if (supportsScanlineDecoding) {
  293. bm.eraseColor(SK_ColorYELLOW);
  294. REPORTER_ASSERT(r, startResult == SkCodec::kSuccess);
  295. for (int y = 0; y < info.height(); y++) {
  296. const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0);
  297. if (!supportsIncomplete) {
  298. REPORTER_ASSERT(r, 1 == lines);
  299. }
  300. }
  301. // verify that scanline decoding gives the same result.
  302. if (SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder()) {
  303. compare_to_good_digest(r, codecDigest, bm);
  304. }
  305. // Cannot continue to decode scanlines beyond the end
  306. REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0)
  307. == 0);
  308. // Interrupting a scanline decode with a full decode starts from
  309. // scratch
  310. REPORTER_ASSERT(r, codec->startScanlineDecode(info) == SkCodec::kSuccess);
  311. const int lines = codec->getScanlines(bm.getAddr(0, 0), 1, 0);
  312. if (!supportsIncomplete) {
  313. REPORTER_ASSERT(r, lines == 1);
  314. }
  315. REPORTER_ASSERT(r, codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes())
  316. == expectedResult);
  317. REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0)
  318. == 0);
  319. REPORTER_ASSERT(r, codec->skipScanlines(1)
  320. == 0);
  321. // Test partial scanline decodes
  322. if (supports_partial_scanlines(path) && info.width() >= 3) {
  323. SkCodec::Options options;
  324. int width = info.width();
  325. int height = info.height();
  326. SkIRect subset = SkIRect::MakeXYWH(2 * (width / 3), 0, width / 3, height);
  327. options.fSubset = &subset;
  328. const auto partialStartResult = codec->startScanlineDecode(info, &options);
  329. REPORTER_ASSERT(r, partialStartResult == SkCodec::kSuccess);
  330. for (int y = 0; y < height; y++) {
  331. const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0);
  332. if (!supportsIncomplete) {
  333. REPORTER_ASSERT(r, 1 == lines);
  334. }
  335. }
  336. }
  337. } else {
  338. REPORTER_ASSERT(r, startResult == SkCodec::kUnimplemented);
  339. }
  340. // The rest of this function tests decoding subsets, and will decode an arbitrary number of
  341. // random subsets.
  342. // Do not attempt to decode subsets of an image of only once pixel, since there is no
  343. // meaningful subset.
  344. if (size.width() * size.height() == 1) {
  345. return;
  346. }
  347. SkRandom rand;
  348. SkIRect subset;
  349. SkCodec::Options opts;
  350. opts.fSubset = &subset;
  351. for (int i = 0; i < 5; i++) {
  352. subset = generate_random_subset(&rand, size.width(), size.height());
  353. SkASSERT(!subset.isEmpty());
  354. const bool supported = codec->getValidSubset(&subset);
  355. REPORTER_ASSERT(r, supported == supportsSubsetDecoding);
  356. SkImageInfo subsetInfo = info.makeWH(subset.width(), subset.height());
  357. SkBitmap bm;
  358. bm.allocPixels(subsetInfo);
  359. const auto result = codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes(), &opts);
  360. if (supportsSubsetDecoding) {
  361. if (expectedResult == SkCodec::kSuccess) {
  362. REPORTER_ASSERT(r, result == expectedResult);
  363. }
  364. // Webp is the only codec that supports subsets, and it will have modified the subset
  365. // to have even left/top.
  366. REPORTER_ASSERT(r, SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
  367. } else {
  368. // No subsets will work.
  369. REPORTER_ASSERT(r, result == SkCodec::kUnimplemented);
  370. }
  371. }
  372. // SkAndroidCodec tests
  373. if (supportsScanlineDecoding || supportsSubsetDecoding || supportsNewScanlineDecoding) {
  374. std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
  375. if (!stream) {
  376. return;
  377. }
  378. auto androidCodec = SkAndroidCodec::MakeFromCodec(std::move(codec));
  379. if (!androidCodec) {
  380. ERRORF(r, "Unable to decode '%s'", path);
  381. return;
  382. }
  383. SkBitmap bm;
  384. SkMD5::Digest androidCodecDigest;
  385. test_codec(r, path, androidCodec.get(), bm, info, size, expectedResult, &androidCodecDigest,
  386. &codecDigest);
  387. }
  388. if (!supportsIncomplete) {
  389. // Test SkCodecImageGenerator
  390. std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
  391. sk_sp<SkData> fullData(SkData::MakeFromStream(stream.get(), stream->getLength()));
  392. std::unique_ptr<SkImageGenerator> gen(
  393. SkCodecImageGenerator::MakeFromEncodedCodec(fullData));
  394. SkBitmap bm;
  395. bm.allocPixels(info);
  396. REPORTER_ASSERT(r, gen->getPixels(info, bm.getPixels(), bm.rowBytes()));
  397. compare_to_good_digest(r, codecDigest, bm);
  398. #ifndef SK_PNG_DISABLE_TESTS
  399. // Test using SkFrontBufferedStream, as Android does
  400. auto bufferedStream = SkFrontBufferedStream::Make(
  401. SkMemoryStream::Make(std::move(fullData)), SkCodec::MinBufferedBytesNeeded());
  402. REPORTER_ASSERT(r, bufferedStream);
  403. codec = SkCodec::MakeFromStream(std::move(bufferedStream));
  404. REPORTER_ASSERT(r, codec);
  405. if (codec) {
  406. test_info(r, codec.get(), info, SkCodec::kSuccess, &codecDigest);
  407. }
  408. #endif
  409. }
  410. }
  411. DEF_TEST(Codec_wbmp, r) {
  412. check(r, "images/mandrill.wbmp", SkISize::Make(512, 512), true, false, true);
  413. }
  414. DEF_TEST(Codec_webp, r) {
  415. check(r, "images/baby_tux.webp", SkISize::Make(386, 395), false, true, true);
  416. check(r, "images/color_wheel.webp", SkISize::Make(128, 128), false, true, true);
  417. check(r, "images/yellow_rose.webp", SkISize::Make(400, 301), false, true, true);
  418. }
  419. DEF_TEST(Codec_bmp, r) {
  420. check(r, "images/randPixels.bmp", SkISize::Make(8, 8), true, false, true);
  421. check(r, "images/rle.bmp", SkISize::Make(320, 240), true, false, true);
  422. }
  423. DEF_TEST(Codec_ico, r) {
  424. // FIXME: We are not ready to test incomplete ICOs
  425. // These two tests examine interestingly different behavior:
  426. // Decodes an embedded BMP image
  427. check(r, "images/color_wheel.ico", SkISize::Make(128, 128), true, false, false);
  428. // Decodes an embedded PNG image
  429. check(r, "images/google_chrome.ico", SkISize::Make(256, 256), false, false, false, true);
  430. }
  431. DEF_TEST(Codec_gif, r) {
  432. check(r, "images/box.gif", SkISize::Make(200, 55), false, false, true, true);
  433. check(r, "images/color_wheel.gif", SkISize::Make(128, 128), false, false, true, true);
  434. // randPixels.gif is too small to test incomplete
  435. check(r, "images/randPixels.gif", SkISize::Make(8, 8), false, false, false, true);
  436. }
  437. DEF_TEST(Codec_jpg, r) {
  438. check(r, "images/CMYK.jpg", SkISize::Make(642, 516), true, false, true);
  439. check(r, "images/color_wheel.jpg", SkISize::Make(128, 128), true, false, true);
  440. // grayscale.jpg is too small to test incomplete
  441. check(r, "images/grayscale.jpg", SkISize::Make(128, 128), true, false, false);
  442. check(r, "images/mandrill_512_q075.jpg", SkISize::Make(512, 512), true, false, true);
  443. // randPixels.jpg is too small to test incomplete
  444. check(r, "images/randPixels.jpg", SkISize::Make(8, 8), true, false, false);
  445. }
  446. DEF_TEST(Codec_png, r) {
  447. check(r, "images/arrow.png", SkISize::Make(187, 312), false, false, true, true);
  448. check(r, "images/baby_tux.png", SkISize::Make(240, 246), false, false, true, true);
  449. check(r, "images/color_wheel.png", SkISize::Make(128, 128), false, false, true, true);
  450. // half-transparent-white-pixel.png is too small to test incomplete
  451. check(r, "images/half-transparent-white-pixel.png", SkISize::Make(1, 1), false, false, false, true);
  452. check(r, "images/mandrill_128.png", SkISize::Make(128, 128), false, false, true, true);
  453. // mandrill_16.png is too small (relative to embedded sRGB profile) to test incomplete
  454. check(r, "images/mandrill_16.png", SkISize::Make(16, 16), false, false, false, true);
  455. check(r, "images/mandrill_256.png", SkISize::Make(256, 256), false, false, true, true);
  456. check(r, "images/mandrill_32.png", SkISize::Make(32, 32), false, false, true, true);
  457. check(r, "images/mandrill_512.png", SkISize::Make(512, 512), false, false, true, true);
  458. check(r, "images/mandrill_64.png", SkISize::Make(64, 64), false, false, true, true);
  459. check(r, "images/plane.png", SkISize::Make(250, 126), false, false, true, true);
  460. check(r, "images/plane_interlaced.png", SkISize::Make(250, 126), false, false, true, true);
  461. check(r, "images/randPixels.png", SkISize::Make(8, 8), false, false, true, true);
  462. check(r, "images/yellow_rose.png", SkISize::Make(400, 301), false, false, true, true);
  463. }
  464. // Disable RAW tests for Win32.
  465. #if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
  466. DEF_TEST(Codec_raw, r) {
  467. check(r, "images/sample_1mp.dng", SkISize::Make(600, 338), false, false, false);
  468. check(r, "images/sample_1mp_rotated.dng", SkISize::Make(600, 338), false, false, false);
  469. check(r, "images/dng_with_preview.dng", SkISize::Make(600, 338), true, false, false);
  470. }
  471. #endif
  472. static void test_invalid_stream(skiatest::Reporter* r, const void* stream, size_t len) {
  473. // Neither of these calls should return a codec. Bots should catch us if we leaked anything.
  474. REPORTER_ASSERT(r, !SkCodec::MakeFromStream(
  475. skstd::make_unique<SkMemoryStream>(stream, len, false)));
  476. REPORTER_ASSERT(r, !SkAndroidCodec::MakeFromStream(
  477. skstd::make_unique<SkMemoryStream>(stream, len, false)));
  478. }
  479. // Ensure that SkCodec::NewFromStream handles freeing the passed in SkStream,
  480. // even on failure. Test some bad streams.
  481. DEF_TEST(Codec_leaks, r) {
  482. // No codec should claim this as their format, so this tests SkCodec::NewFromStream.
  483. const char nonSupportedStream[] = "hello world";
  484. // The other strings should look like the beginning of a file type, so we'll call some
  485. // internal version of NewFromStream, which must also delete the stream on failure.
  486. const unsigned char emptyPng[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
  487. const unsigned char emptyJpeg[] = { 0xFF, 0xD8, 0xFF };
  488. const char emptyWebp[] = "RIFF1234WEBPVP";
  489. const char emptyBmp[] = { 'B', 'M' };
  490. const char emptyIco[] = { '\x00', '\x00', '\x01', '\x00' };
  491. const char emptyGif[] = "GIFVER";
  492. test_invalid_stream(r, nonSupportedStream, sizeof(nonSupportedStream));
  493. test_invalid_stream(r, emptyPng, sizeof(emptyPng));
  494. test_invalid_stream(r, emptyJpeg, sizeof(emptyJpeg));
  495. test_invalid_stream(r, emptyWebp, sizeof(emptyWebp));
  496. test_invalid_stream(r, emptyBmp, sizeof(emptyBmp));
  497. test_invalid_stream(r, emptyIco, sizeof(emptyIco));
  498. test_invalid_stream(r, emptyGif, sizeof(emptyGif));
  499. }
  500. DEF_TEST(Codec_null, r) {
  501. // Attempting to create an SkCodec or an SkAndroidCodec with null should not
  502. // crash.
  503. REPORTER_ASSERT(r, !SkCodec::MakeFromStream(nullptr));
  504. REPORTER_ASSERT(r, !SkAndroidCodec::MakeFromStream(nullptr));
  505. }
  506. static void test_dimensions(skiatest::Reporter* r, const char path[]) {
  507. // Create the codec from the resource file
  508. std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
  509. if (!stream) {
  510. return;
  511. }
  512. std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromStream(std::move(stream)));
  513. if (!codec) {
  514. ERRORF(r, "Unable to create codec '%s'", path);
  515. return;
  516. }
  517. // Check that the decode is successful for a variety of scales
  518. for (int sampleSize = 1; sampleSize < 32; sampleSize++) {
  519. // Scale the output dimensions
  520. SkISize scaledDims = codec->getSampledDimensions(sampleSize);
  521. SkImageInfo scaledInfo = codec->getInfo()
  522. .makeWH(scaledDims.width(), scaledDims.height())
  523. .makeColorType(kN32_SkColorType);
  524. // Set up for the decode
  525. size_t rowBytes = scaledDims.width() * sizeof(SkPMColor);
  526. size_t totalBytes = scaledInfo.computeByteSize(rowBytes);
  527. SkAutoTMalloc<SkPMColor> pixels(totalBytes);
  528. SkAndroidCodec::AndroidOptions options;
  529. options.fSampleSize = sampleSize;
  530. SkCodec::Result result =
  531. codec->getAndroidPixels(scaledInfo, pixels.get(), rowBytes, &options);
  532. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  533. }
  534. }
  535. // Ensure that onGetScaledDimensions returns valid image dimensions to use for decodes
  536. DEF_TEST(Codec_Dimensions, r) {
  537. // JPG
  538. test_dimensions(r, "images/CMYK.jpg");
  539. test_dimensions(r, "images/color_wheel.jpg");
  540. test_dimensions(r, "images/grayscale.jpg");
  541. test_dimensions(r, "images/mandrill_512_q075.jpg");
  542. test_dimensions(r, "images/randPixels.jpg");
  543. // Decoding small images with very large scaling factors is a potential
  544. // source of bugs and crashes. We disable these tests in Gold because
  545. // tiny images are not very useful to look at.
  546. // Here we make sure that we do not crash or access illegal memory when
  547. // performing scaled decodes on small images.
  548. test_dimensions(r, "images/1x1.png");
  549. test_dimensions(r, "images/2x2.png");
  550. test_dimensions(r, "images/3x3.png");
  551. test_dimensions(r, "images/3x1.png");
  552. test_dimensions(r, "images/1x1.png");
  553. test_dimensions(r, "images/16x1.png");
  554. test_dimensions(r, "images/1x16.png");
  555. test_dimensions(r, "images/mandrill_16.png");
  556. // RAW
  557. // Disable RAW tests for Win32.
  558. #if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
  559. test_dimensions(r, "images/sample_1mp.dng");
  560. test_dimensions(r, "images/sample_1mp_rotated.dng");
  561. test_dimensions(r, "images/dng_with_preview.dng");
  562. #endif
  563. }
  564. static void test_invalid(skiatest::Reporter* r, const char path[]) {
  565. auto data = GetResourceAsData(path);
  566. if (!data) {
  567. ERRORF(r, "Failed to get resource %s", path);
  568. return;
  569. }
  570. REPORTER_ASSERT(r, !SkCodec::MakeFromData(data));
  571. }
  572. DEF_TEST(Codec_Empty, r) {
  573. if (GetResourcePath().isEmpty()) {
  574. return;
  575. }
  576. // Test images that should not be able to create a codec
  577. test_invalid(r, "empty_images/zero-dims.gif");
  578. test_invalid(r, "empty_images/zero-embedded.ico");
  579. test_invalid(r, "empty_images/zero-width.bmp");
  580. test_invalid(r, "empty_images/zero-height.bmp");
  581. test_invalid(r, "empty_images/zero-width.jpg");
  582. test_invalid(r, "empty_images/zero-height.jpg");
  583. test_invalid(r, "empty_images/zero-width.png");
  584. test_invalid(r, "empty_images/zero-height.png");
  585. test_invalid(r, "empty_images/zero-width.wbmp");
  586. test_invalid(r, "empty_images/zero-height.wbmp");
  587. // This image is an ico with an embedded mask-bmp. This is illegal.
  588. test_invalid(r, "invalid_images/mask-bmp-ico.ico");
  589. // It is illegal for a webp frame to not be fully contained by the canvas.
  590. test_invalid(r, "invalid_images/invalid-offset.webp");
  591. #if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
  592. test_invalid(r, "empty_images/zero_height.tiff");
  593. #endif
  594. test_invalid(r, "invalid_images/b37623797.ico");
  595. test_invalid(r, "invalid_images/osfuzz6295.webp");
  596. test_invalid(r, "invalid_images/osfuzz6288.bmp");
  597. test_invalid(r, "invalid_images/ossfuzz6347");
  598. }
  599. #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  600. #ifndef SK_PNG_DISABLE_TESTS // reading chunks does not work properly with older versions.
  601. // It does not appear that anyone in Google3 is reading chunks.
  602. static void codex_test_write_fn(png_structp png_ptr, png_bytep data, png_size_t len) {
  603. SkWStream* sk_stream = (SkWStream*)png_get_io_ptr(png_ptr);
  604. if (!sk_stream->write(data, len)) {
  605. png_error(png_ptr, "sk_write_fn Error!");
  606. }
  607. }
  608. DEF_TEST(Codec_pngChunkReader, r) {
  609. // Create a dummy bitmap. Use unpremul RGBA for libpng.
  610. SkBitmap bm;
  611. const int w = 1;
  612. const int h = 1;
  613. const SkImageInfo bmInfo = SkImageInfo::Make(w, h, kRGBA_8888_SkColorType,
  614. kUnpremul_SkAlphaType);
  615. bm.setInfo(bmInfo);
  616. bm.allocPixels();
  617. bm.eraseColor(SK_ColorBLUE);
  618. SkMD5::Digest goodDigest = md5(bm);
  619. // Write to a png file.
  620. png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  621. REPORTER_ASSERT(r, png);
  622. if (!png) {
  623. return;
  624. }
  625. png_infop info = png_create_info_struct(png);
  626. REPORTER_ASSERT(r, info);
  627. if (!info) {
  628. png_destroy_write_struct(&png, nullptr);
  629. return;
  630. }
  631. if (setjmp(png_jmpbuf(png))) {
  632. ERRORF(r, "failed writing png");
  633. png_destroy_write_struct(&png, &info);
  634. return;
  635. }
  636. SkDynamicMemoryWStream wStream;
  637. png_set_write_fn(png, (void*) (&wStream), codex_test_write_fn, nullptr);
  638. png_set_IHDR(png, info, (png_uint_32)w, (png_uint_32)h, 8,
  639. PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
  640. PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
  641. // Create some chunks that match the Android framework's use.
  642. static png_unknown_chunk gUnknowns[] = {
  643. { "npOl", (png_byte*)"outline", sizeof("outline"), PNG_HAVE_IHDR },
  644. { "npLb", (png_byte*)"layoutBounds", sizeof("layoutBounds"), PNG_HAVE_IHDR },
  645. { "npTc", (png_byte*)"ninePatchData", sizeof("ninePatchData"), PNG_HAVE_IHDR },
  646. };
  647. png_set_keep_unknown_chunks(png, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"npOl\0npLb\0npTc\0", 3);
  648. png_set_unknown_chunks(png, info, gUnknowns, SK_ARRAY_COUNT(gUnknowns));
  649. #if PNG_LIBPNG_VER < 10600
  650. /* Deal with unknown chunk location bug in 1.5.x and earlier */
  651. png_set_unknown_chunk_location(png, info, 0, PNG_HAVE_IHDR);
  652. png_set_unknown_chunk_location(png, info, 1, PNG_HAVE_IHDR);
  653. #endif
  654. png_write_info(png, info);
  655. for (int j = 0; j < h; j++) {
  656. png_bytep row = (png_bytep)(bm.getAddr(0, j));
  657. png_write_rows(png, &row, 1);
  658. }
  659. png_write_end(png, info);
  660. png_destroy_write_struct(&png, &info);
  661. class ChunkReader : public SkPngChunkReader {
  662. public:
  663. ChunkReader(skiatest::Reporter* r)
  664. : fReporter(r)
  665. {
  666. this->reset();
  667. }
  668. bool readChunk(const char tag[], const void* data, size_t length) override {
  669. for (size_t i = 0; i < SK_ARRAY_COUNT(gUnknowns); ++i) {
  670. if (!strcmp(tag, (const char*) gUnknowns[i].name)) {
  671. // Tag matches. This should have been the first time we see it.
  672. REPORTER_ASSERT(fReporter, !fSeen[i]);
  673. fSeen[i] = true;
  674. // Data and length should match
  675. REPORTER_ASSERT(fReporter, length == gUnknowns[i].size);
  676. REPORTER_ASSERT(fReporter, !strcmp((const char*) data,
  677. (const char*) gUnknowns[i].data));
  678. return true;
  679. }
  680. }
  681. ERRORF(fReporter, "Saw an unexpected unknown chunk.");
  682. return true;
  683. }
  684. bool allHaveBeenSeen() {
  685. bool ret = true;
  686. for (auto seen : fSeen) {
  687. ret &= seen;
  688. }
  689. return ret;
  690. }
  691. void reset() {
  692. sk_bzero(fSeen, sizeof(fSeen));
  693. }
  694. private:
  695. skiatest::Reporter* fReporter; // Unowned
  696. bool fSeen[3];
  697. };
  698. ChunkReader chunkReader(r);
  699. // Now read the file with SkCodec.
  700. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(wStream.detachAsData(), &chunkReader));
  701. REPORTER_ASSERT(r, codec);
  702. if (!codec) {
  703. return;
  704. }
  705. // Now compare to the original.
  706. SkBitmap decodedBm;
  707. decodedBm.setInfo(codec->getInfo());
  708. decodedBm.allocPixels();
  709. SkCodec::Result result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(),
  710. decodedBm.rowBytes());
  711. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  712. if (decodedBm.colorType() != bm.colorType()) {
  713. SkBitmap tmp;
  714. bool success = ToolUtils::copy_to(&tmp, bm.colorType(), decodedBm);
  715. REPORTER_ASSERT(r, success);
  716. if (!success) {
  717. return;
  718. }
  719. tmp.swap(decodedBm);
  720. }
  721. compare_to_good_digest(r, goodDigest, decodedBm);
  722. REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen());
  723. // Decoding again will read the chunks again.
  724. chunkReader.reset();
  725. REPORTER_ASSERT(r, !chunkReader.allHaveBeenSeen());
  726. result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(), decodedBm.rowBytes());
  727. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  728. REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen());
  729. }
  730. #endif // SK_PNG_DISABLE_TESTS
  731. #endif // PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  732. // Stream that can only peek up to a limit
  733. class LimitedPeekingMemStream : public SkStream {
  734. public:
  735. LimitedPeekingMemStream(sk_sp<SkData> data, size_t limit)
  736. : fStream(std::move(data))
  737. , fLimit(limit) {}
  738. size_t peek(void* buf, size_t bytes) const override {
  739. return fStream.peek(buf, SkTMin(bytes, fLimit));
  740. }
  741. size_t read(void* buf, size_t bytes) override {
  742. return fStream.read(buf, bytes);
  743. }
  744. bool rewind() override {
  745. return fStream.rewind();
  746. }
  747. bool isAtEnd() const override {
  748. return fStream.isAtEnd();
  749. }
  750. private:
  751. SkMemoryStream fStream;
  752. const size_t fLimit;
  753. };
  754. // Disable RAW tests for Win32.
  755. #if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
  756. // Test that the RawCodec works also for not asset stream. This will test the code path using
  757. // SkRawBufferedStream instead of SkRawAssetStream.
  758. DEF_TEST(Codec_raw_notseekable, r) {
  759. constexpr char path[] = "images/dng_with_preview.dng";
  760. sk_sp<SkData> data(GetResourceAsData(path));
  761. if (!data) {
  762. SkDebugf("Missing resource '%s'\n", path);
  763. return;
  764. }
  765. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(
  766. skstd::make_unique<NotAssetMemStream>(std::move(data))));
  767. REPORTER_ASSERT(r, codec);
  768. test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
  769. }
  770. #endif
  771. // Test that even if webp_parse_header fails to peek enough, it will fall back to read()
  772. // + rewind() and succeed.
  773. DEF_TEST(Codec_webp_peek, r) {
  774. constexpr char path[] = "images/baby_tux.webp";
  775. auto data = GetResourceAsData(path);
  776. if (!data) {
  777. SkDebugf("Missing resource '%s'\n", path);
  778. return;
  779. }
  780. // The limit is less than webp needs to peek or read.
  781. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(
  782. skstd::make_unique<LimitedPeekingMemStream>(data, 25)));
  783. REPORTER_ASSERT(r, codec);
  784. test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
  785. // Similarly, a stream which does not peek should still succeed.
  786. codec = SkCodec::MakeFromStream(skstd::make_unique<LimitedPeekingMemStream>(data, 0));
  787. REPORTER_ASSERT(r, codec);
  788. test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
  789. }
  790. // SkCodec's wbmp decoder was initially unnecessarily restrictive.
  791. // It required the second byte to be zero. The wbmp specification allows
  792. // a couple of bits to be 1 (so long as they do not overlap with 0x9F).
  793. // Test that SkCodec now supports an image with these bits set.
  794. DEF_TEST(Codec_wbmp_restrictive, r) {
  795. const char* path = "images/mandrill.wbmp";
  796. std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
  797. if (!stream) {
  798. return;
  799. }
  800. // Modify the stream to contain a second byte with some bits set.
  801. auto data = SkCopyStreamToData(stream.get());
  802. uint8_t* writeableData = static_cast<uint8_t*>(data->writable_data());
  803. writeableData[1] = static_cast<uint8_t>(~0x9F);
  804. // SkCodec should support this.
  805. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(data));
  806. REPORTER_ASSERT(r, codec);
  807. if (!codec) {
  808. return;
  809. }
  810. test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
  811. }
  812. // wbmp images have a header that can be arbitrarily large, depending on the
  813. // size of the image. We cap the size at 65535, meaning we only need to look at
  814. // 8 bytes to determine whether we can read the image. This is important
  815. // because SkCodec only passes a limited number of bytes to SkWbmpCodec to
  816. // determine whether the image is a wbmp.
  817. DEF_TEST(Codec_wbmp_max_size, r) {
  818. const unsigned char maxSizeWbmp[] = { 0x00, 0x00, // Header
  819. 0x83, 0xFF, 0x7F, // W: 65535
  820. 0x83, 0xFF, 0x7F }; // H: 65535
  821. std::unique_ptr<SkStream> stream(new SkMemoryStream(maxSizeWbmp, sizeof(maxSizeWbmp), false));
  822. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
  823. REPORTER_ASSERT(r, codec);
  824. if (!codec) return;
  825. REPORTER_ASSERT(r, codec->getInfo().width() == 65535);
  826. REPORTER_ASSERT(r, codec->getInfo().height() == 65535);
  827. // Now test an image which is too big. Any image with a larger header (i.e.
  828. // has bigger width/height) is also too big.
  829. const unsigned char tooBigWbmp[] = { 0x00, 0x00, // Header
  830. 0x84, 0x80, 0x00, // W: 65536
  831. 0x84, 0x80, 0x00 }; // H: 65536
  832. stream.reset(new SkMemoryStream(tooBigWbmp, sizeof(tooBigWbmp), false));
  833. codec = SkCodec::MakeFromStream(std::move(stream));
  834. REPORTER_ASSERT(r, !codec);
  835. }
  836. DEF_TEST(Codec_jpeg_rewind, r) {
  837. const char* path = "images/mandrill_512_q075.jpg";
  838. sk_sp<SkData> data(GetResourceAsData(path));
  839. if (!data) {
  840. return;
  841. }
  842. data = SkData::MakeSubset(data.get(), 0, data->size() / 2);
  843. std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(data));
  844. if (!codec) {
  845. ERRORF(r, "Unable to create codec '%s'.", path);
  846. return;
  847. }
  848. const int width = codec->getInfo().width();
  849. const int height = codec->getInfo().height();
  850. size_t rowBytes = sizeof(SkPMColor) * width;
  851. SkAutoMalloc pixelStorage(height * rowBytes);
  852. // Perform a sampled decode.
  853. SkAndroidCodec::AndroidOptions opts;
  854. opts.fSampleSize = 12;
  855. auto sampledInfo = codec->getInfo().makeWH(width / 12, height / 12);
  856. auto result = codec->getAndroidPixels(sampledInfo, pixelStorage.get(), rowBytes, &opts);
  857. REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
  858. // Rewind the codec and perform a full image decode.
  859. result = codec->getPixels(codec->getInfo(), pixelStorage.get(), rowBytes);
  860. REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
  861. // Now perform a subset decode.
  862. {
  863. opts.fSampleSize = 1;
  864. SkIRect subset = SkIRect::MakeWH(100, 100);
  865. opts.fSubset = &subset;
  866. result = codec->getAndroidPixels(codec->getInfo().makeWH(100, 100), pixelStorage.get(),
  867. rowBytes, &opts);
  868. // Though we only have half the data, it is enough to decode this subset.
  869. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  870. }
  871. // Perform another full image decode. ASAN will detect if we look at the subset when it is
  872. // out of scope. This would happen if we depend on the old state in the codec.
  873. // This tests two layers of bugs: both SkJpegCodec::readRows and SkCodec::fillIncompleteImage
  874. // used to look at the old subset.
  875. opts.fSubset = nullptr;
  876. result = codec->getAndroidPixels(codec->getInfo(), pixelStorage.get(), rowBytes, &opts);
  877. REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
  878. }
  879. static void check_color_xform(skiatest::Reporter* r, const char* path) {
  880. std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromStream(GetResourceAsStream(path)));
  881. SkAndroidCodec::AndroidOptions opts;
  882. opts.fSampleSize = 3;
  883. const int subsetWidth = codec->getInfo().width() / 2;
  884. const int subsetHeight = codec->getInfo().height() / 2;
  885. SkIRect subset = SkIRect::MakeWH(subsetWidth, subsetHeight);
  886. opts.fSubset = &subset;
  887. const int dstWidth = subsetWidth / opts.fSampleSize;
  888. const int dstHeight = subsetHeight / opts.fSampleSize;
  889. auto colorSpace = SkColorSpace::MakeRGB(SkNamedTransferFn::k2Dot2, SkNamedGamut::kAdobeRGB);
  890. SkImageInfo dstInfo = codec->getInfo().makeWH(dstWidth, dstHeight)
  891. .makeColorType(kN32_SkColorType)
  892. .makeColorSpace(colorSpace);
  893. size_t rowBytes = dstInfo.minRowBytes();
  894. SkAutoMalloc pixelStorage(dstInfo.computeByteSize(rowBytes));
  895. SkCodec::Result result = codec->getAndroidPixels(dstInfo, pixelStorage.get(), rowBytes, &opts);
  896. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  897. }
  898. DEF_TEST(Codec_ColorXform, r) {
  899. check_color_xform(r, "images/mandrill_512_q075.jpg");
  900. check_color_xform(r, "images/mandrill_512.png");
  901. }
  902. static bool color_type_match(SkColorType origColorType, SkColorType codecColorType) {
  903. switch (origColorType) {
  904. case kRGBA_8888_SkColorType:
  905. case kBGRA_8888_SkColorType:
  906. return kRGBA_8888_SkColorType == codecColorType ||
  907. kBGRA_8888_SkColorType == codecColorType;
  908. default:
  909. return origColorType == codecColorType;
  910. }
  911. }
  912. static bool alpha_type_match(SkAlphaType origAlphaType, SkAlphaType codecAlphaType) {
  913. switch (origAlphaType) {
  914. case kUnpremul_SkAlphaType:
  915. case kPremul_SkAlphaType:
  916. return kUnpremul_SkAlphaType == codecAlphaType ||
  917. kPremul_SkAlphaType == codecAlphaType;
  918. default:
  919. return origAlphaType == codecAlphaType;
  920. }
  921. }
  922. static void check_round_trip(skiatest::Reporter* r, SkCodec* origCodec, const SkImageInfo& info) {
  923. SkBitmap bm1;
  924. bm1.allocPixels(info);
  925. SkCodec::Result result = origCodec->getPixels(info, bm1.getPixels(), bm1.rowBytes());
  926. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  927. // Encode the image to png.
  928. auto data = SkEncodeBitmap(bm1, SkEncodedImageFormat::kPNG, 100);
  929. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(data));
  930. REPORTER_ASSERT(r, color_type_match(info.colorType(), codec->getInfo().colorType()));
  931. REPORTER_ASSERT(r, alpha_type_match(info.alphaType(), codec->getInfo().alphaType()));
  932. SkBitmap bm2;
  933. bm2.allocPixels(info);
  934. result = codec->getPixels(info, bm2.getPixels(), bm2.rowBytes());
  935. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  936. REPORTER_ASSERT(r, md5(bm1) == md5(bm2));
  937. }
  938. DEF_TEST(Codec_PngRoundTrip, r) {
  939. auto codec = SkCodec::MakeFromStream(GetResourceAsStream("images/mandrill_512_q075.jpg"));
  940. SkColorType colorTypesOpaque[] = {
  941. kRGB_565_SkColorType, kRGBA_8888_SkColorType, kBGRA_8888_SkColorType
  942. };
  943. for (SkColorType colorType : colorTypesOpaque) {
  944. SkImageInfo newInfo = codec->getInfo().makeColorType(colorType);
  945. check_round_trip(r, codec.get(), newInfo);
  946. }
  947. codec = SkCodec::MakeFromStream(GetResourceAsStream("images/grayscale.jpg"));
  948. check_round_trip(r, codec.get(), codec->getInfo());
  949. codec = SkCodec::MakeFromStream(GetResourceAsStream("images/yellow_rose.png"));
  950. SkColorType colorTypesWithAlpha[] = {
  951. kRGBA_8888_SkColorType, kBGRA_8888_SkColorType
  952. };
  953. SkAlphaType alphaTypes[] = {
  954. kUnpremul_SkAlphaType, kPremul_SkAlphaType
  955. };
  956. for (SkColorType colorType : colorTypesWithAlpha) {
  957. for (SkAlphaType alphaType : alphaTypes) {
  958. // Set color space to nullptr because color correct premultiplies do not round trip.
  959. SkImageInfo newInfo = codec->getInfo().makeColorType(colorType)
  960. .makeAlphaType(alphaType)
  961. .makeColorSpace(nullptr);
  962. check_round_trip(r, codec.get(), newInfo);
  963. }
  964. }
  965. codec = SkCodec::MakeFromStream(GetResourceAsStream("images/index8.png"));
  966. for (SkAlphaType alphaType : alphaTypes) {
  967. SkImageInfo newInfo = codec->getInfo().makeAlphaType(alphaType)
  968. .makeColorSpace(nullptr);
  969. check_round_trip(r, codec.get(), newInfo);
  970. }
  971. }
  972. static void test_conversion_possible(skiatest::Reporter* r, const char* path,
  973. bool supportsScanlineDecoder,
  974. bool supportsIncrementalDecoder) {
  975. std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
  976. if (!stream) {
  977. return;
  978. }
  979. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
  980. if (!codec) {
  981. ERRORF(r, "failed to create a codec for %s", path);
  982. return;
  983. }
  984. SkImageInfo infoF16 = codec->getInfo().makeColorType(kRGBA_F16_SkColorType);
  985. SkBitmap bm;
  986. bm.allocPixels(infoF16);
  987. SkCodec::Result result = codec->getPixels(infoF16, bm.getPixels(), bm.rowBytes());
  988. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  989. result = codec->startScanlineDecode(infoF16);
  990. if (supportsScanlineDecoder) {
  991. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  992. } else {
  993. REPORTER_ASSERT(r, SkCodec::kUnimplemented == result
  994. || SkCodec::kSuccess == result);
  995. }
  996. result = codec->startIncrementalDecode(infoF16, bm.getPixels(), bm.rowBytes());
  997. if (supportsIncrementalDecoder) {
  998. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  999. } else {
  1000. REPORTER_ASSERT(r, SkCodec::kUnimplemented == result
  1001. || SkCodec::kSuccess == result);
  1002. }
  1003. infoF16 = infoF16.makeColorSpace(infoF16.colorSpace()->makeLinearGamma());
  1004. result = codec->getPixels(infoF16, bm.getPixels(), bm.rowBytes());
  1005. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  1006. result = codec->startScanlineDecode(infoF16);
  1007. if (supportsScanlineDecoder) {
  1008. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  1009. } else {
  1010. REPORTER_ASSERT(r, SkCodec::kUnimplemented == result);
  1011. }
  1012. result = codec->startIncrementalDecode(infoF16, bm.getPixels(), bm.rowBytes());
  1013. if (supportsIncrementalDecoder) {
  1014. REPORTER_ASSERT(r, SkCodec::kSuccess == result);
  1015. } else {
  1016. REPORTER_ASSERT(r, SkCodec::kUnimplemented == result);
  1017. }
  1018. }
  1019. DEF_TEST(Codec_F16ConversionPossible, r) {
  1020. test_conversion_possible(r, "images/color_wheel.webp", false, false);
  1021. test_conversion_possible(r, "images/mandrill_512_q075.jpg", true, false);
  1022. test_conversion_possible(r, "images/yellow_rose.png", false, true);
  1023. }
  1024. static void decode_frame(skiatest::Reporter* r, SkCodec* codec, size_t frame) {
  1025. SkBitmap bm;
  1026. auto info = codec->getInfo().makeColorType(kN32_SkColorType);
  1027. bm.allocPixels(info);
  1028. SkCodec::Options opts;
  1029. opts.fFrameIndex = frame;
  1030. REPORTER_ASSERT(r, SkCodec::kSuccess == codec->getPixels(info,
  1031. bm.getPixels(), bm.rowBytes(), &opts));
  1032. }
  1033. // For an animated GIF, we should only read enough to decode frame 0 if the
  1034. // client never calls getFrameInfo and only decodes frame 0.
  1035. DEF_TEST(Codec_skipFullParse, r) {
  1036. auto path = "images/test640x479.gif";
  1037. auto streamObj = GetResourceAsStream(path);
  1038. if (!streamObj) {
  1039. return;
  1040. }
  1041. SkStream* stream = streamObj.get();
  1042. // Note that we cheat and hold on to the stream pointer, but SkCodec will
  1043. // take ownership. We will not refer to the stream after the SkCodec
  1044. // deletes it.
  1045. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(streamObj)));
  1046. if (!codec) {
  1047. ERRORF(r, "Failed to create codec for %s", path);
  1048. return;
  1049. }
  1050. REPORTER_ASSERT(r, stream->hasPosition());
  1051. const size_t sizePosition = stream->getPosition();
  1052. REPORTER_ASSERT(r, stream->hasLength() && sizePosition < stream->getLength());
  1053. // This should read more of the stream, but not the whole stream.
  1054. decode_frame(r, codec.get(), 0);
  1055. const size_t positionAfterFirstFrame = stream->getPosition();
  1056. REPORTER_ASSERT(r, positionAfterFirstFrame > sizePosition
  1057. && positionAfterFirstFrame < stream->getLength());
  1058. // There is more data in the stream.
  1059. auto frameInfo = codec->getFrameInfo();
  1060. REPORTER_ASSERT(r, frameInfo.size() == 4);
  1061. REPORTER_ASSERT(r, stream->getPosition() > positionAfterFirstFrame);
  1062. }
  1063. // Only rewinds up to a limit.
  1064. class LimitedRewindingStream : public SkStream {
  1065. public:
  1066. static std::unique_ptr<SkStream> Make(const char path[], size_t limit) {
  1067. auto stream = GetResourceAsStream(path);
  1068. if (!stream) {
  1069. return nullptr;
  1070. }
  1071. return std::unique_ptr<SkStream>(new LimitedRewindingStream(std::move(stream), limit));
  1072. }
  1073. size_t read(void* buffer, size_t size) override {
  1074. const size_t bytes = fStream->read(buffer, size);
  1075. fPosition += bytes;
  1076. return bytes;
  1077. }
  1078. bool isAtEnd() const override {
  1079. return fStream->isAtEnd();
  1080. }
  1081. bool rewind() override {
  1082. if (fPosition <= fLimit && fStream->rewind()) {
  1083. fPosition = 0;
  1084. return true;
  1085. }
  1086. return false;
  1087. }
  1088. private:
  1089. std::unique_ptr<SkStream> fStream;
  1090. const size_t fLimit;
  1091. size_t fPosition;
  1092. LimitedRewindingStream(std::unique_ptr<SkStream> stream, size_t limit)
  1093. : fStream(std::move(stream))
  1094. , fLimit(limit)
  1095. , fPosition(0)
  1096. {
  1097. SkASSERT(fStream);
  1098. }
  1099. };
  1100. DEF_TEST(Codec_fallBack, r) {
  1101. // SkAndroidCodec needs to be able to fall back to scanline decoding
  1102. // if incremental decoding does not work. Make sure this does not
  1103. // require a rewind.
  1104. // Formats that currently do not support incremental decoding
  1105. auto files = {
  1106. "images/CMYK.jpg",
  1107. "images/color_wheel.ico",
  1108. "images/mandrill.wbmp",
  1109. "images/randPixels.bmp",
  1110. };
  1111. for (auto file : files) {
  1112. auto stream = LimitedRewindingStream::Make(file, SkCodec::MinBufferedBytesNeeded());
  1113. if (!stream) {
  1114. SkDebugf("Missing resources (%s). Set --resourcePath.\n", file);
  1115. return;
  1116. }
  1117. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
  1118. if (!codec) {
  1119. ERRORF(r, "Failed to create codec for %s,", file);
  1120. continue;
  1121. }
  1122. SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
  1123. SkBitmap bm;
  1124. bm.allocPixels(info);
  1125. if (SkCodec::kUnimplemented != codec->startIncrementalDecode(info, bm.getPixels(),
  1126. bm.rowBytes())) {
  1127. ERRORF(r, "Is scanline decoding now implemented for %s?", file);
  1128. continue;
  1129. }
  1130. // Scanline decoding should not require a rewind.
  1131. SkCodec::Result result = codec->startScanlineDecode(info);
  1132. if (SkCodec::kSuccess != result) {
  1133. ERRORF(r, "Scanline decoding failed for %s with %i", file, result);
  1134. }
  1135. }
  1136. }
  1137. // This test verifies that we fixed an assert statement that fired when reusing a png codec
  1138. // after scaling.
  1139. DEF_TEST(Codec_reusePng, r) {
  1140. std::unique_ptr<SkStream> stream(GetResourceAsStream("images/plane.png"));
  1141. if (!stream) {
  1142. return;
  1143. }
  1144. std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromStream(std::move(stream)));
  1145. if (!codec) {
  1146. ERRORF(r, "Failed to create codec\n");
  1147. return;
  1148. }
  1149. SkAndroidCodec::AndroidOptions opts;
  1150. opts.fSampleSize = 5;
  1151. auto size = codec->getSampledDimensions(opts.fSampleSize);
  1152. auto info = codec->getInfo().makeWH(size.fWidth, size.fHeight).makeColorType(kN32_SkColorType);
  1153. SkBitmap bm;
  1154. bm.allocPixels(info);
  1155. auto result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &opts);
  1156. REPORTER_ASSERT(r, result == SkCodec::kSuccess);
  1157. info = codec->getInfo().makeColorType(kN32_SkColorType);
  1158. bm.allocPixels(info);
  1159. opts.fSampleSize = 1;
  1160. result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &opts);
  1161. REPORTER_ASSERT(r, result == SkCodec::kSuccess);
  1162. }
  1163. DEF_TEST(Codec_rowsDecoded, r) {
  1164. auto file = "images/plane_interlaced.png";
  1165. std::unique_ptr<SkStream> stream(GetResourceAsStream(file));
  1166. if (!stream) {
  1167. return;
  1168. }
  1169. // This is enough to read the header etc, but no rows.
  1170. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(SkData::MakeFromStream(stream.get(), 99)));
  1171. if (!codec) {
  1172. ERRORF(r, "Failed to create codec\n");
  1173. return;
  1174. }
  1175. auto info = codec->getInfo().makeColorType(kN32_SkColorType);
  1176. SkBitmap bm;
  1177. bm.allocPixels(info);
  1178. auto result = codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes());
  1179. REPORTER_ASSERT(r, result == SkCodec::kSuccess);
  1180. // This is an arbitrary value. The important fact is that it is not zero, and rowsDecoded
  1181. // should get set to zero by incrementalDecode.
  1182. int rowsDecoded = 77;
  1183. result = codec->incrementalDecode(&rowsDecoded);
  1184. REPORTER_ASSERT(r, result == SkCodec::kIncompleteInput);
  1185. REPORTER_ASSERT(r, rowsDecoded == 0);
  1186. }
  1187. static void test_invalid_images(skiatest::Reporter* r, const char* path,
  1188. SkCodec::Result expectedResult) {
  1189. auto stream = GetResourceAsStream(path);
  1190. if (!stream) {
  1191. return;
  1192. }
  1193. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
  1194. REPORTER_ASSERT(r, codec);
  1195. test_info(r, codec.get(), codec->getInfo().makeColorType(kN32_SkColorType), expectedResult,
  1196. nullptr);
  1197. }
  1198. DEF_TEST(Codec_InvalidImages, r) {
  1199. // ASAN will complain if there is an issue.
  1200. test_invalid_images(r, "invalid_images/skbug5887.gif", SkCodec::kErrorInInput);
  1201. test_invalid_images(r, "invalid_images/many-progressive-scans.jpg", SkCodec::kInvalidInput);
  1202. test_invalid_images(r, "invalid_images/b33251605.bmp", SkCodec::kIncompleteInput);
  1203. test_invalid_images(r, "invalid_images/bad_palette.png", SkCodec::kInvalidInput);
  1204. }
  1205. static void test_invalid_header(skiatest::Reporter* r, const char* path) {
  1206. auto data = GetResourceAsData(path);
  1207. if (!data) {
  1208. return;
  1209. }
  1210. std::unique_ptr<SkStreamAsset> stream(new SkMemoryStream(std::move(data)));
  1211. if (!stream) {
  1212. return;
  1213. }
  1214. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
  1215. REPORTER_ASSERT(r, !codec);
  1216. }
  1217. DEF_TEST(Codec_InvalidHeader, r) {
  1218. test_invalid_header(r, "invalid_images/int_overflow.ico");
  1219. // These files report values that have caused problems with SkFILEStreams.
  1220. // They are invalid, and should not create SkCodecs.
  1221. test_invalid_header(r, "invalid_images/b33651913.bmp");
  1222. test_invalid_header(r, "invalid_images/b34778578.bmp");
  1223. }
  1224. /*
  1225. For the Codec_InvalidAnimated test, immediately below,
  1226. resources/invalid_images/skbug6046.gif is:
  1227. 00000000: 4749 4638 3961 2000 0000 0000 002c ff00 GIF89a ......,..
  1228. 00000010: 7400 0600 0000 4001 0021 f904 0a00 0000 t.....@..!......
  1229. 00000020: 002c ff00 0000 ff00 7400 0606 0606 0601 .,......t.......
  1230. 00000030: 0021 f904 0000 0000 002c ff00 0000 ffcc .!.......,......
  1231. 00000040: 1b36 5266 deba 543d .6Rf..T=
  1232. It nominally contains 3 frames, but only the first one is valid. It came from a
  1233. fuzzer doing random mutations and copies. The breakdown:
  1234. @000 6 bytes magic "GIF89a"
  1235. @006 7 bytes Logical Screen Descriptor: 0x20 0x00 ... 0x00
  1236. - width = 32
  1237. - height = 0
  1238. - flags = 0x00
  1239. - background color index, pixel aspect ratio bytes ignored
  1240. @00D 10 bytes Image Descriptor header: 0x2C 0xFF ... 0x40
  1241. - origin_x = 255
  1242. - origin_y = 116
  1243. - width = 6
  1244. - height = 0
  1245. - flags = 0x40, interlaced
  1246. @017 2 bytes Image Descriptor body (pixel data): 0x01 0x00
  1247. - lit_width = 1
  1248. - 0x00 byte means "end of data" for this frame
  1249. @019 8 bytes Graphic Control Extension: 0x21 0xF9 ... 0x00
  1250. - valid, but irrelevant here.
  1251. @021 10 bytes Image Descriptor header: 0x2C 0xFF ... 0x06
  1252. - origin_x = 255
  1253. - origin_y = 0
  1254. - width = 255
  1255. - height = 116
  1256. - flags = 0x06, INVALID, 0x80 BIT ZERO IMPLIES 0x07 BITS SHOULD BE ZERO
  1257. @02B 14 bytes Image Descriptor body (pixel data): 0x06 0x06 ... 0x00
  1258. - lit_width = 6
  1259. - 0x06 precedes a 6 byte block of data
  1260. - 0x04 precedes a 4 byte block of data
  1261. - 0x00 byte means "end of data" for this frame
  1262. @039 10 bytes Image Descriptor header: 0x2C 0xFF ... 0x06
  1263. - origin_x = 255
  1264. - origin_y = 0
  1265. - width = 52479
  1266. - height = 13851
  1267. - flags = 0x52, INVALID, 0x80 BIT ZERO IMPLIES 0x07 BITS SHOULD BE ZERO
  1268. @043 5 bytes Image Descriptor body (pixel data): 0x66 0xDE ... unexpected-EOF
  1269. - lit_width = 102, INVALID, GREATER THAN 8
  1270. - 0xDE precedes a 222 byte block of data, INVALIDLY TRUNCATED
  1271. On Image Descriptor flags INVALIDITY,
  1272. https://www.w3.org/Graphics/GIF/spec-gif89a.txt section 20.c says that "Size of
  1273. Local Color Table [the low 3 bits]... should be 0 if there is no Local Color
  1274. Table specified [the high bit]."
  1275. On LZW literal width (also known as Minimum Code Size) INVALIDITY,
  1276. https://www.w3.org/Graphics/GIF/spec-gif89a.txt Appendix F says that "Normally
  1277. this will be the same as the number of [palette index] bits. Because of some
  1278. algorithmic constraints however, black & white images which have one color bit
  1279. must be indicated as having a code size of 2." In practice, some GIF decoders,
  1280. including both the old third_party/gif code and the Wuffs GIF decoder, don't
  1281. enforce this "at least 2" constraint. Nonetheless, any width greater than 8 is
  1282. invalid, as there are only 8 bits in a byte.
  1283. */
  1284. DEF_TEST(Codec_InvalidAnimated, r) {
  1285. // ASAN will complain if there is an issue.
  1286. auto path = "invalid_images/skbug6046.gif";
  1287. auto stream = GetResourceAsStream(path);
  1288. if (!stream) {
  1289. return;
  1290. }
  1291. std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
  1292. REPORTER_ASSERT(r, codec);
  1293. if (!codec) {
  1294. return;
  1295. }
  1296. const auto info = codec->getInfo().makeColorType(kN32_SkColorType);
  1297. SkBitmap bm;
  1298. bm.allocPixels(info);
  1299. auto frameInfos = codec->getFrameInfo();
  1300. SkCodec::Options opts;
  1301. for (int i = 0; static_cast<size_t>(i) < frameInfos.size(); i++) {
  1302. opts.fFrameIndex = i;
  1303. const auto reqFrame = frameInfos[i].fRequiredFrame;
  1304. opts.fPriorFrame = reqFrame == i - 1 ? reqFrame : SkCodec::kNoFrame;
  1305. auto result = codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes(), &opts);
  1306. if (result != SkCodec::kSuccess) {
  1307. ERRORF(r, "Failed to start decoding frame %i (out of %i) with error %i\n", i,
  1308. frameInfos.size(), result);
  1309. continue;
  1310. }
  1311. codec->incrementalDecode();
  1312. }
  1313. }
  1314. static void encode_format(SkDynamicMemoryWStream* stream, const SkPixmap& pixmap,
  1315. SkEncodedImageFormat format) {
  1316. switch (format) {
  1317. case SkEncodedImageFormat::kPNG:
  1318. SkPngEncoder::Encode(stream, pixmap, SkPngEncoder::Options());
  1319. break;
  1320. case SkEncodedImageFormat::kJPEG:
  1321. SkJpegEncoder::Encode(stream, pixmap, SkJpegEncoder::Options());
  1322. break;
  1323. case SkEncodedImageFormat::kWEBP:
  1324. SkWebpEncoder::Encode(stream, pixmap, SkWebpEncoder::Options());
  1325. break;
  1326. default:
  1327. SkASSERT(false);
  1328. break;
  1329. }
  1330. }
  1331. static void test_encode_icc(skiatest::Reporter* r, SkEncodedImageFormat format) {
  1332. // Test with sRGB color space.
  1333. SkBitmap srgbBitmap;
  1334. SkImageInfo srgbInfo = SkImageInfo::MakeS32(1, 1, kOpaque_SkAlphaType);
  1335. srgbBitmap.allocPixels(srgbInfo);
  1336. *srgbBitmap.getAddr32(0, 0) = 0;
  1337. SkPixmap pixmap;
  1338. srgbBitmap.peekPixels(&pixmap);
  1339. SkDynamicMemoryWStream srgbBuf;
  1340. encode_format(&srgbBuf, pixmap, format);
  1341. sk_sp<SkData> srgbData = srgbBuf.detachAsData();
  1342. std::unique_ptr<SkCodec> srgbCodec(SkCodec::MakeFromData(srgbData));
  1343. REPORTER_ASSERT(r, srgbCodec->getInfo().colorSpace() == sk_srgb_singleton());
  1344. // Test with P3 color space.
  1345. SkDynamicMemoryWStream p3Buf;
  1346. sk_sp<SkColorSpace> p3 = SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, SkNamedGamut::kDCIP3);
  1347. pixmap.setColorSpace(p3);
  1348. encode_format(&p3Buf, pixmap, format);
  1349. sk_sp<SkData> p3Data = p3Buf.detachAsData();
  1350. std::unique_ptr<SkCodec> p3Codec(SkCodec::MakeFromData(p3Data));
  1351. REPORTER_ASSERT(r, p3Codec->getInfo().colorSpace()->gammaCloseToSRGB());
  1352. skcms_Matrix3x3 mat0, mat1;
  1353. bool success = p3->toXYZD50(&mat0);
  1354. REPORTER_ASSERT(r, success);
  1355. success = p3Codec->getInfo().colorSpace()->toXYZD50(&mat1);
  1356. REPORTER_ASSERT(r, success);
  1357. for (int i = 0; i < 3; i++) {
  1358. for (int j = 0; j < 3; j++) {
  1359. REPORTER_ASSERT(r, color_space_almost_equal(mat0.vals[i][j], mat1.vals[i][j]));
  1360. }
  1361. }
  1362. }
  1363. DEF_TEST(Codec_EncodeICC, r) {
  1364. test_encode_icc(r, SkEncodedImageFormat::kPNG);
  1365. test_encode_icc(r, SkEncodedImageFormat::kJPEG);
  1366. test_encode_icc(r, SkEncodedImageFormat::kWEBP);
  1367. }
  1368. DEF_TEST(Codec_webp_rowsDecoded, r) {
  1369. const char* path = "images/baby_tux.webp";
  1370. sk_sp<SkData> data(GetResourceAsData(path));
  1371. if (!data) {
  1372. return;
  1373. }
  1374. // Truncate this file so that the header is available but no rows can be
  1375. // decoded. This should create a codec but fail to decode.
  1376. size_t truncatedSize = 5000;
  1377. sk_sp<SkData> subset = SkData::MakeSubset(data.get(), 0, truncatedSize);
  1378. std::unique_ptr<SkCodec> codec = SkCodec::MakeFromData(std::move(subset));
  1379. if (!codec) {
  1380. ERRORF(r, "Failed to create a codec for %s truncated to only %lu bytes",
  1381. path, truncatedSize);
  1382. return;
  1383. }
  1384. test_info(r, codec.get(), codec->getInfo(), SkCodec::kInvalidInput, nullptr);
  1385. }
  1386. /*
  1387. For the Codec_ossfuzz6274 test, immediately below,
  1388. resources/invalid_images/ossfuzz6274.gif is:
  1389. 00000000: 4749 4638 3961 2000 2000 f120 2020 2020 GIF89a . ..
  1390. 00000010: 2020 2020 2020 2020 2021 f903 ff20 2020 !...
  1391. 00000020: 002c 0000 0000 2000 2000 2000 00 .,.... . . ..
  1392. @000 6 bytes magic "GIF89a"
  1393. @006 7 bytes Logical Screen Descriptor: 0x20 0x00 ... 0x00
  1394. - width = 32
  1395. - height = 32
  1396. - flags = 0xF1, global color table, 4 RGB entries
  1397. - background color index, pixel aspect ratio bytes ignored
  1398. @00D 12 bytes Color Table: 0x20 0x20 ... 0x20
  1399. @019 20 bytes Graphic Control Extension: 0x21 0xF9 ... unexpected-EOF
  1400. - 0x03 precedes a 3 byte block of data, INVALID, MUST BE 4
  1401. - 0x20 precedes a 32 byte block of data, INVALIDly truncated
  1402. https://www.w3.org/Graphics/GIF/spec-gif89a.txt section 23.c says that the
  1403. block size (for an 0x21 0xF9 Graphic Control Extension) must be "the fixed
  1404. value 4".
  1405. */
  1406. DEF_TEST(Codec_ossfuzz6274, r) {
  1407. if (GetResourcePath().isEmpty()) {
  1408. return;
  1409. }
  1410. const char* file = "invalid_images/ossfuzz6274.gif";
  1411. auto image = GetResourceAsImage(file);
  1412. #ifdef SK_HAS_WUFFS_LIBRARY
  1413. // We are transitioning from an old GIF implementation to a new (Wuffs) GIF
  1414. // implementation.
  1415. //
  1416. // This test (without SK_HAS_WUFFS_LIBRARY) is overly specific to the old
  1417. // implementation. In the new implementation, the MakeFromStream factory
  1418. // method returns a nullptr SkImage*, instead of returning a non-null but
  1419. // otherwise all-transparent SkImage*.
  1420. //
  1421. // Either way, the end-to-end result is the same - the source input is
  1422. // rejected as an invalid GIF image - but the two implementations differ in
  1423. // how that's represented.
  1424. //
  1425. // Once the transition is complete, we can remove the #ifdef and delete the
  1426. // rest of the test function.
  1427. //
  1428. // See Codec_GifTruncated3 for the equivalent of the rest of the test
  1429. // function, on different (but still truncated) source data.
  1430. if (image) {
  1431. ERRORF(r, "Invalid data gave non-nullptr image");
  1432. }
  1433. return;
  1434. #endif
  1435. if (!image) {
  1436. ERRORF(r, "Missing %s", file);
  1437. return;
  1438. }
  1439. REPORTER_ASSERT(r, image->width() == 32);
  1440. REPORTER_ASSERT(r, image->height() == 32);
  1441. SkBitmap bm;
  1442. if (!bm.tryAllocPixels(SkImageInfo::MakeN32Premul(32, 32))) {
  1443. ERRORF(r, "Failed to allocate pixels");
  1444. return;
  1445. }
  1446. bm.eraseColor(SK_ColorTRANSPARENT);
  1447. SkCanvas canvas(bm);
  1448. canvas.drawImage(image, 0, 0, nullptr);
  1449. for (int i = 0; i < image->width(); ++i)
  1450. for (int j = 0; j < image->height(); ++j) {
  1451. SkColor actual = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(i, j));
  1452. if (actual != SK_ColorTRANSPARENT) {
  1453. ERRORF(r, "did not initialize pixels! %i, %i is %x", i, j, actual);
  1454. }
  1455. }
  1456. }
  1457. DEF_TEST(Codec_78329453, r) {
  1458. if (GetResourcePath().isEmpty()) {
  1459. return;
  1460. }
  1461. const char* file = "images/b78329453.jpeg";
  1462. auto data = GetResourceAsData(file);
  1463. if (!data) {
  1464. ERRORF(r, "Missing %s", file);
  1465. return;
  1466. }
  1467. auto codec = SkAndroidCodec::MakeFromCodec(SkCodec::MakeFromData(data));
  1468. if (!codec) {
  1469. ERRORF(r, "failed to create codec from %s", file);
  1470. return;
  1471. }
  1472. // A bug in jpeg_skip_scanlines resulted in an infinite loop for this specific
  1473. // sample size on this image. Other sample sizes could have had the same result,
  1474. // but the ones tested by DM happen to not.
  1475. constexpr int kSampleSize = 19;
  1476. const auto size = codec->getSampledDimensions(kSampleSize);
  1477. auto info = codec->getInfo().makeWH(size.width(), size.height());
  1478. SkBitmap bm;
  1479. bm.allocPixels(info);
  1480. bm.eraseColor(SK_ColorTRANSPARENT);
  1481. SkAndroidCodec::AndroidOptions options;
  1482. options.fSampleSize = kSampleSize;
  1483. auto result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &options);
  1484. if (result != SkCodec::kSuccess) {
  1485. ERRORF(r, "failed to decode with error %s", SkCodec::ResultToString(result));
  1486. }
  1487. }
  1488. DEF_TEST(Codec_A8, r) {
  1489. if (GetResourcePath().isEmpty()) {
  1490. return;
  1491. }
  1492. const char* file = "images/mandrill_cmyk.jpg";
  1493. auto data = GetResourceAsData(file);
  1494. if (!data) {
  1495. ERRORF(r, "missing %s", file);
  1496. return;
  1497. }
  1498. auto codec = SkCodec::MakeFromData(std::move(data));
  1499. auto info = codec->getInfo().makeColorType(kAlpha_8_SkColorType);
  1500. SkBitmap bm;
  1501. bm.allocPixels(info);
  1502. REPORTER_ASSERT(r, codec->getPixels(bm.pixmap()) == SkCodec::kInvalidConversion);
  1503. }
  1504. DEF_TEST(Codec_crbug807324, r) {
  1505. if (GetResourcePath().isEmpty()) {
  1506. return;
  1507. }
  1508. const char* file = "images/crbug807324.png";
  1509. auto image = GetResourceAsImage(file);
  1510. if (!image) {
  1511. ERRORF(r, "Missing %s", file);
  1512. return;
  1513. }
  1514. const int kWidth = image->width();
  1515. const int kHeight = image->height();
  1516. SkBitmap bm;
  1517. if (!bm.tryAllocPixels(SkImageInfo::MakeN32Premul(kWidth, kHeight))) {
  1518. ERRORF(r, "Could not allocate pixels (%i x %i)", kWidth, kHeight);
  1519. return;
  1520. }
  1521. bm.eraseColor(SK_ColorTRANSPARENT);
  1522. SkCanvas canvas(bm);
  1523. canvas.drawImage(image, 0, 0, nullptr);
  1524. for (int i = 0; i < kWidth; ++i)
  1525. for (int j = 0; j < kHeight; ++j) {
  1526. if (*bm.getAddr32(i, j) == SK_ColorTRANSPARENT) {
  1527. ERRORF(r, "image should not be transparent! %i, %i is 0", i, j);
  1528. return;
  1529. }
  1530. }
  1531. }