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 i in 0..gct_entries {
236                let off: usize = cursor + i * 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: bytes.to_vec(),
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    /// Normalizes a GIF89a centisecond frame delay according to `GifDecodeConfig`.
403    ///
404    /// # Arguments
405    ///
406    /// - `u16` - Raw delay in `1/100 s` centiseconds.
407    /// - `&GifDecodeConfig` - Compatibility policy.
408    ///
409    /// # Returns
410    ///
411    /// - `u32` - Effective millisecond frame delay.
412    #[must_use]
413    pub fn normalize_delay_ms(delay_cs: u16, config: &GifDecodeConfig) -> u32 {
414        let raw_ms: u32 = (delay_cs as u32).saturating_mul(10);
415        if config.get_strict_delays() {
416            return raw_ms;
417        }
418        if delay_cs <= 1 {
419            config.get_zero_delay_fallback_ms().max(1)
420        } else {
421            raw_ms.max(config.get_min_delay_ms())
422        }
423    }
424
425    /// Advances past a sequence of GIF length-prefixed data sub-blocks terminated by a `0x00` byte.
426    ///
427    /// # Arguments
428    ///
429    /// - `&[u8]` - Full GIF stream bytes.
430    /// - `usize` - Starting byte offset at the first sub-block length byte.
431    ///
432    /// # Returns
433    ///
434    /// - `Result<usize, String>` - Offset immediately after the `0x00` terminator or truncation error.
435    fn skip_subblocks(bytes: &[u8], mut cursor: usize) -> Result<usize, String> {
436        loop {
437            if cursor >= bytes.len() {
438                return Err(GIF_ERR_TRUNC_SUB.to_string());
439            }
440            let sub_len: usize = bytes[cursor] as usize;
441            cursor += 1;
442            if sub_len == 0 {
443                return Ok(cursor);
444            }
445            if cursor.saturating_add(sub_len) > bytes.len() {
446                return Err(GIF_ERR_TRUNC_SUB.to_string());
447            }
448            cursor += sub_len;
449        }
450    }
451
452    /// Decompresses variable-width GIF LZW sub-blocks directly into `out_indices` without copying sub-blocks.
453    ///
454    /// # Arguments
455    ///
456    /// - `&[u8]` - Raw sub-block byte slice starting at the first sub-block length byte.
457    /// - `u8` - Initial LZW minimum code size (`2..=8`).
458    /// - `usize` - Expected pixel index count (`frame_width * frame_height`).
459    /// - `&mut Vec<u8>` - Reusable destination palette-index vector cleared and populated in place.
460    ///
461    /// # Returns
462    ///
463    /// - `Result<(), String>` - `Ok(())` on exact decompression, or `Err` on corrupt/truncated LZW data.
464    pub fn decode_lzw_subblocks(
465        subblocks: &[u8],
466        min_code_size: u8,
467        expected_pixels: usize,
468        out_indices: &mut Vec<u8>,
469    ) -> Result<(), String> {
470        if !(2..=8).contains(&min_code_size) {
471            return Err(GIF_ERR_LZW_MIN.to_string());
472        }
473        out_indices.clear();
474        if expected_pixels == 0 {
475            return Ok(());
476        }
477        if out_indices.capacity() < expected_pixels {
478            out_indices.reserve(expected_pixels - out_indices.capacity());
479        }
480        let clear_code: u16 = 1_u16 << min_code_size;
481        let eoi_code: u16 = clear_code + 1;
482        let mut code_size: u8 = min_code_size + 1;
483        let mut next_code: u16 = eoi_code + 1;
484        let mut prefix: [u16; GIF_LZW_MAX_TABLE] = [0; GIF_LZW_MAX_TABLE];
485        let mut suffix: [u8; GIF_LZW_MAX_TABLE] = [0; GIF_LZW_MAX_TABLE];
486        let mut stack: [u8; GIF_LZW_MAX_TABLE] = [0; GIF_LZW_MAX_TABLE];
487        for (i, slot) in suffix.iter_mut().enumerate().take(clear_code as usize) {
488            *slot = i as u8;
489        }
490        let mut sub_cursor: usize = 0;
491        let mut cur_block_end: usize = 0;
492        let mut cur_byte_pos: usize = 0;
493        let mut bit_buf: u32 = 0;
494        let mut bit_count: u8 = 0;
495        let mut prev_code: Option<u16> = None;
496        let mut first_char: u8 = 0;
497        let mut saw_any_byte: bool = false;
498        while out_indices.len() < expected_pixels {
499            while bit_count < code_size {
500                while cur_byte_pos >= cur_block_end {
501                    if sub_cursor >= subblocks.len() {
502                        if out_indices.len() == expected_pixels {
503                            return Ok(());
504                        }
505                        return Err(GIF_ERR_LZW_EMPTY.to_string());
506                    }
507                    let block_len: usize = subblocks[sub_cursor] as usize;
508                    sub_cursor += 1;
509                    if block_len == 0 {
510                        if out_indices.len() == expected_pixels {
511                            return Ok(());
512                        }
513                        return Err(GIF_ERR_LZW_EMPTY.to_string());
514                    }
515                    if sub_cursor.saturating_add(block_len) > subblocks.len() {
516                        return Err(GIF_ERR_TRUNC_SUB.to_string());
517                    }
518                    cur_byte_pos = sub_cursor;
519                    cur_block_end = sub_cursor + block_len;
520                    sub_cursor = cur_block_end;
521                }
522                let byte: u8 = subblocks[cur_byte_pos];
523                cur_byte_pos += 1;
524                saw_any_byte = true;
525                bit_buf |= (byte as u32) << bit_count;
526                bit_count += 8;
527            }
528            let mask: u32 = (1_u32 << code_size) - 1;
529            let code: u16 = (bit_buf & mask) as u16;
530            bit_buf >>= code_size;
531            bit_count -= code_size;
532            if code == clear_code {
533                code_size = min_code_size + 1;
534                next_code = eoi_code + 1;
535                prev_code = None;
536                continue;
537            }
538            if code == eoi_code {
539                break;
540            }
541            if prev_code.is_none() {
542                if code >= clear_code {
543                    return Err(GIF_ERR_LZW_CODE.to_string());
544                }
545                let ch: u8 = code as u8;
546                out_indices.push(ch);
547                first_char = ch;
548                prev_code = Some(code);
549                continue;
550            }
551            let mut sp: usize = 0;
552            let mut cur: u16 = code;
553            if cur >= next_code {
554                if cur != next_code {
555                    return Err(GIF_ERR_LZW_CODE.to_string());
556                }
557                if sp >= GIF_LZW_MAX_TABLE {
558                    return Err(GIF_ERR_LZW_CODE.to_string());
559                }
560                stack[sp] = first_char;
561                sp += 1;
562                let Some(p) = prev_code else {
563                    return Err(GIF_ERR_LZW_CODE.to_string());
564                };
565                cur = p;
566            }
567            while cur >= clear_code {
568                if (cur as usize) >= GIF_LZW_MAX_TABLE || sp >= GIF_LZW_MAX_TABLE {
569                    return Err(GIF_ERR_LZW_CODE.to_string());
570                }
571                stack[sp] = suffix[cur as usize];
572                sp += 1;
573                cur = prefix[cur as usize];
574            }
575            first_char = suffix[cur as usize];
576            if sp < GIF_LZW_MAX_TABLE {
577                stack[sp] = first_char;
578                sp += 1;
579            }
580            while sp > 0 && out_indices.len() < expected_pixels {
581                sp -= 1;
582                out_indices.push(stack[sp]);
583            }
584            if let Some(p) = prev_code
585                && (next_code as usize) < GIF_LZW_MAX_TABLE
586            {
587                prefix[next_code as usize] = p;
588                suffix[next_code as usize] = first_char;
589                next_code += 1;
590                if next_code == (1_u16 << code_size) && code_size < GIF_LZW_MAX_BITS {
591                    code_size += 1;
592                }
593            }
594            prev_code = Some(code);
595        }
596        if !saw_any_byte || out_indices.len() < expected_pixels {
597            return Err(GIF_ERR_LZW_EMPTY.to_string());
598        }
599        Ok(())
600    }
601
602    /// Maps an interlaced decoded row index `src_row` to its visual canvas row inside `0..height`.
603    ///
604    /// # Arguments
605    ///
606    /// - `usize` - Decoded row index in stream order.
607    /// - `usize` - Frame height in pixels.
608    ///
609    /// # Returns
610    ///
611    /// - `usize` - Target visual row index inside `0..height`.
612    #[must_use]
613    pub fn deinterlace_row(src_row: usize, height: usize) -> usize {
614        let mut remaining: usize = src_row;
615        for pass in 0..4 {
616            let start: usize = GIF_INTERLACE_STARTS[pass];
617            let step: usize = GIF_INTERLACE_STEPS[pass];
618            if start >= height {
619                continue;
620            }
621            let rows_in_pass: usize = (height - 1 - start) / step + 1;
622            if remaining < rows_in_pass {
623                return start + remaining * step;
624            }
625            remaining -= rows_in_pass;
626        }
627        src_row.min(height.saturating_sub(1))
628    }
629
630    /// Resolves RGB color for palette index `color_idx` against the frame's Local Color Table or fallback Global Color Table.
631    ///
632    /// # Arguments
633    ///
634    /// - `&Self` - GIF decoder reference.
635    /// - `&GifFrameDescriptor` - Active frame descriptor.
636    /// - `u8` - Palette index.
637    ///
638    /// # Returns
639    ///
640    /// - `[u8; 3]` - Resolved `[r, g, b]` color triplet (`[0, 0, 0]` if out of palette bounds).
641    #[must_use]
642    pub fn lookup_rgb(&self, desc: &GifFrameDescriptor, color_idx: u8) -> [u8; 3] {
643        let idx: usize = color_idx as usize;
644        if let Some((start, end)) = desc.local_color_table_range() {
645            let off: usize = start.saturating_add(idx.saturating_mul(3));
646            let raw: &[u8] = self.get_bytes().as_slice();
647            if off + 3 <= end && off + 3 <= raw.len() {
648                return [raw[off], raw[off + 1], raw[off + 2]];
649            }
650            return [0, 0, 0];
651        }
652        self.get_global_color_table()
653            .get(idx)
654            .copied()
655            .unwrap_or([0, 0, 0])
656    }
657
658    /// Decodes all frames in sequence into a `GifAnimation` using a single reusable composite canvas.
659    ///
660    /// # Arguments
661    ///
662    /// - `&Self` - GIF decoder reference.
663    /// - `&str` - Asset title.
664    ///
665    /// # Returns
666    ///
667    /// - `Result<GifAnimation, String>` - Fully decoded `GifAnimation` with exact source dimensions and composited RGBA8 frames.
668    pub fn decode_all_animation(&self, title: &str) -> Result<GifAnimation, String> {
669        let mut player: GifStreamPlayer = GifStreamPlayer::from_decoder(self.clone());
670        let total: usize = self.get_frames().len();
671        let mut media_frames: Vec<MediaFrame> = Vec::with_capacity(total);
672        let mut total_ms: u32 = 0;
673        for idx in 0..total {
674            let decoded: GifDecodedFrame = player.decode_frame(idx)?;
675            total_ms = total_ms.saturating_add(decoded.get_delay_ms());
676            media_frames.push(MediaFrame {
677                image: decoded.get_image().clone(),
678                delay_ms: decoded.get_delay_ms(),
679                timestamp_secs: decoded.get_timestamp_secs(),
680            });
681        }
682        let width: u32 = self.get_logical_width() as u32;
683        let height: u32 = self.get_logical_height() as u32;
684        let frame_count: usize = media_frames.len();
685        Ok(GifAnimation {
686            frames: media_frames,
687            loop_count: self.get_loop_count(),
688            current_frame: 0,
689            elapsed_ms: 0,
690            playing: true,
691            metadata: MediaMetadata {
692                title: title.to_string(),
693                width,
694                height,
695                duration_secs: (total_ms as f32) / 1000.0,
696                page_count: 1,
697                frame_count,
698                sample_rate_hz: 0,
699                channels: 0,
700                format_label: format!("{} · {}f", self.get_version(), frame_count),
701            },
702        })
703    }
704}
705
706/// Reusable-canvas compositing, bounded pre-decode caching, disposal dirty reporting, and visibility pause/resume for `GifStreamPlayer`.
707impl GifStreamPlayer {
708    /// Creates a streaming GIF player directly from raw `.gif` bytes and `GifDecodeConfig`.
709    ///
710    /// # Arguments
711    ///
712    /// - `&[u8]` - Raw `.gif` file bytes.
713    /// - `GifDecodeConfig` - Memory budget and frame-delay compatibility policy.
714    ///
715    /// # Returns
716    ///
717    /// - `Result<Self, String>` - Initialized streaming GIF player or parse error.
718    pub fn from_bytes_with_config(bytes: &[u8], config: GifDecodeConfig) -> Result<Self, String> {
719        let decoder: GifDecoder = GifDecoder::parse_with_config(bytes, config)?;
720        Ok(Self::from_decoder(decoder))
721    }
722
723    /// Creates a streaming GIF player from an already-parsed `GifDecoder`.
724    ///
725    /// # Arguments
726    ///
727    /// - `GifDecoder` - Parsed GIF stream decoder.
728    ///
729    /// # Returns
730    ///
731    /// - `Self` - Initialized streaming GIF player with reusable canvas.
732    #[must_use]
733    pub fn from_decoder(decoder: GifDecoder) -> Self {
734        let w: usize = decoder.get_logical_width() as usize;
735        let h: usize = decoder.get_logical_height() as usize;
736        let canvas_len: usize = w.saturating_mul(h).saturating_mul(4);
737        Self {
738            decoder,
739            canvas: vec![0; canvas_len],
740            restore_snapshot: Vec::new(),
741            index_scratch: Vec::new(),
742            cache: Vec::new(),
743            cache_bytes: 0,
744            last_composited_index: None,
745            pending_disposal_rect: None,
746            pending_disposal: GifDisposalMethod::Unspecified,
747            current_frame: 0,
748            elapsed_ms: 0,
749            completed_loops: 0,
750            visible: true,
751            visibility_policy: GifVisibilityPolicy::PauseAndResumeFromCurrent,
752            status: GifPlaybackStatus::Playing,
753            last_dirty_rect: GifDirtyRect::new(0, 0, w as u32, h as u32),
754            cache_hits: 0,
755            decode_count: 0,
756        }
757    }
758
759    /// Updates viewport visibility, suspending pre-decoding and timing while off-screen and resuming cleanly per `visibility_policy`.
760    ///
761    /// # Arguments
762    ///
763    /// - `&Self` - Mutable streaming GIF player.
764    /// - `bool` - `true` when the GIF is visible on screen, `false` when off-screen or frozen.
765    pub fn set_visible(&mut self, visible: bool) {
766        let was_visible: bool = self.get_visible();
767        self.set_visible_flag(visible);
768        if !visible {
769            if self.get_status() == GifPlaybackStatus::Playing
770                || self.get_status() == GifPlaybackStatus::Ready
771            {
772                self.set_status(GifPlaybackStatus::PausedOffscreen);
773            }
774            return;
775        }
776        if !was_visible && self.get_status() == GifPlaybackStatus::PausedOffscreen {
777            if self.get_visibility_policy() == GifVisibilityPolicy::PauseAndRestart {
778                self.set_current_frame(0);
779                self.set_elapsed_ms(0);
780                self.set_completed_loops(0);
781            }
782            self.set_status(GifPlaybackStatus::Playing);
783        }
784    }
785
786    /// Internal helper updating the visibility boolean without name collision.
787    ///
788    /// # Arguments
789    ///
790    /// - `&Self` - Mutable streaming GIF player.
791    /// - `bool` - New visibility state.
792    fn set_visible_flag(&mut self, value: bool) {
793        let Self { visible, .. } = self;
794        *visible = value;
795    }
796
797    /// Pre-decodes up to `window` upcoming frames into the bounded cache when visible (no-op when off-screen).
798    ///
799    /// # Arguments
800    ///
801    /// - `&Self` - Mutable streaming GIF player.
802    /// - `usize` - Maximum number of upcoming frames to pre-decode.
803    ///
804    /// # Returns
805    ///
806    /// - `Result<usize, String>` - Number of frames present in the cache after pre-decoding.
807    pub fn predecode_upcoming(&mut self, window: usize) -> Result<usize, String> {
808        if !self.get_visible() || self.get_status() == GifPlaybackStatus::Corrupt {
809            return Ok(self.get_cache().len());
810        }
811        let total: usize = self.get_decoder().get_frames().len();
812        if total == 0 {
813            return Ok(0);
814        }
815        let limit: usize = window
816            .min(self.get_decoder().get_config().get_max_predecode_frames())
817            .min(total);
818        let start: usize = self.get_current_frame();
819        for offset in 0..limit {
820            let idx: usize = (start + offset) % total;
821            let _: GifDecodedFrame = self.decode_frame(idx)?;
822        }
823        Ok(self.get_cache().len())
824    }
825
826    /// Advances playback by `dt_ms` milliseconds when visible and playing, returning `Some(GifDecodedFrame)` whenever the active frame updates.
827    ///
828    /// # Arguments
829    ///
830    /// - `&Self` - Mutable streaming GIF player.
831    /// - `u32` - Elapsed wall time in milliseconds.
832    ///
833    /// # Returns
834    ///
835    /// - `Result<Option<GifDecodedFrame>, String>` - Newly active composited frame and dirty region, or `None` when unchanged/paused/off-screen.
836    pub fn step_ms(&mut self, dt_ms: u32) -> Result<Option<GifDecodedFrame>, String> {
837        if !self.get_visible() || self.get_status() != GifPlaybackStatus::Playing {
838            return Ok(None);
839        }
840        let total: usize = self.get_decoder().get_frames().len();
841        if total == 0 {
842            return Ok(None);
843        }
844        let cur: usize = self.get_current_frame() % total;
845        let delay: u32 = self.get_decoder().get_frames()[cur].get_delay_ms().max(1);
846        let next_elapsed: u32 = self.get_elapsed_ms().saturating_add(dt_ms);
847        if next_elapsed < delay {
848            self.set_elapsed_ms(next_elapsed);
849            return Ok(None);
850        }
851        let remainder: u32 = next_elapsed - delay;
852        let next_idx: usize = cur + 1;
853        if next_idx >= total {
854            let max_loops: u32 = self.get_decoder().get_loop_count();
855            let completed: u32 = self.get_completed_loops().saturating_add(1);
856            self.set_completed_loops(completed);
857            if self.get_decoder().get_has_netscape_loop() && max_loops > 0 && completed >= max_loops
858            {
859                self.set_elapsed_ms(0);
860                self.set_status(GifPlaybackStatus::Ended);
861                return Ok(None);
862            }
863            self.set_current_frame(0);
864            self.set_elapsed_ms(remainder);
865            let frame: GifDecodedFrame = self.decode_frame(0)?;
866            self.set_last_dirty_rect(frame.get_dirty_rect());
867            return Ok(Some(frame));
868        }
869        self.set_current_frame(next_idx);
870        self.set_elapsed_ms(remainder);
871        let frame: GifDecodedFrame = self.decode_frame(next_idx)?;
872        self.set_last_dirty_rect(frame.get_dirty_rect());
873        Ok(Some(frame))
874    }
875
876    /// Returns the composited `GifDecodedFrame` for `target_index`, hitting the bounded cache when available or compositing sequentially on the reusable canvas.
877    ///
878    /// # Arguments
879    ///
880    /// - `&Self` - Mutable streaming GIF player.
881    /// - `usize` - Zero-based frame index.
882    ///
883    /// # Returns
884    ///
885    /// - `Result<GifDecodedFrame, String>` - Composited frame with disposal-aware dirty rectangle or decode error.
886    pub fn decode_frame(&mut self, target_index: usize) -> Result<GifDecodedFrame, String> {
887        let total: usize = self.get_decoder().get_frames().len();
888        if target_index >= total {
889            return Err(GIF_ERR_FRAME_OOB.to_string());
890        }
891        if let Some(cached) = self
892            .get_cache()
893            .iter()
894            .find(|entry: &&GifDecodedFrame| entry.get_frame_index() == target_index)
895            .cloned()
896        {
897            let next_hits: u64 = self.get_cache_hits().saturating_add(1);
898            self.set_cache_hits(next_hits);
899            self.set_last_dirty_rect(cached.get_dirty_rect());
900            return Ok(cached);
901        }
902        let last_idx: Option<usize> = {
903            let Self {
904                last_composited_index,
905                ..
906            } = self;
907            *last_composited_index
908        };
909        let start_from: usize = match last_idx {
910            Some(prev) if prev < target_index => prev + 1,
911            _ => {
912                self.reset_canvas_state();
913                0
914            }
915        };
916        let mut latest_frame: Option<GifDecodedFrame> = None;
917        for step_idx in start_from..=target_index {
918            match self.composite_next_frame(step_idx) {
919                Ok(decoded) => {
920                    self.insert_cache_bounded(decoded.clone());
921                    latest_frame = Some(decoded);
922                }
923                Err(err) => {
924                    self.set_status(GifPlaybackStatus::Corrupt);
925                    return Err(err);
926                }
927            }
928        }
929        let Some(frame) = latest_frame else {
930            return Err(GIF_ERR_FRAME_OOB.to_string());
931        };
932        self.set_last_dirty_rect(frame.get_dirty_rect());
933        Ok(frame)
934    }
935
936    /// Resets the reusable composite canvas and pending disposal state back to a clean transparent screen.
937    ///
938    /// # Arguments
939    ///
940    /// - `&Self` - Mutable streaming GIF player.
941    fn reset_canvas_state(&mut self) {
942        self.get_mut_canvas().fill(0);
943        let Self {
944            last_composited_index,
945            pending_disposal_rect,
946            restore_snapshot,
947            ..
948        } = self;
949        *last_composited_index = None;
950        *pending_disposal_rect = None;
951        restore_snapshot.clear();
952        self.set_pending_disposal(GifDisposalMethod::Unspecified);
953    }
954
955    /// Composites frame `frame_idx` onto `self.canvas`, applying the prior frame's disposal and computing the exact dirty region.
956    ///
957    /// # Arguments
958    ///
959    /// - `&Self` - Mutable streaming GIF player.
960    /// - `usize` - Sequential frame index to composite.
961    ///
962    /// # Returns
963    ///
964    /// - `Result<GifDecodedFrame, String>` - Composited RGBA8 frame and disposal-aware dirty rectangle.
965    fn composite_next_frame(&mut self, frame_idx: usize) -> Result<GifDecodedFrame, String> {
966        let canvas_w: u32 = self.get_decoder().get_logical_width() as u32;
967        let canvas_h: u32 = self.get_decoder().get_logical_height() as u32;
968        let desc: GifFrameDescriptor = self.get_decoder().get_frames()[frame_idx];
969        let mut dirty_rect: GifDirtyRect = if frame_idx == 0 {
970            GifDirtyRect::new(0, 0, canvas_w, canvas_h)
971        } else {
972            GifDirtyRect::default()
973        };
974        let prev_disposal: GifDisposalMethod = self.get_pending_disposal();
975        let prev_rect_opt: Option<GifDirtyRect> = {
976            let Self {
977                pending_disposal_rect,
978                ..
979            } = self;
980            *pending_disposal_rect
981        };
982        if let Some(prev_rect) = prev_rect_opt {
983            match prev_disposal {
984                GifDisposalMethod::RestoreToBackground => {
985                    Self::clear_canvas_rect(
986                        self.get_mut_canvas().as_mut_slice(),
987                        canvas_w as usize,
988                        prev_rect,
989                    );
990                    dirty_rect = dirty_rect.union(prev_rect);
991                }
992                GifDisposalMethod::RestoreToPrevious => {
993                    let Self {
994                        canvas,
995                        restore_snapshot,
996                        ..
997                    } = self;
998                    if restore_snapshot.len() == canvas.len() {
999                        canvas.copy_from_slice(restore_snapshot.as_slice());
1000                    }
1001                    dirty_rect = dirty_rect.union(prev_rect);
1002                }
1003                GifDisposalMethod::Unspecified | GifDisposalMethod::Keep => {}
1004            }
1005        }
1006        if desc.get_disposal() == GifDisposalMethod::RestoreToPrevious {
1007            let Self {
1008                canvas,
1009                restore_snapshot,
1010                ..
1011            } = self;
1012            if restore_snapshot.len() != canvas.len() {
1013                restore_snapshot.resize(canvas.len(), 0);
1014            }
1015            restore_snapshot.copy_from_slice(canvas.as_slice());
1016        }
1017        let expected_pixels: usize =
1018            (desc.get_width() as usize).saturating_mul(desc.get_height() as usize);
1019        {
1020            let Self {
1021                decoder,
1022                index_scratch,
1023                ..
1024            } = self;
1025            let raw_subblocks: &[u8] =
1026                &decoder.get_bytes()[desc.get_lzw_data_start()..desc.get_lzw_data_end()];
1027            GifDecoder::decode_lzw_subblocks(
1028                raw_subblocks,
1029                desc.get_lzw_min_code_size(),
1030                expected_pixels,
1031                index_scratch,
1032            )?;
1033        }
1034        let sub_rect: GifDirtyRect = GifDirtyRect::clipped_subframe(
1035            desc.get_left(),
1036            desc.get_top(),
1037            desc.get_width(),
1038            desc.get_height(),
1039            canvas_w,
1040            canvas_h,
1041        );
1042        dirty_rect = dirty_rect.union(sub_rect);
1043        let fw: usize = desc.get_width() as usize;
1044        let fh: usize = desc.get_height() as usize;
1045        let left: usize = desc.get_left() as usize;
1046        let top: usize = desc.get_top() as usize;
1047        let cw: usize = canvas_w as usize;
1048        let ch: usize = canvas_h as usize;
1049        let interlaced: bool = desc.get_interlaced();
1050        let transparent_idx: Option<u8> = desc.transparent_color_index();
1051        let Self {
1052            decoder,
1053            canvas,
1054            index_scratch,
1055            ..
1056        } = self;
1057        for src_row in 0..fh {
1058            let local_y: usize = if interlaced {
1059                GifDecoder::deinterlace_row(src_row, fh)
1060            } else {
1061                src_row
1062            };
1063            let dst_y: usize = top.saturating_add(local_y);
1064            if dst_y >= ch {
1065                continue;
1066            }
1067            let src_row_off: usize = src_row * fw;
1068            let dst_row_off: usize = dst_y * cw;
1069            for local_x in 0..fw {
1070                let dst_x: usize = left.saturating_add(local_x);
1071                if dst_x >= cw {
1072                    break;
1073                }
1074                let pal_idx: u8 = index_scratch[src_row_off + local_x];
1075                if transparent_idx == Some(pal_idx) {
1076                    continue;
1077                }
1078                let rgb: [u8; 3] = decoder.lookup_rgb(&desc, pal_idx);
1079                let out_off: usize = (dst_row_off + dst_x) * 4;
1080                canvas[out_off] = rgb[0];
1081                canvas[out_off + 1] = rgb[1];
1082                canvas[out_off + 2] = rgb[2];
1083                canvas[out_off + 3] = 255;
1084            }
1085        }
1086        let Self {
1087            last_composited_index,
1088            pending_disposal_rect,
1089            ..
1090        } = self;
1091        *last_composited_index = Some(frame_idx);
1092        *pending_disposal_rect = Some(sub_rect);
1093        self.set_pending_disposal(desc.get_disposal());
1094        let next_decodes: u64 = self.get_decode_count().saturating_add(1);
1095        self.set_decode_count(next_decodes);
1096        let image: ImageBuffer = ImageBuffer::new(canvas_w, canvas_h, self.get_canvas().clone());
1097        Ok(GifDecodedFrame {
1098            frame_index: frame_idx,
1099            image,
1100            delay_ms: desc.get_delay_ms(),
1101            timestamp_secs: (desc.get_timestamp_ms() as f32) / 1000.0,
1102            dirty_rect,
1103            disposal: desc.get_disposal(),
1104        })
1105    }
1106
1107    /// Clears all RGBA pixels inside `rect` on `canvas` to transparent `[0, 0, 0, 0]`.
1108    ///
1109    /// # Arguments
1110    ///
1111    /// - `&mut [u8]` - Full RGBA8 canvas buffer.
1112    /// - `usize` - Canvas width in pixels.
1113    /// - `GifDirtyRect` - Sub-rectangle to clear.
1114    fn clear_canvas_rect(canvas: &mut [u8], canvas_w: usize, rect: GifDirtyRect) {
1115        if rect.is_empty() || canvas_w == 0 {
1116            return;
1117        }
1118        let x0: usize = rect.get_x() as usize;
1119        let y0: usize = rect.get_y() as usize;
1120        let rw: usize = rect.get_width() as usize;
1121        let rh: usize = rect.get_height() as usize;
1122        let row_bytes: usize = rw * 4;
1123        for dy in 0..rh {
1124            let start: usize = ((y0 + dy) * canvas_w + x0) * 4;
1125            let end: usize = start.saturating_add(row_bytes).min(canvas.len());
1126            if start < end {
1127                canvas[start..end].fill(0);
1128            }
1129        }
1130    }
1131
1132    /// Inserts `frame` into the bounded pre-decode cache, evicting oldest entries whenever frame count or byte budgets are exceeded.
1133    ///
1134    /// # Arguments
1135    ///
1136    /// - `&Self` - Mutable streaming GIF player.
1137    /// - `GifDecodedFrame` - Composited frame to cache.
1138    fn insert_cache_bounded(&mut self, frame: GifDecodedFrame) {
1139        let cfg: GifDecodeConfig = self.get_decoder().get_config();
1140        let frame_bytes: usize = frame.get_image().get_pixels().len();
1141        if cfg.get_max_predecode_frames() == 0 || frame_bytes > cfg.get_max_cache_bytes() {
1142            return;
1143        }
1144        if self
1145            .get_cache()
1146            .iter()
1147            .any(|e: &GifDecodedFrame| e.get_frame_index() == frame.get_frame_index())
1148        {
1149            return;
1150        }
1151        while !self.get_cache().is_empty()
1152            && (self.get_cache().len() >= cfg.get_max_predecode_frames()
1153                || self.get_cache_bytes().saturating_add(frame_bytes) > cfg.get_max_cache_bytes())
1154        {
1155            let evicted: GifDecodedFrame = self.get_mut_cache().remove(0);
1156            let next_bytes: usize = self
1157                .get_cache_bytes()
1158                .saturating_sub(evicted.get_image().get_pixels().len());
1159            self.set_cache_bytes(next_bytes);
1160        }
1161        let next_bytes: usize = self.get_cache_bytes().saturating_add(frame_bytes);
1162        self.set_cache_bytes(next_bytes);
1163        self.get_mut_cache().push(frame);
1164    }
1165}
1166
1167/// Optional field accessors for `GifEncodeFrameInput`.
1168impl GifEncodeFrameInput {
1169    /// Returns the optional transparent palette index.
1170    ///
1171    /// # Arguments
1172    ///
1173    /// - `&Self` - Encode frame descriptor reference.
1174    ///
1175    /// # Returns
1176    ///
1177    /// - `Option<u8>` - Transparent palette index if set.
1178    #[must_use]
1179    pub const fn transparent_color_index(&self) -> Option<u8> {
1180        let Self {
1181            transparent_index, ..
1182        } = *self;
1183        transparent_index
1184    }
1185
1186    /// Returns the optional frame-specific local palette.
1187    ///
1188    /// # Arguments
1189    ///
1190    /// - `&Self` - Encode frame descriptor reference.
1191    ///
1192    /// # Returns
1193    ///
1194    /// - `Option<&[[u8; 3]]>` - Borrowed local palette slice if set.
1195    #[must_use]
1196    pub fn local_palette_slice(&self) -> Option<&[[u8; 3]]> {
1197        let Self { local_palette, .. } = self;
1198        local_palette.as_deref()
1199    }
1200}
1201
1202/// Spec-compliant pure-Rust GIF89a LZW encoding for `GifEncoder`.
1203impl GifEncoder {
1204    /// Computes the power-of-two color table bits `(table_size_code, padded_entries, min_lzw_bits)` for a palette of length `len`.
1205    ///
1206    /// # Arguments
1207    ///
1208    /// - `usize` - Number of RGB palette entries (`1..=256`).
1209    ///
1210    /// # Returns
1211    ///
1212    /// - `(u8, usize, u8)` - `(packed_size_bits, padded_table_entries, lzw_min_code_size)`.
1213    #[must_use]
1214    fn palette_table_params(len: usize) -> (u8, usize, u8) {
1215        let clamped: usize = len.clamp(2, 256);
1216        let mut bits: u8 = 1;
1217        while (1_usize << bits) < clamped && bits < 8 {
1218            bits += 1;
1219        }
1220        let entries: usize = 1_usize << bits;
1221        let min_lzw: u8 = bits.max(2);
1222        (bits - 1, entries, min_lzw)
1223    }
1224
1225    /// Compresses `indices` into GIF variable-width LSB-first LZW data sub-blocks.
1226    ///
1227    /// # Arguments
1228    ///
1229    /// - `&[u8]` - Stream-ordered palette indices.
1230    /// - `u8` - Initial LZW minimum code size (`2..=8`).
1231    /// - `&mut Vec<u8>` - Destination GIF byte buffer.
1232    fn encode_lzw_subblocks(indices: &[u8], min_code_size: u8, out: &mut Vec<u8>) {
1233        out.push(min_code_size);
1234        let clear_code: u16 = 1_u16 << min_code_size;
1235        let eoi_code: u16 = clear_code + 1;
1236        let mut code_size: u8 = min_code_size + 1;
1237        let mut next_code: u16 = eoi_code + 1;
1238        let mut dict: HashMap<(u16, u8), u16> = HashMap::new();
1239        let mut packed_bytes: Vec<u8> = Vec::with_capacity(indices.len() + 16);
1240        let mut bit_buf: u32 = 0;
1241        let mut bit_count: u8 = 0;
1242        Self::emit_lzw_code(
1243            clear_code,
1244            code_size,
1245            &mut bit_buf,
1246            &mut bit_count,
1247            &mut packed_bytes,
1248        );
1249        if let Some(&first_px) = indices.first() {
1250            let mut prefix: u16 = first_px as u16;
1251            for &sym in indices[1..].iter() {
1252                if let Some(&existing) = dict.get(&(prefix, sym)) {
1253                    prefix = existing;
1254                } else {
1255                    Self::emit_lzw_code(
1256                        prefix,
1257                        code_size,
1258                        &mut bit_buf,
1259                        &mut bit_count,
1260                        &mut packed_bytes,
1261                    );
1262                    if (next_code as usize) < GIF_LZW_MAX_TABLE {
1263                        let _: Option<u16> = dict.insert((prefix, sym), next_code);
1264                        next_code += 1;
1265                        if next_code > (1_u16 << code_size) && code_size < GIF_LZW_MAX_BITS {
1266                            code_size += 1;
1267                        }
1268                    } else {
1269                        Self::emit_lzw_code(
1270                            clear_code,
1271                            code_size,
1272                            &mut bit_buf,
1273                            &mut bit_count,
1274                            &mut packed_bytes,
1275                        );
1276                        dict.clear();
1277                        code_size = min_code_size + 1;
1278                        next_code = eoi_code + 1;
1279                    }
1280                    prefix = sym as u16;
1281                }
1282            }
1283            Self::emit_lzw_code(
1284                prefix,
1285                code_size,
1286                &mut bit_buf,
1287                &mut bit_count,
1288                &mut packed_bytes,
1289            );
1290        }
1291        Self::emit_lzw_code(
1292            eoi_code,
1293            code_size,
1294            &mut bit_buf,
1295            &mut bit_count,
1296            &mut packed_bytes,
1297        );
1298        if bit_count > 0 {
1299            packed_bytes.push((bit_buf & 0xFF) as u8);
1300        }
1301        for chunk in packed_bytes.chunks(255) {
1302            out.push(chunk.len() as u8);
1303            out.extend_from_slice(chunk);
1304        }
1305        out.push(0x00);
1306    }
1307
1308    /// Writes one variable-width LSB-first LZW code into the active bit buffer and flushes complete bytes.
1309    ///
1310    /// # Arguments
1311    ///
1312    /// - `u16` - LZW code value to emit.
1313    /// - `u8` - Active code width in bits.
1314    /// - `&mut u32` - Accumulated bit buffer.
1315    /// - `&mut u8` - Number of buffered bits currently held.
1316    /// - `&mut Vec<u8>` - Destination packed byte buffer.
1317    fn emit_lzw_code(code: u16, width: u8, buf: &mut u32, bits: &mut u8, dst: &mut Vec<u8>) {
1318        *buf |= (code as u32) << *bits;
1319        *bits += width;
1320        while *bits >= 8 {
1321            dst.push((*buf & 0xFF) as u8);
1322            *buf >>= 8;
1323            *bits -= 8;
1324        }
1325    }
1326
1327    /// Encodes a complete spec-compliant GIF89a animated image stream with LZW compression, Netscape loop count, GCE, interlacing, and local palettes.
1328    ///
1329    /// # Arguments
1330    ///
1331    /// - `u16` - Logical screen width in pixels.
1332    /// - `u16` - Logical screen height in pixels.
1333    /// - `&[[u8; 3]]` - Global Color Table RGB triplets (may be empty if every frame supplies a local palette).
1334    /// - `Option<u16>` - Optional Netscape 2.0 loop count (`Some(0)` = infinite, `Some(n)` = `n` loops).
1335    /// - `&[GifEncodeFrameInput]` - Ordered animation frames to encode.
1336    ///
1337    /// # Returns
1338    ///
1339    /// - `Vec<u8>` - Encoded GIF89a binary payload.
1340    #[must_use]
1341    pub fn encode(
1342        logical_width: u16,
1343        logical_height: u16,
1344        global_palette: &[[u8; 3]],
1345        netscape_loop: Option<u16>,
1346        frames: &[GifEncodeFrameInput],
1347    ) -> Vec<u8> {
1348        let mut out: Vec<u8> = Vec::new();
1349        out.extend_from_slice(MAGIC_GIF89A);
1350        out.extend_from_slice(&logical_width.to_le_bytes());
1351        out.extend_from_slice(&logical_height.to_le_bytes());
1352        let (gct_packed, gct_entries, gct_lzw_min): (u8, usize, u8) = if global_palette.is_empty() {
1353            (0x00, 0, 2)
1354        } else {
1355            let (sz_bits, entries, lzw_min): (u8, usize, u8) =
1356                Self::palette_table_params(global_palette.len());
1357            let gct_flags: u8 = 0xF0 | (sz_bits & 0x07);
1358            (gct_flags, entries, lzw_min)
1359        };
1360        out.push(gct_packed);
1361        out.push(0);
1362        out.push(0);
1363        for i in 0..gct_entries {
1364            let rgb: [u8; 3] = global_palette.get(i).copied().unwrap_or([0, 0, 0]);
1365            out.extend_from_slice(&rgb);
1366        }
1367        if let Some(loops) = netscape_loop {
1368            out.push(GIF_EXT_INTRO);
1369            out.push(GIF_EXT_APP);
1370            out.push(11);
1371            out.extend_from_slice(GIF_NETSCAPE_20);
1372            out.push(3);
1373            out.push(0x01);
1374            out.extend_from_slice(&loops.to_le_bytes());
1375            out.push(0x00);
1376        }
1377        for frame in frames.iter() {
1378            let trans_opt: Option<u8> = frame.transparent_color_index();
1379            let gce_packed: u8 =
1380                (frame.get_disposal().to_gce_bits() << 2) | u8::from(trans_opt.is_some());
1381            out.push(GIF_EXT_INTRO);
1382            out.push(GIF_EXT_GCE);
1383            out.push(4);
1384            out.push(gce_packed);
1385            out.extend_from_slice(&frame.get_delay_cs().to_le_bytes());
1386            out.push(trans_opt.unwrap_or(0));
1387            out.push(0x00);
1388            out.push(GIF_IMG_INTRO);
1389            out.extend_from_slice(&frame.get_left().to_le_bytes());
1390            out.extend_from_slice(&frame.get_top().to_le_bytes());
1391            out.extend_from_slice(&frame.get_width().to_le_bytes());
1392            out.extend_from_slice(&frame.get_height().to_le_bytes());
1393            let (lct_flag_bits, lct_entries, lzw_min): (u8, usize, u8) =
1394                if let Some(lpal) = frame.local_palette_slice() {
1395                    let (sz_bits, entries, min_bits): (u8, usize, u8) =
1396                        Self::palette_table_params(lpal.len());
1397                    (0x80 | (sz_bits & 0x07), entries, min_bits)
1398                } else {
1399                    (0x00, 0, gct_lzw_min)
1400                };
1401            let interlace_bit: u8 = if frame.get_interlaced() { 0x40 } else { 0x00 };
1402            out.push(lct_flag_bits | interlace_bit);
1403            if let Some(lpal) = frame.local_palette_slice() {
1404                for i in 0..lct_entries {
1405                    let rgb: [u8; 3] = lpal.get(i).copied().unwrap_or([0, 0, 0]);
1406                    out.extend_from_slice(&rgb);
1407                }
1408            }
1409            let fw: usize = frame.get_width() as usize;
1410            let fh: usize = frame.get_height() as usize;
1411            let expected: usize = fw.saturating_mul(fh);
1412            let stream_indices: Vec<u8> = if frame.get_interlaced() && fh > 0 && fw > 0 {
1413                let mut reordered: Vec<u8> = Vec::with_capacity(expected);
1414                let src: &[u8] = frame.get_indices().as_slice();
1415                for pass in 0..4 {
1416                    let mut row: usize = GIF_INTERLACE_STARTS[pass];
1417                    let step: usize = GIF_INTERLACE_STEPS[pass];
1418                    while row < fh {
1419                        let start: usize = row * fw;
1420                        let end: usize = (start + fw).min(src.len());
1421                        if start < end {
1422                            reordered.extend_from_slice(&src[start..end]);
1423                        }
1424                        while reordered.len() < (reordered.len().div_ceil(fw)) * fw {
1425                            reordered.push(0);
1426                        }
1427                        row += step;
1428                    }
1429                }
1430                reordered.resize(expected, 0);
1431                reordered
1432            } else {
1433                let mut flat: Vec<u8> = frame.get_indices().clone();
1434                flat.resize(expected, 0);
1435                flat
1436            };
1437            Self::encode_lzw_subblocks(stream_indices.as_slice(), lzw_min, &mut out);
1438        }
1439        out.push(GIF_TRAILER);
1440        out
1441    }
1442}