*: 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
Cargo.lock
# Vim temporary files
*.swp
*.swo
*.swn

View File

@ -3,8 +3,10 @@ use std::env;
fn main() {
for (name, _value) in env::vars() {
if name.starts_with("DEP_FFMPEG_") {
println!(r#"cargo:rustc-cfg=feature="{}""#,
name["DEP_FFMPEG_".len() .. name.len()].to_lowercase());
println!(
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() {
let title = match chapter.metadata().get("title") {
@ -28,9 +29,17 @@ fn main() {
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()),
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) =>
println!("error: {}", error)
Err(error) => println!("error: {}", error),
}
}

View File

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

View File

@ -23,14 +23,20 @@ fn main() {
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() {
println!("stream index {}:", stream.index());
println!("\ttime_base: {}", stream.time_base());
println!("\tstart_time: {}", stream.start_time());
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!("\tdisposition: {:?}", stream.disposition());
println!("\tdiscard: {:?}", stream.discard());
@ -53,13 +59,15 @@ fn main() {
println!("\tvideo.color_space: {:?}", video.color_space());
println!("\tvideo.color_range: {:?}", video.color_range());
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.references: {}", video.references());
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() {
println!("\tbit_rate: {}", audio.bit_rate());
println!("\tmax_rate: {}", audio.max_bit_rate());
@ -74,10 +82,8 @@ fn main() {
}
}
}
}
Err(error) =>
println!("error: {}", error)
Err(error) => println!("error: {}", error),
}
}

View File

@ -3,17 +3,26 @@ extern crate ffmpeg;
use std::env;
use std::path::Path;
use ffmpeg::{format, codec, frame, media, filter};
use ffmpeg::{codec, filter, format, frame, media};
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 args = format!("time_base={}:sample_rate={}:sample_fmt={}:channel_layout=0x{:x}",
decoder.time_base(), decoder.rate(), decoder.format().name(), decoder.channel_layout().bits());
let args = format!(
"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));
try!(filter.add(&filter::find("abuffersink").unwrap(), "out", ""));
filter.add(&filter::find("abuffer").unwrap(), "in", &args)?;
filter.add(&filter::find("abuffersink").unwrap(), "out", "")?;
{
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());
}
try!(try!(try!(filter.output("in", 0)).input("out", 0)).parse(spec));
try!(filter.validate());
filter.output("in", 0)?.input("out", 0)?.parse(spec)?;
filter.validate()?;
println!("{}", filter.dump());
if let Some(codec) = encoder.codec() {
if !codec.capabilities().contains(ffmpeg::codec::capabilities::VARIABLE_FRAME_SIZE) {
filter.get("out").unwrap().sink().set_frame_size(encoder.frame_size());
if !codec
.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,
}
fn transcoder<P: AsRef<Path>>(ictx: &mut format::context::Input, octx: &mut format::context::Output, path: &P, 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 = try!(input.codec().decoder().audio());
let codec = try!(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);
fn transcoder<P: AsRef<Path>>(
ictx: &mut format::context::Input,
octx: &mut format::context::Output,
path: &P,
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 encoder = try!(output.codec().encoder().audio());
let mut output = octx.add_stream(codec)?;
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()))
.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_channel_layout(channel_layout);
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_max_bit_rate(decoder.max_bit_rate());
encoder.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);
let filter = try!(filter(filter_spec, &decoder, &encoder));
let filter = filter(filter_spec, &decoder, &encoder)?;
Ok(Transcoder {
stream: input.index(),
@ -102,7 +136,7 @@ fn main() {
let input = env::args().nth(1).expect("missing input");
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 mut ictx = format::input(&input).unwrap();
@ -134,9 +168,21 @@ fn main() {
let timestamp = decoded.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) {
encoded.set_stream(0);
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) {
encoded.set_stream(0);
encoded.rescale_ts(in_time_base, out_time_base);

View File

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

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::AVAudioServiceType::*;
use ffi::*;
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum AudioService {
@ -26,7 +26,7 @@ impl From<AVAudioServiceType> for AudioService {
AV_AUDIO_SERVICE_TYPE_EMERGENCY => AudioService::Emergency,
AV_AUDIO_SERVICE_TYPE_VOICE_OVER => AudioService::VoiceOver,
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::Emergency => AV_AUDIO_SERVICE_TYPE_EMERGENCY,
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 libc::c_uint;
bitflags! {
pub struct Capabilities: c_uint {

View File

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

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*;
use libc::c_int;
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Compliance {
@ -19,7 +19,7 @@ impl From<c_int> for Compliance {
FF_COMPLIANCE_UNOFFICIAL => Compliance::Unofficial,
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::Normal => FF_COMPLIANCE_NORMAL,
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::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::encoder::Encoder;
use super::{threading, Compliance, Debug, Flags, Id, Parameters};
use ffi::*;
use libc::c_int;
use media;
use {Codec, Error};
pub struct Context {
ptr: *mut AVCodecContext,
owner: Option<Rc<Drop>>,
}
unsafe impl Send for Context { }
unsafe impl Send for Context {}
impl Context {
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 {
@ -33,7 +36,10 @@ impl Context {
impl Context {
pub fn new() -> Self {
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 {
if (*self.as_ptr()).codec.is_null() {
None
}
else {
} else {
Some(Codec::wrap((*self.as_ptr()).codec as *mut _))
}
}
}
pub fn medium(&self) -> media::Type {
unsafe {
media::Type::from((*self.as_ptr()).codec_type)
}
unsafe { media::Type::from((*self.as_ptr()).codec_type) }
}
pub fn set_flags(&mut self, value: Flags) {
@ -69,9 +72,7 @@ impl Context {
}
pub fn id(&self) -> Id {
unsafe {
Id::from((*self.as_ptr()).codec_id)
}
unsafe { Id::from((*self.as_ptr()).codec_id) }
}
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 {
fn drop(&mut self) {
unsafe {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,22 +1,31 @@
use std::ops::{Deref, DerefMut};
use libc::c_int;
use ffi::*;
use libc::c_int;
use super::Opened;
use ::{packet, Error};
use ::codec::Context;
use codec::Context;
use {packet, Error};
pub struct Subtitle(pub Opened);
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 {
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)),
_ => Ok(got != 0)
_ => Ok(got != 0),
}
}
}
@ -31,14 +40,14 @@ impl Deref 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
}
}
impl AsRef<Context> for Subtitle {
fn as_ref(&self) -> &Context {
&self
self
}
}

View File

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

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::AVDiscard::*;
use ffi::*;
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Discard {
@ -21,7 +21,7 @@ impl From<AVDiscard> for Discard {
AVDISCARD_BIDIR => Discard::Bidirectional,
AVDISCARD_NONINTRA => Discard::NonIntra,
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::NonIntra => AVDISCARD_NONINTRA,
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::ptr;
use libc::c_int;
use ffi::*;
use libc::c_int;
use super::Encoder as Super;
use ::{packet, Error, Dictionary, ChannelLayout, frame};
use ::util::format;
use codec::{traits, Context};
use util::format;
use {frame, packet, ChannelLayout, Dictionary, Error};
pub struct Audio(pub Super);
@ -16,7 +16,7 @@ impl Audio {
unsafe {
match avcodec_open2(self.as_mut_ptr(), ptr::null(), ptr::null_mut()) {
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() {
match avcodec_open2(self.as_mut_ptr(), codec.as_ptr(), ptr::null_mut()) {
0 => Ok(Encoder(self)),
e => Err(Error::from(e))
e => Err(Error::from(e)),
}
}
else {
} else {
Err(Error::EncoderNotFound)
}
}
@ -44,12 +43,16 @@ impl Audio {
match res {
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 {
if let Some(codec) = codec.encoder() {
let mut opts = options.disown();
@ -59,10 +62,9 @@ impl Audio {
match res {
0 => Ok(Encoder(self)),
e => Err(Error::from(e))
e => Err(Error::from(e)),
}
}
else {
} else {
Err(Error::EncoderNotFound)
}
}
@ -75,9 +77,7 @@ impl Audio {
}
pub fn rate(&self) -> u32 {
unsafe {
(*self.as_ptr()).sample_rate as u32
}
unsafe { (*self.as_ptr()).sample_rate as u32 }
}
pub fn set_format(&mut self, value: format::Sample) {
@ -87,9 +87,7 @@ impl Audio {
}
pub fn format(&self) -> format::Sample {
unsafe {
format::Sample::from((*self.as_ptr()).sample_fmt)
}
unsafe { format::Sample::from((*self.as_ptr()).sample_fmt) }
}
pub fn set_channel_layout(&mut self, value: ChannelLayout) {
@ -99,9 +97,7 @@ impl Audio {
}
pub fn channel_layout(&self) -> ChannelLayout {
unsafe {
ChannelLayout::from_bits_truncate((*self.as_ptr()).channel_layout)
}
unsafe { ChannelLayout::from_bits_truncate((*self.as_ptr()).channel_layout) }
}
pub fn set_channels(&mut self, value: i32) {
@ -111,9 +107,7 @@ impl Audio {
}
pub fn channels(&self) -> u16 {
unsafe {
(*self.as_ptr()).channels as u16
}
unsafe { (*self.as_ptr()).channels as u16 }
}
}
@ -126,14 +120,14 @@ impl Deref 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
}
}
impl AsRef<Context> for Audio {
fn as_ref(&self) -> &Context {
&self
self
}
}
@ -146,7 +140,11 @@ impl AsMut<Context> for Audio {
pub struct Encoder(pub Audio);
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 {
if self.format() != frame.format() {
return Err(Error::InvalidData);
@ -154,9 +152,14 @@ impl Encoder {
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)),
_ => Ok(got != 0)
_ => Ok(got != 0),
}
}
}
@ -165,17 +168,20 @@ impl Encoder {
unsafe {
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)),
_ => Ok(got != 0)
_ => Ok(got != 0),
}
}
}
pub fn frame_size(&self) -> u32 {
unsafe {
(*self.as_ptr()).frame_size as u32
}
unsafe { (*self.as_ptr()).frame_size as u32 }
}
}
@ -189,7 +195,7 @@ impl Deref for Encoder {
impl AsRef<Context> for Encoder {
fn as_ref(&self) -> &Context {
&self
self
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::AVFieldOrder::*;
use ffi::*;
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum FieldOrder {
@ -19,7 +19,7 @@ impl From<AVFieldOrder> for FieldOrder {
AV_FIELD_TT => FieldOrder::TT,
AV_FIELD_BB => FieldOrder::BB,
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::BB => AV_FIELD_BB,
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 libc::c_uint;
bitflags! {
pub struct Flags: c_uint {
@ -23,4 +23,3 @@ bitflags! {
const CLOSED_GOP = AV_CODEC_FLAG_CLOSED_GOP;
}
}

View File

@ -1,9 +1,9 @@
use std::ffi::CStr;
use std::str::from_utf8_unchecked;
use ffi::*;
use ffi::AVCodecID::*;
use ::util::media;
use ffi::*;
use util::media;
#[allow(non_camel_case_types)]
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
@ -485,15 +485,11 @@ pub enum Id {
impl Id {
pub fn medium(&self) -> media::Type {
unsafe {
media::Type::from(avcodec_get_type((*self).into()))
}
unsafe { media::Type::from(avcodec_get_type((*self).into())) }
}
pub fn name(&self) -> &'static str {
unsafe {
from_utf8_unchecked(CStr::from_ptr(avcodec_get_name((*self).into())).to_bytes())
}
unsafe { 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 use self::audio::Audio;
pub mod field_order;
pub mod audio_service;
pub mod field_order;
pub mod compliance;
pub use self::compliance::Compliance;
@ -43,8 +43,8 @@ pub use self::profile::Profile;
pub mod threading;
pub mod encoder;
pub mod decoder;
pub mod encoder;
pub mod traits;
use std::ffi::CStr;
@ -53,19 +53,13 @@ use std::str::from_utf8_unchecked;
use ffi::*;
pub fn version() -> u32 {
unsafe {
avcodec_version()
}
unsafe { avcodec_version() }
}
pub fn configuration() -> &'static str {
unsafe {
from_utf8_unchecked(CStr::from_ptr(avcodec_configuration()).to_bytes())
}
unsafe { from_utf8_unchecked(CStr::from_ptr(avcodec_configuration()).to_bytes()) }
}
pub fn license() -> &'static str {
unsafe {
from_utf8_unchecked(CStr::from_ptr(avcodec_license()).to_bytes())
}
unsafe { from_utf8_unchecked(CStr::from_ptr(avcodec_license()).to_bytes()) }
}

View File

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

View File

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

View File

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

View File

@ -2,15 +2,15 @@ use std::marker::PhantomData;
use std::mem;
use std::slice;
use libc::c_int;
use super::{flag, Borrow, Flags, Mut, Ref, SideData};
use ffi::*;
use ::{Error, Rational, format};
use super::{flag, Flags, SideData, Ref, Mut, Borrow};
use libc::c_int;
use {format, Error, Rational};
pub struct Packet(AVPacket);
unsafe impl Send for Packet { }
unsafe impl Sync for Packet { }
unsafe impl Send for Packet {}
unsafe impl Sync for Packet {}
impl Packet {
#[inline(always)]
@ -48,7 +48,7 @@ impl Packet {
use std::io::Write;
let mut packet = Packet::new(data.len());
packet.data_mut().unwrap().write(data).unwrap();
packet.data_mut().unwrap().write_all(data).unwrap();
packet
}
@ -74,11 +74,16 @@ impl Packet {
#[inline]
pub fn rescale_ts<S, D>(&mut self, source: S, destination: D)
where S: Into<Rational>,
D: Into<Rational>
where
S: Into<Rational>,
D: Into<Rational>,
{
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 {
if self.0.data.is_null() {
None
}
else {
} else {
Some(slice::from_raw_parts(self.0.data, self.0.size as usize))
}
}
@ -184,8 +188,7 @@ impl Packet {
unsafe {
if self.0.data.is_null() {
None
}
else {
} else {
Some(slice::from_raw_parts_mut(self.0.data, self.0.size as usize))
}
}
@ -196,7 +199,7 @@ impl Packet {
unsafe {
match av_read_frame(format.as_mut_ptr(), self.as_mut_ptr()) {
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 _) {
1 => Ok(true),
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 _) {
1 => Ok(true),
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> {
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 {
if self.cur >= (*self.ptr).side_data_elems {
None
}
else {
} else {
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::slice;
use ffi::*;
use ffi::AVPacketSideDataType::*;
use super::Packet;
use ffi::AVPacketSideDataType::*;
use ffi::*;
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Type {
@ -104,12 +104,15 @@ impl Into<AVPacketSideDataType> for Type {
pub struct SideData<'a> {
ptr: *mut AVPacketSideData,
_marker: PhantomData<&'a Packet>
_marker: PhantomData<&'a Packet>,
}
impl<'a> SideData<'a> {
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 {
@ -119,14 +122,10 @@ impl<'a> SideData<'a> {
impl<'a> SideData<'a> {
pub fn kind(&self) -> Type {
unsafe {
Type::from((*self.as_ptr()).type_)
}
unsafe { Type::from((*self.as_ptr()).type_) }
}
pub fn data(&self) -> &[u8] {
unsafe {
slice::from_raw_parts((*self.as_ptr()).data, (*self.as_ptr()).size as usize)
}
unsafe { 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 super::{Context, Id};
use ffi::*;
use media;
use super::{Id, Context};
pub struct Parameters {
ptr: *mut AVCodecParameters,
owner: Option<Rc<Drop>>,
}
unsafe impl Send for Parameters { }
unsafe impl Send for Parameters {}
impl Parameters {
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 {
@ -28,20 +31,25 @@ impl Parameters {
impl Parameters {
pub fn new() -> Self {
unsafe {
Parameters { ptr: avcodec_parameters_alloc(), owner: None }
Parameters {
ptr: avcodec_parameters_alloc(),
owner: None,
}
}
}
pub fn medium(&self) -> media::Type {
unsafe {
media::Type::from((*self.as_ptr()).codec_type)
}
unsafe { media::Type::from((*self.as_ptr()).codec_type) }
}
pub fn id(&self) -> Id {
unsafe {
Id::from((*self.as_ptr()).codec_id)
unsafe { 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::slice;
use std::marker::PhantomData;
use libc::{c_int, size_t};
use ffi::*;
use ::format;
use ::Error;
use format;
use libc::{c_int, size_t};
use Error;
pub struct Picture<'a> {
ptr: *mut AVPicture,
@ -19,7 +19,12 @@ pub struct 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 {
ptr: ptr,
@ -28,7 +33,7 @@ impl<'a> Picture<'a> {
height: height,
_own: false,
_marker: PhantomData
_marker: PhantomData,
}
}
@ -46,7 +51,7 @@ impl<'a> Picture<'a> {
unsafe {
match avpicture_get_size(format.into(), width as c_int, height as c_int) {
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,
_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> {
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),
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 {
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),
e => Err(Error::from(e))
e => Err(Error::from(e)),
}
}
}
@ -108,9 +133,15 @@ impl<'a> Picture<'a> {
}
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(()),
e => Err(Error::from(e))
e => Err(Error::from(e)),
}
}
}
@ -119,8 +150,16 @@ impl<'a> Picture<'a> {
let mut result = Vec::new();
unsafe {
for (i, length) in (*self.as_ptr()).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)))
for (i, length) in (*self.as_ptr())
.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();
unsafe {
for (i, length) in (*self.as_ptr()).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)))
for (i, length) in (*self.as_ptr())
.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) {
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 ffi::*;
use libc::c_int;
#[allow(non_camel_case_types)]
#[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_HE => Profile::AAC(AAC::MPEG2HE),
_ => Profile::Unknown
_ => Profile::Unknown,
},
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_N_BIT => Profile::MPEG4(MPEG4::NBit),
FF_PROFILE_MPEG4_SCALABLE_TEXTURE => Profile::MPEG4(MPEG4::ScalableTexture),
FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION => Profile::MPEG4(MPEG4::SimpleFaceAnimation),
FF_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE => Profile::MPEG4(MPEG4::BasicAnimatedTexture),
FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION => {
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_ADVANCED_REAL_TIME => Profile::MPEG4(MPEG4::AdvancedRealTime),
FF_PROFILE_MPEG4_CORE_SCALABLE => Profile::MPEG4(MPEG4::CoreScalable),
FF_PROFILE_MPEG4_ADVANCED_CODING => Profile::MPEG4(MPEG4::AdvancedCoding),
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_ADVANCED_SIMPLE => Profile::MPEG4(MPEG4::AdvancedSimple),
@ -235,9 +241,15 @@ impl From<(Id, c_int)> for Profile {
},
Id::JPEG2000 => match value {
FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0 => Profile::JPEG2000(JPEG2000::CStreamRestriction0),
FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1 => Profile::JPEG2000(JPEG2000::CStreamRestriction1),
FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION => Profile::JPEG2000(JPEG2000::CStreamNoRestriction),
FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0 => {
Profile::JPEG2000(JPEG2000::CStreamRestriction0)
}
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_4K => Profile::JPEG2000(JPEG2000::DCinema4K),
@ -262,7 +274,7 @@ impl From<(Id, c_int)> for Profile {
_ => 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::AdvancedCoding) => FF_PROFILE_MPEG4_ADVANCED_CODING,
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::AdvancedSimple) => FF_PROFILE_MPEG4_ADVANCED_SIMPLE,
Profile::JPEG2000(JPEG2000::CStreamRestriction0) => FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0,
Profile::JPEG2000(JPEG2000::CStreamRestriction1) => FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1,
Profile::JPEG2000(JPEG2000::CStreamNoRestriction) => FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION,
Profile::JPEG2000(JPEG2000::CStreamRestriction0) => {
FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0
}
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::DCinema4K) => FF_PROFILE_JPEG2000_DCINEMA_4K,

View File

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

View File

@ -2,17 +2,17 @@ pub mod flag;
pub use self::flag::Flags;
mod rect;
pub use self::rect::{Rect, Bitmap, Text, Ass};
pub use self::rect::{Ass, Bitmap, Rect, Text};
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::mem;
use libc::{c_uint, uint32_t, size_t};
use ffi::*;
use ffi::AVSubtitleType::*;
use ffi::*;
use libc::{c_uint, size_t, uint32_t};
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Type {
@ -28,7 +28,7 @@ impl From<AVSubtitleType> for Type {
SUBTITLE_NONE => Type::None,
SUBTITLE_BITMAP => Type::Bitmap,
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::Bitmap => SUBTITLE_BITMAP,
Type::Text => SUBTITLE_TEXT,
Type::Ass => SUBTITLE_ASS
Type::Ass => SUBTITLE_ASS,
}
}
}
@ -58,15 +58,13 @@ impl Subtitle {
impl Subtitle {
pub fn new() -> Self {
unsafe {
Subtitle(mem::zeroed())
}
unsafe { Subtitle(mem::zeroed()) }
}
pub fn pts(&self) -> Option<i64> {
match self.0.pts {
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 {
unsafe {
self.0.num_rects += 1;
self.0.rects = av_realloc(self.0.rects as *mut _,
(mem::size_of::<*const AVSubtitleRect>() * self.0.num_rects as usize) as size_t)
as *mut _;
self.0.rects = av_realloc(
self.0.rects 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();
*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> {
ptr: *const AVSubtitle,
cur: c_uint,
@ -124,7 +130,11 @@ pub struct RectIter<'a> {
impl<'a> RectIter<'a> {
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 {
if self.cur >= (*self.ptr).num_rects {
None
}
else {
} else {
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> {
ptr: *mut AVSubtitle,
@ -163,7 +174,11 @@ pub struct RectMutIter<'a> {
impl<'a> RectMutIter<'a> {
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 {
if self.cur >= (*self.ptr).num_rects {
None
}
else {
} else {
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::marker::PhantomData;
use std::str::from_utf8_unchecked;
use super::{Flags, Type};
use ffi::*;
use super::{Type, Flags};
use ::{format, Picture};
use {format, Picture};
pub enum Rect<'a> {
None(*const AVSubtitleRect),
@ -19,16 +19,16 @@ impl<'a> Rect<'a> {
Type::None => Rect::None(ptr),
Type::Bitmap => Rect::Bitmap(Bitmap::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 {
match self {
&Rect::None(ptr) => ptr,
&Rect::Bitmap(ref b) => b.as_ptr(),
&Rect::Text(ref t) => t.as_ptr(),
&Rect::Ass(ref a) => a.as_ptr()
match *self {
Rect::None(ptr) => ptr,
Rect::Bitmap(ref b) => b.as_ptr(),
Rect::Text(ref t) => t.as_ptr(),
Rect::Ass(ref a) => a.as_ptr(),
}
}
}
@ -36,11 +36,11 @@ impl<'a> Rect<'a> {
impl<'a> Rect<'a> {
pub fn flags(&self) -> Flags {
unsafe {
Flags::from_bits_truncate(match self {
&Rect::None(ptr) => (*ptr).flags,
&Rect::Bitmap(ref b) => (*b.as_ptr()).flags,
&Rect::Text(ref t) => (*t.as_ptr()).flags,
&Rect::Ass(ref a) => (*a.as_ptr()).flags
Flags::from_bits_truncate(match *self {
Rect::None(ptr) => (*ptr).flags,
Rect::Bitmap(ref b) => (*b.as_ptr()).flags,
Rect::Text(ref t) => (*t.as_ptr()).flags,
Rect::Ass(ref a) => (*a.as_ptr()).flags,
})
}
}
@ -54,7 +54,10 @@ pub struct Bitmap<'a> {
impl<'a> Bitmap<'a> {
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 {
@ -64,39 +67,34 @@ impl<'a> Bitmap<'a> {
impl<'a> Bitmap<'a> {
pub fn x(&self) -> usize {
unsafe {
(*self.as_ptr()).x as usize
}
unsafe { (*self.as_ptr()).x as usize }
}
pub fn y(&self) -> usize {
unsafe {
(*self.as_ptr()).y as usize
}
unsafe { (*self.as_ptr()).y as usize }
}
pub fn width(&self) -> u32 {
unsafe {
(*self.as_ptr()).w as u32
}
unsafe { (*self.as_ptr()).w as u32 }
}
pub fn height(&self) -> u32 {
unsafe {
(*self.as_ptr()).h as u32
}
unsafe { (*self.as_ptr()).h as u32 }
}
pub fn colors(&self) -> usize {
unsafe {
(*self.as_ptr()).nb_colors as usize
}
unsafe { (*self.as_ptr()).nb_colors as usize }
}
// XXX: must split Picture and PictureMut
pub fn picture(&self, format: format::Pixel) -> Picture<'a> {
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> {
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 {
@ -119,9 +120,7 @@ impl<'a> Text<'a> {
impl<'a> Text<'a> {
pub fn get(&self) -> &str {
unsafe {
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).text).to_bytes())
}
unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).text).to_bytes()) }
}
}
@ -133,7 +132,10 @@ pub struct Ass<'a> {
impl<'a> Ass<'a> {
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 {
@ -143,8 +145,6 @@ impl<'a> Ass<'a> {
impl<'a> Ass<'a> {
pub fn get(&self) -> &str {
unsafe {
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).ass).to_bytes())
}
unsafe { 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::ops::Deref;
use libc::c_int;
use super::{Ass, Bitmap, Flags, Text, Type};
use ffi::*;
use super::{Type, Flags, Bitmap, Text, Ass};
use libc::c_int;
pub enum RectMut<'a> {
None(*mut AVSubtitleRect),
@ -18,25 +18,25 @@ impl<'a> RectMut<'a> {
Type::None => RectMut::None(ptr),
Type::Bitmap => RectMut::Bitmap(BitmapMut::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 {
match self {
&RectMut::None(ptr) => ptr as *const _,
&RectMut::Bitmap(ref b) => b.as_ptr(),
&RectMut::Text(ref t) => t.as_ptr(),
&RectMut::Ass(ref a) => a.as_ptr()
match *self {
RectMut::None(ptr) => ptr as *const _,
RectMut::Bitmap(ref b) => b.as_ptr(),
RectMut::Text(ref t) => t.as_ptr(),
RectMut::Ass(ref a) => a.as_ptr(),
}
}
pub unsafe fn as_mut_ptr(&mut self) -> *mut AVSubtitleRect {
match self {
&mut RectMut::None(ptr) => ptr,
&mut RectMut::Bitmap(ref mut b) => b.as_mut_ptr(),
&mut RectMut::Text(ref mut t) => t.as_mut_ptr(),
&mut RectMut::Ass(ref mut a) => a.as_mut_ptr()
match *self {
RectMut::None(ptr) => ptr,
RectMut::Bitmap(ref mut b) => b.as_mut_ptr(),
RectMut::Text(ref mut t) => t.as_mut_ptr(),
RectMut::Ass(ref mut a) => a.as_mut_ptr(),
}
}
}
@ -44,11 +44,11 @@ impl<'a> RectMut<'a> {
impl<'a> RectMut<'a> {
pub fn flags(&self) -> Flags {
unsafe {
Flags::from_bits_truncate(match self {
&RectMut::None(ptr) => (*ptr).flags,
&RectMut::Bitmap(ref b) => (*b.as_ptr()).flags,
&RectMut::Text(ref t) => (*t.as_ptr()).flags,
&RectMut::Ass(ref a) => (*a.as_ptr()).flags
Flags::from_bits_truncate(match *self {
RectMut::None(ptr) => (*ptr).flags,
RectMut::Bitmap(ref b) => (*b.as_ptr()).flags,
RectMut::Text(ref t) => (*t.as_ptr()).flags,
RectMut::Ass(ref a) => (*a.as_ptr()).flags,
})
}
}
@ -60,7 +60,9 @@ pub struct BitmapMut<'a> {
impl<'a> BitmapMut<'a> {
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 {
@ -114,7 +116,9 @@ pub struct TextMut<'a> {
impl<'a> TextMut<'a> {
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 {
@ -146,7 +150,9 @@ pub struct AssMut<'a> {
impl<'a> AssMut<'a> {
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 {

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*;
use libc::c_int;
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub struct Config {
@ -10,15 +10,24 @@ pub struct Config {
impl Config {
pub fn kind(value: Type) -> Self {
Config { kind: value, .. Default::default() }
Config {
kind: value,
..Default::default()
}
}
pub fn count(value: usize) -> Self {
Config { count: value, .. Default::default() }
Config {
count: value,
..Default::default()
}
}
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 {
Type::None => 0,
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 codec::{Audio, Id, Video};
use Codec;
pub trait Decoder {
fn decoder(self) -> Option<Codec>;
@ -22,8 +22,7 @@ impl Decoder for Codec {
fn decoder(self) -> Option<Codec> {
if self.is_decoder() {
Some(self)
}
else {
} else {
None
}
}
@ -38,9 +37,8 @@ impl Decoder for Option<Codec> {
impl Decoder for Audio {
fn decoder(self) -> Option<Codec> {
if self.is_decoder() {
Some(*&*self)
}
else {
Some(*self)
} else {
None
}
}
@ -49,9 +47,8 @@ impl Decoder for Audio {
impl Decoder for Video {
fn decoder(self) -> Option<Codec> {
if self.is_decoder() {
Some(*&*self)
}
else {
Some(*self)
} else {
None
}
}
@ -77,8 +74,7 @@ impl Encoder for Codec {
fn encoder(self) -> Option<Codec> {
if self.is_encoder() {
Some(self)
}
else {
} else {
None
}
}
@ -93,9 +89,8 @@ impl Encoder for Option<Codec> {
impl Encoder for Audio {
fn encoder(self) -> Option<Codec> {
if self.is_encoder() {
Some(*&*self)
}
else {
Some(*self)
} else {
None
}
}
@ -104,9 +99,8 @@ impl Encoder for Audio {
impl Encoder for Video {
fn encoder(self) -> Option<Codec> {
if self.is_encoder() {
Some(*&*self)
}
else {
Some(*self)
} else {
None
}
}

View File

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

View File

@ -1,17 +1,15 @@
use std::ptr;
use std::marker::PhantomData;
use std::ptr;
use device;
use ffi::*;
use ::Error;
use ::format::context::common::Context;
use ::device;
use format::context::common::Context;
use libc::c_int;
use Error;
impl Context {
pub fn devices(&self) -> Result<DeviceIter, Error> {
unsafe {
DeviceIter::wrap(self.as_ptr())
}
unsafe { DeviceIter::wrap(self.as_ptr()) }
}
}
@ -27,20 +25,20 @@ impl<'a> DeviceIter<'a> {
let mut ptr: *mut AVDeviceInfoList = ptr::null_mut();
match avdevice_list_devices(ctx as *mut _, &mut ptr) {
n if n < 0 =>
Err(Error::from(n)),
n if n < 0 => Err(Error::from(n)),
_ =>
Ok(DeviceIter { ptr: ptr, cur: 0, _marker: PhantomData })
_ => Ok(DeviceIter {
ptr: ptr,
cur: 0,
_marker: PhantomData,
}),
}
}
}
impl<'a> DeviceIter<'a> {
pub fn default(&self) -> usize {
unsafe {
(*self.ptr).default_device as usize
}
unsafe { (*self.ptr).default_device as usize }
}
}
@ -59,10 +57,11 @@ impl<'a> Iterator for DeviceIter<'a> {
unsafe {
if self.cur >= (*self.ptr).nb_devices {
None
}
else {
} else {
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 ffi::*;
use ::format;
use ::Format;
use format;
use Format;
pub struct AudioIter(*mut AVInputFormat);
@ -15,8 +15,7 @@ impl Iterator for AudioIter {
if ptr.is_null() && !self.0.is_null() {
None
}
else {
} else {
self.0 = ptr;
Some(Format::Input(format::Input::wrap(ptr)))
@ -40,8 +39,7 @@ impl Iterator for VideoIter {
if ptr.is_null() && !self.0.is_null() {
None
}
else {
} else {
self.0 = ptr;
Some(Format::Input(format::Input::wrap(ptr)))

View File

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

View File

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

View File

@ -1,9 +1,9 @@
use std::marker::PhantomData;
use super::{Sink, Source};
use ffi::*;
use libc::c_void;
use ::{option, format, ChannelLayout};
use super::{Source, Sink};
use {format, option, ChannelLayout};
pub struct Context<'a> {
ptr: *mut AVFilterContext,
@ -13,7 +13,10 @@ pub struct Context<'a> {
impl<'a> Context<'a> {
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 {
@ -27,15 +30,11 @@ impl<'a> Context<'a> {
impl<'a> Context<'a> {
pub fn source(&'a mut self) -> Source<'a> {
unsafe {
Source::wrap(self)
}
unsafe { Source::wrap(self) }
}
pub fn sink(&'a mut self) -> Sink<'a> {
unsafe {
Sink::wrap(self)
}
unsafe { Sink::wrap(self) }
}
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) {
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) {
@ -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 libc::c_int;
use ::{Frame, Error};
use super::Context;
use {Error, Frame};
pub struct Sink<'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> {
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(()),
e => Err(Error::from(e)),
}

View File

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

View File

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

View File

@ -1,18 +1,18 @@
use std::ffi::{CStr, CString};
use std::ptr;
use std::ffi::{CString, CStr};
use std::str::from_utf8_unchecked;
use super::{Context, Filter};
use ffi::*;
use libc::c_int;
use ::Error;
use super::{Context, Filter};
use Error;
pub struct Graph {
ptr: *mut AVFilterGraph,
}
unsafe impl Send for Graph { }
unsafe impl Sync for Graph { }
unsafe impl Send for Graph {}
unsafe impl Sync for Graph {}
impl Graph {
pub unsafe fn wrap(ptr: *mut AVFilterGraph) -> Self {
@ -45,39 +45,50 @@ impl Graph {
unsafe {
match avfilter_graph_config(self.as_mut_ptr(), ptr::null_mut()) {
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 {
let name = CString::new(name).unwrap();
let args = CString::new(args).unwrap();
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(),
name.as_ptr(),
args.as_ptr(),
ptr::null_mut(),
self.as_mut_ptr())
{
self.as_mut_ptr(),
) {
n if n >= 0 => Ok(Context::wrap(context)),
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 {
let name = CString::new(name).unwrap();
let ptr = avfilter_graph_get_filter(self.as_mut_ptr(), name.as_ptr());
if ptr.is_null() {
None
}
else {
} else {
Some(Context::wrap(ptr))
}
}
@ -86,7 +97,7 @@ impl Graph {
pub fn dump(&self) -> String {
unsafe {
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();
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> {
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();
if input.is_null() {
@ -149,8 +160,7 @@ impl<'a> Parser<'a> {
if self.inputs.is_null() {
self.inputs = input;
}
else {
} else {
(*self.inputs).next = input;
}
}
@ -160,7 +170,7 @@ impl<'a> Parser<'a> {
pub fn output(mut self, name: &str, pad: usize) -> Result<Self, Error> {
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();
if output.is_null() {
@ -176,8 +186,7 @@ impl<'a> Parser<'a> {
if self.outputs.is_null() {
self.outputs = output;
}
else {
} else {
(*self.outputs).next = output;
}
}
@ -189,17 +198,27 @@ impl<'a> Parser<'a> {
unsafe {
let spec = CString::new(spec).unwrap();
let result = avfilter_graph_parse_ptr(self.graph.as_mut_ptr(),
spec.as_ptr(), &mut self.inputs, &mut self.outputs,
ptr::null_mut());
let result = avfilter_graph_parse_ptr(
self.graph.as_mut_ptr(),
spec.as_ptr(),
&mut self.inputs,
&mut self.outputs,
ptr::null_mut(),
);
avfilter_inout_free(&mut self.inputs);
avfilter_inout_free(&mut self.outputs);
match result {
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 mod context;
pub use self::context::{Context, Source, Sink};
pub use self::context::{Context, Sink, Source};
pub mod graph;
pub use self::graph::Graph;
use std::ffi::{CString, CStr};
use std::ffi::{CStr, CString};
use std::str::from_utf8_unchecked;
use ffi::*;
use ::Error;
use Error;
pub fn register_all() {
unsafe {
@ -35,21 +35,15 @@ pub fn register(filter: &Filter) -> Result<(), Error> {
}
pub fn version() -> u32 {
unsafe {
avfilter_version()
}
unsafe { avfilter_version() }
}
pub fn configuration() -> &'static str {
unsafe {
from_utf8_unchecked(CStr::from_ptr(avfilter_configuration()).to_bytes())
}
unsafe { from_utf8_unchecked(CStr::from_ptr(avfilter_configuration()).to_bytes()) }
}
pub fn license() -> &'static str {
unsafe {
from_utf8_unchecked(CStr::from_ptr(avfilter_license()).to_bytes())
}
unsafe { from_utf8_unchecked(CStr::from_ptr(avfilter_license()).to_bytes()) }
}
pub fn find(name: &str) -> Option<Filter> {
@ -59,8 +53,7 @@ pub fn find(name: &str) -> Option<Filter> {
if ptr.is_null() {
None
}
else {
} else {
Some(Filter::wrap(ptr))
}
}

View File

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

View File

@ -1,5 +1,5 @@
use ffi::*;
use ::{Rational, DictionaryRef};
use {DictionaryRef, Rational};
use format::context::common::Context;
@ -12,11 +12,16 @@ pub struct Chapter<'a> {
impl<'a> Chapter<'a> {
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 {
*(*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 {
unsafe {
(*self.as_ptr()).id
}
unsafe { (*self.as_ptr()).id }
}
pub fn time_base(&self) -> Rational {
unsafe {
Rational::from((*self.as_ptr()).time_base)
}
unsafe { Rational::from((*self.as_ptr()).time_base) }
}
pub fn start(&self) -> i64 {
unsafe {
(*self.as_ptr()).start
}
unsafe { (*self.as_ptr()).start }
}
pub fn end(&self) -> i64 {
unsafe {
(*self.as_ptr()).end
}
unsafe { (*self.as_ptr()).end }
}
pub fn metadata(&self) -> DictionaryRef {
unsafe {
DictionaryRef::wrap((*self.as_ptr()).metadata)
}
unsafe { DictionaryRef::wrap((*self.as_ptr()).metadata) }
}
}
impl<'a> PartialEq for Chapter<'a> {
fn eq(&self, other: &Self) -> bool {
unsafe {
self.as_ptr() == other.as_ptr()
}
unsafe { self.as_ptr() == other.as_ptr() }
}
}

View File

@ -1,10 +1,10 @@
use std::ops::Deref;
use std::mem;
use std::ops::Deref;
use ffi::*;
use ::{Rational, Dictionary, DictionaryMut};
use super::Chapter;
use ffi::*;
use format::context::common::Context;
use {Dictionary, DictionaryMut, Rational};
// 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)
@ -21,12 +21,14 @@ impl<'a> ChapterMut<'a> {
context: mem::transmute_copy(&context),
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 {
*(*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 {
unsafe {
DictionaryMut::wrap((*self.as_mut_ptr()).metadata)
}
unsafe { 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::ptr;
use std::rc::Rc;
use super::destructor::{self, Destructor};
use ffi::*;
use libc::{c_int, c_uint};
use ::{media, Stream, StreamMut, Chapter, ChapterMut, DictionaryRef};
use super::destructor::{self, Destructor};
use {media, Chapter, ChapterMut, DictionaryRef, Stream, StreamMut};
pub struct Context {
ptr: *mut AVFormatContext,
dtor: Rc<Destructor>,
}
unsafe impl Send for Context { }
unsafe impl Send for Context {}
impl Context {
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 {
@ -28,28 +31,32 @@ impl Context {
}
pub unsafe fn destructor(&self) -> Rc<Destructor> {
self.dtor.clone()
Rc::clone(&self.dtor)
}
}
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 {
if index >= (*self.as_ptr()).nb_streams as usize {
None
}
else {
} else {
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 {
if index >= (*self.as_ptr()).nb_streams as usize {
None
}
else {
} else {
Some(StreamMut::wrap(self, index))
}
}
@ -64,34 +71,34 @@ impl Context {
}
pub fn duration(&self) -> i64 {
unsafe {
(*self.as_ptr()).duration
}
unsafe { (*self.as_ptr()).duration }
}
pub fn nb_chapters(&self) -> u32 {
unsafe {
(*self.as_ptr()).nb_chapters
}
unsafe { (*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 {
if index >= (*self.as_ptr()).nb_chapters as usize {
None
}
else {
} else {
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 {
if index >= (*self.as_ptr()).nb_chapters as usize {
None
}
else {
} else {
Some(ChapterMut::wrap(self, index))
}
}
@ -106,9 +113,7 @@ impl Context {
}
pub fn metadata(&self) -> DictionaryRef {
unsafe {
DictionaryRef::wrap((*self.as_ptr()).metadata)
}
unsafe { 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
}
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
}
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 {
let mut decoder = ptr::null_mut();
let index = av_find_best_stream(self.context.ptr,
kind.into(), self.wanted as c_int, self.related as c_int,
&mut decoder, 0);
let index = av_find_best_stream(
self.context.ptr,
kind.into(),
self.wanted as c_int,
self.related as c_int,
&mut decoder,
0,
);
if index >= 0 && !decoder.is_null() {
Some(Stream::wrap(self.context, index as usize))
}
else {
} else {
None
}
}
@ -163,27 +181,35 @@ pub struct StreamIter<'a> {
impl<'a> StreamIter<'a> {
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> {
pub fn wanted<'b, 'c>(&self, stream: &'b Stream) -> Best<'c> where 'a: 'b, 'a: 'c {
unsafe {
Best::new(self.context).wanted(stream)
}
pub fn wanted<'b, 'c>(&self, stream: &'b Stream) -> Best<'c>
where
'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 {
unsafe {
Best::new(self.context).related(stream)
}
pub fn related<'b, 'c>(&self, stream: &'b Stream) -> Best<'c>
where
'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 {
unsafe {
Best::new(self.context).best(kind)
}
pub fn best<'b>(&self, kind: media::Type) -> Option<Stream<'b>>
where
'a: 'b,
{
unsafe { Best::new(self.context).best(kind) }
}
}
@ -206,12 +232,15 @@ impl<'a> Iterator for StreamIter<'a> {
unsafe {
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> {
context: &'a mut Context,
@ -220,7 +249,10 @@ pub struct StreamIterMut<'a> {
impl<'a> StreamIterMut<'a> {
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> {
unsafe {
if self.current >= (*self.context.as_ptr()).nb_streams {
return None
return None;
}
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 {
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> {
context: &'a Context,
@ -257,7 +295,10 @@ pub struct ChapterIter<'a> {
impl<'a> ChapterIter<'a> {
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 {
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> {
context: &'a mut Context,
@ -294,7 +338,10 @@ pub struct ChapterIterMut<'a> {
impl<'a> ChapterIterMut<'a> {
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> {
unsafe {
if self.current >= (*self.context.as_ptr()).nb_chapters {
return None
return None;
}
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 {
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) {
unsafe {
match self.mode {
Mode::Input =>
avformat_close_input(&mut self.ptr),
Mode::Input => avformat_close_input(&mut self.ptr),
Mode::Output => {
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::ptr;
use std::mem;
use std::ffi::CString;
use ffi::*;
use ::{Error, Codec, Stream, Packet, format};
use super::common::Context;
use super::destructor;
use ffi::*;
use util::range::Range;
use {format, Codec, Error, Packet, Stream};
pub struct Input {
ptr: *mut AVFormatContext,
ctx: Context,
}
unsafe impl Send for Input { }
unsafe impl Send for Input {}
impl Input {
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 {
@ -32,9 +35,7 @@ impl Input {
impl Input {
pub fn format(&self) -> format::Input {
unsafe {
format::Input::wrap((*self.as_ptr()).iformat)
}
unsafe { format::Input::wrap((*self.as_ptr()).iformat) }
}
pub fn video_codec(&self) -> Option<Codec> {
@ -43,8 +44,7 @@ impl Input {
if ptr.is_null() {
None
}
else {
} else {
Some(Codec::wrap(ptr))
}
}
@ -56,8 +56,7 @@ impl Input {
if ptr.is_null() {
None
}
else {
} else {
Some(Codec::wrap(ptr))
}
}
@ -69,8 +68,7 @@ impl Input {
if ptr.is_null() {
None
}
else {
} else {
Some(Codec::wrap(ptr))
}
}
@ -82,17 +80,14 @@ impl Input {
if ptr.is_null() {
None
}
else {
} else {
Some(Codec::wrap(ptr))
}
}
}
pub fn probe_score(&self) -> i32 {
unsafe {
av_format_get_probe_score(self.as_ptr())
}
unsafe { av_format_get_probe_score(self.as_ptr()) }
}
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> {
unsafe {
match avformat_seek_file(self.as_mut_ptr(), -1,
range.start().map(|v| *v).unwrap_or(i64::min_value()), ts,
range.end().map(|v| *v).unwrap_or(i64::max_value()), 0)
{
match avformat_seek_file(
self.as_mut_ptr(),
-1,
range.start().cloned().unwrap_or(i64::min_value()),
ts,
range.end().cloned().unwrap_or(i64::max_value()),
0,
) {
s if s >= 0 => Ok(()),
e => Err(Error::from(e)),
}
@ -165,14 +164,13 @@ impl<'a> Iterator for PacketIter<'a> {
Ok(..) => unsafe {
return Some((
Stream::wrap(mem::transmute_copy(&self.context), packet.stream()),
packet));
packet,
));
},
Err(Error::Eof) =>
return None,
Err(Error::Eof) => 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());
unsafe {
av_dump_format(ctx.as_ptr() as *mut _, index,
url.map(|u| u.as_ptr()).unwrap_or(ptr::null()), 0);
av_dump_format(
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),
}
unsafe impl Send for Context { }
unsafe impl Send for Context {}
impl Context {
pub fn is_input(&self) -> bool {
if let &Context::Input(..) = self {
if let Context::Input(..) = *self {
true
}
else {
} else {
false
}
}
@ -36,10 +35,9 @@ impl Context {
}
pub fn is_output(&self) -> bool {
if let &Context::Output(..) = self {
if let Context::Output(..) = *self {
true
}
else {
} else {
false
}
}

View File

@ -1,26 +1,29 @@
use std::ffi::CString;
use std::mem::size_of;
use std::ops::{Deref, DerefMut};
use std::ptr;
use std::mem::size_of;
use std::ffi::CString;
use libc;
use ffi::*;
use ::{Error, StreamMut, ChapterMut, Rational, Dictionary, format};
use super::common::Context;
use super::destructor;
use codec::traits;
use ffi::*;
use {format, ChapterMut, Dictionary, Error, Rational, StreamMut};
pub struct Output {
ptr: *mut AVFormatContext,
ctx: Context,
}
unsafe impl Send for Output { }
unsafe impl Send for Output {}
impl Output {
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 {
@ -34,9 +37,7 @@ impl Output {
impl Output {
pub fn format(&self) -> format::Output {
unsafe {
format::Output::wrap((*self.as_ptr()).oformat)
}
unsafe { format::Output::wrap((*self.as_ptr()).oformat) }
}
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> {
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());
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,
time_base: R,
start: i64,
end: i64,
title: S) -> Result<ChapterMut, Error>
{
title: S,
) -> Result<ChapterMut, Error> {
// avpriv_new_chapter is private (libavformat/internal.h)
if start > end {
@ -108,22 +110,23 @@ impl Output {
let index = match existing {
Some(index) => index,
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;
// chapters array will be freed by `avformat_free_context`
av_dynarray_add(
&mut (*self.as_mut_ptr()).chapters as *mut _ as *mut libc::c_void,
&mut nb_chapters,
ptr
ptr,
);
if nb_chapters > 0 {
(*self.as_mut_ptr()).nb_chapters = nb_chapters as u32;
let index = (*self.ctx.as_ptr()).nb_chapters - 1;
index as usize
}
else {
} else {
// failed to add the chapter
av_freep(ptr);
return Err(Error::Bug);
@ -131,8 +134,7 @@ impl Output {
},
};
let mut chapter = self.chapter_mut(index)
.ok_or(Error::Bug)?;
let mut chapter = self.chapter_mut(index).ok_or(Error::Bug)?;
chapter.set_id(id);
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());
unsafe {
av_dump_format(ctx.as_ptr() as *mut _, index,
url.map(|u| u.as_ptr()).unwrap_or(ptr::null()), 1);
av_dump_format(
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 libc::c_int;
bitflags! {
pub struct Flags: c_int {
@ -23,4 +23,3 @@ bitflags! {
const SEEK_TO_PTS = AVFMT_SEEK_TO_PTS;
}
}

View File

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

View File

@ -1,7 +1,7 @@
use std::ptr;
use ffi::*;
use super::{Format, Input, Output};
use ffi::*;
pub struct Iter {
input: *mut AVInputFormat,
@ -17,7 +17,17 @@ enum Step {
impl Iter {
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.next()
}
else {
} else {
self.input = ptr;
Some(Format::Input(Input::wrap(ptr)))
@ -49,16 +58,14 @@ impl Iterator for Iter {
self.step = Step::Done;
self.next()
}
else {
} else {
self.output = ptr;
Some(Format::Output(Output::wrap(ptr)))
}
}
Step::Done =>
None
Step::Done => None,
}
}
}

View File

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

View File

@ -1,12 +1,12 @@
use std::path::Path;
use std::ptr;
use std::ffi::{CStr, CString};
use std::ptr;
use std::str::from_utf8_unchecked;
use super::Flags;
use ffi::*;
use {codec, media};
use super::Flags;
pub struct Output {
ptr: *mut AVOutputFormat,
@ -28,15 +28,11 @@ impl Output {
impl Output {
pub fn name(&self) -> &str {
unsafe {
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).name).to_bytes())
}
unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).name).to_bytes()) }
}
pub fn description(&self) -> &str {
unsafe {
from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).long_name).to_bytes())
}
unsafe { from_utf8_unchecked(CStr::from_ptr((*self.as_ptr()).long_name).to_bytes()) }
}
pub fn extensions(&self) -> Vec<&str> {
@ -45,9 +41,10 @@ impl Output {
if ptr.is_null() {
Vec::new()
}
else {
from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes()).split(',').collect()
} else {
from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes())
.split(',')
.collect()
}
}
}
@ -58,9 +55,10 @@ impl Output {
if ptr.is_null() {
Vec::new()
}
else {
from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes()).split(',').collect()
} else {
from_utf8_unchecked(CStr::from_ptr(ptr).to_bytes())
.split(',')
.collect()
}
}
}
@ -70,13 +68,17 @@ impl Output {
let path = CString::new(path.as_ref().as_os_str().to_str().unwrap()).unwrap();
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 {
unsafe {
Flags::from_bits_truncate((*self.as_ptr()).flags)
}
unsafe { 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};
use ::util::interrupt;
pub use util::format::{pixel, Pixel};
pub use util::format::{sample, Sample};
use util::interrupt;
pub mod stream;
@ -10,18 +10,18 @@ pub mod context;
pub use self::context::Context;
pub mod format;
pub use self::format::{Input, Output, list};
pub use self::format::{flag, Flags};
pub use self::format::{list, Input, Output};
pub mod network;
use std::ptr;
use std::ffi::{CStr, CString};
use std::path::Path;
use std::ffi::{CString, CStr};
use std::ptr;
use std::str::from_utf8_unchecked;
use ffi::*;
use ::{Error, Format, Dictionary};
use {Dictionary, Error, Format};
pub fn register_all() {
unsafe {
@ -30,33 +30,27 @@ pub fn register_all() {
}
pub fn register(format: &Format) {
match format {
&Format::Input(ref format) => unsafe {
match *format {
Format::Input(ref format) => unsafe {
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 _);
}
},
}
}
pub fn version() -> u32 {
unsafe {
avformat_version()
}
unsafe { avformat_version() }
}
pub fn configuration() -> &'static str {
unsafe {
from_utf8_unchecked(CStr::from_ptr(avformat_configuration()).to_bytes())
}
unsafe { from_utf8_unchecked(CStr::from_ptr(avformat_configuration()).to_bytes()) }
}
pub fn license() -> &'static str {
unsafe {
from_utf8_unchecked(CStr::from_ptr(avformat_license()).to_bytes())
}
unsafe { from_utf8_unchecked(CStr::from_ptr(avformat_license()).to_bytes()) }
}
// 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 path = from_path(path);
match format {
&Format::Input(ref format) => {
match avformat_open_input(&mut ps, path.as_ptr(), format.as_ptr() as *mut _, ptr::null_mut()) {
0 => {
match avformat_find_stream_info(ps, ptr::null_mut()) {
match *format {
Format::Input(ref format) => match avformat_open_input(
&mut ps,
path.as_ptr(),
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))),
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) {
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)),
},
}
}
}
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 {
let mut ps = ptr::null_mut();
let path = from_path(path);
let mut opts = options.disown();
match format {
&Format::Input(ref format) => {
let res = avformat_open_input(&mut ps, path.as_ptr(), format.as_ptr() as *mut _, &mut opts);
match *format {
Format::Input(ref format) => {
let res = avformat_open_input(
&mut ps,
path.as_ptr(),
format.as_ptr() as *mut _,
&mut opts,
);
Dictionary::own(opts);
match res {
0 => {
match avformat_find_stream_info(ps, ptr::null_mut()) {
0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
r if r >= 0 => Ok(Context::Input(context::Input::wrap(ps))),
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))
}
}
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);
match avformat_open_input(&mut ps, path.as_ptr(), ptr::null_mut(), ptr::null_mut()) {
0 => {
match avformat_find_stream_info(ps, ptr::null_mut()) {
0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
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 {
let mut ps = ptr::null_mut();
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);
match res {
0 => {
match avformat_find_stream_info(ps, ptr::null_mut()) {
0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
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>
where F: FnMut() -> bool {
pub fn input_with_interrupt<P: AsRef<Path>, F>(
path: &P,
closure: F,
) -> Result<context::Input, Error>
where
F: FnMut() -> bool,
{
unsafe {
let mut ps = avformat_alloc_context();
let path = from_path(path);
(*ps).interrupt_callback = interrupt::new(Box::new(closure)).interrupt;
match avformat_open_input(&mut ps, path.as_ptr(), ptr::null_mut(), ptr::null_mut()) {
0 => {
match avformat_find_stream_info(ps, ptr::null_mut()) {
0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
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);
match avformat_alloc_output_context2(&mut ps, ptr::null_mut(), ptr::null(), path.as_ptr()) {
0 => {
match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
0 => match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
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 {
let mut ps = ptr::null_mut();
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()) {
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);
match res {
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 format = CString::new(format).unwrap();
match avformat_alloc_output_context2(&mut ps, ptr::null_mut(), format.as_ptr(), path.as_ptr()) {
0 => {
match avio_open(&mut (*ps).pb, path.as_ptr(), AVIO_FLAG_WRITE) {
match avformat_alloc_output_context2(
&mut ps,
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)),
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 {
let mut ps = ptr::null_mut();
let path = from_path(path);
let format = CString::new(format).unwrap();
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 => {
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);
match res {
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 libc::c_int;
bitflags! {
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 codec::{self, packet};
use ffi::*;
use format::context::common::Context;
use libc::c_int;
use {DictionaryRef, Discard, Rational};
pub struct Stream<'a> {
context: &'a Context,
@ -12,7 +12,10 @@ pub struct Stream<'a> {
impl<'a> Stream<'a> {
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 {
@ -22,15 +25,11 @@ impl<'a> Stream<'a> {
impl<'a> Stream<'a> {
pub fn id(&self) -> i32 {
unsafe {
i32::from((*self.as_ptr()).id)
}
unsafe { (*self.as_ptr()).id }
}
pub fn codec(&self) -> codec::Context {
unsafe {
codec::Context::wrap((*self.as_ptr()).codec, Some(self.context.destructor()))
}
unsafe { codec::Context::wrap((*self.as_ptr()).codec, Some(self.context.destructor())) }
}
pub fn parameters(&self) -> codec::Parameters {
@ -40,45 +39,31 @@ impl<'a> Stream<'a> {
}
pub fn index(&self) -> usize {
unsafe {
(*self.as_ptr()).index as usize
}
unsafe { (*self.as_ptr()).index as usize }
}
pub fn time_base(&self) -> Rational {
unsafe {
Rational::from((*self.as_ptr()).time_base)
}
unsafe { Rational::from((*self.as_ptr()).time_base) }
}
pub fn start_time(&self) -> i64 {
unsafe {
(*self.as_ptr()).start_time
}
unsafe { (*self.as_ptr()).start_time }
}
pub fn duration(&self) -> i64 {
unsafe {
(*self.as_ptr()).duration
}
unsafe { (*self.as_ptr()).duration }
}
pub fn frames(&self) -> i64 {
unsafe {
(*self.as_ptr()).nb_frames
}
unsafe { (*self.as_ptr()).nb_frames }
}
pub fn disposition(&self) -> Disposition {
unsafe {
Disposition::from_bits_truncate((*self.as_ptr()).disposition)
}
unsafe { Disposition::from_bits_truncate((*self.as_ptr()).disposition) }
}
pub fn discard(&self) -> Discard {
unsafe {
Discard::from((*self.as_ptr()).discard)
}
unsafe { Discard::from((*self.as_ptr()).discard) }
}
pub fn side_data(&self) -> SideDataIter {
@ -86,33 +71,25 @@ impl<'a> Stream<'a> {
}
pub fn rate(&self) -> Rational {
unsafe {
Rational::from(av_stream_get_r_frame_rate(self.as_ptr()))
}
unsafe { Rational::from(av_stream_get_r_frame_rate(self.as_ptr())) }
}
pub fn avg_frame_rate(&self) -> Rational {
unsafe {
Rational::from((*self.as_ptr()).avg_frame_rate)
}
unsafe { Rational::from((*self.as_ptr()).avg_frame_rate) }
}
pub fn metadata(&self) -> DictionaryRef {
unsafe {
DictionaryRef::wrap((*self.as_ptr()).metadata)
}
unsafe { DictionaryRef::wrap((*self.as_ptr()).metadata) }
}
}
impl<'a> PartialEq for Stream<'a> {
fn eq(&self, other: &Self) -> bool {
unsafe {
self.as_ptr() == other.as_ptr()
}
unsafe { self.as_ptr() == other.as_ptr() }
}
}
impl<'a> Eq for Stream<'a> { }
impl<'a> Eq for Stream<'a> {}
pub struct SideDataIter<'a> {
stream: &'a Stream<'a>,
@ -121,7 +98,10 @@ pub struct SideDataIter<'a> {
impl<'a> SideDataIter<'a> {
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;
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 {
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::ops::Deref;
use ffi::*;
use ::{Rational, codec};
use super::Stream;
use ffi::*;
use format::context::common::Context;
use {codec, Rational};
pub struct StreamMut<'a> {
context: &'a mut Context,
@ -19,12 +19,14 @@ impl<'a> StreamMut<'a> {
context: mem::transmute_copy(&context),
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 {
*(*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)]
#![cfg_attr(feature = "cargo-clippy", allow(inline_always))]
extern crate libc;
#[macro_use]
extern crate bitflags;
pub extern crate ffmpeg_sys as sys;
#[macro_use] extern crate bitflags;
#[cfg(feature = "image")] extern crate image;
#[cfg(feature = "image")]
extern crate image;
extern crate libc;
pub use sys as ffi;
#[macro_use]
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::Mut as DictionaryMut;
pub use util::dictionary::Owned as Dictionary;
pub use util::dictionary::Ref as DictionaryRef;
pub use util::dictionary::Mut as DictionaryMut;
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::error::Error;
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::mathematics::{self, Rounding, Rescale, rescale};
pub use util::picture;
pub use util::rational::{self, Rational};
pub use util::time;
#[cfg(feature = "format")]
pub mod format;
#[cfg(feature = "format")]
pub use format::chapter::{Chapter, ChapterMut};
#[cfg(feature = "format")]
pub use format::format::Format;
#[cfg(feature = "format")]
pub use format::stream::{Stream, StreamMut};
#[cfg(feature = "format")]
pub use format::chapter::{Chapter, ChapterMut};
#[cfg(feature = "codec")]
pub mod codec;
#[cfg(feature = "codec")]
pub use codec::packet::{self, Packet};
#[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;
pub use codec::audio_service::AudioService;
#[cfg(feature = "codec")]
pub use codec::codec::Codec;
#[cfg(feature = "codec")]
pub use codec::{decoder, encoder};
pub use codec::discard::Discard;
#[cfg(feature = "codec")]
pub use codec::field_order::FieldOrder;
#[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")]
pub use codec::threading;
#[cfg(feature = "codec")]
pub use codec::{decoder, encoder};
#[cfg(feature = "device")]
pub mod device;
@ -75,7 +78,7 @@ fn init_format() {
}
#[cfg(not(feature = "format"))]
fn init_format() { }
fn init_format() {}
#[cfg(feature = "device")]
fn init_device() {
@ -83,7 +86,7 @@ fn init_device() {
}
#[cfg(not(feature = "device"))]
fn init_device() { }
fn init_device() {}
#[cfg(feature = "filter")]
fn init_filter() {
@ -91,7 +94,7 @@ fn init_filter() {
}
#[cfg(not(feature = "filter"))]
fn init_filter() { }
fn init_filter() {}
pub fn init() -> Result<(), Error> {
init_error();

View File

@ -3,20 +3,33 @@ pub mod scaling;
#[cfg(feature = "software-scaling")]
#[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),
(out_width, out_height): (u32, u32))
-> Result<scaling::Context, ::Error> {
scaling::Context::get(format, in_width, in_height, format, out_width, out_height, flags)
(out_width, out_height): (u32, u32),
) -> Result<scaling::Context, ::Error> {
scaling::Context::get(
format, in_width, in_height, format, out_width, out_height, flags,
)
}
#[cfg(feature = "software-scaling")]
#[inline]
pub fn converter((width, height): (u32, u32),
pub fn converter(
(width, height): (u32, u32),
input: ::format::Pixel,
output: ::format::Pixel)
-> Result<scaling::Context, ::Error> {
scaling::Context::get(input, width, height, output, width, height, scaling::flag::FAST_BILINEAR)
output: ::format::Pixel,
) -> Result<scaling::Context, ::Error> {
scaling::Context::get(
input,
width,
height,
output,
width,
height,
scaling::flag::FAST_BILINEAR,
)
}
#[cfg(feature = "software-resampling")]
@ -24,8 +37,11 @@ pub mod resampling;
#[cfg(feature = "software-resampling")]
#[inline]
pub fn resampler((in_format, in_layout, in_rate): (::format::Sample, ::ChannelLayout, u32),
(out_format, out_layout, out_rate): (::format::Sample, ::ChannelLayout, u32))
-> Result<resampling::Context, ::Error> {
resampling::Context::get(in_format, in_layout, in_rate, out_format, out_layout, out_rate)
pub fn resampler(
(in_format, in_layout, in_rate): (::format::Sample, ::ChannelLayout, u32),
(out_format, out_layout, out_rate): (::format::Sample, ::ChannelLayout, u32),
) -> 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 libc::{c_int, int64_t};
use ffi::*;
use ::util::format;
use ::{Error, ChannelLayout, frame};
use super::Delay;
use ffi::*;
use libc::{c_int, int64_t};
use util::format;
use {frame, ChannelLayout, Error};
#[derive(Eq, PartialEq, Copy, Clone)]
pub struct Definition {
@ -34,21 +34,32 @@ impl Context {
impl Context {
/// Create a resampler with the given definitions.
pub fn get(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> {
pub fn get(
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 {
let ptr = swr_alloc_set_opts(ptr::null_mut(),
dst_channel_layout.bits() as int64_t, 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());
let ptr = swr_alloc_set_opts(
ptr::null_mut(),
dst_channel_layout.bits() as int64_t,
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) {
e if e < 0 =>
Err(Error::from(e)),
e if e < 0 => Err(Error::from(e)),
_ =>
Ok(Context {
_ => Ok(Context {
ptr: ptr,
input: Definition {
@ -61,11 +72,10 @@ impl Context {
format: dst_format,
channel_layout: dst_channel_layout,
rate: dst_rate,
},
}),
}
})
}
}
else {
} else {
Err(Error::InvalidData)
}
}
@ -86,7 +96,7 @@ impl Context {
unsafe {
match swr_get_delay(self.as_ptr() as *mut _, 1) {
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.
///
/// 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);
unsafe {
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()) {
0 =>
Ok(self.delay()),
0 => Ok(self.delay()),
e =>
Err(Error::from(e))
e => Err(Error::from(e)),
}
}
}
@ -120,11 +136,9 @@ impl Context {
unsafe {
match swr_convert_frame(self.as_mut_ptr(), output.as_mut_ptr(), ptr::null()) {
0 =>
Ok(self.delay()),
0 => Ok(self.delay()),
e =>
Err(Error::from(e))
e => Err(Error::from(e)),
}
}
}

View File

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

View File

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

View File

@ -1,19 +1,41 @@
use util::format;
use ::{decoder, Error, ChannelLayout, frame};
use super::Context;
use util::format;
use {decoder, frame, ChannelLayout, Error};
impl frame::Audio {
#[inline]
pub fn resampler(&self, format: format::Sample, channel_layout: ChannelLayout, rate: u32) -> Result<Context, Error> {
Context::get(self.format(), self.channel_layout(), self.rate(),
format, channel_layout, rate)
pub fn resampler(
&self,
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 {
#[inline]
pub fn resampler(&self, format: format::Sample, channel_layout: ChannelLayout, rate: u32) -> Result<Context, Error> {
Context::get(self.format(), self.channel_layout(), self.rate(),
format, channel_layout, rate)
pub fn resampler(
&self,
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::*;
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Filter {

View File

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

View File

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

View File

@ -1,5 +1,5 @@
use libc::c_int;
use ffi::*;
use libc::c_int;
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum ColorSpace {
@ -21,7 +21,7 @@ impl From<c_int> for ColorSpace {
SWS_CS_DEFAULT => ColorSpace::Default,
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::ITU624 => SWS_CS_ITU624,
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 libc::{c_int};
use ffi::*;
use ::{Error, frame};
use ::util::format;
use super::Flags;
use ffi::*;
use libc::c_int;
use util::format;
use {frame, Error};
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub struct Definition {
@ -33,17 +33,30 @@ impl Context {
}
impl Context {
pub fn get(src_format: format::Pixel, src_w: u32, src_h: u32,
dst_format: format::Pixel, dst_w: u32, dst_h: u32,
flags: Flags) -> Result<Self, Error> {
pub fn get(
src_format: format::Pixel,
src_w: u32,
src_h: u32,
dst_format: format::Pixel,
dst_w: u32,
dst_h: u32,
flags: Flags,
) -> Result<Self, Error> {
unsafe {
let ptr = sws_getContext(
src_w as c_int, src_h as c_int, src_format.into(),
dst_w as c_int, dst_h as c_int, dst_format.into(),
src_w as c_int,
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_mut());
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
);
if ptr != ptr::null_mut() {
if ptr.is_null() {
Ok(Context {
ptr: ptr,
@ -59,17 +72,22 @@ impl Context {
height: dst_h,
},
})
}
else {
} else {
Err(Error::InvalidData)
}
}
}
pub fn cached(&mut self,
src_format: format::Pixel, src_w: u32, src_h: u32,
dst_format: format::Pixel, dst_w: u32, dst_h: u32,
flags: Flags) {
pub fn cached(
&mut self,
src_format: format::Pixel,
src_w: u32,
src_h: u32,
dst_format: format::Pixel,
dst_w: u32,
dst_h: u32,
flags: Flags,
) {
self.input = Definition {
format: src_format,
width: src_w,
@ -83,10 +101,19 @@ impl Context {
};
unsafe {
self.ptr = sws_getCachedContext(self.as_mut_ptr(),
src_w as c_int, 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());
self.ptr = sws_getCachedContext(
self.as_mut_ptr(),
src_w as c_int,
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> {
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);
}
@ -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);
}
unsafe {
sws_scale(self.as_mut_ptr(),
(*input.as_ptr()).data.as_ptr() as *const *const _, (*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 _);
sws_scale(
self.as_mut_ptr(),
(*input.as_ptr()).data.as_ptr() as *const *const _,
(*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(())

View File

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

View File

@ -1,5 +1,5 @@
use ffi::*;
use super::Vector;
use ffi::*;
pub struct Filter {
ptr: *mut SwsFilter,
@ -16,14 +16,25 @@ impl Filter {
}
impl Filter {
pub fn get(luma_g_blur: f32, chroma_g_blur: f32,
luma_sharpen: f32, chroma_sharpen: f32,
chroma_h_shift: f32, chroma_v_shift: f32) -> Self {
pub fn get(
luma_g_blur: f32,
chroma_g_blur: f32,
luma_sharpen: f32,
chroma_sharpen: f32,
chroma_h_shift: f32,
chroma_v_shift: f32,
) -> Self {
unsafe {
Filter {
ptr: sws_getDefaultFilter(luma_g_blur, chroma_g_blur,
luma_sharpen, chroma_sharpen,
chroma_h_shift, chroma_v_shift, 0)
ptr: sws_getDefaultFilter(
luma_g_blur,
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 {
unsafe {
Vector::wrap((*self.as_ptr()).lumH)
}
unsafe { Vector::wrap((*self.as_ptr()).lumH) }
}
pub fn luma_horizontal_mut(&mut self) -> Vector {
unsafe {
Vector::wrap((*self.as_mut_ptr()).lumH)
}
unsafe { Vector::wrap((*self.as_mut_ptr()).lumH) }
}
pub fn luma_vertical(&self) -> Vector {
unsafe {
Vector::wrap((*self.as_ptr()).lumV)
}
unsafe { Vector::wrap((*self.as_ptr()).lumV) }
}
pub fn luma_vertical_mut(&mut self) -> Vector {
unsafe {
Vector::wrap((*self.as_mut_ptr()).lumV)
}
unsafe { Vector::wrap((*self.as_mut_ptr()).lumV) }
}
pub fn chroma_horizontal(&self) -> Vector {
unsafe {
Vector::wrap((*self.as_ptr()).lumV)
}
unsafe { Vector::wrap((*self.as_ptr()).lumV) }
}
pub fn chroma_horizontal_mut(&mut self) -> Vector {
unsafe {
Vector::wrap((*self.as_mut_ptr()).lumV)
}
unsafe { Vector::wrap((*self.as_mut_ptr()).lumV) }
}
pub fn chroma_vertical(&self) -> Vector {
unsafe {
Vector::wrap((*self.as_ptr()).lumV)
}
unsafe { Vector::wrap((*self.as_ptr()).lumV) }
}
pub fn chroma_vertical_mut(&mut self) -> Vector {
unsafe {
Vector::wrap((*self.as_mut_ptr()).lumV)
unsafe { 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 libc::c_int;
bitflags! {
pub struct Flags: c_int {

View File

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

View File

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

View File

@ -1,8 +1,8 @@
use std::marker::PhantomData;
use std::slice;
use libc::{c_int, c_double};
use ffi::*;
use libc::{c_double, c_int};
pub struct Vector<'a> {
ptr: *mut SwsVector,
@ -13,7 +13,11 @@ pub struct Vector<'a> {
impl<'a> Vector<'a> {
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 {
@ -28,25 +32,41 @@ impl<'a> Vector<'a> {
impl<'a> Vector<'a> {
pub fn new(length: usize) -> Self {
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 {
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 {
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 {
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] {
unsafe {
slice::from_raw_parts((*self.as_ptr()).coeff,
(*self.as_ptr()).length as usize)
}
unsafe { slice::from_raw_parts((*self.as_ptr()).coeff, (*self.as_ptr()).length as usize) }
}
pub fn coefficients_mut(&self) -> &[f64] {
unsafe {
slice::from_raw_parts_mut((*self.as_ptr()).coeff,
(*self.as_ptr()).length as usize)
slice::from_raw_parts_mut((*self.as_ptr()).coeff, (*self.as_ptr()).length as usize)
}
}
}
@ -104,7 +120,11 @@ impl<'a> Vector<'a> {
impl<'a> Clone for Vector<'a> {
fn clone(&self) -> Self {
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 libc::c_ulonglong;
bitflags! {
pub struct ChannelLayout: c_ulonglong {
@ -64,9 +64,7 @@ bitflags! {
impl ChannelLayout {
#[inline]
pub fn channels(&self) -> i32 {
unsafe {
av_get_channel_layout_nb_channels(self.bits())
}
unsafe { av_get_channel_layout_nb_channels(self.bits()) }
}
pub fn default(number: i32) -> ChannelLayout {

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::AVChromaLocation::*;
use ffi::*;
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Location {
@ -22,7 +22,7 @@ impl From<AVChromaLocation> for Location {
AVCHROMA_LOC_TOP => Location::Top,
AVCHROMA_LOC_BOTTOMLEFT => Location::BottomLeft,
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::Top => AVCHROMA_LOC_TOP,
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::*;
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Primaries {

View File

@ -1,5 +1,5 @@
use ffi::*;
use ffi::AVColorRange::*;
use ffi::*;
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
pub enum Range {
@ -14,7 +14,7 @@ impl From<AVColorRange> for Range {
AVCOL_RANGE_UNSPECIFIED => Range::Unspecified,
AVCOL_RANGE_MPEG => Range::MPEG,
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 {
Range::Unspecified => AVCOL_RANGE_UNSPECIFIED,
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