| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | use ec_core::frame::{PixelFormat, Plane, VideoFrame}; |
| 14 | use ec_h265::Decoder; |
| 15 | use ec_h265::encoder::{Encoder, EncoderConfig, RateControl}; |
| 16 | use std::io::{BufWriter, Read, Write}; |
| 17 | use std::process::ExitCode; |
| 18 | |
| 19 | fn frame_size(w: usize, h: usize) -> usize { |
| 20 | w * h + 2 * w.div_ceil(2) * h.div_ceil(2) |
| 21 | } |
| 22 | |
| 23 | fn split_frame(buf: &[u8], w: usize, h: usize) -> VideoFrame { |
| 24 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 25 | let y = buf[..w * h].to_vec(); |
| 26 | let cb = buf[w * h..w * h + cw * ch].to_vec(); |
| 27 | let cr = buf[w * h + cw * ch..].to_vec(); |
| 28 | VideoFrame::try_new( |
| 29 | PixelFormat::I420, |
| 30 | w as u32, |
| 31 | h as u32, |
| 32 | vec![Plane::new(y, w), Plane::new(cb, cw), Plane::new(cr, cw)], |
| 33 | ) |
| 34 | .expect("I420 planes at the stated size") |
| 35 | } |
| 36 | |
| 37 | |
| 38 | |
| 39 | fn access_units(stream: &[u8]) -> Vec<&[u8]> { |
| 40 | let mut starts = Vec::new(); |
| 41 | let mut last_slice = false; |
| 42 | let mut i = 0; |
| 43 | while i + 3 <= stream.len() { |
| 44 | if stream[i] == 0 && stream[i + 1] == 0 && stream[i + 2] == 1 { |
| 45 | let nal_type = stream.get(i + 3).map_or(0, |b| (b >> 1) & 0x3f); |
| 46 | if nal_type == 32 || (nal_type == 34 && last_slice) { |
| 47 | starts.push(i); |
| 48 | } |
| 49 | last_slice = nal_type < 32; |
| 50 | i += 3; |
| 51 | } else { |
| 52 | i += 1; |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | let mut out: Vec<&[u8]> = starts.windows(2).map(|w| &stream[w[0]..w[1]]).collect(); |
| 57 | if let Some(&last) = starts.last() { |
| 58 | out.push(&stream[last..]); |
| 59 | } |
| 60 | out |
| 61 | } |
| 62 | |
| 63 | fn encode(args: &[String]) -> Result<(), String> { |
| 64 | let arg = |i: usize| { |
| 65 | args.get(i) |
| 66 | .cloned() |
| 67 | .ok_or_else(|| format!("missing argument {i}")) |
| 68 | }; |
| 69 | let input = std::fs::File::open(arg(2)?).map_err(|e| e.to_string())?; |
| 70 | let w: usize = arg(3)?.parse().map_err(|_| "width")?; |
| 71 | let h: usize = arg(4)?.parse().map_err(|_| "height")?; |
| 72 | let keyint: usize = arg(5)?.parse().map_err(|_| "keyint")?; |
| 73 | let kbps: u32 = arg(6)?.parse().map_err(|_| "kbps")?; |
| 74 | let fps: f64 = arg(7)?.parse().map_err(|_| "fps")?; |
| 75 | let fs = frame_size(w, h); |
| 76 | |
| 77 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 78 | cfg.rate_control = RateControl::Bitrate { kbps, fps }; |
| 79 | cfg.keyint = keyint; |
| 80 | cfg.keep_recon = true; |
| 81 | if let Ok(v) = std::env::var("EC_H265_THREADS") { |
| 82 | cfg.threads = v.parse().map_err(|_| "EC_H265_THREADS")?; |
| 83 | } |
| 84 | let enc = Encoder::new(cfg).map_err(|e| e.to_string())?; |
| 85 | |
| 86 | let mut stream_out = BufWriter::new(std::fs::File::create(arg(8)?).map_err(|e| e.to_string())?); |
| 87 | let mut recon_out = BufWriter::new(std::fs::File::create(arg(9)?).map_err(|e| e.to_string())?); |
| 88 | let mut reader = std::io::BufReader::new(input); |
| 89 | let mut buf = vec![0u8; fs]; |
| 90 | let frames = std::iter::from_fn(move || { |
| 91 | |
| 92 | match reader.read_exact(&mut buf) { |
| 93 | Ok(()) => Some(split_frame(&buf, w, h)), |
| 94 | Err(_) => None, |
| 95 | } |
| 96 | }); |
| 97 | |
| 98 | let (mut count, mut bytes, mut qp_sum) = (0u64, 0u64, 0u64); |
| 99 | let (mut qp_min, mut qp_max) = (i32::MAX, i32::MIN); |
| 100 | enc.encode_sequence_with(frames, |pic| { |
| 101 | stream_out |
| 102 | .write_all(&pic.au) |
| 103 | .map_err(|e| ec_core::Error::corrupt(e.to_string()))?; |
| 104 | bytes += pic.au.len() as u64; |
| 105 | qp_sum += pic.qp as u64; |
| 106 | qp_min = qp_min.min(pic.qp); |
| 107 | qp_max = qp_max.max(pic.qp); |
| 108 | count += 1; |
| 109 | if let Some(r) = &pic.recon { |
| 110 | for p in &r.planes { |
| 111 | recon_out |
| 112 | .write_all(&p.data) |
| 113 | .map_err(|e| ec_core::Error::corrupt(e.to_string()))?; |
| 114 | } |
| 115 | } |
| 116 | Ok(()) |
| 117 | }) |
| 118 | .map_err(|e| e.to_string())?; |
| 119 | stream_out.flush().map_err(|e| e.to_string())?; |
| 120 | recon_out.flush().map_err(|e| e.to_string())?; |
| 121 | |
| 122 | let seconds = count as f64 / fps; |
| 123 | println!( |
| 124 | "frames={count} bytes={bytes} kbps={:.1} mean_qp={:.2} qp_min={qp_min} qp_max={qp_max}", |
| 125 | bytes as f64 * 8.0 / seconds / 1000.0, |
| 126 | qp_sum as f64 / count.max(1) as f64 |
| 127 | ); |
| 128 | Ok(()) |
| 129 | } |
| 130 | |
| 131 | fn decode(args: &[String]) -> Result<(), String> { |
| 132 | let arg = |i: usize| { |
| 133 | args.get(i) |
| 134 | .cloned() |
| 135 | .ok_or_else(|| format!("missing argument {i}")) |
| 136 | }; |
| 137 | let stream = std::fs::read(arg(2)?).map_err(|e| e.to_string())?; |
| 138 | let mut out = BufWriter::new(std::fs::File::create(arg(3)?).map_err(|e| e.to_string())?); |
| 139 | let mut dec = Decoder::new(); |
| 140 | let mut n = 0u64; |
| 141 | let emit = |dec: &mut Decoder, |
| 142 | out: &mut BufWriter<std::fs::File>, |
| 143 | n: &mut u64| |
| 144 | -> Result<(), String> { |
| 145 | while let Some(f) = dec.next_frame() { |
| 146 | let pic = &f.picture; |
| 147 | let win = f.window; |
| 148 | let (sw, sh) = ( |
| 149 | 2 * (win.left + win.right) as usize, |
| 150 | 2 * (win.top + win.bottom) as usize, |
| 151 | ); |
| 152 | let w = pic.width - sw; |
| 153 | let h = pic.height - sh; |
| 154 | let (x0, y0) = (2 * win.left as usize, 2 * win.top as usize); |
| 155 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 156 | let ccw = pic.width / 2; |
| 157 | let (cx0, cy0) = (x0 / 2, y0 / 2); |
| 158 | for (plane, pw, ph, ox, oy, stride) in [ |
| 159 | (&pic.y, w, h, x0, y0, pic.width), |
| 160 | (&pic.cb, cw, ch, cx0, cy0, ccw), |
| 161 | (&pic.cr, cw, ch, cx0, cy0, ccw), |
| 162 | ] { |
| 163 | let mut row_buf = Vec::with_capacity(pw); |
| 164 | for r in 0..ph { |
| 165 | row_buf.clear(); |
| 166 | row_buf.extend( |
| 167 | plane[(oy + r) * stride + ox..][..pw] |
| 168 | .iter() |
| 169 | .map(|&s| s as u8), |
| 170 | ); |
| 171 | out.write_all(&row_buf).map_err(|e| e.to_string())?; |
| 172 | } |
| 173 | } |
| 174 | *n += 1; |
| 175 | } |
| 176 | Ok(()) |
| 177 | }; |
| 178 | for au in access_units(&stream) { |
| 179 | dec.decode_annex_b(au).map_err(|e| e.to_string())?; |
| 180 | emit(&mut dec, &mut out, &mut n)?; |
| 181 | } |
| 182 | dec.flush().map_err(|e| e.to_string())?; |
| 183 | emit(&mut dec, &mut out, &mut n)?; |
| 184 | out.flush().map_err(|e| e.to_string())?; |
| 185 | println!("frames={n}"); |
| 186 | Ok(()) |
| 187 | } |
| 188 | |
| 189 | fn run() -> Result<(), String> { |
| 190 | let args: Vec<String> = std::env::args().collect(); |
| 191 | match args.get(1).map(String::as_str) { |
| 192 | Some("encode") => encode(&args), |
| 193 | Some("decode") => decode(&args), |
| 194 | other => Err(format!("unknown command {other:?}")), |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | fn main() -> ExitCode { |
| 199 | match run() { |
| 200 | Ok(()) => ExitCode::SUCCESS, |
| 201 | Err(e) => { |
| 202 | eprintln!("hevc_rc: {e}"); |
| 203 | ExitCode::FAILURE |
| 204 | } |
| 205 | } |
| 206 | } |