psd/sections/layer_and_mask_information_section/mod.rs
1use std::collections::HashMap;
2use std::ops::Range;
3
4use crate::psd_channel::PsdChannelCompression;
5use crate::psd_channel::PsdChannelKind;
6use crate::sections::image_data_section::ChannelBytes;
7use crate::sections::layer_and_mask_information_section::groups::Groups;
8use crate::sections::layer_and_mask_information_section::layer::{
9 BlendMode, GroupDivider, LayerChannels, LayerRecord, PsdGroup, PsdLayer, PsdLayerError,
10};
11use crate::sections::layer_and_mask_information_section::layers::Layers;
12use crate::sections::PsdCursor;
13
14/// One of the possible additional layer block signatures
15const SIGNATURE_EIGHT_BIM: [u8; 4] = [56, 66, 73, 77];
16/// One of the possible additional layer block signatures
17const SIGNATURE_EIGHT_B64: [u8; 4] = [56, 66, 54, 52];
18
19/// Additional Layer Information constants.
20/// Key of `Unicode layer name (Photoshop 5.0)`, "luni"
21const KEY_UNICODE_LAYER_NAME: &[u8; 4] = b"luni";
22/// Key of `Section divider setting (Photoshop 6.0)`, "lsct"
23const KEY_SECTION_DIVIDER_SETTING: &[u8; 4] = b"lsct";
24
25pub mod groups;
26pub mod layer;
27pub mod layers;
28
29/// The LayerAndMaskInformationSection comes from the bytes in the fourth section of the PSD.
30///
31/// When possible we'll make the data easier to work with by storing it structures such as HashMaps.
32///
33/// # Note
34///
35/// We do not currently store all of the information that is present in the layer and mask
36/// information section of the PSD. If something that you need is missing please open an issue.
37///
38/// # [Adobe Docs](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)
39///
40/// The fourth section of a Photoshop file contains information about layers and masks. This section of the document describes the formats of layer and mask records.
41///
42/// The complete merged image data is not stored here. The complete merged/composite image resides in the last section of the file. See See Image Data Section. If maximize compatibility is unchecked then the merged/composite is not created and the layer data must be read to reproduce the final image.
43///
44/// See Layer and mask information section shows the overall structure of this section. If there are no layers or masks, this section is just 4 bytes: the length field, which is set to zero. (**PSB** length is 8 bytes
45///
46/// 'Layr', 'Lr16' and 'Lr32' start at See Layer info. NOTE: The length of the section may already be known.)
47///
48/// When parsing this section pay close attention to the length of sections.
49///
50/// | Length | Description |
51/// |----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
52/// | 4 | Length of the layer and mask information section.<br> (**PSB** length is 8 bytes.) |
53/// | Variable | Layer info (see See Layer info for details). |
54/// | Variable | Global layer mask info (see See Global layer mask info for details). |
55/// | Variable | (Photoshop 4.0 and later) <br> Series of tagged blocks containing various types of data. See See Additional Layer Information for the list of the types of data that can be included here. |
56#[derive(Debug)]
57pub struct LayerAndMaskInformationSection {
58 pub(crate) layers: Layers,
59 pub(crate) groups: Groups,
60}
61
62/// Frame represents a group stack frame
63#[derive(Debug)]
64struct Frame {
65 start_idx: usize,
66 name: String,
67 group_id: u32,
68 parent_group_id: u32,
69}
70
71impl LayerAndMaskInformationSection {
72 /// Create a LayerAndMaskInformationSection from the bytes in the corresponding section in a
73 /// PSD file (including the length marker).
74 pub fn from_bytes(
75 bytes: &[u8],
76 psd_width: u32,
77 psd_height: u32,
78 ) -> Result<LayerAndMaskInformationSection, PsdLayerError> {
79 let mut cursor = PsdCursor::new(bytes);
80
81 // The first four bytes of the section is the length marker for the layer and mask
82 // information section.
83 //
84 // We do not currently use it since the number of bytes passed into this function was
85 // the exact number of bytes in the layer and information mask section of the PSD file,
86 // so there's no way for us to accidentally read too many bytes. If we did the program
87 // would panic.
88 let len = cursor.read_u32();
89
90 if len == 0 {
91 return Ok(LayerAndMaskInformationSection {
92 layers: Layers::new(),
93 groups: Groups::with_capacity(0),
94 });
95 }
96
97 // Read the next four bytes to get the length of the layer info section.
98 let _layer_info_section_len = cursor.read_u32();
99
100 // Next 2 bytes is the layer count
101 //
102 // NOTE: Appears to be -1 when we create a new PSD and don't create any new layers but
103 // instead only manipulate the default background layer.
104 //
105 // # [Adobe Docs](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)
106 //
107 // Layer count. If it is a negative number, its absolute value is the number of layers and
108 // the first alpha channel contains the transparency data for the merged result.
109 let layer_count = cursor.read_i16();
110
111 // TODO: If the layer count was negative we were supposed to treat the first alpha
112 // channel as transparency data for the merged result.. So add a new test with a transparent
113 // PSD and make sure that we're handling this case properly.
114 let layer_count: u16 = layer_count.abs() as u16;
115 let (group_count, layer_records) =
116 LayerAndMaskInformationSection::read_layer_records(&mut cursor, layer_count)?;
117
118 LayerAndMaskInformationSection::decode_layers(
119 layer_records,
120 group_count,
121 (psd_width, psd_height),
122 )
123 }
124
125 fn decode_layers(
126 layer_records: Vec<(LayerRecord, LayerChannels)>,
127 group_count: usize,
128 psd_size: (u32, u32),
129 ) -> Result<LayerAndMaskInformationSection, PsdLayerError> {
130 let mut layers = Layers::with_capacity(layer_records.len());
131 let mut groups = Groups::with_capacity(group_count);
132
133 // Create stack with root-level
134 let mut stack: Vec<Frame> = vec![Frame {
135 start_idx: 0,
136 name: String::from("root"),
137 group_id: 0,
138 parent_group_id: 0,
139 }];
140
141 // Viewed group counter
142 let mut already_viewed = 0;
143
144 // Read each layer's channel image data
145 for (layer_record, channels) in layer_records.into_iter() {
146 // get current group from stack
147 let current_group_id = stack.last().unwrap().group_id;
148
149 match layer_record.divider_type {
150 // open the folder
151 Some(GroupDivider::CloseFolder) | Some(GroupDivider::OpenFolder) => {
152 already_viewed = already_viewed + 1;
153
154 let frame = Frame {
155 start_idx: layers.len(),
156 name: layer_record.name,
157 group_id: already_viewed,
158 parent_group_id: current_group_id,
159 };
160
161 stack.push(frame);
162 }
163
164 // close the folder
165 Some(GroupDivider::BoundingSection) => {
166 let frame = stack.pop().unwrap();
167
168 let range = Range {
169 start: frame.start_idx,
170 end: layers.len(),
171 };
172
173 groups.push(PsdGroup::new(
174 frame.name,
175 frame.group_id,
176 range,
177 &layer_record,
178 psd_size.0,
179 psd_size.1,
180 if frame.parent_group_id > 0 {
181 Some(frame.parent_group_id)
182 } else {
183 None
184 },
185 ));
186 }
187
188 _ => {
189 let psd_layer = LayerAndMaskInformationSection::read_layer(
190 &layer_record,
191 current_group_id,
192 psd_size,
193 channels,
194 )?;
195
196 layers.push(psd_layer.name.clone(), psd_layer);
197 }
198 };
199 }
200
201 Ok(LayerAndMaskInformationSection { layers, groups })
202 }
203
204 fn read_layer_records(
205 cursor: &mut PsdCursor,
206 layer_count: u16,
207 ) -> Result<(usize, Vec<(LayerRecord, LayerChannels)>), PsdLayerError> {
208 let mut groups_count = 0;
209
210 let mut layer_records = vec![];
211 // Read each layer record
212 for _layer_num in 0..layer_count {
213 let layer_record = read_layer_record(cursor)?;
214
215 match layer_record.divider_type {
216 Some(GroupDivider::BoundingSection) => {
217 groups_count = groups_count + 1;
218 }
219 _ => {}
220 }
221
222 layer_records.push(layer_record);
223 }
224
225 let mut result = vec![];
226 for layer_record in layer_records {
227 let channels = read_layer_channels(
228 cursor,
229 &layer_record.channel_data_lengths,
230 layer_record.height() as usize,
231 )?;
232
233 result.push((layer_record, channels));
234 }
235
236 // Photoshop stores layers in reverse order
237 result.reverse();
238 Ok((groups_count, result))
239 }
240
241 fn read_layer(
242 layer_record: &LayerRecord,
243 parent_id: u32,
244 psd_size: (u32, u32),
245 channels: LayerChannels,
246 ) -> Result<PsdLayer, PsdLayerError> {
247 Ok(PsdLayer::new(
248 &layer_record,
249 psd_size.0,
250 psd_size.1,
251 if parent_id > 0 { Some(parent_id) } else { None },
252 channels,
253 ))
254 }
255}
256
257/// Reads layer channels
258fn read_layer_channels(
259 cursor: &mut PsdCursor,
260 channel_data_lengths: &Vec<(PsdChannelKind, u32)>,
261 scanlines: usize,
262) -> Result<LayerChannels, PsdLayerError> {
263 let capacity = channel_data_lengths.len();
264 let mut channels = HashMap::with_capacity(capacity);
265
266 for (channel_kind, channel_length) in channel_data_lengths.iter() {
267 let compression = cursor.read_u16();
268 let compression = PsdChannelCompression::new(compression)
269 .ok_or(PsdLayerError::InvalidCompression { compression })?;
270
271 let compression = if *channel_length > 0 {
272 compression
273 } else {
274 PsdChannelCompression::RawData
275 };
276
277 let channel_data = cursor.read(*channel_length);
278 let channel_bytes = match compression {
279 PsdChannelCompression::RawData => ChannelBytes::RawData(channel_data.into()),
280 PsdChannelCompression::RleCompressed => {
281 // We're skipping over the bytes that describe the length of each scanline since
282 // we don't currently use them. We might re-think this in the future when we
283 // implement serialization of a Psd back into bytes.. But not a concern at the
284 // moment.
285 // Compressed bytes per scanline are encoded at the beginning as 2 bytes
286 // per scanline
287 let channel_data = &channel_data[2 * scanlines..];
288 ChannelBytes::RleCompressed(channel_data.into())
289 }
290 _ => unimplemented!("Zip compression currently unsupported"),
291 };
292
293 channels.insert(*channel_kind, channel_bytes);
294 }
295
296 Ok(channels)
297}
298
299/// Read bytes, starting from the cursor, until we've processed all of the data for a layer in
300/// the layer records section.
301///
302/// At the moment we skip over some of the data.
303///
304/// Please open an issue if there is data in here that you need that we don't currently parse.
305///
306/// # [Adobe Docs](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)
307///
308/// Information about each layer.
309///
310/// | Length | Description |
311/// |------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
312/// | 4 * 4 | Rectangle containing the contents of the layer. Specified as top, left, bottom, right coordinates |
313/// | 2 | Number of channels in the layer |
314/// | 6 * number of channels | Channel information. Six bytes per channel,<br> consisting of: 2 bytes for Channel ID: 0 = red, 1 = green, etc.; <br> -1 = transparency mask; -2 = user supplied layer mask, -3 real user supplied layer mask (when both a user mask and a vector mask are present) <br> 4 bytes for length of corresponding channel data. (**PSB** 8 bytes for length of corresponding channel data.) See See Channel image data for structure of channel data. |
315/// | 4 | Blend mode signature: '8BIM' |
316/// | 4 | Blend mode key: <br> 'pass' = pass through, 'norm' = normal, 'diss' = dissolve, 'dark' = darken, 'mul ' = multiply, 'idiv' = color burn, 'lbrn' = linear burn, 'dkCl' = darker color, 'lite' = lighten, 'scrn' = screen, 'div ' = color dodge, 'lddg' = linear dodge, 'lgCl' = lighter color, 'over' = overlay, 'sLit' = soft light, 'hLit' = hard light, 'vLit' = vivid light, 'lLit' = linear light, 'pLit' = pin light, 'hMix' = hard mix, 'diff' = difference, 'smud' = exclusion, 'fsub' = subtract, 'fdiv' = divide 'hue ' = hue, 'sat ' = saturation, 'colr' = color, 'lum ' = luminosity, |
317/// | 1 | Opacity. 0 = transparent ... 255 = opaque |
318/// | 1 | Clipping: 0 = base, 1 = non-base |
319/// | 1 | Flags: <br> bit 0 = transparency protected; <br> bit 1 = visible; <br> bit 2 = obsolete; <br> bit 3 = 1 for Photoshop 5.0 and later, tells if bit 4 has useful information; <br> bit 4 = pixel data irrelevant to appearance of document |
320/// | 1 | Filler (zero) |
321/// | 4 | Length of the extra data field ( = the total length of the next five fields). |
322/// | Variable | Layer mask data: See See Layer mask / adjustment layer data for structure. Can be 40 bytes, 24 bytes, or 4 bytes if no layer mask. |
323/// | Variable | Layer blending ranges: See See Layer blending ranges data. |
324/// | Variable | Layer name: Pascal string, padded to a multiple of 4 bytes. |
325fn read_layer_record(cursor: &mut PsdCursor) -> Result<LayerRecord, PsdLayerError> {
326 let mut channel_data_lengths = vec![];
327
328 // FIXME:
329 // Ran into a bug where a PSD file had a top and left of over 4billion.
330 // The PSD file was 128x128 yet the single layer in the file was 1024x1024.
331 // Manually changing the layer's dimensions fixed the problem.. but this is something
332 // that we should look into handling automatically since the file opened just fine in
333 // Photoshop.
334
335 // Read the rectangle that encloses the layer mask.
336 let top = cursor.read_i32();
337
338 let left = cursor.read_i32();
339
340 // Subtract one in order to zero index. If a layer is fully transparent it's bottom will
341 // already be 0 so we don't subtract
342 let bottom = cursor.read_i32();
343 let bottom = if bottom == 0 { 0 } else { bottom - 1 };
344
345 // Subtract one in order to zero index. If a layer is fully transparent it's right will
346 // already be zero so we don't subtract.
347 let right = cursor.read_i32();
348 let right = if right == 0 { 0 } else { right - 1 };
349
350 // Get the number of channels in the layer
351 let channel_count = cursor.read_u16();
352
353 // Read the channel information
354 for _ in 0..channel_count {
355 let channel_id = cursor.read_i16();
356 let channel_id =
357 PsdChannelKind::new(channel_id).ok_or(PsdLayerError::InvalidChannel { channel_id })?;
358
359 let channel_length = cursor.read_u32();
360 // The first two bytes encode the compression, the rest of the bytes
361 // are the channel data.
362 let channel_data_length = channel_length - 2;
363
364 channel_data_lengths.push((channel_id, channel_data_length));
365 }
366
367 // We do not currently parse the blend mode signature, skip it
368 cursor.read_4();
369
370 let mut key = [0; 4];
371 key.copy_from_slice(cursor.read_4());
372 let blend_mode = match BlendMode::match_mode(key) {
373 Some(v) => v,
374 None => return Err(PsdLayerError::UnknownBlendingMode { mode: key }),
375 };
376
377 let opacity = cursor.read_u8();
378
379 let clipping_base = cursor.read_u8();
380 let clipping_base = clipping_base == 0;
381
382 // We do not currently parse all flags, only visible
383 // Flags:
384 // - bit 0 = transparency protected;
385 // - bit 1 = visible;
386 // - bit 2 = obsolete;
387 // - bit 3 = 1 for Photoshop 5.0 and later, tells if bit 4 has useful information;
388 // - bit 4 = pixel data irrelevant to appearance of document
389 let visible = cursor.read_u8() & (1 << 1) != 0; // here we get second bit - visible
390
391 // We do not currently parse the filler, skip it
392 cursor.read_1();
393
394 // We do not currently use the length of the extra data field, skip it
395 cursor.read_4();
396
397 // We do not currently use the layer mask data, skip it
398 let layer_mask_data_len = cursor.read_u32();
399 cursor.read(layer_mask_data_len);
400
401 // We do not currently use the layer blending range, skip it
402 let layer_blending_range_data_len = cursor.read_u32();
403 cursor.read(layer_blending_range_data_len);
404
405 // Read the layer name
406 let name_len = cursor.read_u8();
407 let name = cursor.read(name_len as u32);
408 let name = String::from_utf8_lossy(name);
409 let mut name = name.to_string();
410
411 // Layer name is padded to the next multiple of 4 bytes.
412 // So if the name length is 9, there will be three throwaway bytes
413 // after it. Here we skip over those throwaday bytes.
414 //
415 // The 1 is the 1 byte that we read for the name length
416 let bytes_mod_4 = (name_len + 1) % 4;
417 let padding = (4 - bytes_mod_4) % 4;
418 cursor.read(padding as u32);
419
420 let mut divider_type = None;
421 // There can be multiple additional layer information sections so we'll loop
422 // until we stop seeing them.
423 while cursor.peek_4() == SIGNATURE_EIGHT_BIM || cursor.peek_4() == SIGNATURE_EIGHT_B64 {
424 let _signature = cursor.read_4();
425 let mut key = [0; 4];
426 key.copy_from_slice(cursor.read_4());
427 let additional_layer_info_len = cursor.read_u32();
428
429 match &key {
430 KEY_UNICODE_LAYER_NAME => {
431 let pos = cursor.position();
432 name = cursor.read_unicode_string_padding(1);
433 cursor.seek(pos + additional_layer_info_len as u64);
434 }
435 KEY_SECTION_DIVIDER_SETTING => {
436 divider_type = GroupDivider::match_divider(cursor.read_i32());
437
438 // data present only if length >= 12
439 if additional_layer_info_len >= 12 {
440 let _signature = cursor.read_4();
441 let _key = cursor.read_4();
442 }
443
444 // data present only if length >= 16
445 if additional_layer_info_len >= 16 {
446 cursor.read_4();
447 }
448 }
449
450 // TODO: Skipping other keys until we implement parsing for them
451 _ => {
452 cursor.read(additional_layer_info_len);
453 }
454 }
455 }
456
457 Ok(LayerRecord {
458 name,
459 channel_data_lengths,
460 top,
461 left,
462 bottom,
463 right,
464 visible,
465 opacity,
466 clipping_base,
467 blend_mode,
468 divider_type,
469 })
470}