|
| 1 | +//! Example: AV1 Video Encoding |
| 2 | +//! |
| 3 | +//! Demonstrates AV1 video encoding using PixelForge with Vulkan Video. |
| 4 | +//! Loads raw YUV420 frames from `testdata/test_frames.yuv`. |
| 5 | +
|
| 6 | +use pixelforge::{ |
| 7 | + Codec, EncodeBitDepth, EncodeConfig, Encoder, InputImage, PixelFormat, RateControlMode, |
| 8 | + VideoContextBuilder, |
| 9 | +}; |
| 10 | +use std::fs::File; |
| 11 | +use std::io::{Read, Write}; |
| 12 | +use std::path::Path; |
| 13 | +use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, Layer}; |
| 14 | + |
| 15 | +const TEST_FRAMES_PATH: &str = "testdata/test_frames.yuv"; |
| 16 | +const WIDTH: u32 = 320; |
| 17 | +const HEIGHT: u32 = 240; |
| 18 | + |
| 19 | +fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 20 | + // Initialize tracing with RUST_LOG support. |
| 21 | + tracing_subscriber::registry() |
| 22 | + .with( |
| 23 | + tracing_subscriber::fmt::layer().with_filter( |
| 24 | + tracing_subscriber::EnvFilter::try_from_default_env() |
| 25 | + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")), |
| 26 | + ), |
| 27 | + ) |
| 28 | + .init(); |
| 29 | + |
| 30 | + println!("PixelForge AV1 Encode Example\n"); |
| 31 | + |
| 32 | + // Load test frames. |
| 33 | + let test_path = Path::new(TEST_FRAMES_PATH); |
| 34 | + if !test_path.exists() { |
| 35 | + eprintln!("Test frames not found at '{TEST_FRAMES_PATH}'"); |
| 36 | + eprintln!("Generate with: ffmpeg -f lavfi -i testsrc=duration=0.5:size=320x240:rate=30 -pix_fmt yuv420p -f rawvideo testdata/test_frames.yuv"); |
| 37 | + return Ok(()); |
| 38 | + } |
| 39 | + |
| 40 | + let mut yuv_data = Vec::new(); |
| 41 | + File::open(test_path)?.read_to_end(&mut yuv_data)?; |
| 42 | + |
| 43 | + let frame_size = (WIDTH * HEIGHT * 3 / 2) as usize; |
| 44 | + let num_frames = yuv_data.len() / frame_size; |
| 45 | + println!( |
| 46 | + "Input: {num_frames} frames, {WIDTH}x{HEIGHT} YUV420, {} bytes", |
| 47 | + yuv_data.len() |
| 48 | + ); |
| 49 | + |
| 50 | + // Create video context. |
| 51 | + let context = VideoContextBuilder::new() |
| 52 | + .app_name("AV1 Encode Example") |
| 53 | + .enable_validation(cfg!(debug_assertions)) |
| 54 | + .require_encode(Codec::AV1) |
| 55 | + .build()?; |
| 56 | + |
| 57 | + if !context.supports_encode(Codec::AV1) { |
| 58 | + eprintln!("AV1 encode not supported"); |
| 59 | + return Ok(()); |
| 60 | + } |
| 61 | + |
| 62 | + // Configure encoder. |
| 63 | + let config = EncodeConfig::av1(WIDTH, HEIGHT) |
| 64 | + .with_rate_control(RateControlMode::Cqp) |
| 65 | + .with_quality_level(26) |
| 66 | + .with_frame_rate(30, 1) |
| 67 | + .with_gop_size(30) |
| 68 | + .with_b_frames(0); |
| 69 | + |
| 70 | + println!( |
| 71 | + "Config: {:?}, QP={}, GOP={}, B-frames={}\n", |
| 72 | + config.rate_control_mode, config.quality_level, config.gop_size, config.b_frame_count |
| 73 | + ); |
| 74 | + |
| 75 | + // Create input image for uploading frames. |
| 76 | + let mut input_image = InputImage::new( |
| 77 | + context.clone(), |
| 78 | + Codec::AV1, |
| 79 | + WIDTH, |
| 80 | + HEIGHT, |
| 81 | + EncodeBitDepth::Eight, |
| 82 | + PixelFormat::Yuv420, |
| 83 | + )?; |
| 84 | + let mut encoder = Encoder::new(context, config)?; |
| 85 | + let mut output = File::create("output.av1")?; |
| 86 | + let mut total_bytes = 0; |
| 87 | + |
| 88 | + // Encode frames. |
| 89 | + for i in 0..num_frames { |
| 90 | + let frame = &yuv_data[i * frame_size..(i + 1) * frame_size]; |
| 91 | + |
| 92 | + // Upload YUV420 data to the input image. |
| 93 | + input_image.upload_yuv420(frame)?; |
| 94 | + |
| 95 | + // Encode the image (passing InputImage's image, which triggers |
| 96 | + // an internal copy to the encoder's input image with proper |
| 97 | + // layout transitions). |
| 98 | + for packet in encoder.encode(input_image.image())? { |
| 99 | + total_bytes += packet.data.len(); |
| 100 | + output.write_all(&packet.data)?; |
| 101 | + println!( |
| 102 | + " pts={:<2} dts={:<2}: {:>5} bytes, {:?}{}", |
| 103 | + packet.pts, |
| 104 | + packet.dts, |
| 105 | + packet.data.len(), |
| 106 | + packet.frame_type, |
| 107 | + if packet.is_key_frame { " [KEY]" } else { "" } |
| 108 | + ); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + // Flush remaining frames. |
| 113 | + for packet in encoder.flush()? { |
| 114 | + total_bytes += packet.data.len(); |
| 115 | + output.write_all(&packet.data)?; |
| 116 | + println!( |
| 117 | + " pts={:<2} dts={:<2}: {:>5} bytes, {:?} (flushed)", |
| 118 | + packet.pts, |
| 119 | + packet.dts, |
| 120 | + packet.data.len(), |
| 121 | + packet.frame_type |
| 122 | + ); |
| 123 | + } |
| 124 | + |
| 125 | + let ratio = (num_frames * frame_size) as f64 / total_bytes as f64; |
| 126 | + println!("\nEncoded {num_frames} frames, {total_bytes} bytes, {ratio:.1}:1 compression"); |
| 127 | + println!("Output: output.av1"); |
| 128 | + |
| 129 | + Ok(()) |
| 130 | +} |
0 commit comments