|
| 1 | +use crate::{SCREEN_FRAME_RATE, SCREEN_HEIGHT, SCREEN_SCALE, SCREEN_WIDTH}; |
| 2 | +use fast_image_resize as fr; |
| 3 | +use image::RgbImage; |
| 4 | +use ndarray::Array3; |
| 5 | +use std::num::NonZeroU32; |
| 6 | +use video_rs::{Encoder, Time}; |
| 7 | + |
| 8 | +pub struct Encoding { |
| 9 | + pub encoder: Encoder, |
| 10 | + pub position: Time, |
| 11 | + pub frame_duration: Time, |
| 12 | + pub resizer: fr::Resizer, |
| 13 | + pub size_src: (NonZeroU32, NonZeroU32), |
| 14 | + pub size_dst: (NonZeroU32, NonZeroU32), |
| 15 | +} |
| 16 | + |
| 17 | +impl Encoding { |
| 18 | + pub fn new(encoder: Encoder) -> Self { |
| 19 | + Encoding { |
| 20 | + encoder, |
| 21 | + position: Time::zero(), |
| 22 | + frame_duration: Time::from_nth_of_a_second(*SCREEN_FRAME_RATE), |
| 23 | + size_src: ( |
| 24 | + NonZeroU32::new(*SCREEN_WIDTH).unwrap(), |
| 25 | + NonZeroU32::new(*SCREEN_HEIGHT).unwrap(), |
| 26 | + ), |
| 27 | + size_dst: ( |
| 28 | + NonZeroU32::new(*SCREEN_WIDTH * *SCREEN_SCALE).unwrap(), |
| 29 | + NonZeroU32::new(*SCREEN_HEIGHT * *SCREEN_SCALE).unwrap(), |
| 30 | + ), |
| 31 | + resizer: fr::Resizer::new(fr::ResizeAlg::Nearest), |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + pub fn resize_frame(&mut self, frame: &mut RgbImage) -> Vec<u8> { |
| 36 | + if *SCREEN_SCALE == 1 { |
| 37 | + return frame.as_raw().to_vec(); |
| 38 | + } |
| 39 | + |
| 40 | + let src_image = |
| 41 | + fr::Image::from_slice_u8(self.size_src.0, self.size_src.1, frame, fr::PixelType::U8x3) |
| 42 | + .unwrap(); |
| 43 | + |
| 44 | + let mut dst_image = fr::Image::new(self.size_dst.0, self.size_dst.1, fr::PixelType::U8x3); |
| 45 | + |
| 46 | + // Get mutable view of destination image data |
| 47 | + let mut dst_view = dst_image.view_mut(); |
| 48 | + self.resizer |
| 49 | + .resize(&src_image.view(), &mut dst_view) |
| 50 | + .unwrap(); |
| 51 | + |
| 52 | + dst_image.buffer().to_vec() |
| 53 | + } |
| 54 | + |
| 55 | + pub fn render_frame(&mut self, frame: &mut RgbImage) { |
| 56 | + let pixels = self.resize_frame(frame); |
| 57 | + let ef: Array3<u8> = ndarray::Array3::from_shape_vec( |
| 58 | + ( |
| 59 | + self.size_dst.1.get() as usize, |
| 60 | + self.size_dst.0.get() as usize, |
| 61 | + 3, |
| 62 | + ), |
| 63 | + pixels, |
| 64 | + ) |
| 65 | + .unwrap(); |
| 66 | + |
| 67 | + self.encoder.encode(&ef, &self.position).unwrap(); |
| 68 | + self.update_position(); |
| 69 | + } |
| 70 | + |
| 71 | + pub fn update_position(&mut self) { |
| 72 | + self.position = self.position.aligned_with(&self.frame_duration).add(); |
| 73 | + } |
| 74 | + |
| 75 | + pub fn flush(&mut self) { |
| 76 | + self.encoder.finish().unwrap(); |
| 77 | + } |
| 78 | +} |
0 commit comments