Skip to main content

euv_core/media/codec/
impl.rs

1use super::*;
2
3/// Magic-byte detection, MIME classification, and pure-Rust decoders for all cross-platform media formats.
4impl MediaCodecRegistry {
5    /// Checks whether `haystack` starts with `prefix` using zero-allocation ASCII case folding.
6    ///
7    /// # Arguments
8    ///
9    /// - `&[u8]` - Source byte slice.
10    /// - `&[u8]` - Expected ASCII prefix bytes.
11    ///
12    /// # Returns
13    ///
14    /// - `bool` - `true` when `haystack` begins with `prefix` ignoring ASCII case.
15    #[inline(always)]
16    #[must_use]
17    fn starts_with_ignore_ascii_case(haystack: &[u8], prefix: &[u8]) -> bool {
18        haystack.len() >= prefix.len() && haystack[..prefix.len()].eq_ignore_ascii_case(prefix)
19    }
20
21    /// Checks whether `haystack` ends with `suffix` using zero-allocation ASCII case folding.
22    ///
23    /// # Arguments
24    ///
25    /// - `&[u8]` - Source byte slice.
26    /// - `&[u8]` - Expected ASCII suffix bytes.
27    ///
28    /// # Returns
29    ///
30    /// - `bool` - `true` when `haystack` ends with `suffix` ignoring ASCII case.
31    #[inline(always)]
32    #[must_use]
33    fn ends_with_ignore_ascii_case(haystack: &[u8], suffix: &[u8]) -> bool {
34        haystack.len() >= suffix.len()
35            && haystack[(haystack.len() - suffix.len())..].eq_ignore_ascii_case(suffix)
36    }
37
38    /// Checks whether `haystack` contains `needle` using zero-allocation ASCII case folding.
39    ///
40    /// # Arguments
41    ///
42    /// - `&[u8]` - Source byte slice.
43    /// - `&[u8]` - Expected ASCII substring bytes.
44    ///
45    /// # Returns
46    ///
47    /// - `bool` - `true` when `needle` occurs anywhere inside `haystack` ignoring ASCII case.
48    #[inline]
49    #[must_use]
50    fn contains_ignore_ascii_case(haystack: &[u8], needle: &[u8]) -> bool {
51        if needle.is_empty() {
52            return true;
53        }
54        if haystack.len() < needle.len() {
55            return false;
56        }
57        haystack
58            .windows(needle.len())
59            .any(|win: &[u8]| win.eq_ignore_ascii_case(needle))
60    }
61
62    /// Sniffs `MediaKind` from raw payload magic bytes first, falling back to `uri` extension without heap allocations.
63    ///
64    /// # Arguments
65    ///
66    /// - `&str` - Source URI or filename.
67    /// - `&[u8]` - Optional leading raw bytes.
68    ///
69    /// # Returns
70    ///
71    /// - `MediaKind` - Detected high-level media type.
72    #[must_use]
73    pub fn detect_media_kind(uri: &str, bytes: &[u8]) -> MediaKind {
74        if bytes.starts_with(MAGIC_PDF) {
75            return MediaKind::Pdf;
76        }
77        if bytes.starts_with(MAGIC_GIF87A) || bytes.starts_with(MAGIC_GIF89A) {
78            return MediaKind::AnimatedGif;
79        }
80        if bytes.len() >= 12 && &bytes[0..4] == MAGIC_RIFF && &bytes[8..12] == MAGIC_WAVE {
81            return MediaKind::Audio;
82        }
83        if bytes.len() >= 12 && &bytes[0..4] == MAGIC_RIFF && &bytes[8..12] == MAGIC_WEBP {
84            return MediaKind::Image;
85        }
86        let is_png_or_jpg: bool =
87            bytes.starts_with(MAGIC_PNG) || bytes.starts_with(&[0xFF, 0xD8, 0xFF]);
88        if is_png_or_jpg || bytes.starts_with(MAGIC_BMP) {
89            return MediaKind::Image;
90        }
91        if bytes.starts_with(MAGIC_ID3)
92            || (bytes.len() >= 2 && bytes[0] == 0xFF && (bytes[1] & 0xE0) == 0xE0)
93        {
94            return MediaKind::Audio;
95        }
96        if bytes.len() >= 8 && &bytes[4..8] == MAGIC_FTYP {
97            return MediaKind::Video;
98        }
99        if let Ok(text) = from_utf8(bytes) {
100            let trimmed: &[u8] = text.trim_start().as_bytes();
101            let head: &[u8] = &trimmed[..trimmed.len().min(32)];
102            if Self::starts_with_ignore_ascii_case(head, TAG_SVG_OPEN.as_bytes())
103                || Self::contains_ignore_ascii_case(head, TAG_SVG_SPACE)
104            {
105                return MediaKind::Svg;
106            }
107            let is_doc_or_html: bool = Self::starts_with_ignore_ascii_case(head, TAG_DOCTYPE_HTML)
108                || Self::starts_with_ignore_ascii_case(head, TAG_HTML_OPEN);
109            let is_art_or_div: bool = Self::starts_with_ignore_ascii_case(head, TAG_ARTICLE_OPEN)
110                || Self::starts_with_ignore_ascii_case(head, TAG_DIV_OPEN);
111            if is_doc_or_html || is_art_or_div {
112                return MediaKind::Html;
113            }
114        }
115        let uri_b: &[u8] = uri.as_bytes();
116        if Self::ends_with_ignore_ascii_case(uri_b, EXT_GIF.as_bytes()) {
117            return MediaKind::AnimatedGif;
118        }
119        if Self::ends_with_ignore_ascii_case(uri_b, EXT_LIVE_BYTES)
120            || Self::ends_with_ignore_ascii_case(uri_b, EXT_LIVP_BYTES)
121        {
122            return MediaKind::LivePhoto;
123        }
124        let vid_a: bool = Self::ends_with_ignore_ascii_case(uri_b, EXT_MP4_BYTES)
125            || Self::ends_with_ignore_ascii_case(uri_b, EXT_MOV_BYTES);
126        let vid_b: bool = Self::ends_with_ignore_ascii_case(uri_b, EXT_WEBM_BYTES)
127            || Self::ends_with_ignore_ascii_case(uri_b, EXT_MKV_BYTES);
128        if vid_a || vid_b {
129            return MediaKind::Video;
130        }
131        let aud_a: bool = Self::ends_with_ignore_ascii_case(uri_b, EXT_WAV_BYTES)
132            || Self::ends_with_ignore_ascii_case(uri_b, EXT_MP3_BYTES);
133        let aud_b: bool = Self::ends_with_ignore_ascii_case(uri_b, EXT_AAC_BYTES)
134            || Self::ends_with_ignore_ascii_case(uri_b, EXT_OGG_BYTES);
135        let aud_ab: bool = aud_a || aud_b;
136        if aud_ab || Self::ends_with_ignore_ascii_case(uri_b, EXT_FLAC_BYTES) {
137            return MediaKind::Audio;
138        }
139        if Self::ends_with_ignore_ascii_case(uri_b, EXT_PDF_BYTES) {
140            return MediaKind::Pdf;
141        }
142        if Self::ends_with_ignore_ascii_case(uri_b, EXT_HTML_BYTES)
143            || Self::ends_with_ignore_ascii_case(uri_b, EXT_HTM_BYTES)
144        {
145            return MediaKind::Html;
146        }
147        if Self::ends_with_ignore_ascii_case(uri_b, EXT_SVG.as_bytes()) {
148            return MediaKind::Svg;
149        }
150        MediaKind::Image
151    }
152
153    /// Detects the encoded `ImageFormat` from leading magic bytes or filename extension without heap allocations.
154    ///
155    /// # Arguments
156    ///
157    /// - `&str` - Source URI or filename.
158    /// - `&[u8]` - Optional leading bytes.
159    ///
160    /// # Returns
161    ///
162    /// - `ImageFormat` - Resolved image format.
163    #[must_use]
164    pub fn detect_image_format(uri: &str, bytes: &[u8]) -> ImageFormat {
165        if bytes.starts_with(MAGIC_PNG) {
166            return ImageFormat::Png;
167        }
168        if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
169            return ImageFormat::Jpeg;
170        }
171        if bytes.starts_with(MAGIC_GIF87A) || bytes.starts_with(MAGIC_GIF89A) {
172            return ImageFormat::Gif;
173        }
174        if bytes.starts_with(MAGIC_BMP) {
175            return ImageFormat::Bmp;
176        }
177        if bytes.len() >= 12 && &bytes[0..4] == MAGIC_RIFF && &bytes[8..12] == MAGIC_WEBP {
178            return ImageFormat::WebP;
179        }
180        let uri_b: &[u8] = uri.as_bytes();
181        if Self::ends_with_ignore_ascii_case(uri_b, EXT_JPG_BYTES)
182            || Self::ends_with_ignore_ascii_case(uri_b, EXT_JPEG_BYTES)
183        {
184            ImageFormat::Jpeg
185        } else if Self::ends_with_ignore_ascii_case(uri_b, EXT_WEBP_BYTES) {
186            ImageFormat::WebP
187        } else if Self::ends_with_ignore_ascii_case(uri_b, EXT_GIF.as_bytes()) {
188            ImageFormat::Gif
189        } else if Self::ends_with_ignore_ascii_case(uri_b, EXT_BMP_BYTES) {
190            ImageFormat::Bmp
191        } else if Self::ends_with_ignore_ascii_case(uri_b, EXT_SVG.as_bytes()) {
192            ImageFormat::Svg
193        } else if Self::ends_with_ignore_ascii_case(uri_b, EXT_HEIC_BYTES)
194            || Self::ends_with_ignore_ascii_case(uri_b, EXT_HEIF_BYTES)
195        {
196            ImageFormat::Heic
197        } else if Self::ends_with_ignore_ascii_case(uri_b, EXT_AVIF_BYTES) {
198            ImageFormat::Avif
199        } else {
200            ImageFormat::Png
201        }
202    }
203
204    /// Decodes an uncompressed 24-bit or 32-bit Windows BMP byte slice into an `ImageAsset`.
205    ///
206    /// # Arguments
207    ///
208    /// - `&[u8]` - Raw `.bmp` file bytes.
209    /// - `&str` - Accessibility alt text.
210    ///
211    /// # Returns
212    ///
213    /// - `Result<ImageAsset, String>` - Decoded `ImageAsset` or format error message.
214    pub fn decode_bmp(bytes: &[u8], alt_text: &str) -> Result<ImageAsset, String> {
215        if bytes.len() < 54 || &bytes[0..2] != MAGIC_BMP {
216            return Err("invalid BMP header".to_string());
217        }
218        let data_offset: usize =
219            u32::from_le_bytes([bytes[10], bytes[11], bytes[12], bytes[13]]) as usize;
220        let width_i: i32 = i32::from_le_bytes([bytes[18], bytes[19], bytes[20], bytes[21]]);
221        let height_i: i32 = i32::from_le_bytes([bytes[22], bytes[23], bytes[24], bytes[25]]);
222        let bpp: u16 = u16::from_le_bytes([bytes[28], bytes[29]]);
223        let compression: u32 = u32::from_le_bytes([bytes[30], bytes[31], bytes[32], bytes[33]]);
224        let bad_dims: bool = width_i <= 0 || height_i == 0;
225        let bad_fmt: bool = compression != 0 || (bpp != 24 && bpp != 32);
226        if bad_dims || bad_fmt {
227            return Err(
228                "unsupported BMP pixel layout (expected uncompressed 24/32bpp)".to_string(),
229            );
230        }
231        let width: u32 = width_i as u32;
232        let height: u32 = height_i.unsigned_abs();
233        let w_usize: usize = width as usize;
234        let h_usize: usize = height as usize;
235        let top_down: bool = height_i < 0;
236        let bytes_per_pixel: usize = (bpp / 8) as usize;
237        let row_stride: usize = (w_usize * bytes_per_pixel + 3) & !3;
238        let needed: usize = data_offset.saturating_add(row_stride.saturating_mul(h_usize));
239        if bytes.len() < needed {
240            return Err("truncated BMP pixel payload".to_string());
241        }
242        let total_bytes: usize = w_usize * h_usize * 4;
243        let mut rgba: Vec<u8> = Vec::with_capacity(total_bytes);
244        let dst_ptr: *mut u8 = rgba.as_mut_ptr();
245        let dst_row_bytes: usize = w_usize * 4;
246        if bytes_per_pixel == 4 {
247            let src_row_bytes: usize = w_usize * 4;
248            for y in 0..h_usize {
249                let src_y: usize = if top_down { y } else { h_usize - 1 - y };
250                let src_off: usize = data_offset + src_y * row_stride;
251                let src_slice: &[u8] = &bytes[src_off..(src_off + src_row_bytes)];
252                let dst_row_off: usize = y * dst_row_bytes;
253                for (x, px) in src_slice.as_chunks::<4>().0.iter().enumerate() {
254                    // SAFETY: `dst_row_off + x * 4 + 4 <= total_bytes <= rgba.capacity()`, `[u8; 4]` align is 1.
255                    unsafe {
256                        dst_ptr
257                            .add(dst_row_off + x * 4)
258                            .cast::<[u8; 4]>()
259                            .write([px[2], px[1], px[0], px[3]]);
260                    }
261                }
262            }
263        } else {
264            let src_row_bytes: usize = w_usize * 3;
265            for y in 0..h_usize {
266                let src_y: usize = if top_down { y } else { h_usize - 1 - y };
267                let src_off: usize = data_offset + src_y * row_stride;
268                let src_slice: &[u8] = &bytes[src_off..(src_off + src_row_bytes)];
269                let dst_row_off: usize = y * dst_row_bytes;
270                for (x, px) in src_slice.as_chunks::<3>().0.iter().enumerate() {
271                    // SAFETY: `dst_row_off + x * 4 + 4 <= total_bytes <= rgba.capacity()`, `[u8; 4]` align is 1.
272                    unsafe {
273                        dst_ptr
274                            .add(dst_row_off + x * 4)
275                            .cast::<[u8; 4]>()
276                            .write([px[2], px[1], px[0], 255]);
277                    }
278                }
279            }
280        }
281        // SAFETY: Both branches unconditionally initialize all `h_usize * w_usize * 4 == total_bytes` bytes.
282        unsafe {
283            rgba.set_len(total_bytes);
284        }
285        let meta: MediaMetadata = MediaMetadata {
286            title: alt_text.to_string(),
287            width,
288            height,
289            duration_secs: 0.0,
290            page_count: 1,
291            frame_count: 1,
292            sample_rate_hz: 0,
293            channels: 0,
294            format_label: "BMP".to_string(),
295        };
296        Ok(ImageAsset {
297            format: ImageFormat::Bmp,
298            buffer: ImageBuffer::new(width, height, rgba),
299            alt_text: alt_text.to_string(),
300            metadata: meta,
301        })
302    }
303
304    /// Decodes a real GIF87a/GIF89a byte stream using full LZW decompression, palettes, de-interlacing, transparency, and all 4 disposal methods.
305    ///
306    /// # Arguments
307    ///
308    /// - `&[u8]` - Raw `.gif` file bytes.
309    /// - `&str` - Asset title.
310    ///
311    /// # Returns
312    ///
313    /// - `Result<GifAnimation, String>` - Decoded multi-frame `GifAnimation` with exact source dimensions or parse/decode error.
314    pub fn decode_gif(bytes: &[u8], title: &str) -> Result<GifAnimation, String> {
315        Self::decode_gif_with_config(bytes, title, GifDecodeConfig::default())
316    }
317
318    /// Decodes a GIF87a/GIF89a byte stream using explicit `GifDecodeConfig` memory budgets and frame-delay compatibility settings.
319    ///
320    /// # Arguments
321    ///
322    /// - `&[u8]` - Raw `.gif` file bytes.
323    /// - `&str` - Asset title.
324    /// - `GifDecodeConfig` - Canvas/cache byte budget and frame-delay compatibility policy.
325    ///
326    /// # Returns
327    ///
328    /// - `Result<GifAnimation, String>` - Decoded multi-frame `GifAnimation` or parse/decode error.
329    pub fn decode_gif_with_config(
330        bytes: &[u8],
331        title: &str,
332        config: GifDecodeConfig,
333    ) -> Result<GifAnimation, String> {
334        let decoder: GifDecoder = GifDecoder::parse_with_config(bytes, config)?;
335        decoder.decode_all_animation(title)
336    }
337
338    /// Decodes a RIFF PCM WAV audio byte slice (8-bit or 16-bit) into a normalized `AudioTrack` with waveform peaks.
339    ///
340    /// # Arguments
341    ///
342    /// - `&[u8]` - Raw `.wav` bytes.
343    /// - `&str` - Track title.
344    ///
345    /// # Returns
346    ///
347    /// - `Result<AudioTrack, String>` - Decoded `AudioTrack` or format error.
348    pub fn decode_wav(bytes: &[u8], title: &str) -> Result<AudioTrack, String> {
349        let bad_riff: bool = bytes.len() < 44 || &bytes[0..4] != MAGIC_RIFF;
350        if bad_riff || &bytes[8..12] != MAGIC_WAVE {
351            return Err("invalid RIFF WAVE header".to_string());
352        }
353        let mut cursor: usize = 12;
354        let mut channels: u16 = 1;
355        let mut sample_rate: u32 = 44_100;
356        let mut bits_per_sample: u16 = 16;
357        let mut pcm_bytes: &[u8] = &[];
358        while cursor + 8 <= bytes.len() {
359            let chunk_id: &[u8] = &bytes[cursor..cursor + 4];
360            let chunk_size: usize = u32::from_le_bytes([
361                bytes[cursor + 4],
362                bytes[cursor + 5],
363                bytes[cursor + 6],
364                bytes[cursor + 7],
365            ]) as usize;
366            let body_start: usize = cursor + 8;
367            let body_end: usize = body_start.saturating_add(chunk_size).min(bytes.len());
368            if chunk_id == MAGIC_WAV_FMT && body_end - body_start >= 16 {
369                channels =
370                    u16::from_le_bytes([bytes[body_start + 2], bytes[body_start + 3]]).max(1);
371                sample_rate = u32::from_le_bytes([
372                    bytes[body_start + 4],
373                    bytes[body_start + 5],
374                    bytes[body_start + 6],
375                    bytes[body_start + 7],
376                ])
377                .max(8_000);
378                bits_per_sample =
379                    u16::from_le_bytes([bytes[body_start + 14], bytes[body_start + 15]]);
380            } else if chunk_id == MAGIC_WAV_DATA {
381                pcm_bytes = &bytes[body_start..body_end];
382            }
383            let padded: usize = chunk_size + (chunk_size & 1);
384            cursor = body_start.saturating_add(padded);
385        }
386        if pcm_bytes.is_empty() {
387            return Err("WAV file contained no data chunk".to_string());
388        }
389        let samples: Vec<f32> = if bits_per_sample == 16 {
390            let inv_scale: f32 = 1.0 / 32_768.0;
391            let chunks: &[[u8; 2]] = pcm_bytes.as_chunks::<2>().0;
392            let mut out: Vec<f32> = Vec::with_capacity(chunks.len());
393            for pair in chunks.iter() {
394                let s: i16 = i16::from_le_bytes(*pair);
395                out.push((s as f32) * inv_scale);
396            }
397            out
398        } else if bits_per_sample == 8 {
399            let inv_scale: f32 = 1.0 / 128.0;
400            let mut out: Vec<f32> = Vec::with_capacity(pcm_bytes.len());
401            for b in pcm_bytes.iter().copied() {
402                out.push(((b as f32) - 128.0) * inv_scale);
403            }
404            out
405        } else {
406            return Err("unsupported WAV bit depth (expected 8 or 16 bit PCM)".to_string());
407        };
408        let frames_total: usize = samples.len() / (channels as usize).max(1);
409        let duration_secs: f32 = (frames_total as f32) / (sample_rate as f32).max(1.0);
410        let waveform_peaks: Vec<f32> = Self::compute_waveform_peaks(&samples, 48);
411        Ok(AudioTrack {
412            metadata: MediaMetadata {
413                title: title.to_string(),
414                width: 0,
415                height: 0,
416                duration_secs,
417                page_count: 1,
418                frame_count: frames_total,
419                sample_rate_hz: sample_rate,
420                channels,
421                format_label: format!(
422                    "WAV · {:.1} kHz · {}",
423                    (sample_rate as f32) / 1000.0,
424                    if channels == 1 { "Mono" } else { "Stereo" }
425                ),
426            },
427            codec: AudioCodec::Wav,
428            samples,
429            waveform_peaks,
430            state: PlaybackState::Idle,
431            current_time_secs: 0.0,
432            volume: 0.85,
433            muted: false,
434            playback_rate: 1.0,
435            looping: true,
436        })
437    }
438
439    /// Parses a `%PDF-1.x` byte stream extracting version, info dictionary metadata, page count, and `Tj`/`TJ` text runs.
440    ///
441    /// # Arguments
442    ///
443    /// - `&[u8]` - Raw `.pdf` document bytes.
444    ///
445    /// # Returns
446    ///
447    /// - `Result<PdfDocument, String>` - Structured multi-page `PdfDocument` or format error.
448    pub fn parse_pdf(bytes: &[u8]) -> Result<PdfDocument, String> {
449        if bytes.len() < 8 || !bytes.starts_with(MAGIC_PDF) {
450            return Err("invalid PDF signature (expected %PDF-)".to_string());
451        }
452        let text: String = String::from_utf8_lossy(bytes).into_owned();
453        let version: String = text
454            .lines()
455            .next()
456            .and_then(|line: &str| line.strip_prefix(PREFIX_PDF))
457            .map(|v: &str| v.trim().to_string())
458            .filter(|v: &String| !v.is_empty())
459            .unwrap_or_else(|| "1.7".to_string());
460        let title: String = Self::extract_pdf_dict_string(&text, "/Title")
461            .unwrap_or_else(|| "Untitled PDF Document".to_string());
462        let author: String =
463            Self::extract_pdf_dict_string(&text, "/Author").unwrap_or_else(|| "euv".to_string());
464        let mut extracted_runs: Vec<String> = Vec::new();
465        let raw_bytes: &[u8] = text.as_bytes();
466        let mut i: usize = 0;
467        while i < raw_bytes.len() {
468            if raw_bytes[i] == BYTE_PAREN_OPEN {
469                let start: usize = i + 1;
470                let mut j: usize = start;
471                let mut depth: i32 = 1;
472                while j < raw_bytes.len() && depth > 0 {
473                    if raw_bytes[j] == b'\\' && j + 1 < raw_bytes.len() {
474                        j += 2;
475                        continue;
476                    }
477                    if raw_bytes[j] == BYTE_PAREN_OPEN {
478                        depth += 1;
479                    } else if raw_bytes[j] == BYTE_PAREN_CLOSE {
480                        depth -= 1;
481                        if depth == 0 {
482                            break;
483                        }
484                    }
485                    j += 1;
486                }
487                let tail: &str = text.get(j..).unwrap_or("");
488                let trimmed_tail: &str = tail.trim_start_matches(')').trim_start();
489                if trimmed_tail.starts_with("Tj") || trimmed_tail.starts_with("] TJ") {
490                    let run: String = text[start..j]
491                        .replace("\\(", "(")
492                        .replace("\\)", ")")
493                        .replace("\\\\", "\\")
494                        .trim()
495                        .to_string();
496                    if !run.is_empty() {
497                        extracted_runs.push(run);
498                    }
499                }
500                i = j.saturating_add(1);
501            } else {
502                i += 1;
503            }
504        }
505        let declared_pages: usize = text
506            .matches("/Type /Page")
507            .count()
508            .saturating_sub(text.matches("/Type /Pages").count())
509            .max(1);
510        let mut pages: Vec<PdfPage> = Vec::with_capacity(declared_pages);
511        let per_page: usize = extracted_runs.len().div_ceil(declared_pages).max(1);
512        for p_idx in 0..declared_pages {
513            let start: usize = p_idx.saturating_mul(per_page);
514            let end: usize = start.saturating_add(per_page).min(extracted_runs.len());
515            let mut blocks: Vec<String> = if start < end {
516                extracted_runs[start..end].to_vec()
517            } else {
518                Vec::new()
519            };
520            if blocks.is_empty() {
521                blocks.push(format!(
522                    "Page {} content stream parsed from PDF {version}.",
523                    p_idx + 1
524                ));
525            }
526            let page_title: String = blocks
527                .first()
528                .cloned()
529                .unwrap_or_else(|| format!("Page {}", p_idx + 1));
530            pages.push(PdfPage {
531                page_number: p_idx + 1,
532                width_pt: 595.0,
533                height_pt: 842.0,
534                title: page_title,
535                text_blocks: blocks,
536                preview_image: None,
537            });
538        }
539        Ok(PdfDocument {
540            title,
541            author,
542            version,
543            pages,
544            current_page: 0,
545            zoom: 1.0,
546        })
547    }
548
549    /// Parses raw HTML5 markup into a sanitized, zero-JS `HtmlDocument` ready for native `euv` rendering.
550    ///
551    /// # Arguments
552    ///
553    /// - `&str` - Raw HTML markup string.
554    ///
555    /// # Returns
556    ///
557    /// - `HtmlDocument` - Parsed document title, links count, and ordered `HtmlBlock` items.
558    #[must_use]
559    pub fn parse_html(raw: &str) -> HtmlDocument {
560        let mut title: String = String::new();
561        let mut blocks: Vec<HtmlBlock> = Vec::new();
562        let mut links_count: usize = 0;
563        let bytes: &[u8] = raw.as_bytes();
564        let mut i: usize = 0;
565        let mut current_kind: Option<HtmlNodeKind> = None;
566        let mut current_href: Option<String> = None;
567        let mut in_title: bool = false;
568        let mut in_script_or_style: bool = false;
569        let mut buf: String = String::new();
570        while i < bytes.len() {
571            if bytes[i] == BYTE_ANGLE_OPEN {
572                let text_chunk: String = Self::decode_html_entities(buf.trim());
573                buf.clear();
574                if !text_chunk.is_empty() && !in_script_or_style {
575                    if in_title {
576                        title = text_chunk;
577                    } else {
578                        let kind: HtmlNodeKind = current_kind.unwrap_or(HtmlNodeKind::Paragraph);
579                        if kind == HtmlNodeKind::Link {
580                            links_count += 1;
581                        }
582                        blocks.push(HtmlBlock {
583                            kind,
584                            text: text_chunk,
585                            href: current_href.clone(),
586                            src: None,
587                        });
588                    }
589                }
590                let Some(close_rel) = raw[i..].find('>') else {
591                    break;
592                };
593                let tag_inner: &str = raw[i + 1..i + close_rel].trim();
594                let tag_b: &[u8] = tag_inner.as_bytes();
595                if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_SCRIPT)
596                    || Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_STYLE)
597                {
598                    in_script_or_style = true;
599                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_CLOSE_SCRIPT)
600                    || Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_CLOSE_STYLE)
601                {
602                    in_script_or_style = false;
603                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_TITLE) {
604                    in_title = true;
605                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_CLOSE_TITLE) {
606                    in_title = false;
607                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_HR) {
608                    blocks.push(HtmlBlock {
609                        kind: HtmlNodeKind::HorizontalRule,
610                        text: String::new(),
611                        href: None,
612                        src: None,
613                    });
614                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_IMG) {
615                    let src_val: Option<String> = Self::extract_html_attr(tag_inner, "src");
616                    let alt_val: String = Self::extract_html_attr(tag_inner, "alt")
617                        .unwrap_or_else(|| "Embedded Image".to_string());
618                    blocks.push(HtmlBlock {
619                        kind: HtmlNodeKind::Image,
620                        text: alt_val,
621                        href: None,
622                        src: src_val,
623                    });
624                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_H1) {
625                    current_kind = Some(HtmlNodeKind::Heading(1));
626                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_H2) {
627                    current_kind = Some(HtmlNodeKind::Heading(2));
628                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_H3) {
629                    current_kind = Some(HtmlNodeKind::Heading(3));
630                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_BLOCKQUOTE) {
631                    current_kind = Some(HtmlNodeKind::Blockquote);
632                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_PRE)
633                    || Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_CODE)
634                {
635                    current_kind = Some(HtmlNodeKind::CodeBlock);
636                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_LI) {
637                    current_kind = Some(HtmlNodeKind::ListItem);
638                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_A_SPACE)
639                    || tag_b.eq_ignore_ascii_case(HTML_TAG_A)
640                {
641                    current_kind = Some(HtmlNodeKind::Link);
642                    current_href = Self::extract_html_attr(tag_inner, "href");
643                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_P_SPACE)
644                    || tag_b.eq_ignore_ascii_case(HTML_TAG_P)
645                {
646                    current_kind = Some(HtmlNodeKind::Paragraph);
647                } else if tag_b.starts_with(HTML_TAG_CLOSE_PREFIX) {
648                    current_kind = None;
649                    current_href = None;
650                }
651                i += close_rel + 1;
652            } else {
653                let ch: char = raw[i..].chars().next().unwrap_or(' ');
654                buf.push(ch);
655                i += ch.len_utf8();
656            }
657        }
658        let trailing: String = Self::decode_html_entities(buf.trim());
659        if !trailing.is_empty() && !in_script_or_style {
660            blocks.push(HtmlBlock {
661                kind: current_kind.unwrap_or(HtmlNodeKind::Paragraph),
662                text: trailing,
663                href: current_href,
664                src: None,
665            });
666        }
667        if title.is_empty() {
668            title = blocks
669                .iter()
670                .find(|b: &&HtmlBlock| matches!(b.get_kind(), HtmlNodeKind::Heading(_)))
671                .map(|b: &HtmlBlock| b.get_text().clone())
672                .unwrap_or_else(|| "HTML Document".to_string());
673        }
674        HtmlDocument {
675            title,
676            raw_html: raw.to_string(),
677            blocks,
678            links_count,
679        }
680    }
681
682    /// Parses an SVG document (`<svg>`, `<rect>`, `<circle>`, `<line>`) and rasterizes it into an `ImageBuffer`.
683    ///
684    /// # Arguments
685    ///
686    /// - `&str` - Raw SVG XML source.
687    /// - `u32` - Target rasterization width in pixels.
688    /// - `u32` - Target rasterization height in pixels.
689    ///
690    /// # Returns
691    ///
692    /// - `Result<SvgDocument, String>` - Parsed and rasterized `SvgDocument` or error.
693    pub fn parse_and_rasterize_svg(
694        raw_svg: &str,
695        out_w: u32,
696        out_h: u32,
697    ) -> Result<SvgDocument, String> {
698        if !raw_svg.contains(TAG_SVG_OPEN) {
699            return Err("invalid SVG document (missing <svg> root)".to_string());
700        }
701        let w: u32 = out_w.clamp(16, 512);
702        let h: u32 = out_h.clamp(16, 512);
703        let mut vb_w: f32 = w as f32;
704        let mut vb_h: f32 = h as f32;
705        if let Some(vb_str) = Self::extract_html_attr(raw_svg, "viewBox") {
706            let nums: Vec<f32> = vb_str
707                .split_whitespace()
708                .filter_map(|s: &str| s.parse::<f32>().ok())
709                .collect();
710            if nums.len() >= 4 {
711                vb_w = nums[2].max(1.0);
712                vb_h = nums[3].max(1.0);
713            }
714        }
715        let scale_x: f32 = (w as f32) / vb_w;
716        let scale_y: f32 = (h as f32) / vb_h;
717        let mut pixels: Vec<u8> = vec![0; (w as usize) * (h as usize) * 4];
718        let mut primitive_count: usize = 0;
719        let mut cursor: usize = 0;
720        while let Some(open_rel) = raw_svg[cursor..].find('<') {
721            let start: usize = cursor + open_rel;
722            let Some(close_rel) = raw_svg[start..].find('>') else {
723                break;
724            };
725            let tag: &str = raw_svg[start + 1..start + close_rel].trim();
726            cursor = start + close_rel + 1;
727            if tag.starts_with("rect") {
728                let x: f32 = Self::attr_f32(tag, "x", 0.0) * scale_x;
729                let y: f32 = Self::attr_f32(tag, "y", 0.0) * scale_y;
730                let rw: f32 = Self::attr_f32(tag, "width", vb_w) * scale_x;
731                let rh: f32 = Self::attr_f32(tag, "height", vb_h) * scale_y;
732                let col: Color = Self::parse_hex_color(
733                    Self::extract_html_attr(tag, "fill")
734                        .as_deref()
735                        .unwrap_or("#0F172A"),
736                );
737                Self::fill_rect_rgba(&mut pixels, w, h, Rect::new(x, y, rw, rh), col);
738                primitive_count += 1;
739            } else if tag.starts_with("circle") {
740                let cx: f32 = Self::attr_f32(tag, "cx", vb_w * 0.5) * scale_x;
741                let cy: f32 = Self::attr_f32(tag, "cy", vb_h * 0.5) * scale_y;
742                let r: f32 = Self::attr_f32(tag, "r", 16.0) * scale_x.min(scale_y);
743                let col: Color = Self::parse_hex_color(
744                    Self::extract_html_attr(tag, "fill")
745                        .as_deref()
746                        .unwrap_or("#38BDF8"),
747                );
748                Self::fill_circle_rgba(&mut pixels, w, h, cx, cy, r, col);
749                primitive_count += 1;
750            } else if tag.starts_with("line") {
751                let x1: f32 = Self::attr_f32(tag, "x1", 0.0) * scale_x;
752                let y1: f32 = Self::attr_f32(tag, "y1", 0.0) * scale_y;
753                let x2: f32 = Self::attr_f32(tag, "x2", vb_w) * scale_x;
754                let y2: f32 = Self::attr_f32(tag, "y2", vb_h) * scale_y;
755                let col: Color = Self::parse_hex_color(
756                    Self::extract_html_attr(tag, "stroke")
757                        .as_deref()
758                        .unwrap_or("#FFFFFF"),
759                );
760                Self::draw_line_rgba(
761                    &mut pixels,
762                    w,
763                    h,
764                    Point::new(x1, y1),
765                    Point::new(x2, y2),
766                    col,
767                );
768                primitive_count += 1;
769            }
770        }
771        Ok(SvgDocument {
772            view_box_width: vb_w,
773            view_box_height: vb_h,
774            raw_svg: raw_svg.to_string(),
775            rasterized: ImageBuffer::new(w, h, pixels),
776            primitive_count,
777        })
778    }
779
780    /// Computes normalized RMS waveform bar peaks (`0.08..=1.0`) from PCM samples.
781    ///
782    /// # Arguments
783    ///
784    /// - `&[f32]` - Input PCM samples.
785    /// - `usize` - Number of output bars.
786    ///
787    /// # Returns
788    ///
789    /// - `Vec<f32>` - Normalized bar peak heights.
790    #[must_use]
791    pub fn compute_waveform_peaks(samples: &[f32], bars: usize) -> Vec<f32> {
792        let count: usize = bars.max(8);
793        if samples.is_empty() {
794            return vec![0.25; count];
795        }
796        let step: usize = (samples.len() / count).max(1);
797        let mut peaks: Vec<f32> = Vec::with_capacity(count);
798        for i in 0..count {
799            let start: usize = (i * step).min(samples.len());
800            let end: usize = (start + step).min(samples.len());
801            let mut sum_sq: f32 = 0.0;
802            let len: usize = end.saturating_sub(start).max(1);
803            for s in &samples[start..end] {
804                sum_sq += (*s) * (*s);
805            }
806            let rms: f32 = (sum_sq / (len as f32)).sqrt();
807            peaks.push((rms * 1.45).clamp(0.10, 1.0));
808        }
809        peaks
810    }
811
812    /// Synthesizes a clean multi-band gradient + orbiting geometric emblem frame for sample GIF/Video/LIVE buffers.
813    ///
814    /// # Arguments
815    ///
816    /// - `u32` - Frame width in pixels.
817    /// - `u32` - Frame height in pixels.
818    /// - `Color` - Base background tone.
819    /// - `Color` - Primary accent tone.
820    /// - `usize` - Animation frame index.
821    ///
822    /// # Returns
823    ///
824    /// - `ImageBuffer` - Rendered RGBA8 bitmap frame.
825    #[must_use]
826    pub fn synthesize_frame(
827        width: u32,
828        height: u32,
829        bg: Color,
830        accent: Color,
831        frame_idx: usize,
832    ) -> ImageBuffer {
833        let w: u32 = width.max(16);
834        let h: u32 = height.max(16);
835        let mut pixels: Vec<u8> = vec![0; (w as usize) * (h as usize) * 4];
836        let phase: f32 = (frame_idx as f32) * 0.55;
837        let orb_x: f32 = (w as f32) * (0.5 + 0.28 * phase.cos());
838        let orb_y: f32 = (h as f32) * (0.48 + 0.18 * (phase * 1.3).sin());
839        let orb_r: f32 = (w.min(h) as f32) * 0.22;
840        let bg_r: f32 = bg.get_r() as f32;
841        let bg_g: f32 = bg.get_g() as f32;
842        let bg_b: f32 = bg.get_b() as f32;
843        let ac_r: f32 = accent.get_r() as f32;
844        let ac_g: f32 = accent.get_g() as f32;
845        let ac_b: f32 = accent.get_b() as f32;
846        for y in 0..h {
847            let fy: f32 = y as f32;
848            let v: f32 = fy / (h as f32);
849            let row: usize = (y as usize) * (w as usize) * 4;
850            for x in 0..w {
851                let fx: f32 = x as f32;
852                let u: f32 = fx / (w as f32);
853                let dx: f32 = fx - orb_x;
854                let dy: f32 = fy - orb_y;
855                let dist: f32 = (dx * dx + dy * dy).sqrt();
856                let glow: f32 = (1.0 - (dist / (orb_r * 2.2)).clamp(0.0, 1.0)).powf(2.0);
857                let horizon: f32 = if v > 0.68 { (v - 0.68) * 1.4 } else { 0.0 };
858                let wave: f32 = ((u * 8.0 + phase).sin() * 0.5 + 0.5) * horizon;
859                let mix: f32 = (glow * 0.85 + wave * 0.45 + v * 0.18).clamp(0.0, 1.0);
860                let idx: usize = row + (x as usize) * 4;
861                pixels[idx] = (bg_r + (ac_r - bg_r) * mix).clamp(0.0, 255.0) as u8;
862                pixels[idx + 1] = (bg_g + (ac_g - bg_g) * mix).clamp(0.0, 255.0) as u8;
863                pixels[idx + 2] = (bg_b + (ac_b - bg_b) * mix).clamp(0.0, 255.0) as u8;
864                pixels[idx + 3] = 255;
865            }
866        }
867        ImageBuffer::new(w, h, pixels)
868    }
869
870    /// Extracts a PDF Info dictionary parenthesized value such as `/Title (Hello)`.
871    ///
872    /// # Arguments
873    ///
874    /// - `&str` - Decoded PDF ASCII text.
875    /// - `&str` - Dictionary key prefix (e.g. `"/Title"`).
876    ///
877    /// # Returns
878    ///
879    /// - `Option<String>` - Extracted string value if present.
880    #[must_use]
881    fn extract_pdf_dict_string(text: &str, key: &str) -> Option<String> {
882        let pos: usize = text.find(key)?;
883        let rest: &str = text.get(pos + key.len()..)?.trim_start();
884        let after_open: &str = rest.strip_prefix('(')?;
885        let close: usize = after_open.find(')')?;
886        let val: String = after_open[..close].trim().to_string();
887        if val.is_empty() { None } else { Some(val) }
888    }
889
890    /// Extracts an HTML/XML quoted attribute value (`attr="value"` or `attr='value'`).
891    ///
892    /// # Arguments
893    ///
894    /// - `&str` - Tag inner source slice.
895    /// - `&str` - Attribute name.
896    ///
897    /// # Returns
898    ///
899    /// - `Option<String>` - Unquoted attribute value if present.
900    #[must_use]
901    fn extract_html_attr(tag: &str, attr: &str) -> Option<String> {
902        let needle_dq: String = format!("{attr}=\"");
903        if let Some(pos) = tag.find(&needle_dq) {
904            let rest: &str = &tag[pos + needle_dq.len()..];
905            let end: usize = rest.find('"')?;
906            return Some(rest[..end].to_string());
907        }
908        let needle_sq: String = format!("{attr}='");
909        if let Some(pos) = tag.find(&needle_sq) {
910            let rest: &str = &tag[pos + needle_sq.len()..];
911            let end: usize = rest.find('\'')?;
912            return Some(rest[..end].to_string());
913        }
914        None
915    }
916
917    /// Parses a numeric SVG attribute with fallback default.
918    ///
919    /// # Arguments
920    ///
921    /// - `&str` - Tag inner string.
922    /// - `&str` - Attribute name.
923    /// - `f32` - Default fallback scalar.
924    ///
925    /// # Returns
926    ///
927    /// - `f32` - Parsed value or default.
928    #[must_use]
929    fn attr_f32(tag: &str, attr: &str, default: f32) -> f32 {
930        Self::extract_html_attr(tag, attr)
931            .and_then(|s: String| s.trim_end_matches("px").parse::<f32>().ok())
932            .unwrap_or(default)
933    }
934
935    /// Decodes standard HTML character entities into UTF-8 text.
936    ///
937    /// # Arguments
938    ///
939    /// - `&str` - Input text slice.
940    ///
941    /// # Returns
942    ///
943    /// - `String` - Decoded string.
944    #[must_use]
945    fn decode_html_entities(s: &str) -> String {
946        s.replace("&amp;", "&")
947            .replace("&lt;", "<")
948            .replace("&gt;", ">")
949            .replace("&quot;", "\"")
950            .replace("&#39;", "'")
951            .replace("&nbsp;", " ")
952    }
953
954    /// Parses a `#RRGGBB` hex color string with safe fallback.
955    ///
956    /// # Arguments
957    ///
958    /// - `&str` - Hex color text.
959    ///
960    /// # Returns
961    ///
962    /// - `Color` - Parsed RGBA color.
963    #[must_use]
964    fn parse_hex_color(raw: &str) -> Color {
965        let trimmed: &str = raw.trim().trim_start_matches('#');
966        if trimmed.len() == 6
967            && let Ok(val) = u32::from_str_radix(trimmed, 16)
968        {
969            return Color::hex(val);
970        }
971        Color::hex(0x38BDF8)
972    }
973
974    /// Rasterizes a solid axis-aligned rectangle into `pixels`.
975    ///
976    /// # Arguments
977    ///
978    /// - `&mut [u8]` - Destination RGBA8 buffer.
979    /// - `u32` - Buffer width.
980    /// - `u32` - Buffer height.
981    /// - `Rect` - Rectangle bounds in pixel coordinates.
982    /// - `Color` - Fill color.
983    fn fill_rect_rgba(pixels: &mut [u8], w: u32, h: u32, rect: Rect, color: Color) {
984        let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(w);
985        let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(h);
986        let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(w);
987        let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(h);
988        let rgba: [u8; 4] = color.to_rgba_bytes();
989        for py in y0..y1 {
990            let row: usize = (py as usize) * (w as usize) * 4;
991            for px in x0..x1 {
992                let idx: usize = row + (px as usize) * 4;
993                pixels[idx..idx + 4].copy_from_slice(&rgba);
994            }
995        }
996    }
997
998    /// Rasterizes a filled circle into `pixels`.
999    ///
1000    /// # Arguments
1001    ///
1002    /// - `&mut [u8]` - Destination RGBA8 buffer.
1003    /// - `u32` - Buffer width.
1004    /// - `u32` - Buffer height.
1005    /// - `f32` - Center X coordinate.
1006    /// - `f32` - Center Y coordinate.
1007    /// - `f32` - Circle radius.
1008    /// - `Color` - Fill color.
1009    fn fill_circle_rgba(pixels: &mut [u8], w: u32, h: u32, cx: f32, cy: f32, r: f32, color: Color) {
1010        let pad: f32 = r + 1.5;
1011        let x0: u32 = ((cx - pad).floor().max(0.0) as u32).min(w);
1012        let y0: u32 = ((cy - pad).floor().max(0.0) as u32).min(h);
1013        let x1: u32 = ((cx + pad).ceil().max(0.0) as u32).min(w);
1014        let y1: u32 = ((cy + pad).ceil().max(0.0) as u32).min(h);
1015        let rgba: [u8; 4] = color.to_rgba_bytes();
1016        let src_a: f32 = (rgba[3] as f32) / 255.0;
1017        for py in y0..y1 {
1018            let dy: f32 = (py as f32) + 0.5 - cy;
1019            let row: usize = (py as usize) * (w as usize) * 4;
1020            for px in x0..x1 {
1021                let dx: f32 = (px as f32) + 0.5 - cx;
1022                let dist: f32 = (dx * dx + dy * dy).sqrt();
1023                let cov: f32 = (r + 0.5 - dist).clamp(0.0, 1.0) * src_a;
1024                if cov <= 0.0 {
1025                    continue;
1026                }
1027                let idx: usize = row + (px as usize) * 4;
1028                if cov >= 0.999 {
1029                    pixels[idx..idx + 4].copy_from_slice(&rgba);
1030                } else {
1031                    let inv: f32 = 1.0 - cov;
1032                    pixels[idx] =
1033                        ((rgba[0] as f32) * cov + (pixels[idx] as f32) * inv).round() as u8;
1034                    pixels[idx + 1] =
1035                        ((rgba[1] as f32) * cov + (pixels[idx + 1] as f32) * inv).round() as u8;
1036                    pixels[idx + 2] =
1037                        ((rgba[2] as f32) * cov + (pixels[idx + 2] as f32) * inv).round() as u8;
1038                    pixels[idx + 3] = 255;
1039                }
1040            }
1041        }
1042    }
1043
1044    /// Rasterizes a straight line segment into `pixels` using uniform sampling.
1045    ///
1046    /// # Arguments
1047    ///
1048    /// - `&mut [u8]` - Destination RGBA8 buffer.
1049    /// - `u32` - Buffer width.
1050    /// - `u32` - Buffer height.
1051    /// - `Point` - Segment start point.
1052    /// - `Point` - Segment end point.
1053    /// - `Color` - Stroke color.
1054    fn draw_line_rgba(pixels: &mut [u8], w: u32, h: u32, from: Point, to: Point, color: Color) {
1055        let dx: f32 = to.get_x() - from.get_x();
1056        let dy: f32 = to.get_y() - from.get_y();
1057        let steps: usize = (dx.abs().max(dy.abs()).ceil() as usize).max(1);
1058        let rgba: [u8; 4] = color.to_rgba_bytes();
1059        for i in 0..=steps {
1060            let t: f32 = (i as f32) / (steps as f32);
1061            let px: i32 = (from.get_x() + dx * t).round() as i32;
1062            let py: i32 = (from.get_y() + dy * t).round() as i32;
1063            if px >= 0 && py >= 0 && (px as u32) < w && (py as u32) < h {
1064                let idx: usize = ((py as usize) * (w as usize) + (px as usize)) * 4;
1065                pixels[idx..idx + 4].copy_from_slice(&rgba);
1066            }
1067        }
1068    }
1069}