1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 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
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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
#![deny(missing_docs)]

//! The PNG encoder that no one asked for.
//!
//! The abstraction is pretty leaky, but it's simple enough that you can make
//! cool things without much effort, such as this program, which creates a very
//! blank image.
//!
//! ```
//! use repng::Options;
//!
//! let mut png = Vec::new();
//!
//! {
//!     let mut encoder = Options::smallest(480, 360)
//!         .build(&mut png)
//!         .unwrap();
//!
//!     let row = [255; 480 * 4];
//!
//!     for y in 0..360 {
//!         encoder.write(&row).unwrap();
//!     }
//!
//!     encoder.finish().unwrap();
//! }
//!
//! println!("{:?}", png);
//! ```

extern crate byteorder;
extern crate flate2;

pub mod filter;
pub mod meta;
pub use options::{Compression, ColorFormat, Options};

mod compress;
mod options;

use byteorder::{ByteOrder, NetworkEndian, WriteBytesExt};
use compress::Compressor;
use filter::Filter;
use flate2::Crc;
use std::io::{self, Write};

/// Encode an RGBA image.
pub fn encode<W: Write>(sink: W, width: u32, height: u32, image: &[u8])
    -> io::Result<()>
{
    let mut encoder = Options::smallest(width, height).build(sink)?;
    encoder.write(&image)?;
    encoder.finish()?;
    Ok(())
}

/// The main object, which does all of the encoding work.
pub struct Encoder<W, F> {
    filter: F,
    sink: W,

    compress: Compressor,
    stride: usize,
    prior: Vec<u8>,
}

impl<W: Write, F> Encoder<W, F> {
    /// Finish encoding an image, writing any delayed data.
    pub fn finish(&mut self) -> io::Result<()> {
        let Self { ref mut compress, ref mut sink, .. } = *self;

        compress::Writer::new(
            compress,
            |bytes: &[u8]| Self::sinking_chunk(sink, b"IDAT", bytes),
        ).finish()?;

        Self::sinking_chunk(sink, b"IEND", &[])?;
        Ok(())
    }

    /// Write a chunk with the given type and data.
    pub fn chunk(&mut self, kind: &[u8; 4], data: &[u8]) -> io::Result<()> {
        Self::sinking_chunk(&mut self.sink, kind, data)
    }

    /// Get access to the writer that this was built with.
    ///
    /// Be careful, because you can easily corrupt the image with this method.
    pub fn writer(&mut self) -> &mut W { &mut self.sink }

    fn sinking_chunk(sink: &mut W, kind: &[u8; 4], data: &[u8])
        -> io::Result<()>
    {
        let mut crc = Crc::new();

        crc.update(kind);
        crc.update(data);

        sink.write_u32::<NetworkEndian>(data.len() as u32)?;
        sink.write_all(kind)?;
        sink.write_all(data)?;
        sink.write_u32::<NetworkEndian>(crc.sum())?;

        Ok(())
    }

    fn write_header(&mut self, opts: &Options) -> io::Result<()> {
        let mut ihdr = [0; 13];
        NetworkEndian::write_u32(&mut ihdr, opts.width);
        NetworkEndian::write_u32(&mut ihdr[4..], opts.height);
        ihdr[8]  = opts.depth;
        ihdr[9]  = opts.format as u8;
        ihdr[10] = 0; // Compression
        ihdr[11] = 0; // Filter
        ihdr[12] = 0; // Interlace
        self.chunk(b"IHDR", &ihdr)
    }
}

impl<W: Write, F: Filter> Encoder<W, F> {
    /// Make a new encoder, which writes to a given sink, with a custom filter.
    ///
    /// This method also immediately writes the PNG headers to the sink.
    pub fn new(opts: &Options, mut sink: W) -> io::Result<Self> {
        sink.write_all(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])?;

        let stride = opts.stride();

        let mut this = Self {
            compress: Compressor::new(opts),
            stride: stride,
            prior: vec![0; stride],

            filter: F::from(opts),
            sink: sink,
        };

        this.write_header(opts)?;
        Ok(this)
    }

    /// Feed zero or more rows to the encoder.
    ///
    /// Rows are specified in top-to-bottom and left-to-right order.
    ///
    /// # Panics
    ///
    /// This method panics if you try to write data that doesn't fit into a
    /// whole number of rows.
    pub fn write(&mut self, mut rows: &[u8]) -> io::Result<()> {
        assert!(rows.len() % self.stride == 0);

        let r = self.stride;
        let Self {
            ref mut sink,
            ref mut filter,
            ref mut compress,
            ref mut prior,
            ..
        } = *self;

        if rows.len() == 0 {
            return Ok(());
        }

        let mut writer = compress::Writer::new(
            compress,
            |bytes: &[u8]| Self::sinking_chunk(sink, b"IDAT", bytes),
        );

        filter.apply(&mut writer, &prior, &rows[..r])?;
        prior.copy_from_slice(&rows[rows.len() - r..]);

        while r < rows.len() {
            filter.apply(&mut writer, &rows[..r], &rows[r..2*r])?;
            rows = &rows[r..];
        }

        Ok(())
    }

    /// Reset the encoder to encode another image with the given options.
    ///
    /// There's a good chance that, before calling this method, you'll want to
    /// call `writer()` to get a mutable reference to the writer, and swap that
    /// out with a different writer. This method also writes the headers of the
    /// new image to the sink.
    ///
    /// # Warning
    ///
    /// This currently doesn't change the compression level!
    pub fn reset(&mut self, opts: &Options) -> io::Result<()> {
        self.compress.reset(opts);
        self.stride = opts.stride();
        self.prior.clear();
        self.prior.resize(self.stride, 0);
        self.filter.reset(opts);
        self.write_header(opts)?;
        Ok(())
    }
}