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
use bitstream_io::{BitWrite, BitWriter, LittleEndian};
use enum_dispatch::enum_dispatch;
use std::io::{BufWriter, Read, Result};

use crate::MediaPrimitive;

#[enum_dispatch]
pub enum UnveilAlgorithms {
    OneBitUnveil,
}

/// generic unveil algorithm
#[enum_dispatch(UnveilAlgorithms)]
pub trait UnveilAlgorithm {
    fn decode(&self, carrier: MediaPrimitive) -> bool;
}

/// generic stegano decoder
pub struct Decoder<I, A>
where
    I: Iterator<Item = MediaPrimitive>,
    A: UnveilAlgorithm,
{
    pub input: I,
    pub algorithm: A,
}

/// generic stegano decoder constructor method
impl<I, A> Decoder<I, A>
where
    I: Iterator<Item = MediaPrimitive>,
    A: UnveilAlgorithm,
{
    pub fn new(input: I, algorithm: A) -> Self {
        Decoder { input, algorithm }
    }
}

impl<I, A> Read for Decoder<I, A>
where
    I: Iterator<Item = MediaPrimitive>,
    A: UnveilAlgorithm,
{
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        // TODO better let the algorithm determine the density of decoding
        let items_to_take = buf.len() << 3; // 1 bit per carrier item
        let buf_writer = BufWriter::new(buf);
        let mut bit_buffer = BitWriter::endian(buf_writer, LittleEndian);

        let mut bit_read: usize = 0;
        for carrier in self.input.by_ref().take(items_to_take) {
            let bit = self.algorithm.decode(carrier);
            bit_buffer.write_bit(bit).expect("Cannot write bit n");
            bit_read += 1;
        }

        if !bit_buffer.byte_aligned() {
            bit_buffer
                .byte_align()
                .expect("Failed to align the last byte read from carrier.");
        }

        Ok(bit_read >> 3)
    }
}

/// default 1 bit unveil strategy
#[derive(Debug)]
pub struct OneBitUnveil;
impl UnveilAlgorithm for OneBitUnveil {
    #[inline]
    fn decode(&self, carrier: MediaPrimitive) -> bool {
        match carrier {
            MediaPrimitive::ImageColorChannel(b) => (b & 0x1) > 0,
            MediaPrimitive::AudioSample(b) => (b & 0x1) > 0,
        }
    }
}