The project I'm currently working on involves capturing screen frames on Windows via the Desktop Duplication API
as raw BGRA format pixel data, and then encoding these frames into h264 format.
At this point, I have successfully created a video in the h264 format using the X264
crate. However, my next task is to mux the h264 frames into an mp4 file, and this is where I'm facing some difficulties. I am currently trying to utilize the ffmpeg-the-third
crate, an FFmpeg wrapper in Rust, to perform this task, but I am unsure how to proceed with it.
I'm seeking assistance on how to use the ffmpeg-the-third
crate or anything else that could allow me to convert the h264 video file to mp4 format. Specifically, I need help on how to implement the muxing process manually. Any guidance, examples, or resources that can guide me through this process would be greatly appreciated. Thank you!
Here is the code that I use to encode the captured frames into h264 via the x264
crate:
fn encode_frames(frames: Vec<Vec<u8>>, width: u32, height: u32, fps: u32) -> Result<()> {
let mut file = File::create("../vid/captured_video.h264").unwrap();
let mut encoder = Encoder::builder()
.fps(fps, 1)
.build(Colorspace::BGRA, width as _, height as _)
.unwrap();
{
let headers = encoder.headers().unwrap();
file.write_all(headers.entirety()).unwrap();
}
for (index, mut pic_data) in frames.into_iter().enumerate() {
let image = Image::bgra(width as _, height as _, &pic_data);
let (data, _) = encoder.encode((fps as usize * index) as _, image).unwrap();
file.write_all(data.entirety()).unwrap();
}
// Flush out delayed frames
{
let mut flush = encoder.flush();
while let Some(result) = flush.next() {
let (data, _) = result.unwrap();
file.write_all(data.entirety()).unwrap();
}
}
Ok(())
}
I did this once using the
minimp4
crate.In your case it should look something like that (untested):
I also have this simple self-contained demonstration for encoding images to a mp4 video (in memory):
with these dependencies:
Additional information on this topic can be found in this rustlang forum post.