Class: ZPNG::ScanLine

Inherits:
Object
  • Object
show all
Defined in:
lib/zpng/scan_line.rb,
lib/zpng/scan_line/mixins.rb

Defined Under Namespace

Modules: Mixins

Constant Summary collapse

FILTER_NONE =
0
FILTER_SUB =
1
FILTER_UP =
2
FILTER_AVERAGE =
3
FILTER_PAETH =
4
VALID_FILTERS =
FILTER_NONE..FILTER_PAETH

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(image, idx, params = {}) ⇒ ScanLine

Returns a new instance of ScanLine.



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
# File 'lib/zpng/scan_line.rb', line 18

def initialize image, idx, params={}
  @image,@idx = image,idx
  @bpp = image.hdr.bpp
  raise "[!] zero bpp" if @bpp == 0

  # Bytes Per Pixel, if bpp = 8, 16, 24, 32
  # NULL otherwise
  @BPP = (@bpp%8 == 0) && (@bpp>>3)

  if @image.new?
    @size = params[:size]
    @decoded_bytes = params[:decoded_bytes] || "\x00" * (size-1)
    @filter = FILTER_NONE
    @offset = params[:offset] || idx*size
  else
    @offset =
      if image.interlaced?
        image.adam7.scanline_offset(idx)
      else
        idx*size
      end
    if @filter = image.imagedata[@offset]
      @filter = @filter.ord
    elsif @image.verbose >= -1
      STDERR.puts "[!] #{self.class}: ##@idx: no data at pos 0, scanline dropped".red
    end
  end
  @errors = Set.new
end

Instance Attribute Details

#bppObject

Returns the value of attribute bpp.



15
16
17
# File 'lib/zpng/scan_line.rb', line 15

def bpp
  @bpp
end

#decoded_bytesObject



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
# File 'lib/zpng/scan_line.rb', line 276

def decoded_bytes
  @decoded_bytes ||=
    begin
      raw = @image.imagedata[@offset+1, size-1]
      if raw.size < size-1
        # handle broken images when data ends in the middle of scanline
        raw += "\x00" * (size-1-raw.size)
      end
      # TODO: check if converting raw to array would give any speedup

      # number of bytes per complete pixel, rounding up to one
      bpp1 = (@bpp/8.0).ceil

      case @filter

      when FILTER_NONE    # 0
        s = raw

      when FILTER_SUB     # 1
        s = "\x00" * (size-1)
        s[0,bpp1] = raw[0,bpp1] # TODO: optimize
        bpp1.upto(size-2) do |i|
          s.setbyte(i, raw.getbyte(i) + s.getbyte(i-bpp1))
        end

      when FILTER_UP      # 2
        s = "\x00" * (size-1)
        0.upto(size-2) do |i|
          s.setbyte(i, raw.getbyte(i) + prev_scanline_byte(i))
        end

      when FILTER_AVERAGE # 3
        s = "\x00" * (size-1)
        0.upto(bpp1-1) do |i|
          s.setbyte(i, raw.getbyte(i) + prev_scanline_byte(i)/2)
        end
        bpp1.upto(size-2) do |i|
          s.setbyte(i, raw.getbyte(i) + (s.getbyte(i-bpp1) + prev_scanline_byte(i))/2)
        end

      when FILTER_PAETH   # 4
        s = "\x00" * (size-1)
        0.upto(bpp1-1) do |i|
          s.setbyte(i, raw.getbyte(i) + prev_scanline_byte(i))
        end
        bpp1.upto(size-2) do |i|
          s.setbyte(i,
            raw.getbyte(i) +
            paeth_predictor(s.getbyte(i-bpp1), prev_scanline_byte(i), prev_scanline_byte(i-bpp1))
          )
        end

      else
        STDERR.puts "[!] #{self.class}: ##@idx: invalid filter #@filter, assuming FILTER_NONE".red
        s = raw
      end

      s
    end
end

#filterObject

Returns the value of attribute filter.



15
16
17
# File 'lib/zpng/scan_line.rb', line 15

def filter
  @filter
end

#idxObject

Returns the value of attribute idx.



15
16
17
# File 'lib/zpng/scan_line.rb', line 15

def idx
  @idx
end

#imageObject

Returns the value of attribute image.



15
16
17
# File 'lib/zpng/scan_line.rb', line 15

def image
  @image
end

#offsetObject

Returns the value of attribute offset.



15
16
17
# File 'lib/zpng/scan_line.rb', line 15

def offset
  @offset
end

Instance Method Details

#[](x) ⇒ Object



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
# File 'lib/zpng/scan_line.rb', line 171

def [] x
  raw =
    if @BPP
      # 8, 16, 24, 32, 48 bits per pixel
      decoded_bytes[x*@BPP, @BPP]
    else
      # 1, 2 or 4 bits per pixel
      decoded_bytes[x*@bpp/8]
    end

  case image.hdr.color
  when COLOR_INDEXED                # ALLOWED_DEPTHS: 1, 2, 4, 8
    mask  = 2**@bpp-1
    shift = 8-(x%(8/@bpp)+1)*@bpp
    raise "invalid shift #{shift}" if shift < 0 || shift > 7
    idx = (raw.ord >> shift) & mask
    color = image.palette[idx]
    unless color
      if !@errors.include?(x) && @image.verbose >= -1
        # prevent same error popping up multiple times, f.ex. in zsteg analysis
        @errors << x
        if (32..127).include?(idx)
          msg = '[!] %s: color #%-3d ("%c") at x=%d y=%d is out of palette!'.red % [self.class, idx, idx, x, @idx]
        else
          msg = "[!] %s: color #%-3d at x=%d y=%d is out of palette!".red % [self.class, idx, x, @idx]
        end
        STDERR.puts msg
      end
      color = Color.new(0,0,0)
    end
    if image.trns
      # transparency from tRNS chunk
      # For color type 3 (indexed color), the tRNS chunk contains a series of one-byte alpha values,
      # corresponding to entries in the PLTE chunk:
      #
      #   Alpha for palette index 0:  1 byte
      #   Alpha for palette index 1:  1 byte
      #   ...
      #
      if color.alpha = image.trns.data[idx]
        # if it's not NULL - convert it from char to int,
        # otherwise it means fully opaque color, as well as NULL alpha in ZPNG::Color
        color = color.dup
        color.alpha = color.alpha.ord
      end
    end
    return color

  when COLOR_GRAYSCALE              # ALLOWED_DEPTHS: 1, 2, 4, 8, 16
    c = if @bpp == 16
          raw.unpack('n')[0]
        else
          mask  = 2**@bpp-1
          shift = 8-(x%(8/@bpp)+1)*@bpp
          raise "invalid shift #{shift}" if shift < 0 || shift > 7
          (raw.ord >> shift) & mask
        end

    color = Color.from_grayscale(c, :depth => @bpp) # only in this color mode depth == bpp
    color.alpha = image._alpha_color(color)
    return color

  when COLOR_RGB                    # ALLOWED_DEPTHS: 8, 16
    color =
      case @bpp
      when 24                     # RGB  8 bits per sample = 24bpp
        if image.trns
          extend Mixins::RGB24_TRNS
        else
          extend Mixins::RGB24
        end
        return self[x]
      when 48                     # RGB 16 bits per sample = 48bpp
        Color.new(*raw.unpack('n3'), :depth => 16)
      else raise "COLOR_RGB unexpected bpp #@bpp"
      end

    color.alpha = image._alpha_color(color)
    return color

  when COLOR_GRAY_ALPHA             # ALLOWED_DEPTHS: 8, 16
    case @bpp
    when 16                         #  8-bit grayscale +  8-bit alpha
      return Color.from_grayscale(*raw.unpack('C2'))
    when 32                         # 16-bit grayscale + 16-bit alpha
      return Color.from_grayscale(*raw.unpack('n2'), :depth => 16)
    else raise "COLOR_GRAY_ALPHA unexpected bpp #@bpp"
    end

  when COLOR_RGBA                   # ALLOWED_DEPTHS: 8, 16
    case @bpp
    when 32                         # RGBA  8-bit/sample
      extend Mixins::RGBA32
      return self[x]
    when 64                         # RGBA 16-bit/sample
      return Color.new(*raw.unpack('n4'), :depth => 16 )
    else raise "COLOR_RGBA unexpected bpp #@bpp"
    end

  else
    raise "unexpected color mode #{image.hdr.color}"

  end # case img.hdr.color
end

#[]=(x, color) ⇒ Object



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
# File 'lib/zpng/scan_line.rb', line 94

def []= x, color
  case image.hdr.color
  when COLOR_INDEXED                # ALLOWED_DEPTHS: 1, 2, 4, 8
    color_idx = image.palette.find_or_add(color)
    raise "no color #{color.inspect} in palette" unless color_idx

    mask  = 2**@bpp-1
    shift = 8-(x%(8/@bpp)+1)*@bpp
    raise "invalid shift #{shift}" if shift < 0 || shift > 7

    pos = x*@bpp/8
    b = decoded_bytes.getbyte(pos)
    b = (b & (0xff-(mask<<shift))) | ((color_idx & mask) << shift)
    decoded_bytes.setbyte(pos, b)
    # TODO: transparency in TRNS

  when COLOR_GRAYSCALE              # ALLOWED_DEPTHS: 1, 2, 4, 8, 16
    raw = color.to_depth(@bpp).to_grayscale
    pos = x*@bpp/8
    if @bpp == 16
      decoded_bytes[pos,2] = [raw].pack('n')
    else
      mask  = 2**@bpp-1
      shift = 8-(x%(8/@bpp)+1)*@bpp
      raise "invalid shift #{shift}" if shift < 0 || shift > 7
      b = decoded_bytes[pos].ord
      b = (b & (0xff-(mask<<shift))) | ((raw & mask) << shift)
      decoded_bytes[pos] = b.chr
    end
    # TODO: transparency in TRNS

  when COLOR_RGB                    # ALLOWED_DEPTHS: 8, 16
    case @bpp
    when 24; decoded_bytes[x*3,3] = color.to_depth(8).to_a.pack('C3')
    when 48; decoded_bytes[x*6,6] = color.to_depth(16).to_a.pack('n3')
    else raise "unexpected bpp #@bpp"
    end
    # TODO: transparency in TRNS

  when COLOR_GRAY_ALPHA             # ALLOWED_DEPTHS: 8, 16
    case @bpp
    when 16; decoded_bytes[x*2,2] = color.to_depth(8).to_gray_alpha.pack('C2')
    when 32; decoded_bytes[x*4,4] = color.to_depth(16).to_gray_alpha.pack('n2')
    else raise "unexpected bpp #@bpp"
    end

  when COLOR_RGBA                   # ALLOWED_DEPTHS: 8, 16
    case @bpp
    when 32; decoded_bytes[x*4,4] = color.to_depth(8).to_a.pack('C4')
    when 64; decoded_bytes[x*8,8] = color.to_depth(16).to_a.pack('n4')
    else raise "unexpected bpp #@bpp"
    end

  else
    raise "unexpected color mode #{image.hdr.color}"

  end # case image.hdr.color
end

#bad?Boolean

ScanLine is BAD if it has no filter

Returns:

  • (Boolean)


49
50
51
# File 'lib/zpng/scan_line.rb', line 49

def bad?
  !@filter
end

#crop!(x, w) ⇒ Object



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
# File 'lib/zpng/scan_line.rb', line 389

def crop! x, w
  @size = nil # unmemoize self size b/c it's changed after crop
  if @BPP
    # great, crop is byte-aligned! :)
    decoded_bytes[0,x*@BPP]   = ''
    decoded_bytes[w*@BPP..-1] = ''
  else
    # oh, no we have to shift bits in a whole line :(
    case @bpp
    when 1,2,4
      cut_bits_head = @bpp*x
      if cut_bits_head > 8
        # cut whole head bytes
        decoded_bytes[0,cut_bits_head/8] = ''
      end
      cut_bits_head %= 8
      if cut_bits_head > 0
        # bit-shift all remaining bytes
        (w*@bpp/8.0).ceil.times do |i|
          decoded_bytes[i] = ((
            (decoded_bytes[i].ord<<cut_bits_head) |
            (decoded_bytes[i+1].ord>>(8-cut_bits_head))
          ) & 0xff).chr
        end
      end

      new_width_bits = w*@bpp
      diff = decoded_bytes.size*8 - new_width_bits
      raise if diff < 0
      if diff > 8
        # cut whole tail bytes
        decoded_bytes[(new_width_bits/8.0).ceil..-1] = ''
      end
      diff %= 8
      if diff > 0
        # zero tail bits of last byte
        decoded_bytes[-1] = (decoded_bytes[-1].ord & (0xff-(2**diff)+1)).chr
      end

    else
      raise "unexpected bpp=#@bpp"
    end
  end
end

#decode!Object



337
338
339
340
# File 'lib/zpng/scan_line.rb', line 337

def decode!
  decoded_bytes
  true
end

#each_pixelObject



445
446
447
448
449
# File 'lib/zpng/scan_line.rb', line 445

def each_pixel
  width.times do |i|
    yield self[i], i
  end
end

#exportObject



434
435
436
437
438
439
440
441
442
443
# File 'lib/zpng/scan_line.rb', line 434

def export
  # we export in FILTER_NONE mode
  # [] is for preventing spare tail bytes that can break scanlines sequence
  if @decoded_bytes
    FILTER_NONE.chr + decoded_bytes[0,size-1]
  else
    # scanline was never decoded => export it as-is to save memory & CPU
    @image.imagedata[@offset, size]
  end
end

#get_raw(x) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/zpng/scan_line.rb', line 153

def get_raw x
  return nil if @bpp > 8 || image.hdr.color != COLOR_INDEXED

  raw =
    if @BPP
      # 8, 16, 24, 32, 48 bits per pixel
      decoded_bytes[x*@BPP, @BPP]
    else
      # 1, 2 or 4 bits per pixel
      decoded_bytes[x*@bpp/8]
    end

  mask  = 2**@bpp-1
  shift = 8-(x%(8/@bpp)+1)*@bpp
  raise "invalid shift #{shift}" if shift < 0 || shift > 7
  idx = (raw.ord >> shift) & mask
end

#inspectObject



78
79
80
81
82
83
84
85
86
# File 'lib/zpng/scan_line.rb', line 78

def inspect
  if image.interlaced?
    "#<ZPNG::ScanLine idx=%-2d offset=%-3d width=%-2d size=%-2d bpp=%d filter=%d>" %
      [idx, offset, width, size, bpp, filter]
  else
    "#<ZPNG::ScanLine idx=%-2d offset=%-3d size=%-2d bpp=%d filter=%d>" %
      [idx, offset, size, bpp, filter]
  end
end

#pixelsObject



451
452
453
# File 'lib/zpng/scan_line.rb', line 451

def pixels
  Pixels.new(self)
end

#raw_dataObject



342
343
344
# File 'lib/zpng/scan_line.rb', line 342

def raw_data
  @offset ? @image.imagedata[@offset, size] : ''
end

#raw_data=(data) ⇒ Object



346
347
348
349
350
351
352
# File 'lib/zpng/scan_line.rb', line 346

def raw_data= data
  if data.size == size
    @image.imagedata[@offset, size] = data
  else
    raise Exception, "raw data size must be #{size}, got #{data.size}"
  end
end

#raw_set(offset, value) ⇒ Object

set raw byte data at specified offset modifies @image, resets @decoded_bytes



356
357
358
359
360
361
362
363
# File 'lib/zpng/scan_line.rb', line 356

def raw_set offset, value
  @decoded_bytes = nil
  value = value.ord if value.is_a?(String)
  if offset == 0
    @filter = value # XXX possible bugs with Singleton Modules
  end
  @image.imagedata.setbyte(@offset+offset, value)
end

#sizeObject

total scanline size in bytes, INCLUDING leading ‘filter’ byte



58
59
60
61
62
63
64
65
66
67
# File 'lib/zpng/scan_line.rb', line 58

def size
  @size ||=
    begin
      if @BPP
        width*@BPP+1
      else
        (width*@bpp/8.0+1).ceil
      end
    end
end

#to_ascii(*args) ⇒ Object



88
89
90
91
92
# File 'lib/zpng/scan_line.rb', line 88

def to_ascii *args
  @image.width.times.map do |i|
    self[i].to_ascii(*args)
  end.join
end

#valid_filter?Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/zpng/scan_line.rb', line 53

def valid_filter?
  VALID_FILTERS.include?(@filter)
end

#widthObject

scanline width in pixels



70
71
72
73
74
75
76
# File 'lib/zpng/scan_line.rb', line 70

def width
  if image.interlaced?
    image.adam7.scanline_width(idx)
  else
    image.width
  end
end