ironrdp_pdu/basic_output/bitmap/
rdp6.rs

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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
use ironrdp_core::{
    ensure_fixed_part_size, ensure_size, invalid_field_err, Decode, DecodeResult, Encode, EncodeResult, ReadCursor,
    WriteCursor,
};

const NON_RLE_PADDING_SIZE: usize = 1;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorPlaneDefinition {
    Argb,
    AYCoCg {
        color_loss_level: u8,
        use_chroma_subsampling: bool,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BitmapStreamHeader {
    pub enable_rle_compression: bool,
    pub use_alpha: bool,
    pub color_plane_definition: ColorPlaneDefinition,
}

impl BitmapStreamHeader {
    pub const NAME: &'static str = "Rdp6BitmapStreamHeader";
    const FIXED_PART_SIZE: usize = 1;
}

impl Decode<'_> for BitmapStreamHeader {
    fn decode(src: &mut ReadCursor<'_>) -> DecodeResult<Self> {
        ensure_fixed_part_size!(in: src);
        let header = src.read_u8();

        let color_loss_level = header & 0x07;
        let use_chroma_subsampling = (header & 0x08) != 0;
        let enable_rle_compression = (header & 0x10) != 0;
        let use_alpha = (header & 0x20) == 0;

        let color_plane_definition = match color_loss_level {
            0 => ColorPlaneDefinition::Argb,
            color_loss_level => ColorPlaneDefinition::AYCoCg {
                color_loss_level,
                use_chroma_subsampling,
            },
        };

        Ok(Self {
            enable_rle_compression,
            use_alpha,
            color_plane_definition,
        })
    }
}

impl Encode for BitmapStreamHeader {
    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size());

        let mut header = ((self.enable_rle_compression as u8) << 4) | ((!self.use_alpha as u8) << 5);

        match self.color_plane_definition {
            ColorPlaneDefinition::Argb { .. } => {
                // ARGB color planes keep cll and cs flags set to 0
            }
            ColorPlaneDefinition::AYCoCg {
                color_loss_level,
                use_chroma_subsampling,
                ..
            } => {
                // Add cll and cs flags to header
                header |= (color_loss_level & 0x07) | ((use_chroma_subsampling as u8) << 3);
            }
        }

        dst.write_u8(header);

        Ok(())
    }

    fn name(&self) -> &'static str {
        Self::NAME
    }

    fn size(&self) -> usize {
        Self::FIXED_PART_SIZE
            + if self.enable_rle_compression {
                0
            } else {
                NON_RLE_PADDING_SIZE
            }
    }
}

/// Represents `RDP6_BITMAP_STREAM` structure described in [MS-RDPEGDI] 2.2.2.5.1
#[derive(Debug, Clone)]
pub struct BitmapStream<'a> {
    pub header: BitmapStreamHeader,
    pub color_planes: &'a [u8],
}

impl<'a> BitmapStream<'a> {
    pub const NAME: &'static str = "Rdp6BitmapStream";
    const FIXED_PART_SIZE: usize = 1;

    pub fn color_panes_data(&self) -> &'a [u8] {
        self.color_planes
    }

    pub fn has_subsampled_chroma(&self) -> bool {
        match self.header.color_plane_definition {
            ColorPlaneDefinition::Argb { .. } => false,
            ColorPlaneDefinition::AYCoCg {
                use_chroma_subsampling, ..
            } => use_chroma_subsampling,
        }
    }
}

impl<'a> Decode<'a> for BitmapStream<'a> {
    fn decode(src: &mut ReadCursor<'a>) -> DecodeResult<Self> {
        ensure_fixed_part_size!(in: src);
        let header = ironrdp_core::decode_cursor::<BitmapStreamHeader>(src)?;

        let color_planes_size = if !header.enable_rle_compression {
            // Cut padding field if RLE flags is set to 0
            if src.is_empty() {
                return Err(invalid_field_err!(
                    "padding",
                    "missing padding byte from zero-sized non-RLE bitmap data",
                ));
            }
            src.len() - NON_RLE_PADDING_SIZE
        } else {
            src.len()
        };

        let color_planes = src.read_slice(color_planes_size);

        Ok(Self { header, color_planes })
    }
}

impl Encode for BitmapStream<'_> {
    fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> {
        ensure_size!(in: dst, size: self.size());

        ironrdp_core::encode_cursor(&self.header, dst)?;
        dst.write_slice(self.color_panes_data());

        // Write padding
        if !self.header.enable_rle_compression {
            dst.write_u8(0);
        }

        Ok(())
    }

    fn name(&self) -> &'static str {
        Self::NAME
    }

    fn size(&self) -> usize {
        self.header.size() + self.color_panes_data().len()
    }
}

#[cfg(test)]
#[cfg(feature = "alloc")]
mod tests {
    use expect_test::{expect, Expect};

    use super::*;

    fn assert_roundtrip(buffer: &[u8], expected: Expect) {
        let pdu = ironrdp_core::decode::<BitmapStream<'_>>(buffer).unwrap();
        expected.assert_debug_eq(&pdu);
        assert_eq!(pdu.size(), buffer.len());
        let reencoded = ironrdp_core::encode_vec(&pdu).unwrap();
        assert_eq!(reencoded.as_slice(), buffer);
    }

    fn assert_parsing_failure(buffer: &[u8], expected: Expect) {
        let error = ironrdp_core::decode::<BitmapStream<'_>>(buffer).err().unwrap();
        expected.assert_debug_eq(&error);
    }

    #[test]
    fn parsing_valid_data_succeeds() {
        // AYCoCg color planes, with RLE
        assert_roundtrip(
            &[0x3F, 0x01, 0x02, 0x03, 0x04],
            expect![[r#"
                BitmapStream {
                    header: BitmapStreamHeader {
                        enable_rle_compression: true,
                        use_alpha: false,
                        color_plane_definition: AYCoCg {
                            color_loss_level: 7,
                            use_chroma_subsampling: true,
                        },
                    },
                    color_planes: [
                        1,
                        2,
                        3,
                        4,
                    ],
                }
            "#]],
        );

        // RGB color planes, with RLE, with alpha
        assert_roundtrip(
            &[0x10, 0x01, 0x02, 0x03, 0x04],
            expect![[r#"
                BitmapStream {
                    header: BitmapStreamHeader {
                        enable_rle_compression: true,
                        use_alpha: true,
                        color_plane_definition: Argb,
                    },
                    color_planes: [
                        1,
                        2,
                        3,
                        4,
                    ],
                }
            "#]],
        );

        // Without RLE, validate that padding is handled correctly
        assert_roundtrip(
            &[0x20, 0x01, 0x02, 0x03, 0x00],
            expect![[r#"
                BitmapStream {
                    header: BitmapStreamHeader {
                        enable_rle_compression: false,
                        use_alpha: false,
                        color_plane_definition: Argb,
                    },
                    color_planes: [
                        1,
                        2,
                        3,
                    ],
                }
            "#]],
        );

        // Empty color planes, with RLE
        assert_roundtrip(
            &[0x10],
            expect![[r#"
                BitmapStream {
                    header: BitmapStreamHeader {
                        enable_rle_compression: true,
                        use_alpha: true,
                        color_plane_definition: Argb,
                    },
                    color_planes: [],
                }
            "#]],
        );

        // Empty color planes, without RLE
        assert_roundtrip(
            &[0x00, 0x00],
            expect![[r#"
                BitmapStream {
                    header: BitmapStreamHeader {
                        enable_rle_compression: false,
                        use_alpha: true,
                        color_plane_definition: Argb,
                    },
                    color_planes: [],
                }
            "#]],
        );
    }

    #[test]
    fn failures_handled_gracefully() {
        // Empty buffer
        assert_parsing_failure(
            &[],
            expect![[r#"
                Error {
                    context: "<ironrdp_pdu::basic_output::bitmap::rdp6::BitmapStream as ironrdp_core::decode::Decode>::decode",
                    kind: NotEnoughBytes {
                        received: 0,
                        expected: 1,
                    },
                    source: None,
                }
            "#]],
        );

        // Without RLE, Check that missing padding byte is handled correctly
        assert_parsing_failure(
            &[0x20],
            expect![[r#"
                Error {
                    context: "<ironrdp_pdu::basic_output::bitmap::rdp6::BitmapStream as ironrdp_core::decode::Decode>::decode",
                    kind: InvalidField {
                        field: "padding",
                        reason: "missing padding byte from zero-sized non-RLE bitmap data",
                    },
                    source: None,
                }
            "#]],
        );
    }
}