common.rs 6.99 KB
Newer Older
1
use clap::{App, Arg};
2
use rav1e::*;
3 4
use std::fs::File;
use std::io;
5 6
use std::io::prelude::*;
use std::slice;
Kyle Siefring's avatar
Kyle Siefring committed
7
use std::sync::Arc;
8
use y4m;
9 10

pub struct EncoderIO {
Kyle Siefring's avatar
Kyle Siefring committed
11 12 13
  pub input: Box<dyn Read>,
  pub output: Box<dyn Write>,
  pub rec: Option<Box<dyn Write>>
14 15
}

Luca Barbato's avatar
Luca Barbato committed
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
pub fn parse_cli() -> (EncoderIO, EncoderConfig, usize) {
  let matches = App::new("rav1e")
    .version("0.1.0")
    .about("AV1 video encoder")
    .arg(
      Arg::with_name("INPUT")
        .help("Uncompressed YUV4MPEG2 video input")
        .required(true)
        .index(1)
    ).arg(
      Arg::with_name("OUTPUT")
        .help("Compressed AV1 in IVF video output")
        .short("o")
        .long("output")
        .required(true)
        .takes_value(true)
    ).arg(Arg::with_name("RECONSTRUCTION").short("r").takes_value(true))
    .arg(
      Arg::with_name("LIMIT")
        .help("Maximum number of frames to encode")
        .short("l")
        .long("limit")
        .takes_value(true)
        .default_value("0")
    ).arg(
      Arg::with_name("QP")
        .help("Quantizer (0-255)")
        .long("quantizer")
        .takes_value(true)
        .default_value("100")
    ).arg(
      Arg::with_name("SPEED")
        .help("Speed level (0(slow)-10(fast))")
        .short("s")
        .long("speed")
        .takes_value(true)
        .default_value("3")
53 54 55 56 57 58 59 60 61 62 63 64
    ).arg(
      Arg::with_name("KEYFRAME_INTERVAL")
        .help("Keyframe interval")
        .short("I")
        .long("keyint")
        .takes_value(true)
        .default_value("30")
    ).arg(
      Arg::with_name("LOW_LATENCY")
        .help("low latency mode. true or false")
        .long("low_latency")
        .takes_value(true)
Frank Bossen's avatar
Frank Bossen committed
65
        .default_value("true")
Luca Barbato's avatar
Luca Barbato committed
66 67 68 69 70 71 72 73
    ).arg(
      Arg::with_name("TUNE")
        .help("Quality tuning (Will enforce partition sizes >= 8x8)")
        .long("tune")
        .possible_values(&Tune::variants())
        .default_value("psnr")
        .case_insensitive(true)
    ).get_matches();
74

Luca Barbato's avatar
Luca Barbato committed
75 76 77 78 79 80 81 82 83 84 85 86 87
  let io = EncoderIO {
    input: match matches.value_of("INPUT").unwrap() {
      "-" => Box::new(io::stdin()) as Box<dyn Read>,
      f => Box::new(File::open(&f).unwrap()) as Box<dyn Read>
    },
    output: match matches.value_of("OUTPUT").unwrap() {
      "-" => Box::new(io::stdout()) as Box<dyn Write>,
      f => Box::new(File::create(&f).unwrap()) as Box<dyn Write>
    },
    rec: matches
      .value_of("RECONSTRUCTION")
      .map(|f| Box::new(File::create(&f).unwrap()) as Box<dyn Write>)
  };
Kyle Siefring's avatar
Kyle Siefring committed
88

Luca Barbato's avatar
Luca Barbato committed
89
  let config = EncoderConfig {
90 91
    key_frame_interval: matches.value_of("KEYFRAME_INTERVAL").unwrap().parse().unwrap(),
    low_latency: matches.value_of("LOW_LATENCY").unwrap().parse().unwrap(),
Luca Barbato's avatar
Luca Barbato committed
92 93 94 95
    quantizer: matches.value_of("QP").unwrap().parse().unwrap(),
    speed: matches.value_of("SPEED").unwrap().parse().unwrap(),
    tune: matches.value_of("TUNE").unwrap().parse().unwrap()
  };
Kyle Siefring's avatar
Kyle Siefring committed
96

Luca Barbato's avatar
Luca Barbato committed
97 98 99 100 101 102
  // Validate arguments
  if config.quantizer == 0 {
    unimplemented!();
  } else if config.quantizer > 255 || config.speed > 10 {
    panic!("argument out of range");
  }
Kyle Siefring's avatar
Kyle Siefring committed
103

Luca Barbato's avatar
Luca Barbato committed
104
  let limit = matches.value_of("LIMIT").unwrap().parse().unwrap();
Kyle Siefring's avatar
Kyle Siefring committed
105

Luca Barbato's avatar
Luca Barbato committed
106
  (io, config, limit)
107
}
108 109

/// Encode and write a frame.
fbossen's avatar
fbossen committed
110
/// returns wheter done with sequence
Kyle Siefring's avatar
Kyle Siefring committed
111 112 113
pub fn process_frame(
  ctx: &mut Context, output_file: &mut dyn Write,
  y4m_dec: &mut y4m::Decoder<'_, Box<dyn Read>>,
114
  mut y4m_enc: Option<&mut y4m::Encoder<'_, Box<dyn Write>>>
Kyle Siefring's avatar
Kyle Siefring committed
115 116 117 118 119 120 121 122 123 124 125
) -> bool {
  unsafe {
    av1_rtcd();
    aom_dsp_rtcd();
  }
  let width = y4m_dec.get_width();
  let height = y4m_dec.get_height();
  let y4m_bits = y4m_dec.get_bit_depth();
  let y4m_bytes = y4m_dec.get_bytes_per_sample();
  let bit_depth = y4m_dec.get_colorspace().get_bit_depth();

fbossen's avatar
fbossen committed
126
  let read_frame =
Kyle Siefring's avatar
Kyle Siefring committed
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
  match y4m_dec.read_frame() {
    Ok(y4m_frame) => {
      let y4m_y = y4m_frame.get_y_plane();
      let y4m_u = y4m_frame.get_u_plane();
      let y4m_v = y4m_frame.get_v_plane();
      let mut input = ctx.new_frame();
      {
        let input = Arc::get_mut(&mut input).unwrap();
        input.planes[0].copy_from_raw_u8(&y4m_y, width * y4m_bytes, y4m_bytes);
        input.planes[1].copy_from_raw_u8(
          &y4m_u,
          width * y4m_bytes / 2,
          y4m_bytes
        );
        input.planes[2].copy_from_raw_u8(
          &y4m_v,
          width * y4m_bytes / 2,
          y4m_bytes
        );
      }

      match y4m_bits {
        8 | 10 | 12 => {}
        _ => panic!("unknown input bit depth!")
      }

      let _ = ctx.send_frame(input);
fbossen's avatar
fbossen committed
154 155 156 157 158 159 160 161 162 163 164 165 166
      true
    }
    _ => {
      ctx.flush();
      false
    }
  };

  let mut has_data = true;
  while has_data {
    let pkt_wrapped = ctx.receive_packet();
    match pkt_wrapped {
    Ok(pkt) => {
Kyle Siefring's avatar
Kyle Siefring committed
167 168
      eprintln!("{}", pkt);
      write_ivf_frame(output_file, pkt.number as u64, pkt.data.as_ref());
169
      if let Some(y4m_enc_uw) = y4m_enc.as_mut() {
fbossen's avatar
fbossen committed
170
      if let Some(rec) = pkt.rec {
Kyle Siefring's avatar
Kyle Siefring committed
171 172 173 174 175 176 177 178 179 180
        let pitch_y = if bit_depth > 8 { width * 2 } else { width };
        let pitch_uv = pitch_y / 2;

        let (mut rec_y, mut rec_u, mut rec_v) = (
          vec![128u8; pitch_y * height],
          vec![128u8; pitch_uv * (height / 2)],
          vec![128u8; pitch_uv * (height / 2)]
        );

        let (stride_y, stride_u, stride_v) = (
fbossen's avatar
fbossen committed
181 182 183
          rec.planes[0].cfg.stride,
          rec.planes[1].cfg.stride,
          rec.planes[2].cfg.stride
Kyle Siefring's avatar
Kyle Siefring committed
184 185
        );

fbossen's avatar
fbossen committed
186
        for (line, line_out) in rec.planes[0]
Kyle Siefring's avatar
Kyle Siefring committed
187 188 189 190 191 192 193 194 195 196
          .data_origin()
          .chunks(stride_y)
          .zip(rec_y.chunks_mut(pitch_y))
        {
          if bit_depth > 8 {
            unsafe {
              line_out.copy_from_slice(slice::from_raw_parts::<u8>(
                line.as_ptr() as (*const u8),
                pitch_y
              ));
Luca Barbato's avatar
Luca Barbato committed
197
            }
Kyle Siefring's avatar
Kyle Siefring committed
198 199 200 201 202 203
          } else {
            line_out.copy_from_slice(
              &line.iter().map(|&v| v as u8).collect::<Vec<u8>>()[..pitch_y]
            );
          }
        }
fbossen's avatar
fbossen committed
204
        for (line, line_out) in rec.planes[1]
Kyle Siefring's avatar
Kyle Siefring committed
205 206 207 208 209 210 211 212 213 214
          .data_origin()
          .chunks(stride_u)
          .zip(rec_u.chunks_mut(pitch_uv))
        {
          if bit_depth > 8 {
            unsafe {
              line_out.copy_from_slice(slice::from_raw_parts::<u8>(
                line.as_ptr() as (*const u8),
                pitch_uv
              ));
215
            }
Kyle Siefring's avatar
Kyle Siefring committed
216 217 218 219 220 221
          } else {
            line_out.copy_from_slice(
              &line.iter().map(|&v| v as u8).collect::<Vec<u8>>()[..pitch_uv]
            );
          }
        }
fbossen's avatar
fbossen committed
222
        for (line, line_out) in rec.planes[2]
Kyle Siefring's avatar
Kyle Siefring committed
223 224 225 226 227 228 229 230 231 232
          .data_origin()
          .chunks(stride_v)
          .zip(rec_v.chunks_mut(pitch_uv))
        {
          if bit_depth > 8 {
            unsafe {
              line_out.copy_from_slice(slice::from_raw_parts::<u8>(
                line.as_ptr() as (*const u8),
                pitch_uv
              ));
233
            }
Kyle Siefring's avatar
Kyle Siefring committed
234 235 236 237 238 239 240 241
          } else {
            line_out.copy_from_slice(
              &line.iter().map(|&v| v as u8).collect::<Vec<u8>>()[..pitch_uv]
            );
          }
        }

        let rec_frame = y4m::Frame::new([&rec_y, &rec_u, &rec_v], None);
fbossen's avatar
fbossen committed
242
        y4m_enc_uw.write_frame(&rec_frame).unwrap();
Kyle Siefring's avatar
Kyle Siefring committed
243
      }
244
      }
fbossen's avatar
fbossen committed
245 246
    },
    _ => { has_data = false; }
247
    }
Kyle Siefring's avatar
Kyle Siefring committed
248
  }
fbossen's avatar
fbossen committed
249
  read_frame
250
}