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    /// Sniffs `MediaKind` from raw payload magic bytes first, falling back to `uri` extension.
6    ///
7    /// # Arguments
8    ///
9    /// - `&str` - Source URI or filename.
10    /// - `&[u8]` - Optional leading raw bytes.
11    ///
12    /// # Returns
13    ///
14    /// - `MediaKind` - Detected high-level media type.
15    #[must_use]
16    pub fn detect_media_kind(uri: &str, bytes: &[u8]) -> MediaKind {
17        if bytes.starts_with(MAGIC_PDF) {
18            return MediaKind::Pdf;
19        }
20        if bytes.starts_with(MAGIC_GIF87A) || bytes.starts_with(MAGIC_GIF89A) {
21            return MediaKind::AnimatedGif;
22        }
23        if bytes.len() >= 12 && &bytes[0..4] == MAGIC_RIFF && &bytes[8..12] == MAGIC_WAVE {
24            return MediaKind::Audio;
25        }
26        if bytes.len() >= 12 && &bytes[0..4] == MAGIC_RIFF && &bytes[8..12] == MAGIC_WEBP {
27            return MediaKind::Image;
28        }
29        if bytes.starts_with(MAGIC_PNG)
30            || bytes.starts_with(&[0xFF, 0xD8, 0xFF])
31            || bytes.starts_with(MAGIC_BMP)
32        {
33            return MediaKind::Image;
34        }
35        if bytes.starts_with(MAGIC_ID3)
36            || (bytes.len() >= 2 && bytes[0] == 0xFF && (bytes[1] & 0xE0) == 0xE0)
37        {
38            return MediaKind::Audio;
39        }
40        if bytes.len() >= 8 && &bytes[4..8] == MAGIC_FTYP {
41            return MediaKind::Video;
42        }
43        if let Ok(text) = from_utf8(bytes) {
44            let trimmed: &str = text.trim_start();
45            let lower: String = trimmed
46                .chars()
47                .take(32)
48                .collect::<String>()
49                .to_ascii_lowercase();
50            if lower.starts_with(TAG_SVG_OPEN) || lower.contains("<svg ") {
51                return MediaKind::Svg;
52            }
53            if lower.starts_with("<!doctype html")
54                || lower.starts_with("<html")
55                || lower.starts_with("<article")
56                || lower.starts_with("<div")
57            {
58                return MediaKind::Html;
59            }
60        }
61        let lower_uri: String = uri.to_ascii_lowercase();
62        if lower_uri.ends_with(EXT_GIF) {
63            MediaKind::AnimatedGif
64        } else if lower_uri.ends_with(".live") || lower_uri.ends_with(".livp") {
65            MediaKind::LivePhoto
66        } else if lower_uri.ends_with(".mp4")
67            || lower_uri.ends_with(".mov")
68            || lower_uri.ends_with(".webm")
69            || lower_uri.ends_with(".mkv")
70        {
71            MediaKind::Video
72        } else if lower_uri.ends_with(".wav")
73            || lower_uri.ends_with(".mp3")
74            || lower_uri.ends_with(".aac")
75            || lower_uri.ends_with(".ogg")
76            || lower_uri.ends_with(".flac")
77        {
78            MediaKind::Audio
79        } else if lower_uri.ends_with(".pdf") {
80            MediaKind::Pdf
81        } else if lower_uri.ends_with(".html") || lower_uri.ends_with(".htm") {
82            MediaKind::Html
83        } else if lower_uri.ends_with(EXT_SVG) {
84            MediaKind::Svg
85        } else {
86            MediaKind::Image
87        }
88    }
89
90    /// Detects the encoded `ImageFormat` from leading magic bytes or filename extension.
91    ///
92    /// # Arguments
93    ///
94    /// - `&str` - Source URI or filename.
95    /// - `&[u8]` - Optional leading bytes.
96    ///
97    /// # Returns
98    ///
99    /// - `ImageFormat` - Resolved image format.
100    #[must_use]
101    pub fn detect_image_format(uri: &str, bytes: &[u8]) -> ImageFormat {
102        if bytes.starts_with(MAGIC_PNG) {
103            return ImageFormat::Png;
104        }
105        if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
106            return ImageFormat::Jpeg;
107        }
108        if bytes.starts_with(MAGIC_GIF87A) || bytes.starts_with(MAGIC_GIF89A) {
109            return ImageFormat::Gif;
110        }
111        if bytes.starts_with(MAGIC_BMP) {
112            return ImageFormat::Bmp;
113        }
114        if bytes.len() >= 12 && &bytes[0..4] == MAGIC_RIFF && &bytes[8..12] == MAGIC_WEBP {
115            return ImageFormat::WebP;
116        }
117        let lower: String = uri.to_ascii_lowercase();
118        if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
119            ImageFormat::Jpeg
120        } else if lower.ends_with(".webp") {
121            ImageFormat::WebP
122        } else if lower.ends_with(EXT_GIF) {
123            ImageFormat::Gif
124        } else if lower.ends_with(".bmp") {
125            ImageFormat::Bmp
126        } else if lower.ends_with(EXT_SVG) {
127            ImageFormat::Svg
128        } else if lower.ends_with(".heic") || lower.ends_with(".heif") {
129            ImageFormat::Heic
130        } else if lower.ends_with(".avif") {
131            ImageFormat::Avif
132        } else {
133            ImageFormat::Png
134        }
135    }
136
137    /// Decodes an uncompressed 24-bit or 32-bit Windows BMP byte slice into an `ImageAsset`.
138    ///
139    /// # Arguments
140    ///
141    /// - `&[u8]` - Raw `.bmp` file bytes.
142    /// - `&str` - Accessibility alt text.
143    ///
144    /// # Returns
145    ///
146    /// - `Result<ImageAsset, String>` - Decoded `ImageAsset` or format error message.
147    pub fn decode_bmp(bytes: &[u8], alt_text: &str) -> Result<ImageAsset, String> {
148        if bytes.len() < 54 || &bytes[0..2] != MAGIC_BMP {
149            return Err("invalid BMP header".to_string());
150        }
151        let data_offset: usize =
152            u32::from_le_bytes([bytes[10], bytes[11], bytes[12], bytes[13]]) as usize;
153        let width_i: i32 = i32::from_le_bytes([bytes[18], bytes[19], bytes[20], bytes[21]]);
154        let height_i: i32 = i32::from_le_bytes([bytes[22], bytes[23], bytes[24], bytes[25]]);
155        let bpp: u16 = u16::from_le_bytes([bytes[28], bytes[29]]);
156        let compression: u32 = u32::from_le_bytes([bytes[30], bytes[31], bytes[32], bytes[33]]);
157        let bad_dims: bool = width_i <= 0 || height_i == 0;
158        let bad_fmt: bool = compression != 0 || (bpp != 24 && bpp != 32);
159        if bad_dims || bad_fmt {
160            return Err(
161                "unsupported BMP pixel layout (expected uncompressed 24/32bpp)".to_string(),
162            );
163        }
164        let width: u32 = width_i as u32;
165        let height: u32 = height_i.unsigned_abs();
166        let top_down: bool = height_i < 0;
167        let bytes_per_pixel: usize = (bpp / 8) as usize;
168        let row_stride: usize = ((width as usize) * bytes_per_pixel + 3) & !3;
169        let needed: usize = data_offset.saturating_add(row_stride.saturating_mul(height as usize));
170        if bytes.len() < needed {
171            return Err("truncated BMP pixel payload".to_string());
172        }
173        let mut rgba: Vec<u8> = vec![255; (width as usize) * (height as usize) * 4];
174        for y in 0..height {
175            let src_y: usize = if top_down {
176                y as usize
177            } else {
178                (height - 1 - y) as usize
179            };
180            let src_row: usize = data_offset + src_y * row_stride;
181            let dst_row: usize = (y as usize) * (width as usize) * 4;
182            for x in 0..width {
183                let s: usize = src_row + (x as usize) * bytes_per_pixel;
184                let d: usize = dst_row + (x as usize) * 4;
185                rgba[d] = bytes[s + 2];
186                rgba[d + 1] = bytes[s + 1];
187                rgba[d + 2] = bytes[s];
188                rgba[d + 3] = if bytes_per_pixel == 4 {
189                    bytes[s + 3]
190                } else {
191                    255
192                };
193            }
194        }
195        let meta: MediaMetadata = MediaMetadata {
196            title: alt_text.to_string(),
197            width,
198            height,
199            duration_secs: 0.0,
200            page_count: 1,
201            frame_count: 1,
202            sample_rate_hz: 0,
203            channels: 0,
204            format_label: "BMP".to_string(),
205        };
206        Ok(ImageAsset {
207            format: ImageFormat::Bmp,
208            buffer: ImageBuffer::new(width, height, rgba),
209            alt_text: alt_text.to_string(),
210            metadata: meta,
211        })
212    }
213
214    /// Parses a GIF87a/GIF89a byte stream header, global color table, and Graphics Control frame timings.
215    ///
216    /// # Arguments
217    ///
218    /// - `&[u8]` - Raw `.gif` file bytes.
219    /// - `&str` - Asset title.
220    ///
221    /// # Returns
222    ///
223    /// - `Result<GifAnimation, String>` - Decoded multi-frame `GifAnimation` or parse error.
224    pub fn decode_gif(bytes: &[u8], title: &str) -> Result<GifAnimation, String> {
225        let valid_sig: bool = bytes.starts_with(MAGIC_GIF87A) || bytes.starts_with(MAGIC_GIF89A);
226        if bytes.len() < 13 || !valid_sig {
227            return Err("invalid GIF87a/GIF89a header".to_string());
228        }
229        let width: u32 = u16::from_le_bytes([bytes[6], bytes[7]]).max(1) as u32;
230        let height: u32 = u16::from_le_bytes([bytes[8], bytes[9]]).max(1) as u32;
231        let packed: u8 = bytes[10];
232        let has_gct: bool = (packed & 0x80) != 0;
233        let gct_entries: usize = if has_gct {
234            1_usize << ((packed & 0x07) + 1)
235        } else {
236            0
237        };
238        let mut cursor: usize = 13;
239        let mut palette: Vec<Color> = Vec::new();
240        if has_gct && cursor + gct_entries * 3 <= bytes.len() {
241            for i in 0..gct_entries {
242                let off: usize = cursor + i * 3;
243                palette.push(Color::rgb(bytes[off], bytes[off + 1], bytes[off + 2]));
244            }
245            cursor += gct_entries * 3;
246        }
247        if palette.is_empty() {
248            palette.push(Color::hex(0x0F172A));
249            palette.push(Color::hex(0x38BDF8));
250            palette.push(Color::hex(0xA855F7));
251            palette.push(Color::hex(0x34D399));
252        }
253        let mut frames: Vec<MediaFrame> = Vec::new();
254        let mut next_delay_ms: u32 = 100;
255        let mut elapsed_sec: f32 = 0.0;
256        while cursor < bytes.len() {
257            let intro: u8 = bytes[cursor];
258            cursor += 1;
259            if intro == 0x3B {
260                break;
261            }
262            if intro == 0x21 && cursor < bytes.len() {
263                let label: u8 = bytes[cursor];
264                cursor += 1;
265                if label == 0xF9 && cursor + 5 < bytes.len() && bytes[cursor] == 4 {
266                    let delay_cs: u16 = u16::from_le_bytes([bytes[cursor + 2], bytes[cursor + 3]]);
267                    next_delay_ms = ((delay_cs as u32) * 10).max(20);
268                }
269                while cursor < bytes.len() {
270                    let sub_len: usize = bytes[cursor] as usize;
271                    cursor += 1;
272                    if sub_len == 0 {
273                        break;
274                    }
275                    cursor = cursor.saturating_add(sub_len).min(bytes.len());
276                }
277            } else if intro == 0x2C && cursor + 9 <= bytes.len() {
278                let img_packed: u8 = bytes[cursor + 8];
279                cursor += 9;
280                if (img_packed & 0x80) != 0 {
281                    let lct_len: usize = (1_usize << ((img_packed & 0x07) + 1)) * 3;
282                    cursor = cursor.saturating_add(lct_len).min(bytes.len());
283                }
284                if cursor < bytes.len() {
285                    cursor += 1;
286                }
287                while cursor < bytes.len() {
288                    let sub_len: usize = bytes[cursor] as usize;
289                    cursor += 1;
290                    if sub_len == 0 {
291                        break;
292                    }
293                    cursor = cursor.saturating_add(sub_len).min(bytes.len());
294                }
295                let frame_idx: usize = frames.len();
296                let bg: Color = palette[frame_idx % palette.len()];
297                let accent: Color = palette[(frame_idx + 1) % palette.len()];
298                let img: ImageBuffer =
299                    Self::synthesize_frame(width.min(320), height.min(200), bg, accent, frame_idx);
300                frames.push(MediaFrame {
301                    image: img,
302                    delay_ms: next_delay_ms,
303                    timestamp_secs: elapsed_sec,
304                });
305                elapsed_sec += (next_delay_ms as f32) / 1000.0;
306                next_delay_ms = 100;
307            }
308        }
309        if frames.is_empty() {
310            frames.push(MediaFrame {
311                image: Self::synthesize_frame(
312                    width.min(320),
313                    height.min(200),
314                    palette[0],
315                    palette[1 % palette.len()],
316                    0,
317                ),
318                delay_ms: 100,
319                timestamp_secs: 0.0,
320            });
321            elapsed_sec = 0.1;
322        }
323        let frame_count: usize = frames.len();
324        Ok(GifAnimation {
325            frames,
326            loop_count: 0,
327            current_frame: 0,
328            elapsed_ms: 0,
329            playing: true,
330            metadata: MediaMetadata {
331                title: title.to_string(),
332                width,
333                height,
334                duration_secs: elapsed_sec,
335                page_count: 1,
336                frame_count,
337                sample_rate_hz: 0,
338                channels: 0,
339                format_label: "GIF89a".to_string(),
340            },
341        })
342    }
343
344    /// Decodes a RIFF PCM WAV audio byte slice (8-bit or 16-bit) into a normalized `AudioTrack` with waveform peaks.
345    ///
346    /// # Arguments
347    ///
348    /// - `&[u8]` - Raw `.wav` bytes.
349    /// - `&str` - Track title.
350    ///
351    /// # Returns
352    ///
353    /// - `Result<AudioTrack, String>` - Decoded `AudioTrack` or format error.
354    pub fn decode_wav(bytes: &[u8], title: &str) -> Result<AudioTrack, String> {
355        let bad_riff: bool = bytes.len() < 44 || &bytes[0..4] != MAGIC_RIFF;
356        if bad_riff || &bytes[8..12] != MAGIC_WAVE {
357            return Err("invalid RIFF WAVE header".to_string());
358        }
359        let mut cursor: usize = 12;
360        let mut channels: u16 = 1;
361        let mut sample_rate: u32 = 44_100;
362        let mut bits_per_sample: u16 = 16;
363        let mut pcm_bytes: &[u8] = &[];
364        while cursor + 8 <= bytes.len() {
365            let chunk_id: &[u8] = &bytes[cursor..cursor + 4];
366            let chunk_size: usize = u32::from_le_bytes([
367                bytes[cursor + 4],
368                bytes[cursor + 5],
369                bytes[cursor + 6],
370                bytes[cursor + 7],
371            ]) as usize;
372            let body_start: usize = cursor + 8;
373            let body_end: usize = body_start.saturating_add(chunk_size).min(bytes.len());
374            if chunk_id == MAGIC_WAV_FMT && body_end - body_start >= 16 {
375                channels =
376                    u16::from_le_bytes([bytes[body_start + 2], bytes[body_start + 3]]).max(1);
377                sample_rate = u32::from_le_bytes([
378                    bytes[body_start + 4],
379                    bytes[body_start + 5],
380                    bytes[body_start + 6],
381                    bytes[body_start + 7],
382                ])
383                .max(8_000);
384                bits_per_sample =
385                    u16::from_le_bytes([bytes[body_start + 14], bytes[body_start + 15]]);
386            } else if chunk_id == MAGIC_WAV_DATA {
387                pcm_bytes = &bytes[body_start..body_end];
388            }
389            let padded: usize = chunk_size + (chunk_size & 1);
390            cursor = body_start.saturating_add(padded);
391        }
392        if pcm_bytes.is_empty() {
393            return Err("WAV file contained no data chunk".to_string());
394        }
395        let mut samples: Vec<f32> = Vec::new();
396        if bits_per_sample == 16 {
397            for pair in pcm_bytes.as_chunks::<2>().0 {
398                let s: i16 = i16::from_le_bytes([pair[0], pair[1]]);
399                samples.push((s as f32) / 32_768.0);
400            }
401        } else if bits_per_sample == 8 {
402            for b in pcm_bytes.iter().copied() {
403                samples.push(((b as f32) - 128.0) / 128.0);
404            }
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 lower_tag: String = tag_inner.to_ascii_lowercase();
595                if lower_tag.starts_with("script") || lower_tag.starts_with("style") {
596                    in_script_or_style = true;
597                } else if lower_tag.starts_with("/script") || lower_tag.starts_with("/style") {
598                    in_script_or_style = false;
599                } else if lower_tag.starts_with("title") {
600                    in_title = true;
601                } else if lower_tag.starts_with("/title") {
602                    in_title = false;
603                } else if lower_tag.starts_with("hr") {
604                    blocks.push(HtmlBlock {
605                        kind: HtmlNodeKind::HorizontalRule,
606                        text: String::new(),
607                        href: None,
608                        src: None,
609                    });
610                } else if lower_tag.starts_with("img") {
611                    let src_val: Option<String> = Self::extract_html_attr(tag_inner, "src");
612                    let alt_val: String = Self::extract_html_attr(tag_inner, "alt")
613                        .unwrap_or_else(|| "Embedded Image".to_string());
614                    blocks.push(HtmlBlock {
615                        kind: HtmlNodeKind::Image,
616                        text: alt_val,
617                        href: None,
618                        src: src_val,
619                    });
620                } else if lower_tag.starts_with("h1") {
621                    current_kind = Some(HtmlNodeKind::Heading(1));
622                } else if lower_tag.starts_with("h2") {
623                    current_kind = Some(HtmlNodeKind::Heading(2));
624                } else if lower_tag.starts_with("h3") {
625                    current_kind = Some(HtmlNodeKind::Heading(3));
626                } else if lower_tag.starts_with("blockquote") {
627                    current_kind = Some(HtmlNodeKind::Blockquote);
628                } else if lower_tag.starts_with("pre") || lower_tag.starts_with("code") {
629                    current_kind = Some(HtmlNodeKind::CodeBlock);
630                } else if lower_tag.starts_with("li") {
631                    current_kind = Some(HtmlNodeKind::ListItem);
632                } else if lower_tag.starts_with("a ") || lower_tag == "a" {
633                    current_kind = Some(HtmlNodeKind::Link);
634                    current_href = Self::extract_html_attr(tag_inner, "href");
635                } else if lower_tag.starts_with("p ") || lower_tag == "p" {
636                    current_kind = Some(HtmlNodeKind::Paragraph);
637                } else if lower_tag.starts_with('/') {
638                    current_kind = None;
639                    current_href = None;
640                }
641                i += close_rel + 1;
642            } else {
643                let ch: char = raw[i..].chars().next().unwrap_or(' ');
644                buf.push(ch);
645                i += ch.len_utf8();
646            }
647        }
648        let trailing: String = Self::decode_html_entities(buf.trim());
649        if !trailing.is_empty() && !in_script_or_style {
650            blocks.push(HtmlBlock {
651                kind: current_kind.unwrap_or(HtmlNodeKind::Paragraph),
652                text: trailing,
653                href: current_href,
654                src: None,
655            });
656        }
657        if title.is_empty() {
658            title = blocks
659                .iter()
660                .find(|b: &&HtmlBlock| matches!(b.get_kind(), HtmlNodeKind::Heading(_)))
661                .map(|b: &HtmlBlock| b.get_text().clone())
662                .unwrap_or_else(|| "HTML Document".to_string());
663        }
664        HtmlDocument {
665            title,
666            raw_html: raw.to_string(),
667            blocks,
668            links_count,
669        }
670    }
671
672    /// Parses an SVG document (`<svg>`, `<rect>`, `<circle>`, `<line>`) and rasterizes it into an `ImageBuffer`.
673    ///
674    /// # Arguments
675    ///
676    /// - `&str` - Raw SVG XML source.
677    /// - `u32` - Target rasterization width in pixels.
678    /// - `u32` - Target rasterization height in pixels.
679    ///
680    /// # Returns
681    ///
682    /// - `Result<SvgDocument, String>` - Parsed and rasterized `SvgDocument` or error.
683    pub fn parse_and_rasterize_svg(
684        raw_svg: &str,
685        out_w: u32,
686        out_h: u32,
687    ) -> Result<SvgDocument, String> {
688        if !raw_svg.contains(TAG_SVG_OPEN) {
689            return Err("invalid SVG document (missing <svg> root)".to_string());
690        }
691        let w: u32 = out_w.clamp(16, 512);
692        let h: u32 = out_h.clamp(16, 512);
693        let mut vb_w: f32 = w as f32;
694        let mut vb_h: f32 = h as f32;
695        if let Some(vb_str) = Self::extract_html_attr(raw_svg, "viewBox") {
696            let nums: Vec<f32> = vb_str
697                .split_whitespace()
698                .filter_map(|s: &str| s.parse::<f32>().ok())
699                .collect();
700            if nums.len() >= 4 {
701                vb_w = nums[2].max(1.0);
702                vb_h = nums[3].max(1.0);
703            }
704        }
705        let scale_x: f32 = (w as f32) / vb_w;
706        let scale_y: f32 = (h as f32) / vb_h;
707        let mut pixels: Vec<u8> = vec![0; (w as usize) * (h as usize) * 4];
708        let mut primitive_count: usize = 0;
709        let mut cursor: usize = 0;
710        while let Some(open_rel) = raw_svg[cursor..].find('<') {
711            let start: usize = cursor + open_rel;
712            let Some(close_rel) = raw_svg[start..].find('>') else {
713                break;
714            };
715            let tag: &str = raw_svg[start + 1..start + close_rel].trim();
716            cursor = start + close_rel + 1;
717            if tag.starts_with("rect") {
718                let x: f32 = Self::attr_f32(tag, "x", 0.0) * scale_x;
719                let y: f32 = Self::attr_f32(tag, "y", 0.0) * scale_y;
720                let rw: f32 = Self::attr_f32(tag, "width", vb_w) * scale_x;
721                let rh: f32 = Self::attr_f32(tag, "height", vb_h) * scale_y;
722                let col: Color = Self::parse_hex_color(
723                    Self::extract_html_attr(tag, "fill")
724                        .as_deref()
725                        .unwrap_or("#0F172A"),
726                );
727                Self::fill_rect_rgba(&mut pixels, w, h, Rect::new(x, y, rw, rh), col);
728                primitive_count += 1;
729            } else if tag.starts_with("circle") {
730                let cx: f32 = Self::attr_f32(tag, "cx", vb_w * 0.5) * scale_x;
731                let cy: f32 = Self::attr_f32(tag, "cy", vb_h * 0.5) * scale_y;
732                let r: f32 = Self::attr_f32(tag, "r", 16.0) * scale_x.min(scale_y);
733                let col: Color = Self::parse_hex_color(
734                    Self::extract_html_attr(tag, "fill")
735                        .as_deref()
736                        .unwrap_or("#38BDF8"),
737                );
738                Self::fill_circle_rgba(&mut pixels, w, h, cx, cy, r, col);
739                primitive_count += 1;
740            } else if tag.starts_with("line") {
741                let x1: f32 = Self::attr_f32(tag, "x1", 0.0) * scale_x;
742                let y1: f32 = Self::attr_f32(tag, "y1", 0.0) * scale_y;
743                let x2: f32 = Self::attr_f32(tag, "x2", vb_w) * scale_x;
744                let y2: f32 = Self::attr_f32(tag, "y2", vb_h) * scale_y;
745                let col: Color = Self::parse_hex_color(
746                    Self::extract_html_attr(tag, "stroke")
747                        .as_deref()
748                        .unwrap_or("#FFFFFF"),
749                );
750                Self::draw_line_rgba(
751                    &mut pixels,
752                    w,
753                    h,
754                    Point::new(x1, y1),
755                    Point::new(x2, y2),
756                    col,
757                );
758                primitive_count += 1;
759            }
760        }
761        Ok(SvgDocument {
762            view_box_width: vb_w,
763            view_box_height: vb_h,
764            raw_svg: raw_svg.to_string(),
765            rasterized: ImageBuffer::new(w, h, pixels),
766            primitive_count,
767        })
768    }
769
770    /// Computes normalized RMS waveform bar peaks (`0.08..=1.0`) from PCM samples.
771    ///
772    /// # Arguments
773    ///
774    /// - `&[f32]` - Input PCM samples.
775    /// - `usize` - Number of output bars.
776    ///
777    /// # Returns
778    ///
779    /// - `Vec<f32>` - Normalized bar peak heights.
780    #[must_use]
781    pub fn compute_waveform_peaks(samples: &[f32], bars: usize) -> Vec<f32> {
782        let count: usize = bars.max(8);
783        if samples.is_empty() {
784            return vec![0.25; count];
785        }
786        let step: usize = (samples.len() / count).max(1);
787        let mut peaks: Vec<f32> = Vec::with_capacity(count);
788        for i in 0..count {
789            let start: usize = (i * step).min(samples.len());
790            let end: usize = (start + step).min(samples.len());
791            let mut sum_sq: f32 = 0.0;
792            let len: usize = end.saturating_sub(start).max(1);
793            for s in &samples[start..end] {
794                sum_sq += (*s) * (*s);
795            }
796            let rms: f32 = (sum_sq / (len as f32)).sqrt();
797            peaks.push((rms * 1.45).clamp(0.10, 1.0));
798        }
799        peaks
800    }
801
802    /// Synthesizes a clean multi-band gradient + orbiting geometric emblem frame for sample GIF/Video/LIVE buffers.
803    ///
804    /// # Arguments
805    ///
806    /// - `u32` - Frame width in pixels.
807    /// - `u32` - Frame height in pixels.
808    /// - `Color` - Base background tone.
809    /// - `Color` - Primary accent tone.
810    /// - `usize` - Animation frame index.
811    ///
812    /// # Returns
813    ///
814    /// - `ImageBuffer` - Rendered RGBA8 bitmap frame.
815    #[must_use]
816    pub fn synthesize_frame(
817        width: u32,
818        height: u32,
819        bg: Color,
820        accent: Color,
821        frame_idx: usize,
822    ) -> ImageBuffer {
823        let w: u32 = width.max(16);
824        let h: u32 = height.max(16);
825        let mut pixels: Vec<u8> = vec![0; (w as usize) * (h as usize) * 4];
826        let phase: f32 = (frame_idx as f32) * 0.55;
827        let orb_x: f32 = (w as f32) * (0.5 + 0.28 * phase.cos());
828        let orb_y: f32 = (h as f32) * (0.48 + 0.18 * (phase * 1.3).sin());
829        let orb_r: f32 = (w.min(h) as f32) * 0.22;
830        let bg_r: f32 = bg.get_r() as f32;
831        let bg_g: f32 = bg.get_g() as f32;
832        let bg_b: f32 = bg.get_b() as f32;
833        let ac_r: f32 = accent.get_r() as f32;
834        let ac_g: f32 = accent.get_g() as f32;
835        let ac_b: f32 = accent.get_b() as f32;
836        for y in 0..h {
837            let fy: f32 = y as f32;
838            let v: f32 = fy / (h as f32);
839            let row: usize = (y as usize) * (w as usize) * 4;
840            for x in 0..w {
841                let fx: f32 = x as f32;
842                let u: f32 = fx / (w as f32);
843                let dx: f32 = fx - orb_x;
844                let dy: f32 = fy - orb_y;
845                let dist: f32 = (dx * dx + dy * dy).sqrt();
846                let glow: f32 = (1.0 - (dist / (orb_r * 2.2)).clamp(0.0, 1.0)).powf(2.0);
847                let horizon: f32 = if v > 0.68 { (v - 0.68) * 1.4 } else { 0.0 };
848                let wave: f32 = ((u * 8.0 + phase).sin() * 0.5 + 0.5) * horizon;
849                let mix: f32 = (glow * 0.85 + wave * 0.45 + v * 0.18).clamp(0.0, 1.0);
850                let idx: usize = row + (x as usize) * 4;
851                pixels[idx] = (bg_r + (ac_r - bg_r) * mix).clamp(0.0, 255.0) as u8;
852                pixels[idx + 1] = (bg_g + (ac_g - bg_g) * mix).clamp(0.0, 255.0) as u8;
853                pixels[idx + 2] = (bg_b + (ac_b - bg_b) * mix).clamp(0.0, 255.0) as u8;
854                pixels[idx + 3] = 255;
855            }
856        }
857        ImageBuffer::new(w, h, pixels)
858    }
859
860    /// Extracts a PDF Info dictionary parenthesized value such as `/Title (Hello)`.
861    ///
862    /// # Arguments
863    ///
864    /// - `&str` - Decoded PDF ASCII text.
865    /// - `&str` - Dictionary key prefix (e.g. `"/Title"`).
866    ///
867    /// # Returns
868    ///
869    /// - `Option<String>` - Extracted string value if present.
870    #[must_use]
871    fn extract_pdf_dict_string(text: &str, key: &str) -> Option<String> {
872        let pos: usize = text.find(key)?;
873        let rest: &str = text.get(pos + key.len()..)?.trim_start();
874        let after_open: &str = rest.strip_prefix('(')?;
875        let close: usize = after_open.find(')')?;
876        let val: String = after_open[..close].trim().to_string();
877        if val.is_empty() { None } else { Some(val) }
878    }
879
880    /// Extracts an HTML/XML quoted attribute value (`attr="value"` or `attr='value'`).
881    ///
882    /// # Arguments
883    ///
884    /// - `&str` - Tag inner source slice.
885    /// - `&str` - Attribute name.
886    ///
887    /// # Returns
888    ///
889    /// - `Option<String>` - Unquoted attribute value if present.
890    #[must_use]
891    fn extract_html_attr(tag: &str, attr: &str) -> Option<String> {
892        let needle_dq: String = format!("{attr}=\"");
893        if let Some(pos) = tag.find(&needle_dq) {
894            let rest: &str = &tag[pos + needle_dq.len()..];
895            let end: usize = rest.find('"')?;
896            return Some(rest[..end].to_string());
897        }
898        let needle_sq: String = format!("{attr}='");
899        if let Some(pos) = tag.find(&needle_sq) {
900            let rest: &str = &tag[pos + needle_sq.len()..];
901            let end: usize = rest.find('\'')?;
902            return Some(rest[..end].to_string());
903        }
904        None
905    }
906
907    /// Parses a numeric SVG attribute with fallback default.
908    ///
909    /// # Arguments
910    ///
911    /// - `&str` - Tag inner string.
912    /// - `&str` - Attribute name.
913    /// - `f32` - Default fallback scalar.
914    ///
915    /// # Returns
916    ///
917    /// - `f32` - Parsed value or default.
918    #[must_use]
919    fn attr_f32(tag: &str, attr: &str, default: f32) -> f32 {
920        Self::extract_html_attr(tag, attr)
921            .and_then(|s: String| s.trim_end_matches("px").parse::<f32>().ok())
922            .unwrap_or(default)
923    }
924
925    /// Decodes standard HTML character entities into UTF-8 text.
926    ///
927    /// # Arguments
928    ///
929    /// - `&str` - Input text slice.
930    ///
931    /// # Returns
932    ///
933    /// - `String` - Decoded string.
934    #[must_use]
935    fn decode_html_entities(s: &str) -> String {
936        s.replace("&amp;", "&")
937            .replace("&lt;", "<")
938            .replace("&gt;", ">")
939            .replace("&quot;", "\"")
940            .replace("&#39;", "'")
941            .replace("&nbsp;", " ")
942    }
943
944    /// Parses a `#RRGGBB` hex color string with safe fallback.
945    ///
946    /// # Arguments
947    ///
948    /// - `&str` - Hex color text.
949    ///
950    /// # Returns
951    ///
952    /// - `Color` - Parsed RGBA color.
953    #[must_use]
954    fn parse_hex_color(raw: &str) -> Color {
955        let trimmed: &str = raw.trim().trim_start_matches('#');
956        if trimmed.len() == 6
957            && let Ok(val) = u32::from_str_radix(trimmed, 16)
958        {
959            return Color::hex(val);
960        }
961        Color::hex(0x38BDF8)
962    }
963
964    /// Rasterizes a solid axis-aligned rectangle into `pixels`.
965    ///
966    /// # Arguments
967    ///
968    /// - `&mut [u8]` - Destination RGBA8 buffer.
969    /// - `u32` - Buffer width.
970    /// - `u32` - Buffer height.
971    /// - `Rect` - Rectangle bounds in pixel coordinates.
972    /// - `Color` - Fill color.
973    fn fill_rect_rgba(pixels: &mut [u8], w: u32, h: u32, rect: Rect, color: Color) {
974        let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(w);
975        let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(h);
976        let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(w);
977        let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(h);
978        let rgba: [u8; 4] = color.to_rgba_bytes();
979        for py in y0..y1 {
980            let row: usize = (py as usize) * (w as usize) * 4;
981            for px in x0..x1 {
982                let idx: usize = row + (px as usize) * 4;
983                pixels[idx..idx + 4].copy_from_slice(&rgba);
984            }
985        }
986    }
987
988    /// Rasterizes a filled circle into `pixels`.
989    ///
990    /// # Arguments
991    ///
992    /// - `&mut [u8]` - Destination RGBA8 buffer.
993    /// - `u32` - Buffer width.
994    /// - `u32` - Buffer height.
995    /// - `f32` - Center X coordinate.
996    /// - `f32` - Center Y coordinate.
997    /// - `f32` - Circle radius.
998    /// - `Color` - Fill color.
999    fn fill_circle_rgba(pixels: &mut [u8], w: u32, h: u32, cx: f32, cy: f32, r: f32, color: Color) {
1000        let pad: f32 = r + 1.5;
1001        let x0: u32 = ((cx - pad).floor().max(0.0) as u32).min(w);
1002        let y0: u32 = ((cy - pad).floor().max(0.0) as u32).min(h);
1003        let x1: u32 = ((cx + pad).ceil().max(0.0) as u32).min(w);
1004        let y1: u32 = ((cy + pad).ceil().max(0.0) as u32).min(h);
1005        let rgba: [u8; 4] = color.to_rgba_bytes();
1006        let src_a: f32 = (rgba[3] as f32) / 255.0;
1007        for py in y0..y1 {
1008            let dy: f32 = (py as f32) + 0.5 - cy;
1009            let row: usize = (py as usize) * (w as usize) * 4;
1010            for px in x0..x1 {
1011                let dx: f32 = (px as f32) + 0.5 - cx;
1012                let dist: f32 = (dx * dx + dy * dy).sqrt();
1013                let cov: f32 = (r + 0.5 - dist).clamp(0.0, 1.0) * src_a;
1014                if cov <= 0.0 {
1015                    continue;
1016                }
1017                let idx: usize = row + (px as usize) * 4;
1018                if cov >= 0.999 {
1019                    pixels[idx..idx + 4].copy_from_slice(&rgba);
1020                } else {
1021                    let inv: f32 = 1.0 - cov;
1022                    pixels[idx] =
1023                        ((rgba[0] as f32) * cov + (pixels[idx] as f32) * inv).round() as u8;
1024                    pixels[idx + 1] =
1025                        ((rgba[1] as f32) * cov + (pixels[idx + 1] as f32) * inv).round() as u8;
1026                    pixels[idx + 2] =
1027                        ((rgba[2] as f32) * cov + (pixels[idx + 2] as f32) * inv).round() as u8;
1028                    pixels[idx + 3] = 255;
1029                }
1030            }
1031        }
1032    }
1033
1034    /// Rasterizes a straight line segment into `pixels` using uniform sampling.
1035    ///
1036    /// # Arguments
1037    ///
1038    /// - `&mut [u8]` - Destination RGBA8 buffer.
1039    /// - `u32` - Buffer width.
1040    /// - `u32` - Buffer height.
1041    /// - `Point` - Segment start point.
1042    /// - `Point` - Segment end point.
1043    /// - `Color` - Stroke color.
1044    fn draw_line_rgba(pixels: &mut [u8], w: u32, h: u32, from: Point, to: Point, color: Color) {
1045        let dx: f32 = to.get_x() - from.get_x();
1046        let dy: f32 = to.get_y() - from.get_y();
1047        let steps: usize = (dx.abs().max(dy.abs()).ceil() as usize).max(1);
1048        let rgba: [u8; 4] = color.to_rgba_bytes();
1049        for i in 0..=steps {
1050            let t: f32 = (i as f32) / (steps as f32);
1051            let px: i32 = (from.get_x() + dx * t).round() as i32;
1052            let py: i32 = (from.get_y() + dy * t).round() as i32;
1053            if px >= 0 && py >= 0 && (px as u32) < w && (py as u32) < h {
1054                let idx: usize = ((py as usize) * (w as usize) + (px as usize)) * 4;
1055                pixels[idx..idx + 4].copy_from_slice(&rgba);
1056            }
1057        }
1058    }
1059}