1 | // Copyright (c) 2020-2022, The rav1e contributors. All rights reserved |
2 | // |
3 | // This source code is subject to the terms of the BSD 2 Clause License and |
4 | // the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License |
5 | // was not distributed with this source code in the LICENSE file, you can |
6 | // obtain it at www.aomedia.org/license/software. If the Alliance for Open |
7 | // Media Patent License 1.0 was not distributed with this source code in the |
8 | // PATENTS file, you can obtain it at www.aomedia.org/license/patent. |
9 | |
10 | use thiserror::Error; |
11 | |
12 | use crate::rate::*; |
13 | |
14 | /// Rate control errors |
15 | #[derive (Debug, Error)] |
16 | pub enum Error { |
17 | /// The summary provided is not compatible with the current encoder version |
18 | #[error("Incompatible version {0}" )] |
19 | InvalidVersion(i64), |
20 | /// The summary provided is possibly corrupted |
21 | #[error("The summary content is invalid: {0}" )] |
22 | CorruptedSummary(String), |
23 | } |
24 | |
25 | /// Rate control configuration |
26 | #[derive (Clone, Debug, Default)] |
27 | pub struct RateControlConfig { |
28 | pub(crate) emit_pass_data: bool, |
29 | pub(crate) summary: Option<RateControlSummary>, |
30 | } |
31 | |
32 | pub use crate::rate::RCSummary as RateControlSummary; |
33 | |
34 | impl RateControlSummary { |
35 | /// Deserializes a byte slice into a `RateControlSummary` |
36 | pub(crate) fn from_slice(bytes: &[u8]) -> Result<Self, Error> { |
37 | let mut de: RCDeserialize = RCDeserialize::default(); |
38 | let _ = de.buffer_fill(buf:bytes, consumed:0, TWOPASS_HEADER_SZ); |
39 | |
40 | de.parse_summary().map_err(op:Error::CorruptedSummary) |
41 | } |
42 | } |
43 | |
44 | impl RateControlConfig { |
45 | /// Create a rate control configuration from a serialized summary |
46 | /// |
47 | /// # Errors |
48 | /// |
49 | /// Returns an error if the serialized data is invalid. |
50 | pub fn from_summary_slice(bytes: &[u8]) -> Result<Self, Error> { |
51 | Ok(Self { |
52 | summary: Some(RateControlSummary::from_slice(bytes)?), |
53 | ..Default::default() |
54 | }) |
55 | } |
56 | /// Create a default rate control configuration |
57 | /// |
58 | /// By default the encoder is in single pass mode. |
59 | pub fn new() -> Self { |
60 | Default::default() |
61 | } |
62 | |
63 | /// Set a rate control summary |
64 | /// |
65 | /// Enable the second pass encoding mode |
66 | pub const fn with_summary(mut self, summary: RateControlSummary) -> Self { |
67 | self.summary = Some(summary); |
68 | self |
69 | } |
70 | |
71 | /// Emit the current pass data |
72 | /// |
73 | /// The pass data will be used in a second pass encoding session |
74 | pub const fn with_emit_data(mut self, emit: bool) -> Self { |
75 | self.emit_pass_data = emit; |
76 | self |
77 | } |
78 | } |
79 | |