Debian Codegraph @

gm/wacky_yuv_formats.cpp

raw
1 /*
2 * Copyright 2018 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
8 #include "gm/gm.h"
9 #include "include/core/SkBitmap.h"
10 #include "include/core/SkBlendMode.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkColor.h"
13 #include "include/core/SkColorFilter.h"
14 #include "include/core/SkColorSpace.h"
15 #include "include/core/SkFont.h"
16 #include "include/core/SkFontStyle.h"
17 #include "include/core/SkFontTypes.h"
18 #include "include/core/SkImage.h"
19 #include "include/core/SkImageGenerator.h"
20 #include "include/core/SkImageInfo.h"
21 #include "include/core/SkMatrix.h"
22 #include "include/core/SkPaint.h"
23 #include "include/core/SkPath.h"
24 #include "include/core/SkPathBuilder.h"
25 #include "include/core/SkPixmap.h"
26 #include "include/core/SkPoint.h"
27 #include "include/core/SkRect.h"
28 #include "include/core/SkRefCnt.h"
29 #include "include/core/SkScalar.h"
30 #include "include/core/SkSize.h"
31 #include "include/core/SkString.h"
32 #include "include/core/SkTypeface.h"
33 #include "include/core/SkTypes.h"
34 #include "include/gpu/graphite/Image.h"
35 #include "include/private/base/SkTArray.h"
36 #include "include/private/base/SkTDArray.h"
37 #include "include/private/base/SkTPin.h"
38 #include "include/private/base/SkTemplates.h"
39 #include "include/utils/SkTextUtils.h"
40 #include "src/base/SkHalf.h"
41 #include "src/core/SkColorPriv.h"
42 #include "src/core/SkConvertPixels.h"
43 #include "src/core/SkYUVMath.h"
44 #include "src/image/SkImage_Base.h"
45 #include "tools/DecodeUtils.h"
46 #include "tools/ToolUtils.h"
47 #include "tools/fonts/FontToolUtils.h"
48 #include "tools/gpu/YUVUtils.h"
49
50 #if defined(SK_GANESH)
51 #include "include/gpu/ganesh/GrBackendSurface.h"
52 #include "include/gpu/ganesh/GrDirectContext.h"
53 #include "include/gpu/ganesh/GrRecordingContext.h"
54 #include "include/gpu/ganesh/GrTypes.h"
55 #include "include/gpu/ganesh/SkImageGanesh.h"
56 #include "include/private/gpu/ganesh/GrTypesPriv.h"
57 #include "src/gpu/ganesh/GrCaps.h"
58 #include "src/gpu/ganesh/GrRecordingContextPriv.h"
59 #include "src/gpu/ganesh/SkGaneshRecorder.h"
60 #endif
61
62 #if defined(SK_GRAPHITE)
63 #include "include/gpu/graphite/Recorder.h"
64 #include "src/gpu/graphite/RecorderPriv.h"
65 #endif
66
67 #include <math.h>
68 #include <string.h>
69 #include <initializer_list>
70 #include <memory>
71 #include <utility>
72 #include <vector>
73
74 static const int kTileWidthHeight = 128;
75 static const int kLabelWidth = 64;
76 static const int kLabelHeight = 32;
77 static const int kSubsetPadding = 8;
78 static const int kPad = 1;
79
80 using Recorder = skgpu::graphite::Recorder;
81
82 enum YUVFormat {
83 // 4:2:0 formats, 24 bpp
84 kP016_YUVFormat, // 16-bit Y plane + 2x2 down sampled interleaved U/V plane (2 textures)
85 // 4:2:0 formats, "15 bpp" (but really 24 bpp)
86 kP010_YUVFormat, // same as kP016 except "10 bpp". Note that it is the same memory layout
87 // except that the bottom 6 bits are zeroed out (2 textures)
88 // TODO: we're cheating a bit w/ P010 and just treating it as unorm 16. This means its
89 // fully saturated values are 65504 rather than 65535 (that is just .9995 out of 1.0 though).
90
91 // This is laid out the same as kP016 and kP010 but uses F16 unstead of U16. In this case
92 // the 10 bits/channel vs 16 bits/channel distinction isn't relevant.
93 kP016F_YUVFormat,
94
95 // 4:4:4 formats, 64 bpp
96 kY416_YUVFormat, // 16-bit AVYU values all interleaved (1 texture)
97
98 // 4:4:4 formats, 32 bpp
99 kAYUV_YUVFormat, // 8-bit YUVA values all interleaved (1 texture)
100 kY410_YUVFormat, // AVYU w/ 10bpp for YUV and 2 for A all interleaved (1 texture)
101
102 // 4:2:0 formats, 12 bpp
103 kNV12_YUVFormat, // 8-bit Y plane + 2x2 down sampled interleaved U/V planes (2 textures)
104 kNV21_YUVFormat, // same as kNV12 but w/ U/V reversed in the interleaved texture (2 textures)
105
106 kI420_YUVFormat, // 8-bit Y plane + separate 2x2 down sampled U and V planes (3 textures)
107 kYV12_YUVFormat, // 8-bit Y plane + separate 2x2 down sampled V and U planes (3 textures)
108
109 kLast_YUVFormat = kYV12_YUVFormat
110 };
111
112 // Does the YUVFormat contain a slot for alpha? If not an external alpha plane is required for
113 // transparency.
114 static bool has_alpha_channel(YUVFormat format) {
115 switch (format) {
116 case kP016_YUVFormat: return false;
117 case kP010_YUVFormat: return false;
118 case kP016F_YUVFormat: return false;
119 case kY416_YUVFormat: return true;
120 case kAYUV_YUVFormat: return true;
121 case kY410_YUVFormat: return true;
122 case kNV12_YUVFormat: return false;
123 case kNV21_YUVFormat: return false;
124 case kI420_YUVFormat: return false;
125 case kYV12_YUVFormat: return false;
126 }
127 SkUNREACHABLE;
128 }
129
130 class YUVAPlanarConfig {
131 public:
132 YUVAPlanarConfig(YUVFormat format, bool opaque, SkEncodedOrigin origin) : fOrigin(origin) {
133 switch (format) {
134 case kP016_YUVFormat:
135 case kP010_YUVFormat:
136 case kP016F_YUVFormat:
137 case kNV12_YUVFormat:
138 if (opaque) {
139 fPlaneConfig = SkYUVAInfo::PlaneConfig::kY_UV;
140 fSubsampling = SkYUVAInfo::Subsampling::k420;
141 } else {
142 fPlaneConfig = SkYUVAInfo::PlaneConfig::kY_UV_A;
143 fSubsampling = SkYUVAInfo::Subsampling::k420;
144 }
145 break;
146 case kY416_YUVFormat:
147 case kY410_YUVFormat:
148 if (opaque) {
149 fPlaneConfig = SkYUVAInfo::PlaneConfig::kUYV;
150 fSubsampling = SkYUVAInfo::Subsampling::k444;
151 } else {
152 fPlaneConfig = SkYUVAInfo::PlaneConfig::kUYVA;
153 fSubsampling = SkYUVAInfo::Subsampling::k444;
154 }
155 break;
156 case kAYUV_YUVFormat:
157 if (opaque) {
158 fPlaneConfig = SkYUVAInfo::PlaneConfig::kYUV;
159 fSubsampling = SkYUVAInfo::Subsampling::k444;
160 } else {
161 fPlaneConfig = SkYUVAInfo::PlaneConfig::kYUVA;
162 fSubsampling = SkYUVAInfo::Subsampling::k444;
163 }
164 break;
165 case kNV21_YUVFormat:
166 if (opaque) {
167 fPlaneConfig = SkYUVAInfo::PlaneConfig::kY_VU;
168 fSubsampling = SkYUVAInfo::Subsampling::k420;
169 } else {
170 fPlaneConfig = SkYUVAInfo::PlaneConfig::kY_VU_A;
171 fSubsampling = SkYUVAInfo::Subsampling::k420;
172 }
173 break;
174 case kI420_YUVFormat:
175 if (opaque) {
176 fPlaneConfig = SkYUVAInfo::PlaneConfig::kY_U_V;
177 fSubsampling = SkYUVAInfo::Subsampling::k420;
178 } else {
179 fPlaneConfig = SkYUVAInfo::PlaneConfig::kY_U_V_A;
180 fSubsampling = SkYUVAInfo::Subsampling::k420;
181 }
182 break;
183 case kYV12_YUVFormat:
184 if (opaque) {
185 fPlaneConfig = SkYUVAInfo::PlaneConfig::kY_V_U;
186 fSubsampling = SkYUVAInfo::Subsampling::k420;
187 } else {
188 fPlaneConfig = SkYUVAInfo::PlaneConfig::kY_V_U_A;
189 fSubsampling = SkYUVAInfo::Subsampling::k420;
190 }
191 break;
192 }
193 }
194
195 int numPlanes() const { return SkYUVAInfo::NumPlanes(fPlaneConfig); }
196
197 SkYUVAPixmaps makeYUVAPixmaps(SkISize dimensions,
198 SkYUVColorSpace yuvColorSpace,
199 const SkBitmap bitmaps[],
200 int numBitmaps) const;
201
202 private:
203 SkYUVAInfo::PlaneConfig fPlaneConfig;
204 SkYUVAInfo::Subsampling fSubsampling;
205 SkEncodedOrigin fOrigin;
206 };
207
208 SkYUVAPixmaps YUVAPlanarConfig::makeYUVAPixmaps(SkISize dimensions,
209 SkYUVColorSpace yuvColorSpace,
210 const SkBitmap bitmaps[],
211 int numBitmaps) const {
212 SkYUVAInfo info(dimensions, fPlaneConfig, fSubsampling, yuvColorSpace, fOrigin);
213 SkPixmap pmaps[SkYUVAInfo::kMaxPlanes];
214 int n = info.numPlanes();
215 if (numBitmaps < n) {
216 return {};
217 }
218 for (int i = 0; i < n; ++i) {
219 pmaps[i] = bitmaps[i].pixmap();
220 }
221 return SkYUVAPixmaps::FromExternalPixmaps(info, pmaps);
222 }
223
224 // All the planes we need to construct the various YUV formats
225 struct PlaneData {
226 SkBitmap fYFull;
227 SkBitmap fUFull;
228 SkBitmap fVFull;
229 SkBitmap fAFull;
230 SkBitmap fUQuarter; // 2x2 downsampled U channel
231 SkBitmap fVQuarter; // 2x2 downsampled V channel
232
233 SkBitmap fFull;
234 SkBitmap fQuarter; // 2x2 downsampled YUVA
235 };
236
237 // Add a portion of a circle to 'path'. The points 'o1' and 'o2' are on the border of the circle
238 // and have tangents 'v1' and 'v2'.
239 static void add_arc(SkPathBuilder* path,
240 const SkPoint& o1, const SkVector& v1,
241 const SkPoint& o2, const SkVector& v2,
242 SkTDArray<SkRect>* circles, bool takeLongWayRound) {
243
244 SkVector v3 = { -v1.fY, v1.fX };
245 SkVector v4 = { v2.fY, -v2.fX };
246
247 SkScalar t = ((o2.fX - o1.fX) * v4.fY - (o2.fY - o1.fY) * v4.fX) / v3.cross(v4);
248 SkPoint center = { o1.fX + t * v3.fX, o1.fY + t * v3.fY };
249
250 SkRect r = { center.fX - t, center.fY - t, center.fX + t, center.fY + t };
251
252 if (circles) {
253 circles->push_back(r);
254 }
255
256 SkVector startV = o1 - center, endV = o2 - center;
257 startV.normalize();
258 endV.normalize();
259
260 SkScalar startDeg = SkRadiansToDegrees(SkScalarATan2(startV.fY, startV.fX));
261 SkScalar endDeg = SkRadiansToDegrees(SkScalarATan2(endV.fY, endV.fX));
262
263 startDeg += 360.0f;
264 startDeg = fmodf(startDeg, 360.0f);
265
266 endDeg += 360.0f;
267 endDeg = fmodf(endDeg, 360.0f);
268
269 if (endDeg < startDeg) {
270 endDeg += 360.0f;
271 }
272
273 SkScalar sweepDeg = SkTAbs(endDeg - startDeg);
274 if (!takeLongWayRound) {
275 sweepDeg = sweepDeg - 360;
276 }
277
278 path->arcTo(r, startDeg, sweepDeg, false);
279 }
280
281 static SkPath create_splat(const SkPoint& o, SkScalar innerRadius, SkScalar outerRadius,
282 SkScalar ratio, int numLobes, SkTDArray<SkRect>* circles) {
283 if (numLobes <= 1) {
284 return SkPath();
285 }
286
287 int numDivisions = 2 * numLobes;
288 SkScalar fullLobeDegrees = 360.0f / numLobes;
289 SkScalar outDegrees = ratio * fullLobeDegrees / (ratio + 1.0f);
290 SkScalar innerDegrees = fullLobeDegrees / (ratio + 1.0f);
291 SkMatrix outerStep, innerStep;
292 outerStep.setRotate(outDegrees);
293 innerStep.setRotate(innerDegrees);
294 SkVector curV = SkVector::Make(0.0f, 1.0f);
295
296 if (circles) {
297 circles->push_back(SkRect::MakeLTRB(o.fX - innerRadius, o.fY - innerRadius,
298 o.fX + innerRadius, o.fY + innerRadius));
299 }
300
301 SkPathBuilder p;
302 p.moveTo(o.fX + innerRadius * curV.fX, o.fY + innerRadius * curV.fY);
303
304 for (int i = 0; i < numDivisions; ++i) {
305
306 SkVector nextV;
307 if (0 == (i % 2)) {
308 nextV = outerStep.mapVector(curV.fX, curV.fY);
309
310 SkPoint top = SkPoint::Make(o.fX + outerRadius * curV.fX,
311 o.fY + outerRadius * curV.fY);
312 SkPoint nextTop = SkPoint::Make(o.fX + outerRadius * nextV.fX,
313 o.fY + outerRadius * nextV.fY);
314
315 p.lineTo(top);
316 add_arc(&p, top, curV, nextTop, nextV, circles, true);
317 } else {
318 nextV = innerStep.mapVector(curV.fX, curV.fY);
319
320 SkPoint bot = SkPoint::Make(o.fX + innerRadius * curV.fX,
321 o.fY + innerRadius * curV.fY);
322 SkPoint nextBot = SkPoint::Make(o.fX + innerRadius * nextV.fX,
323 o.fY + innerRadius * nextV.fY);
324
325 p.lineTo(bot);
326 add_arc(&p, bot, curV, nextBot, nextV, nullptr, false);
327 }
328
329 curV = nextV;
330 }
331
332 p.close();
333
334 return p.detach();
335 }
336
337 static SkBitmap make_bitmap(SkColorType colorType, const SkPath& path,
338 const SkTDArray<SkRect>& circles, bool opaque, bool padWithRed) {
339 const SkColor kGreen = ToolUtils::color_to_565(SkColorSetARGB(0xFF, 178, 240, 104));
340 const SkColor kBlue = ToolUtils::color_to_565(SkColorSetARGB(0xFF, 173, 167, 252));
341 const SkColor kYellow = ToolUtils::color_to_565(SkColorSetARGB(0xFF, 255, 221, 117));
342 const SkColor kMagenta = ToolUtils::color_to_565(SkColorSetARGB(0xFF, 255, 60, 217));
343 const SkColor kCyan = ToolUtils::color_to_565(SkColorSetARGB(0xFF, 45, 237, 205));
344
345 int widthHeight = kTileWidthHeight + (padWithRed ? 2 * kSubsetPadding : 0);
346
347 SkImageInfo ii = SkImageInfo::Make(widthHeight, widthHeight,
348 colorType, kPremul_SkAlphaType);
349
350 SkBitmap bm;
351 bm.allocPixels(ii);
352
353 std::unique_ptr<SkCanvas> canvas = SkCanvas::MakeRasterDirect(ii,
354 bm.getPixels(),
355 bm.rowBytes());
356 if (padWithRed) {
357 canvas->clear(SK_ColorRED);
358 canvas->translate(kSubsetPadding, kSubsetPadding);
359 canvas->clipRect(SkRect::MakeWH(kTileWidthHeight, kTileWidthHeight));
360 }
361 canvas->clear(opaque ? kGreen : SK_ColorTRANSPARENT);
362
363 SkPaint paint;
364 paint.setAntiAlias(false); // serialize-8888 doesn't seem to work well w/ partial transparency
365 paint.setColor(kBlue);
366
367 canvas->drawPath(path, paint);
368
369 paint.setBlendMode(SkBlendMode::kSrc);
370 for (int i = 0; i < circles.size(); ++i) {
371 SkColor color;
372 switch (i % 3) {
373 case 0: color = kYellow; break;
374 case 1: color = kMagenta; break;
375 default: color = kCyan; break;
376 }
377 paint.setColor(color);
378 paint.setAlpha(opaque ? 0xFF : 0x40);
379 SkRect r = circles[i];
380 r.inset(r.width()/4, r.height()/4);
381 canvas->drawOval(r, paint);
382 }
383
384 return bm;
385 }
386
387 static void convert_rgba_to_yuva(const float mtx[20], SkColor col, uint8_t yuv[4]) {
388 const uint8_t r = SkColorGetR(col);
389 const uint8_t g = SkColorGetG(col);
390 const uint8_t b = SkColorGetB(col);
391
392 yuv[0] = SkTPin(SkScalarRoundToInt(mtx[ 0]*r + mtx[ 1]*g + mtx[ 2]*b + mtx[ 4]*255), 0, 255);
393 yuv[1] = SkTPin(SkScalarRoundToInt(mtx[ 5]*r + mtx[ 6]*g + mtx[ 7]*b + mtx[ 9]*255), 0, 255);
394 yuv[2] = SkTPin(SkScalarRoundToInt(mtx[10]*r + mtx[11]*g + mtx[12]*b + mtx[14]*255), 0, 255);
395 yuv[3] = SkColorGetA(col);
396 }
397
398 static void extract_planes(const SkBitmap& origBM,
399 SkYUVColorSpace yuvColorSpace,
400 SkEncodedOrigin origin,
401 PlaneData* planes) {
402 SkImageInfo ii = origBM.info();
403 if (SkEncodedOriginSwapsWidthHeight(origin)) {
404 ii = ii.makeWH(ii.height(), ii.width());
405 }
406 SkBitmap orientedBM;
407 orientedBM.allocPixels(ii);
408 SkCanvas canvas(orientedBM);
409 SkMatrix matrix = SkEncodedOriginToMatrixInverse(origin, origBM.width(), origBM.height());
410 canvas.concat(matrix);
411 canvas.drawImage(origBM.asImage(), 0, 0);
412
413 if (yuvColorSpace == kIdentity_SkYUVColorSpace) {
414 // To test the identity color space we use JPEG YUV planes
415 yuvColorSpace = kJPEG_SkYUVColorSpace;
416 }
417
418 SkASSERT(!(ii.width() % 2));
419 SkASSERT(!(ii.height() % 2));
420 planes->fYFull.allocPixels(
421 SkImageInfo::Make(ii.dimensions(), kGray_8_SkColorType, kUnpremul_SkAlphaType));
422 planes->fUFull.allocPixels(
423 SkImageInfo::Make(ii.dimensions(), kGray_8_SkColorType, kUnpremul_SkAlphaType));
424 planes->fVFull.allocPixels(
425 SkImageInfo::Make(ii.dimensions(), kGray_8_SkColorType, kUnpremul_SkAlphaType));
426 planes->fAFull.allocPixels(SkImageInfo::MakeA8(ii.dimensions()));
427 planes->fUQuarter.allocPixels(SkImageInfo::Make(ii.width()/2, ii.height()/2,
428 kGray_8_SkColorType, kUnpremul_SkAlphaType));
429 planes->fVQuarter.allocPixels(SkImageInfo::Make(ii.width()/2, ii.height()/2,
430 kGray_8_SkColorType, kUnpremul_SkAlphaType));
431
432 planes->fFull.allocPixels(
433 SkImageInfo::Make(ii.dimensions(), kRGBA_F32_SkColorType, kUnpremul_SkAlphaType));
434 planes->fQuarter.allocPixels(SkImageInfo::Make(ii.width()/2, ii.height()/2,
435 kRGBA_F32_SkColorType, kUnpremul_SkAlphaType));
436
437 float mtx[20];
438 SkColorMatrix_RGB2YUV(yuvColorSpace, mtx);
439
440 SkColor4f* dst = (SkColor4f *) planes->fFull.getAddr(0, 0);
441 for (int y = 0; y < orientedBM.height(); ++y) {
442 for (int x = 0; x < orientedBM.width(); ++x) {
443 SkColor col = orientedBM.getColor(x, y);
444
445 uint8_t yuva[4];
446
447 convert_rgba_to_yuva(mtx, col, yuva);
448
449 *planes->fYFull.getAddr8(x, y) = yuva[0];
450 *planes->fUFull.getAddr8(x, y) = yuva[1];
451 *planes->fVFull.getAddr8(x, y) = yuva[2];
452 *planes->fAFull.getAddr8(x, y) = yuva[3];
453
454 // TODO: render in F32 rather than converting here
455 dst->fR = yuva[0] / 255.0f;
456 dst->fG = yuva[1] / 255.0f;
457 dst->fB = yuva[2] / 255.0f;
458 dst->fA = yuva[3] / 255.0f;
459 ++dst;
460 }
461 }
462
463 dst = (SkColor4f *) planes->fQuarter.getAddr(0, 0);
464 for (int y = 0; y < orientedBM.height()/2; ++y) {
465 for (int x = 0; x < orientedBM.width()/2; ++x) {
466 uint32_t yAccum = 0, uAccum = 0, vAccum = 0, aAccum = 0;
467
468 yAccum += *planes->fYFull.getAddr8(2*x, 2*y);
469 yAccum += *planes->fYFull.getAddr8(2*x+1, 2*y);
470 yAccum += *planes->fYFull.getAddr8(2*x, 2*y+1);
471 yAccum += *planes->fYFull.getAddr8(2*x+1, 2*y+1);
472
473 uAccum += *planes->fUFull.getAddr8(2*x, 2*y);
474 uAccum += *planes->fUFull.getAddr8(2*x+1, 2*y);
475 uAccum += *planes->fUFull.getAddr8(2*x, 2*y+1);
476 uAccum += *planes->fUFull.getAddr8(2*x+1, 2*y+1);
477
478 *planes->fUQuarter.getAddr8(x, y) = uAccum / 4.0f;
479
480 vAccum += *planes->fVFull.getAddr8(2*x, 2*y);
481 vAccum += *planes->fVFull.getAddr8(2*x+1, 2*y);
482 vAccum += *planes->fVFull.getAddr8(2*x, 2*y+1);
483 vAccum += *planes->fVFull.getAddr8(2*x+1, 2*y+1);
484
485 *planes->fVQuarter.getAddr8(x, y) = vAccum / 4.0f;
486
487 aAccum += *planes->fAFull.getAddr8(2*x, 2*y);
488 aAccum += *planes->fAFull.getAddr8(2*x+1, 2*y);
489 aAccum += *planes->fAFull.getAddr8(2*x, 2*y+1);
490 aAccum += *planes->fAFull.getAddr8(2*x+1, 2*y+1);
491
492 // TODO: render in F32 rather than converting here
493 dst->fR = yAccum / (4.0f * 255.0f);
494 dst->fG = uAccum / (4.0f * 255.0f);
495 dst->fB = vAccum / (4.0f * 255.0f);
496 dst->fA = aAccum / (4.0f * 255.0f);
497 ++dst;
498 }
499 }
500 }
501
502 // Create a 2x2 downsampled SkBitmap. It is stored in an RG texture. It can optionally be
503 // uv (i.e., NV12) or vu (i.e., NV21).
504 static SkBitmap make_quarter_2_channel(const SkBitmap& fullY,
505 const SkBitmap& quarterU,
506 const SkBitmap& quarterV,
507 bool uv) {
508 SkBitmap result;
509
510 result.allocPixels(SkImageInfo::Make(fullY.width()/2,
511 fullY.height()/2,
512 kR8G8_unorm_SkColorType,
513 kUnpremul_SkAlphaType));
514
515 for (int y = 0; y < fullY.height()/2; ++y) {
516 for (int x = 0; x < fullY.width()/2; ++x) {
517 uint8_t u8 = *quarterU.getAddr8(x, y);
518 uint8_t v8 = *quarterV.getAddr8(x, y);
519
520 if (uv) {
521 *result.getAddr16(x, y) = (v8 << 8) | u8;
522 } else {
523 *result.getAddr16(x, y) = (u8 << 8) | v8;
524 }
525 }
526 }
527
528 return result;
529 }
530
531 // Create some flavor of a 16bits/channel bitmap from a RGBA_F32 source
532 static SkBitmap make_16(const SkBitmap& src, SkColorType dstCT,
533 std::function<void(uint16_t* dstPixel, const float* srcPixel)> convert) {
534 SkASSERT(src.colorType() == kRGBA_F32_SkColorType);
535
536 SkBitmap result;
537
538 result.allocPixels(SkImageInfo::Make(src.dimensions(), dstCT, kUnpremul_SkAlphaType));
539
540 for (int y = 0; y < src.height(); ++y) {
541 for (int x = 0; x < src.width(); ++x) {
542 const float* srcPixel = (const float*) src.getAddr(x, y);
543 uint16_t* dstPixel = (uint16_t*) result.getAddr(x, y);
544
545 convert(dstPixel, srcPixel);
546 }
547 }
548
549 return result;
550 }
551
552 static uint16_t flt_2_uint16(float flt) { return SkScalarRoundToInt(flt * 65535.0f); }
553
554 // Recombine the separate planes into some YUV format. Returns the number of planes.
555 static int create_YUV(const PlaneData& planes,
556 YUVFormat yuvFormat,
557 SkBitmap resultBMs[],
558 bool opaque) {
559 int nextLayer = 0;
560
561 switch (yuvFormat) {
562 case kY416_YUVFormat: {
563 resultBMs[nextLayer++] = make_16(planes.fFull, kR16G16B16A16_unorm_SkColorType,
564 [] (uint16_t* dstPixel, const float* srcPixel) {
565 dstPixel[0] = flt_2_uint16(srcPixel[1]); // U
566 dstPixel[1] = flt_2_uint16(srcPixel[0]); // Y
567 dstPixel[2] = flt_2_uint16(srcPixel[2]); // V
568 dstPixel[3] = flt_2_uint16(srcPixel[3]); // A
569 });
570 break;
571 }
572 case kAYUV_YUVFormat: {
573 SkBitmap yuvaFull;
574
575 yuvaFull.allocPixels(SkImageInfo::Make(planes.fYFull.width(), planes.fYFull.height(),
576 kRGBA_8888_SkColorType, kUnpremul_SkAlphaType));
577
578 for (int y = 0; y < planes.fYFull.height(); ++y) {
579 for (int x = 0; x < planes.fYFull.width(); ++x) {
580
581 uint8_t Y = *planes.fYFull.getAddr8(x, y);
582 uint8_t U = *planes.fUFull.getAddr8(x, y);
583 uint8_t V = *planes.fVFull.getAddr8(x, y);
584 uint8_t A = *planes.fAFull.getAddr8(x, y);
585
586 // NOT premul!
587 // V and Y swapped to match RGBA layout
588 SkColor c = SkColorSetARGB(A, V, U, Y);
589 *yuvaFull.getAddr32(x, y) = c;
590 }
591 }
592
593 resultBMs[nextLayer++] = yuvaFull;
594 break;
595 }
596 case kY410_YUVFormat: {
597 SkBitmap yuvaFull;
598 uint32_t Y, U, V;
599 uint8_t A;
600
601 yuvaFull.allocPixels(SkImageInfo::Make(planes.fYFull.width(), planes.fYFull.height(),
602 kRGBA_1010102_SkColorType,
603 kUnpremul_SkAlphaType));
604
605 for (int y = 0; y < planes.fYFull.height(); ++y) {
606 for (int x = 0; x < planes.fYFull.width(); ++x) {
607
608 Y = SkScalarRoundToInt((*planes.fYFull.getAddr8(x, y) / 255.0f) * 1023.0f);
609 U = SkScalarRoundToInt((*planes.fUFull.getAddr8(x, y) / 255.0f) * 1023.0f);
610 V = SkScalarRoundToInt((*planes.fVFull.getAddr8(x, y) / 255.0f) * 1023.0f);
611 A = SkScalarRoundToInt((*planes.fAFull.getAddr8(x, y) / 255.0f) * 3.0f);
612
613 // NOT premul!
614 *yuvaFull.getAddr32(x, y) = (A << 30) | (V << 20) | (Y << 10) | (U << 0);
615 }
616 }
617
618 resultBMs[nextLayer++] = yuvaFull;
619 break;
620 }
621 case kP016_YUVFormat: // fall through
622 case kP010_YUVFormat: {
623 resultBMs[nextLayer++] = make_16(planes.fFull, kA16_unorm_SkColorType,
624 [tenBitsPP = (yuvFormat == kP010_YUVFormat)]
625 (uint16_t* dstPixel, const float* srcPixel) {
626 uint16_t val16 = flt_2_uint16(srcPixel[0]);
627 dstPixel[0] = tenBitsPP ? (val16 & 0xFFC0)
628 : val16;
629 });
630 resultBMs[nextLayer++] = make_16(planes.fQuarter, kR16G16_unorm_SkColorType,
631 [tenBitsPP = (yuvFormat == kP010_YUVFormat)]
632 (uint16_t* dstPixel, const float* srcPixel) {
633 uint16_t u16 = flt_2_uint16(srcPixel[1]);
634 uint16_t v16 = flt_2_uint16(srcPixel[2]);
635 dstPixel[0] = tenBitsPP ? (u16 & 0xFFC0) : u16;
636 dstPixel[1] = tenBitsPP ? (v16 & 0xFFC0) : v16;
637 });
638 if (!opaque) {
639 resultBMs[nextLayer++] = make_16(planes.fFull, kA16_unorm_SkColorType,
640 [tenBitsPP = (yuvFormat == kP010_YUVFormat)]
641 (uint16_t* dstPixel, const float* srcPixel) {
642 uint16_t val16 = flt_2_uint16(srcPixel[3]);
643 dstPixel[0] = tenBitsPP ? (val16 & 0xFFC0)
644 : val16;
645 });
646 }
647 return nextLayer;
648 }
649 case kP016F_YUVFormat: {
650 resultBMs[nextLayer++] = make_16(planes.fFull, kA16_float_SkColorType,
651 [] (uint16_t* dstPixel, const float* srcPixel) {
652 dstPixel[0] = SkFloatToHalf(srcPixel[0]);
653 });
654 resultBMs[nextLayer++] = make_16(planes.fQuarter, kR16G16_float_SkColorType,
655 [] (uint16_t* dstPixel, const float* srcPixel) {
656 dstPixel[0] = SkFloatToHalf(srcPixel[1]);
657 dstPixel[1] = SkFloatToHalf(srcPixel[2]);
658 });
659 if (!opaque) {
660 resultBMs[nextLayer++] = make_16(planes.fFull, kA16_float_SkColorType,
661 [] (uint16_t* dstPixel, const float* srcPixel) {
662 dstPixel[0] = SkFloatToHalf(srcPixel[3]);
663 });
664 }
665 return nextLayer;
666 }
667 case kNV12_YUVFormat: {
668 SkBitmap uvQuarter = make_quarter_2_channel(planes.fYFull,
669 planes.fUQuarter,
670 planes.fVQuarter, true);
671 resultBMs[nextLayer++] = planes.fYFull;
672 resultBMs[nextLayer++] = uvQuarter;
673 break;
674 }
675 case kNV21_YUVFormat: {
676 SkBitmap vuQuarter = make_quarter_2_channel(planes.fYFull,
677 planes.fUQuarter,
678 planes.fVQuarter, false);
679 resultBMs[nextLayer++] = planes.fYFull;
680 resultBMs[nextLayer++] = vuQuarter;
681 break;
682 }
683 case kI420_YUVFormat:
684 resultBMs[nextLayer++] = planes.fYFull;
685 resultBMs[nextLayer++] = planes.fUQuarter;
686 resultBMs[nextLayer++] = planes.fVQuarter;
687 break;
688 case kYV12_YUVFormat:
689 resultBMs[nextLayer++] = planes.fYFull;
690 resultBMs[nextLayer++] = planes.fVQuarter;
691 resultBMs[nextLayer++] = planes.fUQuarter;
692 break;
693 }
694
695 if (!opaque && !has_alpha_channel(yuvFormat)) {
696 resultBMs[nextLayer++] = planes.fAFull;
697 }
698 return nextLayer;
699 }
700
701 static void draw_col_label(SkCanvas* canvas, int x, int yuvColorSpace, bool opaque) {
702 static const char* kYUVColorSpaceNames[] = {
703 "JPEG", "601", "709F", "709L", "2020_8F", "2020_8L",
704 "2020_10F", "2020_10L", "2020_12F", "2020_12L", "2020_16F", "2020_16L",
705 "FCCF", "FCCL", "SMPTE240F", "SMPTE240L", "YDZDXF", "YDZDXL",
706 "GBRF", "GBRL", "YCGCO_8F", "YCGCO_8L", "YCGCO_10F", "YCGCO_10L",
707 "YCGCO_12F", "YCGCO_12L", "YCGCO_16F", "YCGCO_16L", "Identity"};
708 static_assert(std::size(kYUVColorSpaceNames) == kLastEnum_SkYUVColorSpace + 1);
709
710 SkPaint paint;
711 SkFont font(ToolUtils::CreatePortableTypeface("Sans", SkFontStyle::Bold()), 16);
712 font.setEdging(SkFont::Edging::kAlias);
713
714 SkRect textRect;
715 SkString colLabel;
716
717 colLabel.printf("%s", kYUVColorSpaceNames[yuvColorSpace]);
718 font.measureText(colLabel.c_str(), colLabel.size(), SkTextEncoding::kUTF8, &textRect);
719 int y = textRect.height();
720
721 SkTextUtils::DrawString(canvas, colLabel.c_str(), x, y, font, paint, SkTextUtils::kCenter_Align);
722
723 colLabel.printf("%s", opaque ? "Opaque" : "Transparent");
724
725 font.measureText(colLabel.c_str(), colLabel.size(), SkTextEncoding::kUTF8, &textRect);
726 y += textRect.height();
727
728 SkTextUtils::DrawString(canvas, colLabel.c_str(), x, y, font, paint, SkTextUtils::kCenter_Align);
729 }
730
731 static void draw_row_label(SkCanvas* canvas, int y, int yuvFormat) {
732 static const char* kYUVFormatNames[] = {
733 "P016", "P010", "P016F", "Y416", "AYUV", "Y410", "NV12", "NV21", "I420", "YV12"
734 };
735 static_assert(std::size(kYUVFormatNames) == kLast_YUVFormat + 1);
736
737 SkPaint paint;
738 SkFont font(ToolUtils::CreatePortableTypeface("Sans", SkFontStyle::Bold()), 16);
739 font.setEdging(SkFont::Edging::kAlias);
740
741 SkRect textRect;
742 SkString rowLabel;
743
744 rowLabel.printf("%s", kYUVFormatNames[yuvFormat]);
745 font.measureText(rowLabel.c_str(), rowLabel.size(), SkTextEncoding::kUTF8, &textRect);
746 y += kTileWidthHeight/2 + textRect.height()/2;
747
748 canvas->drawString(rowLabel, 0, y, font, paint);
749 }
750
751 static sk_sp<SkColorFilter> yuv_to_rgb_colorfilter() {
752 static const float kJPEGConversionMatrix[20] = {
753 1.0f, 0.0f, 1.402f, 0.0f, -180.0f/255,
754 1.0f, -0.344136f, -0.714136f, 0.0f, 136.0f/255,
755 1.0f, 1.772f, 0.0f, 0.0f, -227.6f/255,
756 0.0f, 0.0f, 0.0f, 1.0f, 0.0f
757 };
758
759 return SkColorFilters::Matrix(kJPEGConversionMatrix);
760 }
761
762
763 namespace skiagm {
764
765 // This GM creates an opaque and transparent bitmap, extracts the planes and then recombines
766 // them into various YUV formats. It then renders the results in the grid, e.g.:
767 //
768 // JPEG 601 709 Identity
769 // Transparent Opaque Transparent Opaque Transparent Opaque Transparent Opaque
770 // originals
771 // P016
772 // P010
773 // P016F
774 // Y416
775 // AYUV
776 // Y410
777 // NV12
778 // NV21
779 // I420
780 // YV12
781 class WackyYUVFormatsGM : public GM {
782 public:
783 using Type = sk_gpu_test::LazyYUVImage::Type;
784
785 WackyYUVFormatsGM(bool useLimitedRange, bool useTargetColorSpace, bool useSubset,
786 bool useCubicSampling, Type type)
787 : fUseLimitedRange(useLimitedRange)
788 , fUseTargetColorSpace(useTargetColorSpace)
789 , fUseSubset(useSubset)
790 , fUseCubicSampling(useCubicSampling)
791 , fImageType(type) {
792 this->setBGColor(0xFFCCCCCC);
793 }
794
795 protected:
796 SkString getName() const override {
797 SkString name("wacky_yuv_formats");
798 if (fUseLimitedRange) {
799 name += "_limited";
800 }
801 if (fUseTargetColorSpace) {
802 name += "_cs";
803 }
804 if (fUseSubset) {
805 name += "_domain";
806 }
807 if (fUseCubicSampling) {
808 name += "_cubic";
809 }
810 switch (fImageType) {
811 case Type::kFromPixmaps:
812 name += "_frompixmaps";
813 break;
814 case Type::kFromTextures:
815 break;
816 case Type::kFromGenerator:
817 name += "_imggen";
818 break;
819 case Type::kFromImages:
820 name += "_fromimages";
821 break;
822 }
823
824 return name;
825 }
826
827 SkISize getISize() override {
828 int numCols = 2 * (kLastEnum_SkYUVColorSpace + 1)/2; // opacity x #-color-spaces/2
829 int numRows = 1 + (kLast_YUVFormat + 1); // original + #-yuv-formats
830 int wh = SkScalarCeilToInt(kTileWidthHeight * (fUseSubset ? 1.5f : 1.f));
831 return SkISize::Make(kLabelWidth + numCols * (wh + kPad),
832 kLabelHeight + numRows * (wh + kPad));
833 }
834
835 void createBitmaps() {
836 SkPoint origin = { kTileWidthHeight/2.0f, kTileWidthHeight/2.0f };
837 float outerRadius = kTileWidthHeight/2.0f - 20.0f;
838 float innerRadius = 20.0f;
839
840 {
841 // transparent
842 SkTDArray<SkRect> circles;
843 SkPath path = create_splat(origin, innerRadius, outerRadius, 1.0f, 5, &circles);
844 fOriginalBMs[0] = make_bitmap(kRGBA_8888_SkColorType, path, circles, false, fUseSubset);
845 }
846
847 {
848 // opaque
849 SkTDArray<SkRect> circles;
850 SkPath path = create_splat(origin, innerRadius, outerRadius, 1.0f, 7, &circles);
851 fOriginalBMs[1] = make_bitmap(kRGBA_8888_SkColorType, path, circles, true, fUseSubset);
852 }
853
854 if (fUseTargetColorSpace) {
855 fTargetColorSpace = SkColorSpace::MakeSRGB()->makeColorSpin();
856 }
857 }
858
859 bool createImages(GrDirectContext* dContext, Recorder* recorder) {
860 int origin = 0;
861 for (bool opaque : { false, true }) {
862 for (int cs = kJPEG_SkYUVColorSpace; cs <= kLastEnum_SkYUVColorSpace; ++cs) {
863 if (fUseLimitedRange !=
864 SkYUVColorSpaceIsLimitedRange(static_cast<SkYUVColorSpace>(cs))) {
865 continue;
866 }
867
868 PlaneData planes;
869 extract_planes(fOriginalBMs[opaque],
870 static_cast<SkYUVColorSpace>(cs),
871 static_cast<SkEncodedOrigin>(origin + 1), // valid origins are 1...8
872 &planes);
873
874 for (int f = kP016_YUVFormat; f <= kLast_YUVFormat; ++f) {
875 auto format = static_cast<YUVFormat>(f);
876 SkBitmap resultBMs[4];
877
878 int numPlanes = create_YUV(planes, format, resultBMs, opaque);
879 const YUVAPlanarConfig planarConfig(format,
880 opaque,
881 static_cast<SkEncodedOrigin>(origin + 1));
882 SkYUVAPixmaps pixmaps =
883 planarConfig.makeYUVAPixmaps(fOriginalBMs[opaque].dimensions(),
884 static_cast<SkYUVColorSpace>(cs),
885 resultBMs,
886 numPlanes);
887 auto lazyYUV = sk_gpu_test::LazyYUVImage::Make(std::move(pixmaps));
888 #if defined(SK_GRAPHITE)
889 if (recorder) {
890 fImages[opaque][cs][format] = lazyYUV->refImage(recorder, fImageType);
891 } else
892 #endif
893 {
894 fImages[opaque][cs][format] = lazyYUV->refImage(dContext, fImageType);
895 }
896 }
897 origin = (origin + 1) % 8;
898 }
899 }
900
901 #if defined(SK_GANESH)
902 if (dContext) {
903 // Some backends (e.g., Vulkan) require all work be completed for backend textures
904 // before they are deleted. Since we don't know when we'll next have access to a
905 // direct context, flush all the work now.
906 dContext->flush();
907 dContext->submit(GrSyncCpu::kYes);
908 }
909 #endif
910
911 return true;
912 }
913
914 DrawResult onGpuSetup(SkCanvas* canvas, SkString* errorMsg, GraphiteTestContext*) override {
915 GrDirectContext* dContext = nullptr;
916 #if defined(SK_GANESH)
917 dContext = GrAsDirectContext(canvas->recordingContext());
918 if (dContext && dContext->abandoned()) {
919 // This isn't a GpuGM so a null 'context' is okay but an abandoned context
920 // if forbidden.
921 return DrawResult::kSkip;
922 }
923 #endif
924 auto recorder = canvas->recorder();
925 this->createBitmaps();
926
927 // Only the generator is expected to work with the CPU backend.
928 if (fImageType != Type::kFromGenerator && !dContext && !recorder) {
929 return DrawResult::kSkip;
930 }
931
932 if (!this->createImages(dContext, recorder)) {
933 *errorMsg = "Failed to create YUV images";
934 return DrawResult::kFail;
935 }
936
937 return DrawResult::kOk;
938 }
939
940 void onGpuTeardown() override {
941 for (int i = 0; i < 2; ++i) {
942 for (int j = 0; j <= kLastEnum_SkYUVColorSpace; ++j) {
943 for (int k = 0; k <= kLast_YUVFormat; ++k) {
944 fImages[i][j][k] = nullptr;
945 }
946 }
947 }
948 }
949
950 void onDraw(SkCanvas* canvas) override {
951 auto recorder = canvas->baseRecorder();
952 SkASSERT(recorder);
953
954 float cellWidth = kTileWidthHeight, cellHeight = kTileWidthHeight;
955 if (fUseSubset) {
956 cellWidth *= 1.5f;
957 cellHeight *= 1.5f;
958 }
959
960 SkRect srcRect = SkRect::Make(fOriginalBMs[0].dimensions());
961 SkRect dstRect = SkRect::MakeXYWH(kLabelWidth, 0.f, srcRect.width(), srcRect.height());
962
963 SkCanvas::SrcRectConstraint constraint = SkCanvas::kFast_SrcRectConstraint;
964 if (fUseSubset) {
965 srcRect.inset(kSubsetPadding, kSubsetPadding);
966 // Draw a larger rectangle to ensure bilerp filtering would normally read outside the
967 // srcRect and hit the red pixels, if strict constraint weren't used.
968 dstRect.fRight = kLabelWidth + 1.5f * srcRect.width();
969 dstRect.fBottom = 1.5f * srcRect.height();
970 constraint = SkCanvas::kStrict_SrcRectConstraint;
971 }
972
973 SkSamplingOptions sampling = fUseCubicSampling
974 ? SkSamplingOptions(SkCubicResampler::Mitchell())
975 : SkSamplingOptions(SkFilterMode::kLinear);
976 for (int cs = kJPEG_SkYUVColorSpace; cs <= kLastEnum_SkYUVColorSpace; ++cs) {
977 if (fUseLimitedRange !=
978 SkYUVColorSpaceIsLimitedRange(static_cast<SkYUVColorSpace>(cs))) {
979 continue;
980 }
981
982 SkPaint paint;
983 if (kIdentity_SkYUVColorSpace == cs) {
984 // The identity color space needs post processing to appear correctly
985 paint.setColorFilter(yuv_to_rgb_colorfilter());
986 }
987
988 for (int opaque : { 0, 1 }) {
989 dstRect.offsetTo(dstRect.fLeft, kLabelHeight);
990
991 draw_col_label(canvas, dstRect.fLeft + cellWidth / 2, cs, opaque);
992
993 canvas->drawImageRect(fOriginalBMs[opaque].asImage(), srcRect, dstRect,
994 SkSamplingOptions(), nullptr, constraint);
995 dstRect.offset(0.f, cellHeight + kPad);
996
997 for (int format = kP016_YUVFormat; format <= kLast_YUVFormat; ++format) {
998 draw_row_label(canvas, dstRect.fTop, format);
999 if (fUseTargetColorSpace && fImages[opaque][cs][format]) {
1000 // Making a CS-specific version of a kIdentity_SkYUVColorSpace YUV image
1001 // doesn't make a whole lot of sense. The colorSpace conversion will
1002 // operate on the YUV components rather than the RGB components.
1003 sk_sp<SkImage> csImage = fImages[opaque][cs][format]->makeColorSpace(
1004 recorder, fTargetColorSpace, {});
1005 canvas->drawImageRect(csImage, srcRect, dstRect, sampling,
1006 &paint, constraint);
1007 } else {
1008 canvas->drawImageRect(fImages[opaque][cs][format], srcRect, dstRect,
1009 sampling, &paint, constraint);
1010 }
1011 dstRect.offset(0.f, cellHeight + kPad);
1012 }
1013
1014 dstRect.offset(cellWidth + kPad, 0.f);
1015 }
1016 }
1017 }
1018
1019 private:
1020 SkBitmap fOriginalBMs[2];
1021 sk_sp<SkImage> fImages[2][kLastEnum_SkYUVColorSpace + 1][kLast_YUVFormat + 1];
1022 bool fUseLimitedRange;
1023 bool fUseTargetColorSpace;
1024 bool fUseSubset;
1025 bool fUseCubicSampling;
1026 Type fImageType;
1027 sk_sp<SkColorSpace> fTargetColorSpace;
1028
1029 using INHERITED = GM;
1030 };
1031
1032 //////////////////////////////////////////////////////////////////////////////
1033
1034 DEF_GM(return new WackyYUVFormatsGM(/*useLimitedRange=*/false,
1035 /*useTargetColorSpace=*/false,
1036 /*useSubset=*/false,
1037 /*useCubicSampling=*/false,
1038 WackyYUVFormatsGM::Type::kFromTextures);)
1039 DEF_GM(return new WackyYUVFormatsGM(/*useLimitedRange=*/true,
1040 /*useTargetColorSpace=*/false,
1041 /*useSubset=*/false,
1042 /*useCubicSampling=*/false,
1043 WackyYUVFormatsGM::Type::kFromTextures);)
1044 DEF_GM(return new WackyYUVFormatsGM(/*useLimitedRange=*/false,
1045 /*useTargetColorSpace=*/false,
1046 /*useSubset=*/true,
1047 /*useCubicSampling=*/false,
1048 WackyYUVFormatsGM::Type::kFromTextures);)
1049 DEF_GM(return new WackyYUVFormatsGM(/*useLimitedRange=*/false,
1050 /*useTargetColorSpace=*/true,
1051 /*useSubset=*/false,
1052 /*useCubicSampling=*/false,
1053 WackyYUVFormatsGM::Type::kFromTextures);)
1054 DEF_GM(return new WackyYUVFormatsGM(/*useLimitedRange=*/true,
1055 /*useTargetColorSpace=*/true,
1056 /*useSubset=*/false,
1057 /*useCubicSampling=*/false,
1058 WackyYUVFormatsGM::Type::kFromTextures);)
1059 DEF_GM(return new WackyYUVFormatsGM(/*useLimitedRange=*/false,
1060 /*useTargetColorSpace=*/false,
1061 /*useSubset=*/false,
1062 /*useCubicSampling=*/true,
1063 WackyYUVFormatsGM::Type::kFromTextures);)
1064 DEF_GM(return new WackyYUVFormatsGM(/*useLimitedRange=*/false,
1065 /*useTargetColorSpace=*/false,
1066 /*useSubset=*/false,
1067 /*useCubicSampling=*/false,
1068 WackyYUVFormatsGM::Type::kFromGenerator);)
1069 DEF_GM(return new WackyYUVFormatsGM(/*useLimitedRange=*/false,
1070 /*useTargetColorSpace=*/false,
1071 /*useSubset=*/false,
1072 /*useCubicSampling=*/false,
1073 WackyYUVFormatsGM::Type::kFromPixmaps);)
1074 #if defined(SK_GRAPHITE)
1075 DEF_GM(return new WackyYUVFormatsGM(/*useLimitedRange=*/false,
1076 /*useTargetColorSpace=*/false,
1077 /*useSubset=*/false,
1078 /*useCubicSampling=*/false,
1079 WackyYUVFormatsGM::Type::kFromImages);)
1080 DEF_GM(return new WackyYUVFormatsGM(/*useLimitedRange=*/true,
1081 /*useTargetColorSpace=*/false,
1082 /*useSubset=*/false,
1083 /*useCubicSampling=*/false,
1084 WackyYUVFormatsGM::Type::kFromImages);)
1085 #endif
1086
1087 class YUVMakeColorSpaceGM : public GM {
1088 public:
1089 YUVMakeColorSpaceGM() {
1090 this->setBGColor(0xFFCCCCCC);
1091 }
1092
1093 protected:
1094 SkString getName() const override { return SkString("yuv_make_color_space"); }
1095
1096 SkISize getISize() override {
1097 int numCols = 4; // (transparent, opaque) x (untagged, tagged)
1098 int numRows = 5; // original, YUV, subset, makeNonTextureImage, readPixels
1099 return SkISize::Make(numCols * (kTileWidthHeight + kPad) + kPad,
1100 numRows * (kTileWidthHeight + kPad) + kPad);
1101 }
1102
1103 void createBitmaps() {
1104 SkPoint origin = { kTileWidthHeight/2.0f, kTileWidthHeight/2.0f };
1105 float outerRadius = kTileWidthHeight/2.0f - 20.0f;
1106 float innerRadius = 20.0f;
1107
1108 {
1109 // transparent
1110 SkTDArray<SkRect> circles;
1111 SkPath path = create_splat(origin, innerRadius, outerRadius, 1.0f, 5, &circles);
1112 fOriginalBMs[0] = make_bitmap(kN32_SkColorType, path, circles, false, false);
1113 }
1114
1115 {
1116 // opaque
1117 SkTDArray<SkRect> circles;
1118 SkPath path = create_splat(origin, innerRadius, outerRadius, 1.0f, 7, &circles);
1119 fOriginalBMs[1] = make_bitmap(kN32_SkColorType, path, circles, true, false);
1120 }
1121
1122 fTargetColorSpace = SkColorSpace::MakeSRGB()->makeColorSpin();
1123 }
1124
1125 bool createImages(GrDirectContext* context, Recorder* recorder) {
1126 for (bool opaque : { false, true }) {
1127 PlaneData planes;
1128 extract_planes(fOriginalBMs[opaque],
1129 kJPEG_SkYUVColorSpace,
1130 kTopLeft_SkEncodedOrigin,
1131 &planes);
1132
1133 SkBitmap resultBMs[4];
1134
1135 create_YUV(planes, kAYUV_YUVFormat, resultBMs, opaque);
1136
1137 YUVAPlanarConfig planarConfig(kAYUV_YUVFormat, opaque, kTopLeft_SkEncodedOrigin);
1138
1139 auto yuvaPixmaps = planarConfig.makeYUVAPixmaps(fOriginalBMs[opaque].dimensions(),
1140 kJPEG_Full_SkYUVColorSpace,
1141 resultBMs,
1142 std::size(resultBMs));
1143
1144 int i = 0;
1145 for (sk_sp<SkColorSpace> cs : {sk_sp<SkColorSpace>(nullptr),
1146 SkColorSpace::MakeSRGB()}) {
1147 auto lazyYUV = sk_gpu_test::LazyYUVImage::Make(
1148 yuvaPixmaps, skgpu::Mipmapped::kNo, std::move(cs));
1149 #if defined(SK_GRAPHITE)
1150 if (recorder) {
1151 fImages[opaque][i++] = lazyYUV->refImage(
1152 recorder, sk_gpu_test::LazyYUVImage::Type::kFromTextures);
1153 } else
1154 #endif
1155 {
1156 fImages[opaque][i++] = lazyYUV->refImage(
1157 context, sk_gpu_test::LazyYUVImage::Type::kFromTextures);
1158 }
1159 }
1160 }
1161
1162 #if defined(SK_GANESH)
1163 // Some backends (e.g., Vulkan) require all work be completed for backend textures before
1164 // they are deleted. Since we don't know when we'll next have access to a direct context,
1165 // flush all the work now.
1166 if (context) {
1167 context->flush();
1168 context->submit(GrSyncCpu::kYes);
1169 }
1170 #endif
1171 return true;
1172 }
1173
1174 DrawResult onGpuSetup(SkCanvas* canvas, SkString* errorMsg, GraphiteTestContext*) override {
1175 GrDirectContext* dContext = nullptr;
1176 #if defined(SK_GANESH)
1177 dContext = GrAsDirectContext(canvas->recordingContext());
1178 if (dContext && dContext->abandoned()) {
1179 *errorMsg = "Abandoned GrDirectContext cannot create YUV images";
1180 return DrawResult::kSkip;
1181 }
1182 #endif
1183 auto recorder = canvas->recorder();
1184 if (!recorder && !dContext) {
1185 *errorMsg = "GPU context required to create YUV images";
1186 return DrawResult::kSkip;
1187 }
1188
1189 this->createBitmaps();
1190 if (!this->createImages(dContext, recorder)) {
1191 *errorMsg = "Failed to create YUV images";
1192 return DrawResult::kFail;
1193 }
1194
1195 return DrawResult::kOk;
1196 }
1197
1198 void onGpuTeardown() override {
1199 fImages[0][0] = fImages[0][1] = fImages[1][0] = fImages[1][1] = nullptr;
1200 }
1201
1202 DrawResult onDraw(SkCanvas* canvas, SkString* msg) override {
1203 SkASSERT(fImages[0][0] && fImages[0][1] && fImages[1][0] && fImages[1][1]);
1204
1205 auto recorder = canvas->baseRecorder();
1206 if (!recorder) {
1207 *msg = "YUV ColorSpace image creation requires a GPU context.";
1208 return DrawResult::kSkip;
1209 }
1210
1211 int x = kPad;
1212 for (int tagged : { 0, 1 }) {
1213 for (int opaque : { 0, 1 }) {
1214 int y = kPad;
1215
1216 auto raster = fOriginalBMs[opaque].asImage()->makeColorSpace(
1217 nullptr, fTargetColorSpace, {});
1218 canvas->drawImage(raster, x, y);
1219 y += kTileWidthHeight + kPad;
1220
1221 if (fImages[opaque][tagged]) {
1222 sk_sp<SkImage> yuv = fImages[opaque][tagged]->makeColorSpace(
1223 recorder, fTargetColorSpace, {/*fMipmapped=*/false});
1224
1225 SkASSERT(yuv);
1226 SkASSERT(SkColorSpace::Equals(yuv->colorSpace(), fTargetColorSpace.get()));
1227 canvas->drawImage(yuv, x, y);
1228 y += kTileWidthHeight + kPad;
1229
1230 SkIRect bounds = SkIRect::MakeWH(kTileWidthHeight / 2, kTileWidthHeight / 2);
1231 sk_sp<SkImage> subset;
1232 #if defined(SK_GRAPHITE)
1233 if (auto gr = skgpu::graphite::AsGraphiteRecorder(recorder)) {
1234 subset = SkImages::SubsetTextureFrom(gr, yuv.get(), bounds);
1235 }
1236 #endif
1237 #if defined(SK_GANESH)
1238 if (auto gRecorder = AsGaneshRecorder(recorder)) {
1239 subset = SkImages::SubsetTextureFrom(
1240 gRecorder->directContext(), yuv.get(), bounds);
1241 }
1242 #endif
1243 SkASSERT(subset);
1244 canvas->drawImage(subset, x, y);
1245 y += kTileWidthHeight + kPad;
1246
1247 // Graphite doesn't support makeNonTextureImage() so skip this
1248 if (!recorder) {
1249 auto nonTexture = yuv->makeNonTextureImage();
1250 SkASSERT(nonTexture);
1251 canvas->drawImage(nonTexture, x, y);
1252 }
1253 y += kTileWidthHeight + kPad;
1254
1255 SkBitmap readBack;
1256 readBack.allocPixels(yuv->imageInfo());
1257 #if defined(SK_GRAPHITE)
1258 if (recorder->type() == SkRecorder::Type::kGraphite) {
1259 SkAssertResult(
1260 as_IB(yuv)->readPixelsGraphite(recorder, readBack.pixmap(), 0, 0));
1261 } else
1262 #endif
1263 {
1264 #if defined(SK_GANESH)
1265 auto dContext = GrAsDirectContext(canvas->recordingContext());
1266 SkAssertResult(yuv->readPixels(dContext, readBack.pixmap(), 0, 0));
1267 #else
1268 SkASSERT(false);
1269 #endif
1270 }
1271 canvas->drawImage(readBack.asImage(), x, y);
1272 }
1273 x += kTileWidthHeight + kPad;
1274 }
1275 }
1276 return DrawResult::kOk;
1277 }
1278
1279 private:
1280 SkBitmap fOriginalBMs[2];
1281 sk_sp<SkImage> fImages[2][2];
1282 sk_sp<SkColorSpace> fTargetColorSpace;
1283
1284 using INHERITED = GM;
1285 };
1286
1287 DEF_GM(return new YUVMakeColorSpaceGM();)
1288
1289 } // namespace skiagm
1290
1291 ///////////////
1292
1293 #include "include/effects/SkColorMatrix.h"
1294 #include "src/core/SkAutoPixmapStorage.h"
1295 #include "tools/Resources.h"
1296
1297 #if defined(SK_GANESH)
1298 static void draw_diff(SkCanvas* canvas, SkScalar x, SkScalar y,
1299 const SkImage* a, const SkImage* b) {
1300 auto sh = SkShaders::Blend(SkBlendMode::kDifference,
1301 a->makeShader(SkSamplingOptions()),
1302 b->makeShader(SkSamplingOptions()));
1303 SkPaint paint;
1304 paint.setShader(sh);
1305 canvas->save();
1306 canvas->translate(x, y);
1307 canvas->drawRect(SkRect::MakeWH(a->width(), a->height()), paint);
1308
1309 SkColorMatrix cm;
1310 cm.setScale(64, 64, 64);
1311 paint.setShader(sh->makeWithColorFilter(SkColorFilters::Matrix(cm)));
1312 canvas->translate(0, a->height());
1313 canvas->drawRect(SkRect::MakeWH(a->width(), a->height()), paint);
1314
1315 canvas->restore();
1316 }
1317
1318 // Exercises SkColorMatrix_RGB2YUV for yuv colorspaces, showing the planes, and the
1319 // resulting (recombined) images (gpu only for now).
1320 //
1321 class YUVSplitterGM : public skiagm::GM {
1322 sk_sp<SkImage> fOrig;
1323
1324 public:
1325 YUVSplitterGM() {}
1326
1327 protected:
1328 SkString getName() const override { return SkString("yuv_splitter"); }
1329
1330 SkISize getISize() override { return SkISize::Make(1280, 768); }
1331
1332 void onOnceBeforeDraw() override {
1333 fOrig = ToolUtils::GetResourceAsImage("images/mandrill_256.png");
1334 }
1335
1336 void onDraw(SkCanvas* canvas) override {
1337 canvas->translate(fOrig->width(), 0);
1338 canvas->save();
1339 SkYUVAInfo info;
1340 std::array<sk_sp<SkImage>, SkYUVAInfo::kMaxPlanes> planes;
1341 for (auto cs : {kRec709_SkYUVColorSpace,
1342 kRec601_SkYUVColorSpace,
1343 kJPEG_SkYUVColorSpace,
1344 kBT2020_SkYUVColorSpace}) {
1345 std::tie(planes, info) = sk_gpu_test::MakeYUVAPlanesAsA8(fOrig.get(),
1346 cs,
1347 SkYUVAInfo::Subsampling::k444,
1348 /*recording context*/ nullptr);
1349 SkPixmap pixmaps[4];
1350 for (int i = 0; i < info.numPlanes(); ++i) {
1351 planes[i]->peekPixels(&pixmaps[i]);
1352 }
1353 auto yuvaPixmaps = SkYUVAPixmaps::FromExternalPixmaps(info, pixmaps);
1354 auto img = SkImages::TextureFromYUVAPixmaps(canvas->recordingContext(),
1355 yuvaPixmaps,
1356 skgpu::Mipmapped::kNo,
1357 /* limit to max tex size */ false,
1358 /* color space */ nullptr);
1359 if (img) {
1360 canvas->drawImage(img, 0, 0);
1361 draw_diff(canvas, 0, fOrig->height(), fOrig.get(), img.get());
1362 }
1363 canvas->translate(fOrig->width(), 0);
1364 }
1365 canvas->restore();
1366 canvas->translate(-fOrig->width(), 0);
1367 int y = 0;
1368 for (int i = 0; i < info.numPlanes(); ++i) {
1369 canvas->drawImage(planes[i], 0, y);
1370 y += planes[i]->height();
1371 }
1372 }
1373
1374 private:
1375 using INHERITED = GM;
1376 };
1377 DEF_GM( return new YUVSplitterGM; )
1378 #endif