playa 0.1.133

Image sequence player (EXR, PNG, JPEG, TIFF, .MP4). Pure Rust with optional OpenEXR/FFmpeg support.
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
//! Playback engine with frame-accurate timing and JKL controls
//!
//! **Why**: Professional playback requires:
//! - Frame-accurate timing (not wall-clock)
//! - JKL shuttle controls (J=reverse, K=pause, L=forward)
//! - Dropped frame handling for heavy sequences
//!
//! **Used by**: Keyboard handler (JKL/Space), UI (timeline position)
//!
//! # Timing Model
//!
//! FPS-based: Each frame has fixed duration (1/fps seconds).
//! No dropped frames from timer - we advance by frame count.
//! If frame not loaded: display last good frame (no black flash).
//!
//! # JKL Controls
//!
//! - **J**: Reverse at 1x, 2x, 4x (tap to increase speed)
//! - **K**: Pause (hold K+L/J for slow motion)
//! - **L**: Forward at 1x, 2x, 4x (tap to increase speed)
//! - **Space**: Play/Pause toggle
//!
//! # Playback Loop
//!
//! `update()` called at 60Hz, advances frame index based on FPS.
//! Handles sequence boundaries (loop or stop at end).

use log::{debug, info};
use std::sync::mpsc;
use std::time::Instant;

use crate::cache::{Cache, CacheMessage};
use crate::frame::Frame;

/// FPS presets for jog/shuttle control
const FPS_PRESETS: &[f32] = &[1.0, 2.0, 4.0, 8.0, 12.0, 24.0, 30.0, 60.0, 120.0, 240.0];

/// Frame step size for Shift+Arrow and Shift+PageUp/PageDown
pub const FRAME_JUMP_STEP: i32 = 25;

/// Playback state manager with new architecture
pub struct Player {
    pub cache: Cache,
    pub is_playing: bool,
    pub fps_base: f32,       // Base FPS (persistent setting)
    pub fps_play: f32,       // Current playback FPS (temporary, resets on stop)
    pub loop_enabled: bool,
    pub play_direction: f32, // 1.0 forward, -1.0 backward
    last_frame_time: Option<Instant>,
    pub selected_seq_idx: Option<usize>, // Currently selected sequence in playlist
}

impl Player {
    /// Create new player with empty cache and defaults
    /// Returns (Player, UI message receiver)
    pub fn new() -> (Self, mpsc::Receiver<CacheMessage>) {
        Self::new_with_config(0.75, None)
    }

    /// Create new player with configurable memory budget and worker count
    pub fn new_with_config(
        max_mem_fraction: f64,
        workers: Option<usize>,
    ) -> (Self, mpsc::Receiver<CacheMessage>) {
        info!("Player initialized with new architecture");

        let (cache, ui_rx) = Cache::new(max_mem_fraction, workers); // configurable memory/workers

        let player = Self {
            cache,
            is_playing: false,
            fps_base: 24.0,
            fps_play: 24.0,
            loop_enabled: true,
            play_direction: 1.0,
            last_frame_time: None,
            selected_seq_idx: None,
        };

        (player, ui_rx)
    }

    /// Get current frame from cache
    pub fn get_current_frame(&mut self) -> Option<&Frame> {
        let frame_idx = self.cache.frame();
        self.cache.get_frame(frame_idx)
    }

    /// Update playback state
    pub fn update(&mut self) {
        if !self.is_playing || self.cache.total_frames() == 0 {
            return;
        }

        // Ensure play_fps is not lower than base_fps
        // base_fps acts as a "floor" that pushes play_fps from below
        if self.fps_play < self.fps_base {
            self.fps_play = self.fps_base;
        }

        let now = Instant::now();

        if let Some(last_time) = self.last_frame_time {
            let elapsed = now.duration_since(last_time).as_secs_f32();
            let frame_duration = 1.0 / self.fps_play;

            if elapsed >= frame_duration {
                self.advance_frame();
                self.last_frame_time = Some(now);
            }
        } else {
            self.last_frame_time = Some(now);
        }
    }

    /// Advance to next frame
    fn advance_frame(&mut self) {
        let total_frames = self.cache.total_frames();
        if total_frames == 0 {
            return;
        }

        let current = self.cache.frame();
        let (play_start, play_end) = self.cache.get_play_range();

        if self.play_direction > 0.0 {
            // Forward
            let next = current + 1;
            if next > play_end {
                if self.loop_enabled {
                    debug!("Frame loop: {} -> {}", current, play_start);
                    self.cache.set_frame(play_start);
                } else {
                    debug!("Reached play range end, stopping");
                    self.cache.set_frame(play_end);
                    self.is_playing = false;
                }
            } else {
                self.cache.set_frame(next);
            }
        } else {
            // Backward
            if current <= play_start {
                if self.loop_enabled {
                    debug!("Frame loop: {} -> {}", current, play_end);
                    self.cache.set_frame(play_end);
                } else {
                    debug!("Reached play range start, stopping");
                    self.is_playing = false;
                }
            } else {
                self.cache.set_frame(current - 1);
            }
        }
    }

    /// Toggle play/pause (Space, K, ArrowUp)
    pub fn toggle_play_pause(&mut self) {
        self.is_playing = !self.is_playing;
        if self.is_playing {
            debug!("Playback started at frame {}", self.cache.frame());
            self.last_frame_time = Some(Instant::now());
            // Start preloading when playback begins
            self.cache.signal_preload();
        } else {
            debug!("Playback paused at frame {}", self.cache.frame());
            self.last_frame_time = None;
            // Reset fps_play to fps_base on stop
            self.fps_play = self.fps_base;
        }
    }

    /// Stop playback (always stops, doesn't toggle)
    pub fn stop(&mut self) {
        if self.is_playing {
            self.is_playing = false;
            debug!("Playback stopped at frame {}", self.cache.frame());
            self.last_frame_time = None;
            // Reset fps_play to fps_base on stop
            self.fps_play = self.fps_base;
        }
    }

    /// Rewind to start
    pub fn to_start(&mut self) {
        debug!("Rewinding to frame 0");
        self.cache.set_frame(0);
        self.last_frame_time = None;
        self.cache.signal_preload();
    }

    /// Skip to end
    pub fn to_end(&mut self) {
        let (_, global_end) = self.cache.range();
        debug!("Skipping to end: frame {}", global_end);
        self.cache.set_frame(global_end);
        self.last_frame_time = None;
        self.cache.signal_preload();
    }

    /// Set current frame
    pub fn set_frame(&mut self, frame: usize) {
        let (_, global_end) = self.cache.range();
        let clamped = frame.min(global_end);
        self.cache.set_frame(clamped);
        self.last_frame_time = None;

        // Start preloading from new position
        self.cache.signal_preload();
    }

    /// Step by N frames (positive = forward, negative = backward)
    /// Respects play range and loop_enabled setting
    pub fn step(&mut self, count: i32) {
        if count == 0 {
            return;
        }

        let current = self.cache.frame();
        let (play_start, play_end) = self.cache.get_play_range();

        // Calculate target frame with saturating arithmetic
        let target = if count > 0 {
            current.saturating_add(count as usize)
        } else {
            current.saturating_sub(count.unsigned_abs() as usize)
        };

        // Apply loop/clamp logic based on loop_enabled
        let final_frame = if target > play_end {
            if self.loop_enabled {
                // Loop: wrap around to play_start
                let overflow = target - play_end;
                let range_size = play_end - play_start + 1;
                play_start + ((overflow - 1) % range_size)
            } else {
                // Clamp to play_end
                play_end
            }
        } else if target < play_start {
            if self.loop_enabled {
                // Loop: wrap around to play_end
                let underflow = play_start - target;
                let range_size = play_end - play_start + 1;
                play_end - ((underflow - 1) % range_size)
            } else {
                // Clamp to play_start
                play_start
            }
        } else {
            target
        };

        self.cache.set_frame(final_frame);
        self.cache.signal_preload();
    }

    /// Get current frame index
    #[inline]
    pub fn current_frame(&self) -> usize {
        self.cache.frame()
    }

    /// Get total frames
    pub fn total_frames(&self) -> usize {
        self.cache.total_frames()
    }

    /// Internal helper to start jogging in the specified direction
    fn start_jog(&mut self, direction: f32) {
        if !self.is_playing {
            // Start playing in specified direction
            self.play_direction = direction;
            self.is_playing = true;
            self.fps_play = self.fps_base; // Start with base FPS
            self.last_frame_time = Some(Instant::now());
        } else if self.play_direction.signum() != direction.signum() {
            // Change direction
            self.play_direction = direction;
            self.fps_play = self.fps_base; // Reset on direction change
        } else {
            // Already playing in same direction, increase speed
            self.increase_fps_play();
        }
    }

    /// Jog forward (L, >, ArrowRight)
    pub fn jog_forward(&mut self) {
        self.start_jog(1.0);
    }

    /// Jog backward (J, <, ArrowLeft)
    pub fn jog_backward(&mut self) {
        self.start_jog(-1.0);
    }

    /// Increase base FPS to next preset (-/+ keys, Keypad)
    pub fn increase_fps_base(&mut self) {
        // Find first preset strictly greater than current FPS
        if let Some(idx) = FPS_PRESETS.iter().position(|&f| f > self.fps_base) {
            self.fps_base = FPS_PRESETS[idx];
            // If not playing, update fps_play too
            if !self.is_playing {
                self.fps_play = self.fps_base;
            }
            debug!("Base FPS increased to {}", self.fps_base);
        }
    }

    /// Decrease base FPS to previous preset (-/+ keys, Keypad)
    pub fn decrease_fps_base(&mut self) {
        // Find last preset strictly less than current FPS
        if let Some(idx) = FPS_PRESETS.iter().rposition(|&f| f < self.fps_base) {
            self.fps_base = FPS_PRESETS[idx];
            // If not playing, update fps_play too
            if !self.is_playing {
                self.fps_play = self.fps_base;
            }
            debug!("Base FPS decreased to {}", self.fps_base);
        }
    }

    /// Increase play FPS to next preset (J/L when playing)
    fn increase_fps_play(&mut self) {
        if let Some(idx) = FPS_PRESETS.iter().position(|&f| f >= self.fps_play)
            && idx + 1 < FPS_PRESETS.len() {
                self.fps_play = FPS_PRESETS[idx + 1];
                debug!("Play FPS increased to {}", self.fps_play);
            }
    }

    /// Jump to next sequence start (] key)
    /// If within sequence -> jump to next sequence start
    /// If on last sequence -> jump to end of range
    /// If at end and loop enabled -> jump to first sequence start
    pub fn jump_next_sequence(&mut self) {
        let sequences = self.cache.sequences();
        if sequences.is_empty() {
            return;
        }

        let (global_start, global_end) = self.cache.range();
        let current_frame = self.cache.frame();

        // Check if we're already at the end
        if current_frame >= global_end {
            if self.loop_enabled {
                // Loop to first sequence start
                self.cache.set_frame(global_start);
                debug!("Looped from end to start: frame {}", global_start);
            }
            // If loop disabled, stay at end
        } else if let Some((seq_idx, _local_frame)) = self.cache.current_sequence() {
            // We're inside a sequence
            if seq_idx + 1 < sequences.len() {
                // Jump to start of next sequence
                if let Some(next_start) = self.cache.local_to_global(seq_idx + 1, 0) {
                    self.cache.set_frame(next_start);
                    debug!("Jumped to next sequence start: frame {}", next_start);
                }
            } else {
                // We're on last sequence, jump to end
                self.cache.set_frame(global_end);
                debug!("Jumped to end: frame {}", global_end);
            }
        }

        self.last_frame_time = None;
        self.cache.signal_preload();
    }

    /// Jump to previous sequence start ([ key)
    /// If within sequence -> jump to current sequence start
    /// If already at current sequence start -> jump to previous sequence start
    /// If on first sequence start and loop enabled -> jump to end
    pub fn jump_prev_sequence(&mut self) {
        let sequences = self.cache.sequences();
        if sequences.is_empty() {
            return;
        }

        let (_, global_end) = self.cache.range();
        let current_frame = self.cache.frame();

        if let Some((seq_idx, local_frame)) = self.cache.current_sequence() {
            // We're inside a sequence
            if local_frame == 0 {
                // Already at sequence start, jump to previous sequence
                if seq_idx > 0 {
                    if let Some(prev_start) = self.cache.local_to_global(seq_idx - 1, 0) {
                        self.cache.set_frame(prev_start);
                        debug!("Jumped to previous sequence start: frame {}", prev_start);
                    }
                } else if self.loop_enabled {
                    // We're at first sequence start, loop to end
                    self.cache.set_frame(global_end);
                    debug!("Looped to end: frame {}", global_end);
                }
            } else {
                // Not at sequence start, jump to current sequence start
                if let Some(cur_start) = self.cache.local_to_global(seq_idx, 0) {
                    self.cache.set_frame(cur_start);
                    debug!("Jumped to current sequence start: frame {}", cur_start);
                }
            }
        } else if current_frame >= global_end && self.loop_enabled {
            // We're at the end, position at end
            self.cache.set_frame(global_end);
            debug!("At end, positioned at frame {}", global_end);
        }

        self.last_frame_time = None;
        self.cache.signal_preload();
    }

    /// Reset settings
    pub fn reset_settings(&mut self) {
        self.fps_base = 24.0;
        self.fps_play = 24.0;
        self.loop_enabled = true;
        info!("Player settings reset");
    }
}

impl Default for Player {
    fn default() -> Self {
        let (player, _rx) = Self::new();
        player
    }
}