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
#![warn(clippy::all, clippy::pedantic, clippy::nursery)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::missing_panics_doc)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::must_use_candidate)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::cast_possible_wrap)]
#![allow(clippy::if_not_else)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::items_after_statements)]
#[macro_use]
extern crate log;
use crate::{
encoder::Encoder,
progress_bar::{finish_multi_progress_bar, finish_progress_bar},
target_quality::TargetQuality,
};
use chunk::Chunk;
use dashmap::DashMap;
use once_cell::sync::OnceCell;
use serde::{Deserialize, Serialize};
use std::{
collections::hash_map::DefaultHasher,
fs,
fs::File,
hash::{Hash, Hasher},
io::Write,
path::{Path, PathBuf},
string::ToString,
sync::atomic::{AtomicBool, AtomicUsize},
time::Instant,
};
use sysinfo::SystemExt;
pub mod broker;
pub mod chunk;
pub mod concat;
pub mod encoder;
pub mod ffmpeg;
pub mod progress_bar;
pub mod scene_detect;
pub mod settings;
pub mod split;
pub mod target_quality;
pub mod util;
pub mod vapoursynth;
pub mod vmaf;
#[derive(Debug)]
pub enum Input {
VapourSynth(PathBuf),
Video(PathBuf),
}
impl Input {
pub fn as_video_path(&self) -> &Path {
match &self {
Input::Video(path) => path.as_ref(),
Input::VapourSynth(_) => {
panic!("called `Input::as_video_path()` on an `Input::VapourSynth` variant")
}
}
}
pub fn as_vapoursynth_path(&self) -> &Path {
match &self {
Input::VapourSynth(path) => path.as_ref(),
Input::Video(_) => {
panic!("called `Input::as_vapoursynth_path()` on an `Input::Video` variant")
}
}
}
pub fn as_path(&self) -> &Path {
match &self {
Input::Video(path) | Input::VapourSynth(path) => path.as_ref(),
}
}
pub const fn is_video(&self) -> bool {
matches!(&self, Input::Video(_))
}
pub const fn is_vapoursynth(&self) -> bool {
matches!(&self, Input::VapourSynth(_))
}
pub fn frames(&self) -> usize {
match &self {
Input::Video(path) => ffmpeg::num_frames(path.as_path()).unwrap(),
Input::VapourSynth(path) => vapoursynth::num_frames(path.as_path()).unwrap(),
}
}
}
impl<P: AsRef<Path> + Into<PathBuf>> From<P> for Input {
#[allow(clippy::option_if_let_else)]
fn from(path: P) -> Self {
if let Some(ext) = path.as_ref().extension() {
if ext == "py" || ext == "vpy" {
Self::VapourSynth(path.into())
} else {
Self::Video(path.into())
}
} else {
Self::Video(path.into())
}
}
}
#[derive(Debug, Deserialize, Serialize)]
struct DoneJson {
frames: AtomicUsize,
done: DashMap<String, usize>,
audio_done: AtomicBool,
}
static DONE_JSON: OnceCell<DoneJson> = OnceCell::new();
fn get_done() -> &'static DoneJson {
DONE_JSON.get().unwrap()
}
fn init_done(done: DoneJson) -> &'static DoneJson {
DONE_JSON.get_or_init(|| done)
}
pub fn list_index(params: &[impl AsRef<str>], is_match: fn(&str) -> bool) -> Option<usize> {
assert!(!params.is_empty(), "received empty list of parameters");
params.iter().enumerate().find_map(|(idx, s)| {
if is_match(s.as_ref()) {
Some(idx)
} else {
None
}
})
}
#[derive(Serialize, Deserialize, Debug, strum::EnumString, strum::IntoStaticStr)]
pub enum SplitMethod {
#[strum(serialize = "av-scenechange")]
AvScenechange,
#[strum(serialize = "none")]
None,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, strum::EnumString, strum::IntoStaticStr)]
pub enum ScenecutMethod {
#[strum(serialize = "fast")]
Fast,
#[strum(serialize = "standard")]
Standard,
}
#[derive(
PartialEq, Eq, Copy, Clone, Serialize, Deserialize, Debug, strum::EnumString, strum::IntoStaticStr,
)]
pub enum ChunkMethod {
#[strum(serialize = "select")]
Select,
#[strum(serialize = "hybrid")]
Hybrid,
#[strum(serialize = "segment")]
Segment,
#[strum(serialize = "ffms2")]
FFMS2,
#[strum(serialize = "lsmash")]
LSMASH,
}
#[must_use]
pub fn determine_workers(encoder: Encoder) -> u64 {
let mut system = sysinfo::System::new();
system.refresh_memory();
let cpu = num_cpus::get() as u64;
let ram_gb = system.available_memory() / 10_u64.pow(6);
std::cmp::max(
match encoder {
Encoder::aom | Encoder::rav1e | Encoder::vpx => std::cmp::min(
(cpu as f64 / 3.0).round() as u64,
(ram_gb as f64 / 1.5).round() as u64,
),
Encoder::svt_av1 | Encoder::x264 | Encoder::x265 => std::cmp::min(cpu, ram_gb) / 8,
},
1,
)
}
pub fn hash_path(path: &Path) -> String {
let mut s = DefaultHasher::new();
path.hash(&mut s);
format!("{:x}", s.finish())[..7].to_string()
}
pub async fn process_pipe(pipe: tokio::process::Child, chunk_index: usize) -> Result<(), String> {
let status = pipe.wait_with_output().await.unwrap();
if !status.status.success() {
return Err(format!(
"Encoder encountered an error on chunk {}: {:?}",
chunk_index, status
));
}
Ok(())
}
fn save_chunk_queue(temp: &str, chunk_queue: &[Chunk]) {
let mut file = File::create(Path::new(temp).join("chunks.json")).unwrap();
file
.write_all(serde_json::to_string(&chunk_queue).unwrap().as_bytes())
.unwrap();
}
#[derive(Clone, Copy, PartialEq)]
pub enum Verbosity {
Verbose,
Normal,
Quiet,
}
fn read_chunk_queue(temp: &Path) -> Vec<Chunk> {
let contents = fs::read_to_string(Path::new(temp).join("chunks.json")).unwrap();
serde_json::from_str(&contents).unwrap()
}