remux/
remux.rs

1extern crate ffmpeg_next as ffmpeg;
2
3use std::env;
4
5use ffmpeg::{codec, encoder, format, log, media, Rational};
6
7fn main() {
8    let input_file = env::args().nth(1).expect("missing input file");
9    let output_file = env::args().nth(2).expect("missing output file");
10
11    ffmpeg::init().unwrap();
12    log::set_level(log::Level::Warning);
13
14    let mut ictx = format::input(&input_file).unwrap();
15    let mut octx = format::output(&output_file).unwrap();
16
17    let mut stream_mapping = vec![0; ictx.nb_streams() as _];
18    let mut ist_time_bases = vec![Rational(0, 1); ictx.nb_streams() as _];
19    let mut ost_index = 0;
20    for (ist_index, ist) in ictx.streams().enumerate() {
21        let ist_medium = ist.parameters().medium();
22        if ist_medium != media::Type::Audio
23            && ist_medium != media::Type::Video
24            && ist_medium != media::Type::Subtitle
25        {
26            stream_mapping[ist_index] = -1;
27            continue;
28        }
29        stream_mapping[ist_index] = ost_index;
30        ist_time_bases[ist_index] = ist.time_base();
31        ost_index += 1;
32        let mut ost = octx.add_stream(encoder::find(codec::Id::None)).unwrap();
33        ost.set_parameters(ist.parameters());
34        // We need to set codec_tag to 0 lest we run into incompatible codec tag
35        // issues when muxing into a different container format. Unfortunately
36        // there's no high level API to do this (yet).
37        unsafe {
38            (*ost.parameters().as_mut_ptr()).codec_tag = 0;
39        }
40    }
41
42    octx.set_metadata(ictx.metadata().to_owned());
43    octx.write_header().unwrap();
44
45    for (stream, mut packet) in ictx.packets() {
46        let ist_index = stream.index();
47        let ost_index = stream_mapping[ist_index];
48        if ost_index < 0 {
49            continue;
50        }
51        let ost = octx.stream(ost_index as _).unwrap();
52        packet.rescale_ts(ist_time_bases[ist_index], ost.time_base());
53        packet.set_position(-1);
54        packet.set_stream(ost_index as _);
55        packet.write_interleaved(&mut octx).unwrap();
56    }
57
58    octx.write_trailer().unwrap();
59}