pure_jpeg 0.4.0 → 0.5.0

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.
@@ -1,309 +1,305 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PureJPEG
4
- # Baseline JPEG decoder.
4
+ # Baseline and progressive JPEG decoder.
5
5
  #
6
- # Decodes baseline DCT (SOF0) JPEGs with 1 or 3 components, any chroma
7
- # subsampling factor, and restart markers.
6
+ # Decodes baseline (SOF0) and progressive (SOF2) 8-bit grayscale/YCbCr
7
+ # JPEGs, including separate component scans and restart markers.
8
8
  #
9
9
  # Use {PureJPEG.read} for a convenient entry point.
10
10
  class Decoder
11
11
  # Decode a JPEG from a file path or binary string.
12
12
  #
13
13
  # @param path_or_data [String] a file path or raw JPEG bytes
14
+ # @param max_pixels [Integer] positive maximum image area
14
15
  # @return [Image] decoded image with pixel access
15
- def self.decode(path_or_data)
16
- data = if path_or_data.is_a?(String) && !path_or_data.start_with?("\xFF\xD8".b) && File.exist?(path_or_data)
16
+ def self.decode(path_or_data, max_pixels: MAX_PIXELS)
17
+ data = if path_or_data.is_a?(String) && !path_or_data.b.include?("\0") && !path_or_data.b.start_with?("\xFF\xD8".b) && File.exist?(path_or_data)
17
18
  File.binread(path_or_data)
18
19
  else
19
20
  path_or_data.b
20
21
  end
21
- new(data).decode
22
+ new(data, max_pixels: max_pixels).decode
22
23
  end
23
24
 
24
- def initialize(data)
25
+ def initialize(data, max_pixels: MAX_PIXELS)
26
+ unless max_pixels.is_a?(Integer) && max_pixels > 0
27
+ raise ArgumentError, "max_pixels must be a positive Integer"
28
+ end
25
29
  @data = data
30
+ @max_pixels = max_pixels
26
31
  end
27
32
 
28
- def decode
29
- jfif = JFIFReader.new(@data)
30
- @icc_profile = jfif.icc_profile
31
- validate_dimensions!(jfif.width, jfif.height)
32
- return decode_progressive(jfif) if jfif.progressive
33
+ # Each component holds one frame MCU row of samples (and, for progressive
34
+ # scans, coefficients). Each scan keeps its own entropy position across rows.
35
+ ComponentStrip = Struct.new(:component, :block_columns, :scan_columns, :scan_rows,
36
+ :quant_table, :samples, :coefficients)
37
+ ScanState = Struct.new(:scan, :reader, :mcu_blocks, :prev_dc, :mcu_count, :eobrun)
38
+ private_constant :ComponentStrip, :ScanState
33
39
 
40
+ def decode
41
+ jfif = JFIFReader.new(@data, max_pixels: @max_pixels)
34
42
  width = jfif.width
35
43
  height = jfif.height
44
+ validate_dimensions!(width, height)
45
+ validate_frame_and_scans!(jfif)
36
46
 
37
- # Build Huffman decode tables
38
- dc_tables = {}
39
- ac_tables = {}
40
- jfif.huffman_tables.each do |(table_class, table_id), info|
41
- table = Huffman::DecodeTable.new(info[:bits], info[:values])
42
- if table_class == 0
43
- dc_tables[table_id] = table
44
- else
45
- ac_tables[table_id] = table
46
- end
47
- end
48
-
49
- # Map component IDs to their info
50
- comp_info = {}
51
- jfif.components.each { |c| comp_info[c.id] = c }
52
-
53
- # Determine max sampling factors
54
47
  max_h = jfif.components.map(&:h_sampling).max
55
48
  max_v = jfif.components.map(&:v_sampling).max
56
-
57
- # MCU dimensions in pixels
58
- mcu_px_w = max_h * 8
59
- mcu_px_h = max_v * 8
60
- mcus_x = (width + mcu_px_w - 1) / mcu_px_w
61
- mcus_y = (height + mcu_px_h - 1) / mcu_px_h
62
-
63
- # Allocate channel buffers (full padded size)
64
- padded_w = mcus_x * mcu_px_w
65
- padded_h = mcus_y * mcu_px_h
66
- channels = {}
67
- jfif.components.each do |c|
68
- ch_w = (padded_w * c.h_sampling) / max_h
69
- ch_h = (padded_h * c.v_sampling) / max_v
70
- channels[c.id] = { data: Array.new(ch_w * ch_h, 0), width: ch_w, height: ch_h }
49
+ mcu_width = max_h * 8
50
+ strip_height = max_v * 8
51
+ mcu_columns = (width + mcu_width - 1) / mcu_width
52
+ strips = {}
53
+ jfif.components.each do |comp|
54
+ block_columns = mcu_columns * comp.h_sampling
55
+ size = block_columns * comp.v_sampling * 64
56
+ scan_columns = (width * comp.h_sampling + mcu_width - 1) / mcu_width
57
+ scan_rows = (height * comp.v_sampling + strip_height - 1) / strip_height
58
+ coeffs = Array.new(size, 0) if jfif.progressive
59
+ strips[comp.id] = ComponentStrip.new(comp, block_columns, scan_columns, scan_rows,
60
+ fetch_quant_table!(jfif, comp), Array.new(size, 0), coeffs)
71
61
  end
72
-
73
- # Decode scan data
74
- reader = BitReader.new(jfif.scan_data)
75
- prev_dc = Hash.new(0)
76
- restart_interval = jfif.restart_interval
77
- mcu_count = 0
78
-
79
- # Reusable buffers
62
+ ordered_strips = resolve_color_components(jfif.components).map { |comp| strips[comp.id] }
63
+ states = jfif.scans.map { |scan| build_scan_state(scan, strips, jfif.progressive) }
64
+ pixels = Array.new(width * height, 0)
80
65
  zigzag = Array.new(64, 0)
81
66
  dequant = Array.new(64, 0)
82
67
 
83
- scan_components = jfif.scan_components.map do |sc|
84
- comp, dc_tab, ac_tab = resolve_scan_references!(sc, comp_info, dc_tables, ac_tables)
85
- [sc, comp, dc_tab, ac_tab, fetch_quant_table!(jfif, comp), channels[comp.id]]
68
+ # Scans refine the same blocks in file order. Predictors, restart counts,
69
+ # and EOB runs belong to their scan and continue into the next strip.
70
+ (0...height).step(strip_height) do |top|
71
+ states.each do |state|
72
+ decode_scan_strip(state, top / strip_height, mcu_columns, jfif.progressive, zigzag, dequant)
73
+ end
74
+ if jfif.progressive
75
+ ordered_strips.each { |strip| reconstruct_strip(strip, dequant) }
76
+ end
77
+ rows = [strip_height, height - top].min
78
+ if ordered_strips.length == 1
79
+ assemble_grayscale(pixels, width, top, rows, ordered_strips.first)
80
+ else
81
+ assemble_color(pixels, width, top, rows, ordered_strips, max_h, max_v)
82
+ end
86
83
  end
84
+ states.each do |state|
85
+ raise DecodeError, "Progressive EOB run exceeds scan" if state.eobrun > 0
86
+ state.reader.finish_scan!
87
+ end
88
+ Image.new(width, height, pixels, icc_profile: jfif.icc_profile)
89
+ end
87
90
 
88
- mcus_y.times do |mcu_row|
89
- mcus_x.times do |mcu_col|
90
- # Handle restart interval
91
- if restart_interval > 0 && mcu_count > 0 && (mcu_count % restart_interval) == 0
92
- reader.reset
93
- prev_dc.clear
94
- end
91
+ private
95
92
 
96
- scan_components.each do |sc, comp, dc_tab, ac_tab, qt, ch|
97
- comp.v_sampling.times do |bv|
98
- comp.h_sampling.times do |bh|
99
- # Decode one 8x8 block
100
- decode_block(reader, dc_tab, ac_tab, prev_dc, sc.id, zigzag)
93
+ def build_scan_state(scan, strips, progressive)
94
+ dc_tables, ac_tables = build_decode_tables(scan)
95
+ require_dc = !progressive || (scan.spectral_start == 0 && scan.successive_high == 0)
96
+ require_ac = !progressive || scan.spectral_start > 0
97
+ interleaved = scan.components.length > 1
98
+ blocks = []
99
+ scan.components.each do |sc|
100
+ strip = strips.fetch(sc.id)
101
+ dc = dc_tables[sc.dc_table_id]
102
+ ac = ac_tables[sc.ac_table_id]
103
+ if require_dc && !dc
104
+ raise DecodeError, "Component #{sc.id} references missing DC Huffman table #{sc.dc_table_id}"
105
+ end
106
+ if require_ac && !ac
107
+ raise DecodeError, "Component #{sc.id} references missing AC Huffman table #{sc.ac_table_id}"
108
+ end
109
+ # Precompute the block layout of an MCU once for this scan.
110
+ h_blocks = interleaved ? strip.component.h_sampling : 1
111
+ v_blocks = interleaved ? strip.component.v_sampling : 1
112
+ v_blocks.times do |dy|
113
+ h_blocks.times { |dx| blocks << [strip, dc, ac, h_blocks, dx, dy] }
114
+ end
115
+ end
116
+ ScanState.new(scan, BitReader.new(scan.data), blocks, Hash.new(0), 0, 0)
117
+ end
101
118
 
102
- # Inverse pipeline: unzigzag -> dequantize -> IDCT -> level shift
103
- Quantization.dequantize_zigzag!(zigzag, qt, dequant)
104
- DCT.inverse!(dequant)
119
+ def decode_scan_strip(state, strip_index, mcu_columns, progressive, zigzag, dequant)
120
+ scan = state.scan
121
+ reader = state.reader
122
+ interval = scan.restart_interval
123
+ blocks = state.mcu_blocks
124
+ columns = mcu_columns
125
+ rows = 1
126
+ if scan.components.length == 1
127
+ # A non-interleaved MCU is one block. Omit the frame's padding blocks
128
+ # at the right and bottom edges while keeping the padded storage stride.
129
+ strip = blocks.first[0]
130
+ v = strip.component.v_sampling
131
+ columns = strip.scan_columns
132
+ rows = [v, strip.scan_rows - strip_index * v].min
133
+ return decode_ac_strip(state, rows, columns) if scan.spectral_start > 0
134
+ end
105
135
 
106
- # Write block into channel buffer
107
- bx = (mcu_col * comp.h_sampling + bh) * 8
108
- by = (mcu_row * comp.v_sampling + bv) * 8
109
- write_block(dequant, ch[:data], ch[:width], bx, by)
136
+ count = state.mcu_count
137
+ rows.times do |row|
138
+ columns.times do |col|
139
+ if interval > 0 && count > 0 && (count % interval) == 0
140
+ reader.read_restart((count / interval - 1) % 8)
141
+ state.prev_dc.clear
142
+ end
143
+ # An indexed loop avoids a per-MCU closure allocation on Spinel.
144
+ index = 0
145
+ while index < blocks.length
146
+ strip, dc, ac, h_blocks, dx, dy = blocks[index]
147
+ index += 1
148
+ bx = col * h_blocks + dx
149
+ by = row + dy
150
+ if progressive
151
+ offset = (by * strip.block_columns + bx) * 64
152
+ coeffs = strip.coefficients
153
+ if scan.successive_high == 0
154
+ id = strip.component.id
155
+ state.prev_dc[id] = prog_dc_first(reader, dc, state.prev_dc[id], coeffs, offset, scan.successive_low)
156
+ else
157
+ prog_dc_refine(reader, coeffs, offset, scan.successive_low)
110
158
  end
159
+ else
160
+ decode_block(reader, dc, ac, state.prev_dc, strip.component.id, zigzag)
161
+ Quantization.dequantize_zigzag!(zigzag, strip.quant_table, dequant)
162
+ DCT.inverse!(dequant)
163
+ write_block(dequant, strip.samples, strip.block_columns * 8, bx * 8, by * 8)
111
164
  end
112
165
  end
113
-
114
- mcu_count += 1
166
+ count += 1
115
167
  end
116
168
  end
117
-
118
- # Assemble pixels
119
- num_components = jfif.components.length
120
- if num_components == 1
121
- assemble_grayscale(width, height, channels, jfif.components[0])
122
- elsif num_components == 3
123
- assemble_color(width, height, channels, jfif.components, max_h, max_v)
124
- else
125
- raise DecodeError, "Unsupported number of components: #{num_components}"
126
- end
169
+ state.mcu_count = count
127
170
  end
128
171
 
129
- private
130
-
131
- def validate_dimensions!(width, height)
132
- raise DecodeError, "Invalid image dimensions: #{width}x#{height}" if width <= 0 || height <= 0
133
- raise DecodeError, "Image too large: #{width}x#{height} (max #{MAX_DIMENSION}x#{MAX_DIMENSION})" if width > MAX_DIMENSION || height > MAX_DIMENSION
172
+ def build_decode_tables(scan)
173
+ dc_tables = {}
174
+ ac_tables = {}
175
+ scan.huffman_tables.each do |(table_class, table_id), info|
176
+ table = Huffman::DecodeTable.new(info[:bits], info[:values])
177
+ if table_class == 0
178
+ dc_tables[table_id] = table
179
+ else
180
+ ac_tables[table_id] = table
181
+ end
182
+ end
183
+ [dc_tables, ac_tables]
134
184
  end
135
185
 
136
- # --- Progressive JPEG decoding ---
137
-
138
- def decode_progressive(jfif)
139
- width = jfif.width
140
- height = jfif.height
141
-
142
- comp_info = {}
143
- jfif.components.each { |c| comp_info[c.id] = c }
144
-
145
- max_h = jfif.components.map(&:h_sampling).max
146
- max_v = jfif.components.map(&:v_sampling).max
147
-
148
- mcu_px_w = max_h * 8
149
- mcu_px_h = max_v * 8
150
- mcus_x = (width + mcu_px_w - 1) / mcu_px_w
151
- mcus_y = (height + mcu_px_h - 1) / mcu_px_h
152
-
153
- # Coefficient buffers per component (zigzag order, pre-dequantization)
154
- coeffs = {}
155
- comp_blocks = {}
156
- jfif.components.each do |c|
157
- bx = mcus_x * c.h_sampling
158
- by = mcus_y * c.v_sampling
159
- coeffs[c.id] = Array.new(bx * by * 64, 0)
160
- comp_blocks[c.id] = [bx, by]
186
+ def validate_frame_and_scans!(jfif)
187
+ unless jfif.precision == 8
188
+ raise DecodeError, "Unsupported JPEG precision: #{jfif.precision}"
161
189
  end
190
+ count = jfif.components.length
191
+ unless count == 1 || count == 3
192
+ raise DecodeError, "Unsupported number of components: #{count}"
193
+ end
194
+ ids = jfif.components.map(&:id)
195
+ if count == 3 && (jfif.adobe_transform == 0 || ids.sort == [66, 71, 82])
196
+ raise DecodeError, "RGB JPEG decoding is unsupported"
197
+ end
198
+ if jfif.adobe_transform && ![0, 1].include?(jfif.adobe_transform)
199
+ raise DecodeError, "Unsupported Adobe color transform: #{jfif.adobe_transform}"
200
+ end
201
+ raise DecodeError, "JPEG scan data not found" if jfif.scans.empty?
162
202
 
163
- restart_interval = jfif.restart_interval
164
-
203
+ progression = {}
204
+ ids.each { |id| progression[id] = Array.new(64) }
165
205
  jfif.scans.each do |scan|
166
- # Build Huffman tables from this scan's snapshot (tables change between scans)
167
- dc_tables = {}
168
- ac_tables = {}
169
- scan.huffman_tables.each do |(table_class, table_id), info|
170
- table = Huffman::DecodeTable.new(info[:bits], info[:values])
171
- if table_class == 0
172
- dc_tables[table_id] = table
173
- else
174
- ac_tables[table_id] = table
175
- end
206
+ scan_ids = scan.components.map(&:id)
207
+ if scan_ids.empty? || scan_ids.uniq.length != scan_ids.length
208
+ raise DecodeError, "Invalid JPEG scan components"
209
+ end
210
+ scan_ids.each do |id|
211
+ raise DecodeError, "Scan references unknown component id #{id}" unless progression.key?(id)
212
+ end
213
+ if scan_ids.length > 1
214
+ blocks = jfif.components.select { |c| scan_ids.include?(c.id) }.sum { |c| c.h_sampling * c.v_sampling }
215
+ raise DecodeError, "Too many blocks in JPEG MCU" if blocks > 10
176
216
  end
177
217
 
178
- reader = BitReader.new(scan.data)
179
218
  ss = scan.spectral_start
180
219
  se = scan.spectral_end
181
220
  ah = scan.successive_high
182
221
  al = scan.successive_low
183
-
184
- if scan.components.length == 1
185
- prog_scan_non_interleaved(reader, scan, comp_info, dc_tables, ac_tables,
186
- coeffs, comp_blocks, restart_interval, ss, se, ah, al)
187
- else
188
- prog_scan_interleaved(reader, scan, comp_info, dc_tables, ac_tables,
189
- coeffs, comp_blocks, mcus_x, mcus_y, restart_interval, ss, se, ah, al)
222
+ if jfif.progressive
223
+ valid = ss <= se && se <= 63 && ah <= 13 && al <= 13 &&
224
+ (ss == 0 ? se == 0 : scan_ids.length == 1) &&
225
+ (ah == 0 || al == ah - 1)
226
+ raise DecodeError, "Invalid progressive scan parameters" unless valid
227
+ elsif ss != 0 || se != 63 || ah != 0 || al != 0
228
+ raise DecodeError, "Invalid baseline scan parameters"
190
229
  end
191
- end
192
-
193
- # Reconstruct: unzigzag/dequantize, IDCT, write to channel buffers
194
- padded_w = mcus_x * mcu_px_w
195
- padded_h = mcus_y * mcu_px_h
196
- channels = {}
197
- jfif.components.each do |c|
198
- ch_w = (padded_w * c.h_sampling) / max_h
199
- ch_h = (padded_h * c.v_sampling) / max_v
200
- channels[c.id] = { data: Array.new(ch_w * ch_h, 0), width: ch_w, height: ch_h }
201
- end
202
-
203
- dequant = Array.new(64, 0)
204
-
205
- jfif.components.each do |c|
206
- qt = fetch_quant_table!(jfif, c)
207
- ch = channels[c.id]
208
- coeff_buf = coeffs[c.id]
209
- bx_count, by_count = comp_blocks[c.id]
210
-
211
- by_count.times do |block_y|
212
- bx_count.times do |block_x|
213
- offset = (block_y * bx_count + block_x) * 64
214
- Quantization.dequantize_zigzag!(coeff_buf, qt, dequant, offset)
215
- DCT.inverse!(dequant)
216
- write_block(dequant, ch[:data], ch[:width], block_x * 8, block_y * 8)
230
+ scan_ids.each do |id|
231
+ state = progression[id]
232
+ if ss > 0 && state[0].nil?
233
+ raise DecodeError, "Progressive AC scan precedes DC scan"
234
+ end
235
+ ss.upto(se) do |k|
236
+ unless ah == 0 ? state[k].nil? : state[k] == ah
237
+ raise DecodeError, "Invalid JPEG scan progression"
238
+ end
239
+ state[k] = al
217
240
  end
218
241
  end
219
242
  end
220
-
221
- num_components = jfif.components.length
222
- if num_components == 1
223
- assemble_grayscale(width, height, channels, jfif.components[0])
224
- elsif num_components == 3
225
- assemble_color(width, height, channels, jfif.components, max_h, max_v)
226
- else
227
- raise DecodeError, "Unsupported number of components: #{num_components}"
243
+ if progression.values.any? { |state| state[0].nil? }
244
+ raise DecodeError, "JPEG scan omits a frame component"
228
245
  end
246
+ jfif.components.each { |c| fetch_quant_table!(jfif, c) }
229
247
  end
230
248
 
231
- def prog_scan_non_interleaved(reader, scan, comp_info, dc_tables, ac_tables,
232
- coeffs, comp_blocks, restart_interval, ss, se, ah, al)
233
- sc = scan.components[0]
234
- comp, dc_tab, ac_tab = resolve_scan_references!(sc, comp_info, dc_tables, ac_tables, require_ac: ss > 0)
235
- coeff_buf = coeffs[comp.id]
236
- bx_count, by_count = comp_blocks[comp.id]
237
-
238
- prev_dc = 0
239
- eobrun = 0
240
- mcu_count = 0
241
-
242
- by_count.times do |block_y|
243
- bx_count.times do |block_x|
244
- if restart_interval > 0 && mcu_count > 0 && (mcu_count % restart_interval) == 0
245
- reader.reset
246
- prev_dc = 0
247
- eobrun = 0
248
- end
249
+ def validate_dimensions!(width, height)
250
+ raise DecodeError, "JPEG frame header not found" unless width && height
251
+ raise DecodeError, "Invalid image dimensions: #{width}x#{height}" if width <= 0 || height <= 0
252
+ raise DecodeError, "Image too large: #{width}x#{height} (max #{MAX_DIMENSION}x#{MAX_DIMENSION})" if width > MAX_DIMENSION || height > MAX_DIMENSION
253
+ end
249
254
 
250
- offset = (block_y * bx_count + block_x) * 64
255
+ # --- Progressive JPEG decoding ---
251
256
 
252
- if ss == 0
253
- if ah == 0
254
- prev_dc = prog_dc_first(reader, dc_tab, prev_dc, coeff_buf, offset, al)
255
- else
256
- prog_dc_refine(reader, coeff_buf, offset, al)
257
- end
257
+ # Progressive AC scans always visit one block per MCU. An EOB run may
258
+ # span several rows, including the boundary between two strips.
259
+ def decode_ac_strip(state, rows, columns)
260
+ strip, _dc, ac = state.mcu_blocks.first
261
+ coeffs = strip.coefficients
262
+ scan = state.scan
263
+ reader = state.reader
264
+ ss = scan.spectral_start
265
+ se = scan.spectral_end
266
+ al = scan.successive_low
267
+ first = scan.successive_high == 0
268
+ interval = scan.restart_interval
269
+ count = state.mcu_count
270
+ eobrun = state.eobrun
271
+ rows.times do |row|
272
+ offset = row * strip.block_columns * 64
273
+ columns.times do
274
+ if interval > 0 && count > 0 && (count % interval) == 0
275
+ raise DecodeError, "Progressive EOB run crosses restart boundary" if eobrun > 0
276
+ reader.read_restart((count / interval - 1) % 8)
277
+ end
278
+ if first
279
+ eobrun = prog_ac_first(reader, ac, coeffs, offset, ss, se, al, eobrun)
258
280
  else
259
- if ah == 0
260
- eobrun = prog_ac_first(reader, ac_tab, coeff_buf, offset, ss, se, al, eobrun)
261
- else
262
- eobrun = prog_ac_refine(reader, ac_tab, coeff_buf, offset, ss, se, al, eobrun)
263
- end
281
+ eobrun = prog_ac_refine(reader, ac, coeffs, offset, ss, se, al, eobrun)
264
282
  end
265
-
266
- mcu_count += 1
283
+ count += 1
284
+ offset += 64
267
285
  end
268
286
  end
287
+ state.mcu_count = count
288
+ state.eobrun = eobrun
269
289
  end
270
290
 
271
- def prog_scan_interleaved(reader, scan, comp_info, dc_tables, ac_tables,
272
- coeffs, comp_blocks, mcus_x, mcus_y, restart_interval, ss, se, ah, al)
273
- prev_dc = Hash.new(0)
274
- mcu_count = 0
275
-
276
- scan_components = scan.components.map do |sc|
277
- comp, dc_tab = resolve_scan_references!(sc, comp_info, dc_tables, ac_tables, require_ac: false)
278
- [sc, comp, dc_tab, coeffs[comp.id], comp_blocks[comp.id][0]]
279
- end
280
-
281
- mcus_y.times do |mcu_row|
282
- mcus_x.times do |mcu_col|
283
- if restart_interval > 0 && mcu_count > 0 && (mcu_count % restart_interval) == 0
284
- reader.reset
285
- prev_dc.clear
286
- end
287
-
288
- scan_components.each do |sc, comp, dc_tab, coeff_buf, bx_count|
289
- comp.v_sampling.times do |bv|
290
- comp.h_sampling.times do |bh|
291
- block_x = mcu_col * comp.h_sampling + bh
292
- block_y = mcu_row * comp.v_sampling + bv
293
- offset = (block_y * bx_count + block_x) * 64
294
-
295
- if ah == 0
296
- prev_dc[sc.id] = prog_dc_first(reader, dc_tab, prev_dc[sc.id], coeff_buf, offset, al)
297
- else
298
- prog_dc_refine(reader, coeff_buf, offset, al)
299
- end
300
- end
301
- end
302
- end
303
-
304
- mcu_count += 1
291
+ def reconstruct_strip(strip, dequant)
292
+ coeffs = strip.coefficients
293
+ columns = strip.block_columns
294
+ strip.component.v_sampling.times do |by|
295
+ columns.times do |bx|
296
+ offset = (by * columns + bx) * 64
297
+ Quantization.dequantize_zigzag!(coeffs, strip.quant_table, dequant, offset)
298
+ DCT.inverse!(dequant)
299
+ write_block(dequant, strip.samples, columns * 8, bx * 8, by * 8)
305
300
  end
306
301
  end
302
+ coeffs.fill(0)
307
303
  end
308
304
 
309
305
  def prog_dc_first(reader, dc_tab, prev_dc, coeff_buf, offset, al)
@@ -330,6 +326,7 @@ module PureJPEG
330
326
  if size == 0
331
327
  if run == 15
332
328
  k += 16
329
+ raise DecodeError, "AC run exceeds spectral band" if k > se + 1
333
330
  else
334
331
  # EOBn
335
332
  eobrun = (1 << run)
@@ -338,6 +335,7 @@ module PureJPEG
338
335
  end
339
336
  else
340
337
  k += run
338
+ raise DecodeError, "AC run exceeds spectral band" if k > se
341
339
  coeff_buf[offset + k] = reader.receive_extend(size) << al
342
340
  k += 1
343
341
  end
@@ -367,6 +365,7 @@ module PureJPEG
367
365
  # (the value bits come before refinement bits in the bitstream)
368
366
  new_value = nil
369
367
  if s != 0
368
+ raise DecodeError, "Invalid progressive AC refinement symbol" unless s == 1
370
369
  new_value = reader.receive_extend(s) << al
371
370
  elsif r != 15
372
371
  # EOBn: refine remaining nonzero coefficients in this block
@@ -393,7 +392,8 @@ module PureJPEG
393
392
  end
394
393
 
395
394
  # Place new coefficient at the target zero position
396
- if new_value && k <= se
395
+ raise DecodeError, "AC refinement run exceeds spectral band" if k > se
396
+ if new_value
397
397
  coeff_buf[offset + k] = new_value
398
398
  end
399
399
  k += 1
@@ -429,6 +429,7 @@ module PureJPEG
429
429
  end
430
430
  break
431
431
  elsif symbol == 0xF0 # ZRL (16 zeros)
432
+ raise DecodeError, "AC run exceeds block" if i + 16 > 64
432
433
  16.times do
433
434
  out[i] = 0
434
435
  i += 1
@@ -436,6 +437,8 @@ module PureJPEG
436
437
  else
437
438
  run = (symbol >> 4) & 0x0F
438
439
  size = symbol & 0x0F
440
+ raise DecodeError, "Invalid baseline AC symbol" if size == 0
441
+ raise DecodeError, "AC run exceeds block" if i + run >= 64
439
442
  run.times do
440
443
  out[i] = 0
441
444
  i += 1
@@ -464,42 +467,24 @@ module PureJPEG
464
467
  end
465
468
  end
466
469
 
467
- def resolve_scan_references!(scan_component, comp_info, dc_tables, ac_tables, require_ac: true)
468
- comp = comp_info[scan_component.id]
469
- raise DecodeError, "Scan references unknown component id #{scan_component.id}" unless comp
470
-
471
- dc_tab = dc_tables[scan_component.dc_table_id]
472
- raise DecodeError, "Component #{scan_component.id} references missing DC Huffman table #{scan_component.dc_table_id}" unless dc_tab
473
-
474
- if require_ac
475
- ac_tab = ac_tables[scan_component.ac_table_id]
476
- raise DecodeError, "Component #{scan_component.id} references missing AC Huffman table #{scan_component.ac_table_id}" unless ac_tab
477
- end
478
-
479
- [comp, dc_tab, ac_tab]
480
- end
481
-
482
470
  def fetch_quant_table!(jfif, comp)
483
- qt = jfif.quant_tables[comp.qt_id]
471
+ qt = jfif.component_quant_tables[comp.id]
484
472
  raise DecodeError, "Component #{comp.id} references missing quantization table #{comp.qt_id}" unless qt
485
473
 
486
474
  qt
487
475
  end
488
476
 
489
- def assemble_grayscale(width, height, channels, comp)
490
- ch = channels[comp.id]
491
- ch_data = ch[:data]
492
- ch_width = ch[:width]
493
- pixels = Array.new(width * height)
477
+ def assemble_grayscale(pixels, width, top, height, strip)
478
+ ch_data = strip.samples
479
+ ch_width = strip.block_columns * 8
494
480
  height.times do |y|
495
481
  src_row = y * ch_width
496
- dst_row = y * width
482
+ dst_row = (top + y) * width
497
483
  width.times do |x|
498
484
  v = ch_data[src_row + x]
499
485
  pixels[dst_row + x] = (v << 16) | (v << 8) | v
500
486
  end
501
487
  end
502
- Image.new(width, height, pixels, icc_profile: @icc_profile)
503
488
  end
504
489
 
505
490
  # Fixed-point coefficients (scaled by 2^16) for YCbCr→RGB.
@@ -509,37 +494,31 @@ module PureJPEG
509
494
  FP_B_CB = 116130 # 1.772 * 65536
510
495
  FP_HALF = 32768 # rounding bias
511
496
 
512
- def assemble_color(width, height, channels, components, max_h, max_v)
513
- # Upsample chroma channels if needed and convert YCbCr to RGB
514
- y_comp, cb_comp, cr_comp = resolve_color_components(components)
515
-
516
- y_ch = channels[y_comp.id]
517
- cb_ch = channels[cb_comp.id]
518
- cr_ch = channels[cr_comp.id]
519
-
520
- y_data = y_ch[:data]
521
- cb_data = cb_ch[:data]
522
- cr_data = cr_ch[:data]
523
- y_stride = y_ch[:width]
524
- cb_stride = cb_ch[:width]
525
- cr_stride = cr_ch[:width]
526
- cb_h = cb_comp.h_sampling
527
- cb_v = cb_comp.v_sampling
528
- cr_h = cr_comp.h_sampling
529
- cr_v = cr_comp.v_sampling
530
-
531
- pixels = Array.new(width * height)
497
+ def assemble_color(pixels, width, top, height, strips, max_h, max_v)
498
+ y_ch, cb_ch, cr_ch = strips
499
+ y_data = y_ch.samples
500
+ cb_data = cb_ch.samples
501
+ cr_data = cr_ch.samples
502
+ y_stride = y_ch.block_columns * 8
503
+ y_h = y_ch.component.h_sampling
504
+ y_v = y_ch.component.v_sampling
505
+ cb_stride = cb_ch.block_columns * 8
506
+ cr_stride = cr_ch.block_columns * 8
507
+ cb_h = cb_ch.component.h_sampling
508
+ cb_v = cb_ch.component.v_sampling
509
+ cr_h = cr_ch.component.h_sampling
510
+ cr_v = cr_ch.component.v_sampling
532
511
 
533
512
  height.times do |py|
534
- dst_row = py * width
535
- y_row = py * y_stride
513
+ dst_row = (top + py) * width
514
+ y_row = ((py * y_v) / max_v) * y_stride
536
515
 
537
516
  # Chroma coordinates (nearest-neighbor upsampling)
538
517
  cb_row = ((py * cb_v) / max_v) * cb_stride
539
518
  cr_row = ((py * cr_v) / max_v) * cr_stride
540
519
 
541
520
  width.times do |px|
542
- lum = y_data[y_row + px]
521
+ lum = y_data[y_row + (px * y_h) / max_h]
543
522
 
544
523
  cb_x = (px * cb_h) / max_h
545
524
  cr_x = (px * cr_h) / max_h
@@ -558,8 +537,6 @@ module PureJPEG
558
537
  pixels[dst_row + px] = (r << 16) | (g << 8) | b
559
538
  end
560
539
  end
561
-
562
- Image.new(width, height, pixels, icc_profile: @icc_profile)
563
540
  end
564
541
 
565
542
  def resolve_color_components(components)