av1converter 3.0.0

Batch convert video files to AV1 with FFmpeg, from a terminal UI or a daemon with a web UI
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
use serde::{Deserialize, Serialize};

/// Overall quality preset that drives the per-tier encoding settings.
///
/// `Low`, `Medium` and `High` apply a fixed set of per-resolution values,
/// while `Custom` leaves the user's hand-tuned values untouched and editable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum QualityPreset {
    #[serde(rename = "low")]
    Low,
    #[default]
    #[serde(rename = "medium")]
    Medium,
    #[serde(rename = "high")]
    High,
    #[serde(rename = "custom")]
    Custom,
}

impl QualityPreset {
    /// All presets, in display/cycle order.
    pub const ALL: [QualityPreset; 4] = [
        QualityPreset::Low,
        QualityPreset::Medium,
        QualityPreset::High,
        QualityPreset::Custom,
    ];

    /// The next preset in [`QualityPreset::ALL`], wrapping around.
    pub fn next(self) -> Self {
        let i = Self::ALL.iter().position(|&p| p == self).unwrap_or(0);
        Self::ALL[(i + 1) % Self::ALL.len()]
    }

    /// The previous preset in [`QualityPreset::ALL`], wrapping around.
    pub fn prev(self) -> Self {
        let i = Self::ALL.iter().position(|&p| p == self).unwrap_or(0);
        Self::ALL[(i + Self::ALL.len() - 1) % Self::ALL.len()]
    }

    /// The per-tier encoding presets for this quality level, or `None` for
    /// [`QualityPreset::Custom`] (which keeps the user's own values).
    pub fn presets(self) -> Option<EncodingPresetsConfig> {
        match self {
            QualityPreset::Low => Some(EncodingPresetsConfig::low()),
            QualityPreset::Medium => Some(EncodingPresetsConfig::medium()),
            QualityPreset::High => Some(EncodingPresetsConfig::high()),
            QualityPreset::Custom => None,
        }
    }
}

/// Quality configuration
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct QualityConfig {
    /// VMAF quality threshold (0-100)
    pub vmaf_threshold: f64,
    /// Whether to run VMAF after encoding
    pub vmaf_enabled: bool,
    /// Delete source file after encoding when VMAF score meets threshold
    #[serde(default)]
    pub delete_source_on_success: bool,
}

impl Default for QualityConfig {
    fn default() -> Self {
        Self {
            vmaf_threshold: 90.0,
            vmaf_enabled: true,
            delete_source_on_success: false,
        }
    }
}

/// Performance configuration
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PerformanceConfig {
    /// SVT-AV1 preset (0-13, lower = slower/better)
    pub svt_preset: u8,
    /// NVENC preset name
    pub nvenc_preset: String,
}

impl PerformanceConfig {
    pub const NVENC_PRESETS: [&'static str; 7] = ["p1", "p2", "p3", "p4", "p5", "p6", "p7"];

    pub fn valid_nvenc_preset(value: &str) -> bool {
        Self::NVENC_PRESETS.contains(&value)
    }
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self {
            svt_preset: 4,
            nvenc_preset: "p4".to_string(),
        }
    }
}

/// Encoding preset for a specific resolution tier
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EncodingPreset {
    /// CRF value for software encoding
    pub crf: u8,
    /// Film grain synthesis level (0-50)
    pub film_grain: u8,
    /// CQ value for NVENC
    pub nvenc_cq: u8,
    /// Quality value for QSV
    pub qsv_quality: u8,
    /// Quality value for AMF
    pub amf_quality: u8,
}

impl EncodingPreset {
    /// Shift every quality value by `delta` (a higher value means lower quality
    /// and smaller files). Film grain synthesis is left untouched.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    fn shifted(&self, delta: i16) -> EncodingPreset {
        // Clamped to 0..=63 before the cast to u8.
        let adj = |v: u8| -> u8 { (i16::from(v) + delta).clamp(0, 63) as u8 };
        EncodingPreset {
            crf: adj(self.crf),
            film_grain: self.film_grain,
            nvenc_cq: adj(self.nvenc_cq),
            qsv_quality: adj(self.qsv_quality),
            amf_quality: adj(self.amf_quality),
        }
    }
}

/// Encoding presets per resolution tier. A missing tier or value takes the
/// tier's default.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(from = "PartialPresets")]
pub struct EncodingPresetsConfig {
    pub sd: EncodingPreset,
    pub hd: EncodingPreset,
    pub full_hd: EncodingPreset,
    pub full_hd_hdr: EncodingPreset,
    pub full_hd_dv: EncodingPreset,
    pub uhd: EncodingPreset,
    pub uhd_hdr: EncodingPreset,
    pub uhd_dv: EncodingPreset,
}

/// One `[presets.<tier>]` table as written, with any value left out.
#[derive(Deserialize, Default)]
#[serde(default)]
struct PartialPreset {
    crf: Option<u8>,
    film_grain: Option<u8>,
    nvenc_cq: Option<u8>,
    qsv_quality: Option<u8>,
    amf_quality: Option<u8>,
}

impl PartialPreset {
    /// The written values, with `base` filling the rest.
    fn over(self, base: &EncodingPreset) -> EncodingPreset {
        EncodingPreset {
            crf: self.crf.unwrap_or(base.crf),
            film_grain: self.film_grain.unwrap_or(base.film_grain),
            nvenc_cq: self.nvenc_cq.unwrap_or(base.nvenc_cq),
            qsv_quality: self.qsv_quality.unwrap_or(base.qsv_quality),
            amf_quality: self.amf_quality.unwrap_or(base.amf_quality),
        }
    }
}

/// The `[presets]` tables as written, with any tier left out.
#[derive(Deserialize, Default)]
#[serde(default)]
struct PartialPresets {
    sd: PartialPreset,
    hd: PartialPreset,
    full_hd: PartialPreset,
    full_hd_hdr: PartialPreset,
    full_hd_dv: PartialPreset,
    uhd: PartialPreset,
    uhd_hdr: PartialPreset,
    uhd_dv: PartialPreset,
}

impl From<PartialPresets> for EncodingPresetsConfig {
    fn from(written: PartialPresets) -> Self {
        let base = Self::default();
        Self {
            sd: written.sd.over(&base.sd),
            hd: written.hd.over(&base.hd),
            full_hd: written.full_hd.over(&base.full_hd),
            full_hd_hdr: written.full_hd_hdr.over(&base.full_hd_hdr),
            full_hd_dv: written.full_hd_dv.over(&base.full_hd_dv),
            uhd: written.uhd.over(&base.uhd),
            uhd_hdr: written.uhd_hdr.over(&base.uhd_hdr),
            uhd_dv: written.uhd_dv.over(&base.uhd_dv),
        }
    }
}

fn default_full_hd_dv() -> EncodingPreset {
    EncodingPreset {
        crf: 20,
        film_grain: 3,
        nvenc_cq: 21,
        qsv_quality: 20,
        amf_quality: 21,
    }
}

fn default_uhd_dv() -> EncodingPreset {
    EncodingPreset {
        crf: 20,
        film_grain: 4,
        nvenc_cq: 20,
        qsv_quality: 20,
        amf_quality: 20,
    }
}

impl EncodingPresetsConfig {
    /// Balanced presets — identical to the built-in defaults.
    pub fn medium() -> Self {
        Self::default()
    }

    /// Smaller-file presets (higher CRF/CQ across every tier).
    pub fn low() -> Self {
        Self::default().shifted(4)
    }

    /// Higher-quality presets (lower CRF/CQ across every tier).
    pub fn high() -> Self {
        Self::default().shifted(-4)
    }

    /// Apply a quality shift to every resolution tier.
    fn shifted(self, delta: i16) -> Self {
        Self {
            sd: self.sd.shifted(delta),
            hd: self.hd.shifted(delta),
            full_hd: self.full_hd.shifted(delta),
            full_hd_hdr: self.full_hd_hdr.shifted(delta),
            full_hd_dv: self.full_hd_dv.shifted(delta),
            uhd: self.uhd.shifted(delta),
            uhd_hdr: self.uhd_hdr.shifted(delta),
            uhd_dv: self.uhd_dv.shifted(delta),
        }
    }

    pub fn all_mut(&mut self) -> [&mut EncodingPreset; 8] {
        [
            &mut self.sd,
            &mut self.hd,
            &mut self.full_hd,
            &mut self.full_hd_hdr,
            &mut self.full_hd_dv,
            &mut self.uhd,
            &mut self.uhd_hdr,
            &mut self.uhd_dv,
        ]
    }
}

impl Default for EncodingPresetsConfig {
    fn default() -> Self {
        Self {
            sd: EncodingPreset {
                crf: 24,
                film_grain: 0,
                nvenc_cq: 26,
                qsv_quality: 24,
                amf_quality: 26,
            },
            hd: EncodingPreset {
                crf: 23,
                film_grain: 0,
                nvenc_cq: 25,
                qsv_quality: 23,
                amf_quality: 25,
            },
            full_hd: EncodingPreset {
                crf: 22,
                film_grain: 0,
                nvenc_cq: 24,
                qsv_quality: 22,
                amf_quality: 24,
            },
            full_hd_hdr: EncodingPreset {
                crf: 23,
                film_grain: 3,
                nvenc_cq: 23,
                qsv_quality: 23,
                amf_quality: 23,
            },
            full_hd_dv: default_full_hd_dv(),
            uhd: EncodingPreset {
                crf: 23,
                film_grain: 4,
                nvenc_cq: 25,
                qsv_quality: 24,
                amf_quality: 25,
            },
            uhd_hdr: EncodingPreset {
                crf: 22,
                film_grain: 4,
                nvenc_cq: 22,
                qsv_quality: 22,
                amf_quality: 22,
            },
            uhd_dv: default_uhd_dv(),
        }
    }
}

/// Output configuration
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct OutputConfig {
    /// Output file suffix
    pub suffix: String,
    /// Output container format, one of [`OutputConfig::CONTAINERS`]
    pub container: String,
    /// Whether to place output in same directory as source
    pub same_directory: bool,
    /// Custom output directory (if `same_directory` is false)
    pub output_directory: Option<String>,
}

impl OutputConfig {
    /// Containers the encoder writes: Matroska, MP4 and `WebM`.
    pub const CONTAINERS: [&'static str; 3] = ["mkv", "mp4", "webm"];

    /// The supported container `name` spells, ignoring case, surrounding
    /// spaces and dots.
    pub fn supported_container(name: &str) -> Option<&'static str> {
        let name = name.trim().trim_matches('.');
        Self::CONTAINERS
            .into_iter()
            .find(|container| container.eq_ignore_ascii_case(name))
    }
}

impl Default for OutputConfig {
    fn default() -> Self {
        Self {
            suffix: "_av1".to_string(),
            container: "mkv".to_string(),
            same_directory: true,
            output_directory: None,
        }
    }
}

/// Daemon / web UI configuration
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct DaemonConfig {
    /// Whether `--start` is allowed to start the daemon
    pub enabled: bool,
    /// Bind address for the web server. Defaults to loopback; reaching the
    /// network is opt-in.
    pub bind_address: String,
    /// TCP port for the web server
    pub port: u16,
    /// Directory the web file browser is confined to. Empty means the whole
    /// filesystem.
    #[serde(default)]
    pub browse_root: String,
    /// Shared secret required by the `/api` endpoints. Values shorter than 32
    /// bytes are replaced with a generated token when the daemon starts.
    #[serde(default)]
    pub auth_token: String,
    /// Explicit opt-in to bind off-loopback over plain HTTP. Without it the
    /// daemon refuses a public bind address.
    #[serde(default)]
    pub allow_insecure_lan: bool,
    /// Treats every web request as remote, which makes the `[daemon]` and
    /// `[disc]` settings and autostart read-only in every browser.
    #[serde(default)]
    pub behind_proxy: bool,
}

impl DaemonConfig {
    pub fn listen_address(&self) -> String {
        self.bind_address.parse::<std::net::IpAddr>().map_or_else(
            |_| format!("{}:{}", self.bind_address, self.port),
            |ip| std::net::SocketAddr::new(ip, self.port).to_string(),
        )
    }

    /// The URL to open the web UI with, carrying the access token when one is
    /// set, which authorises the browser that follows the link.
    ///
    /// A wildcard bind is shown as loopback: `http://0.0.0.0:8399/` is an
    /// address to listen on, not one a browser can open.
    pub fn url(&self) -> String {
        let host = match self.bind_address.parse::<std::net::IpAddr>() {
            Ok(ip) if ip.is_unspecified() && ip.is_ipv4() => "127.0.0.1".to_string(),
            Ok(ip) if ip.is_unspecified() => "[::1]".to_string(),
            Ok(ip) => std::net::SocketAddr::new(ip, self.port)
                .to_string()
                .rsplit_once(':')
                .map_or_else(|| self.bind_address.clone(), |(host, _)| host.to_string()),
            Err(_) => self.bind_address.clone(),
        };
        let authority = format!("{host}:{}", self.port);
        if self.auth_token.is_empty() {
            format!("http://{authority}/")
        } else {
            let token = self
                .auth_token
                .bytes()
                .fold(String::new(), |mut out, byte| {
                    use std::fmt::Write;
                    if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
                        out.push(char::from(byte));
                    } else {
                        let _ = write!(out, "%{byte:02X}");
                    }
                    out
                });
            format!("http://{authority}/#token={token}")
        }
    }

    /// A fresh 128-bit access token, hex encoded.
    pub fn generate_token() -> Result<String, String> {
        crate::utils::random_hex(16)
    }

    /// Bind addresses that expose the daemon beyond this machine.
    pub fn binds_publicly(&self) -> bool {
        match self.bind_address.parse::<std::net::IpAddr>() {
            Ok(ip) => !ip.is_loopback(),
            Err(_) => false,
        }
    }

    /// Public bind without the explicit insecure-LAN opt-in.
    pub fn refuses_public_bind(&self) -> bool {
        self.binds_publicly() && !self.allow_insecure_lan
    }
}

impl Default for DaemonConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            bind_address: "127.0.0.1".to_string(),
            port: 8399,
            browse_root: String::new(),
            auth_token: String::new(),
            allow_insecure_lan: false,
            behind_proxy: false,
        }
    }
}

/// Disc ripping configuration
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct DiscConfig {
    /// Path to `makemkvcon`. Unset resolves through `PATH` and then the
    /// platform's install location.
    #[serde(default)]
    pub makemkvcon_path: Option<String>,
    /// Where ripped titles are staged until their encode finishes. A Blu-ray
    /// title needs 100 GB or more. Unset stages under the system temp
    /// directory.
    #[serde(default)]
    pub staging_directory: Option<String>,
}

/// What to do with the audio tracks of a newly queued file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum AudioMode {
    /// Pass the source streams through untouched
    #[default]
    #[serde(rename = "copy")]
    Copy,
    /// Re-encode to Opus at the source's channel layout
    #[serde(rename = "opus")]
    Opus,
}

impl AudioMode {
    /// All modes, in display/cycle order.
    pub const ALL: [AudioMode; 2] = [AudioMode::Copy, AudioMode::Opus];

    /// The next mode in [`AudioMode::ALL`], wrapping around.
    pub fn next(self) -> Self {
        let i = Self::ALL.iter().position(|&m| m == self).unwrap_or(0);
        Self::ALL[(i + 1) % Self::ALL.len()]
    }

    /// The previous mode in [`AudioMode::ALL`], wrapping around.
    pub fn prev(self) -> Self {
        let i = Self::ALL.iter().position(|&m| m == self).unwrap_or(0);
        Self::ALL[(i + Self::ALL.len() - 1) % Self::ALL.len()]
    }
}

/// Audio transcoding configuration
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct AudioConfig {
    /// What newly analyzed files default to. Per-track choices override it.
    pub default_mode: AudioMode,
    /// Opus bitrate allotted per channel, in kbps. The channel layout is never
    /// changed; the stream bitrate is this times the channel count.
    pub opus_bitrate_per_channel: u16,
    /// Copy tracks that are already Opus instead of re-encoding them.
    pub skip_already_opus: bool,
}

impl AudioConfig {
    /// Lowest and highest per-channel bitrate `sanitize` will accept, in kbps.
    pub const MIN_PER_CHANNEL: u16 = 16;
    pub const MAX_PER_CHANNEL: u16 = 256;

    /// Opus bitrate for a stream with this many channels, in kbps. A source
    /// whose channel count ffprobe could not report is treated as stereo.
    pub fn opus_bitrate_kbps(&self, channels: Option<u16>) -> u32 {
        u32::from(channels.unwrap_or(2).max(1)) * u32::from(self.opus_bitrate_per_channel)
    }
}

impl Default for AudioConfig {
    fn default() -> Self {
        Self {
            default_mode: AudioMode::Copy,
            opus_bitrate_per_channel: 64,
            skip_already_opus: true,
        }
    }
}

/// Track selection preset configuration
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct TrackPresetConfig {
    /// Preferred audio languages
    pub preferred_audio_languages: Vec<String>,
    /// Preferred subtitle languages
    pub preferred_subtitle_languages: Vec<String>,
    /// Whether to auto-select all tracks when no preference matches
    pub select_all_fallback: bool,
}

impl Default for TrackPresetConfig {
    fn default() -> Self {
        Self {
            preferred_audio_languages: vec!["eng".to_string(), "ita".to_string()],
            preferred_subtitle_languages: vec!["eng".to_string()],
            select_all_fallback: true,
        }
    }
}