pure_jpeg 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 780f932b176fecdb5daab2546909fe2610325e54f7364cf482e3e2652ab614a5
4
- data.tar.gz: 1fbc350f25d09b989ee6262e077bb36847c6637db325fb03c29f2083bb0ec973
3
+ metadata.gz: 7c252d678f3b8c916a2430b802569dc5099a19636359e9864637ed9fe01c90a3
4
+ data.tar.gz: 8feec524d8c41ca74be1e9bc47cf41b762cb14dc3500dc03c9240680d5877933
5
5
  SHA512:
6
- metadata.gz: a385db40804bf4a992d78253ba619e90b147aa5be7808b341398918f5f36c3593fbd1a979aaad9729ad874f2427fe15d31fc9a0413e5f7ea98ee44e43e125f2d
7
- data.tar.gz: b9f5581f4c4f27f42460961b3b4231fd94b45be130fbdce74a28bc4888f2a2f3de08fd43b9e3efc782ccb6b4f260aa8484ff7794e7bde1362018dc3deb282b26
6
+ metadata.gz: c8d26b4d4bed6da87f048036b06bc80eddd6c7ff8318032fb9cfccc15f5aea961e62fefe9965dde33c3d33cea5b611b4c2f6cb2397efa2f43effd8eb456fcf93
7
+ data.tar.gz: 63a9fe6bdf1136c8ea6c8e38a6b6641e6be2975fef4fea9394f0b48de22b01862996a87557b5c0bf7d7915020630f08c9285ebf8b8e8482f38f228c31b2d08e7
data/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.3
4
+
5
+ New features:
6
+
7
+ - `PureJPEG.from_chunky_png` accepts `background: [r, g, b]` to composite transparent PNG pixels before JPEG encoding
8
+
9
+ Fixes:
10
+
11
+ - Invalid `quality` and `chroma_quality` values now raise clear `ArgumentError`s
12
+ - `Image#[]` and `Image#[]=` now raise `IndexError` for out-of-bounds coordinates
13
+ - Hardened JFIF segment length validation for malformed JPEG input
14
+
3
15
  ## 0.3.2
4
16
 
5
17
  Performance:
data/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  Convert PNG or other pixel data to JPEG. Or the other way! Implements baseline JPEG encoding (DCT, Huffman, 4:2:0 chroma subsampling) and decodes both baseline and progressive JPEGs. Exposes a variety of encoding options to adjust parts of the JPEG pipeline not normally available (I needed this to recreate the JPEG compression styles of older digital cameras - don't ask..)
8
8
 
9
- It works on CRuby 3.0+, TruffleRuby 33.0, and JRuby 10.0.
9
+ It works on CRuby 3.0+, TruffleRuby 33.0, and JRuby 10.0. There's *almost* 100% test coverage - I need to find some "broken" JPEGs to do the rest (hit me up if you have any sources..)
10
10
 
11
11
  > [!NOTE]
12
12
  > Rubyists might find the [AI Disclosure](#ai-disclosure) section below of interest.
@@ -23,7 +23,7 @@ gem "pure_jpeg"
23
23
  gem install pure_jpeg
24
24
  ```
25
25
 
26
- There are no runtime dependencies. [ChunkyPNG](https://github.com/wvanbergen/chunky_png) is optional (though quite useful) if you want to use `from_chunky_png`. I have a pure PNG encoder/decoder not far behind this that will ultimately plug in nicely too to get 100% pure Ruby graphical bliss ;-)
26
+ There are no runtime dependencies. [ChunkyPNG](https://github.com/wvanbergen/chunky_png) is optional (though quite useful) if you want to use `from_chunky_png`.
27
27
 
28
28
  `examples/` contains some useful example scripts for basic JPEG to PNG and PNG to JPEG conversion if you want to do some quick tests without writing code.
29
29
 
@@ -39,6 +39,13 @@ image = ChunkyPNG::Image.from_file("photo.png")
39
39
  PureJPEG.from_chunky_png(image, quality: 80).write("photo.jpg")
40
40
  ```
41
41
 
42
+ If you want transparent pixels composited against a solid color instead of
43
+ using the PNG's hidden RGB values, pass an RGB background:
44
+
45
+ ```ruby
46
+ PureJPEG.from_chunky_png(image, background: [255, 255, 255], quality: 80).write("photo.jpg")
47
+ ```
48
+
42
49
  ### From any pixel source
43
50
 
44
51
  PureJPEG accepts any object that responds to `width`, `height`, and `[x, y]` (returning an object with `.r`, `.g`, `.b` in 0-255):
@@ -99,7 +106,7 @@ Here's a quick example of sort of the "old digital camera" effect I was looking
99
106
  </tr>
100
107
  </table>
101
108
 
102
- And here's what happens when you convert a PNG with transparency — JPEG doesn't support alpha, so the hidden RGB data behind transparent pixels bleeds through:
109
+ And here's what happens when you convert a PNG with transparency without a `background:` — JPEG doesn't support alpha, so the hidden RGB data behind transparent pixels bleeds through:
103
110
 
104
111
  <table>
105
112
  <tr>
@@ -112,7 +119,7 @@ And here's what happens when you convert a PNG with transparency — JPEG doesn'
112
119
  </tr>
113
120
  </table>
114
121
 
115
- I consider this a feature but you may consider it a deficiency and that a default background of white should be applied. This may be something I'll add if anyone wants it!
122
+ Pass `background: [255, 255, 255]` to composite transparent pixels over white, or any other `[r, g, b]` color you prefer.
116
123
 
117
124
  Note that each stage of the JPEG pipeline is a separate module, so individual components (DCT, quantization, Huffman coding) can be replaced or extended independently which is kinda my plan here as I made this to play around with effects.
118
125
 
@@ -198,25 +205,77 @@ Possible future improvements: ICC profile rendering/conversion.
198
205
 
199
206
  ## Performance
200
207
 
201
- On a 1024x1024 image (Ruby 4.0.2 with YJIT on an M5):
208
+ On a 1024x1024 image (Apple M5, 5 runs after warmup):
209
+
210
+ | Operation | CRuby 4.0.2 (YJIT) | TruffleRuby 33.0.1 |
211
+ |-----------|---------------------|---------------------|
212
+ | Encode (color, q85) | ~0.16s | ~0.08s |
213
+ | Decode (baseline) | ~0.14s | ~0.05s |
214
+ | Decode (progressive) | ~0.18s | ~0.09s |
215
+
216
+ The encoder and decoder use an integer-scaled AAN (Arai-Agui-Nakajima) DCT with fixed-point arithmetic throughout — no Float operations in the hot path. Color space conversion uses fixed-point integer math, and pixel data is stored as packed integers to avoid per-pixel object allocation. TruffleRuby's Graal JIT compiler can optimize these tight integer loops particularly well, resulting in 2-3x faster performance once warmed up.
217
+
218
+ ## Example scripts
219
+
220
+ The `examples/` directory contains ready-to-run scripts. All accept JPEG or PNG input (PNG requires the `chunky_png` gem).
221
+
222
+ **`png_to_jpeg.rb`** -- Convert a PNG to JPEG.
202
223
 
203
- | Operation | Time |
204
- |-----------|------|
205
- | Encode (color, q85) | ~0.16s |
206
- | Decode (baseline) | ~0.14s |
207
- | Decode (progressive) | ~0.18s |
224
+ ```
225
+ ruby examples/png_to_jpeg.rb [--grayscale] INPUT.png OUTPUT.jpg [quality]
226
+ ```
227
+
228
+ **`jpeg_to_png.rb`** -- Convert a JPEG to PNG.
208
229
 
209
- The encoder and decoder use an integer-scaled AAN (Arai-Agui-Nakajima) DCT with fixed-point arithmetic throughout — no Float operations in the hot path. Color space conversion uses fixed-point integer math, and pixel data is stored as packed integers to avoid per-pixel object allocation.
230
+ ```
231
+ ruby examples/jpeg_to_png.rb INPUT.jpg OUTPUT.png
232
+ ```
233
+
234
+ **`kodak.rb`** -- Apply the "scrambled quantization" effect that recreates the gritty look of early digicams like the Casio QV-10. See `CREATIVE.md` for more on this.
235
+
236
+ ```
237
+ ruby examples/kodak.rb INPUT.(jpg|png) [OUTPUT.jpg] [quality]
238
+ ```
239
+
240
+ **`lumacrush.rb`** -- Crush luminance while preserving chrominance. Produces a soft, oil-painting quality where detail is blocky but colors remain accurate.
241
+
242
+ ```
243
+ ruby examples/lumacrush.rb INPUT.(jpg|png) [OUTPUT.jpg] [luma_quality] [chroma_quality]
244
+ ```
245
+
246
+ **`chromacrush.rb`** -- The opposite: sharp detail with collapsed, blocky color patches.
247
+
248
+ ```
249
+ ruby examples/chromacrush.rb INPUT.(jpg|png) [OUTPUT.jpg] [luma_quality] [chroma_quality]
250
+ ```
251
+
252
+ **`loopy.rb`** -- Re-encode a JPEG through multiple passes to see how artifacts accumulate.
253
+
254
+ ```
255
+ ruby examples/loopy.rb INPUT.jpg [quality] [iterations]
256
+ ```
210
257
 
211
258
  ## Some useful `rake` tasks
212
259
 
213
260
  ```
214
261
  bundle install
215
262
  rake test # run the test suite
216
- rake benchmark # benchmark encoding and decoding (3 runs each)
263
+ rake benchmark # basic benchmark of encoding and decoding (5 runs after warmup)
217
264
  rake profile # CPU profile with StackProf (requires the stackprof gem)
218
265
  ```
219
266
 
267
+ ## Full benchmark script
268
+
269
+ `benchmark/run.rb` is a more thorough benchmark that exercises the encode and decode paths in several ways. It auto-enables YJIT, warms up before measuring, and reports object allocations, throughput (iterations/second via `benchmark-ips`), best-of-N wall-clock times, and a sustained mixed workload across encode (q85, q95 optimized, grayscale) and decode (baseline and progressive).
270
+
271
+ ```
272
+ ruby benchmark/run.rb # standard run
273
+ ruby benchmark/run.rb --quick # single-shot wall-clock + allocations
274
+ ruby benchmark/run.rb --full # longer run, includes YJIT runtime stats
275
+ ruby benchmark/run.rb --profile # CPU profile with Vernier (writes JSON to /tmp)
276
+ ruby benchmark/run.rb --profile-alloc # retained-object profile with Vernier
277
+ ```
278
+
220
279
  ## AI Disclosure
221
280
 
222
281
  **Claude Code did the majority of the work.** The math of JPEG encoding/decoding is beyond me, except 'getting it' at a high level. I understand it like I understand the engine in my car :-) *Later update: OpenAI Codex is also reviewing and adding features now. It feels stronger in many areas.*
@@ -236,6 +295,7 @@ rake profile # CPU profile with StackProf (requires the stackprof gem)
236
295
  ## Credits
237
296
 
238
297
  - [Ufuk Kayserilioglu](https://github.com/paracycle) - Major performance optimizations including integer-scaled AAN DCT, fixed-point color space conversion, and YJIT-targeted improvements.
298
+ - [Keith R. Bennett](https://github.com/keithrbennett) - Coverage testing and adding SimpleCov to the project.
239
299
 
240
300
  ## License
241
301
 
@@ -42,6 +42,9 @@ module PureJPEG
42
42
  luminance_table: nil, chrominance_table: nil,
43
43
  quantization_modifier: nil, scramble_quantization: false,
44
44
  optimize_huffman: false)
45
+ validate_quality!(quality, "quality")
46
+ validate_quality!(chroma_quality, "chroma_quality") if chroma_quality
47
+
45
48
  @source = source
46
49
  @quality = quality
47
50
  @grayscale = grayscale
@@ -92,6 +95,12 @@ module PureJPEG
92
95
  modified
93
96
  end
94
97
 
98
+ def validate_quality!(value, name)
99
+ unless value.is_a?(Integer) && value.between?(1, 100)
100
+ raise ArgumentError, "#{name} must be an integer between 1 and 100"
101
+ end
102
+ end
103
+
95
104
  def validate_qtable!(table, name)
96
105
  unless table.respond_to?(:length) && table.respond_to?(:all?)
97
106
  raise ArgumentError, "#{name} must be a 64-element array of integers between 1 and 255"
@@ -38,6 +38,7 @@ module PureJPEG
38
38
  # @param y [Integer] row (0-based)
39
39
  # @return [Source::Pixel] pixel with +.r+, +.g+, +.b+ in 0-255
40
40
  def [](x, y)
41
+ validate_coordinates!(x, y)
41
42
  color = @packed_pixels[y * @width + x]
42
43
  Source::Pixel.new((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF)
43
44
  end
@@ -49,6 +50,7 @@ module PureJPEG
49
50
  # @param pixel [Source::Pixel] replacement pixel
50
51
  # @return [Source::Pixel]
51
52
  def []=(x, y, pixel)
53
+ validate_coordinates!(x, y)
52
54
  @packed_pixels[y * @width + x] = (pixel.r << 16) | (pixel.g << 8) | pixel.b
53
55
  pixel
54
56
  end
@@ -85,5 +87,13 @@ module PureJPEG
85
87
  end
86
88
  end
87
89
  end
90
+
91
+ private
92
+
93
+ def validate_coordinates!(x, y)
94
+ unless x.is_a?(Integer) && y.is_a?(Integer) && x >= 0 && y >= 0 && x < @width && y < @height
95
+ raise IndexError, "Pixel coordinate out of bounds: #{x.inspect}, #{y.inspect}"
96
+ end
97
+ end
88
98
  end
89
99
  end
@@ -101,10 +101,9 @@ module PureJPEG
101
101
  ICC_PROFILE_SIG = "ICC_PROFILE\0".b
102
102
 
103
103
  def parse_app2
104
- length = read_u16
105
- end_pos = @pos + length - 2
104
+ end_pos = read_segment_end
106
105
 
107
- if length >= 16 && @data[@pos, 12] == ICC_PROFILE_SIG
106
+ if (end_pos - @pos) >= 14 && @data[@pos, 12] == ICC_PROFILE_SIG
108
107
  @pos += 12
109
108
  seq_no = read_byte
110
109
  _total = read_byte
@@ -121,18 +120,18 @@ module PureJPEG
121
120
  end
122
121
 
123
122
  def skip_segment
124
- length = read_u16
125
- @pos += length - 2
123
+ @pos = read_segment_end
126
124
  end
127
125
 
128
126
  def parse_dqt
129
- length = read_u16
130
- end_pos = @pos + length - 2
127
+ end_pos = read_segment_end
131
128
 
132
129
  while @pos < end_pos
133
130
  info = read_byte
134
131
  precision = (info >> 4) & 0x0F # 0 = 8-bit, 1 = 16-bit
135
132
  table_id = info & 0x0F
133
+ bytes_per_value = precision == 0 ? 1 : 2
134
+ ensure_remaining_in_segment!(end_pos, 64 * bytes_per_value, "DQT")
136
135
 
137
136
  zigzag_table = Array.new(64)
138
137
  64.times do |i|
@@ -146,16 +145,17 @@ module PureJPEG
146
145
  end
147
146
 
148
147
  def parse_dht
149
- length = read_u16
150
- end_pos = @pos + length - 2
148
+ end_pos = read_segment_end
151
149
 
152
150
  while @pos < end_pos
151
+ ensure_remaining_in_segment!(end_pos, 17, "DHT")
153
152
  info = read_byte
154
153
  table_class = (info >> 4) & 0x0F # 0 = DC, 1 = AC
155
154
  table_id = info & 0x0F
156
155
 
157
156
  bits = Array.new(16) { read_byte }
158
157
  total = bits.sum
158
+ ensure_remaining_in_segment!(end_pos, total, "DHT")
159
159
  values = Array.new(total) { read_byte }
160
160
 
161
161
  @huffman_tables[[table_class, table_id]] = { bits: bits, values: values }
@@ -163,11 +163,13 @@ module PureJPEG
163
163
  end
164
164
 
165
165
  def parse_sof0
166
- read_u16 # length
166
+ end_pos = read_segment_end
167
+ ensure_remaining_in_segment!(end_pos, 6, "SOF")
167
168
  read_byte # precision (always 8 for baseline)
168
169
  @height = read_u16
169
170
  @width = read_u16
170
171
  num_components = read_byte
172
+ ensure_remaining_in_segment!(end_pos, num_components * 3, "SOF")
171
173
 
172
174
  @components = Array.new(num_components) do
173
175
  id = read_byte
@@ -177,11 +179,14 @@ module PureJPEG
177
179
  qt_id = read_byte
178
180
  Component.new(id, h, v, qt_id)
179
181
  end
182
+ @pos = end_pos
180
183
  end
181
184
 
182
185
  def parse_sos
183
- read_u16 # length
186
+ end_pos = read_segment_end
187
+ ensure_remaining_in_segment!(end_pos, 1, "SOS")
184
188
  num_components = read_byte
189
+ ensure_remaining_in_segment!(end_pos, num_components * 2 + 3, "SOS")
185
190
 
186
191
  components = Array.new(num_components) do
187
192
  id = read_byte
@@ -196,12 +201,33 @@ module PureJPEG
196
201
  ahl = read_byte # successive approximation
197
202
  ah = (ahl >> 4) & 0x0F
198
203
  al = ahl & 0x0F
204
+ @pos = end_pos
199
205
  Scan.new(components, ss, se, ah, al, nil)
200
206
  end
201
207
 
202
208
  def parse_dri
203
- read_u16 # length
209
+ end_pos = read_segment_end
210
+ ensure_remaining_in_segment!(end_pos, 2, "DRI")
204
211
  @restart_interval = read_u16
212
+ @pos = end_pos
213
+ end
214
+
215
+ def read_segment_end
216
+ length = read_u16
217
+ raise PureJPEG::DecodeError, "Invalid JPEG segment length: #{length}" if length < 2
218
+
219
+ end_pos = @pos + length - 2
220
+ if end_pos > @data.bytesize
221
+ raise PureJPEG::DecodeError, "JPEG segment length exceeds available data"
222
+ end
223
+
224
+ end_pos
225
+ end
226
+
227
+ def ensure_remaining_in_segment!(end_pos, byte_count, segment_name)
228
+ return if @pos + byte_count <= end_pos
229
+
230
+ raise PureJPEG::DecodeError, "Truncated #{segment_name} segment"
205
231
  end
206
232
 
207
233
  # Extract entropy-coded scan data (everything from current position to EOI marker).
@@ -18,10 +18,16 @@ module PureJPEG
18
18
  attr_reader :height
19
19
 
20
20
  # @param image [ChunkyPNG::Image] the source PNG image
21
- def initialize(image)
21
+ # @param background [Array<Integer>, nil] optional [r, g, b] background
22
+ # color to composite transparent pixels against before encoding
23
+ def initialize(image, background: nil)
22
24
  @width = image.width
23
25
  @height = image.height
24
- @packed_pixels = image.pixels
26
+ @packed_pixels = if background.nil?
27
+ image.pixels
28
+ else
29
+ composite_pixels(image.pixels, background)
30
+ end
25
31
  end
26
32
 
27
33
  # @return [Array<Integer>] flat row-major array of packed RGBA integers
@@ -40,6 +46,37 @@ module PureJPEG
40
46
  (color >> 8) & 0xFF
41
47
  )
42
48
  end
49
+
50
+ private
51
+
52
+ def composite_pixels(pixels, background)
53
+ bg_r, bg_g, bg_b = validate_background!(background)
54
+
55
+ pixels.map do |color|
56
+ alpha = color & 0xFF
57
+ next color if alpha == 255
58
+
59
+ src_r = (color >> 24) & 0xFF
60
+ src_g = (color >> 16) & 0xFF
61
+ src_b = (color >> 8) & 0xFF
62
+ inv_alpha = 255 - alpha
63
+
64
+ r = ((src_r * alpha) + (bg_r * inv_alpha) + 127) / 255
65
+ g = ((src_g * alpha) + (bg_g * inv_alpha) + 127) / 255
66
+ b = ((src_b * alpha) + (bg_b * inv_alpha) + 127) / 255
67
+
68
+ (r << 24) | (g << 16) | (b << 8) | 255
69
+ end
70
+ end
71
+
72
+ def validate_background!(background)
73
+ unless background.respond_to?(:length) && background.length == 3 &&
74
+ background.all? { |v| v.is_a?(Integer) && v.between?(0, 255) }
75
+ raise ArgumentError, "background must be an [r, g, b] array of integers between 0 and 255"
76
+ end
77
+
78
+ background
79
+ end
43
80
  end
44
81
  end
45
82
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PureJPEG
4
- VERSION = "0.3.2"
4
+ VERSION = "0.3.3"
5
5
  end
data/lib/pure_jpeg.rb CHANGED
@@ -50,10 +50,12 @@ module PureJPEG
50
50
  # and passes it to {.encode}.
51
51
  #
52
52
  # @param image [ChunkyPNG::Image] the source image
53
+ # @param background [Array<Integer>, nil] optional [r, g, b] background
54
+ # color to composite transparent pixels against before encoding
53
55
  # @param opts [Hash] encoding options passed to {Encoder#initialize}
54
56
  # @return [Encoder]
55
- def self.from_chunky_png(image, **opts)
56
- source = Source::ChunkyPNGSource.new(image)
57
+ def self.from_chunky_png(image, background: nil, **opts)
58
+ source = Source::ChunkyPNGSource.new(image, background: background)
57
59
  Encoder.new(source, **opts)
58
60
  end
59
61
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pure_jpeg
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.2
4
+ version: 0.3.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Peter Cooper
@@ -86,7 +86,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
86
86
  - !ruby/object:Gem::Version
87
87
  version: '0'
88
88
  requirements: []
89
- rubygems_version: 3.6.9
89
+ rubygems_version: 4.0.6
90
90
  specification_version: 4
91
91
  summary: Pure Ruby JPEG encoder and decoder
92
92
  test_files: []