otr-utils 0.5.1

Utilities for decoding and cutting video files that were downloaded from Online TV Recorder <https://onlinetvrecorder.com/>
Documentation
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
// SPDX-FileCopyrightText: 2024 Michael Picht <mipi@fsfe.org>
//
// SPDX-License-Identifier: GPL-3.0-or-later

use anyhow::{anyhow, Context};
use lazy_static::lazy_static;
use regex::Regex;
use std::{
    fmt::{self, Debug, Display},
    ops::{Add, Sub},
    str::FromStr,
};

use super::info::Metadata;

/// Generalization of an interval boundary - i.e., a timestamp or frame number
pub trait Boundary:
    Clone
    + Copy
    + Display
    + FromStr<Err = anyhow::Error>
    + From<f64>
    + Into<f64>
    + Add<Output = Self>
    + Sub<Output = Self>
    + PartialOrd
{
    /// Convert boundary into frame number
    fn to_frame(self, _: &Metadata) -> anyhow::Result<Frame>;

    /// Convert boundary into timestamp
    fn to_time(self, _: &Metadata) -> anyhow::Result<Time>;
}

/// Boundary type
#[derive(Clone, Default, Eq, Hash, PartialEq)]
pub enum BoundaryType {
    #[default]
    Frame,
    Time,
}
impl Display for BoundaryType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                BoundaryType::Frame => "frame",
                BoundaryType::Time => "time",
            }
        )
    }
}

/// Conversion from &str. Since a variety of different strings could be used to
/// indicate a timestamp or a frame number, the coding must take this into
/// account
impl FromStr for BoundaryType {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.to_uppercase().contains("FRAME") {
            Ok(BoundaryType::Frame)
        } else if s.to_uppercase().contains("TIME") {
            Ok(BoundaryType::Time)
        } else {
            Err(anyhow!("\"{}\" is not a valid boundary type", s))
        }
    }
}

/// Wrapper type for frame numbers
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Frame(usize);
impl Display for Frame {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Conversion from and to usize
impl From<usize> for Frame {
    fn from(frame: usize) -> Self {
        Frame(frame)
    }
}
impl From<Frame> for usize {
    fn from(frame: Frame) -> Self {
        frame.0
    }
}

/// Conversion from and to f64
impl From<f64> for Frame {
    // frame is expected to not being negative. To be on the safe side, the
    // absolute value of frame is used
    fn from(frame: f64) -> Self {
        Frame(frame.abs() as usize)
    }
}
impl From<Frame> for f64 {
    fn from(frame: Frame) -> Self {
        frame.0 as f64
    }
}

/// Conversion from &str
impl FromStr for Frame {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::from(s.parse::<f64>().context(format!(
            "Could not parse a frame number from \"{}\"",
            s
        ))?))
    }
}

/// Addition and substraction with same type and integer types
impl Add for Frame {
    type Output = Self;
    fn add(self, rhs: Self) -> Self {
        Frame(self.0 + rhs.0)
    }
}
impl Add<usize> for Frame {
    type Output = Self;

    fn add(self, rhs: usize) -> Self {
        Frame(self.0 + rhs)
    }
}

impl Sub for Frame {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self {
        Frame(self.0 - rhs.0)
    }
}
impl Sub<usize> for Frame {
    type Output = Self;

    fn sub(self, rhs: usize) -> Self {
        Frame(self.0 - rhs)
    }
}

impl Boundary for Frame {
    // Convert frame number into timestamp
    fn to_frame(self, _: &Metadata) -> anyhow::Result<Frame> {
        Ok(self)
    }

    // Conversion into timestamp: Nothing to do
    fn to_time(self, metadata: &Metadata) -> anyhow::Result<Time> {
        metadata.frame_to_time(self)
    }
}

/// Wrapper type for time (timestamps and time duration. Time is in microseconds
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct Time(u64);
impl Display for Time {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:.6}", self.0 as f64 / 1000000_f64)
    }
}

/// Conversion from and to f64 (f64 value is interpreted as time in seconds)
impl From<f64> for Time {
    // secs is expected to not being negative. To be on the safe side, the
    // absolute value of secs is used
    fn from(secs: f64) -> Self {
        Time((secs.abs() * 1000000_f64) as u64)
    }
}
impl From<Time> for f64 {
    fn from(time: Time) -> Self {
        time.0 as f64 / 1000000_f64
    }
}

lazy_static! {
    // Regular expression representing a time string
    static ref RE_TIME: Regex =
        Regex::new(r#"^(?<hours>\d+):(?<mins>[0-5]\d)+:(?<secs>[0-5]\d)+(\.(?<subs>\d{0,6}))*$"#).unwrap();
}

/// Conversion from &str
impl FromStr for Time {
    type Err = anyhow::Error;

    // s must match "[HH:MM:SS.ssssss]" with HH = hours, MM = minutes,
    // SS = seconds, ssssss = sub seconds
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if !RE_TIME.is_match(s) {
            return Err(anyhow!("\"{}\" is not a valid time string", s));
        }

        // Since here it is clear that s matches the regexp, we can use unwrap()
        // in the following safely

        // Extract hours, minutes and seconds
        let caps = RE_TIME.captures(s).unwrap();
        let hours = caps.name("hours").unwrap().as_str().parse::<f64>().unwrap();
        if !(0.0..=23.0).contains(&hours) {
            return Err(anyhow!("Hours in {} are not valid", s));
        }
        let mins = caps.name("mins").unwrap().as_str().parse::<f64>().unwrap();
        let secs = caps.name("secs").unwrap().as_str().parse::<f64>().unwrap();

        Ok(Self::from(
            hours * 3600.0
                + mins * 60.0
                + secs
                + match caps.name("subs") {
                    Some(subs_match) => {
                        let subs_str = subs_match.as_str();
                        let subs = subs_str.parse::<f64>().unwrap();
                        subs * f64::powf(10_f64, -(subs_str.len() as f64))
                    }
                    None => 0.0,
                },
        ))
    }
}

/// Addition and subtraction for same type
impl Add for Time {
    type Output = Time;
    fn add(self, rhs: Self) -> Self {
        Time(self.0 + rhs.0)
    }
}
impl Sub for Time {
    type Output = Time;
    fn sub(self, rhs: Self) -> Self {
        Time(self.0 - rhs.0)
    }
}

impl Boundary for Time {
    // Convert timestamp into frame number
    fn to_frame(self, metadata: &Metadata) -> anyhow::Result<Frame> {
        if !metadata.has_frames() {
            Err(anyhow!(
                "Cannot turn time boundary into frame boundary, since video has no frames"
            ))
        } else {
            Ok(metadata.time_to_frame(self).context(format!(
                "Cannot turn time boundary {} into frame boundary",
                self
            ))?)
        }
    }

    // Conversion into timestamp: Nothing to do
    fn to_time(self, _: &Metadata) -> anyhow::Result<Time> {
        Ok(self)
    }
}

/// Generic cut interval
pub struct Interval<B>
where
    B: Boundary,
{
    from: B,
    to: B,
}
impl<B> Display for Interval<B>
where
    B: Boundary,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{}, {}]", self.from, self.to)
    }
}

lazy_static! {
    /// Regular expression for a string representing one interval
    static ref RE_INTERVAL: Regex = Regex::new(r#"^\[(?<from>[^\[\],]+),(?<to>[^\[\],]+)\]$"#).unwrap();
}

/// Conversion from string
impl<B> FromStr for Interval<B>
where
    B: Boundary,
{
    type Err = anyhow::Error;

    /// s must have the form "[<FROM-STRING>,<TO-STRING>]", where FROM_STRING and
    /// TO_STRING must be according to the corresponding boundary type
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if !RE_INTERVAL.is_match(s) {
            return Err(anyhow!("\"{}\" is not a valid interval", s));
        }

        Ok(Interval::<B> {
            from: B::from_str(
                RE_INTERVAL
                    .captures(s)
                    .unwrap()
                    .name("from")
                    .unwrap()
                    .as_str(),
            )?,
            to: B::from_str(
                RE_INTERVAL
                    .captures(s)
                    .unwrap()
                    .name("to")
                    .unwrap()
                    .as_str(),
            )?,
        })
    }
}

impl<B> Interval<B>
where
    B: Boundary,
{
    /// Creates an interval with from an to as boundaries. If required, from and
    /// to is switched to make sure that interval.form <= interval.to
    pub fn from_from_to(from: B, to: B) -> Self {
        if from < to {
            Interval::<B> { from, to }
        } else {
            Interval::<B> { from: to, to: from }
        }
    }

    /// Creates an interval with start as lower boundary and start + duration as
    /// upper boundary
    pub fn from_start_duration(start: B, duration: B) -> Self {
        Interval::<B> {
            from: start,
            to: start + duration,
        }
    }

    pub fn from(&self) -> B {
        self.from
    }

    pub fn to(&self) -> B {
        self.to
    }

    pub fn len(&self) -> f64 {
        Into::<f64>::into(self.to - self.from)
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0.0
    }

    pub fn to_frames(&self, metadata: &Metadata) -> anyhow::Result<Interval<Frame>> {
        let err_msg = format!("Could not convert interval {} into frames", self);

        Ok(Interval::<Frame> {
            from: self.from.to_frame(metadata).context(err_msg.clone())?,
            to: self.to.to_frame(metadata).context(err_msg.clone())?,
        })
    }

    pub fn to_times(&self, metadata: &Metadata) -> anyhow::Result<Interval<Time>> {
        let err_msg = format!("Could not convert interval {} into times", self);

        Ok(Interval::<Time> {
            from: self.from.to_time(metadata).context(err_msg.clone())?,
            to: self.to.to_time(metadata).context(err_msg.clone())?,
        })
    }
}

impl Interval<Frame> {
    pub fn to_key_frames(&self, metadata: &Metadata) -> Option<Interval<Frame>> {
        if let Some(from) = metadata.key_frame_greater_or_equal_until_limit(self.from, self.to) {
            if let Some(to) = metadata.key_frame_less_or_equal_until_limit(self.to, self.from) {
                return Some(Interval::<Frame> { from, to });
            }
        }

        None
    }
}

lazy_static! {
    /// Regular expression for a string of intervals
    static ref RE_INTERVALS: Regex = Regex::new(r#"^(?<interval>\[[^\[\],]+,[^\[\],]+\])+$"#).unwrap();
}

/// Create a vector of intervals from a string representation of the form
/// "[<FROM-STRING>,<TO-STRING>][<FROM-STRING>,<TO-STRING>]..[<FROM-STRING>,<TO-STRING>]"
pub fn intervals_from_str<B>(s: &str) -> anyhow::Result<Vec<Interval<B>>>
where
    B: Boundary,
{
    if !RE_INTERVALS.is_match(s) {
        return Err(anyhow!("\"{}\" is not a valid list of intervals", s));
    }

    let mut intervals = vec![];

    // Split string into sub strings, where each sub string contains a single
    // interval string and create an interval from it
    for s in s.split_inclusive(']').collect::<Vec<_>>() {
        let interval = Interval::<B>::from_str(s)
            .context(format!("Could not convert \"{}\" into intervals", s))?;
        // Only accept intervals of length greater than zero
        if !interval.is_empty() {
            intervals.push(interval)
        }
    }

    Ok(intervals)
}