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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use crate as pdf;
use crate::object::*;
use crate::primitive::*;
use crate::error::*;
use crate::parser::Lexer;
use crate::enc::decode;

use once_cell::unsync::OnceCell;

use std::borrow::Cow;
use std::io;
use std::ops::Deref;
use std::fmt;



/// Simple Stream object with only some additional entries from the stream dict (I).
pub struct Stream<I: Object=()> {
    pub info: StreamInfo<I>,
    raw_data: Vec<u8>,
    decoded: OnceCell<Vec<u8>>
}
impl<I: Object + fmt::Debug> Stream<I> {
    pub fn from_stream(s: PdfStream, resolve: &impl Resolve) -> Result<Self> {
        let PdfStream {info, data} = s;
        let info = StreamInfo::<I>::from_primitive(Primitive::Dictionary (info), resolve)?;
        Ok(Stream { info, raw_data: data, decoded: OnceCell::new() })
    }

    /// decode the data.
    /// does not store the result.
    /// The caller is responsible for caching the result
    pub fn decode(&self) -> Result<Cow<[u8]>> {
        let mut data = Cow::Borrowed(&*self.raw_data);
        for filter in &self.info.filters {
            data = match decode(&*data, filter) {
                Ok(data) => data.into(),
                Err(e) => {
                    info!("Stream Info: {:?}", &self.info);
                    dump_data(&data);
                    return Err(e);
                }
            };
        }
        Ok(data)
    }
    pub fn data(&self) -> Result<&[u8]> {
        self.decoded.get_or_try_init(|| {
            let data = self.decode()?;
            Ok(data.into_owned())
        }).map(|v| v.as_slice())
    }

    /// If this is contains DCT encoded data, return the compressed data as is
    pub fn as_jpeg(&self) -> Option<&[u8]> {
        match *self.info.filters.as_slice() {
            [StreamFilter::DCTDecode(_)] => Some(self.raw_data.as_slice()),
            _ => None
        }
    }
}
        
impl<I: Object + fmt::Debug> fmt::Debug for Stream<I> {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        self.info.info.fmt(f)
    }
}

impl<I: Object + fmt::Debug> Object for Stream<I> {
    /// Write object as a byte stream
    fn serialize<W: io::Write>(&self, _: &mut W) -> Result<()> {unimplemented!()}
    /// Convert primitive to Self
    fn from_primitive(p: Primitive, resolve: &impl Resolve) -> Result<Self> {
        let s = PdfStream::from_primitive(p, resolve)?;
        Stream::from_stream(s, resolve)
    }
}

impl<I:Object> Deref for Stream<I> {
    type Target = StreamInfo<I>;
    fn deref(&self) -> &StreamInfo<I> {
        &self.info
    }
}


/// General stream type. `I` is the additional information to be read from the stream dict.
#[derive(Debug, Clone)]
pub struct StreamInfo<I> {
    // General dictionary entries
    /// Filters that the `data` is currently encoded with (corresponds to both `/Filter` and
    /// `/DecodeParms` in the PDF specs), constructed in `from_primitive()`.
    pub filters: Vec<StreamFilter>,

    /// Eventual file containing the stream contentst
    pub file: Option<FileSpec>,
    /// Filters to apply to external file specified in `file`.
    pub file_filters: Vec<StreamFilter>,

    // TODO:
    /*
    /// Filters to apply to external file specified in `file`.
    #[pdf(key="FFilter")]
    file_filters: Vec<StreamFilter>,
    #[pdf(key="FDecodeParms")]
    file_decode_parms: Vec<DecodeParms>,
    /// Number of bytes in the decoded stream
    #[pdf(key="DL")]
    dl: Option<usize>,
    */
    // Specialized dictionary entries
    info: I,
}

impl<I> Deref for StreamInfo<I> {
    type Target = I;
    fn deref(&self) -> &I {
        &self.info
    }
}

impl<I: Default> Default for StreamInfo<I> {
    fn default() -> StreamInfo<I> {
        StreamInfo {
            filters: Vec::new(),
            file: None,
            file_filters: Vec::new(),
            info: I::default(),
        }
    }
}
impl<T> StreamInfo<T> {
/*
    /// If the stream is not encoded, this is a no-op. `decode()` should be called whenever it's uncertain
    /// whether the stream is encoded.
    pub fn encode(&mut self, _filter: StreamFilter) {
        // TODO this should add the filter to `self.filters` and encode the data with the given
        // filter
        unimplemented!();
    }*/
    pub fn get_filters(&self) -> &[StreamFilter] {
        &self.filters
    }
}
impl<T: Object> Object for StreamInfo<T> {
    fn serialize<W: io::Write>(&self, _out: &mut W) -> Result<()> {
        unimplemented!();
    }
    fn from_primitive(p: Primitive, resolve: &impl Resolve) -> Result<Self> {
        let mut dict = Dictionary::from_primitive(p, resolve)?;

        let _length = usize::from_primitive(
            dict.remove("Length").ok_or(PdfError::MissingEntry{ typ: "StreamInfo", field: "Length".into() })?,
            resolve)?;

        let filters = Vec::<String>::from_primitive(
            dict.remove("Filter").or(Some(Primitive::Null)).unwrap(),
            resolve)?;

        let decode_params = Vec::<Dictionary>::from_primitive(
            dict.remove("DecodeParms").or(Some(Primitive::Null)).unwrap(),
            resolve)?;

        let file = Option::<FileSpec>::from_primitive(
            dict.remove("F").or(Some(Primitive::Null)).unwrap(),
            resolve)?;

        let file_filters = Vec::<String>::from_primitive(
            dict.remove("FFilter").or(Some(Primitive::Null)).unwrap(),
            resolve)?;

        let file_decode_params = Vec::<Dictionary>::from_primitive(
            dict.remove("FDecodeParms").or(Some(Primitive::Null)).unwrap(),
            resolve)?;


        let mut new_filters = Vec::new();
        let mut new_file_filters = Vec::new();

        for (i, filter) in filters.iter().enumerate() {
            let params = match decode_params.get(i) {
                Some(params) => params.clone(),
                None => Dictionary::default(),
            };
            new_filters.push(StreamFilter::from_kind_and_params(filter, params, resolve)?);
        }
        for (i, filter) in file_filters.iter().enumerate() {
            let params = match file_decode_params.get(i) {
                Some(params) => params.clone(),
                None => Dictionary::default(),
            };
            new_file_filters.push(StreamFilter::from_kind_and_params(filter, params, resolve)?);
        }

        Ok(StreamInfo {
            // General
            filters: new_filters,
            file,
            file_filters: new_file_filters,
            // Special
            info: T::from_primitive(Primitive::Dictionary (dict), resolve)?,
        })
    }
}

#[derive(Object, Default, Debug)]
#[pdf(Type = "ObjStm")]
pub struct ObjStmInfo {
    #[pdf(key = "N")]
    /// Number of compressed objects in the stream.
    pub num_objects: i32,

    #[pdf(key = "First")]
    /// The byte offset in the decoded stream, of the first compressed object.
    pub first: i32,

    #[pdf(key = "Extends")]
    /// A reference to an eventual ObjectStream which this ObjectStream extends.
    pub extends: Option<Rc<Stream>>,

}


pub struct ObjectStream {
    /// Byte offset of each object. Index is the object number.
    offsets:    Vec<usize>,
    /// The object number of this object.
    _id:         ObjNr,
    
    inner:      Stream<ObjStmInfo>
}

impl Object for ObjectStream {
    fn serialize<W: io::Write>(&self, _out: &mut W) -> Result<()> {
        unimplemented!();
    }
    fn from_primitive(p: Primitive, resolve: &impl Resolve) -> Result<ObjectStream> {
        let stream: Stream<ObjStmInfo> = Stream::from_primitive(p, resolve)?;

        let mut offsets = Vec::new();
        {
            debug!("parsing stream");
            let mut lexer = Lexer::new(stream.data()?);
            for _ in 0..(stream.info.num_objects as ObjNr) {
                let _obj_nr = lexer.next()?.to::<ObjNr>()?;
                let offset = lexer.next()?.to::<usize>()?;
                offsets.push(offset);
            }
        }

        Ok(ObjectStream {
            offsets,
            _id: 0, // TODO
            inner: stream
        })
    }
}

impl ObjectStream {
    pub fn get_object_slice(&self, index: usize) -> Result<&[u8]> {
        if index >= self.offsets.len() {
            err!(PdfError::ObjStmOutOfBounds {index, max: self.offsets.len()});
        }
        let start = self.inner.info.first as usize + self.offsets[index];
        let data = self.inner.data()?;
        let end = if index == self.offsets.len() - 1 {
            data.len()
        } else {
            self.inner.info.first as usize + self.offsets[index + 1]
        };

        Ok(&data[start..end])
    }
    /// Returns the number of contained objects
    pub fn n_objects(&self) -> usize {
        self.offsets.len()
    }
}