Skip to main content

euv_core/media/player/
impl.rs

1use super::*;
2
3/// Built-in sample constructors and helpers for `ImageAsset`.
4impl ImageAsset {
5    /// Generates a crisp high-contrast architectural sample photo asset for previews and tests.
6    ///
7    /// # Arguments
8    ///
9    /// - `&str` - Alternative accessibility caption.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Ready `ImageAsset`.
14    #[must_use]
15    pub fn sample_photo(alt_text: &str) -> Self {
16        let buf: ImageBuffer = MediaCodecRegistry::synthesize_frame(
17            240,
18            135,
19            Color::hex(0x0F172A),
20            Color::hex(0x38BDF8),
21            2,
22        );
23        Self {
24            format: ImageFormat::Png,
25            buffer: buf,
26            alt_text: alt_text.to_string(),
27            metadata: MediaMetadata {
28                title: alt_text.to_string(),
29                width: 240,
30                height: 135,
31                duration_secs: 0.0,
32                page_count: 1,
33                frame_count: 1,
34                sample_rate_hz: 0,
35                channels: 0,
36                format_label: "PNG · 240×135".to_string(),
37            },
38        }
39    }
40}
41
42/// Playback stepping and sample generation for `GifAnimation`.
43impl GifAnimation {
44    /// Creates an 8-frame looping neon GIF animation sample.
45    ///
46    /// # Returns
47    ///
48    /// - `Self` - Populated `GifAnimation`.
49    #[must_use]
50    pub fn sample_neon_gif() -> Self {
51        let accents: [Color; 4] = [
52            Color::hex(0x38BDF8),
53            Color::hex(0xA855F7),
54            Color::hex(0xF43F5E),
55            Color::hex(0x34D399),
56        ];
57        let mut frames: Vec<MediaFrame> = Vec::with_capacity(8);
58        for i in 0..8 {
59            frames.push(MediaFrame {
60                image: MediaCodecRegistry::synthesize_frame(
61                    220,
62                    124,
63                    Color::hex(0x111827),
64                    accents[i % accents.len()],
65                    i,
66                ),
67                delay_ms: 120,
68                timestamp_secs: (i as f32) * 0.12,
69            });
70        }
71        Self {
72            frames,
73            loop_count: 0,
74            current_frame: 0,
75            elapsed_ms: 0,
76            playing: true,
77            metadata: MediaMetadata {
78                title: "Neon Pulse Loop".to_string(),
79                width: 220,
80                height: 124,
81                duration_secs: 0.96,
82                page_count: 1,
83                frame_count: 8,
84                sample_rate_hz: 0,
85                channels: 0,
86                format_label: "GIF89a · 8f".to_string(),
87            },
88        }
89    }
90
91    /// Advances the GIF frame timer by `dt_ms` milliseconds when playing.
92    ///
93    /// # Arguments
94    ///
95    /// - `&Self` - Mutable GIF animation.
96    /// - `u32` - Elapsed time in milliseconds.
97    ///
98    /// # Returns
99    ///
100    /// - `bool` - `true` if the displayed frame index changed.
101    pub fn step_ms(&mut self, dt_ms: u32) -> bool {
102        if !self.get_playing() || self.get_frames().is_empty() {
103            return false;
104        }
105        let cur: usize = self.get_current_frame() % self.get_frames().len();
106        let delay: u32 = self.get_frames()[cur].get_delay_ms().max(16);
107        let next_elapsed: u32 = self.get_elapsed_ms().saturating_add(dt_ms);
108        if next_elapsed >= delay {
109            let next_idx: usize = (cur + 1) % self.get_frames().len();
110            self.set_current_frame(next_idx);
111            self.set_elapsed_ms(next_elapsed - delay);
112            true
113        } else {
114            self.set_elapsed_ms(next_elapsed);
115            false
116        }
117    }
118
119    /// Advances immediately to the next animation frame (useful when paused).
120    ///
121    /// # Arguments
122    ///
123    /// - `&Self` - Mutable GIF animation.
124    pub fn next_frame(&mut self) {
125        if !self.get_frames().is_empty() {
126            let next_idx: usize = (self.get_current_frame() + 1) % self.get_frames().len();
127            self.set_current_frame(next_idx);
128            self.set_elapsed_ms(0);
129        }
130    }
131
132    /// Returns the currently displayed `ImageBuffer` frame.
133    ///
134    /// # Arguments
135    ///
136    /// - `&Self` - GIF animation reference.
137    ///
138    /// # Returns
139    ///
140    /// - `ImageBuffer` - Active frame image buffer.
141    #[must_use]
142    pub fn active_image(&self) -> ImageBuffer {
143        self.get_frames()
144            .get(self.get_current_frame())
145            .or_else(|| self.get_frames().first())
146            .map(|f: &MediaFrame| f.get_image().clone())
147            .unwrap_or_else(|| ImageBuffer::solid(64, 64, Color::hex(0x0F172A)))
148    }
149}
150
151/// Interactive LIVE Photo motion burst playback and sample builder for `LivePhotoAsset`.
152impl LivePhotoAsset {
153    /// Builds a sample LIVE Photo with a sharp still keyframe, 6-frame motion burst, and ambient sound peaks.
154    ///
155    /// # Returns
156    ///
157    /// - `Self` - Ready `LivePhotoAsset`.
158    #[must_use]
159    pub fn sample_live_photo() -> Self {
160        let still: ImageBuffer = MediaCodecRegistry::synthesize_frame(
161            240,
162            135,
163            Color::hex(0x1E1B4B),
164            Color::hex(0xF59E0B),
165            0,
166        );
167        let mut motion_frames: Vec<MediaFrame> = Vec::with_capacity(6);
168        for i in 0..6 {
169            motion_frames.push(MediaFrame {
170                image: MediaCodecRegistry::synthesize_frame(
171                    240,
172                    135,
173                    Color::hex(0x1E1B4B),
174                    Color::hex(0xF59E0B),
175                    i + 1,
176                ),
177                delay_ms: 110,
178                timestamp_secs: (i as f32) * 0.11,
179            });
180        }
181        Self {
182            still_image: still,
183            motion_frames,
184            audio_waveform: vec![0.2, 0.45, 0.78, 0.92, 0.65, 0.50, 0.35, 0.22],
185            active_motion: false,
186            motion_elapsed_ms: 0,
187            muted: false,
188            metadata: MediaMetadata {
189                title: "Golden Hour Boulevard LIVE".to_string(),
190                width: 240,
191                height: 135,
192                duration_secs: 0.66,
193                page_count: 1,
194                frame_count: 6,
195                sample_rate_hz: 48_000,
196                channels: 2,
197                format_label: "LIVE · HEIC+MOV".to_string(),
198            },
199        }
200    }
201
202    /// Starts or stops the LIVE motion burst (called on press-and-hold or LIVE toggle).
203    ///
204    /// # Arguments
205    ///
206    /// - `&Self` - Mutable LIVE Photo asset.
207    /// - `bool` - `true` to begin motion playback, `false` to return to keyframe still.
208    pub fn set_motion_playing(&mut self, active: bool) {
209        self.set_active_motion(active);
210        if !active {
211            self.set_motion_elapsed_ms(0);
212        }
213    }
214
215    /// Advances the LIVE motion burst by `dt_ms` milliseconds.
216    ///
217    /// # Arguments
218    ///
219    /// - `&Self` - Mutable LIVE Photo asset.
220    /// - `u32` - Elapsed time in milliseconds.
221    pub fn step_ms(&mut self, dt_ms: u32) {
222        if !self.get_active_motion() || self.get_motion_frames().is_empty() {
223            return;
224        }
225        let total_ms: u32 = (self.get_motion_frames().len() as u32) * 110;
226        let next: u32 = self.get_motion_elapsed_ms().saturating_add(dt_ms);
227        if next >= total_ms {
228            self.set_motion_elapsed_ms(0);
229            self.set_active_motion(false);
230        } else {
231            self.set_motion_elapsed_ms(next);
232        }
233    }
234
235    /// Returns either the keyframe still photo or the active LIVE motion frame.
236    ///
237    /// # Arguments
238    ///
239    /// - `&Self` - LIVE Photo reference.
240    ///
241    /// # Returns
242    ///
243    /// - `ImageBuffer` - Current display image buffer.
244    #[must_use]
245    pub fn active_image(&self) -> ImageBuffer {
246        if !self.get_active_motion() || self.get_motion_frames().is_empty() {
247            return self.get_still_image().clone();
248        }
249        let idx: usize =
250            ((self.get_motion_elapsed_ms() / 110) as usize) % self.get_motion_frames().len();
251        self.get_motion_frames()[idx].get_image().clone()
252    }
253}
254
255/// Transport playback, seeking, captions, and sample builder for `VideoTrack`.
256impl VideoTrack {
257    /// Generates a deterministic 12-second sample video track with poster, timed frames, and closed captions.
258    ///
259    /// # Returns
260    ///
261    /// - `Self` - Ready `VideoTrack`.
262    #[must_use]
263    pub fn sample_hdr_video() -> Self {
264        let poster: ImageBuffer = MediaCodecRegistry::synthesize_frame(
265            280,
266            158,
267            Color::hex(0x090D16),
268            Color::hex(0x22D3EE),
269            0,
270        );
271        let mut frames: Vec<MediaFrame> = Vec::with_capacity(12);
272        let palette: [Color; 4] = [
273            Color::hex(0x22D3EE),
274            Color::hex(0x6366F1),
275            Color::hex(0xEC4899),
276            Color::hex(0x10B981),
277        ];
278        for i in 0..12 {
279            frames.push(MediaFrame {
280                image: MediaCodecRegistry::synthesize_frame(
281                    280,
282                    158,
283                    Color::hex(0x090D16),
284                    palette[i % palette.len()],
285                    i + 1,
286                ),
287                delay_ms: 1000,
288                timestamp_secs: i as f32,
289            });
290        }
291        Self {
292            metadata: MediaMetadata {
293                title: "euv Engine HDR Showcase Reel".to_string(),
294                width: 280,
295                height: 158,
296                duration_secs: 12.0,
297                page_count: 1,
298                frame_count: 12,
299                sample_rate_hz: 48_000,
300                channels: 2,
301                format_label: "MP4 · H.264 · 60fps".to_string(),
302            },
303            codec: VideoCodec::H264,
304            poster,
305            frames,
306            state: PlaybackState::Paused,
307            current_time_secs: 0.0,
308            volume: 0.85,
309            muted: false,
310            playback_rate: 1.0,
311            looping: true,
312            captions: vec![
313                "Cross-platform native raster + GPU hybrid pipeline.".to_string(),
314                "Zero JavaScript WebAssembly bundle running at 60Hz.".to_string(),
315                "Real-time BVH ray-traced shadows and reflections.".to_string(),
316                "Immersive iOS, Android, macOS, Windows, and Linux.".to_string(),
317            ],
318        }
319    }
320
321    /// Toggles between `PlaybackState::Playing` and `PlaybackState::Paused`.
322    ///
323    /// # Arguments
324    ///
325    /// - `&Self` - Mutable video track.
326    pub fn toggle_play(&mut self) {
327        if self.get_state() == PlaybackState::Playing {
328            self.set_state(PlaybackState::Paused);
329        } else {
330            if self.get_state() == PlaybackState::Ended {
331                self.set_current_time_secs(0.0);
332            }
333            self.set_state(PlaybackState::Playing);
334        }
335    }
336
337    /// Seeks playback position to `secs`, clamped to `[0.0, duration_secs]`.
338    ///
339    /// # Arguments
340    ///
341    /// - `&Self` - Mutable video track.
342    /// - `f32` - Target timestamp in seconds.
343    pub fn seek(&mut self, secs: f32) {
344        let dur: f32 = self.get_metadata().get_duration_secs().max(0.0);
345        self.set_current_time_secs(secs.clamp(0.0, dur));
346    }
347
348    /// Advances video playback by `dt_secs * playback_rate`.
349    ///
350    /// # Arguments
351    ///
352    /// - `&Self` - Mutable video track.
353    /// - `f32` - Elapsed wall delta time in seconds.
354    pub fn step(&mut self, dt_secs: f32) {
355        if self.get_state() != PlaybackState::Playing {
356            return;
357        }
358        let dur: f32 = self.get_metadata().get_duration_secs().max(0.1);
359        let next: f32 = self.get_current_time_secs() + dt_secs * self.get_playback_rate();
360        if next >= dur {
361            if self.get_looping() {
362                self.set_current_time_secs(next % dur);
363            } else {
364                self.set_current_time_secs(dur);
365                self.set_state(PlaybackState::Ended);
366            }
367        } else {
368            self.set_current_time_secs(next);
369        }
370    }
371
372    /// Decodes a real ISOBMFF MP4 container through `Mp4Demuxer` and `SoftwareVideoDecoder` into a `VideoTrack`.
373    ///
374    /// # Arguments
375    ///
376    /// - `Vec<u8>` - Complete MP4 container bytes.
377    /// - `&str` - Human-readable track title.
378    ///
379    /// # Returns
380    ///
381    /// - `Result<Self, String>` - Decoded `VideoTrack` with PTS-ordered frames or descriptive error.
382    pub fn from_mp4_bytes(bytes: Vec<u8>, title: &str) -> Result<Self, String> {
383        let demuxer: Mp4Demuxer = Mp4Demuxer::parse(bytes)?;
384        let config: VideoDecoderConfig = demuxer.video_decoder_config();
385        let mut decoder: SoftwareVideoDecoder = SoftwareVideoDecoder::default();
386        decoder.configure(&config)?;
387        let pool: VideoFramePool = VideoFramePool::with_capacity(VIDEO_DEFAULT_POOL_CAPACITY);
388        let sample_count: usize = demuxer.video_sample_count();
389        let mut decoded_frames: Vec<DecodedVideoFrame> = Vec::with_capacity(sample_count);
390        for idx in 0..sample_count {
391            if let Some(packet) = demuxer.read_video_packet(idx, 1)
392                && let Some(frame) = decoder.decode_packet(&packet, &pool)?
393            {
394                decoded_frames.push(frame);
395            }
396        }
397        decoded_frames.sort_by_key(|f: &DecodedVideoFrame| f.get_pts_us());
398        let mut frames: Vec<MediaFrame> = Vec::with_capacity(decoded_frames.len());
399        for frame in decoded_frames.into_iter() {
400            let delay_ms: u32 = ((frame.get_duration_us() / 1_000) as u32).max(1);
401            let ts_secs: f32 = (frame.get_pts_us().max(0) as f32) / 1_000_000.0;
402            if let Some(image) = frame.to_image_buffer() {
403                frames.push(MediaFrame {
404                    image,
405                    delay_ms,
406                    timestamp_secs: ts_secs,
407                });
408            }
409            pool.recycle_decoded_frame(frame);
410        }
411        let poster: ImageBuffer = frames
412            .first()
413            .map(|f: &MediaFrame| f.get_image().clone())
414            .unwrap_or_else(|| {
415                ImageBuffer::solid(
416                    config.get_width(),
417                    config.get_height(),
418                    Color::hex(0x090D16),
419                )
420            });
421        let codec_label: &str = match config.get_codec() {
422            VideoCodec::H264 => VIDEO_CODEC_LABEL_H264,
423            VideoCodec::H265 => VIDEO_CODEC_LABEL_H265,
424            VideoCodec::Vp9 => VIDEO_CODEC_LABEL_VP9,
425            VideoCodec::Av1 => VIDEO_CODEC_LABEL_AV1,
426            VideoCodec::RawFrames => VIDEO_CODEC_LABEL_RAW,
427        };
428        let duration_secs: f32 = (demuxer.get_movie_duration_us() as f32) / 1_000_000.0;
429        let audio_info: Option<&Mp4TrackInfo> = demuxer.audio_track();
430        let sample_rate_hz: u32 = audio_info
431            .map(|a: &Mp4TrackInfo| a.get_sample_rate_hz())
432            .unwrap_or(0);
433        let channels: u16 = audio_info
434            .map(|a: &Mp4TrackInfo| a.get_channels())
435            .unwrap_or(0);
436        Ok(Self {
437            metadata: MediaMetadata {
438                title: title.to_string(),
439                width: config.get_width(),
440                height: config.get_height(),
441                duration_secs,
442                page_count: 1,
443                frame_count: frames.len(),
444                sample_rate_hz,
445                channels,
446                format_label: format!("{VIDEO_FORMAT_MP4_PREFIX}{codec_label}"),
447            },
448            codec: config.get_codec(),
449            poster,
450            frames,
451            state: PlaybackState::Paused,
452            current_time_secs: 0.0,
453            volume: 0.85,
454            muted: false,
455            playback_rate: 1.0,
456            looping: true,
457            captions: Vec::new(),
458        })
459    }
460
461    /// Returns a zero-copy borrowed reference to the video `ImageBuffer` corresponding to `current_time_secs`.
462    ///
463    /// # Arguments
464    ///
465    /// - `&Self` - Video track reference.
466    ///
467    /// # Returns
468    ///
469    /// - `&ImageBuffer` - Borrowed active video frame or poster image.
470    #[must_use]
471    pub fn active_frame_ref(&self) -> &ImageBuffer {
472        if self.get_frames().is_empty() {
473            return self.get_poster();
474        }
475        let dur: f32 = self.get_metadata().get_duration_secs().max(0.1);
476        let frac: f32 = (self.get_current_time_secs() / dur).clamp(0.0, 0.9999);
477        let idx: usize =
478            ((frac * (self.get_frames().len() as f32)) as usize).min(self.get_frames().len() - 1);
479        self.get_frames()[idx].get_image()
480    }
481
482    /// Returns the video `ImageBuffer` corresponding to `current_time_secs`.
483    ///
484    /// # Arguments
485    ///
486    /// - `&Self` - Video track reference.
487    ///
488    /// # Returns
489    ///
490    /// - `ImageBuffer` - Active video frame or poster image.
491    #[must_use]
492    pub fn active_frame(&self) -> ImageBuffer {
493        self.active_frame_ref().clone()
494    }
495
496    /// Returns the synchronized closed-caption line for the active playback timestamp.
497    ///
498    /// # Arguments
499    ///
500    /// - `&Self` - Video track reference.
501    ///
502    /// # Returns
503    ///
504    /// - `String` - Active closed-caption string or empty string.
505    #[must_use]
506    pub fn active_caption(&self) -> String {
507        if self.get_captions().is_empty() {
508            return String::new();
509        }
510        let dur: f32 = self.get_metadata().get_duration_secs().max(0.1);
511        let frac: f32 = (self.get_current_time_secs() / dur).clamp(0.0, 0.9999);
512        let idx: usize = ((frac * (self.get_captions().len() as f32)) as usize)
513            .min(self.get_captions().len() - 1);
514        self.get_captions()[idx].clone()
515    }
516}
517
518/// Transport playback, seeking, and procedural WAV synthesis for `AudioTrack`.
519impl AudioTrack {
520    /// Synthesizes a valid RIFF PCM 16-bit mono WAV byte stream and decodes it through `MediaCodecRegistry::decode_wav`.
521    ///
522    /// # Returns
523    ///
524    /// - `Self` - Decoded `AudioTrack` with real PCM samples and 48 waveform peaks.
525    #[must_use]
526    pub fn sample_synth_wav() -> Self {
527        let sample_rate: u32 = 8_000;
528        let duration_secs: usize = 8;
529        let sample_count: usize = (sample_rate as usize) * duration_secs;
530        let data_bytes: u32 = (sample_count * 2) as u32;
531        let mut wav: Vec<u8> = Vec::with_capacity(44 + data_bytes as usize);
532        wav.extend_from_slice(MAGIC_RIFF);
533        wav.extend_from_slice(&(36_u32 + data_bytes).to_le_bytes());
534        wav.extend_from_slice(MAGIC_WAVE);
535        wav.extend_from_slice(MAGIC_WAV_FMT);
536        wav.extend_from_slice(&16_u32.to_le_bytes());
537        wav.extend_from_slice(&1_u16.to_le_bytes());
538        wav.extend_from_slice(&1_u16.to_le_bytes());
539        wav.extend_from_slice(&sample_rate.to_le_bytes());
540        wav.extend_from_slice(&(sample_rate * 2).to_le_bytes());
541        wav.extend_from_slice(&2_u16.to_le_bytes());
542        wav.extend_from_slice(&16_u16.to_le_bytes());
543        wav.extend_from_slice(MAGIC_WAV_DATA);
544        wav.extend_from_slice(&data_bytes.to_le_bytes());
545        for i in 0..sample_count {
546            let t: f32 = (i as f32) / (sample_rate as f32);
547            let env: f32 = 0.35 + 0.65 * (t * 1.4).sin().abs();
548            let sig: f32 = ((t * 440.0 * TAU).sin() * 0.55 + (t * 659.25 * TAU).sin() * 0.35) * env;
549            let s16: i16 = (sig.clamp(-1.0, 1.0) * 28_000.0) as i16;
550            wav.extend_from_slice(&s16.to_le_bytes());
551        }
552        MediaCodecRegistry::decode_wav(&wav, "Cyber Boulevard Synth.wav").unwrap_or_default()
553    }
554
555    /// Toggles audio playback between `Playing` and `Paused`.
556    ///
557    /// # Arguments
558    ///
559    /// - `&Self` - Mutable audio track.
560    pub fn toggle_play(&mut self) {
561        if self.get_state() == PlaybackState::Playing {
562            self.set_state(PlaybackState::Paused);
563        } else {
564            if self.get_state() == PlaybackState::Ended {
565                self.set_current_time_secs(0.0);
566            }
567            self.set_state(PlaybackState::Playing);
568        }
569    }
570
571    /// Seeks the audio playhead to `secs`, clamped to `[0.0, duration_secs]`.
572    ///
573    /// # Arguments
574    ///
575    /// - `&Self` - Mutable audio track.
576    /// - `f32` - Target timestamp in seconds.
577    pub fn seek(&mut self, secs: f32) {
578        let dur: f32 = self.get_metadata().get_duration_secs().max(0.0);
579        self.set_current_time_secs(secs.clamp(0.0, dur));
580    }
581
582    /// Advances audio timeline playback by `dt_secs * playback_rate`.
583    ///
584    /// # Arguments
585    ///
586    /// - `&Self` - Mutable audio track.
587    /// - `f32` - Elapsed delta time in seconds.
588    pub fn step(&mut self, dt_secs: f32) {
589        if self.get_state() != PlaybackState::Playing {
590            return;
591        }
592        let dur: f32 = self.get_metadata().get_duration_secs().max(0.1);
593        let next: f32 = self.get_current_time_secs() + dt_secs * self.get_playback_rate();
594        if next >= dur {
595            if self.get_looping() {
596                self.set_current_time_secs(next % dur);
597            } else {
598                self.set_current_time_secs(dur);
599                self.set_state(PlaybackState::Ended);
600            }
601        } else {
602            self.set_current_time_secs(next);
603        }
604    }
605}
606
607/// Optional preview helper for `PdfPage`.
608impl PdfPage {
609    /// Returns a cloned optional page preview image.
610    ///
611    /// # Arguments
612    ///
613    /// - `&Self` - Page reference.
614    ///
615    /// # Returns
616    ///
617    /// - `Option<ImageBuffer>` - Optional page thumbnail image.
618    #[must_use]
619    pub fn preview_image(&self) -> Option<ImageBuffer> {
620        let Self { preview_image, .. } = self;
621        preview_image.clone()
622    }
623}
624
625/// Page navigation, zoom clamping, and sample PDF generation for `PdfDocument`.
626impl PdfDocument {
627    /// Generates and parses a valid multi-page `%PDF-1.7` document through `MediaCodecRegistry::parse_pdf`.
628    ///
629    /// # Returns
630    ///
631    /// - `Self` - Parsed 3-page `PdfDocument`.
632    #[must_use]
633    pub fn sample_pdf() -> Self {
634        let raw_pdf: &str = "%PDF-1.7\n\
6351 0 obj << /Title (euv Cross-Platform Architecture Spec) /Author (euv Engineering) >> endobj\n\
6362 0 obj << /Type /Pages /Count 3 >> endobj\n\
6373 0 obj << /Type /Page >> stream\n\
638(1. Executive Summary: Zero-JS Cross-Platform Native Engine) Tj\n\
639(euv compiles reactive Rust UI, 2D physics, and 3D BVH ray tracing directly to Web, iOS, Android, macOS, Windows, and Linux.) Tj\n\
640endstream endobj\n\
6414 0 obj << /Type /Page >> stream\n\
642(2. Unified Design System & Full Media Pipeline) Tj\n\
643(Native decoders handle BMP/PNG images, animated GIF89a, LIVE Photos, H.264 video frames, RIFF WAV waveforms, PDF documents, and sanitized HTML5.) Tj\n\
644endstream endobj\n\
6455 0 obj << /Type /Page >> stream\n\
646(3. Production Telemetry & Release Stripping) Tj\n\
647(AI Schema introspection and UI automation hooks compile strictly under debug_assertions for zero Release overhead.) Tj\n\
648endstream endobj\n\
649%%EOF\n";
650        MediaCodecRegistry::parse_pdf(raw_pdf.as_bytes()).unwrap_or_default()
651    }
652
653    /// Advances to the next PDF page if available.
654    ///
655    /// # Arguments
656    ///
657    /// - `&Self` - Mutable PDF document.
658    pub fn next_page(&mut self) {
659        if self.get_current_page() + 1 < self.get_pages().len() {
660            let next: usize = self.get_current_page() + 1;
661            self.set_current_page(next);
662        }
663    }
664
665    /// Navigates to the previous PDF page if available.
666    ///
667    /// # Arguments
668    ///
669    /// - `&Self` - Mutable PDF document.
670    pub fn prev_page(&mut self) {
671        if self.get_current_page() > 0 {
672            let prev: usize = self.get_current_page() - 1;
673            self.set_current_page(prev);
674        }
675    }
676
677    /// Adjusts document zoom level clamped to `[0.75, 2.0]`.
678    ///
679    /// # Arguments
680    ///
681    /// - `&Self` - Mutable PDF document.
682    /// - `f32` - Zoom delta (e.g. `0.25` or `-0.25`).
683    pub fn adjust_zoom(&mut self, delta: f32) {
684        let next: f32 = (self.get_zoom() + delta).clamp(0.75, 2.0);
685        self.set_zoom(next);
686    }
687
688    /// Returns the active `PdfPage` if present.
689    ///
690    /// # Arguments
691    ///
692    /// - `&Self` - PDF document reference.
693    ///
694    /// # Returns
695    ///
696    /// - `Option<&PdfPage>` - Reference to active page.
697    #[must_use]
698    pub fn active_page(&self) -> Option<&PdfPage> {
699        self.get_pages().get(self.get_current_page())
700    }
701}
702
703/// Optional URL accessors for `HtmlBlock`.
704impl HtmlBlock {
705    /// Returns the optional hyperlink URL for `HtmlNodeKind::Link`.
706    ///
707    /// # Arguments
708    ///
709    /// - `&Self` - HTML block reference.
710    ///
711    /// # Returns
712    ///
713    /// - `Option<String>` - Hyperlink target URL if present.
714    #[must_use]
715    pub fn href_url(&self) -> Option<String> {
716        let Self { href, .. } = self;
717        href.clone()
718    }
719
720    /// Returns the optional image source URI for `HtmlNodeKind::Image`.
721    ///
722    /// # Arguments
723    ///
724    /// - `&Self` - HTML block reference.
725    ///
726    /// # Returns
727    ///
728    /// - `Option<String>` - Image URI if present.
729    #[must_use]
730    pub fn image_src(&self) -> Option<String> {
731        let Self { src, .. } = self;
732        src.clone()
733    }
734}
735
736/// Sample rich HTML5 document builder for `HtmlDocument`.
737impl HtmlDocument {
738    /// Builds and parses a rich sanitized HTML5 article demonstrating headings, quotes, code, lists, and links.
739    ///
740    /// # Returns
741    ///
742    /// - `Self` - Parsed `HtmlDocument`.
743    #[must_use]
744    pub fn sample_html() -> Self {
745        let src: &str = "<!DOCTYPE html><html><head><title>Native HTML5 Renderer</title></head><body>\
746<h1>Zero-JS Native HTML5 Document</h1>\
747<p>Rendered directly into euv scene nodes across Web, iOS, Android, and Desktop with zero WebView overhead.</p>\
748<blockquote>Sanitized DOM parsing automatically strips &lt;script&gt; tags while preserving semantic typography &amp; links.</blockquote>\
749<pre>let doc = MediaCodecRegistry::parse_html(markup);</pre>\
750<li>Full support for headings, paragraphs, code blocks, lists, images, and dividers</li>\
751<li>Click links below to dispatch native Rust callbacks without JavaScript</li>\
752<hr/>\
753<a href=\"euv://docs/media-engine\">Open euv Media Engine Spec</a>\
754</body></html>";
755        MediaCodecRegistry::parse_html(src)
756    }
757}
758
759/// Sample SVG vector builder for `SvgDocument`.
760impl SvgDocument {
761    /// Builds and rasterizes a clean multi-primitive geometric SVG icon badge.
762    ///
763    /// # Returns
764    ///
765    /// - `Self` - Rasterized `SvgDocument`.
766    #[must_use]
767    pub fn sample_svg() -> Self {
768        let raw: &str = "<svg viewBox=\"0 0 160 100\">\
769<rect x=\"0\" y=\"0\" width=\"160\" height=\"100\" fill=\"#0F172A\"/>\
770<rect x=\"12\" y=\"12\" width=\"136\" height=\"76\" fill=\"#1E293B\"/>\
771<circle cx=\"52\" cy=\"50\" r=\"24\" fill=\"#38BDF8\"/>\
772<circle cx=\"92\" cy=\"50\" r=\"20\" fill=\"#A855F7\"/>\
773<line x1=\"24\" y1=\"80\" x2=\"136\" y2=\"80\" stroke=\"#34D399\"/>\
774</svg>";
775        MediaCodecRegistry::parse_and_rasterize_svg(raw, 480, 300).unwrap_or_default()
776    }
777}