Update Go library to last weekly.
[platform/upstream/gcc.git] / libgo / go / image / png / writer.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package png
6
7 import (
8         "bufio"
9         "compress/zlib"
10         "hash/crc32"
11         "image"
12         "image/color"
13         "io"
14         "os"
15         "strconv"
16 )
17
18 type encoder struct {
19         w      io.Writer
20         m      image.Image
21         cb     int
22         err    os.Error
23         header [8]byte
24         footer [4]byte
25         tmp    [3 * 256]byte
26 }
27
28 // Big-endian.
29 func writeUint32(b []uint8, u uint32) {
30         b[0] = uint8(u >> 24)
31         b[1] = uint8(u >> 16)
32         b[2] = uint8(u >> 8)
33         b[3] = uint8(u >> 0)
34 }
35
36 type opaquer interface {
37         Opaque() bool
38 }
39
40 // Returns whether or not the image is fully opaque.
41 func opaque(m image.Image) bool {
42         if o, ok := m.(opaquer); ok {
43                 return o.Opaque()
44         }
45         b := m.Bounds()
46         for y := b.Min.Y; y < b.Max.Y; y++ {
47                 for x := b.Min.X; x < b.Max.X; x++ {
48                         _, _, _, a := m.At(x, y).RGBA()
49                         if a != 0xffff {
50                                 return false
51                         }
52                 }
53         }
54         return true
55 }
56
57 // The absolute value of a byte interpreted as a signed int8.
58 func abs8(d uint8) int {
59         if d < 128 {
60                 return int(d)
61         }
62         return 256 - int(d)
63 }
64
65 func (e *encoder) writeChunk(b []byte, name string) {
66         if e.err != nil {
67                 return
68         }
69         n := uint32(len(b))
70         if int(n) != len(b) {
71                 e.err = UnsupportedError(name + " chunk is too large: " + strconv.Itoa(len(b)))
72                 return
73         }
74         writeUint32(e.header[0:4], n)
75         e.header[4] = name[0]
76         e.header[5] = name[1]
77         e.header[6] = name[2]
78         e.header[7] = name[3]
79         crc := crc32.NewIEEE()
80         crc.Write(e.header[4:8])
81         crc.Write(b)
82         writeUint32(e.footer[0:4], crc.Sum32())
83
84         _, e.err = e.w.Write(e.header[0:8])
85         if e.err != nil {
86                 return
87         }
88         _, e.err = e.w.Write(b)
89         if e.err != nil {
90                 return
91         }
92         _, e.err = e.w.Write(e.footer[0:4])
93 }
94
95 func (e *encoder) writeIHDR() {
96         b := e.m.Bounds()
97         writeUint32(e.tmp[0:4], uint32(b.Dx()))
98         writeUint32(e.tmp[4:8], uint32(b.Dy()))
99         // Set bit depth and color type.
100         switch e.cb {
101         case cbG8:
102                 e.tmp[8] = 8
103                 e.tmp[9] = ctGrayscale
104         case cbTC8:
105                 e.tmp[8] = 8
106                 e.tmp[9] = ctTrueColor
107         case cbP8:
108                 e.tmp[8] = 8
109                 e.tmp[9] = ctPaletted
110         case cbTCA8:
111                 e.tmp[8] = 8
112                 e.tmp[9] = ctTrueColorAlpha
113         case cbG16:
114                 e.tmp[8] = 16
115                 e.tmp[9] = ctGrayscale
116         case cbTC16:
117                 e.tmp[8] = 16
118                 e.tmp[9] = ctTrueColor
119         case cbTCA16:
120                 e.tmp[8] = 16
121                 e.tmp[9] = ctTrueColorAlpha
122         }
123         e.tmp[10] = 0 // default compression method
124         e.tmp[11] = 0 // default filter method
125         e.tmp[12] = 0 // non-interlaced
126         e.writeChunk(e.tmp[0:13], "IHDR")
127 }
128
129 func (e *encoder) writePLTE(p color.Palette) {
130         if len(p) < 1 || len(p) > 256 {
131                 e.err = FormatError("bad palette length: " + strconv.Itoa(len(p)))
132                 return
133         }
134         for i, c := range p {
135                 r, g, b, _ := c.RGBA()
136                 e.tmp[3*i+0] = uint8(r >> 8)
137                 e.tmp[3*i+1] = uint8(g >> 8)
138                 e.tmp[3*i+2] = uint8(b >> 8)
139         }
140         e.writeChunk(e.tmp[0:3*len(p)], "PLTE")
141 }
142
143 func (e *encoder) maybeWritetRNS(p color.Palette) {
144         last := -1
145         for i, c := range p {
146                 _, _, _, a := c.RGBA()
147                 if a != 0xffff {
148                         last = i
149                 }
150                 e.tmp[i] = uint8(a >> 8)
151         }
152         if last == -1 {
153                 return
154         }
155         e.writeChunk(e.tmp[:last+1], "tRNS")
156 }
157
158 // An encoder is an io.Writer that satisfies writes by writing PNG IDAT chunks,
159 // including an 8-byte header and 4-byte CRC checksum per Write call. Such calls
160 // should be relatively infrequent, since writeIDATs uses a bufio.Writer.
161 //
162 // This method should only be called from writeIDATs (via writeImage).
163 // No other code should treat an encoder as an io.Writer.
164 func (e *encoder) Write(b []byte) (int, os.Error) {
165         e.writeChunk(b, "IDAT")
166         if e.err != nil {
167                 return 0, e.err
168         }
169         return len(b), nil
170 }
171
172 // Chooses the filter to use for encoding the current row, and applies it.
173 // The return value is the index of the filter and also of the row in cr that has had it applied.
174 func filter(cr *[nFilter][]byte, pr []byte, bpp int) int {
175         // We try all five filter types, and pick the one that minimizes the sum of absolute differences.
176         // This is the same heuristic that libpng uses, although the filters are attempted in order of
177         // estimated most likely to be minimal (ftUp, ftPaeth, ftNone, ftSub, ftAverage), rather than
178         // in their enumeration order (ftNone, ftSub, ftUp, ftAverage, ftPaeth).
179         cdat0 := cr[0][1:]
180         cdat1 := cr[1][1:]
181         cdat2 := cr[2][1:]
182         cdat3 := cr[3][1:]
183         cdat4 := cr[4][1:]
184         pdat := pr[1:]
185         n := len(cdat0)
186
187         // The up filter.
188         sum := 0
189         for i := 0; i < n; i++ {
190                 cdat2[i] = cdat0[i] - pdat[i]
191                 sum += abs8(cdat2[i])
192         }
193         best := sum
194         filter := ftUp
195
196         // The Paeth filter.
197         sum = 0
198         for i := 0; i < bpp; i++ {
199                 cdat4[i] = cdat0[i] - paeth(0, pdat[i], 0)
200                 sum += abs8(cdat4[i])
201         }
202         for i := bpp; i < n; i++ {
203                 cdat4[i] = cdat0[i] - paeth(cdat0[i-bpp], pdat[i], pdat[i-bpp])
204                 sum += abs8(cdat4[i])
205                 if sum >= best {
206                         break
207                 }
208         }
209         if sum < best {
210                 best = sum
211                 filter = ftPaeth
212         }
213
214         // The none filter.
215         sum = 0
216         for i := 0; i < n; i++ {
217                 sum += abs8(cdat0[i])
218                 if sum >= best {
219                         break
220                 }
221         }
222         if sum < best {
223                 best = sum
224                 filter = ftNone
225         }
226
227         // The sub filter.
228         sum = 0
229         for i := 0; i < bpp; i++ {
230                 cdat1[i] = cdat0[i]
231                 sum += abs8(cdat1[i])
232         }
233         for i := bpp; i < n; i++ {
234                 cdat1[i] = cdat0[i] - cdat0[i-bpp]
235                 sum += abs8(cdat1[i])
236                 if sum >= best {
237                         break
238                 }
239         }
240         if sum < best {
241                 best = sum
242                 filter = ftSub
243         }
244
245         // The average filter.
246         sum = 0
247         for i := 0; i < bpp; i++ {
248                 cdat3[i] = cdat0[i] - pdat[i]/2
249                 sum += abs8(cdat3[i])
250         }
251         for i := bpp; i < n; i++ {
252                 cdat3[i] = cdat0[i] - uint8((int(cdat0[i-bpp])+int(pdat[i]))/2)
253                 sum += abs8(cdat3[i])
254                 if sum >= best {
255                         break
256                 }
257         }
258         if sum < best {
259                 best = sum
260                 filter = ftAverage
261         }
262
263         return filter
264 }
265
266 func writeImage(w io.Writer, m image.Image, cb int) os.Error {
267         zw, err := zlib.NewWriter(w)
268         if err != nil {
269                 return err
270         }
271         defer zw.Close()
272
273         bpp := 0 // Bytes per pixel.
274
275         switch cb {
276         case cbG8:
277                 bpp = 1
278         case cbTC8:
279                 bpp = 3
280         case cbP8:
281                 bpp = 1
282         case cbTCA8:
283                 bpp = 4
284         case cbTC16:
285                 bpp = 6
286         case cbTCA16:
287                 bpp = 8
288         case cbG16:
289                 bpp = 2
290         }
291         // cr[*] and pr are the bytes for the current and previous row.
292         // cr[0] is unfiltered (or equivalently, filtered with the ftNone filter).
293         // cr[ft], for non-zero filter types ft, are buffers for transforming cr[0] under the
294         // other PNG filter types. These buffers are allocated once and re-used for each row.
295         // The +1 is for the per-row filter type, which is at cr[*][0].
296         b := m.Bounds()
297         var cr [nFilter][]uint8
298         for i := range cr {
299                 cr[i] = make([]uint8, 1+bpp*b.Dx())
300                 cr[i][0] = uint8(i)
301         }
302         pr := make([]uint8, 1+bpp*b.Dx())
303
304         for y := b.Min.Y; y < b.Max.Y; y++ {
305                 // Convert from colors to bytes.
306                 i := 1
307                 switch cb {
308                 case cbG8:
309                         for x := b.Min.X; x < b.Max.X; x++ {
310                                 c := color.GrayModel.Convert(m.At(x, y)).(color.Gray)
311                                 cr[0][i] = c.Y
312                                 i++
313                         }
314                 case cbTC8:
315                         // We have previously verified that the alpha value is fully opaque.
316                         cr0 := cr[0]
317                         if rgba, _ := m.(*image.RGBA); rgba != nil {
318                                 j0 := (y - b.Min.Y) * rgba.Stride
319                                 j1 := j0 + b.Dx()*4
320                                 for j := j0; j < j1; j += 4 {
321                                         cr0[i+0] = rgba.Pix[j+0]
322                                         cr0[i+1] = rgba.Pix[j+1]
323                                         cr0[i+2] = rgba.Pix[j+2]
324                                         i += 3
325                                 }
326                         } else {
327                                 for x := b.Min.X; x < b.Max.X; x++ {
328                                         r, g, b, _ := m.At(x, y).RGBA()
329                                         cr0[i+0] = uint8(r >> 8)
330                                         cr0[i+1] = uint8(g >> 8)
331                                         cr0[i+2] = uint8(b >> 8)
332                                         i += 3
333                                 }
334                         }
335                 case cbP8:
336                         if p, _ := m.(*image.Paletted); p != nil {
337                                 offset := (y - b.Min.Y) * p.Stride
338                                 copy(cr[0][1:], p.Pix[offset:offset+b.Dx()])
339                         } else {
340                                 pi := m.(image.PalettedImage)
341                                 for x := b.Min.X; x < b.Max.X; x++ {
342                                         cr[0][i] = pi.ColorIndexAt(x, y)
343                                         i += 1
344                                 }
345                         }
346                 case cbTCA8:
347                         // Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied.
348                         for x := b.Min.X; x < b.Max.X; x++ {
349                                 c := color.NRGBAModel.Convert(m.At(x, y)).(color.NRGBA)
350                                 cr[0][i+0] = c.R
351                                 cr[0][i+1] = c.G
352                                 cr[0][i+2] = c.B
353                                 cr[0][i+3] = c.A
354                                 i += 4
355                         }
356                 case cbG16:
357                         for x := b.Min.X; x < b.Max.X; x++ {
358                                 c := color.Gray16Model.Convert(m.At(x, y)).(color.Gray16)
359                                 cr[0][i+0] = uint8(c.Y >> 8)
360                                 cr[0][i+1] = uint8(c.Y)
361                                 i += 2
362                         }
363                 case cbTC16:
364                         // We have previously verified that the alpha value is fully opaque.
365                         for x := b.Min.X; x < b.Max.X; x++ {
366                                 r, g, b, _ := m.At(x, y).RGBA()
367                                 cr[0][i+0] = uint8(r >> 8)
368                                 cr[0][i+1] = uint8(r)
369                                 cr[0][i+2] = uint8(g >> 8)
370                                 cr[0][i+3] = uint8(g)
371                                 cr[0][i+4] = uint8(b >> 8)
372                                 cr[0][i+5] = uint8(b)
373                                 i += 6
374                         }
375                 case cbTCA16:
376                         // Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied.
377                         for x := b.Min.X; x < b.Max.X; x++ {
378                                 c := color.NRGBA64Model.Convert(m.At(x, y)).(color.NRGBA64)
379                                 cr[0][i+0] = uint8(c.R >> 8)
380                                 cr[0][i+1] = uint8(c.R)
381                                 cr[0][i+2] = uint8(c.G >> 8)
382                                 cr[0][i+3] = uint8(c.G)
383                                 cr[0][i+4] = uint8(c.B >> 8)
384                                 cr[0][i+5] = uint8(c.B)
385                                 cr[0][i+6] = uint8(c.A >> 8)
386                                 cr[0][i+7] = uint8(c.A)
387                                 i += 8
388                         }
389                 }
390
391                 // Apply the filter.
392                 f := filter(&cr, pr, bpp)
393
394                 // Write the compressed bytes.
395                 _, err = zw.Write(cr[f])
396                 if err != nil {
397                         return err
398                 }
399
400                 // The current row for y is the previous row for y+1.
401                 pr, cr[0] = cr[0], pr
402         }
403         return nil
404 }
405
406 // Write the actual image data to one or more IDAT chunks.
407 func (e *encoder) writeIDATs() {
408         if e.err != nil {
409                 return
410         }
411         var bw *bufio.Writer
412         bw, e.err = bufio.NewWriterSize(e, 1<<15)
413         if e.err != nil {
414                 return
415         }
416         e.err = writeImage(bw, e.m, e.cb)
417         if e.err != nil {
418                 return
419         }
420         e.err = bw.Flush()
421 }
422
423 func (e *encoder) writeIEND() { e.writeChunk(e.tmp[0:0], "IEND") }
424
425 // Encode writes the Image m to w in PNG format. Any Image may be encoded, but
426 // images that are not image.NRGBA might be encoded lossily.
427 func Encode(w io.Writer, m image.Image) os.Error {
428         // Obviously, negative widths and heights are invalid. Furthermore, the PNG
429         // spec section 11.2.2 says that zero is invalid. Excessively large images are
430         // also rejected.
431         mw, mh := int64(m.Bounds().Dx()), int64(m.Bounds().Dy())
432         if mw <= 0 || mh <= 0 || mw >= 1<<32 || mh >= 1<<32 {
433                 return FormatError("invalid image size: " + strconv.Itoa64(mw) + "x" + strconv.Itoa64(mw))
434         }
435
436         var e encoder
437         e.w = w
438         e.m = m
439
440         var pal color.Palette
441         // cbP8 encoding needs PalettedImage's ColorIndexAt method.
442         if _, ok := m.(image.PalettedImage); ok {
443                 pal, _ = m.ColorModel().(color.Palette)
444         }
445         if pal != nil {
446                 e.cb = cbP8
447         } else {
448                 switch m.ColorModel() {
449                 case color.GrayModel:
450                         e.cb = cbG8
451                 case color.Gray16Model:
452                         e.cb = cbG16
453                 case color.RGBAModel, color.NRGBAModel, color.AlphaModel:
454                         if opaque(m) {
455                                 e.cb = cbTC8
456                         } else {
457                                 e.cb = cbTCA8
458                         }
459                 default:
460                         if opaque(m) {
461                                 e.cb = cbTC16
462                         } else {
463                                 e.cb = cbTCA16
464                         }
465                 }
466         }
467
468         _, e.err = io.WriteString(w, pngHeader)
469         e.writeIHDR()
470         if pal != nil {
471                 e.writePLTE(pal)
472                 e.maybeWritetRNS(pal)
473         }
474         e.writeIDATs()
475         e.writeIEND()
476         return e.err
477 }