*: format code with rustfmt and fix clippy suggestions

* Add avformat_close_input call to clean up AVFormantContext
* Format code with rustfmt
* Fix clippy lint double_parens
* Fix clippy lint deref_addrof
* Fix clippy lint identity_conversion
* Fix clippy lint match_ref_pats
* Fix clippy lint cast_lossless
* Fix clippy lint cmp_null
* Fix clippy lint clone_on_ref_ptr
* Fix clippy lint map_clone
* Fix clippy lint needless_borrow
* Fix clippy lint needless_pass_by_value
* Fix clippy lints for examples
* Fix clippy lint unused_io_amount
* Fix clippy lint new_without_default
* Ignore inline_always clippy lint
* Add vim temp files to .gitignore
This commit is contained in:
Tadas Barzdžius 2018-04-10 17:06:42 +03:00 committed by meh
parent 20c7ef399a
commit 0bcd4550b8
128 changed files with 10643 additions and 10233 deletions

6
.gitignore vendored
View File

@ -1,2 +1,8 @@
# Rust files
target target
Cargo.lock Cargo.lock
# Vim temporary files
*.swp
*.swo
*.swn

View File

@ -3,8 +3,10 @@ use std::env;
fn main() { fn main() {
for (name, _value) in env::vars() { for (name, _value) in env::vars() {
if name.starts_with("DEP_FFMPEG_") { if name.starts_with("DEP_FFMPEG_") {
println!(r#"cargo:rustc-cfg=feature="{}""#, println!(
name["DEP_FFMPEG_".len() .. name.len()].to_lowercase()); r#"cargo:rustc-cfg=feature="{}""#,
name["DEP_FFMPEG_".len()..name.len()].to_lowercase()
);
} }
} }
} }

View File

@ -20,7 +20,8 @@ fn main() {
} }
} }
let mut octx = ffmpeg::format::output(&"test.mkv".to_owned()).expect(&format!("Couldn't open test file")); let mut octx =
ffmpeg::format::output(&"test.mkv".to_owned()).expect("Couldn't open test file");
for chapter in ictx.chapters() { for chapter in ictx.chapters() {
let title = match chapter.metadata().get("title") { let title = match chapter.metadata().get("title") {
@ -28,9 +29,17 @@ fn main() {
None => String::new(), None => String::new(),
}; };
match octx.add_chapter(chapter.id(), chapter.time_base(), chapter.start(), chapter.end(), &title) { match octx.add_chapter(
chapter.id(),
chapter.time_base(),
chapter.start(),
chapter.end(),
&title,
) {
Ok(chapter) => println!("Added chapter with id {} to output", chapter.id()), Ok(chapter) => println!("Added chapter with id {} to output", chapter.id()),
Err(error) => println!("Error adding chapter with id: {} - {}", chapter.id(), error), Err(error) => {
println!("Error adding chapter with id: {} - {}", chapter.id(), error)
}
} }
} }
@ -46,7 +55,6 @@ fn main() {
} }
} }
Err(error) => Err(error) => println!("error: {}", error),
println!("error: {}", error)
} }
} }

View File

@ -16,23 +16,20 @@ fn main() {
if let Some(profiles) = codec.profiles() { if let Some(profiles) = codec.profiles() {
println!("\t profiles: {:?}", profiles.collect::<Vec<_>>()); println!("\t profiles: {:?}", profiles.collect::<Vec<_>>());
} } else {
else {
println!("\t profiles: none"); println!("\t profiles: none");
} }
if let Ok(video) = codec.video() { if let Ok(video) = codec.video() {
if let Some(rates) = video.rates() { if let Some(rates) = video.rates() {
println!("\t rates: {:?}", rates.collect::<Vec<_>>()); println!("\t rates: {:?}", rates.collect::<Vec<_>>());
} } else {
else {
println!("\t rates: any"); println!("\t rates: any");
} }
if let Some(formats) = video.formats() { if let Some(formats) = video.formats() {
println!("\t formats: {:?}", formats.collect::<Vec<_>>()); println!("\t formats: {:?}", formats.collect::<Vec<_>>());
} } else {
else {
println!("\t formats: any"); println!("\t formats: any");
} }
} }
@ -40,22 +37,19 @@ fn main() {
if let Ok(audio) = codec.audio() { if let Ok(audio) = codec.audio() {
if let Some(rates) = audio.rates() { if let Some(rates) = audio.rates() {
println!("\t rates: {:?}", rates.collect::<Vec<_>>()); println!("\t rates: {:?}", rates.collect::<Vec<_>>());
} } else {
else {
println!("\t rates: any"); println!("\t rates: any");
} }
if let Some(formats) = audio.formats() { if let Some(formats) = audio.formats() {
println!("\t formats: {:?}", formats.collect::<Vec<_>>()); println!("\t formats: {:?}", formats.collect::<Vec<_>>());
} } else {
else {
println!("\t formats: any"); println!("\t formats: any");
} }
if let Some(layouts) = audio.channel_layouts() { if let Some(layouts) = audio.channel_layouts() {
println!("\t channel_layouts: {:?}", layouts.collect::<Vec<_>>()); println!("\t channel_layouts: {:?}", layouts.collect::<Vec<_>>());
} } else {
else {
println!("\t channel_layouts: any"); println!("\t channel_layouts: any");
} }
} }
@ -64,7 +58,7 @@ fn main() {
} }
if let Some(codec) = ffmpeg::encoder::find_by_name(&arg) { if let Some(codec) = ffmpeg::encoder::find_by_name(&arg) {
println!(""); println!();
println!("type: encoder"); println!("type: encoder");
println!("\t id: {:?}", codec.id()); println!("\t id: {:?}", codec.id());
println!("\t name: {}", codec.name()); println!("\t name: {}", codec.name());
@ -79,15 +73,13 @@ fn main() {
if let Ok(video) = codec.video() { if let Ok(video) = codec.video() {
if let Some(rates) = video.rates() { if let Some(rates) = video.rates() {
println!("\t rates: {:?}", rates.collect::<Vec<_>>()); println!("\t rates: {:?}", rates.collect::<Vec<_>>());
} } else {
else {
println!("\t rates: any"); println!("\t rates: any");
} }
if let Some(formats) = video.formats() { if let Some(formats) = video.formats() {
println!("\t formats: {:?}", formats.collect::<Vec<_>>()); println!("\t formats: {:?}", formats.collect::<Vec<_>>());
} } else {
else {
println!("\t formats: any"); println!("\t formats: any");
} }
} }
@ -95,22 +87,19 @@ fn main() {
if let Ok(audio) = codec.audio() { if let Ok(audio) = codec.audio() {
if let Some(rates) = audio.rates() { if let Some(rates) = audio.rates() {
println!("\t rates: {:?}", rates.collect::<Vec<_>>()); println!("\t rates: {:?}", rates.collect::<Vec<_>>());
} } else {
else {
println!("\t rates: any"); println!("\t rates: any");
} }
if let Some(formats) = audio.formats() { if let Some(formats) = audio.formats() {
println!("\t formats: {:?}", formats.collect::<Vec<_>>()); println!("\t formats: {:?}", formats.collect::<Vec<_>>());
} } else {
else {
println!("\t formats: any"); println!("\t formats: any");
} }
if let Some(layouts) = audio.channel_layouts() { if let Some(layouts) = audio.channel_layouts() {
println!("\t channel_layouts: {:?}", layouts.collect::<Vec<_>>()); println!("\t channel_layouts: {:?}", layouts.collect::<Vec<_>>());
} } else {
else {
println!("\t channel_layouts: any"); println!("\t channel_layouts: any");
} }
} }

View File

@ -23,14 +23,20 @@ fn main() {
println!("Best subtitle stream index: {}", stream.index()); println!("Best subtitle stream index: {}", stream.index());
} }
println!("duration (seconds): {:.2}", context.duration() as f64 / ffmpeg::ffi::AV_TIME_BASE as f64); println!(
"duration (seconds): {:.2}",
context.duration() as f64 / f64::from(ffmpeg::ffi::AV_TIME_BASE)
);
for stream in context.streams() { for stream in context.streams() {
println!("stream index {}:", stream.index()); println!("stream index {}:", stream.index());
println!("\ttime_base: {}", stream.time_base()); println!("\ttime_base: {}", stream.time_base());
println!("\tstart_time: {}", stream.start_time()); println!("\tstart_time: {}", stream.start_time());
println!("\tduration (stream timebase): {}", stream.duration()); println!("\tduration (stream timebase): {}", stream.duration());
println!("\tduration (seconds): {:.2}", stream.duration() as f64 * f64::from(stream.time_base())); println!(
"\tduration (seconds): {:.2}",
stream.duration() as f64 * f64::from(stream.time_base())
);
println!("\tframes: {}", stream.frames()); println!("\tframes: {}", stream.frames());
println!("\tdisposition: {:?}", stream.disposition()); println!("\tdisposition: {:?}", stream.disposition());
println!("\tdiscard: {:?}", stream.discard()); println!("\tdiscard: {:?}", stream.discard());
@ -53,13 +59,15 @@ fn main() {
println!("\tvideo.color_space: {:?}", video.color_space()); println!("\tvideo.color_space: {:?}", video.color_space());
println!("\tvideo.color_range: {:?}", video.color_range()); println!("\tvideo.color_range: {:?}", video.color_range());
println!("\tvideo.color_primaries: {:?}", video.color_primaries()); println!("\tvideo.color_primaries: {:?}", video.color_primaries());
println!("\tvideo.color_transfer_characteristic: {:?}", video.color_transfer_characteristic()); println!(
"\tvideo.color_transfer_characteristic: {:?}",
video.color_transfer_characteristic()
);
println!("\tvideo.chroma_location: {:?}", video.chroma_location()); println!("\tvideo.chroma_location: {:?}", video.chroma_location());
println!("\tvideo.references: {}", video.references()); println!("\tvideo.references: {}", video.references());
println!("\tvideo.intra_dc_precision: {}", video.intra_dc_precision()); println!("\tvideo.intra_dc_precision: {}", video.intra_dc_precision());
} }
} } else if codec.medium() == ffmpeg::media::Type::Audio {
else if codec.medium() == ffmpeg::media::Type::Audio {
if let Ok(audio) = codec.decoder().audio() { if let Ok(audio) = codec.decoder().audio() {
println!("\tbit_rate: {}", audio.bit_rate()); println!("\tbit_rate: {}", audio.bit_rate());
println!("\tmax_rate: {}", audio.max_bit_rate()); println!("\tmax_rate: {}", audio.max_bit_rate());
@ -74,10 +82,8 @@ fn main() {
} }
} }
} }
} }
Err(error) => Err(error) => println!("error: {}", error),
println!("error: {}", error)
} }
} }

View File

@ -3,17 +3,26 @@ extern crate ffmpeg;
use std::env; use std::env;
use std::path::Path; use std::path::Path;
use ffmpeg::{format, codec, frame, media, filter}; use ffmpeg::{codec, filter, format, frame, media};
use ffmpeg::{rescale, Rescale}; use ffmpeg::{rescale, Rescale};
fn filter(spec: &str, decoder: &codec::decoder::Audio, encoder: &codec::encoder::Audio) -> Result<filter::Graph, ffmpeg::Error> { fn filter(
spec: &str,
decoder: &codec::decoder::Audio,
encoder: &codec::encoder::Audio,
) -> Result<filter::Graph, ffmpeg::Error> {
let mut filter = filter::Graph::new(); let mut filter = filter::Graph::new();
let args = format!("time_base={}:sample_rate={}:sample_fmt={}:channel_layout=0x{:x}", let args = format!(
decoder.time_base(), decoder.rate(), decoder.format().name(), decoder.channel_layout().bits()); "time_base={}:sample_rate={}:sample_fmt={}:channel_layout=0x{:x}",
decoder.time_base(),
decoder.rate(),
decoder.format().name(),
decoder.channel_layout().bits()
);
try!(filter.add(&filter::find("abuffer").unwrap(), "in", &args)); filter.add(&filter::find("abuffer").unwrap(), "in", &args)?;
try!(filter.add(&filter::find("abuffersink").unwrap(), "out", "")); filter.add(&filter::find("abuffersink").unwrap(), "out", "")?;
{ {
let mut out = filter.get("out").unwrap(); let mut out = filter.get("out").unwrap();
@ -23,14 +32,21 @@ fn filter(spec: &str, decoder: &codec::decoder::Audio, encoder: &codec::encoder:
out.set_sample_rate(encoder.rate()); out.set_sample_rate(encoder.rate());
} }
try!(try!(try!(filter.output("in", 0)).input("out", 0)).parse(spec)); filter.output("in", 0)?.input("out", 0)?.parse(spec)?;
try!(filter.validate()); filter.validate()?;
println!("{}", filter.dump()); println!("{}", filter.dump());
if let Some(codec) = encoder.codec() { if let Some(codec) = encoder.codec() {
if !codec.capabilities().contains(ffmpeg::codec::capabilities::VARIABLE_FRAME_SIZE) { if !codec
filter.get("out").unwrap().sink().set_frame_size(encoder.frame_size()); .capabilities()
.contains(ffmpeg::codec::capabilities::VARIABLE_FRAME_SIZE)
{
filter
.get("out")
.unwrap()
.sink()
.set_frame_size(encoder.frame_size());
} }
} }
@ -44,18 +60,30 @@ struct Transcoder {
encoder: codec::encoder::Audio, encoder: codec::encoder::Audio,
} }
fn transcoder<P: AsRef<Path>>(ictx: &mut format::context::Input, octx: &mut format::context::Output, path: &P, filter_spec: &str) -> Result<Transcoder, ffmpeg::Error> { fn transcoder<P: AsRef<Path>>(
let input = ictx.streams().best(media::Type::Audio).expect("could not find best audio stream"); ictx: &mut format::context::Input,
let mut decoder = try!(input.codec().decoder().audio()); octx: &mut format::context::Output,
let codec = try!(ffmpeg::encoder::find(octx.format().codec(path, media::Type::Audio)).expect("failed to find encoder").audio()); path: &P,
let global = octx.format().flags().contains(ffmpeg::format::flag::GLOBAL_HEADER); filter_spec: &str,
) -> Result<Transcoder, ffmpeg::Error> {
let input = ictx.streams()
.best(media::Type::Audio)
.expect("could not find best audio stream");
let mut decoder = input.codec().decoder().audio()?;
let codec = ffmpeg::encoder::find(octx.format().codec(path, media::Type::Audio))
.expect("failed to find encoder")
.audio()?;
let global = octx.format()
.flags()
.contains(ffmpeg::format::flag::GLOBAL_HEADER);
try!(decoder.set_parameters(input.parameters())); decoder.set_parameters(input.parameters())?;
let mut output = try!(octx.add_stream(codec)); let mut output = octx.add_stream(codec)?;
let mut encoder = try!(output.codec().encoder().audio()); let mut encoder = output.codec().encoder().audio()?;
let channel_layout = codec.channel_layouts() let channel_layout = codec
.channel_layouts()
.map(|cls| cls.best(decoder.channel_layout().channels())) .map(|cls| cls.best(decoder.channel_layout().channels()))
.unwrap_or(ffmpeg::channel_layout::STEREO); .unwrap_or(ffmpeg::channel_layout::STEREO);
@ -66,17 +94,23 @@ fn transcoder<P: AsRef<Path>>(ictx: &mut format::context::Input, octx: &mut form
encoder.set_rate(decoder.rate() as i32); encoder.set_rate(decoder.rate() as i32);
encoder.set_channel_layout(channel_layout); encoder.set_channel_layout(channel_layout);
encoder.set_channels(channel_layout.channels()); encoder.set_channels(channel_layout.channels());
encoder.set_format(codec.formats().expect("unknown supported formats").next().unwrap()); encoder.set_format(
codec
.formats()
.expect("unknown supported formats")
.next()
.unwrap(),
);
encoder.set_bit_rate(decoder.bit_rate()); encoder.set_bit_rate(decoder.bit_rate());
encoder.set_max_bit_rate(decoder.max_bit_rate()); encoder.set_max_bit_rate(decoder.max_bit_rate());
encoder.set_time_base((1, decoder.rate() as i32)); encoder.set_time_base((1, decoder.rate() as i32));
output.set_time_base((1, decoder.rate() as i32)); output.set_time_base((1, decoder.rate() as i32));
let encoder = try!(encoder.open_as(codec)); let encoder = encoder.open_as(codec)?;
output.set_parameters(&encoder); output.set_parameters(&encoder);
let filter = try!(filter(filter_spec, &decoder, &encoder)); let filter = filter(filter_spec, &decoder, &encoder)?;
Ok(Transcoder { Ok(Transcoder {
stream: input.index(), stream: input.index(),
@ -102,7 +136,7 @@ fn main() {
let input = env::args().nth(1).expect("missing input"); let input = env::args().nth(1).expect("missing input");
let output = env::args().nth(2).expect("missing output"); let output = env::args().nth(2).expect("missing output");
let filter = env::args().nth(3).unwrap_or("anull".to_owned()); let filter = env::args().nth(3).unwrap_or_else(|| "anull".to_owned());
let seek = env::args().nth(4).and_then(|s| s.parse::<i64>().ok()); let seek = env::args().nth(4).and_then(|s| s.parse::<i64>().ok());
let mut ictx = format::input(&input).unwrap(); let mut ictx = format::input(&input).unwrap();
@ -134,9 +168,21 @@ fn main() {
let timestamp = decoded.timestamp(); let timestamp = decoded.timestamp();
decoded.set_pts(timestamp); decoded.set_pts(timestamp);
transcoder.filter.get("in").unwrap().source().add(&decoded).unwrap(); transcoder
.filter
.get("in")
.unwrap()
.source()
.add(&decoded)
.unwrap();
while let Ok(..) = transcoder.filter.get("out").unwrap().sink().frame(&mut decoded) { while let Ok(..) = transcoder
.filter
.get("out")
.unwrap()
.sink()
.frame(&mut decoded)
{
if let Ok(true) = transcoder.encoder.encode(&decoded, &mut encoded) { if let Ok(true) = transcoder.encoder.encode(&decoded, &mut encoded) {
encoded.set_stream(0); encoded.set_stream(0);
encoded.rescale_ts(in_time_base, out_time_base); encoded.rescale_ts(in_time_base, out_time_base);
@ -147,9 +193,21 @@ fn main() {
} }
} }
transcoder.filter.get("in").unwrap().source().flush().unwrap(); transcoder
.filter
.get("in")
.unwrap()
.source()
.flush()
.unwrap();
while let Ok(..) = transcoder.filter.get("out").unwrap().sink().frame(&mut decoded) { while let Ok(..) = transcoder
.filter
.get("out")
.unwrap()
.sink()
.frame(&mut decoded)
{
if let Ok(true) = transcoder.encoder.encode(&decoded, &mut encoded) { if let Ok(true) = transcoder.encoder.encode(&decoded, &mut encoded) {
encoded.set_stream(0); encoded.set_stream(0);
encoded.rescale_ts(in_time_base, out_time_base); encoded.rescale_ts(in_time_base, out_time_base);

View File

@ -1,8 +1,8 @@
use std::ops::Deref; use std::ops::Deref;
use {ChannelLayout, format};
use super::codec::Codec; use super::codec::Codec;
use ffi::*; use ffi::*;
use {format, ChannelLayout};
#[derive(PartialEq, Eq, Copy, Clone)] #[derive(PartialEq, Eq, Copy, Clone)]
pub struct Audio { pub struct Audio {
@ -11,9 +11,7 @@ pub struct Audio {
impl Audio { impl Audio {
pub unsafe fn new(codec: Codec) -> Audio { pub unsafe fn new(codec: Codec) -> Audio {
Audio { Audio { codec: codec }
codec: codec,
}
} }
} }
@ -22,8 +20,7 @@ impl Audio {
unsafe { unsafe {
if (*self.as_ptr()).supported_samplerates.is_null() { if (*self.as_ptr()).supported_samplerates.is_null() {
None None
} } else {
else {
Some(RateIter::new((*self.codec.as_ptr()).supported_samplerates)) Some(RateIter::new((*self.codec.as_ptr()).supported_samplerates))
} }
} }
@ -33,8 +30,7 @@ impl Audio {
unsafe { unsafe {
if (*self.codec.as_ptr()).sample_fmts.is_null() { if (*self.codec.as_ptr()).sample_fmts.is_null() {
None None
} } else {
else {
Some(FormatIter::new((*self.codec.as_ptr()).sample_fmts)) Some(FormatIter::new((*self.codec.as_ptr()).sample_fmts))
} }
} }
@ -44,9 +40,10 @@ impl Audio {
unsafe { unsafe {
if (*self.codec.as_ptr()).channel_layouts.is_null() { if (*self.codec.as_ptr()).channel_layouts.is_null() {
None None
} } else {
else { Some(ChannelLayoutIter::new(
Some(ChannelLayoutIter::new((*self.codec.as_ptr()).channel_layouts)) (*self.codec.as_ptr()).channel_layouts,
))
} }
} }
} }
@ -124,12 +121,12 @@ impl ChannelLayoutIter {
} }
pub fn best(self, max: i32) -> ChannelLayout { pub fn best(self, max: i32) -> ChannelLayout {
self.fold(::channel_layout::MONO, |acc, cur| self.fold(::channel_layout::MONO, |acc, cur| {
if cur.channels() > acc.channels() && cur.channels() <= max { if cur.channels() > acc.channels() && cur.channels() <= max {
cur cur
} } else {
else {
acc acc
}
}) })
} }
} }

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::AVAudioServiceType::*; use ffi::AVAudioServiceType::*;
use ffi::*;
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum AudioService { pub enum AudioService {
@ -26,7 +26,7 @@ impl From<AVAudioServiceType> for AudioService {
AV_AUDIO_SERVICE_TYPE_EMERGENCY => AudioService::Emergency, AV_AUDIO_SERVICE_TYPE_EMERGENCY => AudioService::Emergency,
AV_AUDIO_SERVICE_TYPE_VOICE_OVER => AudioService::VoiceOver, AV_AUDIO_SERVICE_TYPE_VOICE_OVER => AudioService::VoiceOver,
AV_AUDIO_SERVICE_TYPE_KARAOKE => AudioService::Karaoke, AV_AUDIO_SERVICE_TYPE_KARAOKE => AudioService::Karaoke,
AV_AUDIO_SERVICE_TYPE_NB => AudioService::Main AV_AUDIO_SERVICE_TYPE_NB => AudioService::Main,
} }
} }
} }
@ -42,7 +42,7 @@ impl Into<AVAudioServiceType> for AudioService {
AudioService::Commentary => AV_AUDIO_SERVICE_TYPE_COMMENTARY, AudioService::Commentary => AV_AUDIO_SERVICE_TYPE_COMMENTARY,
AudioService::Emergency => AV_AUDIO_SERVICE_TYPE_EMERGENCY, AudioService::Emergency => AV_AUDIO_SERVICE_TYPE_EMERGENCY,
AudioService::VoiceOver => AV_AUDIO_SERVICE_TYPE_VOICE_OVER, AudioService::VoiceOver => AV_AUDIO_SERVICE_TYPE_VOICE_OVER,
AudioService::Karaoke => AV_AUDIO_SERVICE_TYPE_KARAOKE AudioService::Karaoke => AV_AUDIO_SERVICE_TYPE_KARAOKE,
} }
} }
} }

View File

@ -1,5 +1,5 @@
use libc::c_uint;
use ffi::*; use ffi::*;
use libc::c_uint;
bitflags! { bitflags! {
pub struct Capabilities: c_uint { pub struct Capabilities: c_uint {

View File

@ -1,17 +1,17 @@
use std::ffi::CStr; use std::ffi::CStr;
use std::str::from_utf8_unchecked; use std::str::from_utf8_unchecked;
use super::{Audio, Capabilities, Id, Profile, Video};
use ffi::*; use ffi::*;
use super::{Id, Video, Audio, Capabilities, Profile}; use {media, Error};
use ::{Error, media};
#[derive(PartialEq, Eq, Copy, Clone)] #[derive(PartialEq, Eq, Copy, Clone)]
pub struct Codec { pub struct Codec {
ptr: *mut AVCodec, ptr: *mut AVCodec,
} }
unsafe impl Send for Codec { } unsafe impl Send for Codec {}
unsafe impl Sync for Codec { } unsafe impl Sync for Codec {}
impl Codec { impl Codec {
pub unsafe fn wrap(ptr: *mut AVCodec) -> Self { pub unsafe fn wrap(ptr: *mut AVCodec) -> Self {
@ -29,39 +29,27 @@ impl Codec {
impl Codec { impl Codec {
pub fn is_encoder(&self) -> bool { pub fn is_encoder(&self) -> bool {
unsafe { unsafe { av_codec_is_encoder(self.as_ptr()) != 0 }
av_codec_is_encoder(self.as_ptr()) != 0
}
} }
pub fn is_decoder(&self) -> bool { pub fn is_decoder(&self) -> bool {
unsafe { unsafe { av_codec_is_decoder(self.as_ptr()) != 0 }
av_codec_is_decoder(self.as_ptr()) != 0
}
} }
pub fn name(&self) -> &str { pub fn name(&self) -> &str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).name).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).name).to_bytes())
}
} }
pub fn description(&self) -> &str { pub fn description(&self) -> &str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).long_name).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).long_name).to_bytes())
}
} }
pub fn medium(&self) -> media::Type { pub fn medium(&self) -> media::Type {
unsafe { unsafe { media::Type::from((*self.as_ptr()).type_) }
media::Type::from((*self.as_ptr()).type_)
}
} }
pub fn id(&self) -> Id { pub fn id(&self) -> Id {
unsafe { unsafe { Id::from((*self.as_ptr()).id) }
Id::from((*self.as_ptr()).id)
}
} }
pub fn is_video(&self) -> bool { pub fn is_video(&self) -> bool {
@ -72,8 +60,7 @@ impl Codec {
unsafe { unsafe {
if self.medium() == media::Type::Video { if self.medium() == media::Type::Video {
Ok(Video::new(self)) Ok(Video::new(self))
} } else {
else {
Err(Error::InvalidData) Err(Error::InvalidData)
} }
} }
@ -87,31 +74,25 @@ impl Codec {
unsafe { unsafe {
if self.medium() == media::Type::Audio { if self.medium() == media::Type::Audio {
Ok(Audio::new(self)) Ok(Audio::new(self))
} } else {
else {
Err(Error::InvalidData) Err(Error::InvalidData)
} }
} }
} }
pub fn max_lowres(&self) -> i32 { pub fn max_lowres(&self) -> i32 {
unsafe { unsafe { av_codec_get_max_lowres(self.as_ptr()) }
av_codec_get_max_lowres(self.as_ptr())
}
} }
pub fn capabilities(&self) -> Capabilities { pub fn capabilities(&self) -> Capabilities {
unsafe { unsafe { Capabilities::from_bits_truncate((*self.as_ptr()).capabilities as u32) }
Capabilities::from_bits_truncate((*self.as_ptr()).capabilities as u32)
}
} }
pub fn profiles(&self) -> Option<ProfileIter> { pub fn profiles(&self) -> Option<ProfileIter> {
unsafe { unsafe {
if (*self.as_ptr()).profiles.is_null() { if (*self.as_ptr()).profiles.is_null() {
None None
} } else {
else {
Some(ProfileIter::new(self.id(), (*self.as_ptr()).profiles)) Some(ProfileIter::new(self.id(), (*self.as_ptr()).profiles))
} }
} }

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Compliance { pub enum Compliance {
@ -19,7 +19,7 @@ impl From<c_int> for Compliance {
FF_COMPLIANCE_UNOFFICIAL => Compliance::Unofficial, FF_COMPLIANCE_UNOFFICIAL => Compliance::Unofficial,
FF_COMPLIANCE_EXPERIMENTAL => Compliance::Experimental, FF_COMPLIANCE_EXPERIMENTAL => Compliance::Experimental,
_ => Compliance::Normal _ => Compliance::Normal,
} }
} }
} }
@ -31,7 +31,7 @@ impl Into<c_int> for Compliance {
Compliance::Strict => FF_COMPLIANCE_STRICT, Compliance::Strict => FF_COMPLIANCE_STRICT,
Compliance::Normal => FF_COMPLIANCE_NORMAL, Compliance::Normal => FF_COMPLIANCE_NORMAL,
Compliance::Unofficial => FF_COMPLIANCE_UNOFFICIAL, Compliance::Unofficial => FF_COMPLIANCE_UNOFFICIAL,
Compliance::Experimental => FF_COMPLIANCE_EXPERIMENTAL Compliance::Experimental => FF_COMPLIANCE_EXPERIMENTAL,
} }
} }
} }

View File

@ -1,24 +1,27 @@
use std::ptr; use std::ptr;
use std::rc::Rc; use std::rc::Rc;
use libc::c_int;
use ffi::*;
use ::media;
use ::{Codec, Error};
use super::{Flags, Id, Debug, Compliance, threading, Parameters};
use super::decoder::Decoder; use super::decoder::Decoder;
use super::encoder::Encoder; use super::encoder::Encoder;
use super::{threading, Compliance, Debug, Flags, Id, Parameters};
use ffi::*;
use libc::c_int;
use media;
use {Codec, Error};
pub struct Context { pub struct Context {
ptr: *mut AVCodecContext, ptr: *mut AVCodecContext,
owner: Option<Rc<Drop>>, owner: Option<Rc<Drop>>,
} }
unsafe impl Send for Context { } unsafe impl Send for Context {}
impl Context { impl Context {
pub unsafe fn wrap(ptr: *mut AVCodecContext, owner: Option<Rc<Drop>>) -> Self { pub unsafe fn wrap(ptr: *mut AVCodecContext, owner: Option<Rc<Drop>>) -> Self {
Context { ptr: ptr, owner: owner } Context {
ptr: ptr,
owner: owner,
}
} }
pub unsafe fn as_ptr(&self) -> *const AVCodecContext { pub unsafe fn as_ptr(&self) -> *const AVCodecContext {
@ -33,7 +36,10 @@ impl Context {
impl Context { impl Context {
pub fn new() -> Self { pub fn new() -> Self {
unsafe { unsafe {
Context { ptr: avcodec_alloc_context3(ptr::null()), owner: None } Context {
ptr: avcodec_alloc_context3(ptr::null()),
owner: None,
}
} }
} }
@ -49,17 +55,14 @@ impl Context {
unsafe { unsafe {
if (*self.as_ptr()).codec.is_null() { if (*self.as_ptr()).codec.is_null() {
None None
} } else {
else {
Some(Codec::wrap((*self.as_ptr()).codec as *mut _)) Some(Codec::wrap((*self.as_ptr()).codec as *mut _))
} }
} }
} }
pub fn medium(&self) -> media::Type { pub fn medium(&self) -> media::Type {
unsafe { unsafe { media::Type::from((*self.as_ptr()).codec_type) }
media::Type::from((*self.as_ptr()).codec_type)
}
} }
pub fn set_flags(&mut self, value: Flags) { pub fn set_flags(&mut self, value: Flags) {
@ -69,9 +72,7 @@ impl Context {
} }
pub fn id(&self) -> Id { pub fn id(&self) -> Id {
unsafe { unsafe { Id::from((*self.as_ptr()).codec_id) }
Id::from((*self.as_ptr()).codec_id)
}
} }
pub fn compliance(&mut self, value: Compliance) { pub fn compliance(&mut self, value: Compliance) {
@ -116,6 +117,12 @@ impl Context {
} }
} }
impl Default for Context {
fn default() -> Self {
Self::new()
}
}
impl Drop for Context { impl Drop for Context {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
bitflags! { bitflags! {
pub struct Debug: c_int { pub struct Debug: c_int {

View File

@ -1,44 +1,47 @@
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
use super::Opened; use super::Opened;
use ::{packet, Error, AudioService, ChannelLayout}; use codec::Context;
use ::frame; use frame;
use ::util::format; use util::format;
use ::codec::Context; use {packet, AudioService, ChannelLayout, Error};
pub struct Audio(pub Opened); pub struct Audio(pub Opened);
impl Audio { impl Audio {
pub fn decode<P: packet::Ref>(&mut self, packet: &P, out: &mut frame::Audio) -> Result<bool, Error> { pub fn decode<P: packet::Ref>(
&mut self,
packet: &P,
out: &mut frame::Audio,
) -> Result<bool, Error> {
unsafe { unsafe {
let mut got: c_int = 0; let mut got: c_int = 0;
match avcodec_decode_audio4(self.as_mut_ptr(), out.as_mut_ptr(), &mut got, packet.as_ptr()) { match avcodec_decode_audio4(
self.as_mut_ptr(),
out.as_mut_ptr(),
&mut got,
packet.as_ptr(),
) {
e if e < 0 => Err(Error::from(e)), e if e < 0 => Err(Error::from(e)),
_ => Ok(got != 0) _ => Ok(got != 0),
} }
} }
} }
pub fn rate(&self) -> u32 { pub fn rate(&self) -> u32 {
unsafe { unsafe { (*self.as_ptr()).sample_rate as u32 }
(*self.as_ptr()).sample_rate as u32
}
} }
pub fn channels(&self) -> u16 { pub fn channels(&self) -> u16 {
unsafe { unsafe { (*self.as_ptr()).channels as u16 }
(*self.as_ptr()).channels as u16
}
} }
pub fn format(&self) -> format::Sample { pub fn format(&self) -> format::Sample {
unsafe { unsafe { format::Sample::from((*self.as_ptr()).sample_fmt) }
format::Sample::from((*self.as_ptr()).sample_fmt)
}
} }
pub fn request_format(&mut self, value: format::Sample) { pub fn request_format(&mut self, value: format::Sample) {
@ -48,21 +51,15 @@ impl Audio {
} }
pub fn frames(&self) -> usize { pub fn frames(&self) -> usize {
unsafe { unsafe { (*self.as_ptr()).frame_number as usize }
(*self.as_ptr()).frame_number as usize
}
} }
pub fn align(&self) -> usize { pub fn align(&self) -> usize {
unsafe { unsafe { (*self.as_ptr()).block_align as usize }
(*self.as_ptr()).block_align as usize
}
} }
pub fn channel_layout(&self) -> ChannelLayout { pub fn channel_layout(&self) -> ChannelLayout {
unsafe { unsafe { ChannelLayout::from_bits_truncate((*self.as_ptr()).channel_layout) }
ChannelLayout::from_bits_truncate((*self.as_ptr()).channel_layout)
}
} }
pub fn set_channel_layout(&mut self, value: ChannelLayout) { pub fn set_channel_layout(&mut self, value: ChannelLayout) {
@ -78,28 +75,22 @@ impl Audio {
} }
pub fn audio_service(&mut self) -> AudioService { pub fn audio_service(&mut self) -> AudioService {
unsafe { unsafe { AudioService::from((*self.as_mut_ptr()).audio_service_type) }
AudioService::from((*self.as_mut_ptr()).audio_service_type)
}
} }
pub fn max_bit_rate(&self) -> usize { pub fn max_bit_rate(&self) -> usize {
unsafe { unsafe { (*self.as_ptr()).rc_max_rate as usize }
(*self.as_ptr()).rc_max_rate as usize
}
} }
pub fn frame_size(&self) -> u32 { pub fn frame_size(&self) -> u32 {
unsafe { unsafe { (*self.as_ptr()).frame_size as u32 }
(*self.as_ptr()).frame_size as u32
}
} }
pub fn frame_start(&self) -> Option<usize> { pub fn frame_start(&self) -> Option<usize> {
unsafe { unsafe {
match (*self.as_ptr()).timecode_frame_start { match (*self.as_ptr()).timecode_frame_start {
-1 => None, -1 => None,
n => Some(n as usize) n => Some(n as usize),
} }
} }
} }
@ -114,14 +105,14 @@ impl Deref for Audio {
} }
impl DerefMut for Audio { impl DerefMut for Audio {
fn deref_mut(&mut self) -> &mut<Self as Deref>::Target { fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
&mut self.0 &mut self.0
} }
} }
impl AsRef<Context> for Audio { impl AsRef<Context> for Audio {
fn as_ref(&self) -> &Context { fn as_ref(&self) -> &Context {
&self self
} }
} }

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
bitflags! { bitflags! {
pub struct Check: c_int { pub struct Check: c_int {

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
bitflags! { bitflags! {
pub struct Conceal: c_int { pub struct Conceal: c_int {

View File

@ -1,10 +1,10 @@
use std::ptr;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::ptr;
use super::{Audio, Check, Conceal, Opened, Subtitle, Video};
use codec::{traits, Context};
use ffi::*; use ffi::*;
use codec::{Context, traits}; use {Dictionary, Discard, Error, Rational};
use super::{Opened, Video, Audio, Subtitle, Conceal, Check};
use ::{Error, Discard, Rational, Dictionary};
pub struct Decoder(pub Context); pub struct Decoder(pub Context);
@ -13,7 +13,7 @@ impl Decoder {
unsafe { unsafe {
match avcodec_open2(self.as_mut_ptr(), ptr::null(), ptr::null_mut()) { match avcodec_open2(self.as_mut_ptr(), ptr::null(), ptr::null_mut()) {
0 => Ok(Opened(self)), 0 => Ok(Opened(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -23,16 +23,19 @@ impl Decoder {
if let Some(codec) = codec.decoder() { if let Some(codec) = codec.decoder() {
match avcodec_open2(self.as_mut_ptr(), codec.as_ptr(), ptr::null_mut()) { match avcodec_open2(self.as_mut_ptr(), codec.as_ptr(), ptr::null_mut()) {
0 => Ok(Opened(self)), 0 => Ok(Opened(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} } else {
else {
Err(Error::DecoderNotFound) Err(Error::DecoderNotFound)
} }
} }
} }
pub fn open_as_with<D: traits::Decoder>(mut self, codec: D, options: Dictionary) -> Result<Opened, Error> { pub fn open_as_with<D: traits::Decoder>(
mut self,
codec: D,
options: Dictionary,
) -> Result<Opened, Error> {
unsafe { unsafe {
if let Some(codec) = codec.decoder() { if let Some(codec) = codec.decoder() {
let mut opts = options.disown(); let mut opts = options.disown();
@ -42,10 +45,9 @@ impl Decoder {
match res { match res {
0 => Ok(Opened(self)), 0 => Ok(Opened(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} } else {
else {
Err(Error::DecoderNotFound) Err(Error::DecoderNotFound)
} }
} }
@ -54,8 +56,7 @@ impl Decoder {
pub fn video(self) -> Result<Video, Error> { pub fn video(self) -> Result<Video, Error> {
if let Some(codec) = super::find(self.id()) { if let Some(codec) = super::find(self.id()) {
self.open_as(codec).and_then(|o| o.video()) self.open_as(codec).and_then(|o| o.video())
} } else {
else {
Err(Error::DecoderNotFound) Err(Error::DecoderNotFound)
} }
} }
@ -63,8 +64,7 @@ impl Decoder {
pub fn audio(self) -> Result<Audio, Error> { pub fn audio(self) -> Result<Audio, Error> {
if let Some(codec) = super::find(self.id()) { if let Some(codec) = super::find(self.id()) {
self.open_as(codec).and_then(|o| o.audio()) self.open_as(codec).and_then(|o| o.audio())
} } else {
else {
Err(Error::DecoderNotFound) Err(Error::DecoderNotFound)
} }
} }
@ -72,8 +72,7 @@ impl Decoder {
pub fn subtitle(self) -> Result<Subtitle, Error> { pub fn subtitle(self) -> Result<Subtitle, Error> {
if let Some(codec) = super::find(self.id()) { if let Some(codec) = super::find(self.id()) {
self.open_as(codec).and_then(|o| o.subtitle()) self.open_as(codec).and_then(|o| o.subtitle())
} } else {
else {
Err(Error::DecoderNotFound) Err(Error::DecoderNotFound)
} }
} }
@ -109,9 +108,7 @@ impl Decoder {
} }
pub fn time_base(&self) -> Rational { pub fn time_base(&self) -> Rational {
unsafe { unsafe { Rational::from((*self.as_ptr()).time_base) }
Rational::from((*self.as_ptr()).time_base)
}
} }
} }
@ -124,14 +121,14 @@ impl Deref for Decoder {
} }
impl DerefMut for Decoder { impl DerefMut for Decoder {
fn deref_mut(&mut self) -> &mut<Self as Deref>::Target { fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
&mut self.0 &mut self.0
} }
} }
impl AsRef<Context> for Decoder { impl AsRef<Context> for Decoder {
fn as_ref(&self) -> &Context { fn as_ref(&self) -> &Context {
&self self
} }
} }

View File

@ -23,10 +23,10 @@ pub use self::opened::Opened;
use std::ffi::CString; use std::ffi::CString;
use ffi::*;
use codec::Context; use codec::Context;
use ::Codec;
use codec::Id; use codec::Id;
use ffi::*;
use Codec;
pub fn new() -> Decoder { pub fn new() -> Decoder {
Context::new().decoder() Context::new().decoder()
@ -38,8 +38,7 @@ pub fn find(id: Id) -> Option<Codec> {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(Codec::wrap(ptr)) Some(Codec::wrap(ptr))
} }
} }
@ -52,8 +51,7 @@ pub fn find_by_name(name: &str) -> Option<Codec> {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(Codec::wrap(ptr)) Some(Codec::wrap(ptr))
} }
} }

View File

@ -1,10 +1,10 @@
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use super::{Audio, Decoder, Subtitle, Video};
use codec::{Context, Profile};
use ffi::*; use ffi::*;
use super::{Video, Audio, Subtitle, Decoder}; use media;
use ::codec::{Profile, Context}; use {Error, Rational};
use ::{Error, Rational};
use ::media;
pub struct Opened(pub Decoder); pub struct Opened(pub Decoder);
@ -12,8 +12,7 @@ impl Opened {
pub fn video(self) -> Result<Video, Error> { pub fn video(self) -> Result<Video, Error> {
if self.medium() == media::Type::Video { if self.medium() == media::Type::Video {
Ok(Video(self)) Ok(Video(self))
} } else {
else {
Err(Error::InvalidData) Err(Error::InvalidData)
} }
} }
@ -21,8 +20,7 @@ impl Opened {
pub fn audio(self) -> Result<Audio, Error> { pub fn audio(self) -> Result<Audio, Error> {
if self.medium() == media::Type::Audio { if self.medium() == media::Type::Audio {
Ok(Audio(self)) Ok(Audio(self))
} } else {
else {
Err(Error::InvalidData) Err(Error::InvalidData)
} }
} }
@ -30,28 +28,21 @@ impl Opened {
pub fn subtitle(self) -> Result<Subtitle, Error> { pub fn subtitle(self) -> Result<Subtitle, Error> {
if self.medium() == media::Type::Subtitle { if self.medium() == media::Type::Subtitle {
Ok(Subtitle(self)) Ok(Subtitle(self))
} } else {
else {
Err(Error::InvalidData) Err(Error::InvalidData)
} }
} }
pub fn bit_rate(&self) -> usize { pub fn bit_rate(&self) -> usize {
unsafe { unsafe { (*self.as_ptr()).bit_rate as usize }
(*self.as_ptr()).bit_rate as usize
}
} }
pub fn delay(&self) -> usize { pub fn delay(&self) -> usize {
unsafe { unsafe { (*self.as_ptr()).delay as usize }
(*self.as_ptr()).delay as usize
}
} }
pub fn profile(&self) -> Profile { pub fn profile(&self) -> Profile {
unsafe { unsafe { Profile::from((self.id(), (*self.as_ptr()).profile)) }
Profile::from((self.id(), (*self.as_ptr()).profile))
}
} }
pub fn frame_rate(&self) -> Option<Rational> { pub fn frame_rate(&self) -> Option<Rational> {
@ -60,8 +51,7 @@ impl Opened {
if value == (AVRational { num: 0, den: 1 }) { if value == (AVRational { num: 0, den: 1 }) {
None None
} } else {
else {
Some(Rational::from(value)) Some(Rational::from(value))
} }
} }
@ -91,14 +81,14 @@ impl Deref for Opened {
} }
impl DerefMut for Opened { impl DerefMut for Opened {
fn deref_mut(&mut self) -> &mut<Self as Deref>::Target { fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
&mut self.0 &mut self.0
} }
} }
impl AsRef<Context> for Opened { impl AsRef<Context> for Opened {
fn as_ref(&self) -> &Context { fn as_ref(&self) -> &Context {
&self self
} }
} }

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
bitflags! { bitflags! {
pub struct Flags: c_int { pub struct Flags: c_int {

View File

@ -1,22 +1,31 @@
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
use super::Opened; use super::Opened;
use ::{packet, Error}; use codec::Context;
use ::codec::Context; use {packet, Error};
pub struct Subtitle(pub Opened); pub struct Subtitle(pub Opened);
impl Subtitle { impl Subtitle {
pub fn decode<P: packet::Ref>(&mut self, packet: &P, out: &mut ::Subtitle) -> Result<bool, Error> { pub fn decode<P: packet::Ref>(
&mut self,
packet: &P,
out: &mut ::Subtitle,
) -> Result<bool, Error> {
unsafe { unsafe {
let mut got: c_int = 0; let mut got: c_int = 0;
match avcodec_decode_subtitle2(self.as_mut_ptr(), out.as_mut_ptr(), &mut got, packet.as_ptr() as *mut _) { match avcodec_decode_subtitle2(
self.as_mut_ptr(),
out.as_mut_ptr(),
&mut got,
packet.as_ptr() as *mut _,
) {
e if e < 0 => Err(Error::from(e)), e if e < 0 => Err(Error::from(e)),
_ => Ok(got != 0) _ => Ok(got != 0),
} }
} }
} }
@ -31,14 +40,14 @@ impl Deref for Subtitle {
} }
impl DerefMut for Subtitle { impl DerefMut for Subtitle {
fn deref_mut(&mut self) -> &mut<Self as Deref>::Target { fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
&mut self.0 &mut self.0
} }
} }
impl AsRef<Context> for Subtitle { impl AsRef<Context> for Subtitle {
fn as_ref(&self) -> &Context { fn as_ref(&self) -> &Context {
&self self
} }
} }

View File

@ -1,88 +1,77 @@
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
use super::{Opened, slice}; use super::{slice, Opened};
use ::{packet, Error, Rational, FieldOrder}; use codec::Context;
use ::frame; use color;
use ::util::format; use frame;
use ::util::chroma; use util::chroma;
use ::color; use util::format;
use ::codec::Context; use {packet, Error, FieldOrder, Rational};
pub struct Video(pub Opened); pub struct Video(pub Opened);
impl Video { impl Video {
pub fn decode<P: packet::Ref>(&mut self, packet: &P, out: &mut frame::Video) -> Result<bool, Error> { pub fn decode<P: packet::Ref>(
&mut self,
packet: &P,
out: &mut frame::Video,
) -> Result<bool, Error> {
unsafe { unsafe {
let mut got: c_int = 0; let mut got: c_int = 0;
match avcodec_decode_video2(self.as_mut_ptr(), out.as_mut_ptr(), &mut got, packet.as_ptr()) { match avcodec_decode_video2(
self.as_mut_ptr(),
out.as_mut_ptr(),
&mut got,
packet.as_ptr(),
) {
e if e < 0 => Err(Error::from(e)), e if e < 0 => Err(Error::from(e)),
_ => Ok(got != 0) _ => Ok(got != 0),
} }
} }
} }
pub fn width(&self) -> u32 { pub fn width(&self) -> u32 {
unsafe { unsafe { (*self.as_ptr()).width as u32 }
(*self.as_ptr()).width as u32
}
} }
pub fn height(&self) -> u32 { pub fn height(&self) -> u32 {
unsafe { unsafe { (*self.as_ptr()).height as u32 }
(*self.as_ptr()).height as u32
}
} }
pub fn format(&self) -> format::Pixel { pub fn format(&self) -> format::Pixel {
unsafe { unsafe { format::Pixel::from((*self.as_ptr()).pix_fmt) }
format::Pixel::from((*self.as_ptr()).pix_fmt)
}
} }
pub fn has_b_frames(&self) -> bool { pub fn has_b_frames(&self) -> bool {
unsafe { unsafe { (*self.as_ptr()).has_b_frames != 0 }
(*self.as_ptr()).has_b_frames != 0
}
} }
pub fn aspect_ratio(&self) -> Rational { pub fn aspect_ratio(&self) -> Rational {
unsafe { unsafe { Rational::from((*self.as_ptr()).sample_aspect_ratio) }
Rational::from((*self.as_ptr()).sample_aspect_ratio)
}
} }
pub fn color_space(&self) -> color::Space { pub fn color_space(&self) -> color::Space {
unsafe { unsafe { color::Space::from((*self.as_ptr()).colorspace) }
color::Space::from((*self.as_ptr()).colorspace)
}
} }
pub fn color_range(&self) -> color::Range { pub fn color_range(&self) -> color::Range {
unsafe { unsafe { color::Range::from((*self.as_ptr()).color_range) }
color::Range::from((*self.as_ptr()).color_range)
}
} }
pub fn color_primaries(&self) -> color::Primaries { pub fn color_primaries(&self) -> color::Primaries {
unsafe { unsafe { color::Primaries::from((*self.as_ptr()).color_primaries) }
color::Primaries::from((*self.as_ptr()).color_primaries)
}
} }
pub fn color_transfer_characteristic(&self) -> color::TransferCharacteristic { pub fn color_transfer_characteristic(&self) -> color::TransferCharacteristic {
unsafe { unsafe { color::TransferCharacteristic::from((*self.as_ptr()).color_trc) }
color::TransferCharacteristic::from((*self.as_ptr()).color_trc)
}
} }
pub fn chroma_location(&self) -> chroma::Location { pub fn chroma_location(&self) -> chroma::Location {
unsafe { unsafe { chroma::Location::from((*self.as_ptr()).chroma_sample_location) }
chroma::Location::from((*self.as_ptr()).chroma_sample_location)
}
} }
pub fn set_slice_count(&mut self, value: usize) { pub fn set_slice_count(&mut self, value: usize) {
@ -110,9 +99,7 @@ impl Video {
} }
pub fn references(&self) -> usize { pub fn references(&self) -> usize {
unsafe { unsafe { (*self.as_ptr()).refs as usize }
(*self.as_ptr()).refs as usize
}
} }
pub fn set_field_order(&mut self, value: FieldOrder) { pub fn set_field_order(&mut self, value: FieldOrder) {
@ -125,15 +112,11 @@ impl Video {
// inter_matrix // inter_matrix
pub fn intra_dc_precision(&self) -> u8 { pub fn intra_dc_precision(&self) -> u8 {
unsafe { unsafe { (*self.as_ptr()).intra_dc_precision as u8 }
(*self.as_ptr()).intra_dc_precision as u8
}
} }
pub fn max_bit_rate(&self) -> usize { pub fn max_bit_rate(&self) -> usize {
unsafe { unsafe { (*self.as_ptr()).rc_max_rate as usize }
(*self.as_ptr()).rc_max_rate as usize
}
} }
} }
@ -146,14 +129,14 @@ impl Deref for Video {
} }
impl DerefMut for Video { impl DerefMut for Video {
fn deref_mut(&mut self) -> &mut<Self as Deref>::Target { fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
&mut self.0 &mut self.0
} }
} }
impl AsRef<Context> for Video { impl AsRef<Context> for Video {
fn as_ref(&self) -> &Context { fn as_ref(&self) -> &Context {
&self self
} }
} }

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::AVDiscard::*; use ffi::AVDiscard::*;
use ffi::*;
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Discard { pub enum Discard {
@ -21,7 +21,7 @@ impl From<AVDiscard> for Discard {
AVDISCARD_BIDIR => Discard::Bidirectional, AVDISCARD_BIDIR => Discard::Bidirectional,
AVDISCARD_NONINTRA => Discard::NonIntra, AVDISCARD_NONINTRA => Discard::NonIntra,
AVDISCARD_NONKEY => Discard::NonKey, AVDISCARD_NONKEY => Discard::NonKey,
AVDISCARD_ALL => Discard::All AVDISCARD_ALL => Discard::All,
} }
} }
} }
@ -35,7 +35,7 @@ impl Into<AVDiscard> for Discard {
Discard::Bidirectional => AVDISCARD_BIDIR, Discard::Bidirectional => AVDISCARD_BIDIR,
Discard::NonIntra => AVDISCARD_NONINTRA, Discard::NonIntra => AVDISCARD_NONINTRA,
Discard::NonKey => AVDISCARD_NONKEY, Discard::NonKey => AVDISCARD_NONKEY,
Discard::All => AVDISCARD_ALL Discard::All => AVDISCARD_ALL,
} }
} }
} }

View File

@ -1,13 +1,13 @@
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::ptr; use std::ptr;
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
use super::Encoder as Super; use super::Encoder as Super;
use ::{packet, Error, Dictionary, ChannelLayout, frame};
use ::util::format;
use codec::{traits, Context}; use codec::{traits, Context};
use util::format;
use {frame, packet, ChannelLayout, Dictionary, Error};
pub struct Audio(pub Super); pub struct Audio(pub Super);
@ -16,7 +16,7 @@ impl Audio {
unsafe { unsafe {
match avcodec_open2(self.as_mut_ptr(), ptr::null(), ptr::null_mut()) { match avcodec_open2(self.as_mut_ptr(), ptr::null(), ptr::null_mut()) {
0 => Ok(Encoder(self)), 0 => Ok(Encoder(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -26,10 +26,9 @@ impl Audio {
if let Some(codec) = codec.encoder() { if let Some(codec) = codec.encoder() {
match avcodec_open2(self.as_mut_ptr(), codec.as_ptr(), ptr::null_mut()) { match avcodec_open2(self.as_mut_ptr(), codec.as_ptr(), ptr::null_mut()) {
0 => Ok(Encoder(self)), 0 => Ok(Encoder(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} } else {
else {
Err(Error::EncoderNotFound) Err(Error::EncoderNotFound)
} }
} }
@ -44,12 +43,16 @@ impl Audio {
match res { match res {
0 => Ok(Encoder(self)), 0 => Ok(Encoder(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
pub fn open_as_with<E: traits::Encoder>(mut self, codec: E, options: Dictionary) -> Result<Encoder, Error> { pub fn open_as_with<E: traits::Encoder>(
mut self,
codec: E,
options: Dictionary,
) -> Result<Encoder, Error> {
unsafe { unsafe {
if let Some(codec) = codec.encoder() { if let Some(codec) = codec.encoder() {
let mut opts = options.disown(); let mut opts = options.disown();
@ -59,10 +62,9 @@ impl Audio {
match res { match res {
0 => Ok(Encoder(self)), 0 => Ok(Encoder(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} } else {
else {
Err(Error::EncoderNotFound) Err(Error::EncoderNotFound)
} }
} }
@ -75,9 +77,7 @@ impl Audio {
} }
pub fn rate(&self) -> u32 { pub fn rate(&self) -> u32 {
unsafe { unsafe { (*self.as_ptr()).sample_rate as u32 }
(*self.as_ptr()).sample_rate as u32
}
} }
pub fn set_format(&mut self, value: format::Sample) { pub fn set_format(&mut self, value: format::Sample) {
@ -87,9 +87,7 @@ impl Audio {
} }
pub fn format(&self) -> format::Sample { pub fn format(&self) -> format::Sample {
unsafe { unsafe { format::Sample::from((*self.as_ptr()).sample_fmt) }
format::Sample::from((*self.as_ptr()).sample_fmt)
}
} }
pub fn set_channel_layout(&mut self, value: ChannelLayout) { pub fn set_channel_layout(&mut self, value: ChannelLayout) {
@ -99,9 +97,7 @@ impl Audio {
} }
pub fn channel_layout(&self) -> ChannelLayout { pub fn channel_layout(&self) -> ChannelLayout {
unsafe { unsafe { ChannelLayout::from_bits_truncate((*self.as_ptr()).channel_layout) }
ChannelLayout::from_bits_truncate((*self.as_ptr()).channel_layout)
}
} }
pub fn set_channels(&mut self, value: i32) { pub fn set_channels(&mut self, value: i32) {
@ -111,9 +107,7 @@ impl Audio {
} }
pub fn channels(&self) -> u16 { pub fn channels(&self) -> u16 {
unsafe { unsafe { (*self.as_ptr()).channels as u16 }
(*self.as_ptr()).channels as u16
}
} }
} }
@ -126,14 +120,14 @@ impl Deref for Audio {
} }
impl DerefMut for Audio { impl DerefMut for Audio {
fn deref_mut(&mut self) -> &mut<Self as Deref>::Target { fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
&mut self.0 &mut self.0
} }
} }
impl AsRef<Context> for Audio { impl AsRef<Context> for Audio {
fn as_ref(&self) -> &Context { fn as_ref(&self) -> &Context {
&self self
} }
} }
@ -146,7 +140,11 @@ impl AsMut<Context> for Audio {
pub struct Encoder(pub Audio); pub struct Encoder(pub Audio);
impl Encoder { impl Encoder {
pub fn encode<P: packet::Mut>(&mut self, frame: &frame::Audio, out: &mut P) -> Result<bool, Error> { pub fn encode<P: packet::Mut>(
&mut self,
frame: &frame::Audio,
out: &mut P,
) -> Result<bool, Error> {
unsafe { unsafe {
if self.format() != frame.format() { if self.format() != frame.format() {
return Err(Error::InvalidData); return Err(Error::InvalidData);
@ -154,9 +152,14 @@ impl Encoder {
let mut got: c_int = 0; let mut got: c_int = 0;
match avcodec_encode_audio2(self.0.as_mut_ptr(), out.as_mut_ptr(), frame.as_ptr(), &mut got) { match avcodec_encode_audio2(
self.0.as_mut_ptr(),
out.as_mut_ptr(),
frame.as_ptr(),
&mut got,
) {
e if e < 0 => Err(Error::from(e)), e if e < 0 => Err(Error::from(e)),
_ => Ok(got != 0) _ => Ok(got != 0),
} }
} }
} }
@ -165,17 +168,20 @@ impl Encoder {
unsafe { unsafe {
let mut got: c_int = 0; let mut got: c_int = 0;
match avcodec_encode_audio2(self.0.as_mut_ptr(), out.as_mut_ptr(), ptr::null(), &mut got) { match avcodec_encode_audio2(
self.0.as_mut_ptr(),
out.as_mut_ptr(),
ptr::null(),
&mut got,
) {
e if e < 0 => Err(Error::from(e)), e if e < 0 => Err(Error::from(e)),
_ => Ok(got != 0) _ => Ok(got != 0),
} }
} }
} }
pub fn frame_size(&self) -> u32 { pub fn frame_size(&self) -> u32 {
unsafe { unsafe { (*self.as_ptr()).frame_size as u32 }
(*self.as_ptr()).frame_size as u32
}
} }
} }
@ -189,7 +195,7 @@ impl Deref for Encoder {
impl AsRef<Context> for Encoder { impl AsRef<Context> for Encoder {
fn as_ref(&self) -> &Context { fn as_ref(&self) -> &Context {
&self self
} }
} }

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Comparison { pub enum Comparison {

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Decision { pub enum Decision {

View File

@ -1,9 +1,9 @@
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use libc::{c_int, int64_t}; use super::{audio, subtitle, video};
use codec::Context; use codec::Context;
use ::{Error, Rational, media}; use libc::{c_int, int64_t};
use super::{video, audio, subtitle}; use {media, Error, Rational};
pub struct Encoder(pub Context); pub struct Encoder(pub Context);
@ -18,13 +18,9 @@ impl Encoder {
Ok(video::Video(self)) Ok(video::Video(self))
} }
media::Type::Video => { media::Type::Video => Ok(video::Video(self)),
Ok(video::Video(self))
}
_ => { _ => Err(Error::InvalidData),
Err(Error::InvalidData)
}
} }
} }
@ -38,13 +34,9 @@ impl Encoder {
Ok(audio::Audio(self)) Ok(audio::Audio(self))
} }
media::Type::Audio => { media::Type::Audio => Ok(audio::Audio(self)),
Ok(audio::Audio(self))
}
_ => { _ => Err(Error::InvalidData),
Err(Error::InvalidData)
}
} }
} }
@ -58,13 +50,9 @@ impl Encoder {
Ok(subtitle::Subtitle(self)) Ok(subtitle::Subtitle(self))
} }
media::Type::Subtitle => { media::Type::Subtitle => Ok(subtitle::Subtitle(self)),
Ok(subtitle::Subtitle(self))
}
_ => { _ => Err(Error::InvalidData),
Err(Error::InvalidData)
}
} }
} }
@ -96,8 +84,7 @@ impl Encoder {
unsafe { unsafe {
if let Some(value) = value { if let Some(value) = value {
(*self.as_mut_ptr()).compression_level = value as c_int; (*self.as_mut_ptr()).compression_level = value as c_int;
} } else {
else {
(*self.as_mut_ptr()).compression_level = -1; (*self.as_mut_ptr()).compression_level = -1;
} }
} }
@ -113,8 +100,7 @@ impl Encoder {
unsafe { unsafe {
if let Some(value) = value { if let Some(value) = value {
(*self.as_mut_ptr()).framerate = value.into().into(); (*self.as_mut_ptr()).framerate = value.into().into();
} } else {
else {
(*self.as_mut_ptr()).framerate.num = 0; (*self.as_mut_ptr()).framerate.num = 0;
(*self.as_mut_ptr()).framerate.den = 1; (*self.as_mut_ptr()).framerate.den = 1;
} }
@ -131,14 +117,14 @@ impl Deref for Encoder {
} }
impl DerefMut for Encoder { impl DerefMut for Encoder {
fn deref_mut(&mut self) -> &mut<Self as Deref>::Target { fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
&mut self.0 &mut self.0
} }
} }
impl AsRef<Context> for Encoder { impl AsRef<Context> for Encoder {
fn as_ref(&self) -> &Context { fn as_ref(&self) -> &Context {
&self self
} }
} }

View File

@ -24,10 +24,10 @@ pub use self::decision::Decision;
use std::ffi::CString; use std::ffi::CString;
use ffi::*;
use codec::Context; use codec::Context;
use ::Codec;
use codec::Id; use codec::Id;
use ffi::*;
use Codec;
pub fn new() -> Encoder { pub fn new() -> Encoder {
Context::new().encoder() Context::new().encoder()
@ -39,8 +39,7 @@ pub fn find(id: Id) -> Option<Codec> {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(Codec::wrap(ptr)) Some(Codec::wrap(ptr))
} }
} }
@ -53,8 +52,7 @@ pub fn find_by_name(name: &str) -> Option<Codec> {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(Codec::wrap(ptr)) Some(Codec::wrap(ptr))
} }
} }

View File

@ -28,7 +28,7 @@ impl From<c_int> for MotionEstimation {
9 => MotionEstimation::Iter, 9 => MotionEstimation::Iter,
10 => MotionEstimation::Tesa, 10 => MotionEstimation::Tesa,
_ => MotionEstimation::Zero _ => MotionEstimation::Zero,
} }
} }
} }
@ -45,7 +45,7 @@ impl Into<c_int> for MotionEstimation {
MotionEstimation::Hex => 7, MotionEstimation::Hex => 7,
MotionEstimation::Umh => 8, MotionEstimation::Umh => 8,
MotionEstimation::Iter => 9, MotionEstimation::Iter => 9,
MotionEstimation::Tesa => 10 MotionEstimation::Tesa => 10,
} }
} }
} }

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Prediction { pub enum Prediction {
@ -15,7 +15,7 @@ impl From<c_int> for Prediction {
FF_PRED_PLANE => Prediction::Plane, FF_PRED_PLANE => Prediction::Plane,
FF_PRED_MEDIAN => Prediction::Median, FF_PRED_MEDIAN => Prediction::Median,
_ => Prediction::Left _ => Prediction::Left,
} }
} }
} }

View File

@ -1,12 +1,12 @@
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::ptr; use std::ptr;
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
use super::Encoder as Super; use super::Encoder as Super;
use ::{Error, Dictionary};
use codec::{traits, Context}; use codec::{traits, Context};
use {Dictionary, Error};
pub struct Subtitle(pub Super); pub struct Subtitle(pub Super);
@ -15,7 +15,7 @@ impl Subtitle {
unsafe { unsafe {
match avcodec_open2(self.as_mut_ptr(), ptr::null(), ptr::null_mut()) { match avcodec_open2(self.as_mut_ptr(), ptr::null(), ptr::null_mut()) {
0 => Ok(Encoder(self)), 0 => Ok(Encoder(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -25,16 +25,19 @@ impl Subtitle {
if let Some(codec) = codec.encoder() { if let Some(codec) = codec.encoder() {
match avcodec_open2(self.as_mut_ptr(), codec.as_ptr(), ptr::null_mut()) { match avcodec_open2(self.as_mut_ptr(), codec.as_ptr(), ptr::null_mut()) {
0 => Ok(Encoder(self)), 0 => Ok(Encoder(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} } else {
else {
Err(Error::EncoderNotFound) Err(Error::EncoderNotFound)
} }
} }
} }
pub fn open_as_with<E: traits::Encoder>(mut self, codec: E, options: Dictionary) -> Result<Encoder, Error> { pub fn open_as_with<E: traits::Encoder>(
mut self,
codec: E,
options: Dictionary,
) -> Result<Encoder, Error> {
unsafe { unsafe {
if let Some(codec) = codec.encoder() { if let Some(codec) = codec.encoder() {
let mut opts = options.disown(); let mut opts = options.disown();
@ -44,10 +47,9 @@ impl Subtitle {
match res { match res {
0 => Ok(Encoder(self)), 0 => Ok(Encoder(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} } else {
else {
Err(Error::EncoderNotFound) Err(Error::EncoderNotFound)
} }
} }
@ -63,14 +65,14 @@ impl Deref for Subtitle {
} }
impl DerefMut for Subtitle { impl DerefMut for Subtitle {
fn deref_mut(&mut self) -> &mut<Self as Deref>::Target { fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
&mut self.0 &mut self.0
} }
} }
impl AsRef<Context> for Subtitle { impl AsRef<Context> for Subtitle {
fn as_ref(&self) -> &Context { fn as_ref(&self) -> &Context {
&self self
} }
} }
@ -85,9 +87,14 @@ pub struct Encoder(pub Subtitle);
impl Encoder { impl Encoder {
pub fn encode(&mut self, subtitle: &::Subtitle, out: &mut [u8]) -> Result<bool, Error> { pub fn encode(&mut self, subtitle: &::Subtitle, out: &mut [u8]) -> Result<bool, Error> {
unsafe { unsafe {
match avcodec_encode_subtitle(self.0.as_mut_ptr(), out.as_mut_ptr(), out.len() as c_int, subtitle.as_ptr()) { match avcodec_encode_subtitle(
self.0.as_mut_ptr(),
out.as_mut_ptr(),
out.len() as c_int,
subtitle.as_ptr(),
) {
e if e < 0 => Err(Error::from(e)), e if e < 0 => Err(Error::from(e)),
_ => Ok(true) _ => Ok(true),
} }
} }
} }
@ -103,7 +110,7 @@ impl Deref for Encoder {
impl AsRef<Context> for Encoder { impl AsRef<Context> for Encoder {
fn as_ref(&self) -> &Context { fn as_ref(&self) -> &Context {
&self self
} }
} }

View File

@ -1,13 +1,13 @@
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::ptr; use std::ptr;
use libc::{c_int, c_float};
use ffi::*; use ffi::*;
use libc::{c_float, c_int};
use super::Encoder as Super; use super::Encoder as Super;
use super::{MotionEstimation, Prediction, Comparison, Decision}; use super::{Comparison, Decision, MotionEstimation, Prediction};
use ::{color, packet, Error, Rational, Dictionary, frame, format};
use codec::{traits, Context}; use codec::{traits, Context};
use {color, format, frame, packet, Dictionary, Error, Rational};
pub struct Video(pub Super); pub struct Video(pub Super);
@ -17,7 +17,7 @@ impl Video {
unsafe { unsafe {
match avcodec_open2(self.as_mut_ptr(), ptr::null(), ptr::null_mut()) { match avcodec_open2(self.as_mut_ptr(), ptr::null(), ptr::null_mut()) {
0 => Ok(Encoder(self)), 0 => Ok(Encoder(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -28,10 +28,9 @@ impl Video {
if let Some(codec) = codec.encoder() { if let Some(codec) = codec.encoder() {
match avcodec_open2(self.as_mut_ptr(), codec.as_ptr(), ptr::null_mut()) { match avcodec_open2(self.as_mut_ptr(), codec.as_ptr(), ptr::null_mut()) {
0 => Ok(Encoder(self)), 0 => Ok(Encoder(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} } else {
else {
Err(Error::EncoderNotFound) Err(Error::EncoderNotFound)
} }
} }
@ -47,13 +46,17 @@ impl Video {
match res { match res {
0 => Ok(Encoder(self)), 0 => Ok(Encoder(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
#[inline] #[inline]
pub fn open_as_with<E: traits::Encoder>(mut self, codec: E, options: Dictionary) -> Result<Encoder, Error> { pub fn open_as_with<E: traits::Encoder>(
mut self,
codec: E,
options: Dictionary,
) -> Result<Encoder, Error> {
unsafe { unsafe {
if let Some(codec) = codec.encoder() { if let Some(codec) = codec.encoder() {
let mut opts = options.disown(); let mut opts = options.disown();
@ -63,10 +66,9 @@ impl Video {
match res { match res {
0 => Ok(Encoder(self)), 0 => Ok(Encoder(self)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} } else {
else {
Err(Error::EncoderNotFound) Err(Error::EncoderNotFound)
} }
} }
@ -81,9 +83,7 @@ impl Video {
#[inline] #[inline]
pub fn width(&self) -> u32 { pub fn width(&self) -> u32 {
unsafe { unsafe { (*self.as_ptr()).width as u32 }
(*self.as_ptr()).width as u32
}
} }
#[inline] #[inline]
@ -95,9 +95,7 @@ impl Video {
#[inline] #[inline]
pub fn height(&self) -> u32 { pub fn height(&self) -> u32 {
unsafe { unsafe { (*self.as_ptr()).height as u32 }
(*self.as_ptr()).height as u32
}
} }
#[inline] #[inline]
@ -116,9 +114,7 @@ impl Video {
#[inline] #[inline]
pub fn format(&self) -> format::Pixel { pub fn format(&self) -> format::Pixel {
unsafe { unsafe { format::Pixel::from((*self.as_ptr()).pix_fmt) }
format::Pixel::from((*self.as_ptr()).pix_fmt)
}
} }
#[inline] #[inline]
@ -296,8 +292,7 @@ impl Video {
unsafe { unsafe {
if let Some(value) = value { if let Some(value) = value {
(*self.as_mut_ptr()).intra_quant_bias = value as c_int; (*self.as_mut_ptr()).intra_quant_bias = value as c_int;
} } else {
else {
(*self.as_mut_ptr()).intra_quant_bias = FF_DEFAULT_QUANT_BIAS; (*self.as_mut_ptr()).intra_quant_bias = FF_DEFAULT_QUANT_BIAS;
} }
} }
@ -309,8 +304,7 @@ impl Video {
unsafe { unsafe {
if let Some(value) = value { if let Some(value) = value {
(*self.as_mut_ptr()).inter_quant_bias = value as c_int; (*self.as_mut_ptr()).inter_quant_bias = value as c_int;
} } else {
else {
(*self.as_mut_ptr()).inter_quant_bias = FF_DEFAULT_QUANT_BIAS; (*self.as_mut_ptr()).inter_quant_bias = FF_DEFAULT_QUANT_BIAS;
} }
} }
@ -340,7 +334,7 @@ impl Video {
#[inline] #[inline]
pub fn set_intra_dc_precision(&mut self, value: u8) { pub fn set_intra_dc_precision(&mut self, value: u8) {
unsafe { unsafe {
(*self.as_mut_ptr()).intra_dc_precision = value as c_int; (*self.as_mut_ptr()).intra_dc_precision = i32::from(value);
} }
} }
@ -374,9 +368,7 @@ impl Video {
#[inline] #[inline]
pub fn colorspace(&self) -> color::Space { pub fn colorspace(&self) -> color::Space {
unsafe { unsafe { (*self.as_ptr()).colorspace.into() }
(*self.as_ptr()).colorspace.into()
}
} }
#[inline] #[inline]
@ -388,9 +380,7 @@ impl Video {
#[inline] #[inline]
pub fn color_range(&self) -> color::Range { pub fn color_range(&self) -> color::Range {
unsafe { unsafe { (*self.as_ptr()).color_range.into() }
(*self.as_ptr()).color_range.into()
}
} }
} }
@ -405,14 +395,14 @@ impl Deref for Video {
impl DerefMut for Video { impl DerefMut for Video {
#[inline(always)] #[inline(always)]
fn deref_mut(&mut self) -> &mut<Self as Deref>::Target { fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
&mut self.0 &mut self.0
} }
} }
impl AsRef<Context> for Video { impl AsRef<Context> for Video {
fn as_ref(&self) -> &Context { fn as_ref(&self) -> &Context {
&self self
} }
} }
@ -426,17 +416,28 @@ pub struct Encoder(pub Video);
impl Encoder { impl Encoder {
#[inline] #[inline]
pub fn encode<P: packet::Mut>(&mut self, frame: &frame::Video, out: &mut P) -> Result<bool, Error> { pub fn encode<P: packet::Mut>(
&mut self,
frame: &frame::Video,
out: &mut P,
) -> Result<bool, Error> {
unsafe { unsafe {
if self.format() != frame.format() || self.width() != frame.width() || self.height() != frame.height() { if self.format() != frame.format() || self.width() != frame.width()
|| self.height() != frame.height()
{
return Err(Error::InvalidData); return Err(Error::InvalidData);
} }
let mut got: c_int = 0; let mut got: c_int = 0;
match avcodec_encode_video2(self.0.as_mut_ptr(), out.as_mut_ptr(), frame.as_ptr(), &mut got) { match avcodec_encode_video2(
self.0.as_mut_ptr(),
out.as_mut_ptr(),
frame.as_ptr(),
&mut got,
) {
e if e < 0 => Err(Error::from(e)), e if e < 0 => Err(Error::from(e)),
_ => Ok(got != 0) _ => Ok(got != 0),
} }
} }
} }
@ -446,18 +447,21 @@ impl Encoder {
unsafe { unsafe {
let mut got: c_int = 0; let mut got: c_int = 0;
match avcodec_encode_video2(self.0.as_mut_ptr(), out.as_mut_ptr(), ptr::null(), &mut got) { match avcodec_encode_video2(
self.0.as_mut_ptr(),
out.as_mut_ptr(),
ptr::null(),
&mut got,
) {
e if e < 0 => Err(Error::from(e)), e if e < 0 => Err(Error::from(e)),
_ => Ok(got != 0) _ => Ok(got != 0),
} }
} }
} }
#[inline] #[inline]
pub fn frame_size(&self) -> u32 { pub fn frame_size(&self) -> u32 {
unsafe { unsafe { (*self.as_ptr()).frame_size as u32 }
(*self.as_ptr()).frame_size as u32
}
} }
} }
@ -479,7 +483,7 @@ impl DerefMut for Encoder {
impl AsRef<Context> for Encoder { impl AsRef<Context> for Encoder {
fn as_ref(&self) -> &Context { fn as_ref(&self) -> &Context {
&self self
} }
} }

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::AVFieldOrder::*; use ffi::AVFieldOrder::*;
use ffi::*;
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum FieldOrder { pub enum FieldOrder {
@ -19,7 +19,7 @@ impl From<AVFieldOrder> for FieldOrder {
AV_FIELD_TT => FieldOrder::TT, AV_FIELD_TT => FieldOrder::TT,
AV_FIELD_BB => FieldOrder::BB, AV_FIELD_BB => FieldOrder::BB,
AV_FIELD_TB => FieldOrder::TB, AV_FIELD_TB => FieldOrder::TB,
AV_FIELD_BT => FieldOrder::BT AV_FIELD_BT => FieldOrder::BT,
} }
} }
} }
@ -32,7 +32,7 @@ impl Into<AVFieldOrder> for FieldOrder {
FieldOrder::TT => AV_FIELD_TT, FieldOrder::TT => AV_FIELD_TT,
FieldOrder::BB => AV_FIELD_BB, FieldOrder::BB => AV_FIELD_BB,
FieldOrder::TB => AV_FIELD_TB, FieldOrder::TB => AV_FIELD_TB,
FieldOrder::BT => AV_FIELD_BT FieldOrder::BT => AV_FIELD_BT,
} }
} }
} }

View File

@ -1,5 +1,5 @@
use libc::c_uint;
use ffi::*; use ffi::*;
use libc::c_uint;
bitflags! { bitflags! {
pub struct Flags: c_uint { pub struct Flags: c_uint {
@ -23,4 +23,3 @@ bitflags! {
const CLOSED_GOP = AV_CODEC_FLAG_CLOSED_GOP; const CLOSED_GOP = AV_CODEC_FLAG_CLOSED_GOP;
} }
} }

View File

@ -1,9 +1,9 @@
use std::ffi::CStr; use std::ffi::CStr;
use std::str::from_utf8_unchecked; use std::str::from_utf8_unchecked;
use ffi::*;
use ffi::AVCodecID::*; use ffi::AVCodecID::*;
use ::util::media; use ffi::*;
use util::media;
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
@ -485,15 +485,11 @@ pub enum Id {
impl Id { impl Id {
pub fn medium(&self) -> media::Type { pub fn medium(&self) -> media::Type {
unsafe { unsafe { media::Type::from(avcodec_get_type((*self).into())) }
media::Type::from(avcodec_get_type((*self).into()))
}
} }
pub fn name(&self) -> &'static str { pub fn name(&self) -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(avcodec_get_name((*self).into())).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(avcodec_get_name((*self).into())).to_bytes())
}
} }
} }

View File

@ -29,8 +29,8 @@ pub use self::video::Video;
pub mod audio; pub mod audio;
pub use self::audio::Audio; pub use self::audio::Audio;
pub mod field_order;
pub mod audio_service; pub mod audio_service;
pub mod field_order;
pub mod compliance; pub mod compliance;
pub use self::compliance::Compliance; pub use self::compliance::Compliance;
@ -43,8 +43,8 @@ pub use self::profile::Profile;
pub mod threading; pub mod threading;
pub mod encoder;
pub mod decoder; pub mod decoder;
pub mod encoder;
pub mod traits; pub mod traits;
use std::ffi::CStr; use std::ffi::CStr;
@ -53,19 +53,13 @@ use std::str::from_utf8_unchecked;
use ffi::*; use ffi::*;
pub fn version() -> u32 { pub fn version() -> u32 {
unsafe { unsafe { avcodec_version() }
avcodec_version()
}
} }
pub fn configuration() -> &'static str { pub fn configuration() -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(avcodec_configuration()).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(avcodec_configuration()).to_bytes())
}
} }
pub fn license() -> &'static str { pub fn license() -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(avcodec_license()).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(avcodec_license()).to_bytes())
}
} }

View File

@ -1,9 +1,9 @@
use std::mem; use std::mem;
use std::ptr; use std::ptr;
use libc::c_int;
use ffi::*;
use super::Ref; use super::Ref;
use ffi::*;
use libc::c_int;
pub struct Borrow<'a> { pub struct Borrow<'a> {
packet: AVPacket, packet: AVPacket,

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
bitflags! { bitflags! {
pub struct Flags: c_int { pub struct Flags: c_int {

View File

@ -1,5 +1,5 @@
pub mod traits; pub mod traits;
pub use self::traits::{Ref, Mut}; pub use self::traits::{Mut, Ref};
pub mod packet; pub mod packet;
pub use self::packet::Packet; pub use self::packet::Packet;

View File

@ -2,15 +2,15 @@ use std::marker::PhantomData;
use std::mem; use std::mem;
use std::slice; use std::slice;
use libc::c_int; use super::{flag, Borrow, Flags, Mut, Ref, SideData};
use ffi::*; use ffi::*;
use ::{Error, Rational, format}; use libc::c_int;
use super::{flag, Flags, SideData, Ref, Mut, Borrow}; use {format, Error, Rational};
pub struct Packet(AVPacket); pub struct Packet(AVPacket);
unsafe impl Send for Packet { } unsafe impl Send for Packet {}
unsafe impl Sync for Packet { } unsafe impl Sync for Packet {}
impl Packet { impl Packet {
#[inline(always)] #[inline(always)]
@ -48,7 +48,7 @@ impl Packet {
use std::io::Write; use std::io::Write;
let mut packet = Packet::new(data.len()); let mut packet = Packet::new(data.len());
packet.data_mut().unwrap().write(data).unwrap(); packet.data_mut().unwrap().write_all(data).unwrap();
packet packet
} }
@ -74,11 +74,16 @@ impl Packet {
#[inline] #[inline]
pub fn rescale_ts<S, D>(&mut self, source: S, destination: D) pub fn rescale_ts<S, D>(&mut self, source: S, destination: D)
where S: Into<Rational>, where
D: Into<Rational> S: Into<Rational>,
D: Into<Rational>,
{ {
unsafe { unsafe {
av_packet_rescale_ts(self.as_mut_ptr(), source.into().into(), destination.into().into()); av_packet_rescale_ts(
self.as_mut_ptr(),
source.into().into(),
destination.into().into(),
);
} }
} }
@ -172,8 +177,7 @@ impl Packet {
unsafe { unsafe {
if self.0.data.is_null() { if self.0.data.is_null() {
None None
} } else {
else {
Some(slice::from_raw_parts(self.0.data, self.0.size as usize)) Some(slice::from_raw_parts(self.0.data, self.0.size as usize))
} }
} }
@ -184,8 +188,7 @@ impl Packet {
unsafe { unsafe {
if self.0.data.is_null() { if self.0.data.is_null() {
None None
} } else {
else {
Some(slice::from_raw_parts_mut(self.0.data, self.0.size as usize)) Some(slice::from_raw_parts_mut(self.0.data, self.0.size as usize))
} }
} }
@ -196,7 +199,7 @@ impl Packet {
unsafe { unsafe {
match av_read_frame(format.as_mut_ptr(), self.as_mut_ptr()) { match av_read_frame(format.as_mut_ptr(), self.as_mut_ptr()) {
0 => Ok(()), 0 => Ok(()),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -211,7 +214,7 @@ impl Packet {
match av_write_frame(format.as_mut_ptr(), self.as_ptr() as *mut _) { match av_write_frame(format.as_mut_ptr(), self.as_ptr() as *mut _) {
1 => Ok(true), 1 => Ok(true),
0 => Ok(false), 0 => Ok(false),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -226,7 +229,7 @@ impl Packet {
match av_interleaved_write_frame(format.as_mut_ptr(), self.as_ptr() as *mut _) { match av_interleaved_write_frame(format.as_mut_ptr(), self.as_ptr() as *mut _) {
1 => Ok(true), 1 => Ok(true),
0 => Ok(false), 0 => Ok(false),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -278,7 +281,11 @@ pub struct SideDataIter<'a> {
impl<'a> SideDataIter<'a> { impl<'a> SideDataIter<'a> {
pub fn new(ptr: *const AVPacket) -> Self { pub fn new(ptr: *const AVPacket) -> Self {
SideDataIter { ptr: ptr, cur: 0, _marker: PhantomData } SideDataIter {
ptr: ptr,
cur: 0,
_marker: PhantomData,
}
} }
} }
@ -289,10 +296,11 @@ impl<'a> Iterator for SideDataIter<'a> {
unsafe { unsafe {
if self.cur >= (*self.ptr).side_data_elems { if self.cur >= (*self.ptr).side_data_elems {
None None
} } else {
else {
self.cur += 1; self.cur += 1;
Some(SideData::wrap((*self.ptr).side_data.offset((self.cur - 1) as isize))) Some(SideData::wrap(
(*self.ptr).side_data.offset((self.cur - 1) as isize),
))
} }
} }
} }
@ -306,4 +314,4 @@ impl<'a> Iterator for SideDataIter<'a> {
} }
} }
impl<'a> ExactSizeIterator for SideDataIter<'a> { } impl<'a> ExactSizeIterator for SideDataIter<'a> {}

View File

@ -1,9 +1,9 @@
use std::marker::PhantomData; use std::marker::PhantomData;
use std::slice; use std::slice;
use ffi::*;
use ffi::AVPacketSideDataType::*;
use super::Packet; use super::Packet;
use ffi::AVPacketSideDataType::*;
use ffi::*;
#[derive(Eq, PartialEq, Copy, Clone, Debug)] #[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Type { pub enum Type {
@ -104,12 +104,15 @@ impl Into<AVPacketSideDataType> for Type {
pub struct SideData<'a> { pub struct SideData<'a> {
ptr: *mut AVPacketSideData, ptr: *mut AVPacketSideData,
_marker: PhantomData<&'a Packet> _marker: PhantomData<&'a Packet>,
} }
impl<'a> SideData<'a> { impl<'a> SideData<'a> {
pub unsafe fn wrap(ptr: *mut AVPacketSideData) -> Self { pub unsafe fn wrap(ptr: *mut AVPacketSideData) -> Self {
SideData { ptr: ptr, _marker: PhantomData } SideData {
ptr: ptr,
_marker: PhantomData,
}
} }
pub unsafe fn as_ptr(&self) -> *const AVPacketSideData { pub unsafe fn as_ptr(&self) -> *const AVPacketSideData {
@ -119,14 +122,10 @@ impl<'a> SideData<'a> {
impl<'a> SideData<'a> { impl<'a> SideData<'a> {
pub fn kind(&self) -> Type { pub fn kind(&self) -> Type {
unsafe { unsafe { Type::from((*self.as_ptr()).type_) }
Type::from((*self.as_ptr()).type_)
}
} }
pub fn data(&self) -> &[u8] { pub fn data(&self) -> &[u8] {
unsafe { unsafe { slice::from_raw_parts((*self.as_ptr()).data, (*self.as_ptr()).size as usize) }
slice::from_raw_parts((*self.as_ptr()).data, (*self.as_ptr()).size as usize)
}
} }
} }

View File

@ -1,19 +1,22 @@
use std::rc::Rc; use std::rc::Rc;
use super::{Context, Id};
use ffi::*; use ffi::*;
use media; use media;
use super::{Id, Context};
pub struct Parameters { pub struct Parameters {
ptr: *mut AVCodecParameters, ptr: *mut AVCodecParameters,
owner: Option<Rc<Drop>>, owner: Option<Rc<Drop>>,
} }
unsafe impl Send for Parameters { } unsafe impl Send for Parameters {}
impl Parameters { impl Parameters {
pub unsafe fn wrap(ptr: *mut AVCodecParameters, owner: Option<Rc<Drop>>) -> Self { pub unsafe fn wrap(ptr: *mut AVCodecParameters, owner: Option<Rc<Drop>>) -> Self {
Parameters { ptr: ptr, owner: owner } Parameters {
ptr: ptr,
owner: owner,
}
} }
pub unsafe fn as_ptr(&self) -> *const AVCodecParameters { pub unsafe fn as_ptr(&self) -> *const AVCodecParameters {
@ -28,20 +31,25 @@ impl Parameters {
impl Parameters { impl Parameters {
pub fn new() -> Self { pub fn new() -> Self {
unsafe { unsafe {
Parameters { ptr: avcodec_parameters_alloc(), owner: None } Parameters {
ptr: avcodec_parameters_alloc(),
owner: None,
}
} }
} }
pub fn medium(&self) -> media::Type { pub fn medium(&self) -> media::Type {
unsafe { unsafe { media::Type::from((*self.as_ptr()).codec_type) }
media::Type::from((*self.as_ptr()).codec_type)
}
} }
pub fn id(&self) -> Id { pub fn id(&self) -> Id {
unsafe { unsafe { Id::from((*self.as_ptr()).codec_id) }
Id::from((*self.as_ptr()).codec_id)
} }
}
impl Default for Parameters {
fn default() -> Self {
Self::new()
} }
} }

View File

@ -1,11 +1,11 @@
use std::marker::PhantomData;
use std::mem; use std::mem;
use std::slice; use std::slice;
use std::marker::PhantomData;
use libc::{c_int, size_t};
use ffi::*; use ffi::*;
use ::format; use format;
use ::Error; use libc::{c_int, size_t};
use Error;
pub struct Picture<'a> { pub struct Picture<'a> {
ptr: *mut AVPicture, ptr: *mut AVPicture,
@ -19,7 +19,12 @@ pub struct Picture<'a> {
} }
impl<'a> Picture<'a> { impl<'a> Picture<'a> {
pub unsafe fn wrap(ptr: *mut AVPicture, format: format::Pixel, width: u32, height: u32) -> Self { pub unsafe fn wrap(
ptr: *mut AVPicture,
format: format::Pixel,
width: u32,
height: u32,
) -> Self {
Picture { Picture {
ptr: ptr, ptr: ptr,
@ -28,7 +33,7 @@ impl<'a> Picture<'a> {
height: height, height: height,
_own: false, _own: false,
_marker: PhantomData _marker: PhantomData,
} }
} }
@ -46,7 +51,7 @@ impl<'a> Picture<'a> {
unsafe { unsafe {
match avpicture_get_size(format.into(), width as c_int, height as c_int) { match avpicture_get_size(format.into(), width as c_int, height as c_int) {
v if v >= 0 => Ok(v as usize), v if v >= 0 => Ok(v as usize),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -64,10 +69,10 @@ impl<'a> Picture<'a> {
height: height, height: height,
_own: true, _own: true,
_marker: PhantomData _marker: PhantomData,
}), }),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -86,18 +91,38 @@ impl<'a> Picture<'a> {
pub fn layout(&self, out: &mut [u8]) -> Result<usize, Error> { pub fn layout(&self, out: &mut [u8]) -> Result<usize, Error> {
unsafe { unsafe {
match avpicture_layout(self.ptr, self.format.into(), self.width as c_int, self.height as c_int, out.as_mut_ptr(), out.len() as c_int) { match avpicture_layout(
self.ptr,
self.format.into(),
self.width as c_int,
self.height as c_int,
out.as_mut_ptr(),
out.len() as c_int,
) {
s if s >= 0 => Ok(s as usize), s if s >= 0 => Ok(s as usize),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
pub fn layout_as(&self, format: format::Pixel, width: u32, height: u32, out: &mut [u8]) -> Result<usize, Error> { pub fn layout_as(
&self,
format: format::Pixel,
width: u32,
height: u32,
out: &mut [u8],
) -> Result<usize, Error> {
unsafe { unsafe {
match avpicture_layout(self.as_ptr(), format.into(), width as c_int, height as c_int, out.as_mut_ptr(), out.len() as c_int) { match avpicture_layout(
self.as_ptr(),
format.into(),
width as c_int,
height as c_int,
out.as_mut_ptr(),
out.len() as c_int,
) {
s if s >= 0 => Ok(s as usize), s if s >= 0 => Ok(s as usize),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -108,9 +133,15 @@ impl<'a> Picture<'a> {
} }
unsafe { unsafe {
match av_picture_crop(source.as_mut_ptr(), self.as_ptr(), self.format.into(), top as c_int, left as c_int) { match av_picture_crop(
source.as_mut_ptr(),
self.as_ptr(),
self.format.into(),
top as c_int,
left as c_int,
) {
0 => Ok(()), 0 => Ok(()),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -119,8 +150,16 @@ impl<'a> Picture<'a> {
let mut result = Vec::new(); let mut result = Vec::new();
unsafe { unsafe {
for (i, length) in (*self.as_ptr()).linesize.iter().take_while(|l| **l > 0).enumerate() { for (i, length) in (*self.as_ptr())
result.push(slice::from_raw_parts((*self.as_ptr()).data[i], (*length as usize) * (self.height as usize))) .linesize
.iter()
.take_while(|l| **l > 0)
.enumerate()
{
result.push(slice::from_raw_parts(
(*self.as_ptr()).data[i],
(*length as usize) * (self.height as usize),
))
} }
} }
@ -131,8 +170,16 @@ impl<'a> Picture<'a> {
let mut result = Vec::new(); let mut result = Vec::new();
unsafe { unsafe {
for (i, length) in (*self.as_ptr()).linesize.iter().take_while(|l| **l > 0).enumerate() { for (i, length) in (*self.as_ptr())
result.push(slice::from_raw_parts_mut((*self.as_ptr()).data[i], (*length as usize) * (self.height as usize))) .linesize
.iter()
.take_while(|l| **l > 0)
.enumerate()
{
result.push(slice::from_raw_parts_mut(
(*self.as_ptr()).data[i],
(*length as usize) * (self.height as usize),
))
} }
} }
@ -150,7 +197,13 @@ impl<'a> Clone for Picture<'a> {
fn clone_from(&mut self, source: &Self) { fn clone_from(&mut self, source: &Self) {
unsafe { unsafe {
av_picture_copy(self.as_mut_ptr(), source.as_ptr(), source.format.into(), source.width as c_int, source.height as c_int); av_picture_copy(
self.as_mut_ptr(),
source.as_ptr(),
source.format.into(),
source.width as c_int,
source.height as c_int,
);
} }
} }
} }

View File

@ -1,6 +1,6 @@
use libc::c_int;
use ffi::*;
use super::Id; use super::Id;
use ffi::*;
use libc::c_int;
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
@ -159,7 +159,7 @@ impl From<(Id, c_int)> for Profile {
FF_PROFILE_MPEG2_AAC_LOW => Profile::AAC(AAC::MPEG2Low), FF_PROFILE_MPEG2_AAC_LOW => Profile::AAC(AAC::MPEG2Low),
FF_PROFILE_MPEG2_AAC_HE => Profile::AAC(AAC::MPEG2HE), FF_PROFILE_MPEG2_AAC_HE => Profile::AAC(AAC::MPEG2HE),
_ => Profile::Unknown _ => Profile::Unknown,
}, },
Id::DTS => match value { Id::DTS => match value {
@ -220,14 +220,20 @@ impl From<(Id, c_int)> for Profile {
FF_PROFILE_MPEG4_MAIN => Profile::MPEG4(MPEG4::Main), FF_PROFILE_MPEG4_MAIN => Profile::MPEG4(MPEG4::Main),
FF_PROFILE_MPEG4_N_BIT => Profile::MPEG4(MPEG4::NBit), FF_PROFILE_MPEG4_N_BIT => Profile::MPEG4(MPEG4::NBit),
FF_PROFILE_MPEG4_SCALABLE_TEXTURE => Profile::MPEG4(MPEG4::ScalableTexture), FF_PROFILE_MPEG4_SCALABLE_TEXTURE => Profile::MPEG4(MPEG4::ScalableTexture),
FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION => Profile::MPEG4(MPEG4::SimpleFaceAnimation), FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION => {
FF_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE => Profile::MPEG4(MPEG4::BasicAnimatedTexture), Profile::MPEG4(MPEG4::SimpleFaceAnimation)
}
FF_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE => {
Profile::MPEG4(MPEG4::BasicAnimatedTexture)
}
FF_PROFILE_MPEG4_HYBRID => Profile::MPEG4(MPEG4::Hybrid), FF_PROFILE_MPEG4_HYBRID => Profile::MPEG4(MPEG4::Hybrid),
FF_PROFILE_MPEG4_ADVANCED_REAL_TIME => Profile::MPEG4(MPEG4::AdvancedRealTime), FF_PROFILE_MPEG4_ADVANCED_REAL_TIME => Profile::MPEG4(MPEG4::AdvancedRealTime),
FF_PROFILE_MPEG4_CORE_SCALABLE => Profile::MPEG4(MPEG4::CoreScalable), FF_PROFILE_MPEG4_CORE_SCALABLE => Profile::MPEG4(MPEG4::CoreScalable),
FF_PROFILE_MPEG4_ADVANCED_CODING => Profile::MPEG4(MPEG4::AdvancedCoding), FF_PROFILE_MPEG4_ADVANCED_CODING => Profile::MPEG4(MPEG4::AdvancedCoding),
FF_PROFILE_MPEG4_ADVANCED_CORE => Profile::MPEG4(MPEG4::AdvancedCore), FF_PROFILE_MPEG4_ADVANCED_CORE => Profile::MPEG4(MPEG4::AdvancedCore),
FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE => Profile::MPEG4(MPEG4::AdvancedScalableTexture), FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE => {
Profile::MPEG4(MPEG4::AdvancedScalableTexture)
}
FF_PROFILE_MPEG4_SIMPLE_STUDIO => Profile::MPEG4(MPEG4::SimpleStudio), FF_PROFILE_MPEG4_SIMPLE_STUDIO => Profile::MPEG4(MPEG4::SimpleStudio),
FF_PROFILE_MPEG4_ADVANCED_SIMPLE => Profile::MPEG4(MPEG4::AdvancedSimple), FF_PROFILE_MPEG4_ADVANCED_SIMPLE => Profile::MPEG4(MPEG4::AdvancedSimple),
@ -235,9 +241,15 @@ impl From<(Id, c_int)> for Profile {
}, },
Id::JPEG2000 => match value { Id::JPEG2000 => match value {
FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0 => Profile::JPEG2000(JPEG2000::CStreamRestriction0), FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0 => {
FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1 => Profile::JPEG2000(JPEG2000::CStreamRestriction1), Profile::JPEG2000(JPEG2000::CStreamRestriction0)
FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION => Profile::JPEG2000(JPEG2000::CStreamNoRestriction), }
FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1 => {
Profile::JPEG2000(JPEG2000::CStreamRestriction1)
}
FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION => {
Profile::JPEG2000(JPEG2000::CStreamNoRestriction)
}
FF_PROFILE_JPEG2000_DCINEMA_2K => Profile::JPEG2000(JPEG2000::DCinema2K), FF_PROFILE_JPEG2000_DCINEMA_2K => Profile::JPEG2000(JPEG2000::DCinema2K),
FF_PROFILE_JPEG2000_DCINEMA_4K => Profile::JPEG2000(JPEG2000::DCinema4K), FF_PROFILE_JPEG2000_DCINEMA_4K => Profile::JPEG2000(JPEG2000::DCinema4K),
@ -262,7 +274,7 @@ impl From<(Id, c_int)> for Profile {
_ => Profile::Unknown, _ => Profile::Unknown,
}, },
_ => Profile::Unknown _ => Profile::Unknown,
} }
} }
} }
@ -333,13 +345,21 @@ impl Into<c_int> for Profile {
Profile::MPEG4(MPEG4::CoreScalable) => FF_PROFILE_MPEG4_CORE_SCALABLE, Profile::MPEG4(MPEG4::CoreScalable) => FF_PROFILE_MPEG4_CORE_SCALABLE,
Profile::MPEG4(MPEG4::AdvancedCoding) => FF_PROFILE_MPEG4_ADVANCED_CODING, Profile::MPEG4(MPEG4::AdvancedCoding) => FF_PROFILE_MPEG4_ADVANCED_CODING,
Profile::MPEG4(MPEG4::AdvancedCore) => FF_PROFILE_MPEG4_ADVANCED_CORE, Profile::MPEG4(MPEG4::AdvancedCore) => FF_PROFILE_MPEG4_ADVANCED_CORE,
Profile::MPEG4(MPEG4::AdvancedScalableTexture) => FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE, Profile::MPEG4(MPEG4::AdvancedScalableTexture) => {
FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE
}
Profile::MPEG4(MPEG4::SimpleStudio) => FF_PROFILE_MPEG4_SIMPLE_STUDIO, Profile::MPEG4(MPEG4::SimpleStudio) => FF_PROFILE_MPEG4_SIMPLE_STUDIO,
Profile::MPEG4(MPEG4::AdvancedSimple) => FF_PROFILE_MPEG4_ADVANCED_SIMPLE, Profile::MPEG4(MPEG4::AdvancedSimple) => FF_PROFILE_MPEG4_ADVANCED_SIMPLE,
Profile::JPEG2000(JPEG2000::CStreamRestriction0) => FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, Profile::JPEG2000(JPEG2000::CStreamRestriction0) => {
Profile::JPEG2000(JPEG2000::CStreamRestriction1) => FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0
Profile::JPEG2000(JPEG2000::CStreamNoRestriction) => FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, }
Profile::JPEG2000(JPEG2000::CStreamRestriction1) => {
FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1
}
Profile::JPEG2000(JPEG2000::CStreamNoRestriction) => {
FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION
}
Profile::JPEG2000(JPEG2000::DCinema2K) => FF_PROFILE_JPEG2000_DCINEMA_2K, Profile::JPEG2000(JPEG2000::DCinema2K) => FF_PROFILE_JPEG2000_DCINEMA_2K,
Profile::JPEG2000(JPEG2000::DCinema4K) => FF_PROFILE_JPEG2000_DCINEMA_4K, Profile::JPEG2000(JPEG2000::DCinema4K) => FF_PROFILE_JPEG2000_DCINEMA_4K,

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
bitflags! { bitflags! {
pub struct Flags: c_int { pub struct Flags: c_int {

View File

@ -2,17 +2,17 @@ pub mod flag;
pub use self::flag::Flags; pub use self::flag::Flags;
mod rect; mod rect;
pub use self::rect::{Rect, Bitmap, Text, Ass}; pub use self::rect::{Ass, Bitmap, Rect, Text};
mod rect_mut; mod rect_mut;
pub use self::rect_mut::{RectMut, BitmapMut, TextMut, AssMut}; pub use self::rect_mut::{AssMut, BitmapMut, RectMut, TextMut};
use std::marker::PhantomData; use std::marker::PhantomData;
use std::mem; use std::mem;
use libc::{c_uint, uint32_t, size_t};
use ffi::*;
use ffi::AVSubtitleType::*; use ffi::AVSubtitleType::*;
use ffi::*;
use libc::{c_uint, size_t, uint32_t};
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Type { pub enum Type {
@ -28,7 +28,7 @@ impl From<AVSubtitleType> for Type {
SUBTITLE_NONE => Type::None, SUBTITLE_NONE => Type::None,
SUBTITLE_BITMAP => Type::Bitmap, SUBTITLE_BITMAP => Type::Bitmap,
SUBTITLE_TEXT => Type::Text, SUBTITLE_TEXT => Type::Text,
SUBTITLE_ASS => Type::Ass SUBTITLE_ASS => Type::Ass,
} }
} }
} }
@ -39,7 +39,7 @@ impl Into<AVSubtitleType> for Type {
Type::None => SUBTITLE_NONE, Type::None => SUBTITLE_NONE,
Type::Bitmap => SUBTITLE_BITMAP, Type::Bitmap => SUBTITLE_BITMAP,
Type::Text => SUBTITLE_TEXT, Type::Text => SUBTITLE_TEXT,
Type::Ass => SUBTITLE_ASS Type::Ass => SUBTITLE_ASS,
} }
} }
} }
@ -58,15 +58,13 @@ impl Subtitle {
impl Subtitle { impl Subtitle {
pub fn new() -> Self { pub fn new() -> Self {
unsafe { unsafe { Subtitle(mem::zeroed()) }
Subtitle(mem::zeroed())
}
} }
pub fn pts(&self) -> Option<i64> { pub fn pts(&self) -> Option<i64> {
match self.0.pts { match self.0.pts {
AV_NOPTS_VALUE => None, AV_NOPTS_VALUE => None,
pts => Some(pts) pts => Some(pts),
} }
} }
@ -101,11 +99,13 @@ impl Subtitle {
pub fn add_rect(&mut self, kind: Type) -> RectMut { pub fn add_rect(&mut self, kind: Type) -> RectMut {
unsafe { unsafe {
self.0.num_rects += 1; self.0.num_rects += 1;
self.0.rects = av_realloc(self.0.rects as *mut _, self.0.rects = av_realloc(
(mem::size_of::<*const AVSubtitleRect>() * self.0.num_rects as usize) as size_t) self.0.rects as *mut _,
as *mut _; (mem::size_of::<*const AVSubtitleRect>() * self.0.num_rects as usize) as size_t,
) as *mut _;
let rect = av_mallocz(mem::size_of::<AVSubtitleRect>() as size_t) as *mut AVSubtitleRect; let rect =
av_mallocz(mem::size_of::<AVSubtitleRect>() as size_t) as *mut AVSubtitleRect;
(*rect).type_ = kind.into(); (*rect).type_ = kind.into();
*self.0.rects.offset((self.0.num_rects - 1) as isize) = rect; *self.0.rects.offset((self.0.num_rects - 1) as isize) = rect;
@ -115,6 +115,12 @@ impl Subtitle {
} }
} }
impl Default for Subtitle {
fn default() -> Self {
Self::new()
}
}
pub struct RectIter<'a> { pub struct RectIter<'a> {
ptr: *const AVSubtitle, ptr: *const AVSubtitle,
cur: c_uint, cur: c_uint,
@ -124,7 +130,11 @@ pub struct RectIter<'a> {
impl<'a> RectIter<'a> { impl<'a> RectIter<'a> {
pub fn new(ptr: *const AVSubtitle) -> Self { pub fn new(ptr: *const AVSubtitle) -> Self {
RectIter { ptr: ptr, cur: 0, _marker: PhantomData } RectIter {
ptr: ptr,
cur: 0,
_marker: PhantomData,
}
} }
} }
@ -135,10 +145,11 @@ impl<'a> Iterator for RectIter<'a> {
unsafe { unsafe {
if self.cur >= (*self.ptr).num_rects { if self.cur >= (*self.ptr).num_rects {
None None
} } else {
else {
self.cur += 1; self.cur += 1;
Some(Rect::wrap(*(*self.ptr).rects.offset((self.cur - 1) as isize))) Some(Rect::wrap(*(*self.ptr)
.rects
.offset((self.cur - 1) as isize)))
} }
} }
} }
@ -152,7 +163,7 @@ impl<'a> Iterator for RectIter<'a> {
} }
} }
impl<'a> ExactSizeIterator for RectIter<'a> { } impl<'a> ExactSizeIterator for RectIter<'a> {}
pub struct RectMutIter<'a> { pub struct RectMutIter<'a> {
ptr: *mut AVSubtitle, ptr: *mut AVSubtitle,
@ -163,7 +174,11 @@ pub struct RectMutIter<'a> {
impl<'a> RectMutIter<'a> { impl<'a> RectMutIter<'a> {
pub fn new(ptr: *mut AVSubtitle) -> Self { pub fn new(ptr: *mut AVSubtitle) -> Self {
RectMutIter { ptr: ptr, cur: 0, _marker: PhantomData } RectMutIter {
ptr: ptr,
cur: 0,
_marker: PhantomData,
}
} }
} }
@ -174,10 +189,11 @@ impl<'a> Iterator for RectMutIter<'a> {
unsafe { unsafe {
if self.cur >= (*self.ptr).num_rects { if self.cur >= (*self.ptr).num_rects {
None None
} } else {
else {
self.cur += 1; self.cur += 1;
Some(RectMut::wrap(*(*self.ptr).rects.offset((self.cur - 1) as isize))) Some(RectMut::wrap(*(*self.ptr)
.rects
.offset((self.cur - 1) as isize)))
} }
} }
} }
@ -191,4 +207,4 @@ impl<'a> Iterator for RectMutIter<'a> {
} }
} }
impl<'a> ExactSizeIterator for RectMutIter<'a> { } impl<'a> ExactSizeIterator for RectMutIter<'a> {}

View File

@ -1,10 +1,10 @@
use std::marker::PhantomData;
use std::ffi::CStr; use std::ffi::CStr;
use std::marker::PhantomData;
use std::str::from_utf8_unchecked; use std::str::from_utf8_unchecked;
use super::{Flags, Type};
use ffi::*; use ffi::*;
use super::{Type, Flags}; use {format, Picture};
use ::{format, Picture};
pub enum Rect<'a> { pub enum Rect<'a> {
None(*const AVSubtitleRect), None(*const AVSubtitleRect),
@ -19,16 +19,16 @@ impl<'a> Rect<'a> {
Type::None => Rect::None(ptr), Type::None => Rect::None(ptr),
Type::Bitmap => Rect::Bitmap(Bitmap::wrap(ptr)), Type::Bitmap => Rect::Bitmap(Bitmap::wrap(ptr)),
Type::Text => Rect::Text(Text::wrap(ptr)), Type::Text => Rect::Text(Text::wrap(ptr)),
Type::Ass => Rect::Ass(Ass::wrap(ptr)) Type::Ass => Rect::Ass(Ass::wrap(ptr)),
} }
} }
pub unsafe fn as_ptr(&self) -> *const AVSubtitleRect { pub unsafe fn as_ptr(&self) -> *const AVSubtitleRect {
match self { match *self {
&Rect::None(ptr) => ptr, Rect::None(ptr) => ptr,
&Rect::Bitmap(ref b) => b.as_ptr(), Rect::Bitmap(ref b) => b.as_ptr(),
&Rect::Text(ref t) => t.as_ptr(), Rect::Text(ref t) => t.as_ptr(),
&Rect::Ass(ref a) => a.as_ptr() Rect::Ass(ref a) => a.as_ptr(),
} }
} }
} }
@ -36,11 +36,11 @@ impl<'a> Rect<'a> {
impl<'a> Rect<'a> { impl<'a> Rect<'a> {
pub fn flags(&self) -> Flags { pub fn flags(&self) -> Flags {
unsafe { unsafe {
Flags::from_bits_truncate(match self { Flags::from_bits_truncate(match *self {
&Rect::None(ptr) => (*ptr).flags, Rect::None(ptr) => (*ptr).flags,
&Rect::Bitmap(ref b) => (*b.as_ptr()).flags, Rect::Bitmap(ref b) => (*b.as_ptr()).flags,
&Rect::Text(ref t) => (*t.as_ptr()).flags, Rect::Text(ref t) => (*t.as_ptr()).flags,
&Rect::Ass(ref a) => (*a.as_ptr()).flags Rect::Ass(ref a) => (*a.as_ptr()).flags,
}) })
} }
} }
@ -54,7 +54,10 @@ pub struct Bitmap<'a> {
impl<'a> Bitmap<'a> { impl<'a> Bitmap<'a> {
pub unsafe fn wrap(ptr: *const AVSubtitleRect) -> Self { pub unsafe fn wrap(ptr: *const AVSubtitleRect) -> Self {
Bitmap { ptr: ptr, _marker: PhantomData } Bitmap {
ptr: ptr,
_marker: PhantomData,
}
} }
pub unsafe fn as_ptr(&self) -> *const AVSubtitleRect { pub unsafe fn as_ptr(&self) -> *const AVSubtitleRect {
@ -64,39 +67,34 @@ impl<'a> Bitmap<'a> {
impl<'a> Bitmap<'a> { impl<'a> Bitmap<'a> {
pub fn x(&self) -> usize { pub fn x(&self) -> usize {
unsafe { unsafe { (*self.as_ptr()).x as usize }
(*self.as_ptr()).x as usize
}
} }
pub fn y(&self) -> usize { pub fn y(&self) -> usize {
unsafe { unsafe { (*self.as_ptr()).y as usize }
(*self.as_ptr()).y as usize
}
} }
pub fn width(&self) -> u32 { pub fn width(&self) -> u32 {
unsafe { unsafe { (*self.as_ptr()).w as u32 }
(*self.as_ptr()).w as u32
}
} }
pub fn height(&self) -> u32 { pub fn height(&self) -> u32 {
unsafe { unsafe { (*self.as_ptr()).h as u32 }
(*self.as_ptr()).h as u32
}
} }
pub fn colors(&self) -> usize { pub fn colors(&self) -> usize {
unsafe { unsafe { (*self.as_ptr()).nb_colors as usize }
(*self.as_ptr()).nb_colors as usize
}
} }
// XXX: must split Picture and PictureMut // XXX: must split Picture and PictureMut
pub fn picture(&self, format: format::Pixel) -> Picture<'a> { pub fn picture(&self, format: format::Pixel) -> Picture<'a> {
unsafe { unsafe {
Picture::wrap(&(*self.as_ptr()).pict as *const _ as *mut _, format, (*self.as_ptr()).w as u32, (*self.as_ptr()).h as u32) Picture::wrap(
&(*self.as_ptr()).pict as *const _ as *mut _,
format,
(*self.as_ptr()).w as u32,
(*self.as_ptr()).h as u32,
)
} }
} }
} }
@ -109,7 +107,10 @@ pub struct Text<'a> {
impl<'a> Text<'a> { impl<'a> Text<'a> {
pub unsafe fn wrap(ptr: *const AVSubtitleRect) -> Self { pub unsafe fn wrap(ptr: *const AVSubtitleRect) -> Self {
Text { ptr: ptr, _marker: PhantomData } Text {
ptr: ptr,
_marker: PhantomData,
}
} }
pub unsafe fn as_ptr(&self) -> *const AVSubtitleRect { pub unsafe fn as_ptr(&self) -> *const AVSubtitleRect {
@ -119,9 +120,7 @@ impl<'a> Text<'a> {
impl<'a> Text<'a> { impl<'a> Text<'a> {
pub fn get(&self) -> &str { pub fn get(&self) -> &str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).text).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).text).to_bytes())
}
} }
} }
@ -133,7 +132,10 @@ pub struct Ass<'a> {
impl<'a> Ass<'a> { impl<'a> Ass<'a> {
pub unsafe fn wrap(ptr: *const AVSubtitleRect) -> Self { pub unsafe fn wrap(ptr: *const AVSubtitleRect) -> Self {
Ass { ptr: ptr, _marker: PhantomData } Ass {
ptr: ptr,
_marker: PhantomData,
}
} }
pub unsafe fn as_ptr(&self) -> *const AVSubtitleRect { pub unsafe fn as_ptr(&self) -> *const AVSubtitleRect {
@ -143,8 +145,6 @@ impl<'a> Ass<'a> {
impl<'a> Ass<'a> { impl<'a> Ass<'a> {
pub fn get(&self) -> &str { pub fn get(&self) -> &str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).ass).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).ass).to_bytes())
}
} }
} }

View File

@ -1,9 +1,9 @@
use std::ops::Deref;
use std::ffi::CString; use std::ffi::CString;
use std::ops::Deref;
use libc::c_int; use super::{Ass, Bitmap, Flags, Text, Type};
use ffi::*; use ffi::*;
use super::{Type, Flags, Bitmap, Text, Ass}; use libc::c_int;
pub enum RectMut<'a> { pub enum RectMut<'a> {
None(*mut AVSubtitleRect), None(*mut AVSubtitleRect),
@ -18,25 +18,25 @@ impl<'a> RectMut<'a> {
Type::None => RectMut::None(ptr), Type::None => RectMut::None(ptr),
Type::Bitmap => RectMut::Bitmap(BitmapMut::wrap(ptr)), Type::Bitmap => RectMut::Bitmap(BitmapMut::wrap(ptr)),
Type::Text => RectMut::Text(TextMut::wrap(ptr)), Type::Text => RectMut::Text(TextMut::wrap(ptr)),
Type::Ass => RectMut::Ass(AssMut::wrap(ptr)) Type::Ass => RectMut::Ass(AssMut::wrap(ptr)),
} }
} }
pub unsafe fn as_ptr(&self) -> *const AVSubtitleRect { pub unsafe fn as_ptr(&self) -> *const AVSubtitleRect {
match self { match *self {
&RectMut::None(ptr) => ptr as *const _, RectMut::None(ptr) => ptr as *const _,
&RectMut::Bitmap(ref b) => b.as_ptr(), RectMut::Bitmap(ref b) => b.as_ptr(),
&RectMut::Text(ref t) => t.as_ptr(), RectMut::Text(ref t) => t.as_ptr(),
&RectMut::Ass(ref a) => a.as_ptr() RectMut::Ass(ref a) => a.as_ptr(),
} }
} }
pub unsafe fn as_mut_ptr(&mut self) -> *mut AVSubtitleRect { pub unsafe fn as_mut_ptr(&mut self) -> *mut AVSubtitleRect {
match self { match *self {
&mut RectMut::None(ptr) => ptr, RectMut::None(ptr) => ptr,
&mut RectMut::Bitmap(ref mut b) => b.as_mut_ptr(), RectMut::Bitmap(ref mut b) => b.as_mut_ptr(),
&mut RectMut::Text(ref mut t) => t.as_mut_ptr(), RectMut::Text(ref mut t) => t.as_mut_ptr(),
&mut RectMut::Ass(ref mut a) => a.as_mut_ptr() RectMut::Ass(ref mut a) => a.as_mut_ptr(),
} }
} }
} }
@ -44,11 +44,11 @@ impl<'a> RectMut<'a> {
impl<'a> RectMut<'a> { impl<'a> RectMut<'a> {
pub fn flags(&self) -> Flags { pub fn flags(&self) -> Flags {
unsafe { unsafe {
Flags::from_bits_truncate(match self { Flags::from_bits_truncate(match *self {
&RectMut::None(ptr) => (*ptr).flags, RectMut::None(ptr) => (*ptr).flags,
&RectMut::Bitmap(ref b) => (*b.as_ptr()).flags, RectMut::Bitmap(ref b) => (*b.as_ptr()).flags,
&RectMut::Text(ref t) => (*t.as_ptr()).flags, RectMut::Text(ref t) => (*t.as_ptr()).flags,
&RectMut::Ass(ref a) => (*a.as_ptr()).flags RectMut::Ass(ref a) => (*a.as_ptr()).flags,
}) })
} }
} }
@ -60,7 +60,9 @@ pub struct BitmapMut<'a> {
impl<'a> BitmapMut<'a> { impl<'a> BitmapMut<'a> {
pub unsafe fn wrap(ptr: *mut AVSubtitleRect) -> Self { pub unsafe fn wrap(ptr: *mut AVSubtitleRect) -> Self {
BitmapMut { immutable: Bitmap::wrap(ptr as *const _) } BitmapMut {
immutable: Bitmap::wrap(ptr as *const _),
}
} }
pub unsafe fn as_mut_ptr(&mut self) -> *mut AVSubtitleRect { pub unsafe fn as_mut_ptr(&mut self) -> *mut AVSubtitleRect {
@ -114,7 +116,9 @@ pub struct TextMut<'a> {
impl<'a> TextMut<'a> { impl<'a> TextMut<'a> {
pub unsafe fn wrap(ptr: *mut AVSubtitleRect) -> Self { pub unsafe fn wrap(ptr: *mut AVSubtitleRect) -> Self {
TextMut { immutable: Text::wrap(ptr as *const _) } TextMut {
immutable: Text::wrap(ptr as *const _),
}
} }
pub unsafe fn as_mut_ptr(&mut self) -> *mut AVSubtitleRect { pub unsafe fn as_mut_ptr(&mut self) -> *mut AVSubtitleRect {
@ -146,7 +150,9 @@ pub struct AssMut<'a> {
impl<'a> AssMut<'a> { impl<'a> AssMut<'a> {
pub unsafe fn wrap(ptr: *mut AVSubtitleRect) -> Self { pub unsafe fn wrap(ptr: *mut AVSubtitleRect) -> Self {
AssMut { immutable: Ass::wrap(ptr) } AssMut {
immutable: Ass::wrap(ptr),
}
} }
pub unsafe fn as_mut_ptr(&mut self) -> *mut AVSubtitleRect { pub unsafe fn as_mut_ptr(&mut self) -> *mut AVSubtitleRect {

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub struct Config { pub struct Config {
@ -10,15 +10,24 @@ pub struct Config {
impl Config { impl Config {
pub fn kind(value: Type) -> Self { pub fn kind(value: Type) -> Self {
Config { kind: value, .. Default::default() } Config {
kind: value,
..Default::default()
}
} }
pub fn count(value: usize) -> Self { pub fn count(value: usize) -> Self {
Config { count: value, .. Default::default() } Config {
count: value,
..Default::default()
}
} }
pub fn safe(value: bool) -> Self { pub fn safe(value: bool) -> Self {
Config { safe: value, .. Default::default() } Config {
safe: value,
..Default::default()
}
} }
} }
@ -55,7 +64,7 @@ impl Into<c_int> for Type {
match self { match self {
Type::None => 0, Type::None => 0,
Type::Frame => FF_THREAD_FRAME, Type::Frame => FF_THREAD_FRAME,
Type::Slice => FF_THREAD_SLICE Type::Slice => FF_THREAD_SLICE,
} }
} }
} }

View File

@ -1,6 +1,6 @@
use ::Codec;
use codec::{Id, Audio, Video};
use super::{decoder, encoder}; use super::{decoder, encoder};
use codec::{Audio, Id, Video};
use Codec;
pub trait Decoder { pub trait Decoder {
fn decoder(self) -> Option<Codec>; fn decoder(self) -> Option<Codec>;
@ -22,8 +22,7 @@ impl Decoder for Codec {
fn decoder(self) -> Option<Codec> { fn decoder(self) -> Option<Codec> {
if self.is_decoder() { if self.is_decoder() {
Some(self) Some(self)
} } else {
else {
None None
} }
} }
@ -38,9 +37,8 @@ impl Decoder for Option<Codec> {
impl Decoder for Audio { impl Decoder for Audio {
fn decoder(self) -> Option<Codec> { fn decoder(self) -> Option<Codec> {
if self.is_decoder() { if self.is_decoder() {
Some(*&*self) Some(*self)
} } else {
else {
None None
} }
} }
@ -49,9 +47,8 @@ impl Decoder for Audio {
impl Decoder for Video { impl Decoder for Video {
fn decoder(self) -> Option<Codec> { fn decoder(self) -> Option<Codec> {
if self.is_decoder() { if self.is_decoder() {
Some(*&*self) Some(*self)
} } else {
else {
None None
} }
} }
@ -77,8 +74,7 @@ impl Encoder for Codec {
fn encoder(self) -> Option<Codec> { fn encoder(self) -> Option<Codec> {
if self.is_encoder() { if self.is_encoder() {
Some(self) Some(self)
} } else {
else {
None None
} }
} }
@ -93,9 +89,8 @@ impl Encoder for Option<Codec> {
impl Encoder for Audio { impl Encoder for Audio {
fn encoder(self) -> Option<Codec> { fn encoder(self) -> Option<Codec> {
if self.is_encoder() { if self.is_encoder() {
Some(*&*self) Some(*self)
} } else {
else {
None None
} }
} }
@ -104,9 +99,8 @@ impl Encoder for Audio {
impl Encoder for Video { impl Encoder for Video {
fn encoder(self) -> Option<Codec> { fn encoder(self) -> Option<Codec> {
if self.is_encoder() { if self.is_encoder() {
Some(*&*self) Some(*self)
} } else {
else {
None None
} }
} }

View File

@ -1,8 +1,8 @@
use std::ops::Deref; use std::ops::Deref;
use {Rational, format};
use super::codec::Codec; use super::codec::Codec;
use ffi::*; use ffi::*;
use {format, Rational};
#[derive(PartialEq, Eq, Copy, Clone)] #[derive(PartialEq, Eq, Copy, Clone)]
pub struct Video { pub struct Video {
@ -11,9 +11,7 @@ pub struct Video {
impl Video { impl Video {
pub unsafe fn new(codec: Codec) -> Video { pub unsafe fn new(codec: Codec) -> Video {
Video { Video { codec: codec }
codec: codec,
}
} }
} }
@ -22,8 +20,7 @@ impl Video {
unsafe { unsafe {
if (*self.codec.as_ptr()).supported_framerates.is_null() { if (*self.codec.as_ptr()).supported_framerates.is_null() {
None None
} } else {
else {
Some(RateIter::new((*self.codec.as_ptr()).supported_framerates)) Some(RateIter::new((*self.codec.as_ptr()).supported_framerates))
} }
} }
@ -33,8 +30,7 @@ impl Video {
unsafe { unsafe {
if (*self.codec.as_ptr()).pix_fmts.is_null() { if (*self.codec.as_ptr()).pix_fmts.is_null() {
None None
} } else {
else {
Some(FormatIter::new((*self.codec.as_ptr()).pix_fmts)) Some(FormatIter::new((*self.codec.as_ptr()).pix_fmts))
} }
} }

View File

@ -1,17 +1,15 @@
use std::ptr;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::ptr;
use device;
use ffi::*; use ffi::*;
use ::Error; use format::context::common::Context;
use ::format::context::common::Context;
use ::device;
use libc::c_int; use libc::c_int;
use Error;
impl Context { impl Context {
pub fn devices(&self) -> Result<DeviceIter, Error> { pub fn devices(&self) -> Result<DeviceIter, Error> {
unsafe { unsafe { DeviceIter::wrap(self.as_ptr()) }
DeviceIter::wrap(self.as_ptr())
}
} }
} }
@ -27,20 +25,20 @@ impl<'a> DeviceIter<'a> {
let mut ptr: *mut AVDeviceInfoList = ptr::null_mut(); let mut ptr: *mut AVDeviceInfoList = ptr::null_mut();
match avdevice_list_devices(ctx as *mut _, &mut ptr) { match avdevice_list_devices(ctx as *mut _, &mut ptr) {
n if n < 0 => n if n < 0 => Err(Error::from(n)),
Err(Error::from(n)),
_ => _ => Ok(DeviceIter {
Ok(DeviceIter { ptr: ptr, cur: 0, _marker: PhantomData }) ptr: ptr,
cur: 0,
_marker: PhantomData,
}),
} }
} }
} }
impl<'a> DeviceIter<'a> { impl<'a> DeviceIter<'a> {
pub fn default(&self) -> usize { pub fn default(&self) -> usize {
unsafe { unsafe { (*self.ptr).default_device as usize }
(*self.ptr).default_device as usize
}
} }
} }
@ -59,10 +57,11 @@ impl<'a> Iterator for DeviceIter<'a> {
unsafe { unsafe {
if self.cur >= (*self.ptr).nb_devices { if self.cur >= (*self.ptr).nb_devices {
None None
} } else {
else {
self.cur += 1; self.cur += 1;
Some(device::Info::wrap(*(*self.ptr).devices.offset((self.cur - 1) as isize))) Some(device::Info::wrap(*(*self.ptr)
.devices
.offset((self.cur - 1) as isize)))
} }
} }
} }
@ -76,4 +75,4 @@ impl<'a> Iterator for DeviceIter<'a> {
} }
} }
impl<'a> ExactSizeIterator for DeviceIter<'a> { } impl<'a> ExactSizeIterator for DeviceIter<'a> {}

View File

@ -1,8 +1,8 @@
use std::ptr; use std::ptr;
use ffi::*; use ffi::*;
use ::format; use format;
use ::Format; use Format;
pub struct AudioIter(*mut AVInputFormat); pub struct AudioIter(*mut AVInputFormat);
@ -15,8 +15,7 @@ impl Iterator for AudioIter {
if ptr.is_null() && !self.0.is_null() { if ptr.is_null() && !self.0.is_null() {
None None
} } else {
else {
self.0 = ptr; self.0 = ptr;
Some(Format::Input(format::Input::wrap(ptr))) Some(Format::Input(format::Input::wrap(ptr)))
@ -40,8 +39,7 @@ impl Iterator for VideoIter {
if ptr.is_null() && !self.0.is_null() { if ptr.is_null() && !self.0.is_null() {
None None
} } else {
else {
self.0 = ptr; self.0 = ptr;
Some(Format::Input(format::Input::wrap(ptr))) Some(Format::Input(format::Input::wrap(ptr)))

View File

@ -1,10 +1,10 @@
pub mod extensions;
pub mod input; pub mod input;
pub mod output; pub mod output;
pub mod extensions;
use std::ffi::CStr; use std::ffi::CStr;
use std::str::from_utf8_unchecked;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::str::from_utf8_unchecked;
use ffi::*; use ffi::*;
@ -16,7 +16,10 @@ pub struct Info<'a> {
impl<'a> Info<'a> { impl<'a> Info<'a> {
pub unsafe fn wrap(ptr: *mut AVDeviceInfo) -> Self { pub unsafe fn wrap(ptr: *mut AVDeviceInfo) -> Self {
Info { ptr: ptr, _marker: PhantomData } Info {
ptr: ptr,
_marker: PhantomData,
}
} }
pub unsafe fn as_ptr(&self) -> *const AVDeviceInfo { pub unsafe fn as_ptr(&self) -> *const AVDeviceInfo {
@ -30,9 +33,7 @@ impl<'a> Info<'a> {
impl<'a> Info<'a> { impl<'a> Info<'a> {
pub fn name(&self) -> &str { pub fn name(&self) -> &str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).device_name).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).device_name).to_bytes())
}
} }
pub fn description(&self) -> &str { pub fn description(&self) -> &str {
@ -49,19 +50,13 @@ pub fn register_all() {
} }
pub fn version() -> u32 { pub fn version() -> u32 {
unsafe { unsafe { avdevice_version() }
avdevice_version()
}
} }
pub fn configuration() -> &'static str { pub fn configuration() -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(avdevice_configuration()).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(avdevice_configuration()).to_bytes())
}
} }
pub fn license() -> &'static str { pub fn license() -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(avdevice_license()).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(avdevice_license()).to_bytes())
}
} }

View File

@ -1,8 +1,8 @@
use std::ptr; use std::ptr;
use ffi::*; use ffi::*;
use ::format; use format;
use ::Format; use Format;
pub struct AudioIter(*mut AVOutputFormat); pub struct AudioIter(*mut AVOutputFormat);
@ -15,8 +15,7 @@ impl Iterator for AudioIter {
if ptr.is_null() && !self.0.is_null() { if ptr.is_null() && !self.0.is_null() {
None None
} } else {
else {
self.0 = ptr; self.0 = ptr;
Some(Format::Output(format::Output::wrap(ptr))) Some(Format::Output(format::Output::wrap(ptr)))
@ -40,8 +39,7 @@ impl Iterator for VideoIter {
if ptr.is_null() && !self.0.is_null() { if ptr.is_null() && !self.0.is_null() {
None None
} } else {
else {
self.0 = ptr; self.0 = ptr;
Some(Format::Output(format::Output::wrap(ptr))) Some(Format::Output(format::Output::wrap(ptr)))

View File

@ -1,9 +1,9 @@
use std::marker::PhantomData; use std::marker::PhantomData;
use super::{Sink, Source};
use ffi::*; use ffi::*;
use libc::c_void; use libc::c_void;
use ::{option, format, ChannelLayout}; use {format, option, ChannelLayout};
use super::{Source, Sink};
pub struct Context<'a> { pub struct Context<'a> {
ptr: *mut AVFilterContext, ptr: *mut AVFilterContext,
@ -13,7 +13,10 @@ pub struct Context<'a> {
impl<'a> Context<'a> { impl<'a> Context<'a> {
pub unsafe fn wrap(ptr: *mut AVFilterContext) -> Self { pub unsafe fn wrap(ptr: *mut AVFilterContext) -> Self {
Context { ptr: ptr, _marker: PhantomData } Context {
ptr: ptr,
_marker: PhantomData,
}
} }
pub unsafe fn as_ptr(&self) -> *const AVFilterContext { pub unsafe fn as_ptr(&self) -> *const AVFilterContext {
@ -27,15 +30,11 @@ impl<'a> Context<'a> {
impl<'a> Context<'a> { impl<'a> Context<'a> {
pub fn source(&'a mut self) -> Source<'a> { pub fn source(&'a mut self) -> Source<'a> {
unsafe { unsafe { Source::wrap(self) }
Source::wrap(self)
}
} }
pub fn sink(&'a mut self) -> Sink<'a> { pub fn sink(&'a mut self) -> Sink<'a> {
unsafe { unsafe { Sink::wrap(self) }
Sink::wrap(self)
}
} }
pub fn set_pixel_format(&mut self, value: format::Pixel) { pub fn set_pixel_format(&mut self, value: format::Pixel) {
@ -47,7 +46,7 @@ impl<'a> Context<'a> {
} }
pub fn set_sample_rate(&mut self, value: u32) { pub fn set_sample_rate(&mut self, value: u32) {
let _ = option::Settable::set(self, "sample_rates", &(value as i64)); let _ = option::Settable::set(self, "sample_rates", &i64::from(value));
} }
pub fn set_channel_layout(&mut self, value: ChannelLayout) { pub fn set_channel_layout(&mut self, value: ChannelLayout) {
@ -65,4 +64,4 @@ unsafe impl<'a> option::Target for Context<'a> {
} }
} }
impl<'a> option::Settable for Context<'a> { } impl<'a> option::Settable for Context<'a> {}

View File

@ -1,7 +1,7 @@
use super::Context;
use ffi::*; use ffi::*;
use libc::c_int; use libc::c_int;
use ::{Frame, Error}; use {Error, Frame};
use super::Context;
pub struct Sink<'a> { pub struct Sink<'a> {
ctx: &'a mut Context<'a>, ctx: &'a mut Context<'a>,
@ -25,7 +25,11 @@ impl<'a> Sink<'a> {
pub fn samples(&mut self, frame: &mut Frame, samples: usize) -> Result<(), Error> { pub fn samples(&mut self, frame: &mut Frame, samples: usize) -> Result<(), Error> {
unsafe { unsafe {
match av_buffersink_get_samples(self.ctx.as_mut_ptr(), frame.as_mut_ptr(), samples as c_int) { match av_buffersink_get_samples(
self.ctx.as_mut_ptr(),
frame.as_mut_ptr(),
samples as c_int,
) {
n if n >= 0 => Ok(()), n if n >= 0 => Ok(()),
e => Err(Error::from(e)), e => Err(Error::from(e)),
} }

View File

@ -1,8 +1,8 @@
use std::ptr; use std::ptr;
use ffi::*;
use ::{Error, Frame};
use super::Context; use super::Context;
use ffi::*;
use {Error, Frame};
pub struct Source<'a> { pub struct Source<'a> {
ctx: &'a mut Context<'a>, ctx: &'a mut Context<'a>,
@ -16,9 +16,7 @@ impl<'a> Source<'a> {
impl<'a> Source<'a> { impl<'a> Source<'a> {
pub fn failed_requests(&self) -> usize { pub fn failed_requests(&self) -> usize {
unsafe { unsafe { av_buffersrc_get_nb_failed_requests(self.ctx.as_ptr() as *mut _) as usize }
av_buffersrc_get_nb_failed_requests(self.ctx.as_ptr() as *mut _) as usize
}
} }
pub fn add(&mut self, frame: &Frame) -> Result<(), Error> { pub fn add(&mut self, frame: &Frame) -> Result<(), Error> {
@ -31,8 +29,6 @@ impl<'a> Source<'a> {
} }
pub fn flush(&mut self) -> Result<(), Error> { pub fn flush(&mut self) -> Result<(), Error> {
unsafe { unsafe { self.add(&Frame::wrap(ptr::null_mut())) }
self.add(&Frame::wrap(ptr::null_mut()))
}
} }
} }

View File

@ -1,9 +1,9 @@
use std::ffi::CStr; use std::ffi::CStr;
use std::str::from_utf8_unchecked;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::str::from_utf8_unchecked;
use super::{Flags, Pad};
use ffi::*; use ffi::*;
use super::{Pad, Flags};
pub struct Filter { pub struct Filter {
ptr: *mut AVFilter, ptr: *mut AVFilter,
@ -25,9 +25,7 @@ impl Filter {
impl Filter { impl Filter {
pub fn name(&self) -> &str { pub fn name(&self) -> &str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).name).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).name).to_bytes())
}
} }
pub fn description(&self) -> Option<&str> { pub fn description(&self) -> Option<&str> {
@ -36,8 +34,7 @@ impl Filter {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes())) Some(from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes()))
} }
} }
@ -49,8 +46,7 @@ impl Filter {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(PadIter::new((*self.as_ptr()).inputs)) Some(PadIter::new((*self.as_ptr()).inputs))
} }
} }
@ -62,17 +58,14 @@ impl Filter {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(PadIter::new((*self.as_ptr()).outputs)) Some(PadIter::new((*self.as_ptr()).outputs))
} }
} }
} }
pub fn flags(&self) -> Flags { pub fn flags(&self) -> Flags {
unsafe { unsafe { Flags::from_bits_truncate((*self.as_ptr()).flags) }
Flags::from_bits_truncate((*self.as_ptr()).flags)
}
} }
} }
@ -85,7 +78,11 @@ pub struct PadIter<'a> {
impl<'a> PadIter<'a> { impl<'a> PadIter<'a> {
pub fn new(ptr: *const AVFilterPad) -> Self { pub fn new(ptr: *const AVFilterPad) -> Self {
PadIter { ptr: ptr, cur: 0, _marker: PhantomData } PadIter {
ptr: ptr,
cur: 0,
_marker: PhantomData,
}
} }
} }

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
bitflags! { bitflags! {
pub struct Flags: c_int { pub struct Flags: c_int {

View File

@ -1,18 +1,18 @@
use std::ffi::{CStr, CString};
use std::ptr; use std::ptr;
use std::ffi::{CString, CStr};
use std::str::from_utf8_unchecked; use std::str::from_utf8_unchecked;
use super::{Context, Filter};
use ffi::*; use ffi::*;
use libc::c_int; use libc::c_int;
use ::Error; use Error;
use super::{Context, Filter};
pub struct Graph { pub struct Graph {
ptr: *mut AVFilterGraph, ptr: *mut AVFilterGraph,
} }
unsafe impl Send for Graph { } unsafe impl Send for Graph {}
unsafe impl Sync for Graph { } unsafe impl Sync for Graph {}
impl Graph { impl Graph {
pub unsafe fn wrap(ptr: *mut AVFilterGraph) -> Self { pub unsafe fn wrap(ptr: *mut AVFilterGraph) -> Self {
@ -45,39 +45,50 @@ impl Graph {
unsafe { unsafe {
match avfilter_graph_config(self.as_mut_ptr(), ptr::null_mut()) { match avfilter_graph_config(self.as_mut_ptr(), ptr::null_mut()) {
0 => Ok(()), 0 => Ok(()),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
pub fn add<'a, 'b>(&'a mut self, filter: &Filter, name: &str, args: &str) -> Result<Context<'b>, Error> where 'a: 'b { pub fn add<'a, 'b>(
&'a mut self,
filter: &Filter,
name: &str,
args: &str,
) -> Result<Context<'b>, Error>
where
'a: 'b,
{
unsafe { unsafe {
let name = CString::new(name).unwrap(); let name = CString::new(name).unwrap();
let args = CString::new(args).unwrap(); let args = CString::new(args).unwrap();
let mut context = ptr::null_mut(); let mut context = ptr::null_mut();
match avfilter_graph_create_filter(&mut context as *mut *mut AVFilterContext, match avfilter_graph_create_filter(
&mut context as *mut *mut AVFilterContext,
filter.as_ptr(), filter.as_ptr(),
name.as_ptr(), name.as_ptr(),
args.as_ptr(), args.as_ptr(),
ptr::null_mut(), ptr::null_mut(),
self.as_mut_ptr()) self.as_mut_ptr(),
{ ) {
n if n >= 0 => Ok(Context::wrap(context)), n if n >= 0 => Ok(Context::wrap(context)),
e => Err(Error::from(e)), e => Err(Error::from(e)),
} }
} }
} }
pub fn get<'a, 'b>(&'b mut self, name: &str) -> Option<Context<'b>> where 'a: 'b { pub fn get<'a, 'b>(&'b mut self, name: &str) -> Option<Context<'b>>
where
'a: 'b,
{
unsafe { unsafe {
let name = CString::new(name).unwrap(); let name = CString::new(name).unwrap();
let ptr = avfilter_graph_get_filter(self.as_mut_ptr(), name.as_ptr()); let ptr = avfilter_graph_get_filter(self.as_mut_ptr(), name.as_ptr());
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(Context::wrap(ptr)) Some(Context::wrap(ptr))
} }
} }
@ -86,7 +97,7 @@ impl Graph {
pub fn dump(&self) -> String { pub fn dump(&self) -> String {
unsafe { unsafe {
let ptr = avfilter_graph_dump(self.as_ptr() as *mut _, ptr::null()); let ptr = avfilter_graph_dump(self.as_ptr() as *mut _, ptr::null());
let cstr = from_utf8_unchecked(CStr::from_ptr((ptr)).to_bytes()); let cstr = from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes());
let string = cstr.to_owned(); let string = cstr.to_owned();
av_free(ptr as *mut _); av_free(ptr as *mut _);
@ -133,7 +144,7 @@ impl<'a> Parser<'a> {
pub fn input(mut self, name: &str, pad: usize) -> Result<Self, Error> { pub fn input(mut self, name: &str, pad: usize) -> Result<Self, Error> {
unsafe { unsafe {
let mut context = try!(self.graph.get(name).ok_or(Error::InvalidData)); let mut context = self.graph.get(name).ok_or(Error::InvalidData)?;
let input = avfilter_inout_alloc(); let input = avfilter_inout_alloc();
if input.is_null() { if input.is_null() {
@ -149,8 +160,7 @@ impl<'a> Parser<'a> {
if self.inputs.is_null() { if self.inputs.is_null() {
self.inputs = input; self.inputs = input;
} } else {
else {
(*self.inputs).next = input; (*self.inputs).next = input;
} }
} }
@ -160,7 +170,7 @@ impl<'a> Parser<'a> {
pub fn output(mut self, name: &str, pad: usize) -> Result<Self, Error> { pub fn output(mut self, name: &str, pad: usize) -> Result<Self, Error> {
unsafe { unsafe {
let mut context = try!(self.graph.get(name).ok_or(Error::InvalidData)); let mut context = self.graph.get(name).ok_or(Error::InvalidData)?;
let output = avfilter_inout_alloc(); let output = avfilter_inout_alloc();
if output.is_null() { if output.is_null() {
@ -176,8 +186,7 @@ impl<'a> Parser<'a> {
if self.outputs.is_null() { if self.outputs.is_null() {
self.outputs = output; self.outputs = output;
} } else {
else {
(*self.outputs).next = output; (*self.outputs).next = output;
} }
} }
@ -189,17 +198,27 @@ impl<'a> Parser<'a> {
unsafe { unsafe {
let spec = CString::new(spec).unwrap(); let spec = CString::new(spec).unwrap();
let result = avfilter_graph_parse_ptr(self.graph.as_mut_ptr(), let result = avfilter_graph_parse_ptr(
spec.as_ptr(), &mut self.inputs, &mut self.outputs, self.graph.as_mut_ptr(),
ptr::null_mut()); spec.as_ptr(),
&mut self.inputs,
&mut self.outputs,
ptr::null_mut(),
);
avfilter_inout_free(&mut self.inputs); avfilter_inout_free(&mut self.inputs);
avfilter_inout_free(&mut self.outputs); avfilter_inout_free(&mut self.outputs);
match result { match result {
n if n >= 0 => Ok(()), n if n >= 0 => Ok(()),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
} }
impl Default for Graph {
fn default() -> Self {
Self::new()
}
}

View File

@ -8,16 +8,16 @@ pub mod filter;
pub use self::filter::Filter; pub use self::filter::Filter;
pub mod context; pub mod context;
pub use self::context::{Context, Source, Sink}; pub use self::context::{Context, Sink, Source};
pub mod graph; pub mod graph;
pub use self::graph::Graph; pub use self::graph::Graph;
use std::ffi::{CString, CStr}; use std::ffi::{CStr, CString};
use std::str::from_utf8_unchecked; use std::str::from_utf8_unchecked;
use ffi::*; use ffi::*;
use ::Error; use Error;
pub fn register_all() { pub fn register_all() {
unsafe { unsafe {
@ -35,21 +35,15 @@ pub fn register(filter: &Filter) -> Result<(), Error> {
} }
pub fn version() -> u32 { pub fn version() -> u32 {
unsafe { unsafe { avfilter_version() }
avfilter_version()
}
} }
pub fn configuration() -> &'static str { pub fn configuration() -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(avfilter_configuration()).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(avfilter_configuration()).to_bytes())
}
} }
pub fn license() -> &'static str { pub fn license() -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(avfilter_license()).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(avfilter_license()).to_bytes())
}
} }
pub fn find(name: &str) -> Option<Filter> { pub fn find(name: &str) -> Option<Filter> {
@ -59,8 +53,7 @@ pub fn find(name: &str) -> Option<Filter> {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(Filter::wrap(ptr)) Some(Filter::wrap(ptr))
} }
} }

View File

@ -1,9 +1,9 @@
use std::ffi::CStr; use std::ffi::CStr;
use std::str::from_utf8_unchecked;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::str::from_utf8_unchecked;
use ffi::*; use ffi::*;
use ::media; use media;
pub struct Pad<'a> { pub struct Pad<'a> {
ptr: *const AVFilterPad, ptr: *const AVFilterPad,
@ -13,7 +13,10 @@ pub struct Pad<'a> {
impl<'a> Pad<'a> { impl<'a> Pad<'a> {
pub unsafe fn wrap(ptr: *const AVFilterPad) -> Self { pub unsafe fn wrap(ptr: *const AVFilterPad) -> Self {
Pad { ptr: ptr, _marker: PhantomData } Pad {
ptr: ptr,
_marker: PhantomData,
}
} }
pub unsafe fn as_ptr(&self) -> *const AVFilterPad { pub unsafe fn as_ptr(&self) -> *const AVFilterPad {
@ -32,16 +35,13 @@ impl<'a> Pad<'a> {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes())) Some(from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes()))
} }
} }
} }
pub fn medium(&self) -> media::Type { pub fn medium(&self) -> media::Type {
unsafe { unsafe { media::Type::from(avfilter_pad_get_type(self.ptr, 0)) }
media::Type::from(avfilter_pad_get_type(self.ptr, 0))
}
} }
} }

View File

@ -1,5 +1,5 @@
use ffi::*; use ffi::*;
use ::{Rational, DictionaryRef}; use {DictionaryRef, Rational};
use format::context::common::Context; use format::context::common::Context;
@ -12,11 +12,16 @@ pub struct Chapter<'a> {
impl<'a> Chapter<'a> { impl<'a> Chapter<'a> {
pub unsafe fn wrap(context: &Context, index: usize) -> Chapter { pub unsafe fn wrap(context: &Context, index: usize) -> Chapter {
Chapter { context: context, index: index } Chapter {
context: context,
index: index,
}
} }
pub unsafe fn as_ptr(&self) -> *const AVChapter { pub unsafe fn as_ptr(&self) -> *const AVChapter {
*(*self.context.as_ptr()).chapters.offset(self.index as isize) *(*self.context.as_ptr())
.chapters
.offset(self.index as isize)
} }
} }
@ -26,40 +31,28 @@ impl<'a> Chapter<'a> {
} }
pub fn id(&self) -> i32 { pub fn id(&self) -> i32 {
unsafe { unsafe { (*self.as_ptr()).id }
(*self.as_ptr()).id
}
} }
pub fn time_base(&self) -> Rational { pub fn time_base(&self) -> Rational {
unsafe { unsafe { Rational::from((*self.as_ptr()).time_base) }
Rational::from((*self.as_ptr()).time_base)
}
} }
pub fn start(&self) -> i64 { pub fn start(&self) -> i64 {
unsafe { unsafe { (*self.as_ptr()).start }
(*self.as_ptr()).start
}
} }
pub fn end(&self) -> i64 { pub fn end(&self) -> i64 {
unsafe { unsafe { (*self.as_ptr()).end }
(*self.as_ptr()).end
}
} }
pub fn metadata(&self) -> DictionaryRef { pub fn metadata(&self) -> DictionaryRef {
unsafe { unsafe { DictionaryRef::wrap((*self.as_ptr()).metadata) }
DictionaryRef::wrap((*self.as_ptr()).metadata)
}
} }
} }
impl<'a> PartialEq for Chapter<'a> { impl<'a> PartialEq for Chapter<'a> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
unsafe { unsafe { self.as_ptr() == other.as_ptr() }
self.as_ptr() == other.as_ptr()
}
} }
} }

View File

@ -1,10 +1,10 @@
use std::ops::Deref;
use std::mem; use std::mem;
use std::ops::Deref;
use ffi::*;
use ::{Rational, Dictionary, DictionaryMut};
use super::Chapter; use super::Chapter;
use ffi::*;
use format::context::common::Context; use format::context::common::Context;
use {Dictionary, DictionaryMut, Rational};
// WARNING: index refers to the offset in the chapters array (starting from 0) // WARNING: index refers to the offset in the chapters array (starting from 0)
// it is not necessarly equal to the id (which may start at 1) // it is not necessarly equal to the id (which may start at 1)
@ -21,12 +21,14 @@ impl<'a> ChapterMut<'a> {
context: mem::transmute_copy(&context), context: mem::transmute_copy(&context),
index: index, index: index,
immutable: Chapter::wrap(mem::transmute_copy(&context), index) immutable: Chapter::wrap(mem::transmute_copy(&context), index),
} }
} }
pub unsafe fn as_mut_ptr(&mut self) -> *mut AVChapter { pub unsafe fn as_mut_ptr(&mut self) -> *mut AVChapter {
*(*self.context.as_mut_ptr()).chapters.offset(self.index as isize) *(*self.context.as_mut_ptr())
.chapters
.offset(self.index as isize)
} }
} }
@ -66,9 +68,7 @@ impl<'a> ChapterMut<'a> {
} }
pub fn metadata(&mut self) -> DictionaryMut { pub fn metadata(&mut self) -> DictionaryMut {
unsafe { unsafe { DictionaryMut::wrap((*self.as_mut_ptr()).metadata) }
DictionaryMut::wrap((*self.as_mut_ptr()).metadata)
}
} }
} }

View File

@ -1,22 +1,25 @@
use std::rc::Rc;
use std::ptr;
use std::mem; use std::mem;
use std::ptr;
use std::rc::Rc;
use super::destructor::{self, Destructor};
use ffi::*; use ffi::*;
use libc::{c_int, c_uint}; use libc::{c_int, c_uint};
use ::{media, Stream, StreamMut, Chapter, ChapterMut, DictionaryRef}; use {media, Chapter, ChapterMut, DictionaryRef, Stream, StreamMut};
use super::destructor::{self, Destructor};
pub struct Context { pub struct Context {
ptr: *mut AVFormatContext, ptr: *mut AVFormatContext,
dtor: Rc<Destructor>, dtor: Rc<Destructor>,
} }
unsafe impl Send for Context { } unsafe impl Send for Context {}
impl Context { impl Context {
pub unsafe fn wrap(ptr: *mut AVFormatContext, mode: destructor::Mode) -> Self { pub unsafe fn wrap(ptr: *mut AVFormatContext, mode: destructor::Mode) -> Self {
Context { ptr: ptr, dtor: Rc::new(Destructor::new(ptr, mode)) } Context {
ptr: ptr,
dtor: Rc::new(Destructor::new(ptr, mode)),
}
} }
pub unsafe fn as_ptr(&self) -> *const AVFormatContext { pub unsafe fn as_ptr(&self) -> *const AVFormatContext {
@ -28,28 +31,32 @@ impl Context {
} }
pub unsafe fn destructor(&self) -> Rc<Destructor> { pub unsafe fn destructor(&self) -> Rc<Destructor> {
self.dtor.clone() Rc::clone(&self.dtor)
} }
} }
impl Context { impl Context {
pub fn stream<'a, 'b>(&'a self, index: usize) -> Option<Stream<'b>> where 'a: 'b { pub fn stream<'a, 'b>(&'a self, index: usize) -> Option<Stream<'b>>
where
'a: 'b,
{
unsafe { unsafe {
if index >= (*self.as_ptr()).nb_streams as usize { if index >= (*self.as_ptr()).nb_streams as usize {
None None
} } else {
else {
Some(Stream::wrap(self, index)) Some(Stream::wrap(self, index))
} }
} }
} }
pub fn stream_mut<'a, 'b>(&'a mut self, index: usize) -> Option<StreamMut<'b>> where 'a: 'b { pub fn stream_mut<'a, 'b>(&'a mut self, index: usize) -> Option<StreamMut<'b>>
where
'a: 'b,
{
unsafe { unsafe {
if index >= (*self.as_ptr()).nb_streams as usize { if index >= (*self.as_ptr()).nb_streams as usize {
None None
} } else {
else {
Some(StreamMut::wrap(self, index)) Some(StreamMut::wrap(self, index))
} }
} }
@ -64,34 +71,34 @@ impl Context {
} }
pub fn duration(&self) -> i64 { pub fn duration(&self) -> i64 {
unsafe { unsafe { (*self.as_ptr()).duration }
(*self.as_ptr()).duration
}
} }
pub fn nb_chapters(&self) -> u32 { pub fn nb_chapters(&self) -> u32 {
unsafe { unsafe { (*self.as_ptr()).nb_chapters }
(*self.as_ptr()).nb_chapters
}
} }
pub fn chapter<'a, 'b>(&'a self, index: usize) -> Option<Chapter<'b>> where 'a: 'b { pub fn chapter<'a, 'b>(&'a self, index: usize) -> Option<Chapter<'b>>
where
'a: 'b,
{
unsafe { unsafe {
if index >= (*self.as_ptr()).nb_chapters as usize { if index >= (*self.as_ptr()).nb_chapters as usize {
None None
} } else {
else {
Some(Chapter::wrap(self, index)) Some(Chapter::wrap(self, index))
} }
} }
} }
pub fn chapter_mut<'a, 'b>(&'a mut self, index: usize) -> Option<ChapterMut<'b>> where 'a: 'b { pub fn chapter_mut<'a, 'b>(&'a mut self, index: usize) -> Option<ChapterMut<'b>>
where
'a: 'b,
{
unsafe { unsafe {
if index >= (*self.as_ptr()).nb_chapters as usize { if index >= (*self.as_ptr()).nb_chapters as usize {
None None
} } else {
else {
Some(ChapterMut::wrap(self, index)) Some(ChapterMut::wrap(self, index))
} }
} }
@ -106,9 +113,7 @@ impl Context {
} }
pub fn metadata(&self) -> DictionaryRef { pub fn metadata(&self) -> DictionaryRef {
unsafe { unsafe { DictionaryRef::wrap((*self.as_ptr()).metadata) }
DictionaryRef::wrap((*self.as_ptr()).metadata)
}
} }
} }
@ -129,27 +134,40 @@ impl<'a> Best<'a> {
} }
} }
pub fn wanted<'b>(mut self, stream: &'b Stream) -> Best<'a> where 'a: 'b { pub fn wanted<'b>(mut self, stream: &'b Stream) -> Best<'a>
where
'a: 'b,
{
self.wanted = stream.index() as i32; self.wanted = stream.index() as i32;
self self
} }
pub fn related<'b>(mut self, stream: &'b Stream) -> Best<'a> where 'a: 'b { pub fn related<'b>(mut self, stream: &'b Stream) -> Best<'a>
where
'a: 'b,
{
self.related = stream.index() as i32; self.related = stream.index() as i32;
self self
} }
pub fn best<'b>(self, kind: media::Type) -> Option<Stream<'b>> where 'a: 'b { pub fn best<'b>(self, kind: media::Type) -> Option<Stream<'b>>
where
'a: 'b,
{
unsafe { unsafe {
let mut decoder = ptr::null_mut(); let mut decoder = ptr::null_mut();
let index = av_find_best_stream(self.context.ptr, let index = av_find_best_stream(
kind.into(), self.wanted as c_int, self.related as c_int, self.context.ptr,
&mut decoder, 0); kind.into(),
self.wanted as c_int,
self.related as c_int,
&mut decoder,
0,
);
if index >= 0 && !decoder.is_null() { if index >= 0 && !decoder.is_null() {
Some(Stream::wrap(self.context, index as usize)) Some(Stream::wrap(self.context, index as usize))
} } else {
else {
None None
} }
} }
@ -163,27 +181,35 @@ pub struct StreamIter<'a> {
impl<'a> StreamIter<'a> { impl<'a> StreamIter<'a> {
pub fn new<'s, 'c: 's>(context: &'c Context) -> StreamIter<'s> { pub fn new<'s, 'c: 's>(context: &'c Context) -> StreamIter<'s> {
StreamIter { context: context, current: 0 } StreamIter {
context: context,
current: 0,
}
} }
} }
impl<'a> StreamIter<'a> { impl<'a> StreamIter<'a> {
pub fn wanted<'b, 'c>(&self, stream: &'b Stream) -> Best<'c> where 'a: 'b, 'a: 'c { pub fn wanted<'b, 'c>(&self, stream: &'b Stream) -> Best<'c>
unsafe { where
Best::new(self.context).wanted(stream) 'a: 'b,
} 'a: 'c,
{
unsafe { Best::new(self.context).wanted(stream) }
} }
pub fn related<'b, 'c>(&self, stream: &'b Stream) -> Best<'c> where 'a: 'b, 'a: 'c { pub fn related<'b, 'c>(&self, stream: &'b Stream) -> Best<'c>
unsafe { where
Best::new(self.context).related(stream) 'a: 'b,
} 'a: 'c,
{
unsafe { Best::new(self.context).related(stream) }
} }
pub fn best<'b>(&self, kind: media::Type) -> Option<Stream<'b>> where 'a: 'b { pub fn best<'b>(&self, kind: media::Type) -> Option<Stream<'b>>
unsafe { where
Best::new(self.context).best(kind) 'a: 'b,
} {
unsafe { Best::new(self.context).best(kind) }
} }
} }
@ -206,12 +232,15 @@ impl<'a> Iterator for StreamIter<'a> {
unsafe { unsafe {
let length = (*self.context.as_ptr()).nb_streams as usize; let length = (*self.context.as_ptr()).nb_streams as usize;
(length - self.current as usize, Some(length - self.current as usize)) (
length - self.current as usize,
Some(length - self.current as usize),
)
} }
} }
} }
impl<'a> ExactSizeIterator for StreamIter<'a> { } impl<'a> ExactSizeIterator for StreamIter<'a> {}
pub struct StreamIterMut<'a> { pub struct StreamIterMut<'a> {
context: &'a mut Context, context: &'a mut Context,
@ -220,7 +249,10 @@ pub struct StreamIterMut<'a> {
impl<'a> StreamIterMut<'a> { impl<'a> StreamIterMut<'a> {
pub fn new<'s, 'c: 's>(context: &'c mut Context) -> StreamIterMut<'s> { pub fn new<'s, 'c: 's>(context: &'c mut Context) -> StreamIterMut<'s> {
StreamIterMut { context: context, current: 0 } StreamIterMut {
context: context,
current: 0,
}
} }
} }
@ -230,12 +262,15 @@ impl<'a> Iterator for StreamIterMut<'a> {
fn next(&mut self) -> Option<<Self as Iterator>::Item> { fn next(&mut self) -> Option<<Self as Iterator>::Item> {
unsafe { unsafe {
if self.current >= (*self.context.as_ptr()).nb_streams { if self.current >= (*self.context.as_ptr()).nb_streams {
return None return None;
} }
self.current += 1; self.current += 1;
Some(StreamMut::wrap(mem::transmute_copy(&self.context), (self.current - 1) as usize)) Some(StreamMut::wrap(
mem::transmute_copy(&self.context),
(self.current - 1) as usize,
))
} }
} }
@ -243,12 +278,15 @@ impl<'a> Iterator for StreamIterMut<'a> {
unsafe { unsafe {
let length = (*self.context.as_ptr()).nb_streams as usize; let length = (*self.context.as_ptr()).nb_streams as usize;
(length - self.current as usize, Some(length - self.current as usize)) (
length - self.current as usize,
Some(length - self.current as usize),
)
} }
} }
} }
impl<'a> ExactSizeIterator for StreamIterMut<'a> { } impl<'a> ExactSizeIterator for StreamIterMut<'a> {}
pub struct ChapterIter<'a> { pub struct ChapterIter<'a> {
context: &'a Context, context: &'a Context,
@ -257,7 +295,10 @@ pub struct ChapterIter<'a> {
impl<'a> ChapterIter<'a> { impl<'a> ChapterIter<'a> {
pub fn new<'s, 'c: 's>(context: &'c Context) -> ChapterIter<'s> { pub fn new<'s, 'c: 's>(context: &'c Context) -> ChapterIter<'s> {
ChapterIter { context: context, current: 0 } ChapterIter {
context: context,
current: 0,
}
} }
} }
@ -280,12 +321,15 @@ impl<'a> Iterator for ChapterIter<'a> {
unsafe { unsafe {
let length = (*self.context.as_ptr()).nb_chapters as usize; let length = (*self.context.as_ptr()).nb_chapters as usize;
(length - self.current as usize, Some(length - self.current as usize)) (
length - self.current as usize,
Some(length - self.current as usize),
)
} }
} }
} }
impl<'a> ExactSizeIterator for ChapterIter<'a> { } impl<'a> ExactSizeIterator for ChapterIter<'a> {}
pub struct ChapterIterMut<'a> { pub struct ChapterIterMut<'a> {
context: &'a mut Context, context: &'a mut Context,
@ -294,7 +338,10 @@ pub struct ChapterIterMut<'a> {
impl<'a> ChapterIterMut<'a> { impl<'a> ChapterIterMut<'a> {
pub fn new<'s, 'c: 's>(context: &'c mut Context) -> ChapterIterMut<'s> { pub fn new<'s, 'c: 's>(context: &'c mut Context) -> ChapterIterMut<'s> {
ChapterIterMut { context: context, current: 0 } ChapterIterMut {
context: context,
current: 0,
}
} }
} }
@ -304,12 +351,15 @@ impl<'a> Iterator for ChapterIterMut<'a> {
fn next(&mut self) -> Option<<Self as Iterator>::Item> { fn next(&mut self) -> Option<<Self as Iterator>::Item> {
unsafe { unsafe {
if self.current >= (*self.context.as_ptr()).nb_chapters { if self.current >= (*self.context.as_ptr()).nb_chapters {
return None return None;
} }
self.current += 1; self.current += 1;
Some(ChapterMut::wrap(mem::transmute_copy(&self.context), (self.current - 1) as usize)) Some(ChapterMut::wrap(
mem::transmute_copy(&self.context),
(self.current - 1) as usize,
))
} }
} }
@ -317,9 +367,12 @@ impl<'a> Iterator for ChapterIterMut<'a> {
unsafe { unsafe {
let length = (*self.context.as_ptr()).nb_chapters as usize; let length = (*self.context.as_ptr()).nb_chapters as usize;
(length - self.current as usize, Some(length - self.current as usize)) (
length - self.current as usize,
Some(length - self.current as usize),
)
} }
} }
} }
impl<'a> ExactSizeIterator for ChapterIterMut<'a> { } impl<'a> ExactSizeIterator for ChapterIterMut<'a> {}

View File

@ -24,8 +24,7 @@ impl Drop for Destructor {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
match self.mode { match self.mode {
Mode::Input => Mode::Input => avformat_close_input(&mut self.ptr),
avformat_close_input(&mut self.ptr),
Mode::Output => { Mode::Output => {
avio_close((*self.ptr).pb); avio_close((*self.ptr).pb);

View File

@ -1,24 +1,27 @@
use std::ffi::CString;
use std::mem;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::ptr; use std::ptr;
use std::mem;
use std::ffi::CString;
use ffi::*;
use ::{Error, Codec, Stream, Packet, format};
use super::common::Context; use super::common::Context;
use super::destructor; use super::destructor;
use ffi::*;
use util::range::Range; use util::range::Range;
use {format, Codec, Error, Packet, Stream};
pub struct Input { pub struct Input {
ptr: *mut AVFormatContext, ptr: *mut AVFormatContext,
ctx: Context, ctx: Context,
} }
unsafe impl Send for Input { } unsafe impl Send for Input {}
impl Input { impl Input {
pub unsafe fn wrap(ptr: *mut AVFormatContext) -> Self { pub unsafe fn wrap(ptr: *mut AVFormatContext) -> Self {
Input { ptr: ptr, ctx: Context::wrap(ptr, destructor::Mode::Input) } Input {
ptr: ptr,
ctx: Context::wrap(ptr, destructor::Mode::Input),
}
} }
pub unsafe fn as_ptr(&self) -> *const AVFormatContext { pub unsafe fn as_ptr(&self) -> *const AVFormatContext {
@ -32,9 +35,7 @@ impl Input {
impl Input { impl Input {
pub fn format(&self) -> format::Input { pub fn format(&self) -> format::Input {
unsafe { unsafe { format::Input::wrap((*self.as_ptr()).iformat) }
format::Input::wrap((*self.as_ptr()).iformat)
}
} }
pub fn video_codec(&self) -> Option<Codec> { pub fn video_codec(&self) -> Option<Codec> {
@ -43,8 +44,7 @@ impl Input {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(Codec::wrap(ptr)) Some(Codec::wrap(ptr))
} }
} }
@ -56,8 +56,7 @@ impl Input {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(Codec::wrap(ptr)) Some(Codec::wrap(ptr))
} }
} }
@ -69,8 +68,7 @@ impl Input {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(Codec::wrap(ptr)) Some(Codec::wrap(ptr))
} }
} }
@ -82,17 +80,14 @@ impl Input {
if ptr.is_null() { if ptr.is_null() {
None None
} } else {
else {
Some(Codec::wrap(ptr)) Some(Codec::wrap(ptr))
} }
} }
} }
pub fn probe_score(&self) -> i32 { pub fn probe_score(&self) -> i32 {
unsafe { unsafe { av_format_get_probe_score(self.as_ptr()) }
av_format_get_probe_score(self.as_ptr())
}
} }
pub fn packets(&mut self) -> PacketIter { pub fn packets(&mut self) -> PacketIter {
@ -119,10 +114,14 @@ impl Input {
pub fn seek<R: Range<i64>>(&mut self, ts: i64, range: R) -> Result<(), Error> { pub fn seek<R: Range<i64>>(&mut self, ts: i64, range: R) -> Result<(), Error> {
unsafe { unsafe {
match avformat_seek_file(self.as_mut_ptr(), -1, match avformat_seek_file(
range.start().map(|v| *v).unwrap_or(i64::min_value()), ts, self.as_mut_ptr(),
range.end().map(|v| *v).unwrap_or(i64::max_value()), 0) -1,
{ range.start().cloned().unwrap_or(i64::min_value()),
ts,
range.end().cloned().unwrap_or(i64::max_value()),
0,
) {
s if s >= 0 => Ok(()), s if s >= 0 => Ok(()),
e => Err(Error::from(e)), e => Err(Error::from(e)),
} }
@ -165,14 +164,13 @@ impl<'a> Iterator for PacketIter<'a> {
Ok(..) => unsafe { Ok(..) => unsafe {
return Some(( return Some((
Stream::wrap(mem::transmute_copy(&self.context), packet.stream()), Stream::wrap(mem::transmute_copy(&self.context), packet.stream()),
packet)); packet,
));
}, },
Err(Error::Eof) => Err(Error::Eof) => return None,
return None,
Err(..) => Err(..) => (),
()
} }
} }
} }
@ -182,7 +180,11 @@ pub fn dump(ctx: &Input, index: i32, url: Option<&str>) {
let url = url.map(|u| CString::new(u).unwrap()); let url = url.map(|u| CString::new(u).unwrap());
unsafe { unsafe {
av_dump_format(ctx.as_ptr() as *mut _, index, av_dump_format(
url.map(|u| u.as_ptr()).unwrap_or(ptr::null()), 0); ctx.as_ptr() as *mut _,
index,
url.map(|u| u.as_ptr()).unwrap_or(ptr::null()),
0,
);
} }
} }

View File

@ -15,14 +15,13 @@ pub enum Context {
Output(Output), Output(Output),
} }
unsafe impl Send for Context { } unsafe impl Send for Context {}
impl Context { impl Context {
pub fn is_input(&self) -> bool { pub fn is_input(&self) -> bool {
if let &Context::Input(..) = self { if let Context::Input(..) = *self {
true true
} } else {
else {
false false
} }
} }
@ -36,10 +35,9 @@ impl Context {
} }
pub fn is_output(&self) -> bool { pub fn is_output(&self) -> bool {
if let &Context::Output(..) = self { if let Context::Output(..) = *self {
true true
} } else {
else {
false false
} }
} }

View File

@ -1,26 +1,29 @@
use std::ffi::CString;
use std::mem::size_of;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::ptr; use std::ptr;
use std::mem::size_of;
use std::ffi::CString;
use libc; use libc;
use ffi::*;
use ::{Error, StreamMut, ChapterMut, Rational, Dictionary, format};
use super::common::Context; use super::common::Context;
use super::destructor; use super::destructor;
use codec::traits; use codec::traits;
use ffi::*;
use {format, ChapterMut, Dictionary, Error, Rational, StreamMut};
pub struct Output { pub struct Output {
ptr: *mut AVFormatContext, ptr: *mut AVFormatContext,
ctx: Context, ctx: Context,
} }
unsafe impl Send for Output { } unsafe impl Send for Output {}
impl Output { impl Output {
pub unsafe fn wrap(ptr: *mut AVFormatContext) -> Self { pub unsafe fn wrap(ptr: *mut AVFormatContext) -> Self {
Output { ptr: ptr, ctx: Context::wrap(ptr, destructor::Mode::Output) } Output {
ptr: ptr,
ctx: Context::wrap(ptr, destructor::Mode::Output),
}
} }
pub unsafe fn as_ptr(&self) -> *const AVFormatContext { pub unsafe fn as_ptr(&self) -> *const AVFormatContext {
@ -34,9 +37,7 @@ impl Output {
impl Output { impl Output {
pub fn format(&self) -> format::Output { pub fn format(&self) -> format::Output {
unsafe { unsafe { format::Output::wrap((*self.as_ptr()).oformat) }
format::Output::wrap((*self.as_ptr()).oformat)
}
} }
pub fn write_header(&mut self) -> Result<(), Error> { pub fn write_header(&mut self) -> Result<(), Error> {
@ -71,7 +72,7 @@ impl Output {
pub fn add_stream<E: traits::Encoder>(&mut self, codec: E) -> Result<StreamMut, Error> { pub fn add_stream<E: traits::Encoder>(&mut self, codec: E) -> Result<StreamMut, Error> {
unsafe { unsafe {
let codec = try!(codec.encoder().ok_or(Error::EncoderNotFound)); let codec = codec.encoder().ok_or(Error::EncoderNotFound)?;
let ptr = avformat_new_stream(self.as_mut_ptr(), codec.as_ptr()); let ptr = avformat_new_stream(self.as_mut_ptr(), codec.as_ptr());
if ptr.is_null() { if ptr.is_null() {
@ -84,13 +85,14 @@ impl Output {
} }
} }
pub fn add_chapter<R: Into<Rational>, S: AsRef<str>>(&mut self, pub fn add_chapter<R: Into<Rational>, S: AsRef<str>>(
&mut self,
id: i32, id: i32,
time_base: R, time_base: R,
start: i64, start: i64,
end: i64, end: i64,
title: S) -> Result<ChapterMut, Error> title: S,
{ ) -> Result<ChapterMut, Error> {
// avpriv_new_chapter is private (libavformat/internal.h) // avpriv_new_chapter is private (libavformat/internal.h)
if start > end { if start > end {
@ -108,22 +110,23 @@ impl Output {
let index = match existing { let index = match existing {
Some(index) => index, Some(index) => index,
None => unsafe { None => unsafe {
let ptr = av_mallocz(size_of::<AVChapter>()).as_mut().ok_or(Error::Bug)?; let ptr = av_mallocz(size_of::<AVChapter>())
.as_mut()
.ok_or(Error::Bug)?;
let mut nb_chapters = (*self.as_ptr()).nb_chapters as i32; let mut nb_chapters = (*self.as_ptr()).nb_chapters as i32;
// chapters array will be freed by `avformat_free_context` // chapters array will be freed by `avformat_free_context`
av_dynarray_add( av_dynarray_add(
&mut (*self.as_mut_ptr()).chapters as *mut _ as *mut libc::c_void, &mut (*self.as_mut_ptr()).chapters as *mut _ as *mut libc::c_void,
&mut nb_chapters, &mut nb_chapters,
ptr ptr,
); );
if nb_chapters > 0 { if nb_chapters > 0 {
(*self.as_mut_ptr()).nb_chapters = nb_chapters as u32; (*self.as_mut_ptr()).nb_chapters = nb_chapters as u32;
let index = (*self.ctx.as_ptr()).nb_chapters - 1; let index = (*self.ctx.as_ptr()).nb_chapters - 1;
index as usize index as usize
} } else {
else {
// failed to add the chapter // failed to add the chapter
av_freep(ptr); av_freep(ptr);
return Err(Error::Bug); return Err(Error::Bug);
@ -131,8 +134,7 @@ impl Output {
}, },
}; };
let mut chapter = self.chapter_mut(index) let mut chapter = self.chapter_mut(index).ok_or(Error::Bug)?;
.ok_or(Error::Bug)?;
chapter.set_id(id); chapter.set_id(id);
chapter.set_time_base(time_base); chapter.set_time_base(time_base);
@ -168,7 +170,11 @@ pub fn dump(ctx: &Output, index: i32, url: Option<&str>) {
let url = url.map(|u| CString::new(u).unwrap()); let url = url.map(|u| CString::new(u).unwrap());
unsafe { unsafe {
av_dump_format(ctx.as_ptr() as *mut _, index, av_dump_format(
url.map(|u| u.as_ptr()).unwrap_or(ptr::null()), 1); ctx.as_ptr() as *mut _,
index,
url.map(|u| u.as_ptr()).unwrap_or(ptr::null()),
1,
);
} }
} }

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
bitflags! { bitflags! {
pub struct Flags: c_int { pub struct Flags: c_int {
@ -23,4 +23,3 @@ bitflags! {
const SEEK_TO_PTS = AVFMT_SEEK_TO_PTS; const SEEK_TO_PTS = AVFMT_SEEK_TO_PTS;
} }
} }

View File

@ -23,15 +23,11 @@ impl Input {
impl Input { impl Input {
pub fn name(&self) -> &str { pub fn name(&self) -> &str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).name).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).name).to_bytes())
}
} }
pub fn description(&self) -> &str { pub fn description(&self) -> &str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).long_name).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).long_name).to_bytes())
}
} }
pub fn extensions(&self) -> Vec<&str> { pub fn extensions(&self) -> Vec<&str> {
@ -40,9 +36,10 @@ impl Input {
if ptr.is_null() { if ptr.is_null() {
Vec::new() Vec::new()
} } else {
else { from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes())
from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes()).split(',').collect() .split(',')
.collect()
} }
} }
} }
@ -53,9 +50,10 @@ impl Input {
if ptr.is_null() { if ptr.is_null() {
Vec::new() Vec::new()
} } else {
else { from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes())
from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes()).split(',').collect() .split(',')
.collect()
} }
} }
} }

View File

@ -1,7 +1,7 @@
use std::ptr; use std::ptr;
use ffi::*;
use super::{Format, Input, Output}; use super::{Format, Input, Output};
use ffi::*;
pub struct Iter { pub struct Iter {
input: *mut AVInputFormat, input: *mut AVInputFormat,
@ -17,7 +17,17 @@ enum Step {
impl Iter { impl Iter {
pub fn new() -> Self { pub fn new() -> Self {
Iter { input: ptr::null_mut(), output: ptr::null_mut(), step: Step::Input } Iter {
input: ptr::null_mut(),
output: ptr::null_mut(),
step: Step::Input,
}
}
}
impl Default for Iter {
fn default() -> Self {
Self::new()
} }
} }
@ -34,8 +44,7 @@ impl Iterator for Iter {
self.step = Step::Output; self.step = Step::Output;
self.next() self.next()
} } else {
else {
self.input = ptr; self.input = ptr;
Some(Format::Input(Input::wrap(ptr))) Some(Format::Input(Input::wrap(ptr)))
@ -49,16 +58,14 @@ impl Iterator for Iter {
self.step = Step::Done; self.step = Step::Done;
self.next() self.next()
} } else {
else {
self.output = ptr; self.output = ptr;
Some(Format::Output(Output::wrap(ptr))) Some(Format::Output(Output::wrap(ptr)))
} }
} }
Step::Done => Step::Done => None,
None
} }
} }
} }

View File

@ -17,30 +17,30 @@ pub enum Format {
impl Format { impl Format {
pub fn name(&self) -> &str { pub fn name(&self) -> &str {
match self { match *self {
&Format::Input(ref f) => f.name(), Format::Input(ref f) => f.name(),
&Format::Output(ref f) => f.name() Format::Output(ref f) => f.name(),
} }
} }
pub fn description(&self) -> &str { pub fn description(&self) -> &str {
match self { match *self {
&Format::Input(ref f) => f.description(), Format::Input(ref f) => f.description(),
&Format::Output(ref f) => f.description() Format::Output(ref f) => f.description(),
} }
} }
pub fn extensions(&self) -> Vec<&str> { pub fn extensions(&self) -> Vec<&str> {
match self { match *self {
&Format::Input(ref f) => f.extensions(), Format::Input(ref f) => f.extensions(),
&Format::Output(ref f) => f.extensions() Format::Output(ref f) => f.extensions(),
} }
} }
pub fn mime_types(&self) -> Vec<&str> { pub fn mime_types(&self) -> Vec<&str> {
match self { match *self {
&Format::Input(ref f) => f.mime_types(), Format::Input(ref f) => f.mime_types(),
&Format::Output(ref f) => f.mime_types() Format::Output(ref f) => f.mime_types(),
} }
} }
} }

View File

@ -1,12 +1,12 @@
use std::path::Path; use std::path::Path;
use std::ptr;
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
use std::ptr;
use std::str::from_utf8_unchecked; use std::str::from_utf8_unchecked;
use super::Flags;
use ffi::*; use ffi::*;
use {codec, media}; use {codec, media};
use super::Flags;
pub struct Output { pub struct Output {
ptr: *mut AVOutputFormat, ptr: *mut AVOutputFormat,
@ -28,15 +28,11 @@ impl Output {
impl Output { impl Output {
pub fn name(&self) -> &str { pub fn name(&self) -> &str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).name).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).name).to_bytes())
}
} }
pub fn description(&self) -> &str { pub fn description(&self) -> &str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).long_name).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).long_name).to_bytes())
}
} }
pub fn extensions(&self) -> Vec<&str> { pub fn extensions(&self) -> Vec<&str> {
@ -45,9 +41,10 @@ impl Output {
if ptr.is_null() { if ptr.is_null() {
Vec::new() Vec::new()
} } else {
else { from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes())
from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes()).split(',').collect() .split(',')
.collect()
} }
} }
} }
@ -58,9 +55,10 @@ impl Output {
if ptr.is_null() { if ptr.is_null() {
Vec::new() Vec::new()
} } else {
else { from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes())
from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes()).split(',').collect() .split(',')
.collect()
} }
} }
} }
@ -70,13 +68,17 @@ impl Output {
let path = CString::new(path.as_ref().as_os_str().to_str().unwrap()).unwrap(); let path = CString::new(path.as_ref().as_os_str().to_str().unwrap()).unwrap();
unsafe { unsafe {
codec::Id::from(av_guess_codec(self.as_ptr() as *mut _, ptr::null(), path.as_ptr(), ptr::null(), kind.into())) codec::Id::from(av_guess_codec(
self.as_ptr() as *mut _,
ptr::null(),
path.as_ptr(),
ptr::null(),
kind.into(),
))
} }
} }
pub fn flags(&self) -> Flags { pub fn flags(&self) -> Flags {
unsafe { unsafe { Flags::from_bits_truncate((*self.as_ptr()).flags) }
Flags::from_bits_truncate((*self.as_ptr()).flags)
}
} }
} }

View File

@ -1,6 +1,6 @@
pub use ::util::format::{sample, Sample}; pub use util::format::{pixel, Pixel};
pub use ::util::format::{pixel, Pixel}; pub use util::format::{sample, Sample};
use ::util::interrupt; use util::interrupt;
pub mod stream; pub mod stream;
@ -10,18 +10,18 @@ pub mod context;
pub use self::context::Context; pub use self::context::Context;
pub mod format; pub mod format;
pub use self::format::{Input, Output, list};
pub use self::format::{flag, Flags}; pub use self::format::{flag, Flags};
pub use self::format::{list, Input, Output};
pub mod network; pub mod network;
use std::ptr; use std::ffi::{CStr, CString};
use std::path::Path; use std::path::Path;
use std::ffi::{CString, CStr}; use std::ptr;
use std::str::from_utf8_unchecked; use std::str::from_utf8_unchecked;
use ffi::*; use ffi::*;
use ::{Error, Format, Dictionary}; use {Dictionary, Error, Format};
pub fn register_all() { pub fn register_all() {
unsafe { unsafe {
@ -30,33 +30,27 @@ pub fn register_all() {
} }
pub fn register(format: &Format) { pub fn register(format: &Format) {
match format { match *format {
&Format::Input(ref format) => unsafe { Format::Input(ref format) => unsafe {
av_register_input_format(format.as_ptr() as *mut _); av_register_input_format(format.as_ptr() as *mut _);
}, },
&Format::Output(ref format) => unsafe { Format::Output(ref format) => unsafe {
av_register_output_format(format.as_ptr() as *mut _); av_register_output_format(format.as_ptr() as *mut _);
} },
} }
} }
pub fn version() -> u32 { pub fn version() -> u32 {
unsafe { unsafe { avformat_version() }
avformat_version()
}
} }
pub fn configuration() -> &'static str { pub fn configuration() -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(avformat_configuration()).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(avformat_configuration()).to_bytes())
}
} }
pub fn license() -> &'static str { pub fn license() -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(avformat_license()).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(avformat_license()).to_bytes())
}
} }
// XXX: use to_cstring when stable // XXX: use to_cstring when stable
@ -70,72 +64,82 @@ pub fn open<P: AsRef<Path>>(path: &P, format: &Format) -> Result<Context, Error>
let mut ps = ptr::null_mut(); let mut ps = ptr::null_mut();
let path = from_path(path); let path = from_path(path);
match format { match *format {
&Format::Input(ref format) => { Format::Input(ref format) => match avformat_open_input(
match avformat_open_input(&mut ps, path.as_ptr(), format.as_ptr() as *mut _, ptr::null_mut()) { &mut ps,
0 => { path.as_ptr(),
match avformat_find_stream_info(ps, ptr::null_mut()) { format.as_ptr() as *mut _,
ptr::null_mut(),
) {
0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
r if r >= 0 => Ok(Context::Input(context::Input::wrap(ps))), r if r >= 0 => Ok(Context::Input(context::Input::wrap(ps))),
e => Err(Error::from(e)), e => Err(Error::from(e)),
} },
}
e => Err(Error::from(e)) e => Err(Error::from(e)),
} },
}
&Format::Output(ref format) => { Format::Output(ref format) => match avformat_alloc_output_context2(
match avformat_alloc_output_context2(&mut ps, format.as_ptr() as *mut _, ptr::null(), path.as_ptr()) { &mut ps,
0 => { format.as_ptr() as *mut _,
match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) { ptr::null(),
path.as_ptr(),
) {
0 => match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
0 => Ok(Context::Output(context::Output::wrap(ps))), 0 => Ok(Context::Output(context::Output::wrap(ps))),
e => Err(Error::from(e)), e => Err(Error::from(e)),
} },
}
e => Err(Error::from(e)) e => Err(Error::from(e)),
} },
}
} }
} }
} }
pub fn open_with<P: AsRef<Path>>(path: &P, format: &Format, options: Dictionary) -> Result<Context, Error> { pub fn open_with<P: AsRef<Path>>(
path: &P,
format: &Format,
options: Dictionary,
) -> Result<Context, Error> {
unsafe { unsafe {
let mut ps = ptr::null_mut(); let mut ps = ptr::null_mut();
let path = from_path(path); let path = from_path(path);
let mut opts = options.disown(); let mut opts = options.disown();
match format { match *format {
&Format::Input(ref format) => { Format::Input(ref format) => {
let res = avformat_open_input(&mut ps, path.as_ptr(), format.as_ptr() as *mut _, &mut opts); let res = avformat_open_input(
&mut ps,
path.as_ptr(),
format.as_ptr() as *mut _,
&mut opts,
);
Dictionary::own(opts); Dictionary::own(opts);
match res { match res {
0 => { 0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
match avformat_find_stream_info(ps, ptr::null_mut()) {
r if r >= 0 => Ok(Context::Input(context::Input::wrap(ps))), r if r >= 0 => Ok(Context::Input(context::Input::wrap(ps))),
e => Err(Error::from(e)), e => Err(Error::from(e)),
} },
}
e => Err(Error::from(e))
}
}
&Format::Output(ref format) => {
match avformat_alloc_output_context2(&mut ps, format.as_ptr() as *mut _, ptr::null(), path.as_ptr()) {
0 => {
match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
0 => Ok(Context::Output(context::Output::wrap(ps))),
e => Err(Error::from(e)), e => Err(Error::from(e)),
} }
} }
e => Err(Error::from(e)) Format::Output(ref format) => match avformat_alloc_output_context2(
} &mut ps,
} format.as_ptr() as *mut _,
ptr::null(),
path.as_ptr(),
) {
0 => match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
0 => Ok(Context::Output(context::Output::wrap(ps))),
e => Err(Error::from(e)),
},
e => Err(Error::from(e)),
},
} }
} }
} }
@ -146,19 +150,23 @@ pub fn input<P: AsRef<Path>>(path: &P) -> Result<context::Input, Error> {
let path = from_path(path); let path = from_path(path);
match avformat_open_input(&mut ps, path.as_ptr(), ptr::null_mut(), ptr::null_mut()) { match avformat_open_input(&mut ps, path.as_ptr(), ptr::null_mut(), ptr::null_mut()) {
0 => { 0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
match avformat_find_stream_info(ps, ptr::null_mut()) {
r if r >= 0 => Ok(context::Input::wrap(ps)), r if r >= 0 => Ok(context::Input::wrap(ps)),
e => Err(Error::from(e)), e => {
} avformat_close_input(&mut ps);
Err(Error::from(e))
} }
},
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
pub fn input_with_dictionary<P: AsRef<Path>>(path: &P, options: Dictionary) -> Result<context::Input, Error> { pub fn input_with_dictionary<P: AsRef<Path>>(
path: &P,
options: Dictionary,
) -> Result<context::Input, Error> {
unsafe { unsafe {
let mut ps = ptr::null_mut(); let mut ps = ptr::null_mut();
let path = from_path(path); let path = from_path(path);
@ -168,34 +176,41 @@ pub fn input_with_dictionary<P: AsRef<Path>>(path: &P, options: Dictionary) -> R
Dictionary::own(opts); Dictionary::own(opts);
match res { match res {
0 => { 0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
match avformat_find_stream_info(ps, ptr::null_mut()) {
r if r >= 0 => Ok(context::Input::wrap(ps)), r if r >= 0 => Ok(context::Input::wrap(ps)),
e => Err(Error::from(e)), e => {
} avformat_close_input(&mut ps);
Err(Error::from(e))
} }
},
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
pub fn input_with_interrupt<P: AsRef<Path>, F>(path: &P, closure: F) -> Result<context::Input, Error> pub fn input_with_interrupt<P: AsRef<Path>, F>(
where F: FnMut() -> bool { path: &P,
closure: F,
) -> Result<context::Input, Error>
where
F: FnMut() -> bool,
{
unsafe { unsafe {
let mut ps = avformat_alloc_context(); let mut ps = avformat_alloc_context();
let path = from_path(path); let path = from_path(path);
(*ps).interrupt_callback = interrupt::new(Box::new(closure)).interrupt; (*ps).interrupt_callback = interrupt::new(Box::new(closure)).interrupt;
match avformat_open_input(&mut ps, path.as_ptr(), ptr::null_mut(), ptr::null_mut()) { match avformat_open_input(&mut ps, path.as_ptr(), ptr::null_mut(), ptr::null_mut()) {
0 => { 0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
match avformat_find_stream_info(ps, ptr::null_mut()) {
r if r >= 0 => Ok(context::Input::wrap(ps)), r if r >= 0 => Ok(context::Input::wrap(ps)),
e => Err(Error::from(e)), e => {
} avformat_close_input(&mut ps);
Err(Error::from(e))
} }
},
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -206,19 +221,20 @@ pub fn output<P: AsRef<Path>>(path: &P) -> Result<context::Output, Error> {
let path = from_path(path); let path = from_path(path);
match avformat_alloc_output_context2(&mut ps, ptr::null_mut(), ptr::null(), path.as_ptr()) { match avformat_alloc_output_context2(&mut ps, ptr::null_mut(), ptr::null(), path.as_ptr()) {
0 => { 0 => match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
0 => Ok(context::Output::wrap(ps)), 0 => Ok(context::Output::wrap(ps)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} },
}
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
pub fn output_with<P: AsRef<Path>>(path: &P, options: Dictionary) -> Result<context::Output, Error> { pub fn output_with<P: AsRef<Path>>(
path: &P,
options: Dictionary,
) -> Result<context::Output, Error> {
unsafe { unsafe {
let mut ps = ptr::null_mut(); let mut ps = ptr::null_mut();
let path = from_path(path); let path = from_path(path);
@ -226,17 +242,23 @@ pub fn output_with<P: AsRef<Path>>(path: &P, options: Dictionary) -> Result<cont
match avformat_alloc_output_context2(&mut ps, ptr::null_mut(), ptr::null(), path.as_ptr()) { match avformat_alloc_output_context2(&mut ps, ptr::null_mut(), ptr::null(), path.as_ptr()) {
0 => { 0 => {
let res = avio_open2(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE, ptr::null(), &mut opts,); let res = avio_open2(
&mut (*ps).pb,
path.as_ptr(),
AVIO_FLAG_WRITE,
ptr::null(),
&mut opts,
);
Dictionary::own(opts); Dictionary::own(opts);
match res { match res {
0 => Ok(context::Output::wrap(ps)), 0 => Ok(context::Output::wrap(ps)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
@ -247,39 +269,57 @@ pub fn output_as<P: AsRef<Path>>(path: &P, format: &str) -> Result<context::Outp
let path = from_path(path); let path = from_path(path);
let format = CString::new(format).unwrap(); let format = CString::new(format).unwrap();
match avformat_alloc_output_context2(&mut ps, ptr::null_mut(), format.as_ptr(), path.as_ptr()) { match avformat_alloc_output_context2(
0 => { &mut ps,
match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) { ptr::null_mut(),
format.as_ptr(),
path.as_ptr(),
) {
0 => match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
0 => Ok(context::Output::wrap(ps)), 0 => Ok(context::Output::wrap(ps)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} },
}
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }
pub fn output_as_with<P: AsRef<Path>>(path: &P, format: &str, options: Dictionary) -> Result<context::Output, Error> { pub fn output_as_with<P: AsRef<Path>>(
path: &P,
format: &str,
options: Dictionary,
) -> Result<context::Output, Error> {
unsafe { unsafe {
let mut ps = ptr::null_mut(); let mut ps = ptr::null_mut();
let path = from_path(path); let path = from_path(path);
let format = CString::new(format).unwrap(); let format = CString::new(format).unwrap();
let mut opts = options.disown(); let mut opts = options.disown();
match avformat_alloc_output_context2(&mut ps, ptr::null_mut(), format.as_ptr(), path.as_ptr()) { match avformat_alloc_output_context2(
&mut ps,
ptr::null_mut(),
format.as_ptr(),
path.as_ptr(),
) {
0 => { 0 => {
let res = avio_open2(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE, ptr::null(), &mut opts,); let res = avio_open2(
&mut (*ps).pb,
path.as_ptr(),
AVIO_FLAG_WRITE,
ptr::null(),
&mut opts,
);
Dictionary::own(opts); Dictionary::own(opts);
match res { match res {
0 => Ok(context::Output::wrap(ps)), 0 => Ok(context::Output::wrap(ps)),
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
e => Err(Error::from(e)) e => Err(Error::from(e)),
} }
} }
} }

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
bitflags! { bitflags! {
pub struct Disposition: c_int { pub struct Disposition: c_int {

View File

@ -1,9 +1,9 @@
use libc::c_int;
use ffi::*;
use ::codec::{self, packet};
use ::{Rational, Discard, DictionaryRef};
use super::Disposition; use super::Disposition;
use codec::{self, packet};
use ffi::*;
use format::context::common::Context; use format::context::common::Context;
use libc::c_int;
use {DictionaryRef, Discard, Rational};
pub struct Stream<'a> { pub struct Stream<'a> {
context: &'a Context, context: &'a Context,
@ -12,7 +12,10 @@ pub struct Stream<'a> {
impl<'a> Stream<'a> { impl<'a> Stream<'a> {
pub unsafe fn wrap(context: &Context, index: usize) -> Stream { pub unsafe fn wrap(context: &Context, index: usize) -> Stream {
Stream { context: context, index: index } Stream {
context: context,
index: index,
}
} }
pub unsafe fn as_ptr(&self) -> *const AVStream { pub unsafe fn as_ptr(&self) -> *const AVStream {
@ -22,15 +25,11 @@ impl<'a> Stream<'a> {
impl<'a> Stream<'a> { impl<'a> Stream<'a> {
pub fn id(&self) -> i32 { pub fn id(&self) -> i32 {
unsafe { unsafe { (*self.as_ptr()).id }
i32::from((*self.as_ptr()).id)
}
} }
pub fn codec(&self) -> codec::Context { pub fn codec(&self) -> codec::Context {
unsafe { unsafe { codec::Context::wrap((*self.as_ptr()).codec, Some(self.context.destructor())) }
codec::Context::wrap((*self.as_ptr()).codec, Some(self.context.destructor()))
}
} }
pub fn parameters(&self) -> codec::Parameters { pub fn parameters(&self) -> codec::Parameters {
@ -40,45 +39,31 @@ impl<'a> Stream<'a> {
} }
pub fn index(&self) -> usize { pub fn index(&self) -> usize {
unsafe { unsafe { (*self.as_ptr()).index as usize }
(*self.as_ptr()).index as usize
}
} }
pub fn time_base(&self) -> Rational { pub fn time_base(&self) -> Rational {
unsafe { unsafe { Rational::from((*self.as_ptr()).time_base) }
Rational::from((*self.as_ptr()).time_base)
}
} }
pub fn start_time(&self) -> i64 { pub fn start_time(&self) -> i64 {
unsafe { unsafe { (*self.as_ptr()).start_time }
(*self.as_ptr()).start_time
}
} }
pub fn duration(&self) -> i64 { pub fn duration(&self) -> i64 {
unsafe { unsafe { (*self.as_ptr()).duration }
(*self.as_ptr()).duration
}
} }
pub fn frames(&self) -> i64 { pub fn frames(&self) -> i64 {
unsafe { unsafe { (*self.as_ptr()).nb_frames }
(*self.as_ptr()).nb_frames
}
} }
pub fn disposition(&self) -> Disposition { pub fn disposition(&self) -> Disposition {
unsafe { unsafe { Disposition::from_bits_truncate((*self.as_ptr()).disposition) }
Disposition::from_bits_truncate((*self.as_ptr()).disposition)
}
} }
pub fn discard(&self) -> Discard { pub fn discard(&self) -> Discard {
unsafe { unsafe { Discard::from((*self.as_ptr()).discard) }
Discard::from((*self.as_ptr()).discard)
}
} }
pub fn side_data(&self) -> SideDataIter { pub fn side_data(&self) -> SideDataIter {
@ -86,33 +71,25 @@ impl<'a> Stream<'a> {
} }
pub fn rate(&self) -> Rational { pub fn rate(&self) -> Rational {
unsafe { unsafe { Rational::from(av_stream_get_r_frame_rate(self.as_ptr())) }
Rational::from(av_stream_get_r_frame_rate(self.as_ptr()))
}
} }
pub fn avg_frame_rate(&self) -> Rational { pub fn avg_frame_rate(&self) -> Rational {
unsafe { unsafe { Rational::from((*self.as_ptr()).avg_frame_rate) }
Rational::from((*self.as_ptr()).avg_frame_rate)
}
} }
pub fn metadata(&self) -> DictionaryRef { pub fn metadata(&self) -> DictionaryRef {
unsafe { unsafe { DictionaryRef::wrap((*self.as_ptr()).metadata) }
DictionaryRef::wrap((*self.as_ptr()).metadata)
}
} }
} }
impl<'a> PartialEq for Stream<'a> { impl<'a> PartialEq for Stream<'a> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
unsafe { unsafe { self.as_ptr() == other.as_ptr() }
self.as_ptr() == other.as_ptr()
}
} }
} }
impl<'a> Eq for Stream<'a> { } impl<'a> Eq for Stream<'a> {}
pub struct SideDataIter<'a> { pub struct SideDataIter<'a> {
stream: &'a Stream<'a>, stream: &'a Stream<'a>,
@ -121,7 +98,10 @@ pub struct SideDataIter<'a> {
impl<'a> SideDataIter<'a> { impl<'a> SideDataIter<'a> {
pub fn new<'sd, 's: 'sd>(stream: &'s Stream) -> SideDataIter<'sd> { pub fn new<'sd, 's: 'sd>(stream: &'s Stream) -> SideDataIter<'sd> {
SideDataIter { stream: stream, current: 0 } SideDataIter {
stream: stream,
current: 0,
}
} }
} }
@ -137,7 +117,10 @@ impl<'a> Iterator for SideDataIter<'a> {
self.current += 1; self.current += 1;
Some(packet::SideData::wrap( Some(packet::SideData::wrap(
(*self.stream.as_ptr()).side_data.offset((self.current - 1) as isize))) (*self.stream.as_ptr())
.side_data
.offset((self.current - 1) as isize),
))
} }
} }
@ -145,9 +128,12 @@ impl<'a> Iterator for SideDataIter<'a> {
unsafe { unsafe {
let length = (*self.stream.as_ptr()).nb_side_data as usize; let length = (*self.stream.as_ptr()).nb_side_data as usize;
(length - self.current as usize, Some(length - self.current as usize)) (
length - self.current as usize,
Some(length - self.current as usize),
)
} }
} }
} }
impl<'a> ExactSizeIterator for SideDataIter<'a> { } impl<'a> ExactSizeIterator for SideDataIter<'a> {}

View File

@ -1,10 +1,10 @@
use std::ops::Deref;
use std::mem; use std::mem;
use std::ops::Deref;
use ffi::*;
use ::{Rational, codec};
use super::Stream; use super::Stream;
use ffi::*;
use format::context::common::Context; use format::context::common::Context;
use {codec, Rational};
pub struct StreamMut<'a> { pub struct StreamMut<'a> {
context: &'a mut Context, context: &'a mut Context,
@ -19,12 +19,14 @@ impl<'a> StreamMut<'a> {
context: mem::transmute_copy(&context), context: mem::transmute_copy(&context),
index: index, index: index,
immutable: Stream::wrap(mem::transmute_copy(&context), index) immutable: Stream::wrap(mem::transmute_copy(&context), index),
} }
} }
pub unsafe fn as_mut_ptr(&mut self) -> *mut AVStream { pub unsafe fn as_mut_ptr(&mut self) -> *mut AVStream {
*(*self.context.as_mut_ptr()).streams.offset(self.index as isize) *(*self.context.as_mut_ptr())
.streams
.offset(self.index as isize)
} }
} }

View File

@ -1,59 +1,62 @@
#![allow(non_camel_case_types)] #![allow(non_camel_case_types)]
#![cfg_attr(feature = "cargo-clippy", allow(inline_always))]
extern crate libc; #[macro_use]
extern crate bitflags;
pub extern crate ffmpeg_sys as sys; pub extern crate ffmpeg_sys as sys;
#[macro_use] extern crate bitflags; #[cfg(feature = "image")]
#[cfg(feature = "image")] extern crate image; extern crate image;
extern crate libc;
pub use sys as ffi; pub use sys as ffi;
#[macro_use] #[macro_use]
pub mod util; pub mod util;
pub use util::error::Error; pub use util::channel_layout::{self, ChannelLayout};
pub use util::chroma;
pub use util::color;
pub use util::dictionary; pub use util::dictionary;
pub use util::dictionary::Mut as DictionaryMut;
pub use util::dictionary::Owned as Dictionary; pub use util::dictionary::Owned as Dictionary;
pub use util::dictionary::Ref as DictionaryRef; pub use util::dictionary::Ref as DictionaryRef;
pub use util::dictionary::Mut as DictionaryMut; pub use util::error::Error;
pub use util::rational::{self, Rational};
pub use util::media;
pub use util::picture;
pub use util::color;
pub use util::chroma;
pub use util::time;
pub use util::frame::{self, Frame}; pub use util::frame::{self, Frame};
pub use util::channel_layout::{self, ChannelLayout}; pub use util::mathematics::{self, rescale, Rescale, Rounding};
pub use util::media;
pub use util::option; pub use util::option;
pub use util::mathematics::{self, Rounding, Rescale, rescale}; pub use util::picture;
pub use util::rational::{self, Rational};
pub use util::time;
#[cfg(feature = "format")] #[cfg(feature = "format")]
pub mod format; pub mod format;
#[cfg(feature = "format")] #[cfg(feature = "format")]
pub use format::chapter::{Chapter, ChapterMut};
#[cfg(feature = "format")]
pub use format::format::Format; pub use format::format::Format;
#[cfg(feature = "format")] #[cfg(feature = "format")]
pub use format::stream::{Stream, StreamMut}; pub use format::stream::{Stream, StreamMut};
#[cfg(feature = "format")]
pub use format::chapter::{Chapter, ChapterMut};
#[cfg(feature = "codec")] #[cfg(feature = "codec")]
pub mod codec; pub mod codec;
#[cfg(feature = "codec")] #[cfg(feature = "codec")]
pub use codec::packet::{self, Packet}; pub use codec::audio_service::AudioService;
#[cfg(feature = "codec")]
pub use codec::subtitle::{self, Subtitle};
#[cfg(feature = "codec")]
pub use codec::picture::Picture;
#[cfg(feature = "codec")]
pub use codec::discard::Discard;
#[cfg(feature = "codec")] #[cfg(feature = "codec")]
pub use codec::codec::Codec; pub use codec::codec::Codec;
#[cfg(feature = "codec")] #[cfg(feature = "codec")]
pub use codec::{decoder, encoder}; pub use codec::discard::Discard;
#[cfg(feature = "codec")] #[cfg(feature = "codec")]
pub use codec::field_order::FieldOrder; pub use codec::field_order::FieldOrder;
#[cfg(feature = "codec")] #[cfg(feature = "codec")]
pub use codec::audio_service::AudioService; pub use codec::packet::{self, Packet};
#[cfg(feature = "codec")]
pub use codec::picture::Picture;
#[cfg(feature = "codec")]
pub use codec::subtitle::{self, Subtitle};
#[cfg(feature = "codec")] #[cfg(feature = "codec")]
pub use codec::threading; pub use codec::threading;
#[cfg(feature = "codec")]
pub use codec::{decoder, encoder};
#[cfg(feature = "device")] #[cfg(feature = "device")]
pub mod device; pub mod device;
@ -75,7 +78,7 @@ fn init_format() {
} }
#[cfg(not(feature = "format"))] #[cfg(not(feature = "format"))]
fn init_format() { } fn init_format() {}
#[cfg(feature = "device")] #[cfg(feature = "device")]
fn init_device() { fn init_device() {
@ -83,7 +86,7 @@ fn init_device() {
} }
#[cfg(not(feature = "device"))] #[cfg(not(feature = "device"))]
fn init_device() { } fn init_device() {}
#[cfg(feature = "filter")] #[cfg(feature = "filter")]
fn init_filter() { fn init_filter() {
@ -91,7 +94,7 @@ fn init_filter() {
} }
#[cfg(not(feature = "filter"))] #[cfg(not(feature = "filter"))]
fn init_filter() { } fn init_filter() {}
pub fn init() -> Result<(), Error> { pub fn init() -> Result<(), Error> {
init_error(); init_error();

View File

@ -3,20 +3,33 @@ pub mod scaling;
#[cfg(feature = "software-scaling")] #[cfg(feature = "software-scaling")]
#[inline] #[inline]
pub fn scaler(format: ::format::Pixel, flags: scaling::Flags, pub fn scaler(
format: ::format::Pixel,
flags: scaling::Flags,
(in_width, in_height): (u32, u32), (in_width, in_height): (u32, u32),
(out_width, out_height): (u32, u32)) (out_width, out_height): (u32, u32),
-> Result<scaling::Context, ::Error> { ) -> Result<scaling::Context, ::Error> {
scaling::Context::get(format, in_width, in_height, format, out_width, out_height, flags) scaling::Context::get(
format, in_width, in_height, format, out_width, out_height, flags,
)
} }
#[cfg(feature = "software-scaling")] #[cfg(feature = "software-scaling")]
#[inline] #[inline]
pub fn converter((width, height): (u32, u32), pub fn converter(
(width, height): (u32, u32),
input: ::format::Pixel, input: ::format::Pixel,
output: ::format::Pixel) output: ::format::Pixel,
-> Result<scaling::Context, ::Error> { ) -> Result<scaling::Context, ::Error> {
scaling::Context::get(input, width, height, output, width, height, scaling::flag::FAST_BILINEAR) scaling::Context::get(
input,
width,
height,
output,
width,
height,
scaling::flag::FAST_BILINEAR,
)
} }
#[cfg(feature = "software-resampling")] #[cfg(feature = "software-resampling")]
@ -24,8 +37,11 @@ pub mod resampling;
#[cfg(feature = "software-resampling")] #[cfg(feature = "software-resampling")]
#[inline] #[inline]
pub fn resampler((in_format, in_layout, in_rate): (::format::Sample, ::ChannelLayout, u32), pub fn resampler(
(out_format, out_layout, out_rate): (::format::Sample, ::ChannelLayout, u32)) (in_format, in_layout, in_rate): (::format::Sample, ::ChannelLayout, u32),
-> Result<resampling::Context, ::Error> { (out_format, out_layout, out_rate): (::format::Sample, ::ChannelLayout, u32),
resampling::Context::get(in_format, in_layout, in_rate, out_format, out_layout, out_rate) ) -> Result<resampling::Context, ::Error> {
resampling::Context::get(
in_format, in_layout, in_rate, out_format, out_layout, out_rate,
)
} }

View File

@ -1,10 +1,10 @@
use std::ptr; use std::ptr;
use libc::{c_int, int64_t};
use ffi::*;
use ::util::format;
use ::{Error, ChannelLayout, frame};
use super::Delay; use super::Delay;
use ffi::*;
use libc::{c_int, int64_t};
use util::format;
use {frame, ChannelLayout, Error};
#[derive(Eq, PartialEq, Copy, Clone)] #[derive(Eq, PartialEq, Copy, Clone)]
pub struct Definition { pub struct Definition {
@ -34,21 +34,32 @@ impl Context {
impl Context { impl Context {
/// Create a resampler with the given definitions. /// Create a resampler with the given definitions.
pub fn get(src_format: format::Sample, src_channel_layout: ChannelLayout, src_rate: u32, pub fn get(
dst_format: format::Sample, dst_channel_layout: ChannelLayout, dst_rate: u32) -> Result<Self, Error> { src_format: format::Sample,
src_channel_layout: ChannelLayout,
src_rate: u32,
dst_format: format::Sample,
dst_channel_layout: ChannelLayout,
dst_rate: u32,
) -> Result<Self, Error> {
unsafe { unsafe {
let ptr = swr_alloc_set_opts(ptr::null_mut(), let ptr = swr_alloc_set_opts(
dst_channel_layout.bits() as int64_t, dst_format.into(), dst_rate as c_int, ptr::null_mut(),
src_channel_layout.bits() as int64_t, src_format.into(), src_rate as c_int, dst_channel_layout.bits() as int64_t,
0, ptr::null_mut()); dst_format.into(),
dst_rate as c_int,
src_channel_layout.bits() as int64_t,
src_format.into(),
src_rate as c_int,
0,
ptr::null_mut(),
);
if ptr != ptr::null_mut() { if ptr.is_null() {
match swr_init(ptr) { match swr_init(ptr) {
e if e < 0 => e if e < 0 => Err(Error::from(e)),
Err(Error::from(e)),
_ => _ => Ok(Context {
Ok(Context {
ptr: ptr, ptr: ptr,
input: Definition { input: Definition {
@ -61,11 +72,10 @@ impl Context {
format: dst_format, format: dst_format,
channel_layout: dst_channel_layout, channel_layout: dst_channel_layout,
rate: dst_rate, rate: dst_rate,
},
}),
} }
}) } else {
}
}
else {
Err(Error::InvalidData) Err(Error::InvalidData)
} }
} }
@ -86,7 +96,7 @@ impl Context {
unsafe { unsafe {
match swr_get_delay(self.as_ptr() as *mut _, 1) { match swr_get_delay(self.as_ptr() as *mut _, 1) {
0 => None, 0 => None,
_ => Some(Delay::from(self)) _ => Some(Delay::from(self)),
} }
} }
} }
@ -94,20 +104,26 @@ impl Context {
/// Run the resampler from the given input to the given output. /// Run the resampler from the given input to the given output.
/// ///
/// When there are internal frames to process it will return `Ok(Some(Delay { .. }))`. /// When there are internal frames to process it will return `Ok(Some(Delay { .. }))`.
pub fn run(&mut self, input: &frame::Audio, output: &mut frame::Audio) -> Result<Option<Delay>, Error> { pub fn run(
&mut self,
input: &frame::Audio,
output: &mut frame::Audio,
) -> Result<Option<Delay>, Error> {
output.set_rate(self.output.rate); output.set_rate(self.output.rate);
unsafe { unsafe {
if output.is_empty() { if output.is_empty() {
output.alloc(self.output.format, input.samples(), self.output.channel_layout); output.alloc(
self.output.format,
input.samples(),
self.output.channel_layout,
);
} }
match swr_convert_frame(self.as_mut_ptr(), output.as_mut_ptr(), input.as_ptr()) { match swr_convert_frame(self.as_mut_ptr(), output.as_mut_ptr(), input.as_ptr()) {
0 => 0 => Ok(self.delay()),
Ok(self.delay()),
e => e => Err(Error::from(e)),
Err(Error::from(e))
} }
} }
} }
@ -120,11 +136,9 @@ impl Context {
unsafe { unsafe {
match swr_convert_frame(self.as_mut_ptr(), output.as_mut_ptr(), ptr::null()) { match swr_convert_frame(self.as_mut_ptr(), output.as_mut_ptr(), ptr::null()) {
0 => 0 => Ok(self.delay()),
Ok(self.delay()),
e => e => Err(Error::from(e)),
Err(Error::from(e))
} }
} }
} }

View File

@ -1,6 +1,5 @@
use libc::int64_t;
use ffi::*;
use super::Context; use super::Context;
use ffi::*;
#[derive(PartialEq, Eq, Copy, Clone, Debug)] #[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub struct Delay { pub struct Delay {
@ -16,8 +15,8 @@ impl Delay {
Delay { Delay {
seconds: swr_get_delay(context.as_ptr() as *mut _, 1), seconds: swr_get_delay(context.as_ptr() as *mut _, 1),
milliseconds: swr_get_delay(context.as_ptr() as *mut _, 1000), milliseconds: swr_get_delay(context.as_ptr() as *mut _, 1000),
input: swr_get_delay(context.as_ptr() as *mut _, context.input().rate as int64_t), input: swr_get_delay(context.as_ptr() as *mut _, i64::from(context.input().rate)),
output: swr_get_delay(context.as_ptr() as *mut _, context.output().rate as int64_t), output: swr_get_delay(context.as_ptr() as *mut _, i64::from(context.output().rate)),
} }
} }
} }

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::SwrDitherType::*; use ffi::SwrDitherType::*;
use ffi::*;
#[derive(Eq, PartialEq, Copy, Clone, Debug)] #[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Dither { pub enum Dither {

View File

@ -1,19 +1,41 @@
use util::format;
use ::{decoder, Error, ChannelLayout, frame};
use super::Context; use super::Context;
use util::format;
use {decoder, frame, ChannelLayout, Error};
impl frame::Audio { impl frame::Audio {
#[inline] #[inline]
pub fn resampler(&self, format: format::Sample, channel_layout: ChannelLayout, rate: u32) -> Result<Context, Error> { pub fn resampler(
Context::get(self.format(), self.channel_layout(), self.rate(), &self,
format, channel_layout, rate) format: format::Sample,
channel_layout: ChannelLayout,
rate: u32,
) -> Result<Context, Error> {
Context::get(
self.format(),
self.channel_layout(),
self.rate(),
format,
channel_layout,
rate,
)
} }
} }
impl decoder::Audio { impl decoder::Audio {
#[inline] #[inline]
pub fn resampler(&self, format: format::Sample, channel_layout: ChannelLayout, rate: u32) -> Result<Context, Error> { pub fn resampler(
Context::get(self.format(), self.channel_layout(), self.rate(), &self,
format, channel_layout, rate) format: format::Sample,
channel_layout: ChannelLayout,
rate: u32,
) -> Result<Context, Error> {
Context::get(
self.format(),
self.channel_layout(),
self.rate(),
format,
channel_layout,
rate,
)
} }
} }

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::SwrFilterType::*; use ffi::SwrFilterType::*;
use ffi::*;
#[derive(Eq, PartialEq, Copy, Clone, Debug)] #[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Filter { pub enum Filter {

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
bitflags! { bitflags! {
pub struct Flags: c_int { pub struct Flags: c_int {

View File

@ -24,19 +24,13 @@ use std::str::from_utf8_unchecked;
use ffi::*; use ffi::*;
pub fn version() -> u32 { pub fn version() -> u32 {
unsafe { unsafe { swresample_version() }
swresample_version()
}
} }
pub fn configuration() -> &'static str { pub fn configuration() -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(swresample_configuration()).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(swresample_configuration()).to_bytes())
}
} }
pub fn license() -> &'static str { pub fn license() -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(swresample_license()).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(swresample_license()).to_bytes())
}
} }

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum ColorSpace { pub enum ColorSpace {
@ -21,7 +21,7 @@ impl From<c_int> for ColorSpace {
SWS_CS_DEFAULT => ColorSpace::Default, SWS_CS_DEFAULT => ColorSpace::Default,
SWS_CS_SMPTE240M => ColorSpace::SMPTE240M, SWS_CS_SMPTE240M => ColorSpace::SMPTE240M,
_ => ColorSpace::Default _ => ColorSpace::Default,
} }
} }
} }
@ -35,7 +35,7 @@ impl Into<c_int> for ColorSpace {
ColorSpace::ITU601 => SWS_CS_ITU601, ColorSpace::ITU601 => SWS_CS_ITU601,
ColorSpace::ITU624 => SWS_CS_ITU624, ColorSpace::ITU624 => SWS_CS_ITU624,
ColorSpace::SMPTE170M => SWS_CS_SMPTE170M, ColorSpace::SMPTE170M => SWS_CS_SMPTE170M,
ColorSpace::SMPTE240M => SWS_CS_SMPTE240M ColorSpace::SMPTE240M => SWS_CS_SMPTE240M,
} }
} }
} }

View File

@ -1,10 +1,10 @@
use std::ptr; use std::ptr;
use libc::{c_int};
use ffi::*;
use ::{Error, frame};
use ::util::format;
use super::Flags; use super::Flags;
use ffi::*;
use libc::c_int;
use util::format;
use {frame, Error};
#[derive(Eq, PartialEq, Copy, Clone, Debug)] #[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub struct Definition { pub struct Definition {
@ -33,17 +33,30 @@ impl Context {
} }
impl Context { impl Context {
pub fn get(src_format: format::Pixel, src_w: u32, src_h: u32, pub fn get(
dst_format: format::Pixel, dst_w: u32, dst_h: u32, src_format: format::Pixel,
flags: Flags) -> Result<Self, Error> { src_w: u32,
src_h: u32,
dst_format: format::Pixel,
dst_w: u32,
dst_h: u32,
flags: Flags,
) -> Result<Self, Error> {
unsafe { unsafe {
let ptr = sws_getContext( let ptr = sws_getContext(
src_w as c_int, src_h as c_int, src_format.into(), src_w as c_int,
dst_w as c_int, dst_h as c_int, dst_format.into(), src_h as c_int,
src_format.into(),
dst_w as c_int,
dst_h as c_int,
dst_format.into(),
flags.bits(), flags.bits(),
ptr::null_mut(), ptr::null_mut(), ptr::null_mut()); ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
);
if ptr != ptr::null_mut() { if ptr.is_null() {
Ok(Context { Ok(Context {
ptr: ptr, ptr: ptr,
@ -59,17 +72,22 @@ impl Context {
height: dst_h, height: dst_h,
}, },
}) })
} } else {
else {
Err(Error::InvalidData) Err(Error::InvalidData)
} }
} }
} }
pub fn cached(&mut self, pub fn cached(
src_format: format::Pixel, src_w: u32, src_h: u32, &mut self,
dst_format: format::Pixel, dst_w: u32, dst_h: u32, src_format: format::Pixel,
flags: Flags) { src_w: u32,
src_h: u32,
dst_format: format::Pixel,
dst_w: u32,
dst_h: u32,
flags: Flags,
) {
self.input = Definition { self.input = Definition {
format: src_format, format: src_format,
width: src_w, width: src_w,
@ -83,10 +101,19 @@ impl Context {
}; };
unsafe { unsafe {
self.ptr = sws_getCachedContext(self.as_mut_ptr(), self.ptr = sws_getCachedContext(
src_w as c_int, src_h as c_int, src_format.into(), self.as_mut_ptr(),
dst_w as c_int, dst_h as c_int, dst_format.into(), src_w as c_int,
flags.bits(), ptr::null_mut(), ptr::null_mut(), ptr::null()); src_h as c_int,
src_format.into(),
dst_w as c_int,
dst_h as c_int,
dst_format.into(),
flags.bits(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null(),
);
} }
} }
@ -101,7 +128,9 @@ impl Context {
} }
pub fn run(&mut self, input: &frame::Video, output: &mut frame::Video) -> Result<(), Error> { pub fn run(&mut self, input: &frame::Video, output: &mut frame::Video) -> Result<(), Error> {
if input.format() != self.input.format || input.width() != self.input.width || input.height() != self.input.height { if input.format() != self.input.format || input.width() != self.input.width
|| input.height() != self.input.height
{
return Err(Error::InputChanged); return Err(Error::InputChanged);
} }
@ -111,15 +140,22 @@ impl Context {
} }
} }
if output.format() != self.output.format || output.width() != self.output.width || output.height() != self.output.height { if output.format() != self.output.format || output.width() != self.output.width
|| output.height() != self.output.height
{
return Err(Error::OutputChanged); return Err(Error::OutputChanged);
} }
unsafe { unsafe {
sws_scale(self.as_mut_ptr(), sws_scale(
(*input.as_ptr()).data.as_ptr() as *const *const _, (*input.as_ptr()).linesize.as_ptr() as *const _, self.as_mut_ptr(),
0, self.output.height as c_int, (*input.as_ptr()).data.as_ptr() as *const *const _,
(*output.as_mut_ptr()).data.as_ptr() as *const *const _, (*output.as_mut_ptr()).linesize.as_ptr() as *mut _); (*input.as_ptr()).linesize.as_ptr() as *const _,
0,
self.output.height as c_int,
(*output.as_mut_ptr()).data.as_ptr() as *const *const _,
(*output.as_mut_ptr()).linesize.as_ptr() as *mut _,
);
} }
Ok(()) Ok(())

View File

@ -1,52 +1,87 @@
use super::{flag, Context, Flags};
use util::format; use util::format;
use ::{Picture, decoder, Error, frame}; use {decoder, frame, Error, Picture};
use super::{Context, Flags, flag};
impl<'a> Picture<'a> { impl<'a> Picture<'a> {
#[inline] #[inline]
pub fn scaler(&self, width: u32, height: u32, flags: Flags) -> Result<Context, Error> { pub fn scaler(&self, width: u32, height: u32, flags: Flags) -> Result<Context, Error> {
Context::get(self.format(), self.width(), self.height(), Context::get(
self.format(), width, height, self.format(),
flags) self.width(),
self.height(),
self.format(),
width,
height,
flags,
)
} }
#[inline] #[inline]
pub fn converter(&self, format: format::Pixel) -> Result<Context, Error> { pub fn converter(&self, format: format::Pixel) -> Result<Context, Error> {
Context::get(self.format(), self.width(), self.height(), Context::get(
format, self.width(), self.height(), self.format(),
flag::FAST_BILINEAR) self.width(),
self.height(),
format,
self.width(),
self.height(),
flag::FAST_BILINEAR,
)
} }
} }
impl frame::Video { impl frame::Video {
#[inline] #[inline]
pub fn scaler(&self, width: u32, height: u32, flags: Flags) -> Result<Context, Error> { pub fn scaler(&self, width: u32, height: u32, flags: Flags) -> Result<Context, Error> {
Context::get(self.format(), self.width(), self.height(), Context::get(
self.format(), width, height, self.format(),
flags) self.width(),
self.height(),
self.format(),
width,
height,
flags,
)
} }
#[inline] #[inline]
pub fn converter(&self, format: format::Pixel) -> Result<Context, Error> { pub fn converter(&self, format: format::Pixel) -> Result<Context, Error> {
Context::get(self.format(), self.width(), self.height(), Context::get(
format, self.width(), self.height(), self.format(),
flag::FAST_BILINEAR) self.width(),
self.height(),
format,
self.width(),
self.height(),
flag::FAST_BILINEAR,
)
} }
} }
impl decoder::Video { impl decoder::Video {
#[inline] #[inline]
pub fn scaler(&self, width: u32, height: u32, flags: Flags) -> Result<Context, Error> { pub fn scaler(&self, width: u32, height: u32, flags: Flags) -> Result<Context, Error> {
Context::get(self.format(), self.width(), self.height(), Context::get(
self.format(), width, height, self.format(),
flags) self.width(),
self.height(),
self.format(),
width,
height,
flags,
)
} }
#[inline] #[inline]
pub fn converter(&self, format: format::Pixel) -> Result<Context, Error> { pub fn converter(&self, format: format::Pixel) -> Result<Context, Error> {
Context::get(self.format(), self.width(), self.height(), Context::get(
format, self.width(), self.height(), self.format(),
flag::FAST_BILINEAR) self.width(),
self.height(),
format,
self.width(),
self.height(),
flag::FAST_BILINEAR,
)
} }
} }

View File

@ -1,5 +1,5 @@
use ffi::*;
use super::Vector; use super::Vector;
use ffi::*;
pub struct Filter { pub struct Filter {
ptr: *mut SwsFilter, ptr: *mut SwsFilter,
@ -16,14 +16,25 @@ impl Filter {
} }
impl Filter { impl Filter {
pub fn get(luma_g_blur: f32, chroma_g_blur: f32, pub fn get(
luma_sharpen: f32, chroma_sharpen: f32, luma_g_blur: f32,
chroma_h_shift: f32, chroma_v_shift: f32) -> Self { chroma_g_blur: f32,
luma_sharpen: f32,
chroma_sharpen: f32,
chroma_h_shift: f32,
chroma_v_shift: f32,
) -> Self {
unsafe { unsafe {
Filter { Filter {
ptr: sws_getDefaultFilter(luma_g_blur, chroma_g_blur, ptr: sws_getDefaultFilter(
luma_sharpen, chroma_sharpen, luma_g_blur,
chroma_h_shift, chroma_v_shift, 0) chroma_g_blur,
luma_sharpen,
chroma_sharpen,
chroma_h_shift,
chroma_v_shift,
0,
),
} }
} }
} }
@ -33,51 +44,41 @@ impl Filter {
} }
pub fn luma_horizontal(&self) -> Vector { pub fn luma_horizontal(&self) -> Vector {
unsafe { unsafe { Vector::wrap((*self.as_ptr()).lumH) }
Vector::wrap((*self.as_ptr()).lumH)
}
} }
pub fn luma_horizontal_mut(&mut self) -> Vector { pub fn luma_horizontal_mut(&mut self) -> Vector {
unsafe { unsafe { Vector::wrap((*self.as_mut_ptr()).lumH) }
Vector::wrap((*self.as_mut_ptr()).lumH)
}
} }
pub fn luma_vertical(&self) -> Vector { pub fn luma_vertical(&self) -> Vector {
unsafe { unsafe { Vector::wrap((*self.as_ptr()).lumV) }
Vector::wrap((*self.as_ptr()).lumV)
}
} }
pub fn luma_vertical_mut(&mut self) -> Vector { pub fn luma_vertical_mut(&mut self) -> Vector {
unsafe { unsafe { Vector::wrap((*self.as_mut_ptr()).lumV) }
Vector::wrap((*self.as_mut_ptr()).lumV)
}
} }
pub fn chroma_horizontal(&self) -> Vector { pub fn chroma_horizontal(&self) -> Vector {
unsafe { unsafe { Vector::wrap((*self.as_ptr()).lumV) }
Vector::wrap((*self.as_ptr()).lumV)
}
} }
pub fn chroma_horizontal_mut(&mut self) -> Vector { pub fn chroma_horizontal_mut(&mut self) -> Vector {
unsafe { unsafe { Vector::wrap((*self.as_mut_ptr()).lumV) }
Vector::wrap((*self.as_mut_ptr()).lumV)
}
} }
pub fn chroma_vertical(&self) -> Vector { pub fn chroma_vertical(&self) -> Vector {
unsafe { unsafe { Vector::wrap((*self.as_ptr()).lumV) }
Vector::wrap((*self.as_ptr()).lumV)
}
} }
pub fn chroma_vertical_mut(&mut self) -> Vector { pub fn chroma_vertical_mut(&mut self) -> Vector {
unsafe { unsafe { Vector::wrap((*self.as_mut_ptr()).lumV) }
Vector::wrap((*self.as_mut_ptr()).lumV)
} }
}
impl Default for Filter {
fn default() -> Self {
Self::new()
} }
} }

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*; use ffi::*;
use libc::c_int;
bitflags! { bitflags! {
pub struct Flags: c_int { pub struct Flags: c_int {

View File

@ -23,19 +23,13 @@ use std::str::from_utf8_unchecked;
use ffi::*; use ffi::*;
pub fn version() -> u32 { pub fn version() -> u32 {
unsafe { unsafe { swscale_version() }
swscale_version()
}
} }
pub fn configuration() -> &'static str { pub fn configuration() -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(swscale_configuration()).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(swscale_configuration()).to_bytes())
}
} }
pub fn license() -> &'static str { pub fn license() -> &'static str {
unsafe { unsafe { from_utf8_unchecked(CStr::from_ptr(swscale_license()).to_bytes()) }
from_utf8_unchecked(CStr::from_ptr(swscale_license()).to_bytes())
}
} }

View File

@ -1,20 +1,14 @@
use ffi::*; use ffi::*;
use ::util::format; use util::format;
pub fn input(format: format::Pixel) -> bool { pub fn input(format: format::Pixel) -> bool {
unsafe { unsafe { sws_isSupportedInput(format.into()) != 0 }
sws_isSupportedInput(format.into()) != 0
}
} }
pub fn output(format: format::Pixel) -> bool { pub fn output(format: format::Pixel) -> bool {
unsafe { unsafe { sws_isSupportedOutput(format.into()) != 0 }
sws_isSupportedOutput(format.into()) != 0
}
} }
pub fn endianness_conversion(format: format::Pixel) -> bool { pub fn endianness_conversion(format: format::Pixel) -> bool {
unsafe { unsafe { sws_isSupportedEndiannessConversion(format.into()) != 0 }
sws_isSupportedEndiannessConversion(format.into()) != 0
}
} }

View File

@ -1,8 +1,8 @@
use std::marker::PhantomData; use std::marker::PhantomData;
use std::slice; use std::slice;
use libc::{c_int, c_double};
use ffi::*; use ffi::*;
use libc::{c_double, c_int};
pub struct Vector<'a> { pub struct Vector<'a> {
ptr: *mut SwsVector, ptr: *mut SwsVector,
@ -13,7 +13,11 @@ pub struct Vector<'a> {
impl<'a> Vector<'a> { impl<'a> Vector<'a> {
pub unsafe fn wrap(ptr: *mut SwsVector) -> Self { pub unsafe fn wrap(ptr: *mut SwsVector) -> Self {
Vector { ptr: ptr, _own: false, _marker: PhantomData } Vector {
ptr: ptr,
_own: false,
_marker: PhantomData,
}
} }
pub unsafe fn as_ptr(&self) -> *const SwsVector { pub unsafe fn as_ptr(&self) -> *const SwsVector {
@ -28,25 +32,41 @@ impl<'a> Vector<'a> {
impl<'a> Vector<'a> { impl<'a> Vector<'a> {
pub fn new(length: usize) -> Self { pub fn new(length: usize) -> Self {
unsafe { unsafe {
Vector { ptr: sws_allocVec(length as c_int), _own: true, _marker: PhantomData } Vector {
ptr: sws_allocVec(length as c_int),
_own: true,
_marker: PhantomData,
}
} }
} }
pub fn gaussian(variance: f64, quality: f64) -> Self { pub fn gaussian(variance: f64, quality: f64) -> Self {
unsafe { unsafe {
Vector { ptr: sws_getGaussianVec(variance as c_double, quality as c_double), _own: true, _marker: PhantomData } Vector {
ptr: sws_getGaussianVec(variance as c_double, quality as c_double),
_own: true,
_marker: PhantomData,
}
} }
} }
pub fn value(value: f64, length: usize) -> Self { pub fn value(value: f64, length: usize) -> Self {
unsafe { unsafe {
Vector { ptr: sws_getConstVec(value as c_double, length as c_int), _own: true, _marker: PhantomData } Vector {
ptr: sws_getConstVec(value as c_double, length as c_int),
_own: true,
_marker: PhantomData,
}
} }
} }
pub fn identity() -> Self { pub fn identity() -> Self {
unsafe { unsafe {
Vector { ptr: sws_getIdentityVec(), _own: true, _marker: PhantomData } Vector {
ptr: sws_getIdentityVec(),
_own: true,
_marker: PhantomData,
}
} }
} }
@ -87,16 +107,12 @@ impl<'a> Vector<'a> {
} }
pub fn coefficients(&self) -> &[f64] { pub fn coefficients(&self) -> &[f64] {
unsafe { unsafe { slice::from_raw_parts((*self.as_ptr()).coeff, (*self.as_ptr()).length as usize) }
slice::from_raw_parts((*self.as_ptr()).coeff,
(*self.as_ptr()).length as usize)
}
} }
pub fn coefficients_mut(&self) -> &[f64] { pub fn coefficients_mut(&self) -> &[f64] {
unsafe { unsafe {
slice::from_raw_parts_mut((*self.as_ptr()).coeff, slice::from_raw_parts_mut((*self.as_ptr()).coeff, (*self.as_ptr()).length as usize)
(*self.as_ptr()).length as usize)
} }
} }
} }
@ -104,7 +120,11 @@ impl<'a> Vector<'a> {
impl<'a> Clone for Vector<'a> { impl<'a> Clone for Vector<'a> {
fn clone(&self) -> Self { fn clone(&self) -> Self {
unsafe { unsafe {
Vector { ptr: sws_cloneVec(self.as_ptr() as *mut _), _own: true, _marker: PhantomData } Vector {
ptr: sws_cloneVec(self.as_ptr() as *mut _),
_own: true,
_marker: PhantomData,
}
} }
} }
} }

View File

@ -1,5 +1,5 @@
use libc::c_ulonglong;
use ffi::*; use ffi::*;
use libc::c_ulonglong;
bitflags! { bitflags! {
pub struct ChannelLayout: c_ulonglong { pub struct ChannelLayout: c_ulonglong {
@ -64,9 +64,7 @@ bitflags! {
impl ChannelLayout { impl ChannelLayout {
#[inline] #[inline]
pub fn channels(&self) -> i32 { pub fn channels(&self) -> i32 {
unsafe { unsafe { av_get_channel_layout_nb_channels(self.bits()) }
av_get_channel_layout_nb_channels(self.bits())
}
} }
pub fn default(number: i32) -> ChannelLayout { pub fn default(number: i32) -> ChannelLayout {

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::AVChromaLocation::*; use ffi::AVChromaLocation::*;
use ffi::*;
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Location { pub enum Location {
@ -22,7 +22,7 @@ impl From<AVChromaLocation> for Location {
AVCHROMA_LOC_TOP => Location::Top, AVCHROMA_LOC_TOP => Location::Top,
AVCHROMA_LOC_BOTTOMLEFT => Location::BottomLeft, AVCHROMA_LOC_BOTTOMLEFT => Location::BottomLeft,
AVCHROMA_LOC_BOTTOM => Location::Bottom, AVCHROMA_LOC_BOTTOM => Location::Bottom,
AVCHROMA_LOC_NB => Location::Unspecified AVCHROMA_LOC_NB => Location::Unspecified,
} }
} }
} }
@ -36,7 +36,7 @@ impl Into<AVChromaLocation> for Location {
Location::TopLeft => AVCHROMA_LOC_TOPLEFT, Location::TopLeft => AVCHROMA_LOC_TOPLEFT,
Location::Top => AVCHROMA_LOC_TOP, Location::Top => AVCHROMA_LOC_TOP,
Location::BottomLeft => AVCHROMA_LOC_BOTTOMLEFT, Location::BottomLeft => AVCHROMA_LOC_BOTTOMLEFT,
Location::Bottom => AVCHROMA_LOC_BOTTOM Location::Bottom => AVCHROMA_LOC_BOTTOM,
} }
} }
} }

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::AVColorPrimaries::*; use ffi::AVColorPrimaries::*;
use ffi::*;
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Primaries { pub enum Primaries {

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::AVColorRange::*; use ffi::AVColorRange::*;
use ffi::*;
#[derive(Eq, PartialEq, Clone, Copy, Debug)] #[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Range { pub enum Range {
@ -14,7 +14,7 @@ impl From<AVColorRange> for Range {
AVCOL_RANGE_UNSPECIFIED => Range::Unspecified, AVCOL_RANGE_UNSPECIFIED => Range::Unspecified,
AVCOL_RANGE_MPEG => Range::MPEG, AVCOL_RANGE_MPEG => Range::MPEG,
AVCOL_RANGE_JPEG => Range::JPEG, AVCOL_RANGE_JPEG => Range::JPEG,
AVCOL_RANGE_NB => Range::Unspecified AVCOL_RANGE_NB => Range::Unspecified,
} }
} }
} }
@ -24,7 +24,7 @@ impl Into<AVColorRange> for Range {
match self { match self {
Range::Unspecified => AVCOL_RANGE_UNSPECIFIED, Range::Unspecified => AVCOL_RANGE_UNSPECIFIED,
Range::MPEG => AVCOL_RANGE_MPEG, Range::MPEG => AVCOL_RANGE_MPEG,
Range::JPEG => AVCOL_RANGE_JPEG Range::JPEG => AVCOL_RANGE_JPEG,
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show More