1 // Copyright 2022 The PDFium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "core/fxge/calculate_pitch.h"
6
7 #include "core/fxcrt/fx_safe_types.h"
8 #include "core/fxge/dib/fx_dib.h"
9
10 namespace fxge {
11 namespace {
12
CalculatePitch8Safely(uint32_t bpc,uint32_t components,int width)13 FX_SAFE_UINT32 CalculatePitch8Safely(uint32_t bpc,
14 uint32_t components,
15 int width) {
16 FX_SAFE_UINT32 pitch = bpc;
17 pitch *= components;
18 pitch *= width;
19 pitch += 7;
20 pitch /= 8;
21 return pitch;
22 }
23
CalculatePitch32Safely(int bpp,int width)24 FX_SAFE_UINT32 CalculatePitch32Safely(int bpp, int width) {
25 FX_SAFE_UINT32 pitch = bpp;
26 pitch *= width;
27 pitch += 31;
28 pitch /= 32; // quantized to number of 32-bit words.
29 pitch *= 4; // and then back to bytes, (not just /8 in one step).
30 return pitch;
31 }
32
33 } // namespace
34
CalculatePitch8OrDie(uint32_t bits_per_component,uint32_t components_per_pixel,int width_in_pixels)35 uint32_t CalculatePitch8OrDie(uint32_t bits_per_component,
36 uint32_t components_per_pixel,
37 int width_in_pixels) {
38 return CalculatePitch8Safely(bits_per_component, components_per_pixel,
39 width_in_pixels)
40 .ValueOrDie();
41 }
42
CalculatePitch32OrDie(int bits_per_pixel,int width_in_pixels)43 uint32_t CalculatePitch32OrDie(int bits_per_pixel, int width_in_pixels) {
44 return CalculatePitch32Safely(bits_per_pixel, width_in_pixels).ValueOrDie();
45 }
46
CalculatePitch8(uint32_t bits_per_component,uint32_t components,int width_in_pixels)47 std::optional<uint32_t> CalculatePitch8(uint32_t bits_per_component,
48 uint32_t components,
49 int width_in_pixels) {
50 FX_SAFE_UINT32 pitch =
51 CalculatePitch8Safely(bits_per_component, components, width_in_pixels);
52 if (!pitch.IsValid())
53 return std::nullopt;
54 return pitch.ValueOrDie();
55 }
56
CalculatePitch32(int bits_per_pixel,int width_in_pixels)57 std::optional<uint32_t> CalculatePitch32(int bits_per_pixel,
58 int width_in_pixels) {
59 FX_SAFE_UINT32 pitch =
60 CalculatePitch32Safely(bits_per_pixel, width_in_pixels);
61 if (!pitch.IsValid())
62 return std::nullopt;
63 return pitch.ValueOrDie();
64 }
65
66 } // namespace fxge
67