Skip to main content

euv_core/media/gif/
impl.rs

1use super::*;
2
3/// Default bounded decoding budgets and browser-compatible frame-delay policy for `GifDecodeConfig`.
4impl Default for GifDecodeConfig {
5    /// Returns default GIF decoding budgets (`64 MiB` canvas, `16 MiB` / `16` frame cache, `20ms` min / `100ms` zero-delay fallback).
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default GIF decode configuration.
10    fn default() -> Self {
11        Self::new(
12            GIF_DEFAULT_MAX_CANVAS_BYTES,
13            GIF_DEFAULT_MAX_CACHE_BYTES,
14            GIF_DEFAULT_MAX_PREDECODE_FRAMES,
15            GIF_DEFAULT_MIN_DELAY_MS,
16            GIF_DEFAULT_ZERO_DELAY_FALLBACK_MS,
17            false,
18        )
19    }
20}
21
22/// Conversion helpers for `GifDisposalMethod`.
23impl GifDisposalMethod {
24    /// Decodes a 3-bit GIF89a Graphic Control Extension disposal value (`0..=7`).
25    ///
26    /// # Arguments
27    ///
28    /// - `u8` - 3-bit disposal field extracted from GCE packed byte.
29    ///
30    /// # Returns
31    ///
32    /// - `Self` - Normalized disposal method.
33    #[must_use]
34    pub const fn from_gce_bits(bits: u8) -> Self {
35        match bits & 0x07 {
36            1 => Self::Keep,
37            2 => Self::RestoreToBackground,
38            3 => Self::RestoreToPrevious,
39            _ => Self::Unspecified,
40        }
41    }
42
43    /// Encodes this disposal method into its 3-bit GIF89a GCE field representation.
44    ///
45    /// # Arguments
46    ///
47    /// - `Self` - Disposal method variant.
48    ///
49    /// # Returns
50    ///
51    /// - `u8` - 3-bit value (`0..=3`).
52    #[must_use]
53    pub const fn to_gce_bits(self) -> u8 {
54        match self {
55            Self::Unspecified => 0,
56            Self::Keep => 1,
57            Self::RestoreToBackground => 2,
58            Self::RestoreToPrevious => 3,
59        }
60    }
61}
62
63/// Rectangle union and emptiness helpers for `GifDirtyRect`.
64impl GifDirtyRect {
65    /// Returns `true` when either width or height is zero.
66    ///
67    /// # Arguments
68    ///
69    /// - `&Self` - Dirty rectangle reference.
70    ///
71    /// # Returns
72    ///
73    /// - `bool` - `true` if the rectangle covers zero pixels.
74    #[must_use]
75    pub const fn is_empty(&self) -> bool {
76        let Self { width, height, .. } = *self;
77        width == 0 || height == 0
78    }
79
80    /// Computes the tight axis-aligned bounding union of `self` and `other`.
81    ///
82    /// # Arguments
83    ///
84    /// - `Self` - First dirty rectangle.
85    /// - `Self` - Second dirty rectangle.
86    ///
87    /// # Returns
88    ///
89    /// - `Self` - Enclosing dirty rectangle union.
90    #[must_use]
91    pub fn union(self, other: Self) -> Self {
92        if self.is_empty() {
93            return other;
94        }
95        if other.is_empty() {
96            return self;
97        }
98        let x0: u32 = self.get_x().min(other.get_x());
99        let y0: u32 = self.get_y().min(other.get_y());
100        let x1: u32 = (self.get_x().saturating_add(self.get_width()))
101            .max(other.get_x().saturating_add(other.get_width()));
102        let y1: u32 = (self.get_y().saturating_add(self.get_height()))
103            .max(other.get_y().saturating_add(other.get_height()));
104        Self::new(x0, y0, x1.saturating_sub(x0), y1.saturating_sub(y0))
105    }
106
107    /// Clips `(left, top, width, height)` to the logical canvas `(canvas_w, canvas_h)`.
108    ///
109    /// # Arguments
110    ///
111    /// - `u16` - Sub-frame left offset.
112    /// - `u16` - Sub-frame top offset.
113    /// - `u16` - Sub-frame width.
114    /// - `u16` - Sub-frame height.
115    /// - `u32` - Logical canvas width.
116    /// - `u32` - Logical canvas height.
117    ///
118    /// # Returns
119    ///
120    /// - `Self` - Clipped dirty rectangle inside `[0..canvas_w, 0..canvas_h)`.
121    #[must_use]
122    pub fn clipped_subframe(
123        left: u16,
124        top: u16,
125        width: u16,
126        height: u16,
127        canvas_w: u32,
128        canvas_h: u32,
129    ) -> Self {
130        let x0: u32 = (left as u32).min(canvas_w);
131        let y0: u32 = (top as u32).min(canvas_h);
132        let x1: u32 = (left as u32).saturating_add(width as u32).min(canvas_w);
133        let y1: u32 = (top as u32).saturating_add(height as u32).min(canvas_h);
134        Self::new(x0, y0, x1.saturating_sub(x0), y1.saturating_sub(y0))
135    }
136}
137
138/// Optional field accessors for `GifFrameDescriptor`.
139impl GifFrameDescriptor {
140    /// Returns the optional transparent color table index for this frame.
141    ///
142    /// # Arguments
143    ///
144    /// - `&Self` - Frame descriptor reference.
145    ///
146    /// # Returns
147    ///
148    /// - `Option<u8>` - Transparent palette index if enabled by GCE.
149    #[must_use]
150    pub const fn transparent_color_index(&self) -> Option<u8> {
151        let Self {
152            transparent_index, ..
153        } = *self;
154        transparent_index
155    }
156
157    /// Returns the optional byte range of the frame's Local Color Table inside the raw GIF stream.
158    ///
159    /// # Arguments
160    ///
161    /// - `&Self` - Frame descriptor reference.
162    ///
163    /// # Returns
164    ///
165    /// - `Option<(usize, usize)>` - Byte slice `(start, end)` of RGB triplets.
166    #[must_use]
167    pub const fn local_color_table_range(&self) -> Option<(usize, usize)> {
168        let Self { lct_range, .. } = *self;
169        lct_range
170    }
171}
172
173/// GIF87a/GIF89a container parsing and true LZW pixel decompression for `GifDecoder`.
174impl GifDecoder {
175    /// Parses a GIF87a/GIF89a byte stream into lightweight frame descriptors using default `GifDecodeConfig`.
176    ///
177    /// # Arguments
178    ///
179    /// - `&[u8]` - Raw `.gif` file bytes.
180    ///
181    /// # Returns
182    ///
183    /// - `Result<Self, String>` - Parsed GIF decoder or structural/budget error.
184    pub fn parse(bytes: &[u8]) -> Result<Self, String> {
185        Self::parse_with_config(bytes, GifDecodeConfig::default())
186    }
187
188    /// Parses a GIF87a/GIF89a byte stream validating header, palettes, GCEs, Netscape loop count, and sub-block bounds.
189    ///
190    /// # Arguments
191    ///
192    /// - `&[u8]` - Raw `.gif` file bytes.
193    /// - `GifDecodeConfig` - Memory budget and frame-delay compatibility policy.
194    ///
195    /// # Returns
196    ///
197    /// - `Result<Self, String>` - Parsed GIF decoder or error.
198    pub fn parse_with_config(bytes: &[u8], config: GifDecodeConfig) -> Result<Self, String> {
199        let is_87a: bool = bytes.starts_with(MAGIC_GIF87A);
200        let is_89a: bool = bytes.starts_with(MAGIC_GIF89A);
201        if bytes.len() < 13 || (!is_87a && !is_89a) {
202            return Err(GIF_ERR_HEADER.to_string());
203        }
204        let version: String = if is_89a {
205            GIF_VER_89A.to_string()
206        } else {
207            GIF_VER_87A.to_string()
208        };
209        let logical_width: u16 = u16::from_le_bytes([bytes[6], bytes[7]]);
210        let logical_height: u16 = u16::from_le_bytes([bytes[8], bytes[9]]);
211        if logical_width == 0 || logical_height == 0 {
212            return Err(GIF_ERR_ZERO_DIM.to_string());
213        }
214        let canvas_bytes: usize = (logical_width as usize)
215            .saturating_mul(logical_height as usize)
216            .saturating_mul(4);
217        if canvas_bytes > config.get_max_canvas_bytes() {
218            return Err(GIF_ERR_BUDGET.to_string());
219        }
220        let packed: u8 = bytes[10];
221        let background_color_index: u8 = bytes[11];
222        let has_gct: bool = (packed & 0x80) != 0;
223        let gct_entries: usize = if has_gct {
224            1_usize << ((packed & 0x07) + 1)
225        } else {
226            0
227        };
228        let mut cursor: usize = 13;
229        let mut global_color_table: Vec<[u8; 3]> = Vec::with_capacity(gct_entries);
230        if has_gct {
231            let gct_bytes: usize = gct_entries * 3;
232            if cursor.saturating_add(gct_bytes) > bytes.len() {
233                return Err(GIF_ERR_TRUNC_GCT.to_string());
234            }
235            for item_index in 0..gct_entries {
236                let off: usize = cursor + item_index * 3;
237                global_color_table.push([bytes[off], bytes[off + 1], bytes[off + 2]]);
238            }
239            cursor += gct_bytes;
240        }
241        let mut frames: Vec<GifFrameDescriptor> = Vec::new();
242        let mut has_netscape_loop: bool = false;
243        let mut loop_count: u32 = 0;
244        let mut next_disposal: GifDisposalMethod = GifDisposalMethod::Unspecified;
245        let mut next_transparent: Option<u8> = None;
246        let mut next_delay_ms: u32 = Self::normalize_delay_ms(0, &config);
247        let mut timeline_ms: u32 = 0;
248        while cursor < bytes.len() {
249            let intro: u8 = bytes[cursor];
250            cursor += 1;
251            if intro == GIF_TRAILER {
252                break;
253            }
254            if intro == GIF_EXT_INTRO {
255                if cursor >= bytes.len() {
256                    return Err(GIF_ERR_TRUNC_SUB.to_string());
257                }
258                let label: u8 = bytes[cursor];
259                cursor += 1;
260                if label == GIF_EXT_GCE {
261                    if cursor >= bytes.len() {
262                        return Err(GIF_ERR_TRUNC_SUB.to_string());
263                    }
264                    let block_size: usize = bytes[cursor] as usize;
265                    cursor += 1;
266                    if block_size == 4 && cursor + 4 <= bytes.len() {
267                        let gce_packed: u8 = bytes[cursor];
268                        let delay_cs: u16 =
269                            u16::from_le_bytes([bytes[cursor + 1], bytes[cursor + 2]]);
270                        let trans_idx: u8 = bytes[cursor + 3];
271                        next_disposal = GifDisposalMethod::from_gce_bits(gce_packed >> 2);
272                        next_transparent = if (gce_packed & 0x01) != 0 {
273                            Some(trans_idx)
274                        } else {
275                            None
276                        };
277                        next_delay_ms = Self::normalize_delay_ms(delay_cs, &config);
278                        cursor += 4;
279                    } else if cursor.saturating_add(block_size) <= bytes.len() {
280                        cursor += block_size;
281                    } else {
282                        return Err(GIF_ERR_TRUNC_SUB.to_string());
283                    }
284                    cursor = Self::skip_subblocks(bytes, cursor)?;
285                } else if label == GIF_EXT_APP {
286                    if cursor >= bytes.len() {
287                        return Err(GIF_ERR_TRUNC_SUB.to_string());
288                    }
289                    let app_len: usize = bytes[cursor] as usize;
290                    cursor += 1;
291                    if cursor.saturating_add(app_len) > bytes.len() {
292                        return Err(GIF_ERR_TRUNC_SUB.to_string());
293                    }
294                    let app_id: &[u8] = &bytes[cursor..(cursor + app_len)];
295                    cursor += app_len;
296                    let is_netscape: bool = app_id == GIF_NETSCAPE_20 || app_id == GIF_ANIMEXTS_10;
297                    let mut parsed_first_sub: bool = false;
298                    loop {
299                        if cursor >= bytes.len() {
300                            return Err(GIF_ERR_TRUNC_SUB.to_string());
301                        }
302                        let sub_len: usize = bytes[cursor] as usize;
303                        cursor += 1;
304                        if sub_len == 0 {
305                            break;
306                        }
307                        if cursor.saturating_add(sub_len) > bytes.len() {
308                            return Err(GIF_ERR_TRUNC_SUB.to_string());
309                        }
310                        if is_netscape && !parsed_first_sub && sub_len >= 3 && bytes[cursor] == 0x01
311                        {
312                            loop_count =
313                                u16::from_le_bytes([bytes[cursor + 1], bytes[cursor + 2]]) as u32;
314                            has_netscape_loop = true;
315                        }
316                        parsed_first_sub = true;
317                        cursor += sub_len;
318                    }
319                } else {
320                    cursor = Self::skip_subblocks(bytes, cursor)?;
321                }
322            } else if intro == GIF_IMG_INTRO {
323                if cursor + 9 > bytes.len() {
324                    return Err(GIF_ERR_TRUNC_IMG.to_string());
325                }
326                let left: u16 = u16::from_le_bytes([bytes[cursor], bytes[cursor + 1]]);
327                let top: u16 = u16::from_le_bytes([bytes[cursor + 2], bytes[cursor + 3]]);
328                let width: u16 = u16::from_le_bytes([bytes[cursor + 4], bytes[cursor + 5]]);
329                let height: u16 = u16::from_le_bytes([bytes[cursor + 6], bytes[cursor + 7]]);
330                let img_packed: u8 = bytes[cursor + 8];
331                cursor += 9;
332                let has_lct: bool = (img_packed & 0x80) != 0;
333                let interlaced: bool = (img_packed & 0x40) != 0;
334                let lct_range: Option<(usize, usize)> = if has_lct {
335                    let lct_entries: usize = 1_usize << ((img_packed & 0x07) + 1);
336                    let lct_bytes: usize = lct_entries * 3;
337                    if cursor.saturating_add(lct_bytes) > bytes.len() {
338                        return Err(GIF_ERR_TRUNC_LCT.to_string());
339                    }
340                    let start: usize = cursor;
341                    cursor += lct_bytes;
342                    Some((start, cursor))
343                } else {
344                    None
345                };
346                if lct_range.is_none() && global_color_table.is_empty() {
347                    return Err(GIF_ERR_NO_PALETTE.to_string());
348                }
349                if cursor >= bytes.len() {
350                    return Err(GIF_ERR_LZW_MIN.to_string());
351                }
352                let lzw_min_code_size: u8 = bytes[cursor];
353                cursor += 1;
354                if !(2..=8).contains(&lzw_min_code_size) {
355                    return Err(GIF_ERR_LZW_MIN.to_string());
356                }
357                let lzw_data_start: usize = cursor;
358                cursor = Self::skip_subblocks(bytes, cursor)?;
359                let lzw_data_end: usize = cursor;
360                let frame_index: usize = frames.len();
361                frames.push(GifFrameDescriptor {
362                    index: frame_index,
363                    left,
364                    top,
365                    width,
366                    height,
367                    interlaced,
368                    disposal: next_disposal,
369                    transparent_index: next_transparent,
370                    delay_ms: next_delay_ms,
371                    timestamp_ms: timeline_ms,
372                    lct_range,
373                    lzw_min_code_size,
374                    lzw_data_start,
375                    lzw_data_end,
376                });
377                timeline_ms = timeline_ms.saturating_add(next_delay_ms);
378                next_disposal = GifDisposalMethod::Unspecified;
379                next_transparent = None;
380                next_delay_ms = Self::normalize_delay_ms(0, &config);
381            } else {
382                continue;
383            }
384        }
385        if frames.is_empty() {
386            return Err(GIF_ERR_NO_FRAMES.to_string());
387        }
388        Ok(Self {
389            bytes: Arc::from(bytes),
390            version,
391            logical_width,
392            logical_height,
393            background_color_index,
394            global_color_table,
395            has_netscape_loop,
396            loop_count,
397            frames,
398            config,
399        })
400    }
401
402    /// Returns a zero-copy borrowed slice over the backing encoded GIF stream bytes.
403    ///
404    /// # Arguments
405    ///
406    /// - `&Self` - GIF decoder reference.
407    ///
408    /// # Returns
409    ///
410    /// - `&[u8]` - Backing GIF byte stream.
411    #[must_use]
412    pub fn get_bytes(&self) -> &[u8] {
413        self.bytes.as_ref()
414    }
415
416    /// Normalizes a GIF89a centisecond frame delay according to `GifDecodeConfig`.
417    ///
418    /// # Arguments
419    ///
420    /// - `u16` - Raw delay in `1/100 s` centiseconds.
421    /// - `&GifDecodeConfig` - Compatibility policy.
422    ///
423    /// # Returns
424    ///
425    /// - `u32` - Effective millisecond frame delay.
426    #[must_use]
427    pub fn normalize_delay_ms(delay_cs: u16, config: &GifDecodeConfig) -> u32 {
428        let raw_ms: u32 = (delay_cs as u32).saturating_mul(10);
429        if config.get_strict_delays() {
430            return raw_ms;
431        }
432        if delay_cs <= 1 {
433            config.get_zero_delay_fallback_ms().max(1)
434        } else {
435            raw_ms.max(config.get_min_delay_ms())
436        }
437    }
438
439    /// Advances past a sequence of GIF length-prefixed data sub-blocks terminated by a `0x00` byte.
440    ///
441    /// # Arguments
442    ///
443    /// - `&[u8]` - Full GIF stream bytes.
444    /// - `usize` - Starting byte offset at the first sub-block length byte.
445    ///
446    /// # Returns
447    ///
448    /// - `Result<usize, String>` - Offset immediately after the `0x00` terminator or truncation error.
449    fn skip_subblocks(bytes: &[u8], mut cursor: usize) -> Result<usize, String> {
450        loop {
451            if cursor >= bytes.len() {
452                return Err(GIF_ERR_TRUNC_SUB.to_string());
453            }
454            let sub_len: usize = bytes[cursor] as usize;
455            cursor += 1;
456            if sub_len == 0 {
457                return Ok(cursor);
458            }
459            if cursor.saturating_add(sub_len) > bytes.len() {
460                return Err(GIF_ERR_TRUNC_SUB.to_string());
461            }
462            cursor += sub_len;
463        }
464    }
465
466    /// Decompresses variable-width GIF LZW sub-blocks directly into `out_indices` without copying sub-blocks.
467    ///
468    /// # Arguments
469    ///
470    /// - `&[u8]` - Raw sub-block byte slice starting at the first sub-block length byte.
471    /// - `u8` - Initial LZW minimum code size (`2..=8`).
472    /// - `usize` - Expected pixel index count (`frame_width * frame_height`).
473    /// - `&mut Vec<u8>` - Reusable destination palette-index vector cleared and populated in place.
474    ///
475    /// # Returns
476    ///
477    /// - `Result<(), String>` - `Ok(())` on exact decompression, or `Err` on corrupt/truncated LZW data.
478    pub fn decode_lzw_subblocks(
479        subblocks: &[u8],
480        min_code_size: u8,
481        expected_pixels: usize,
482        out_indices: &mut Vec<u8>,
483    ) -> Result<(), String> {
484        if !(2..=8).contains(&min_code_size) {
485            return Err(GIF_ERR_LZW_MIN.to_string());
486        }
487        out_indices.clear();
488        if expected_pixels == 0 {
489            return Ok(());
490        }
491        if out_indices.capacity() < expected_pixels {
492            out_indices.reserve(expected_pixels - out_indices.capacity());
493        }
494        let clear_code: u16 = 1_u16 << min_code_size;
495        let eoi_code: u16 = clear_code + 1;
496        let mut code_size: u8 = min_code_size + 1;
497        let mut next_code: u16 = eoi_code + 1;
498        let mut prefix: [u16; GIF_LZW_MAX_TABLE] = [0; GIF_LZW_MAX_TABLE];
499        let mut suffix: [u8; GIF_LZW_MAX_TABLE] = [0; GIF_LZW_MAX_TABLE];
500        let mut stack: [u8; GIF_LZW_MAX_TABLE] = [0; GIF_LZW_MAX_TABLE];
501        for (item_index, slot) in suffix.iter_mut().enumerate().take(clear_code as usize) {
502            *slot = item_index as u8;
503        }
504        let mut sub_cursor: usize = 0;
505        let mut cur_block_end: usize = 0;
506        let mut cur_byte_pos: usize = 0;
507        let mut bit_buf: u32 = 0;
508        let mut bit_count: u8 = 0;
509        let mut prev_code: Option<u16> = None;
510        let mut first_char: u8 = 0;
511        let mut saw_any_byte: bool = false;
512        while out_indices.len() < expected_pixels {
513            while bit_count < code_size {
514                while cur_byte_pos >= cur_block_end {
515                    if sub_cursor >= subblocks.len() {
516                        if out_indices.len() == expected_pixels {
517                            return Ok(());
518                        }
519                        return Err(GIF_ERR_LZW_EMPTY.to_string());
520                    }
521                    let block_len: usize = subblocks[sub_cursor] as usize;
522                    sub_cursor += 1;
523                    if block_len == 0 {
524                        if out_indices.len() == expected_pixels {
525                            return Ok(());
526                        }
527                        return Err(GIF_ERR_LZW_EMPTY.to_string());
528                    }
529                    if sub_cursor.saturating_add(block_len) > subblocks.len() {
530                        return Err(GIF_ERR_TRUNC_SUB.to_string());
531                    }
532                    cur_byte_pos = sub_cursor;
533                    cur_block_end = sub_cursor + block_len;
534                    sub_cursor = cur_block_end;
535                }
536                let byte: u8 = subblocks[cur_byte_pos];
537                cur_byte_pos += 1;
538                saw_any_byte = true;
539                bit_buf |= (byte as u32) << bit_count;
540                bit_count += 8;
541            }
542            let mask: u32 = (1_u32 << code_size) - 1;
543            let code: u16 = (bit_buf & mask) as u16;
544            bit_buf >>= code_size;
545            bit_count -= code_size;
546            if code == clear_code {
547                code_size = min_code_size + 1;
548                next_code = eoi_code + 1;
549                prev_code = None;
550                continue;
551            }
552            if code == eoi_code {
553                break;
554            }
555            if prev_code.is_none() {
556                if code >= clear_code {
557                    return Err(GIF_ERR_LZW_CODE.to_string());
558                }
559                let ch: u8 = code as u8;
560                out_indices.push(ch);
561                first_char = ch;
562                prev_code = Some(code);
563                continue;
564            }
565            let mut sp: usize = 0;
566            let mut cur: u16 = code;
567            if cur >= next_code {
568                if cur != next_code {
569                    return Err(GIF_ERR_LZW_CODE.to_string());
570                }
571                if sp >= GIF_LZW_MAX_TABLE {
572                    return Err(GIF_ERR_LZW_CODE.to_string());
573                }
574                stack[sp] = first_char;
575                sp += 1;
576                let Some(point_val) = prev_code else {
577                    return Err(GIF_ERR_LZW_CODE.to_string());
578                };
579                cur = point_val;
580            }
581            while cur >= clear_code {
582                if (cur as usize) >= GIF_LZW_MAX_TABLE || sp >= GIF_LZW_MAX_TABLE {
583                    return Err(GIF_ERR_LZW_CODE.to_string());
584                }
585                stack[sp] = suffix[cur as usize];
586                sp += 1;
587                cur = prefix[cur as usize];
588            }
589            first_char = suffix[cur as usize];
590            if sp < GIF_LZW_MAX_TABLE {
591                stack[sp] = first_char;
592                sp += 1;
593            }
594            while sp > 0 && out_indices.len() < expected_pixels {
595                sp -= 1;
596                out_indices.push(stack[sp]);
597            }
598            if let Some(palette_val) = prev_code
599                && (next_code as usize) < GIF_LZW_MAX_TABLE
600            {
601                prefix[next_code as usize] = palette_val;
602                suffix[next_code as usize] = first_char;
603                next_code += 1;
604                if next_code == (1_u16 << code_size) && code_size < GIF_LZW_MAX_BITS {
605                    code_size += 1;
606                }
607            }
608            prev_code = Some(code);
609        }
610        if !saw_any_byte || out_indices.len() < expected_pixels {
611            return Err(GIF_ERR_LZW_EMPTY.to_string());
612        }
613        Ok(())
614    }
615
616    /// Maps an interlaced decoded row index `src_row` to its visual canvas row inside `0..height`.
617    ///
618    /// # Arguments
619    ///
620    /// - `usize` - Decoded row index in stream order.
621    /// - `usize` - Frame height in pixels.
622    ///
623    /// # Returns
624    ///
625    /// - `usize` - Target visual row index inside `0..height`.
626    #[must_use]
627    pub fn deinterlace_row(src_row: usize, height: usize) -> usize {
628        let mut remaining: usize = src_row;
629        for pass in 0..4 {
630            let start: usize = GIF_INTERLACE_STARTS[pass];
631            let step: usize = GIF_INTERLACE_STEPS[pass];
632            if start >= height {
633                continue;
634            }
635            let rows_in_pass: usize = (height - 1 - start) / step + 1;
636            if remaining < rows_in_pass {
637                return start + remaining * step;
638            }
639            remaining -= rows_in_pass;
640        }
641        src_row.min(height.saturating_sub(1))
642    }
643
644    /// Resolves RGB color for palette index `color_idx` against the frame's Local Color Table or fallback Global Color Table.
645    ///
646    /// # Arguments
647    ///
648    /// - `&Self` - GIF decoder reference.
649    /// - `&GifFrameDescriptor` - Active frame descriptor.
650    /// - `u8` - Palette index.
651    ///
652    /// # Returns
653    ///
654    /// - `[u8; 3]` - Resolved `[r, g, b]` color triplet (`[0, 0, 0]` if out of palette bounds).
655    #[must_use]
656    pub fn lookup_rgb(&self, desc: &GifFrameDescriptor, color_idx: u8) -> [u8; 3] {
657        let idx: usize = color_idx as usize;
658        if let Some((start, end)) = desc.local_color_table_range() {
659            let off: usize = start.saturating_add(idx.saturating_mul(3));
660            let raw: &[u8] = self.get_bytes();
661            if off + 3 <= end && off + 3 <= raw.len() {
662                return [raw[off], raw[off + 1], raw[off + 2]];
663            }
664            return [0, 0, 0];
665        }
666        self.get_global_color_table()
667            .get(idx)
668            .copied()
669            .unwrap_or([0, 0, 0])
670    }
671
672    /// Decodes all frames in sequence into a `GifAnimation` using a single reusable composite canvas.
673    ///
674    /// # Arguments
675    ///
676    /// - `&Self` - GIF decoder reference.
677    /// - `&str` - Asset title.
678    ///
679    /// # Returns
680    ///
681    /// - `Result<GifAnimation, String>` - Fully decoded `GifAnimation` with exact source dimensions and composited RGBA8 frames.
682    pub fn decode_all_animation(&self, title: &str) -> Result<GifAnimation, String> {
683        let mut player: GifStreamPlayer = GifStreamPlayer::from_decoder(self.clone());
684        let total: usize = self.get_frames().len();
685        let mut media_frames: Vec<MediaFrame> = Vec::with_capacity(total);
686        let mut total_ms: u32 = 0;
687        for idx in 0..total {
688            let decoded: GifDecodedFrame = player.decode_frame(idx)?;
689            total_ms = total_ms.saturating_add(decoded.get_delay_ms());
690            media_frames.push(MediaFrame {
691                image: decoded.get_image().clone(),
692                delay_ms: decoded.get_delay_ms(),
693                timestamp_secs: decoded.get_timestamp_secs(),
694            });
695        }
696        let width: u32 = self.get_logical_width() as u32;
697        let height: u32 = self.get_logical_height() as u32;
698        let frame_count: usize = media_frames.len();
699        Ok(GifAnimation {
700            frames: media_frames,
701            loop_count: self.get_loop_count(),
702            current_frame: 0,
703            elapsed_ms: 0,
704            playing: true,
705            metadata: MediaMetadata {
706                title: title.to_string(),
707                width,
708                height,
709                duration_secs: (total_ms as f32) / 1000.0,
710                page_count: 1,
711                frame_count,
712                sample_rate_hz: 0,
713                channels: 0,
714                format_label: format!("{} · {}f", self.get_version(), frame_count),
715            },
716        })
717    }
718}
719
720/// Reusable-canvas compositing, bounded pre-decode caching, disposal dirty reporting, and visibility pause/resume for `GifStreamPlayer`.
721impl GifStreamPlayer {
722    /// Creates a streaming GIF player directly from raw `.gif` bytes and `GifDecodeConfig`.
723    ///
724    /// # Arguments
725    ///
726    /// - `&[u8]` - Raw `.gif` file bytes.
727    /// - `GifDecodeConfig` - Memory budget and frame-delay compatibility policy.
728    ///
729    /// # Returns
730    ///
731    /// - `Result<Self, String>` - Initialized streaming GIF player or parse error.
732    pub fn from_bytes_with_config(bytes: &[u8], config: GifDecodeConfig) -> Result<Self, String> {
733        let decoder: GifDecoder = GifDecoder::parse_with_config(bytes, config)?;
734        Ok(Self::from_decoder(decoder))
735    }
736
737    /// Creates a streaming GIF player from an already-parsed `GifDecoder`.
738    ///
739    /// # Arguments
740    ///
741    /// - `GifDecoder` - Parsed GIF stream decoder.
742    ///
743    /// # Returns
744    ///
745    /// - `Self` - Initialized streaming GIF player with reusable canvas.
746    #[must_use]
747    pub fn from_decoder(decoder: GifDecoder) -> Self {
748        let width_val: usize = decoder.get_logical_width() as usize;
749        let height_val: usize = decoder.get_logical_height() as usize;
750        let canvas_len: usize = width_val.saturating_mul(height_val).saturating_mul(4);
751        Self {
752            decoder,
753            canvas: vec![0; canvas_len],
754            restore_snapshot: Vec::new(),
755            index_scratch: Vec::new(),
756            cache: VecDeque::new(),
757            cache_bytes: 0,
758            last_composited_index: None,
759            pending_disposal_rect: None,
760            pending_disposal: GifDisposalMethod::Unspecified,
761            current_frame: 0,
762            elapsed_ms: 0,
763            completed_loops: 0,
764            visible: true,
765            visibility_policy: GifVisibilityPolicy::PauseAndResumeFromCurrent,
766            status: GifPlaybackStatus::Playing,
767            last_dirty_rect: GifDirtyRect::new(0, 0, width_val as u32, height_val as u32),
768            cache_hits: 0,
769            decode_count: 0,
770        }
771    }
772
773    /// Updates viewport visibility, suspending pre-decoding and timing while off-screen and resuming cleanly per `visibility_policy`.
774    ///
775    /// # Arguments
776    ///
777    /// - `&Self` - Mutable streaming GIF player.
778    /// - `bool` - `true` when the GIF is visible on screen, `false` when off-screen or frozen.
779    pub fn set_visible(&mut self, visible: bool) {
780        let was_visible: bool = self.get_visible();
781        self.set_visible_flag(visible);
782        if !visible {
783            if self.get_status() == GifPlaybackStatus::Playing
784                || self.get_status() == GifPlaybackStatus::Ready
785            {
786                self.set_status(GifPlaybackStatus::PausedOffscreen);
787            }
788            return;
789        }
790        if !was_visible && self.get_status() == GifPlaybackStatus::PausedOffscreen {
791            if self.get_visibility_policy() == GifVisibilityPolicy::PauseAndRestart {
792                self.set_current_frame(0);
793                self.set_elapsed_ms(0);
794                self.set_completed_loops(0);
795            }
796            self.set_status(GifPlaybackStatus::Playing);
797        }
798    }
799
800    /// Internal helper updating the visibility boolean without name collision.
801    ///
802    /// # Arguments
803    ///
804    /// - `&Self` - Mutable streaming GIF player.
805    /// - `bool` - New visibility state.
806    fn set_visible_flag(&mut self, value: bool) {
807        let Self { visible, .. } = self;
808        *visible = value;
809    }
810
811    /// Pre-decodes up to `window` upcoming frames into the bounded cache when visible (no-op when off-screen).
812    ///
813    /// # Arguments
814    ///
815    /// - `&Self` - Mutable streaming GIF player.
816    /// - `usize` - Maximum number of upcoming frames to pre-decode.
817    ///
818    /// # Returns
819    ///
820    /// - `Result<usize, String>` - Number of frames present in the cache after pre-decoding.
821    pub fn predecode_upcoming(&mut self, window: usize) -> Result<usize, String> {
822        if !self.get_visible() || self.get_status() == GifPlaybackStatus::Corrupt {
823            return Ok(self.get_cache().len());
824        }
825        let total: usize = self.get_decoder().get_frames().len();
826        if total == 0 {
827            return Ok(0);
828        }
829        let limit: usize = window
830            .min(self.get_decoder().get_config().get_max_predecode_frames())
831            .min(total);
832        let start: usize = self.get_current_frame();
833        for offset in 0..limit {
834            let idx: usize = (start + offset) % total;
835            let _: GifDecodedFrame = self.decode_frame(idx)?;
836        }
837        Ok(self.get_cache().len())
838    }
839
840    /// Advances playback by `dt_ms` milliseconds when visible and playing, returning `Some(GifDecodedFrame)` whenever the active frame updates.
841    ///
842    /// # Arguments
843    ///
844    /// - `&Self` - Mutable streaming GIF player.
845    /// - `u32` - Elapsed wall time in milliseconds.
846    ///
847    /// # Returns
848    ///
849    /// - `Result<Option<GifDecodedFrame>, String>` - Newly active composited frame and dirty region, or `None` when unchanged/paused/off-screen.
850    pub fn step_ms(&mut self, dt_ms: u32) -> Result<Option<GifDecodedFrame>, String> {
851        if !self.get_visible() || self.get_status() != GifPlaybackStatus::Playing {
852            return Ok(None);
853        }
854        let total: usize = self.get_decoder().get_frames().len();
855        if total == 0 {
856            return Ok(None);
857        }
858        let cur: usize = self.get_current_frame() % total;
859        let delay: u32 = self.get_decoder().get_frames()[cur].get_delay_ms().max(1);
860        let next_elapsed: u32 = self.get_elapsed_ms().saturating_add(dt_ms);
861        if next_elapsed < delay {
862            self.set_elapsed_ms(next_elapsed);
863            return Ok(None);
864        }
865        let remainder: u32 = next_elapsed - delay;
866        let next_idx: usize = cur + 1;
867        if next_idx >= total {
868            let max_loops: u32 = self.get_decoder().get_loop_count();
869            let completed: u32 = self.get_completed_loops().saturating_add(1);
870            self.set_completed_loops(completed);
871            if self.get_decoder().get_has_netscape_loop() && max_loops > 0 && completed >= max_loops
872            {
873                self.set_elapsed_ms(0);
874                self.set_status(GifPlaybackStatus::Ended);
875                return Ok(None);
876            }
877            self.set_current_frame(0);
878            self.set_elapsed_ms(remainder);
879            let frame: GifDecodedFrame = self.decode_frame(0)?;
880            self.set_last_dirty_rect(frame.get_dirty_rect());
881            return Ok(Some(frame));
882        }
883        self.set_current_frame(next_idx);
884        self.set_elapsed_ms(remainder);
885        let frame: GifDecodedFrame = self.decode_frame(next_idx)?;
886        self.set_last_dirty_rect(frame.get_dirty_rect());
887        Ok(Some(frame))
888    }
889
890    /// Returns the composited `GifDecodedFrame` for `target_index`, hitting the bounded cache when available or compositing sequentially on the reusable canvas.
891    ///
892    /// # Arguments
893    ///
894    /// - `&Self` - Mutable streaming GIF player.
895    /// - `usize` - Zero-based frame index.
896    ///
897    /// # Returns
898    ///
899    /// - `Result<GifDecodedFrame, String>` - Composited frame with disposal-aware dirty rectangle or decode error.
900    pub fn decode_frame(&mut self, target_index: usize) -> Result<GifDecodedFrame, String> {
901        let total: usize = self.get_decoder().get_frames().len();
902        if target_index >= total {
903            return Err(GIF_ERR_FRAME_OOB.to_string());
904        }
905        if let Some(pos) = self
906            .get_cache()
907            .iter()
908            .position(|entry: &GifDecodedFrame| entry.get_frame_index() == target_index)
909        {
910            let cached: GifDecodedFrame = if pos + 1 == self.get_cache().len() {
911                self.get_cache()[pos].clone()
912            } else if let Some(entry) = self.get_mut_cache().remove(pos) {
913                let shared_copy: GifDecodedFrame = entry.clone();
914                self.get_mut_cache().push_back(entry);
915                shared_copy
916            } else {
917                return Err(GIF_ERR_FRAME_OOB.to_string());
918            };
919            let next_hits: u64 = self.get_cache_hits().saturating_add(1);
920            self.set_cache_hits(next_hits);
921            self.set_last_dirty_rect(cached.get_dirty_rect());
922            return Ok(cached);
923        }
924        let last_idx: Option<usize> = {
925            let Self {
926                last_composited_index,
927                ..
928            } = self;
929            *last_composited_index
930        };
931        let start_from: usize = match last_idx {
932            Some(prev) if prev < target_index => prev + 1,
933            _ => {
934                self.reset_canvas_state();
935                0
936            }
937        };
938        let mut latest_frame: Option<GifDecodedFrame> = None;
939        for step_idx in start_from..=target_index {
940            match self.composite_next_frame(step_idx) {
941                Ok(decoded) => {
942                    self.insert_cache_bounded(decoded.clone());
943                    latest_frame = Some(decoded);
944                }
945                Err(err) => {
946                    self.set_status(GifPlaybackStatus::Corrupt);
947                    return Err(err);
948                }
949            }
950        }
951        let Some(frame) = latest_frame else {
952            return Err(GIF_ERR_FRAME_OOB.to_string());
953        };
954        self.set_last_dirty_rect(frame.get_dirty_rect());
955        Ok(frame)
956    }
957
958    /// Resets the reusable composite canvas and pending disposal state back to a clean transparent screen.
959    ///
960    /// # Arguments
961    ///
962    /// - `&Self` - Mutable streaming GIF player.
963    fn reset_canvas_state(&mut self) {
964        self.get_mut_canvas().fill(0);
965        let Self {
966            last_composited_index,
967            pending_disposal_rect,
968            restore_snapshot,
969            ..
970        } = self;
971        *last_composited_index = None;
972        *pending_disposal_rect = None;
973        restore_snapshot.clear();
974        self.set_pending_disposal(GifDisposalMethod::Unspecified);
975    }
976
977    /// Composites frame `frame_idx` onto `self.canvas`, applying the prior frame's disposal and computing the exact dirty region.
978    ///
979    /// # Arguments
980    ///
981    /// - `&Self` - Mutable streaming GIF player.
982    /// - `usize` - Sequential frame index to composite.
983    ///
984    /// # Returns
985    ///
986    /// - `Result<GifDecodedFrame, String>` - Composited RGBA8 frame and disposal-aware dirty rectangle.
987    fn composite_next_frame(&mut self, frame_idx: usize) -> Result<GifDecodedFrame, String> {
988        let canvas_w: u32 = self.get_decoder().get_logical_width() as u32;
989        let canvas_h: u32 = self.get_decoder().get_logical_height() as u32;
990        let desc: GifFrameDescriptor = self.get_decoder().get_frames()[frame_idx];
991        let mut dirty_rect: GifDirtyRect = if frame_idx == 0 {
992            GifDirtyRect::new(0, 0, canvas_w, canvas_h)
993        } else {
994            GifDirtyRect::default()
995        };
996        let prev_disposal: GifDisposalMethod = self.get_pending_disposal();
997        let prev_rect_opt: Option<GifDirtyRect> = {
998            let Self {
999                pending_disposal_rect,
1000                ..
1001            } = self;
1002            *pending_disposal_rect
1003        };
1004        if let Some(prev_rect) = prev_rect_opt {
1005            match prev_disposal {
1006                GifDisposalMethod::RestoreToBackground => {
1007                    Self::clear_canvas_rect(
1008                        self.get_mut_canvas().as_mut_slice(),
1009                        canvas_w as usize,
1010                        prev_rect,
1011                    );
1012                    dirty_rect = dirty_rect.union(prev_rect);
1013                }
1014                GifDisposalMethod::RestoreToPrevious => {
1015                    let Self {
1016                        canvas,
1017                        restore_snapshot,
1018                        ..
1019                    } = self;
1020                    if restore_snapshot.len() == canvas.len() {
1021                        canvas.copy_from_slice(restore_snapshot.as_slice());
1022                    }
1023                    dirty_rect = dirty_rect.union(prev_rect);
1024                }
1025                GifDisposalMethod::Unspecified | GifDisposalMethod::Keep => {}
1026            }
1027        }
1028        if desc.get_disposal() == GifDisposalMethod::RestoreToPrevious {
1029            let Self {
1030                canvas,
1031                restore_snapshot,
1032                ..
1033            } = self;
1034            if restore_snapshot.len() != canvas.len() {
1035                restore_snapshot.resize(canvas.len(), 0);
1036            }
1037            restore_snapshot.copy_from_slice(canvas.as_slice());
1038        }
1039        let expected_pixels: usize =
1040            (desc.get_width() as usize).saturating_mul(desc.get_height() as usize);
1041        {
1042            let Self {
1043                decoder,
1044                index_scratch,
1045                ..
1046            } = self;
1047            let raw_subblocks: &[u8] =
1048                &decoder.get_bytes()[desc.get_lzw_data_start()..desc.get_lzw_data_end()];
1049            GifDecoder::decode_lzw_subblocks(
1050                raw_subblocks,
1051                desc.get_lzw_min_code_size(),
1052                expected_pixels,
1053                index_scratch,
1054            )?;
1055        }
1056        let sub_rect: GifDirtyRect = GifDirtyRect::clipped_subframe(
1057            desc.get_left(),
1058            desc.get_top(),
1059            desc.get_width(),
1060            desc.get_height(),
1061            canvas_w,
1062            canvas_h,
1063        );
1064        dirty_rect = dirty_rect.union(sub_rect);
1065        let fw: usize = desc.get_width() as usize;
1066        let fh: usize = desc.get_height() as usize;
1067        let left: usize = desc.get_left() as usize;
1068        let top: usize = desc.get_top() as usize;
1069        let cw: usize = canvas_w as usize;
1070        let ch: usize = canvas_h as usize;
1071        let interlaced: bool = desc.get_interlaced();
1072        let transparent_idx: Option<u8> = desc.transparent_color_index();
1073        let Self {
1074            decoder,
1075            canvas,
1076            index_scratch,
1077            ..
1078        } = self;
1079        for src_row in 0..fh {
1080            let local_y: usize = if interlaced {
1081                GifDecoder::deinterlace_row(src_row, fh)
1082            } else {
1083                src_row
1084            };
1085            let dst_y: usize = top.saturating_add(local_y);
1086            if dst_y >= ch {
1087                continue;
1088            }
1089            let src_row_off: usize = src_row * fw;
1090            let dst_row_off: usize = dst_y * cw;
1091            for local_x in 0..fw {
1092                let dst_x: usize = left.saturating_add(local_x);
1093                if dst_x >= cw {
1094                    break;
1095                }
1096                let pal_idx: u8 = index_scratch[src_row_off + local_x];
1097                if transparent_idx == Some(pal_idx) {
1098                    continue;
1099                }
1100                let rgb: [u8; 3] = decoder.lookup_rgb(&desc, pal_idx);
1101                let out_off: usize = (dst_row_off + dst_x) * 4;
1102                canvas[out_off] = rgb[0];
1103                canvas[out_off + 1] = rgb[1];
1104                canvas[out_off + 2] = rgb[2];
1105                canvas[out_off + 3] = 255;
1106            }
1107        }
1108        let Self {
1109            last_composited_index,
1110            pending_disposal_rect,
1111            ..
1112        } = self;
1113        *last_composited_index = Some(frame_idx);
1114        *pending_disposal_rect = Some(sub_rect);
1115        self.set_pending_disposal(desc.get_disposal());
1116        let next_decodes: u64 = self.get_decode_count().saturating_add(1);
1117        self.set_decode_count(next_decodes);
1118        let image: ImageBuffer = ImageBuffer::new(canvas_w, canvas_h, self.get_canvas().as_slice());
1119        Ok(GifDecodedFrame {
1120            frame_index: frame_idx,
1121            image,
1122            delay_ms: desc.get_delay_ms(),
1123            timestamp_secs: (desc.get_timestamp_ms() as f32) / 1000.0,
1124            dirty_rect,
1125            disposal: desc.get_disposal(),
1126        })
1127    }
1128
1129    /// Clears all RGBA pixels inside `rect` on `canvas` to transparent `[0, 0, 0, 0]`.
1130    ///
1131    /// # Arguments
1132    ///
1133    /// - `&mut [u8]` - Full RGBA8 canvas buffer.
1134    /// - `usize` - Canvas width in pixels.
1135    /// - `GifDirtyRect` - Sub-rectangle to clear.
1136    fn clear_canvas_rect(canvas: &mut [u8], canvas_w: usize, rect: GifDirtyRect) {
1137        if rect.is_empty() || canvas_w == 0 {
1138            return;
1139        }
1140        let x0: usize = rect.get_x() as usize;
1141        let y0: usize = rect.get_y() as usize;
1142        let rw: usize = rect.get_width() as usize;
1143        let rh: usize = rect.get_height() as usize;
1144        let row_bytes: usize = rw * 4;
1145        for dy in 0..rh {
1146            let start: usize = ((y0 + dy) * canvas_w + x0) * 4;
1147            let end: usize = start.saturating_add(row_bytes).min(canvas.len());
1148            if start < end {
1149                canvas[start..end].fill(0);
1150            }
1151        }
1152    }
1153
1154    /// Inserts `frame` into the bounded pre-decode cache, evicting oldest entries whenever frame count or byte budgets are exceeded.
1155    ///
1156    /// # Arguments
1157    ///
1158    /// - `&Self` - Mutable streaming GIF player.
1159    /// - `GifDecodedFrame` - Composited frame to cache.
1160    fn insert_cache_bounded(&mut self, frame: GifDecodedFrame) {
1161        let config_spec: GifDecodeConfig = self.get_decoder().get_config();
1162        let frame_bytes: usize = frame.get_image().get_pixels().len();
1163        if config_spec.get_max_predecode_frames() == 0
1164            || frame_bytes > config_spec.get_max_cache_bytes()
1165        {
1166            return;
1167        }
1168        if self.get_cache().iter().any(|event_ref: &GifDecodedFrame| {
1169            event_ref.get_frame_index() == frame.get_frame_index()
1170        }) {
1171            return;
1172        }
1173        while !self.get_cache().is_empty()
1174            && (self.get_cache().len() >= config_spec.get_max_predecode_frames()
1175                || self.get_cache_bytes().saturating_add(frame_bytes)
1176                    > config_spec.get_max_cache_bytes())
1177        {
1178            let Some(evicted) = self.get_mut_cache().pop_front() else {
1179                break;
1180            };
1181            let next_bytes: usize = self
1182                .get_cache_bytes()
1183                .saturating_sub(evicted.get_image().get_pixels().len());
1184            self.set_cache_bytes(next_bytes);
1185        }
1186        let next_bytes: usize = self.get_cache_bytes().saturating_add(frame_bytes);
1187        self.set_cache_bytes(next_bytes);
1188        self.get_mut_cache().push_back(frame);
1189    }
1190}
1191
1192/// Optional field accessors for `GifEncodeFrameInput`.
1193impl GifEncodeFrameInput {
1194    /// Returns the optional transparent palette index.
1195    ///
1196    /// # Arguments
1197    ///
1198    /// - `&Self` - Encode frame descriptor reference.
1199    ///
1200    /// # Returns
1201    ///
1202    /// - `Option<u8>` - Transparent palette index if set.
1203    #[must_use]
1204    pub const fn transparent_color_index(&self) -> Option<u8> {
1205        let Self {
1206            transparent_index, ..
1207        } = *self;
1208        transparent_index
1209    }
1210
1211    /// Returns the optional frame-specific local palette.
1212    ///
1213    /// # Arguments
1214    ///
1215    /// - `&Self` - Encode frame descriptor reference.
1216    ///
1217    /// # Returns
1218    ///
1219    /// - `Option<&[[u8; 3]]>` - Borrowed local palette slice if set.
1220    #[must_use]
1221    pub fn local_palette_slice(&self) -> Option<&[[u8; 3]]> {
1222        let Self { local_palette, .. } = self;
1223        local_palette.as_deref()
1224    }
1225}
1226
1227/// Generation-stamped O(1) flat LZW dictionary operations for `GifLzwEncodeScratch`.
1228impl GifLzwEncodeScratch {
1229    /// Allocates a single reusable flat LZW dictionary table and bitstream buffer for an encode pass.
1230    ///
1231    /// # Returns
1232    ///
1233    /// - `Self` - Ready scratch state.
1234    #[must_use]
1235    fn new_scratch() -> Self {
1236        Self {
1237            table: vec![0; GIF_LZW_HASH_TABLE_SIZE],
1238            generation: 1,
1239            packed_bytes: Vec::new(),
1240        }
1241    }
1242
1243    /// Invalidates all entries in the flat LZW dictionary table in O(1) time via generation bump.
1244    ///
1245    /// # Arguments
1246    ///
1247    /// - `&Self` - Mutable LZW encode scratch.
1248    fn reset_table(&mut self) {
1249        let next_gen: u32 = self.get_generation().wrapping_add(1);
1250        if next_gen == 0 {
1251            self.get_mut_table().fill(0);
1252            self.set_generation(1);
1253        } else {
1254            self.set_generation(next_gen);
1255        }
1256    }
1257
1258    /// Looks up `(prefix, sym)` in the fixed flat LZW table and optionally inserts `next_code` on miss.
1259    ///
1260    /// # Arguments
1261    ///
1262    /// - `&Self` - Mutable LZW encode scratch.
1263    /// - `u16` - Active LZW prefix code (`< 4096`).
1264    /// - `u8` - Next palette index symbol.
1265    /// - `u16` - Code value to record if absent and `can_insert` is `true`.
1266    /// - `bool` - Whether the dictionary has room to insert a new entry (`next_code < 4096`).
1267    ///
1268    /// # Returns
1269    ///
1270    /// - `Option<u16>` - Existing code on hit, or `None` on miss.
1271    fn find_or_insert(
1272        &mut self,
1273        prefix: u16,
1274        sym: u8,
1275        next_code: u16,
1276        can_insert: bool,
1277    ) -> Option<u16> {
1278        let key: u32 = ((prefix as u32) << 8) | (sym as u32);
1279        let cur_gen: u32 = self.get_generation();
1280        let table: &mut [u64] = self.get_mut_table().as_mut_slice();
1281        let mut slot: usize = (((key.wrapping_mul(GIF_LZW_HASH_MULT)) >> GIF_LZW_HASH_SHIFT)
1282            as usize)
1283            & GIF_LZW_HASH_TABLE_MASK;
1284        loop {
1285            let entry: u64 = table[slot];
1286            if ((entry >> 32) as u32) != cur_gen {
1287                if can_insert {
1288                    table[slot] = ((cur_gen as u64) << 32)
1289                        | (((next_code as u64) & GIF_LZW_CODE_MASK) << 20)
1290                        | (key as u64);
1291                }
1292                return None;
1293            }
1294            if ((entry & GIF_LZW_KEY_MASK) as u32) == key {
1295                return Some(((entry >> 20) & GIF_LZW_CODE_MASK) as u16);
1296            }
1297            slot = (slot + 1) & GIF_LZW_HASH_TABLE_MASK;
1298        }
1299    }
1300}
1301
1302/// Spec-compliant pure-Rust GIF89a LZW encoding for `GifEncoder`.
1303impl GifEncoder {
1304    /// Computes the power-of-two color table bits `(table_size_code, padded_entries, min_lzw_bits)` for a palette of length `len`.
1305    ///
1306    /// # Arguments
1307    ///
1308    /// - `usize` - Number of RGB palette entries (`1..=256`).
1309    ///
1310    /// # Returns
1311    ///
1312    /// - `(u8, usize, u8)` - `(packed_size_bits, padded_table_entries, lzw_min_code_size)`.
1313    #[must_use]
1314    fn palette_table_params(len: usize) -> (u8, usize, u8) {
1315        let clamped: usize = len.clamp(2, 256);
1316        let mut bits: u8 = 1;
1317        while (1_usize << bits) < clamped && bits < 8 {
1318            bits += 1;
1319        }
1320        let entries: usize = 1_usize << bits;
1321        let min_lzw: u8 = bits.max(2);
1322        (bits - 1, entries, min_lzw)
1323    }
1324
1325    /// Compresses `indices` into GIF variable-width LSB-first LZW data sub-blocks using a fixed reusable flat table.
1326    ///
1327    /// # Arguments
1328    ///
1329    /// - `&[u8]` - Stream-ordered palette indices.
1330    /// - `u8` - Initial LZW minimum code size (`2..=8`).
1331    /// - `&mut GifLzwEncodeScratch` - Reusable flat LZW dictionary table and packed byte scratch buffer.
1332    /// - `&mut Vec<u8>` - Destination GIF byte buffer.
1333    fn encode_lzw_subblocks(
1334        indices: &[u8],
1335        min_code_size: u8,
1336        scratch: &mut GifLzwEncodeScratch,
1337        out: &mut Vec<u8>,
1338    ) {
1339        out.push(min_code_size);
1340        let clear_code: u16 = 1_u16 << min_code_size;
1341        let eoi_code: u16 = clear_code + 1;
1342        let mut code_size: u8 = min_code_size + 1;
1343        let mut next_code: u16 = eoi_code + 1;
1344        scratch.reset_table();
1345        scratch.get_mut_packed_bytes().clear();
1346        let needed_cap: usize = indices.len().saturating_add(16);
1347        if scratch.get_packed_bytes().capacity() < needed_cap {
1348            let extra: usize = needed_cap - scratch.get_packed_bytes().capacity();
1349            scratch.get_mut_packed_bytes().reserve(extra);
1350        }
1351        let mut bit_buf: u32 = 0;
1352        let mut bit_count: u8 = 0;
1353        Self::emit_lzw_code(
1354            clear_code,
1355            code_size,
1356            &mut bit_buf,
1357            &mut bit_count,
1358            scratch.get_mut_packed_bytes(),
1359        );
1360        if let Some(&first_px) = indices.first() {
1361            let mut prefix: u16 = first_px as u16;
1362            for &sym in indices[1..].iter() {
1363                let can_insert: bool = (next_code as usize) < GIF_LZW_MAX_TABLE;
1364                if let Some(existing) = scratch.find_or_insert(prefix, sym, next_code, can_insert) {
1365                    prefix = existing;
1366                } else {
1367                    Self::emit_lzw_code(
1368                        prefix,
1369                        code_size,
1370                        &mut bit_buf,
1371                        &mut bit_count,
1372                        scratch.get_mut_packed_bytes(),
1373                    );
1374                    if can_insert {
1375                        next_code += 1;
1376                        if next_code > (1_u16 << code_size) && code_size < GIF_LZW_MAX_BITS {
1377                            code_size += 1;
1378                        }
1379                    } else {
1380                        Self::emit_lzw_code(
1381                            clear_code,
1382                            code_size,
1383                            &mut bit_buf,
1384                            &mut bit_count,
1385                            scratch.get_mut_packed_bytes(),
1386                        );
1387                        scratch.reset_table();
1388                        code_size = min_code_size + 1;
1389                        next_code = eoi_code + 1;
1390                    }
1391                    prefix = sym as u16;
1392                }
1393            }
1394            Self::emit_lzw_code(
1395                prefix,
1396                code_size,
1397                &mut bit_buf,
1398                &mut bit_count,
1399                scratch.get_mut_packed_bytes(),
1400            );
1401        }
1402        Self::emit_lzw_code(
1403            eoi_code,
1404            code_size,
1405            &mut bit_buf,
1406            &mut bit_count,
1407            scratch.get_mut_packed_bytes(),
1408        );
1409        if bit_count > 0 {
1410            scratch.get_mut_packed_bytes().push((bit_buf & 0xFF) as u8);
1411        }
1412        for chunk in scratch.get_packed_bytes().chunks(255) {
1413            out.push(chunk.len() as u8);
1414            out.extend_from_slice(chunk);
1415        }
1416        out.push(0x00);
1417    }
1418
1419    /// Writes one variable-width LSB-first LZW code into the active bit buffer and flushes complete bytes.
1420    ///
1421    /// # Arguments
1422    ///
1423    /// - `u16` - LZW code value to emit.
1424    /// - `u8` - Active code width in bits.
1425    /// - `&mut u32` - Accumulated bit buffer.
1426    /// - `&mut u8` - Number of buffered bits currently held.
1427    /// - `&mut Vec<u8>` - Destination packed byte buffer.
1428    fn emit_lzw_code(code: u16, width: u8, buf: &mut u32, bits: &mut u8, dst: &mut Vec<u8>) {
1429        *buf |= (code as u32) << *bits;
1430        *bits += width;
1431        while *bits >= 8 {
1432            dst.push((*buf & 0xFF) as u8);
1433            *buf >>= 8;
1434            *bits -= 8;
1435        }
1436    }
1437
1438    /// Encodes a complete spec-compliant GIF89a animated image stream with LZW compression, Netscape loop count, GCE, interlacing, and local palettes.
1439    ///
1440    /// # Arguments
1441    ///
1442    /// - `u16` - Logical screen width in pixels.
1443    /// - `u16` - Logical screen height in pixels.
1444    /// - `&[[u8; 3]]` - Global Color Table RGB triplets (may be empty if every frame supplies a local palette).
1445    /// - `Option<u16>` - Optional Netscape 2.0 loop count (`Some(0)` = infinite, `Some(n)` = `n` loops).
1446    /// - `&[GifEncodeFrameInput]` - Ordered animation frames to encode.
1447    ///
1448    /// # Returns
1449    ///
1450    /// - `Vec<u8>` - Encoded GIF89a binary payload.
1451    #[must_use]
1452    pub fn encode(
1453        logical_width: u16,
1454        logical_height: u16,
1455        global_palette: &[[u8; 3]],
1456        netscape_loop: Option<u16>,
1457        frames: &[GifEncodeFrameInput],
1458    ) -> Vec<u8> {
1459        let mut out: Vec<u8> = Vec::new();
1460        out.extend_from_slice(MAGIC_GIF89A);
1461        out.extend_from_slice(&logical_width.to_le_bytes());
1462        out.extend_from_slice(&logical_height.to_le_bytes());
1463        let (gct_packed, gct_entries, gct_lzw_min): (u8, usize, u8) = if global_palette.is_empty() {
1464            (0x00, 0, 2)
1465        } else {
1466            let (sz_bits, entries, lzw_min): (u8, usize, u8) =
1467                Self::palette_table_params(global_palette.len());
1468            let gct_flags: u8 = 0xF0 | (sz_bits & 0x07);
1469            (gct_flags, entries, lzw_min)
1470        };
1471        out.push(gct_packed);
1472        out.push(0);
1473        out.push(0);
1474        for item_index in 0..gct_entries {
1475            let rgb: [u8; 3] = global_palette.get(item_index).copied().unwrap_or([0, 0, 0]);
1476            out.extend_from_slice(&rgb);
1477        }
1478        if let Some(loops) = netscape_loop {
1479            out.push(GIF_EXT_INTRO);
1480            out.push(GIF_EXT_APP);
1481            out.push(11);
1482            out.extend_from_slice(GIF_NETSCAPE_20);
1483            out.push(3);
1484            out.push(0x01);
1485            out.extend_from_slice(&loops.to_le_bytes());
1486            out.push(0x00);
1487        }
1488        let mut lzw_scratch: GifLzwEncodeScratch = GifLzwEncodeScratch::new_scratch();
1489        let mut frame_scratch: Vec<u8> = Vec::new();
1490        for frame in frames.iter() {
1491            let trans_opt: Option<u8> = frame.transparent_color_index();
1492            let gce_packed: u8 =
1493                (frame.get_disposal().to_gce_bits() << 2) | u8::from(trans_opt.is_some());
1494            out.push(GIF_EXT_INTRO);
1495            out.push(GIF_EXT_GCE);
1496            out.push(4);
1497            out.push(gce_packed);
1498            out.extend_from_slice(&frame.get_delay_cs().to_le_bytes());
1499            out.push(trans_opt.unwrap_or(0));
1500            out.push(0x00);
1501            out.push(GIF_IMG_INTRO);
1502            out.extend_from_slice(&frame.get_left().to_le_bytes());
1503            out.extend_from_slice(&frame.get_top().to_le_bytes());
1504            out.extend_from_slice(&frame.get_width().to_le_bytes());
1505            out.extend_from_slice(&frame.get_height().to_le_bytes());
1506            let (lct_flag_bits, lct_entries, lzw_min): (u8, usize, u8) =
1507                if let Some(lpal) = frame.local_palette_slice() {
1508                    let (sz_bits, entries, min_bits): (u8, usize, u8) =
1509                        Self::palette_table_params(lpal.len());
1510                    (0x80 | (sz_bits & 0x07), entries, min_bits)
1511                } else {
1512                    (0x00, 0, gct_lzw_min)
1513                };
1514            let interlace_bit: u8 = if frame.get_interlaced() { 0x40 } else { 0x00 };
1515            out.push(lct_flag_bits | interlace_bit);
1516            if let Some(lpal) = frame.local_palette_slice() {
1517                for outer_index in 0..lct_entries {
1518                    let rgb: [u8; 3] = lpal.get(outer_index).copied().unwrap_or([0, 0, 0]);
1519                    out.extend_from_slice(&rgb);
1520                }
1521            }
1522            let fw: usize = frame.get_width() as usize;
1523            let fh: usize = frame.get_height() as usize;
1524            let expected: usize = fw.saturating_mul(fh);
1525            let src_indices: &[u8] = frame.get_indices().as_slice();
1526            let stream_slice: &[u8] = if frame.get_interlaced() && fh > 0 && fw > 0 {
1527                frame_scratch.clear();
1528                if frame_scratch.capacity() < expected {
1529                    frame_scratch.reserve(expected - frame_scratch.capacity());
1530                }
1531                for pass in 0..4 {
1532                    let mut row: usize = GIF_INTERLACE_STARTS[pass];
1533                    let step: usize = GIF_INTERLACE_STEPS[pass];
1534                    while row < fh {
1535                        let start: usize = row * fw;
1536                        let end: usize = (start + fw).min(src_indices.len());
1537                        if start < end {
1538                            frame_scratch.extend_from_slice(&src_indices[start..end]);
1539                        }
1540                        while frame_scratch.len() < (frame_scratch.len().div_ceil(fw)) * fw {
1541                            frame_scratch.push(0);
1542                        }
1543                        row += step;
1544                    }
1545                }
1546                frame_scratch.resize(expected, 0);
1547                frame_scratch.as_slice()
1548            } else if src_indices.len() == expected {
1549                src_indices
1550            } else {
1551                frame_scratch.clear();
1552                let copy_len: usize = src_indices.len().min(expected);
1553                frame_scratch.extend_from_slice(&src_indices[..copy_len]);
1554                frame_scratch.resize(expected, 0);
1555                frame_scratch.as_slice()
1556            };
1557            Self::encode_lzw_subblocks(stream_slice, lzw_min, &mut lzw_scratch, &mut out);
1558        }
1559        out.push(GIF_TRAILER);
1560        out
1561    }
1562}