forked from ArturKovacs/emulsion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
playback_manager.rs
295 lines (251 loc) · 10.1 KB
/
playback_manager.rs
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
use std::ffi::OsString;
use std::io::Write;
use std::mem;
use std::path::PathBuf;
use std::rc::Rc;
use std::time::Instant;
use rand::{thread_rng, Rng};
use sys_info;
use glium;
use window::Window;
use image_cache;
use image_cache::ImageCache;
#[derive(PartialEq)]
pub enum LoadRequest {
None,
LoadNext,
LoadPrevious,
LoadSpecific(PathBuf),
LoadAtIndex(usize),
Jump(i32),
}
#[derive(PartialEq, Copy, Clone)]
pub enum PlaybackState {
Paused,
Forward,
Present,
RandomPresent,
//Backward,
}
pub struct PlaybackManager {
playback_state: PlaybackState,
image_cache: ImageCache,
present_remaining: Vec<usize>,
playback_start_time: Instant,
frame_count_since_playback_start: u64,
load_request: LoadRequest,
should_sleep: bool,
image_texture: Option<Rc<glium::texture::SrgbTexture2d>>,
}
impl PlaybackManager {
pub fn new() -> Self {
let cache_capaxity = match sys_info::mem_info() {
Ok(value) => {
// value originally reported in KiB
((value.total / 8) * 1024) as isize
}
_ => {
println!("Could not get system memory size, using default value");
// bytes
500_000_000
}
};
let thread_count = match sys_info::cpu_num() {
Ok(value) => value.max(2).min(4),
_ => 4,
};
let resulting_window = PlaybackManager {
playback_state: PlaybackState::Paused,
image_cache: ImageCache::new(cache_capaxity, thread_count),
present_remaining: Vec::new(),
playback_start_time: Instant::now(),
frame_count_since_playback_start: 0,
load_request: LoadRequest::None,
should_sleep: true,
image_texture: None,
};
resulting_window
}
pub fn playback_state(&self) -> PlaybackState {
self.playback_state
}
pub fn start_playback_forward(&mut self) {
self.playback_start_time = Instant::now();
self.frame_count_since_playback_start = 0;
self.playback_state = PlaybackState::Forward;
}
pub fn pause_playback(&mut self) {
self.playback_state = PlaybackState::Paused;
}
pub fn start_random_presentation(&mut self) {
self.playback_start_time = Instant::now();
self.frame_count_since_playback_start = 0;
self.playback_state = PlaybackState::RandomPresent;
self.fill_present_remainig_with_random();
}
pub fn start_presentation(&mut self) {
self.playback_start_time = Instant::now();
self.frame_count_since_playback_start = 0;
self.playback_state = PlaybackState::Present;
}
pub fn current_filename(&self) -> OsString {
self.image_cache.current_filename()
}
pub fn current_file_path(&self) -> PathBuf {
self.image_cache.current_file_path()
}
pub fn current_file_index(&self) -> usize {
self.image_cache.current_file_index()
}
pub fn current_dir_len(&self) -> usize {
self.image_cache.current_dir_len()
}
pub fn update_directory(&mut self) -> image_cache::Result<()> {
self.image_cache.update_directory()
}
pub fn cached_from_dir(&self) -> Vec<bool> {
self.image_cache.cached_from_dir()
}
pub fn should_sleep(&self) -> bool {
self.should_sleep
}
pub fn request_load(&mut self, request: LoadRequest) {
self.load_request = request;
}
pub fn load_request<'a>(&'a self) -> &'a LoadRequest {
&self.load_request
}
pub fn image_texture<'a>(&'a self) -> &'a Option<Rc<glium::texture::SrgbTexture2d>> {
&self.image_texture
}
pub fn update_image(&mut self, window: &mut Window) {
self.should_sleep = true;
// The reason why I reset the load request in such a convoluted way is that
// it has to guaranteprefetch_neighborsequest will be reset even if I return from this
// function early
let mut load_request = LoadRequest::None;
mem::swap(&mut self.load_request, &mut load_request);
let framerate = match self.playback_state {
PlaybackState::Present | PlaybackState::RandomPresent => 0.1667, // six seconds per img
_ => 25.0,
};
const NANOS_PER_SEC: u64 = 1000_000_000;
let frame_delta_time_nanos = (NANOS_PER_SEC as f64 / framerate) as u64;
if self.playback_state == PlaybackState::Paused {
self.image_cache
.process_prefetched(window.display())
.unwrap();
self.image_cache.prefetch_neighbors();
} else if load_request == LoadRequest::None {
let elapsed = self.playback_start_time.elapsed();
let elapsed_nanos = elapsed.as_secs() * NANOS_PER_SEC + elapsed.subsec_nanos() as u64;
let frame_step =
(elapsed_nanos / frame_delta_time_nanos) - self.frame_count_since_playback_start;
if frame_step > 0 {
load_request = match self.playback_state {
PlaybackState::Forward | PlaybackState::Present => {
LoadRequest::Jump(frame_step as i32)
}
//PlaybackState::Backward => LoadRequest::Jump(-(frame_step as i32)),
PlaybackState::RandomPresent => {
let mut target = None;
for _ in 0..frame_step {
target = self.present_remaining.pop();
if target == None {
// Restart
self.fill_present_remainig_with_random();
target = self.present_remaining.pop();
}
}
match target {
Some(index) => LoadRequest::LoadAtIndex(index),
None => LoadRequest::None,
}
}
PlaybackState::Paused => unreachable!(),
};
self.frame_count_since_playback_start += frame_step;
} else {
self.image_cache
.process_prefetched(window.display())
.unwrap();
let nanos_since_last = elapsed_nanos % frame_delta_time_nanos;
const BUISY_WAIT_TRESHOLD: f32 = 0.8;
if nanos_since_last > (frame_delta_time_nanos as f32 * BUISY_WAIT_TRESHOLD) as u64 {
// Just buisy wait if we are getting very close to the next frame swap
self.should_sleep = false;
} else {
match self.playback_state {
PlaybackState::RandomPresent => {
if let Some(&last) = self.present_remaining.iter().last() {
self.image_cache.prefetch_at_index(last);
}
}
_ => self.image_cache.prefetch_neighbors(),
}
}
}
}
//let should_sleep = load_request == LoadRequest::None && running && !update_screen;
// Process long operations here
let load_result = match load_request {
LoadRequest::LoadNext => Some(self.image_cache.load_next(window.display())),
LoadRequest::LoadPrevious => Some(self.image_cache.load_prev(window.display())),
LoadRequest::LoadSpecific(ref file_path) => {
Some(if let Some(file_name) = file_path.file_name() {
self.image_cache
.load_specific(window.display(), file_path.as_ref())
.map(|x| (x, OsString::from(file_name)))
} else {
Err(String::from("Could not extract filename").into())
})
}
LoadRequest::LoadAtIndex(index) => {
Some(self.image_cache.load_at_index(window.display(), index))
}
LoadRequest::Jump(jump_count) => {
Some(self.image_cache.load_jump(window.display(), jump_count))
}
LoadRequest::None => None,
};
if let Some(result) = load_result {
match result {
Ok((texture, filename)) => {
self.image_texture = Some(texture);
// FIXME the program hangs when the title is set during a resize
// this is due to the way glutin/winit is architected.
// An issu already exists in winit proposing to redesign
// the even loop.
// Until that is implemented the title is simply not updated during
// playback.
if self.playback_state == PlaybackState::Paused {
window.set_title_filename(filename.to_str().unwrap());
}
}
Err(err) => {
self.image_texture = None;
window.set_title_filename("[none]");
let stderr = &mut ::std::io::stderr();
let stderr_errmsg = "Error writing to stderr";
writeln!(stderr, "Error occured while loading image: {}", err)
.expect(stderr_errmsg);
for e in err.iter().skip(1) {
writeln!(stderr, "... caused by: {}", e).expect(stderr_errmsg);
}
if let Some(backtrace) = err.backtrace() {
writeln!(stderr, "backtrace: {:?}", backtrace).expect(stderr_errmsg);
}
writeln!(stderr).expect(stderr_errmsg);
}
}
self.should_sleep = false;
}
}
fn fill_present_remainig_with_random(&mut self) {
self.present_remaining.clear();
for i in 0..self.image_cache.current_dir_len() {
self.present_remaining.push(i);
}
thread_rng().shuffle(self.present_remaining.as_mut_slice());
}
}