tplay 0.9.3

A media player that visualizes images and videos as ASCII art directly in the terminal (with sound).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//! The `runner` module contains the Runner struct and related functionality to control and run
//! ASCII animations.
//!
//! The `Runner` struct is responsible for handling the image pipeline, processing frames, managing
//! playback state, and controlling the frame rate. It also handles commands for pausing/continuing,
//! resizing, and changing character maps during playback.
use super::{frames::FrameIterator, image_pipeline::ImagePipeline};
use crate::{
    common::{errors::MyError, sync::PlaybackClock},
    msg::broker::Control as MediaControl,
    pipeline::char_maps::*,
    StringInfo, DEFAULT_TERMINAL_SIZE,
};
use crossbeam_channel::{select, Receiver, Sender};
use crossterm::terminal;
use image::DynamicImage;
use std::{sync::Arc, thread, time::Duration};

/// Represents the playback state of the Runner.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum State {
    /// The Runner is currently reading and processing new  frames.
    Running,
    /// The Runner does not process new frames, but can update the terminal by processing the last
    /// frame again if charset or dimension change.
    Paused,
    /// The Runner was stopped by a command and will cease processing frames, and eventually exit.
    Stopped,
}

/// The `Runner` struct handles the image pipeline, processing frames, managing playback state, and
/// controlling the frame rate. It also handles commands for pausing/continuing, resizing, and
/// changing character maps during playback.
pub struct Runner {
    /// The image pipeline responsible for processing images.
    pipeline: ImagePipeline,
    /// The FrameIterator that handles iterating through frames.
    media: FrameIterator,
    /// The current playback state of the Runner.
    state: State,
    /// A channel for receiving processed frames as strings.
    tx_frames: Sender<Option<StringInfo>>,
    /// A channel for sending control commands to the Runner.
    /// A channel for sending control events to the media processing thread.
    rx_controls: Receiver<Control>,
    /// A collection of character maps available for the image pipeline.
    tx_control: Sender<MediaControl>,
    char_maps: Vec<Vec<char>>,
    /// The last frame that was processed by the Runner.
    last_frame: Option<DynamicImage>,
    /// Runner options
    runner_options: RunnerOptions,
    playback_clock: Option<Arc<PlaybackClock>>,
    last_synced_frame: i64,
    /// Source media dimensions for aspect ratio preservation
    source_dimensions: Option<(u32, u32)>,
    /// Whether the source is a network stream (affects sync behavior)
    is_streaming: bool,
    /// Current terminal dimensions in characters (for padding output)
    terminal_cols: u32,
    terminal_rows: u32,
}

pub struct RunnerOptions {
    /// The target frames per second (frame rate) for the Runner.
    pub fps: f64,
    /// The width modifier (use 2 for emojis).
    pub w_mod: u32,
    /// loop_playback back to the first frame after iterating through frames.
    pub loop_playback: bool,
    /// Exit automatically when the media ends
    pub auto_exit: bool,
    /// Preserve source aspect ratio (accounting for terminal character shape)
    pub preserve_aspect_ratio: bool,
}
/// Enum representing the different control commands that can be sent to the Runner.
#[derive(Debug, PartialEq)]
pub enum Control {
    /// Command to toggle between pause and continue playback.
    PauseContinue,
    /// Replay the image pipeline
    Replay,
    /// Command to stop the playback and exit the Runner.
    Exit,
    /// Command to set the character map used by the image pipeline.
    /// The argument represents the index of the desired character map.
    SetCharMap(u32),
    /// Command to resize the target resolution of the image pipeline.
    /// The arguments represent the new target width and height, respectively.
    Resize(u16, u16),
    /// Command to set grayscale mode. We always extract rgb+grayscale from image, the
    /// terminal is responsible for the correct render mode.
    SetGrayscale(bool),
    /// Command to seek forward or backward by the specified number of seconds.
    /// Positive values seek forward, negative values seek backward.
    Seek(f64),
    /// Command to seek to an absolute position in seconds.
    SeekAbsolute(f64),
    /// Command to seek to a percentage of the total duration (0.0 to 1.0).
    SeekPercent(f64),
}

impl Runner {
    /// Initializes a new Runner instance.
    ///
    /// # Arguments
    ///
    /// * `pipeline` - The image pipeline responsible for processing images.
    /// * `media` - The FrameIterator that handles iterating through frames.
    /// * `fps` - The target frames per second (frame rate) for the Runner.
    /// * `tx_frames` - A channel for receiving processed frames as strings.
    /// * `rx_controls` - A channel for sending control commands to the Runner.
    /// * `tx_controls` - A channel for sending control events to the media processing thread.
    /// * `w_mod` - The width modifier (use 2 for emojis).
    /// * `loop_playback` - Flags whether the runner will loop round after processing all frames.
    pub fn new(
        pipeline: ImagePipeline,
        media: FrameIterator,
        tx_frames: Sender<Option<StringInfo>>,
        rx_controls: Receiver<Control>,
        tx_control: Sender<MediaControl>,
        runner_options: RunnerOptions,
        playback_clock: Option<Arc<PlaybackClock>>,
    ) -> Self {
        let source_dimensions = media.dimensions();
        let is_streaming = media.is_streaming();
        let char_maps: Vec<Vec<char>> = vec![
            pipeline.char_map.clone(),
            CHARS1.to_string().chars().collect(),
            CHARS2.to_string().chars().collect(),
            HALFBLOCK.to_string().chars().collect(), // 3: half-block (2x vertical resolution)
            SOLID.to_string().chars().collect(),
            DOTTED.to_string().chars().collect(),
            GRADIENT.to_string().chars().collect(),
            BLACKWHITE.to_string().chars().collect(),
            BW_DOTTED.to_string().chars().collect(),
            BRAILLE.to_string().chars().collect(),
        ];
        Self {
            pipeline,
            media,
            state: State::Running,
            tx_frames,
            rx_controls,
            tx_control,
            char_maps,
            last_frame: None,
            runner_options,
            playback_clock,
            last_synced_frame: -1,
            source_dimensions,
            is_streaming,
            terminal_cols: DEFAULT_TERMINAL_SIZE.0,
            terminal_rows: DEFAULT_TERMINAL_SIZE.1,
        }
    }

    /// The main function responsible for running the animation.
    ///
    /// It processes control commands, updates the state of the Runner, processes frames, and sends
    /// the resulting ASCII strings to the string buffer.
    ///
    /// # Returns
    ///
    /// An empty Result.
    pub fn run(
        &mut self,
        barrier: std::sync::Arc<std::sync::Barrier>,
        allow_frame_skip: bool,
    ) -> Result<(), MyError> {
        barrier.wait();
        let mut time_count = std::time::Instant::now();
        // make sure the first frame is shown immediately
        time_count -= self.target_frame_duration();
        
        while self.state != State::Stopped {
            let frame_needs_refresh = self.process_control_commands();

            let (should_process_frame, frames_to_skip) = if self.playback_clock.is_some() {
                self.should_process_frame_synced()
            } else {
                self.should_process_frame(&mut time_count)
            };
            
            if should_process_frame {
                if frames_to_skip > 0 && allow_frame_skip {
                    self.media.skip_frames(frames_to_skip);
                }
                let frame = self.get_current_frame();

                if self.runner_options.loop_playback && frame.is_none() {
                    // make sure the first frame on replay is shown immediately
                    time_count -= self.target_frame_duration();
                    // send command to broker to replay
                    self.send_control(MediaControl::Replay)?;
                } else if frame.is_none() && self.runner_options.auto_exit {
                    // end of media: ask broker to exit and stop this runner.
                    let _ = self.send_control(MediaControl::Exit);
                    self.state = State::Stopped;
                    // non inviare altri frame
                    continue;
                }

                // Check if terminal is ready for the next frame
                select! {
                    send(self.tx_frames, None) -> _ => {
                        let string_info = self.process_current_frame(frame.as_ref(), frame_needs_refresh);
                        // Best effort send. If the buffer is full the frame will be dropped
                        let _ = self.tx_frames.try_send(string_info);
                    },
                    default(Duration::from_millis(5)) => {}
                }
            } else {
                thread::yield_now();
            }
        }
        Ok(())
    }

    /// Processes the given frame using the image pipeline and converts the processed image to an
    /// ASCII string representation.
    ///
    /// # Arguments
    ///
    /// * `frame` - A reference to the DynamicImage to be processed.
    ///
    /// # Returns
    ///
    /// A Result containing a tuple of the ASCII string representation of the processed image and
    /// the RGB data of the processed image.
    fn process_frame(&mut self, frame: &DynamicImage) -> Result<StringInfo, MyError> {
        let procimage = self.pipeline.resize(frame)?;
        let rgb_image = procimage.into_rgb8();
        let (width, height) = (rgb_image.width(), rgb_image.height());
        let rgb_info = rgb_image.into_raw();

        if self.pipeline.half_block_mode {
            let (ascii, rgb_data) =
                self.pipeline.to_half_blocks_from_rgb(&rgb_info, width, height);
            let (ascii, rgb_data) = self.pad_to_terminal_halfblock(ascii, rgb_data, width, height / 2);
            return Ok((ascii, rgb_data));
        }

        let ascii = self.pipeline.to_ascii_from_rgb(&rgb_info, width, height);

        // Add newlines to the rgb_info to match the ascii string These are not
        // really needed, but it's important if you want to copy/paste the
        // output and preserve the aspect.
        if self.pipeline.new_lines {
            let mut rgb_info_newline =
                Vec::with_capacity(rgb_info.len() + 6 * self.pipeline.target_resolution.0 as usize);

            for (i, pixel) in rgb_info.chunks(3).enumerate() {
                rgb_info_newline.extend_from_slice(pixel);
                if (i + 1) % self.pipeline.target_resolution.0 as usize == 0 {
                    rgb_info_newline.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
                }
            }
            return Ok((ascii, rgb_info_newline));
        }

        let (ascii, rgb_info) = self.pad_to_terminal(ascii, rgb_info);
        Ok((ascii, rgb_info))
    }

    /// Pads each row of the ASCII output to the terminal width with spaces,
    /// and adds blank rows to fill the terminal height. This is necessary when
    /// preserving aspect ratio produces an image smaller than the terminal,
    /// because the terminal draw relies on line-wrapping at exactly the
    /// terminal width.
    fn pad_to_terminal(&self, ascii: String, rgb: Vec<u8>) -> (String, Vec<u8>) {
        let img_w = self.pipeline.target_resolution.0 as usize;
        let img_h = self.pipeline.target_resolution.1 as usize;
        let term_w = self.terminal_cols as usize;
        let term_h = self.terminal_rows as usize;

        if img_w == term_w && img_h == term_h {
            return (ascii, rgb);
        }

        let x_offset = (term_w.saturating_sub(img_w)) / 2;
        let y_offset = (term_h.saturating_sub(img_h)) / 2;

        let mut padded_ascii = String::with_capacity(term_w * term_h);
        let mut padded_rgb = Vec::with_capacity(term_w * term_h * 3);
        let ascii_chars: Vec<char> = ascii.chars().collect();

        for row in 0..term_h {
            let img_row = row.wrapping_sub(y_offset);
            if row >= y_offset && img_row < img_h {
                let start = img_row * img_w;
                let end = (start + img_w).min(ascii_chars.len());
                let written = end - start;
                // Left padding
                for _ in 0..x_offset {
                    padded_ascii.push(' ');
                    padded_rgb.extend_from_slice(&[0, 0, 0]);
                }
                // Image content
                padded_ascii.extend(&ascii_chars[start..end]);
                padded_rgb.extend_from_slice(&rgb[start * 3..end * 3]);
                // Right padding
                for _ in (x_offset + written)..term_w {
                    padded_ascii.push(' ');
                    padded_rgb.extend_from_slice(&[0, 0, 0]);
                }
            } else {
                // Blank row
                for _ in 0..term_w {
                    padded_ascii.push(' ');
                    padded_rgb.extend_from_slice(&[0, 0, 0]);
                }
            }
        }

        (padded_ascii, padded_rgb)
    }

    /// Pads half-block output to the terminal dimensions.
    /// Half-block RGB data uses 6 bytes per cell (fg_rgb + bg_rgb).
    fn pad_to_terminal_halfblock(
        &self,
        ascii: String,
        rgb: Vec<u8>,
        img_w: u32,
        img_h: u32,
    ) -> (String, Vec<u8>) {
        let img_w = img_w as usize;
        let img_h = img_h as usize;
        let term_w = self.terminal_cols as usize;
        let term_h = self.terminal_rows as usize;

        if img_w == term_w && img_h == term_h {
            return (ascii, rgb);
        }

        let x_offset = (term_w.saturating_sub(img_w)) / 2;
        let y_offset = (term_h.saturating_sub(img_h)) / 2;

        let mut padded_ascii = String::with_capacity(term_w * term_h);
        let mut padded_rgb = Vec::with_capacity(term_w * term_h * 6);
        let ascii_chars: Vec<char> = ascii.chars().collect();

        for row in 0..term_h {
            let img_row = row.wrapping_sub(y_offset);
            if row >= y_offset && img_row < img_h {
                let start = img_row * img_w;
                let end = (start + img_w).min(ascii_chars.len());
                let written = end - start;
                // Left padding
                for _ in 0..x_offset {
                    padded_ascii.push(' ');
                    padded_rgb.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
                }
                // Image content
                padded_ascii.extend(&ascii_chars[start..end]);
                padded_rgb.extend_from_slice(&rgb[start * 6..end * 6]);
                // Right padding
                for _ in (x_offset + written)..term_w {
                    padded_ascii.push(' ');
                    padded_rgb.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
                }
            } else {
                // Blank row
                for _ in 0..term_w {
                    padded_ascii.push(' ');
                    padded_rgb.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
                }
            }
        }

        (padded_ascii, padded_rgb)
    }

    /// Processes control commands from the commands buffer and updates the Runner state and
    /// other properties accordingly.
    ///
    /// # Returns
    ///
    /// A boolean indicating if the frame needs to be refreshed.
    fn process_control_commands(&mut self) -> bool {
        let mut needs_refresh = false;

        // If we have control events, process them
        while let Ok(control) = self.rx_controls.recv_timeout(Duration::from_millis(1)) {
            needs_refresh = true;
            match control {
                Control::PauseContinue => self.toggle_pause(),
                Control::Exit => self.state = State::Stopped,
                Control::Resize(width, height) => {
                    self.resize_pipeline(width, height);
                }
                Control::Replay => {
                    self.replay_pipeline();
                }
                Control::SetCharMap(char_map) => {
                    self.set_char_map(char_map);
                }
                Control::SetGrayscale(_) => { /* ignore */ }
                Control::Seek(seconds) => {
                    self.seek_media(seconds);
                }
                Control::SeekAbsolute(seconds) => {
                    self.seek_media_absolute(seconds);
                }
                Control::SeekPercent(pct) => {
                    if let Some(duration) = self.media.duration_secs() {
                        self.seek_media_absolute(duration * pct);
                    }
                }
            }
        }
        needs_refresh
    }

    /// Toggles the playback state of the Runner between `Running` and `Paused`.
    fn toggle_pause(&mut self) {
        match self.state {
            State::Running => self.state = State::Paused,
            State::Paused => self.state = State::Running,
            _ => {}
        }
    }

    /// Resizes the image pipeline's target resolution based on the provided width and height.
    ///
    /// # Arguments
    ///
    /// * `width` - The new target width.
    /// * `height` - The new target height.
    /// Detect the actual character cell aspect ratio from the terminal's pixel
    /// dimensions. Falls back to 2.0 (a typical monospace default) when pixel
    /// info is unavailable.
    fn char_aspect_ratio() -> f64 {
        if let Ok(ws) = terminal::window_size() {
            if ws.width > 0 && ws.height > 0 && ws.columns > 0 && ws.rows > 0 {
                let cell_w = ws.width as f64 / ws.columns as f64;
                let cell_h = ws.height as f64 / ws.rows as f64;
                if cell_w > 0.0 {
                    return cell_h / cell_w;
                }
            }
        }
        2.0
    }

    fn resize_pipeline(&mut self, width: u16, height: u16) {
        let term_w = (width / self.runner_options.w_mod as u16) as u32;
        let term_h = height as u32;
        self.terminal_cols = term_w;
        self.terminal_rows = term_h;

        let (target_w, target_h) =
            if self.runner_options.preserve_aspect_ratio {
                if let Some((src_w, src_h)) = self.source_dimensions {
                    let char_ar = Self::char_aspect_ratio();
                    let src_w = src_w as f64;
                    let src_h = src_h as f64;
                    let tw = term_w as f64;
                    let th = term_h as f64;

                    let scale_w = tw / src_w;
                    let scale_h = (th * char_ar) / src_h;
                    let scale = scale_w.min(scale_h);

                    let display_w = (src_w * scale).round().max(1.0) as u32;
                    let display_h = (src_h * scale / char_ar)
                        .round()
                        .max(1.0) as u32;

                    (display_w.min(term_w), display_h.min(term_h))
                } else {
                    (term_w, term_h)
                }
            } else {
                (term_w, term_h)
            };

        // In half-block mode, we need 2x the pixel height since each terminal row
        // represents 2 vertical pixels
        let target_h = if self.pipeline.half_block_mode {
            target_h * 2
        } else {
            target_h
        };
        let _ = self.pipeline.set_target_resolution(target_w, target_h);
    }

    /// Sets the character map for the image pipeline based on the provided index.
    ///
    /// # Arguments
    ///
    /// * `char_map` - The index of the character map to use.
    fn set_char_map(&mut self, char_map: u32) {
        let idx = (char_map % self.char_maps.len() as u32) as usize;
        self.pipeline.char_map = self.char_maps[idx].clone();
        self.pipeline.half_block_mode = idx == 3; // index 3 = HALFBLOCK
        self.pipeline.rebuild_lut();

        // Re-trigger resize so half_block_mode's 2x height is applied (or reverted)
        self.resize_pipeline(self.terminal_cols as u16, self.terminal_rows as u16);
    }

    /// Determines if a frame should be processed based on the current time and the Runner's state.
    ///
    /// # Arguments
    ///
    /// * `time_count` - A mutable reference to the time counter used for frame rate control.
    ///
    /// # Returns
    ///
    /// A tuple containing a boolean indicating whether a frame should be processed, and the number
    /// of frames to skip if we are behind schedule.
    fn should_process_frame(&self, time_count: &mut std::time::Instant) -> (bool, usize) {
        let (time_to_send_next_frame, frames_to_skip) = self.time_to_send_next_frame(time_count);

        if time_to_send_next_frame && (self.state == State::Running || self.state == State::Paused)
        {
            (true, frames_to_skip)
        } else {
            (false, 0)
        }
    }

    fn should_process_frame_synced(&mut self) -> (bool, usize) {
        let clock = match &self.playback_clock {
            Some(c) => c,
            None => return (false, 0),
        };

        if clock.is_paused() && self.state == State::Running {
            return (false, 0);
        }

        let audio_pos = clock.get_position();
        let target_frame = (audio_pos.as_secs_f64() * self.runner_options.fps) as i64;

        // Get actual current frame position from the media decoder
        let current_frame = self.media.get_position_frames();

        // Calculate diff: Target - Current
        // If diff > 0: We are BEHIND (Audio is at 100, Video at 90) -> Need to catch up
        // If diff < 0: We are AHEAD (Audio at 90, Video at 100) -> Need to wait
        let frame_diff = target_frame - current_frame;

        // Video is AHEAD of Audio (frame_diff < 0)
        if frame_diff < 0 {
             let max_lead_frames = (2.0 * self.runner_options.fps) as i64;
             if frame_diff < -max_lead_frames {
                  self.media.seek_to_frame(target_frame.max(0) as usize);
                  return (true, 0);
             }
             // Just wait for audio to catch up
             return (false, 0);
        }

        // Video is BEHIND Audio (frame_diff > 0)
        if frame_diff == 0 {
            // Perfect sync, process 1 frame (which advances us to +1)
            return (true, 0);
        }

        // If we are behind...

        // Threshold for using "skip" (grab without decode) vs "seek"
        // skip is fast for small gaps. seek is constant time but imprecise/heavy.
        // For streams, always skip (seeking doesn't work on HLS).
        let skip_limit = if self.is_streaming {
            i64::MAX
        } else {
            (2.0 * self.runner_options.fps) as i64
        };

        if frame_diff > skip_limit {
             // Too far behind, use seek
             self.media.seek_to_frame(target_frame.max(0) as usize);
             return (true, 0);
        }

        if self.is_streaming && frame_diff > 1 {
            // For streams, skip frames directly here (not gated by the
            // allow_frame_skip CLI flag) so we discard them silently
            // instead of playing them in fast-forward. Cap per iteration
            // to avoid blocking too long on network reads.
            let skip = ((frame_diff as usize) - 1)
                .min((self.runner_options.fps as usize).max(1));
            self.media.skip_frames(skip);
            // Tell the run loop NOT to process/display a frame this iteration.
            // We'll keep skipping each iteration until we've caught up, then
            // resume normal display.
            return (false, 0);
        }

        // Small gap: Skip 'frame_diff' frames.
        (true, frame_diff as usize)
    }

    fn target_frame_duration(&self) -> Duration {
        let adjusted_fps = self.runner_options.fps;
        Duration::from_nanos((1_000_000_000_f64 / adjusted_fps) as u64)
    }

    /// Determines if the next frame should be sent based on the current time and the Runner's
    /// frame rate.
    ///
    /// # Arguments
    ///
    /// * `time_count` - A mutable reference to the time counter used for frame rate control.
    ///
    /// # Returns
    ///
    /// A tuple containing a boolean indicating whether the next frame should be sent, and the
    /// number of frames to skip if we are behind schedule.
    fn time_to_send_next_frame(&self, time_count: &mut std::time::Instant) -> (bool, usize) {
        let elapsed_time = time_count.elapsed();
        let target_frame_duration = self.target_frame_duration();

        if elapsed_time >= target_frame_duration {
            let frames_to_skip =
                (elapsed_time.as_nanos() / target_frame_duration.as_nanos()) as usize - 1;
            *time_count += target_frame_duration * (frames_to_skip as u32 + 1);
            (true, frames_to_skip)
        } else {
            (false, 0)
        }
    }

    /// Retrieves the current frame based on the Runner's state.
    ///
    /// # Returns
    ///
    /// An Option containing a DynamicImage if the Runner's state is `Running`, or None otherwise.
    fn get_current_frame(&mut self) -> Option<DynamicImage> {
        match self.state {
            State::Running => self.media.next(),
            State::Paused | State::Stopped => self.last_frame.clone(),
        }
    }

    /// Replays the pipeline
    ///
    /// # Returns
    ///
    fn replay_pipeline(&mut self) {
        self.media.reset();
        self.last_synced_frame = -1;
    }

    /// Seeks the media forward or backward by the specified number of seconds.
    /// If the media has ended (no more frames), seeking backwards will reset the video
    /// to the beginning first, then seek to the appropriate position.
    ///
    /// # Arguments
    ///
    /// * `seconds` - The number of seconds to seek. Positive seeks forward, negative seeks backward.
    /// Seeks the media to an absolute position in seconds.
    fn seek_media_absolute(&mut self, seconds: f64) {
        self.media.seek_to_seconds(seconds, self.runner_options.fps);
        self.last_synced_frame = -1;
        self.last_frame = None;
    }

    fn seek_media(&mut self, seconds: f64) {
        let at_end = self.media.is_at_end();

        if at_end && seconds < 0.0 {
            self.media.reset();
            self.last_synced_frame = -1;
        } else {
            self.media.seek_seconds(seconds, self.runner_options.fps);
            self.last_synced_frame = -1;
        }
        self.last_frame = None;
    }

    /// Sends a control command to the media processing thread.
    ///
    /// # Arguments
    ///
    /// * `control` - The control command to send.
    ///
    /// # Errors
    ///
    /// Returns an error if there is an issue with send.
    fn send_control(&self, control: MediaControl) -> Result<(), MyError> {
        self.tx_control.send(control).map_err(|e| {
            MyError::Audio(format!(
                "{error}: {e:?}",
                error = "audio control feedback",
                e = e
            ))
        })
    }

    /// Processes the current frame, if available, and returns the resulting ASCII string. If the
    /// frame is not available or doesn't need to be processed, it returns None.
    ///
    /// # Arguments
    ///
    /// * `frame` - An Option containing a reference to the current DynamicImage, or None.
    /// * `refresh` - A boolean indicating if the frame needs to be refreshed.
    ///
    /// # Returns
    ///
    /// An Optional StringInfo tuple containing the ASCII representation of the processed frame and
    /// RGB info.
    fn process_current_frame(
        &mut self,
        frame: Option<&DynamicImage>,
        refresh: bool,
    ) -> Option<StringInfo> {
        match frame {
            Some(frame) => {
                self.last_frame = Some(frame.clone());
                if let Ok(string_info) = self.process_frame(frame) {
                    return Some(string_info);
                }
                None
            }
            None => {
                if self.last_frame.is_some() && refresh {
                    if let Ok(string_info) = self.process_frame(
                        &self
                            .last_frame
                            .clone()
                            .expect("Last frame should be available"),
                    ) {
                        return Some(string_info);
                    }
                }
                None
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pipeline::{
        char_maps::CHARS1, frames::open_media, image_pipeline::ImagePipeline,
        runner::Control as PipelineControl,
    };
    use crate::StringInfo;
    use crossbeam_channel::{bounded, unbounded};

    const MEDIA_FILE: &str =
        "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4";

    #[test]
    fn test_time_to_send_next_frame() {
        let fps = 23.976;
        let loop_playback = false;
        let media_data =
            open_media(MEDIA_FILE.to_string(), crate::DEFAULT_BROWSER.to_string()).unwrap();
        let media = media_data.frame_iter;
        let pipeline = ImagePipeline::new((23, 80), CHARS1.chars().collect(), false);

        let (tx_frames, _rx_frames) = bounded::<Option<StringInfo>>(1);
        let (_tx_controls_pipeline, rx_controls_pipeline) = unbounded::<PipelineControl>();
        let (tx_control, _rx_controls_media) = unbounded::<MediaControl>();

        let runner = Runner::new(
            pipeline,
            media,
            tx_frames,
            rx_controls_pipeline,
            tx_control,
            RunnerOptions {
                fps,
                w_mod: 1,
                loop_playback,
                auto_exit: false,
                preserve_aspect_ratio: true,
            },
            None,
        );

        let mut time_count = std::time::Instant::now();

        // Horrible, there should be a better way to ensure that
        // time_count.elapsed() does not rely on real-time
        thread::sleep(Duration::from_nanos((1_000_000_000_f64 / fps) as u64 + 1));

        // Test that we process the first frame
        let (should_process, frames_to_skip) = runner.time_to_send_next_frame(&mut time_count);
        assert_eq!(should_process, true);
        assert_eq!(frames_to_skip, 0);

        // No time change. Test that we don't process the second frame
        let (should_process, frames_to_skip) = runner.time_to_send_next_frame(&mut time_count);
        assert_eq!(should_process, false);
        assert_eq!(frames_to_skip, 0);

        // Horrible, there should be a better way to ensure that
        // time_count.elapsed() does not rely on real-time
        thread::sleep(Duration::from_nanos((1_000_000_000_f64 / fps) as u64 + 1));

        // Test that we process the third frame
        let (should_process, frames_to_skip) = runner.time_to_send_next_frame(&mut time_count);
        assert_eq!(should_process, true);
        assert_eq!(frames_to_skip, 0);

        // Add enough time to process the next frame but skip two
        // Horrible, there should be a better way to ensure that
        // time_count.elapsed() does not rely on real-time
        thread::sleep(Duration::from_nanos((1_000_000_000_f64 / fps) as u64 + 1) * 3);

        // Test that we process the fourth frame
        let (should_process, frames_to_skip) = runner.time_to_send_next_frame(&mut time_count);
        assert_eq!(should_process, true);
        assert_eq!(frames_to_skip, 2);
    }

    #[test]
    fn test_playback_speed_affects_frame_duration() {
        let fps = 30.0;
        let loop_playback = false;
        let media_data =
            open_media(MEDIA_FILE.to_string(), crate::DEFAULT_BROWSER.to_string()).unwrap();
        let media = media_data.frame_iter;
        let pipeline = ImagePipeline::new((23, 80), CHARS1.chars().collect(), false);

        let (tx_frames, _rx_frames) = bounded::<Option<StringInfo>>(1);
        let (_tx_controls_pipeline, rx_controls_pipeline) = unbounded::<PipelineControl>();
        let (tx_control, _rx_controls_media) = unbounded::<MediaControl>();

        let runner = Runner::new(
            pipeline,
            media,
            tx_frames,
            rx_controls_pipeline,
            tx_control,
            RunnerOptions {
                fps,
                w_mod: 1,
                loop_playback,
                auto_exit: false,
                preserve_aspect_ratio: true,
            },
            None,
        );

        // At normal speed (1.0x), frame duration should be ~33.33ms for 30fps
        let normal_duration = runner.target_frame_duration();
        let expected_normal_nanos = (1_000_000_000_f64 / fps) as u64;
        assert_eq!(normal_duration.as_nanos() as u64, expected_normal_nanos);
    }

    #[test]
    fn test_playback_speed_clamping() {
        let fps = 30.0;
        let loop_playback = false;
        let media_data =
            open_media(MEDIA_FILE.to_string(), crate::DEFAULT_BROWSER.to_string()).unwrap();
        let media = media_data.frame_iter;
        let pipeline = ImagePipeline::new((23, 80), CHARS1.chars().collect(), false);

        let (tx_frames, _rx_frames) = bounded::<Option<StringInfo>>(1);
        let (_tx_controls_pipeline, rx_controls_pipeline) = unbounded::<PipelineControl>();
        let (tx_control, _rx_controls_media) = unbounded::<MediaControl>();

        let mut _runner = Runner::new(
            pipeline,
            media,
            tx_frames,
            rx_controls_pipeline,
            tx_control,
            RunnerOptions {
                fps,
                w_mod: 1,
                loop_playback,
                auto_exit: false,
                preserve_aspect_ratio: true,
            },
            None,
        );

        // Speed should be clamped to max 4.0
        // runner.set_playback_speed(10.0);
        // assert_eq!(runner.current_speed, 4.0);
    }
}