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
use byteorder::{WriteBytesExt, LE};
use ico::IconDir;
use riff::{ChunkContents, ChunkId, LIST_ID, RIFF_ID};
use std::io::{Seek, Write};
use thiserror::Error;

pub use ico;

#[derive(Error, Debug)]
pub enum Error {
    #[error("I/O error or system error")]
    Io(#[from] std::io::Error),
}

pub type Result<T> = std::result::Result<T, Error>;

pub struct Ani {
    pub header: AniHeader,
    pub frames: Vec<IconDir>,
}

pub struct AniHeader {
    /// The number of stored frames in this animation.
    pub num_frames: u32,
    /// The number of steps in this animation. Since the `seq` chunk is not implemented, it should
    /// be equal to `num_frames`.
    pub num_steps: u32,
    /// The width.
    pub width: u32,
    /// The height.
    pub height: u32,
    /// The number of jiffies (1/60 sec) that each frame displays.
    pub frame_rate: u32,
}

impl Ani {
    pub fn encode<T: Seek + Write>(&self, mut writer: T) -> Result<u64> {
        const fn chunk_id(value: &[u8; 4]) -> ChunkId {
            ChunkId { value: *value }
        }

        let contents = ChunkContents::Children(
            RIFF_ID.clone(),
            chunk_id(b"ACON"),
            vec![
                ChunkContents::Data(chunk_id(b"anih"), self.encode_header()?),
                ChunkContents::Children(LIST_ID.clone(), chunk_id(b"fram"), {
                    let mut chunks = Vec::new();
                    for cur in &self.frames {
                        let mut data = Vec::new();
                        cur.write(&mut data)?;
                        chunks.push(ChunkContents::Data(chunk_id(b"icon"), data));
                    }
                    chunks
                }),
            ],
        );

        contents.write(&mut writer).map_err(From::from)
    }

    fn encode_header(&self) -> Result<Vec<u8>> {
        // 4 (header size) + 32 (the rest)
        let mut data = Vec::with_capacity(36);

        data.write_u32::<LE>(36)?; // Header size

        data.write_u32::<LE>(self.header.num_frames)?;
        data.write_u32::<LE>(self.header.num_steps)?;
        data.write_u32::<LE>(self.header.width)?;
        data.write_u32::<LE>(self.header.height)?;
        data.write_u32::<LE>(32)?; // Color depth
        data.write_u32::<LE>(1)?; // Number of planes
        data.write_u32::<LE>(self.header.frame_rate)?;
        data.write_u32::<LE>(0b01)?; // Flags

        Ok(data)
    }
}