File: ImageConversion.cpp

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

#include "ImageConversion.h"

#include "ImageContainer.h"
#include "YCbCrUtils.h"
#include "libyuv/convert.h"
#include "libyuv/convert_from_argb.h"
#include "libyuv/scale_argb.h"
#include "mozilla/PodOperations.h"
#include "mozilla/RefPtr.h"
#include "mozilla/dom/ImageBitmapBinding.h"
#include "mozilla/dom/ImageUtils.h"
#include "mozilla/gfx/Point.h"
#include "mozilla/gfx/Swizzle.h"
#include "nsThreadUtils.h"
#include "skia/include/core/SkBitmap.h"
#include "skia/include/core/SkColorSpace.h"
#include "skia/include/core/SkImage.h"
#include "skia/include/core/SkImageInfo.h"

using mozilla::ImageFormat;
using mozilla::dom::ImageBitmapFormat;
using mozilla::dom::ImageUtils;
using mozilla::gfx::DataSourceSurface;
using mozilla::gfx::IntSize;
using mozilla::gfx::SourceSurface;
using mozilla::gfx::SurfaceFormat;
using mozilla::layers::Image;
using mozilla::layers::PlanarYCbCrData;
using mozilla::layers::PlanarYCbCrImage;

static const PlanarYCbCrData* GetPlanarYCbCrData(Image* aImage) {
  switch (aImage->GetFormat()) {
    case ImageFormat::PLANAR_YCBCR:
      return aImage->AsPlanarYCbCrImage()->GetData();
    case ImageFormat::NV_IMAGE:
      return aImage->AsNVImage()->GetData();
    default:
      return nullptr;
  }
}

static nsresult MapRv(int aRv) {
  // Docs for libyuv::ConvertToI420 say:
  // Returns 0 for successful; -1 for invalid parameter. Non-zero for failure.
  switch (aRv) {
    case 0:
      return NS_OK;
    case -1:
      return NS_ERROR_INVALID_ARG;
    default:
      return NS_ERROR_FAILURE;
  }
}

namespace mozilla {

already_AddRefed<SourceSurface> GetSourceSurface(Image* aImage) {
  if (!aImage->AsGLImage() || NS_IsMainThread()) {
    return aImage->GetAsSourceSurface();
  }

  // GLImage::GetAsSourceSurface() only supports main thread
  RefPtr<SourceSurface> surf;
  NS_DispatchAndSpinEventLoopUntilComplete(
      "ImageToI420::GLImage::GetSourceSurface"_ns,
      mozilla::GetMainThreadSerialEventTarget(),
      NS_NewRunnableFunction(
          "ImageToI420::GLImage::GetSourceSurface",
          [&aImage, &surf]() { surf = aImage->GetAsSourceSurface(); }));

  return surf.forget();
}

nsresult ConvertToI420(Image* aImage, uint8_t* aDestY, int aDestStrideY,
                       uint8_t* aDestU, int aDestStrideU, uint8_t* aDestV,
                       int aDestStrideV, const IntSize& aDestSize) {
  if (!aImage->IsValid()) {
    return NS_ERROR_INVALID_ARG;
  }

  const IntSize imageSize = aImage->GetSize();
  auto srcPixelCount = CheckedInt<int32_t>(imageSize.width) * imageSize.height;
  auto dstPixelCount = CheckedInt<int32_t>(aDestSize.width) * aDestSize.height;
  if (!srcPixelCount.isValid() || !dstPixelCount.isValid()) {
    MOZ_ASSERT_UNREACHABLE("Bad input or output sizes");
    return NS_ERROR_INVALID_ARG;
  }

  // If we are downscaling, we prefer an early scale. If we are upscaling, we
  // prefer a late scale. This minimizes the number of pixel manipulations.
  // Depending on the input format, we may be forced to do a late scale after
  // conversion to I420, because we don't support scaling the input format.
  const bool needsScale = imageSize != aDestSize;
  bool earlyScale = srcPixelCount.value() > dstPixelCount.value();

  Maybe<DataSourceSurface::ScopedMap> surfaceMap;
  SurfaceFormat surfaceFormat = SurfaceFormat::UNKNOWN;

  const PlanarYCbCrData* data = GetPlanarYCbCrData(aImage);
  Maybe<dom::ImageBitmapFormat> format;
  if (data) {
    const ImageUtils imageUtils(aImage);
    format = imageUtils.GetFormat();
    if (format.isNothing()) {
      MOZ_ASSERT_UNREACHABLE("YUV format conversion not implemented");
      return NS_ERROR_NOT_IMPLEMENTED;
    }

    switch (format.value()) {
      case ImageBitmapFormat::YUV420P:
        // Since the input and output formats match, we can copy or scale
        // directly to the output buffer.
        if (needsScale) {
          return MapRv(libyuv::I420Scale(
              data->mYChannel, data->mYStride, data->mCbChannel,
              data->mCbCrStride, data->mCrChannel, data->mCbCrStride,
              imageSize.width, imageSize.height, aDestY, aDestStrideY, aDestU,
              aDestStrideU, aDestV, aDestStrideV, aDestSize.width,
              aDestSize.height, libyuv::FilterMode::kFilterBox));
        }
        return MapRv(libyuv::I420ToI420(
            data->mYChannel, data->mYStride, data->mCbChannel,
            data->mCbCrStride, data->mCrChannel, data->mCbCrStride, aDestY,
            aDestStrideY, aDestU, aDestStrideU, aDestV, aDestStrideV,
            aDestSize.width, aDestSize.height));
      case ImageBitmapFormat::YUV422P:
        if (!needsScale) {
          return MapRv(libyuv::I422ToI420(
              data->mYChannel, data->mYStride, data->mCbChannel,
              data->mCbCrStride, data->mCrChannel, data->mCbCrStride, aDestY,
              aDestStrideY, aDestU, aDestStrideU, aDestV, aDestStrideV,
              aDestSize.width, aDestSize.height));
        }
        break;
      case ImageBitmapFormat::YUV444P:
        if (!needsScale) {
          return MapRv(libyuv::I444ToI420(
              data->mYChannel, data->mYStride, data->mCbChannel,
              data->mCbCrStride, data->mCrChannel, data->mCbCrStride, aDestY,
              aDestStrideY, aDestU, aDestStrideU, aDestV, aDestStrideV,
              aDestSize.width, aDestSize.height));
        }
        break;
      case ImageBitmapFormat::YUV420SP_NV12:
        if (!needsScale) {
          return MapRv(libyuv::NV12ToI420(
              data->mYChannel, data->mYStride, data->mCbChannel,
              data->mCbCrStride, aDestY, aDestStrideY, aDestU, aDestStrideU,
              aDestV, aDestStrideV, aDestSize.width, aDestSize.height));
        }
        break;
      case ImageBitmapFormat::YUV420SP_NV21:
        if (!needsScale) {
          return MapRv(libyuv::NV21ToI420(
              data->mYChannel, data->mYStride, data->mCrChannel,
              data->mCbCrStride, aDestY, aDestStrideY, aDestU, aDestStrideU,
              aDestV, aDestStrideV, aDestSize.width, aDestSize.height));
        }
        earlyScale = false;
        break;
      default:
        MOZ_ASSERT_UNREACHABLE("YUV format conversion not implemented");
        return NS_ERROR_NOT_IMPLEMENTED;
    }
  } else {
    RefPtr<SourceSurface> surface = GetSourceSurface(aImage);
    if (!surface) {
      return NS_ERROR_FAILURE;
    }

    RefPtr<DataSourceSurface> dataSurface = surface->GetDataSurface();
    if (!dataSurface) {
      return NS_ERROR_FAILURE;
    }

    surfaceMap.emplace(dataSurface, DataSourceSurface::READ);
    if (!surfaceMap->IsMapped()) {
      return NS_ERROR_FAILURE;
    }

    surfaceFormat = dataSurface->GetFormat();
    switch (surfaceFormat) {
      case SurfaceFormat::B8G8R8A8:
      case SurfaceFormat::B8G8R8X8:
        if (!needsScale) {
          return MapRv(
              libyuv::ARGBToI420(static_cast<uint8_t*>(surfaceMap->GetData()),
                                 surfaceMap->GetStride(), aDestY, aDestStrideY,
                                 aDestU, aDestStrideU, aDestV, aDestStrideV,
                                 aDestSize.width, aDestSize.height));
        }
        break;
      case SurfaceFormat::R8G8B8A8:
      case SurfaceFormat::R8G8B8X8:
        if (!needsScale) {
          return MapRv(
              libyuv::ABGRToI420(static_cast<uint8_t*>(surfaceMap->GetData()),
                                 surfaceMap->GetStride(), aDestY, aDestStrideY,
                                 aDestU, aDestStrideU, aDestV, aDestStrideV,
                                 aDestSize.width, aDestSize.height));
        }
        break;
      case SurfaceFormat::R5G6B5_UINT16:
        if (!needsScale) {
          return MapRv(libyuv::RGB565ToI420(
              static_cast<uint8_t*>(surfaceMap->GetData()),
              surfaceMap->GetStride(), aDestY, aDestStrideY, aDestU,
              aDestStrideU, aDestV, aDestStrideV, aDestSize.width,
              aDestSize.height));
        }
        earlyScale = false;
        break;
      default:
        MOZ_ASSERT_UNREACHABLE("Surface format conversion not implemented");
        return NS_ERROR_NOT_IMPLEMENTED;
    }
  }

  MOZ_DIAGNOSTIC_ASSERT(needsScale);

  // We have to scale, and we are unable to scale directly, so we need a
  // temporary buffer to hold the scaled result in the input format, or the
  // unscaled result in the output format.
  IntSize tempBufSize;
  IntSize tempBufCbCrSize;
  if (earlyScale) {
    // Early scaling means we are scaling from the input buffer to a temporary
    // buffer of the same format.
    tempBufSize = aDestSize;
    if (data) {
      tempBufCbCrSize = gfx::ChromaSize(tempBufSize, data->mChromaSubsampling);
    }
  } else {
    // Late scaling means we are scaling from a temporary I420 buffer to the
    // destination I420 buffer.
    tempBufSize = imageSize;
    tempBufCbCrSize = gfx::ChromaSize(
        tempBufSize, gfx::ChromaSubsampling::HALF_WIDTH_AND_HEIGHT);
  }

  MOZ_ASSERT(!tempBufSize.IsEmpty());

  // Make sure we can allocate the temporary buffer.
  gfx::AlignedArray<uint8_t> tempBuf;
  uint8_t* tempBufY = nullptr;
  uint8_t* tempBufU = nullptr;
  uint8_t* tempBufV = nullptr;
  int32_t tempRgbStride = 0;
  if (!tempBufCbCrSize.IsEmpty()) {
    // Our temporary buffer is represented as a YUV format.
    auto tempBufYLen =
        CheckedInt<size_t>(tempBufSize.width) * tempBufSize.height;
    auto tempBufCbCrLen =
        CheckedInt<size_t>(tempBufCbCrSize.width) * tempBufCbCrSize.height;
    auto tempBufLen = tempBufYLen + 2 * tempBufCbCrLen;
    if (!tempBufLen.isValid()) {
      MOZ_ASSERT_UNREACHABLE("Bad buffer size!");
      return NS_ERROR_FAILURE;
    }

    tempBuf.Realloc(tempBufLen.value());
    if (!tempBuf) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    tempBufY = tempBuf;
    tempBufU = tempBufY + tempBufYLen.value();
    tempBufV = tempBufU + tempBufCbCrLen.value();
  } else {
    // The temporary buffer is represented as a RGBA/BGRA format.
    auto tempStride = CheckedInt<int32_t>(tempBufSize.width) * 4;
    auto tempBufLen = tempStride * tempBufSize.height;
    if (!tempStride.isValid() || !tempBufLen.isValid()) {
      MOZ_ASSERT_UNREACHABLE("Bad buffer size!");
      return NS_ERROR_FAILURE;
    }

    tempBuf.Realloc(tempBufLen.value());
    if (!tempBuf) {
      return NS_ERROR_OUT_OF_MEMORY;
    }

    tempRgbStride = tempStride.value();
  }

  nsresult rv;
  if (!earlyScale) {
    // First convert whatever the input format is to I420 into the temp buffer.
    if (data) {
      switch (format.value()) {
        case ImageBitmapFormat::YUV422P:
          rv = MapRv(libyuv::I422ToI420(
              data->mYChannel, data->mYStride, data->mCbChannel,
              data->mCbCrStride, data->mCrChannel, data->mCbCrStride, tempBufY,
              tempBufSize.width, tempBufU, tempBufCbCrSize.width, tempBufV,
              tempBufCbCrSize.width, tempBufSize.width, tempBufSize.height));
          break;
        case ImageBitmapFormat::YUV444P:
          rv = MapRv(libyuv::I444ToI420(
              data->mYChannel, data->mYStride, data->mCbChannel,
              data->mCbCrStride, data->mCrChannel, data->mCbCrStride, tempBufY,
              tempBufSize.width, tempBufU, tempBufCbCrSize.width, tempBufV,
              tempBufCbCrSize.width, tempBufSize.width, tempBufSize.height));
          break;
        case ImageBitmapFormat::YUV420SP_NV12:
          rv = MapRv(libyuv::NV12ToI420(
              data->mYChannel, data->mYStride, data->mCbChannel,
              data->mCbCrStride, tempBufY, tempBufSize.width, tempBufU,
              tempBufCbCrSize.width, tempBufV, tempBufCbCrSize.width,
              tempBufSize.width, tempBufSize.height));
          break;
        case ImageBitmapFormat::YUV420SP_NV21:
          rv = MapRv(libyuv::NV21ToI420(
              data->mYChannel, data->mYStride, data->mCrChannel,
              data->mCbCrStride, tempBufY, tempBufSize.width, tempBufU,
              tempBufCbCrSize.width, tempBufV, tempBufCbCrSize.width,
              tempBufSize.width, tempBufSize.height));
          break;
        default:
          MOZ_ASSERT_UNREACHABLE("YUV format conversion not implemented");
          return NS_ERROR_UNEXPECTED;
      }
    } else {
      switch (surfaceFormat) {
        case SurfaceFormat::B8G8R8A8:
        case SurfaceFormat::B8G8R8X8:
          rv = MapRv(libyuv::ARGBToI420(
              static_cast<uint8_t*>(surfaceMap->GetData()),
              surfaceMap->GetStride(), tempBufY, tempBufSize.width, tempBufU,
              tempBufCbCrSize.width, tempBufV, tempBufCbCrSize.width,
              tempBufSize.width, tempBufSize.height));
          break;
        case SurfaceFormat::R8G8B8A8:
        case SurfaceFormat::R8G8B8X8:
          rv = MapRv(libyuv::ABGRToI420(
              static_cast<uint8_t*>(surfaceMap->GetData()),
              surfaceMap->GetStride(), tempBufY, tempBufSize.width, tempBufU,
              tempBufCbCrSize.width, tempBufV, tempBufCbCrSize.width,
              tempBufSize.width, tempBufSize.height));
          break;
        case SurfaceFormat::R5G6B5_UINT16:
          rv = MapRv(libyuv::RGB565ToI420(
              static_cast<uint8_t*>(surfaceMap->GetData()),
              surfaceMap->GetStride(), tempBufY, tempBufSize.width, tempBufU,
              tempBufCbCrSize.width, tempBufV, tempBufCbCrSize.width,
              tempBufSize.width, tempBufSize.height));
          break;
        default:
          MOZ_ASSERT_UNREACHABLE("Surface format conversion not implemented");
          return NS_ERROR_NOT_IMPLEMENTED;
      }
    }

    if (NS_FAILED(rv)) {
      return rv;
    }

    // Now do the scale in I420 to the output buffer.
    return MapRv(libyuv::I420Scale(
        tempBufY, tempBufSize.width, tempBufU, tempBufCbCrSize.width, tempBufV,
        tempBufCbCrSize.width, tempBufSize.width, tempBufSize.height, aDestY,
        aDestStrideY, aDestU, aDestStrideU, aDestV, aDestStrideV,
        aDestSize.width, aDestSize.height, libyuv::FilterMode::kFilterBox));
  }

  if (data) {
    // First scale in the input format to the desired size into temp buffer, and
    // then convert that into the final I420 result.
    switch (format.value()) {
      case ImageBitmapFormat::YUV422P:
        rv = MapRv(libyuv::I422Scale(
            data->mYChannel, data->mYStride, data->mCbChannel,
            data->mCbCrStride, data->mCrChannel, data->mCbCrStride,
            imageSize.width, imageSize.height, tempBufY, tempBufSize.width,
            tempBufU, tempBufCbCrSize.width, tempBufV, tempBufCbCrSize.width,
            tempBufSize.width, tempBufSize.height,
            libyuv::FilterMode::kFilterBox));
        if (NS_FAILED(rv)) {
          return rv;
        }
        return MapRv(libyuv::I422ToI420(
            tempBufY, tempBufSize.width, tempBufU, tempBufCbCrSize.width,
            tempBufV, tempBufCbCrSize.width, aDestY, aDestStrideY, aDestU,
            aDestStrideU, aDestV, aDestStrideV, aDestSize.width,
            aDestSize.height));
      case ImageBitmapFormat::YUV444P:
        rv = MapRv(libyuv::I444Scale(
            data->mYChannel, data->mYStride, data->mCbChannel,
            data->mCbCrStride, data->mCrChannel, data->mCbCrStride,
            imageSize.width, imageSize.height, tempBufY, tempBufSize.width,
            tempBufU, tempBufCbCrSize.width, tempBufV, tempBufCbCrSize.width,
            tempBufSize.width, tempBufSize.height,
            libyuv::FilterMode::kFilterBox));
        if (NS_FAILED(rv)) {
          return rv;
        }
        return MapRv(libyuv::I444ToI420(
            tempBufY, tempBufSize.width, tempBufU, tempBufCbCrSize.width,
            tempBufV, tempBufCbCrSize.width, aDestY, aDestStrideY, aDestU,
            aDestStrideU, aDestV, aDestStrideV, aDestSize.width,
            aDestSize.height));
      case ImageBitmapFormat::YUV420SP_NV12:
        rv = MapRv(libyuv::NV12Scale(
            data->mYChannel, data->mYStride, data->mCbChannel,
            data->mCbCrStride, imageSize.width, imageSize.height, tempBufY,
            tempBufSize.width, tempBufU, tempBufCbCrSize.width,
            tempBufSize.width, tempBufSize.height,
            libyuv::FilterMode::kFilterBox));
        if (NS_FAILED(rv)) {
          return rv;
        }
        return MapRv(libyuv::NV12ToI420(
            tempBufY, tempBufSize.width, tempBufU, tempBufCbCrSize.width,
            aDestY, aDestStrideY, aDestU, aDestStrideU, aDestV, aDestStrideV,
            aDestSize.width, aDestSize.height));
      default:
        MOZ_ASSERT_UNREACHABLE("YUV format conversion not implemented");
        return NS_ERROR_NOT_IMPLEMENTED;
    }
  }

  MOZ_DIAGNOSTIC_ASSERT(surfaceFormat == SurfaceFormat::B8G8R8X8 ||
                        surfaceFormat == SurfaceFormat::B8G8R8A8 ||
                        surfaceFormat == SurfaceFormat::R8G8B8X8 ||
                        surfaceFormat == SurfaceFormat::R8G8B8A8);

  // We can use the same scaling method for either BGRA or RGBA since the
  // channel orders don't matter to the scaling algorithm.
  rv = MapRv(libyuv::ARGBScale(
      surfaceMap->GetData(), surfaceMap->GetStride(), imageSize.width,
      imageSize.height, tempBuf, tempRgbStride, tempBufSize.width,
      tempBufSize.height, libyuv::FilterMode::kFilterBox));
  if (NS_FAILED(rv)) {
    return rv;
  }

  // Now convert the scale result to I420.
  if (surfaceFormat == SurfaceFormat::B8G8R8A8 ||
      surfaceFormat == SurfaceFormat::B8G8R8X8) {
    return MapRv(libyuv::ARGBToI420(
        tempBuf, tempRgbStride, aDestY, aDestStrideY, aDestU, aDestStrideU,
        aDestV, aDestStrideV, aDestSize.width, aDestSize.height));
  }

  return MapRv(libyuv::ABGRToI420(tempBuf, tempRgbStride, aDestY, aDestStrideY,
                                  aDestU, aDestStrideU, aDestV, aDestStrideV,
                                  aDestSize.width, aDestSize.height));
}

static int32_t CeilingOfHalf(int32_t aValue) {
  MOZ_ASSERT(aValue >= 0);
  return aValue / 2 + (aValue % 2);
}

nsresult ConvertToNV12(layers::Image* aImage, uint8_t* aDestY, int aDestStrideY,
                       uint8_t* aDestUV, int aDestStrideUV,
                       gfx::IntSize aDestSize) {
  if (!aImage->IsValid()) {
    return NS_ERROR_INVALID_ARG;
  }

  if (const PlanarYCbCrData* data = GetPlanarYCbCrData(aImage)) {
    const ImageUtils imageUtils(aImage);
    Maybe<dom::ImageBitmapFormat> format = imageUtils.GetFormat();
    if (format.isNothing()) {
      MOZ_ASSERT_UNREACHABLE("YUV format conversion not implemented");
      return NS_ERROR_NOT_IMPLEMENTED;
    }

    if (format.value() != ImageBitmapFormat::YUV420P) {
      NS_WARNING("ConvertToNV12: Convert YUV data in I420 only");
      return NS_ERROR_NOT_IMPLEMENTED;
    }

    PlanarYCbCrData i420Source = *data;
    gfx::AlignedArray<uint8_t> scaledI420Buffer;

    if (aDestSize != aImage->GetSize()) {
      const int32_t halfWidth = CeilingOfHalf(aDestSize.width);
      const uint32_t halfHeight = CeilingOfHalf(aDestSize.height);

      CheckedInt<size_t> ySize(aDestSize.width);
      ySize *= aDestSize.height;

      CheckedInt<size_t> uSize(halfWidth);
      uSize *= halfHeight;

      CheckedInt<size_t> vSize(uSize);

      CheckedInt<size_t> i420Size = ySize + uSize + vSize;
      if (!i420Size.isValid()) {
        NS_WARNING("ConvertToNV12: Destination size is too large");
        return NS_ERROR_INVALID_ARG;
      }

      scaledI420Buffer.Realloc(i420Size.value());
      if (!scaledI420Buffer) {
        NS_WARNING(
            "ConvertToNV12: Failed to allocate buffer for rescaled I420 image");
        return NS_ERROR_OUT_OF_MEMORY;
      }

      // Y plane
      i420Source.mYChannel = scaledI420Buffer;
      i420Source.mYStride = aDestSize.width;
      i420Source.mYSkip = 0;

      // Cb plane (aka U)
      i420Source.mCbChannel = i420Source.mYChannel + ySize.value();
      i420Source.mCbSkip = 0;

      // Cr plane (aka V)
      i420Source.mCrChannel = i420Source.mCbChannel + uSize.value();
      i420Source.mCrSkip = 0;

      i420Source.mCbCrStride = halfWidth;
      i420Source.mChromaSubsampling =
          gfx::ChromaSubsampling::HALF_WIDTH_AND_HEIGHT;
      i420Source.mPictureRect = {0, 0, aDestSize.width, aDestSize.height};

      nsresult rv = MapRv(libyuv::I420Scale(
          data->mYChannel, data->mYStride, data->mCbChannel, data->mCbCrStride,
          data->mCrChannel, data->mCbCrStride, aImage->GetSize().width,
          aImage->GetSize().height, i420Source.mYChannel, i420Source.mYStride,
          i420Source.mCbChannel, i420Source.mCbCrStride, i420Source.mCrChannel,
          i420Source.mCbCrStride, i420Source.mPictureRect.width,
          i420Source.mPictureRect.height, libyuv::FilterMode::kFilterBox));
      if (NS_FAILED(rv)) {
        NS_WARNING("ConvertToNV12: I420Scale failed");
        return rv;
      }
    }

    return MapRv(libyuv::I420ToNV12(
        i420Source.mYChannel, i420Source.mYStride, i420Source.mCbChannel,
        i420Source.mCbCrStride, i420Source.mCrChannel, i420Source.mCbCrStride,
        aDestY, aDestStrideY, aDestUV, aDestStrideUV, aDestSize.width,
        aDestSize.height));
  }

  RefPtr<SourceSurface> surf = GetSourceSurface(aImage);
  if (!surf) {
    return NS_ERROR_FAILURE;
  }

  RefPtr<DataSourceSurface> data = surf->GetDataSurface();
  if (!data) {
    return NS_ERROR_FAILURE;
  }

  DataSourceSurface::ScopedMap map(data, DataSourceSurface::READ);
  if (!map.IsMapped()) {
    return NS_ERROR_FAILURE;
  }

  if (surf->GetFormat() != SurfaceFormat::B8G8R8A8 &&
      surf->GetFormat() != SurfaceFormat::B8G8R8X8) {
    NS_WARNING("ConvertToNV12: Convert SurfaceFormat in BGR* only");
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  struct RgbSource {
    uint8_t* mBuffer;
    int32_t mStride;
  } rgbSource = {map.GetData(), map.GetStride()};

  gfx::AlignedArray<uint8_t> scaledRGB32Buffer;

  if (aDestSize != aImage->GetSize()) {
    CheckedInt<int> rgbaStride(aDestSize.width);
    rgbaStride *= 4;
    if (!rgbaStride.isValid()) {
      NS_WARNING("ConvertToNV12: Destination width is too large");
      return NS_ERROR_INVALID_ARG;
    }

    CheckedInt<size_t> rgbSize(rgbaStride.value());
    rgbSize *= aDestSize.height;
    if (!rgbSize.isValid()) {
      NS_WARNING("ConvertToNV12: Destination size is too large");
      return NS_ERROR_INVALID_ARG;
    }

    scaledRGB32Buffer.Realloc(rgbSize.value());
    if (!scaledRGB32Buffer) {
      NS_WARNING(
          "ConvertToNV12: Failed to allocate buffer for rescaled RGB32 image");
      return NS_ERROR_OUT_OF_MEMORY;
    }

    nsresult rv = MapRv(libyuv::ARGBScale(
        map.GetData(), map.GetStride(), aImage->GetSize().width,
        aImage->GetSize().height, scaledRGB32Buffer, rgbaStride.value(),
        aDestSize.width, aDestSize.height, libyuv::FilterMode::kFilterBox));
    if (NS_FAILED(rv)) {
      NS_WARNING("ConvertToNV12: ARGBScale failed");
      return rv;
    }

    rgbSource.mBuffer = scaledRGB32Buffer;
    rgbSource.mStride = rgbaStride.value();
  }

  return MapRv(libyuv::ARGBToNV12(rgbSource.mBuffer, rgbSource.mStride, aDestY,
                                  aDestStrideY, aDestUV, aDestStrideUV,
                                  aDestSize.width, aDestSize.height));
}

static bool IsRGBX(const SurfaceFormat& aFormat) {
  return aFormat == SurfaceFormat::B8G8R8A8 ||
         aFormat == SurfaceFormat::B8G8R8X8 ||
         aFormat == SurfaceFormat::R8G8B8A8 ||
         aFormat == SurfaceFormat::R8G8B8X8 ||
         aFormat == SurfaceFormat::X8R8G8B8 ||
         aFormat == SurfaceFormat::A8R8G8B8;
}

static bool HasAlpha(const SurfaceFormat& aFormat) {
  return aFormat == SurfaceFormat::B8G8R8A8 ||
         aFormat == SurfaceFormat::R8G8B8A8 ||
         aFormat == SurfaceFormat::A8R8G8B8;
}

static nsresult SwapRGBA(DataSourceSurface* aSurface,
                         const SurfaceFormat& aDestFormat) {
  if (!aSurface || !IsRGBX(aSurface->GetFormat()) || !IsRGBX(aDestFormat)) {
    return NS_ERROR_INVALID_ARG;
  }

  if (aSurface->GetFormat() == aDestFormat) {
    return NS_OK;
  }

  DataSourceSurface::ScopedMap map(aSurface, DataSourceSurface::READ_WRITE);
  if (!map.IsMapped()) {
    return NS_ERROR_FAILURE;
  }

  gfx::SwizzleData(map.GetData(), map.GetStride(), aSurface->GetFormat(),
                   map.GetData(), map.GetStride(), aDestFormat,
                   aSurface->GetSize());

  return NS_OK;
}

nsresult ConvertToRGBA(Image* aImage, const SurfaceFormat& aDestFormat,
                       uint8_t* aDestBuffer, int aDestStride) {
  if (!aImage || !aImage->IsValid() || aImage->GetSize().IsEmpty() ||
      !aDestBuffer || !IsRGBX(aDestFormat) || aDestStride <= 0) {
    return NS_ERROR_INVALID_ARG;
  }

  // Read YUV image to the given buffer in required RGBA format.
  if (const PlanarYCbCrData* data = GetPlanarYCbCrData(aImage)) {
    SurfaceFormat convertedFormat = aDestFormat;
    gfx::PremultFunc premultOp = nullptr;
    if (data->mAlpha && HasAlpha(aDestFormat)) {
      if (aDestFormat == SurfaceFormat::A8R8G8B8) {
        convertedFormat = SurfaceFormat::B8G8R8A8;
      }
      if (data->mAlpha->mPremultiplied) {
        premultOp = libyuv::ARGBUnattenuate;
      }
    } else {
      if (aDestFormat == SurfaceFormat::X8R8G8B8 ||
          aDestFormat == SurfaceFormat::A8R8G8B8) {
        convertedFormat = SurfaceFormat::B8G8R8X8;
      }
    }

    nsresult result =
        ConvertYCbCrToRGB32(*data, convertedFormat, aDestBuffer,
                            AssertedCast<int32_t>(aDestStride), premultOp);
    if (NS_FAILED(result)) {
      return result;
    }

    if (convertedFormat == aDestFormat) {
      return NS_OK;
    }

    // Since format of the converted data returned from ConvertYCbCrToRGB or
    // ConvertYCbCrAToARGB is BRG* or RBG*, we need swap the RGBA channels to
    // the required format if needed.

    RefPtr<DataSourceSurface> surf =
        gfx::Factory::CreateWrappingDataSourceSurface(
            aDestBuffer, aDestStride, aImage->GetSize(), convertedFormat);

    if (!surf) {
      return NS_ERROR_FAILURE;
    }

    return SwapRGBA(surf.get(), aDestFormat);
  }

  // Read RGBA image to the given buffer in required RGBA format.

  RefPtr<SourceSurface> surf = GetSourceSurface(aImage);
  if (!surf) {
    return NS_ERROR_FAILURE;
  }

  if (!IsRGBX(surf->GetFormat())) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  RefPtr<DataSourceSurface> src = surf->GetDataSurface();
  if (!src) {
    return NS_ERROR_FAILURE;
  }

  DataSourceSurface::ScopedMap srcMap(src, DataSourceSurface::READ);
  if (!srcMap.IsMapped()) {
    return NS_ERROR_FAILURE;
  }

  RefPtr<DataSourceSurface> dest =
      gfx::Factory::CreateWrappingDataSourceSurface(
          aDestBuffer, aDestStride, aImage->GetSize(), aDestFormat);

  if (!dest) {
    return NS_ERROR_FAILURE;
  }

  DataSourceSurface::ScopedMap destMap(dest, gfx::DataSourceSurface::WRITE);
  if (!destMap.IsMapped()) {
    return NS_ERROR_FAILURE;
  }

  gfx::SwizzleData(srcMap.GetData(), srcMap.GetStride(), src->GetFormat(),
                   destMap.GetData(), destMap.GetStride(), dest->GetFormat(),
                   dest->GetSize());

  return NS_OK;
}

static SkColorType ToSkColorType(const SurfaceFormat& aFormat) {
  switch (aFormat) {
    case SurfaceFormat::B8G8R8A8:
    case SurfaceFormat::B8G8R8X8:
      return kBGRA_8888_SkColorType;
    case SurfaceFormat::R8G8B8A8:
    case SurfaceFormat::R8G8B8X8:
      return kRGBA_8888_SkColorType;
    default:
      break;
  }
  return kUnknown_SkColorType;
}

nsresult ConvertSRGBBufferToDisplayP3(uint8_t* aSrcBuffer,
                                      const SurfaceFormat& aSrcFormat,
                                      uint8_t* aDestBuffer, int aWidth,
                                      int aHeight) {
  if (!aSrcBuffer || !aDestBuffer || aWidth <= 0 || aHeight <= 0 ||
      !IsRGBX(aSrcFormat)) {
    return NS_ERROR_INVALID_ARG;
  }

  SkColorType srcColorType = ToSkColorType(aSrcFormat);
  if (srcColorType == kUnknown_SkColorType) {
    return NS_ERROR_NOT_IMPLEMENTED;
  }

  // TODO: Provide source's color space info to customize SkColorSpace.
  auto srcColorSpace = SkColorSpace::MakeSRGB();
  SkImageInfo srcInfo = SkImageInfo::Make(aWidth, aHeight, srcColorType,
                                          kUnpremul_SkAlphaType, srcColorSpace);

  constexpr size_t bytesPerPixel = 4;
  CheckedInt<size_t> rowBytes(bytesPerPixel);
  rowBytes *= aWidth;
  if (!rowBytes.isValid()) {
    return NS_ERROR_DOM_MEDIA_OVERFLOW_ERR;
  }

  SkBitmap srcBitmap;
  if (!srcBitmap.installPixels(srcInfo, aSrcBuffer, rowBytes.value())) {
    return NS_ERROR_FAILURE;
  }

  // TODO: Provide destination's color space info to customize SkColorSpace.
  auto destColorSpace =
      SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, SkNamedGamut::kDisplayP3);

  SkBitmap destBitmap;
  if (!destBitmap.tryAllocPixels(srcInfo.makeColorSpace(destColorSpace))) {
    return NS_ERROR_FAILURE;
  }

  if (!srcBitmap.readPixels(destBitmap.pixmap())) {
    return NS_ERROR_FAILURE;
  }

  CheckedInt<size_t> size(rowBytes.value());
  size *= aHeight;
  if (!size.isValid()) {
    return NS_ERROR_DOM_MEDIA_OVERFLOW_ERR;
  }

  PodCopy(aDestBuffer, reinterpret_cast<uint8_t*>(destBitmap.getPixels()),
          size.value());
  return NS_OK;
}

}  // namespace mozilla