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
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
//! Metadata for PNG images.

use std::io::BufRead;
use std::fmt;

use byteorder::{ReadBytesExt, BigEndian};

use types::{Result, Dimensions};
use traits::LoadableMetadata;

/// Color type used in an image.
///
/// These color types directly corresponds to those defined in PNG spec.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum ColorType {
    Grayscale,
    Rgb,
    Indexed,
    GrayscaleAlpha,
    RgbAlpha
}

impl fmt::Display for ColorType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match *self {
            ColorType::Grayscale => "Grayscale",
            ColorType::Rgb => "RGB",
            ColorType::Indexed => "Indexed",
            ColorType::GrayscaleAlpha => "Grayscale with alpha channel",
            ColorType::RgbAlpha => "RGB with alpha channel",
        })
    }
}

const CT_GRAYSCALE: u8 = 0;
const CT_RGB: u8 = 2;
const CT_INDEXED: u8 = 3;
const CT_GRAYSCALE_ALPHA: u8 = 4;
const CT_RGB_ALPHA: u8 = 6;

impl ColorType {
    fn from_u8(n: u8) -> Option<ColorType> {
        match n {
            CT_GRAYSCALE       => Some(ColorType::Grayscale),
            CT_RGB             => Some(ColorType::Rgb),
            CT_INDEXED         => Some(ColorType::Indexed),
            CT_GRAYSCALE_ALPHA => Some(ColorType::GrayscaleAlpha),
            CT_RGB_ALPHA       => Some(ColorType::RgbAlpha),
            _                  => None
        }
    }
}

fn compute_color_depth(bit_depth: u8, color_type: u8) -> Option<u8> {
    match color_type {
        CT_INDEXED => match bit_depth {
            1 | 2 | 4 | 8 => Some(bit_depth),
            _ => None
        },
        CT_GRAYSCALE => match bit_depth {
            1 | 2 | 4 | 8 | 16 => Some(bit_depth),
            _ => None,
        },
        CT_GRAYSCALE_ALPHA => match bit_depth {
            8 | 16 => Some(bit_depth*2),
            _ => None
        },
        CT_RGB => match bit_depth {
            8 | 16 => Some(bit_depth*3),
            _ => None
        },
        CT_RGB_ALPHA => match bit_depth {
            8 | 16 => Some(bit_depth*4),
            _ => None
        },
        _ => None
    }
}

/// Compression method used in an image.
///
/// PNG spec currently defines only one compression method:
///
/// > At present, only compression method 0 (deflate/inflate compression with a sliding window of
/// at most 32768 bytes) is defined.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum CompressionMethod {
    DeflateInflate
}

impl fmt::Display for CompressionMethod {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match *self {
            CompressionMethod::DeflateInflate => "Deflate/inflate",
        })
    }
}

impl CompressionMethod {
    fn from_u8(n: u8) -> Option<CompressionMethod> {
        match n {
            0 => Some(CompressionMethod::DeflateInflate),
            _ => None
        }
    }
}

/// Filtering method used in an image.
///
/// PNG spec currently defines only one filter method:
///
/// > At present, only filter method 0 (adaptive filtering with five basic filter types) is
/// defined.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum FilterMethod {
    AdaptiveFiltering
}

impl fmt::Display for FilterMethod {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match *self {
            FilterMethod::AdaptiveFiltering => "Adaptive filtering",
        })
    }
}

impl FilterMethod {
    fn from_u8(n: u8) -> Option<FilterMethod> {
        match n {
            0 => Some(FilterMethod::AdaptiveFiltering),
            _ => None
        }
    }
}

/// Interlace method used in an image.
///
/// PNG spec says that interlacing can be disabled or Adam7 interlace method can be used.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum InterlaceMethod {
    Disabled,
    Adam7
}

impl fmt::Display for InterlaceMethod {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match *self {
            InterlaceMethod::Disabled => "Disabled",
            InterlaceMethod::Adam7 => "Adam7",
        })
    }
}

impl InterlaceMethod {
    fn from_u8(n: u8) -> Option<InterlaceMethod> {
        match n {
            0 => Some(InterlaceMethod::Disabled),
            1 => Some(InterlaceMethod::Adam7),
            _ => None
        }
    }
}

/// Represents metadata of a PNG image.
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct Metadata {
    /// Width and height.
    pub dimensions: Dimensions,
    /// Color type used in the image.
    pub color_type: ColorType,
    /// Color depth (bits per pixel) used in the image.
    pub color_depth: u8,
    /// Compression method used in the image.
    pub compression_method: CompressionMethod,
    /// Preprocessing method used in the image.
    pub filter_method: FilterMethod,
    /// Transmission order used in the image.
    pub interlace_method: InterlaceMethod
}

impl LoadableMetadata for Metadata {
    fn load<R: ?Sized + BufRead>(r: &mut R) -> Result<Metadata> {
        let mut signature = [0u8; 8];
        try!(r.read_exact(&mut signature).map_err(if_eof!(std, "when reading PNG signature")));

        if &signature != b"\x89PNG\r\n\x1a\n" {
            return Err(invalid_format!("invalid PNG header: {:?}", signature));
        }

        // chunk length
        let _ = try!(r.read_u32::<BigEndian>().map_err(if_eof!("when reading chunk length")));
        
        let mut chunk_type = [0u8; 4];
        try!(r.read_exact(&mut chunk_type).map_err(if_eof!(std, "when reading chunk type")));

        if &chunk_type != b"IHDR" {
            return Err(invalid_format!("invalid PNG chunk: {:?}", chunk_type));
        }

        let width = try!(r.read_u32::<BigEndian>().map_err(if_eof!("when reading width")));
        let height = try!(r.read_u32::<BigEndian>().map_err(if_eof!("when reading height")));
        let bit_depth = try!(r.read_u8().map_err(if_eof!("when reading bit depth")));
        let color_type = try!(r.read_u8().map_err(if_eof!("when reading color type")));
        let compression_method = try!(r.read_u8().map_err(if_eof!("when reading compression method")));
        let filter_method = try!(r.read_u8().map_err(if_eof!("when reading filter method")));
        let interlace_method = try!(r.read_u8().map_err(if_eof!("when reading interlace method")));

        Ok(Metadata {
            dimensions: (width, height).into(),
            color_type: try!(
                ColorType::from_u8(color_type)
                    .ok_or(invalid_format!("invalid color type: {}", color_type))
            ),
            color_depth: try!(
                compute_color_depth(bit_depth, color_type)
                    .ok_or(invalid_format!("invalid bit depth: {}", bit_depth))
            ),
            compression_method: try!(
                CompressionMethod::from_u8(compression_method)
                    .ok_or(invalid_format!("invalid compression method: {}", compression_method))
            ),
            filter_method: try!(
                FilterMethod::from_u8(filter_method)
                    .ok_or(invalid_format!("invalid filter method: {}", filter_method))
            ),
            interlace_method: try!(
                InterlaceMethod::from_u8(interlace_method)
                    .ok_or(invalid_format!("invalid interlace method: {}", interlace_method))
            )
        })
    }
}