init

Function init 

Source
pub fn init() -> Result<(), Error>
Examples found in repository?
examples/transcode-audio.rs (line 209)
208fn main() {
209    ffmpeg::init().unwrap();
210
211    let input = env::args().nth(1).expect("missing input");
212    let output = env::args().nth(2).expect("missing output");
213    let filter = env::args().nth(3).unwrap_or_else(|| "anull".to_owned());
214    let seek = env::args().nth(4).and_then(|s| s.parse::<i64>().ok());
215
216    let mut ictx = format::input(&input).unwrap();
217    let mut octx = format::output(&output).unwrap();
218    let mut transcoder = transcoder(&mut ictx, &mut octx, &output, &filter).unwrap();
219
220    if let Some(position) = seek {
221        // If the position was given in seconds, rescale it to ffmpegs base timebase.
222        let position = position.rescale((1, 1), rescale::TIME_BASE);
223        // If this seek was embedded in the transcoding loop, a call of `flush()`
224        // for every opened buffer after the successful seek would be advisable.
225        ictx.seek(position, ..position).unwrap();
226    }
227
228    octx.set_metadata(ictx.metadata().to_owned());
229    octx.write_header().unwrap();
230
231    for (stream, mut packet) in ictx.packets() {
232        if stream.index() == transcoder.stream {
233            packet.rescale_ts(stream.time_base(), transcoder.in_time_base);
234            transcoder.send_packet_to_decoder(&packet);
235            transcoder.receive_and_process_decoded_frames(&mut octx);
236        }
237    }
238
239    transcoder.send_eof_to_decoder();
240    transcoder.receive_and_process_decoded_frames(&mut octx);
241
242    transcoder.flush_filter();
243    transcoder.get_and_process_filtered_frames(&mut octx);
244
245    transcoder.send_eof_to_encoder();
246    transcoder.receive_and_process_encoded_packets(&mut octx);
247
248    octx.write_trailer().unwrap();
249}
More examples
Hide additional examples
examples/dump-frames.rs (line 12)
11fn main() -> Result<(), ffmpeg::Error> {
12    ffmpeg::init().unwrap();
13
14    if let Ok(mut ictx) = input(&env::args().nth(1).expect("Cannot open file.")) {
15        let input = ictx
16            .streams()
17            .best(Type::Video)
18            .ok_or(ffmpeg::Error::StreamNotFound)?;
19        let video_stream_index = input.index();
20
21        let context_decoder = ffmpeg::codec::context::Context::from_parameters(input.parameters())?;
22        let mut decoder = context_decoder.decoder().video()?;
23
24        let mut scaler = Context::get(
25            decoder.format(),
26            decoder.width(),
27            decoder.height(),
28            Pixel::RGB24,
29            decoder.width(),
30            decoder.height(),
31            Flags::BILINEAR,
32        )?;
33
34        let mut frame_index = 0;
35
36        let mut receive_and_process_decoded_frames =
37            |decoder: &mut ffmpeg::decoder::Video| -> Result<(), ffmpeg::Error> {
38                let mut decoded = Video::empty();
39                while decoder.receive_frame(&mut decoded).is_ok() {
40                    let mut rgb_frame = Video::empty();
41                    scaler.run(&decoded, &mut rgb_frame)?;
42                    save_file(&rgb_frame, frame_index).unwrap();
43                    frame_index += 1;
44                }
45                Ok(())
46            };
47
48        for (stream, packet) in ictx.packets() {
49            if stream.index() == video_stream_index {
50                decoder.send_packet(&packet)?;
51                receive_and_process_decoded_frames(&mut decoder)?;
52            }
53        }
54        decoder.send_eof()?;
55        receive_and_process_decoded_frames(&mut decoder)?;
56    }
57
58    Ok(())
59}
examples/remux.rs (line 11)
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}
examples/chapters.rs (line 6)
5fn main() {
6    ffmpeg::init().unwrap();
7
8    match ffmpeg::format::input(&env::args().nth(1).expect("missing input file name")) {
9        Ok(ictx) => {
10            println!("Nb chapters: {}", ictx.nb_chapters());
11
12            for chapter in ictx.chapters() {
13                println!("chapter id {}:", chapter.id());
14                println!("\ttime_base: {}", chapter.time_base());
15                println!("\tstart: {}", chapter.start());
16                println!("\tend: {}", chapter.end());
17
18                for (k, v) in chapter.metadata().iter() {
19                    println!("\t{}: {}", k, v);
20                }
21            }
22
23            let mut octx = ffmpeg::format::output(&"test.mkv").expect("Couldn't open test file");
24
25            for chapter in ictx.chapters() {
26                let title = match chapter.metadata().get("title") {
27                    Some(title) => String::from(title),
28                    None => String::new(),
29                };
30
31                match octx.add_chapter(
32                    chapter.id(),
33                    chapter.time_base(),
34                    chapter.start(),
35                    chapter.end(),
36                    &title,
37                ) {
38                    Ok(chapter) => println!("Added chapter with id {} to output", chapter.id()),
39                    Err(error) => {
40                        println!("Error adding chapter with id: {} - {}", chapter.id(), error)
41                    }
42                }
43            }
44
45            println!("\nOuput: nb chapters: {}", octx.nb_chapters());
46            for chapter in octx.chapters() {
47                println!("chapter id {}:", chapter.id());
48                println!("\ttime_base: {}", chapter.time_base());
49                println!("\tstart: {}", chapter.start());
50                println!("\tend: {}", chapter.end());
51                for (k, v) in chapter.metadata().iter() {
52                    println!("\t{}: {}", k, v);
53                }
54            }
55        }
56
57        Err(error) => println!("error: {}", error),
58    }
59}
examples/codec-info.rs (line 6)
5fn main() {
6    ffmpeg::init().unwrap();
7
8    for arg in env::args().skip(1) {
9        if let Some(codec) = ffmpeg::decoder::find_by_name(&arg) {
10            println!("type: decoder");
11            println!("\t id: {:?}", codec.id());
12            println!("\t name: {}", codec.name());
13            println!("\t description: {}", codec.description());
14            println!("\t medium: {:?}", codec.medium());
15            println!("\t capabilities: {:?}", codec.capabilities());
16
17            if let Some(profiles) = codec.profiles() {
18                println!("\t profiles: {:?}", profiles.collect::<Vec<_>>());
19            } else {
20                println!("\t profiles: none");
21            }
22
23            if let Ok(video) = codec.video() {
24                if let Some(rates) = video.rates() {
25                    println!("\t rates: {:?}", rates.collect::<Vec<_>>());
26                } else {
27                    println!("\t rates: any");
28                }
29
30                if let Some(formats) = video.formats() {
31                    println!("\t formats: {:?}", formats.collect::<Vec<_>>());
32                } else {
33                    println!("\t formats: any");
34                }
35            }
36
37            if let Ok(audio) = codec.audio() {
38                if let Some(rates) = audio.rates() {
39                    println!("\t rates: {:?}", rates.collect::<Vec<_>>());
40                } else {
41                    println!("\t rates: any");
42                }
43
44                if let Some(formats) = audio.formats() {
45                    println!("\t formats: {:?}", formats.collect::<Vec<_>>());
46                } else {
47                    println!("\t formats: any");
48                }
49
50                if let Some(layouts) = audio.channel_layouts() {
51                    println!("\t channel_layouts: {:?}", layouts.collect::<Vec<_>>());
52                } else {
53                    println!("\t channel_layouts: any");
54                }
55            }
56
57            println!("\t max_lowres: {:?}", codec.max_lowres());
58        }
59
60        if let Some(codec) = ffmpeg::encoder::find_by_name(&arg) {
61            println!();
62            println!("type: encoder");
63            println!("\t id: {:?}", codec.id());
64            println!("\t name: {}", codec.name());
65            println!("\t description: {}", codec.description());
66            println!("\t medium: {:?}", codec.medium());
67            println!("\t capabilities: {:?}", codec.capabilities());
68
69            if let Some(profiles) = codec.profiles() {
70                println!("\t profiles: {:?}", profiles.collect::<Vec<_>>());
71            }
72
73            if let Ok(video) = codec.video() {
74                if let Some(rates) = video.rates() {
75                    println!("\t rates: {:?}", rates.collect::<Vec<_>>());
76                } else {
77                    println!("\t rates: any");
78                }
79
80                if let Some(formats) = video.formats() {
81                    println!("\t formats: {:?}", formats.collect::<Vec<_>>());
82                } else {
83                    println!("\t formats: any");
84                }
85            }
86
87            if let Ok(audio) = codec.audio() {
88                if let Some(rates) = audio.rates() {
89                    println!("\t rates: {:?}", rates.collect::<Vec<_>>());
90                } else {
91                    println!("\t rates: any");
92                }
93
94                if let Some(formats) = audio.formats() {
95                    println!("\t formats: {:?}", formats.collect::<Vec<_>>());
96                } else {
97                    println!("\t formats: any");
98                }
99
100                if let Some(layouts) = audio.channel_layouts() {
101                    println!("\t channel_layouts: {:?}", layouts.collect::<Vec<_>>());
102                } else {
103                    println!("\t channel_layouts: any");
104                }
105            }
106
107            println!("\t max_lowres: {:?}", codec.max_lowres());
108        }
109    }
110}
examples/transcode-x264.rs (line 181)
169fn main() {
170    let input_file = env::args().nth(1).expect("missing input file");
171    let output_file = env::args().nth(2).expect("missing output file");
172    let x264_opts = parse_opts(
173        env::args()
174            .nth(3)
175            .unwrap_or_else(|| DEFAULT_X264_OPTS.to_string()),
176    )
177    .expect("invalid x264 options string");
178
179    eprintln!("x264 options: {:?}", x264_opts);
180
181    ffmpeg::init().unwrap();
182    log::set_level(log::Level::Info);
183
184    let mut ictx = format::input(&input_file).unwrap();
185    let mut octx = format::output(&output_file).unwrap();
186
187    format::context::input::dump(&ictx, 0, Some(&input_file));
188
189    let best_video_stream_index = ictx
190        .streams()
191        .best(media::Type::Video)
192        .map(|stream| stream.index());
193    let mut stream_mapping: Vec<isize> = vec![0; ictx.nb_streams() as _];
194    let mut ist_time_bases = vec![Rational(0, 0); ictx.nb_streams() as _];
195    let mut ost_time_bases = vec![Rational(0, 0); ictx.nb_streams() as _];
196    let mut transcoders = HashMap::new();
197    let mut ost_index = 0;
198    for (ist_index, ist) in ictx.streams().enumerate() {
199        let ist_medium = ist.parameters().medium();
200        if ist_medium != media::Type::Audio
201            && ist_medium != media::Type::Video
202            && ist_medium != media::Type::Subtitle
203        {
204            stream_mapping[ist_index] = -1;
205            continue;
206        }
207        stream_mapping[ist_index] = ost_index;
208        ist_time_bases[ist_index] = ist.time_base();
209        if ist_medium == media::Type::Video {
210            // Initialize transcoder for video stream.
211            transcoders.insert(
212                ist_index,
213                Transcoder::new(
214                    &ist,
215                    &mut octx,
216                    ost_index as _,
217                    x264_opts.to_owned(),
218                    Some(ist_index) == best_video_stream_index,
219                )
220                .unwrap(),
221            );
222        } else {
223            // Set up for stream copy for non-video stream.
224            let mut ost = octx.add_stream(encoder::find(codec::Id::None)).unwrap();
225            ost.set_parameters(ist.parameters());
226            // We need to set codec_tag to 0 lest we run into incompatible codec tag
227            // issues when muxing into a different container format. Unfortunately
228            // there's no high level API to do this (yet).
229            unsafe {
230                (*ost.parameters().as_mut_ptr()).codec_tag = 0;
231            }
232        }
233        ost_index += 1;
234    }
235
236    octx.set_metadata(ictx.metadata().to_owned());
237    format::context::output::dump(&octx, 0, Some(&output_file));
238    octx.write_header().unwrap();
239
240    for (ost_index, _) in octx.streams().enumerate() {
241        ost_time_bases[ost_index] = octx.stream(ost_index as _).unwrap().time_base();
242    }
243
244    for (stream, mut packet) in ictx.packets() {
245        let ist_index = stream.index();
246        let ost_index = stream_mapping[ist_index];
247        if ost_index < 0 {
248            continue;
249        }
250        let ost_time_base = ost_time_bases[ost_index as usize];
251        match transcoders.get_mut(&ist_index) {
252            Some(transcoder) => {
253                transcoder.send_packet_to_decoder(&packet);
254                transcoder.receive_and_process_decoded_frames(&mut octx, ost_time_base);
255            }
256            None => {
257                // Do stream copy on non-video streams.
258                packet.rescale_ts(ist_time_bases[ist_index], ost_time_base);
259                packet.set_position(-1);
260                packet.set_stream(ost_index as _);
261                packet.write_interleaved(&mut octx).unwrap();
262            }
263        }
264    }
265
266    // Flush encoders and decoders.
267    for (ost_index, transcoder) in transcoders.iter_mut() {
268        let ost_time_base = ost_time_bases[*ost_index];
269        transcoder.send_eof_to_decoder();
270        transcoder.receive_and_process_decoded_frames(&mut octx, ost_time_base);
271        transcoder.send_eof_to_encoder();
272        transcoder.receive_and_process_encoded_packets(&mut octx, ost_time_base);
273    }
274
275    octx.write_trailer().unwrap();
276}