Skip to content

Commit

Permalink
Remove unnecessary RsmpegError discriminants (#170)
Browse files Browse the repository at this point in the history
  • Loading branch information
ldm0 authored Apr 4, 2024
1 parent cfeb1e4 commit 9d1926a
Show file tree
Hide file tree
Showing 11 changed files with 32 additions and 123 deletions.
8 changes: 2 additions & 6 deletions src/avcodec/bitstream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,12 +169,8 @@ impl AVBSFContextUninit {
/// but after you set input parameters via
/// [`AVBSFContextUninit::set_par_in`].
pub fn init(mut self) -> Result<AVBSFContext> {
unsafe {
match ffi::av_bsf_init(self.as_mut_ptr()).upgrade() {
Ok(_) => Ok(AVBSFContext(self)),
Err(x) => Err(RsmpegError::BitstreamInitializationError(x)),
}
}
unsafe { ffi::av_bsf_init(self.as_mut_ptr()) }.upgrade()?;
Ok(AVBSFContext(self))
}

/// Get `filter` field of current [`AVBSFContext`].
Expand Down
17 changes: 7 additions & 10 deletions src/avcodec/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,8 @@ impl AVCodecContext {
/// private options. Function returns a [`AVDictionary`] filled with
/// options that were not found if given dictionary. It can usually be
/// ignored.
///
/// Note: Always call this function before using decoding routines, such as [`Self::receive_frame()`].
pub fn open(&mut self, dict: Option<AVDictionary>) -> Result<Option<AVDictionary>> {
if let Some(mut dict) = dict {
let dict_ptr = {
Expand All @@ -182,8 +184,7 @@ impl AVCodecContext {
unsafe {
ffi::avcodec_open2(self.as_mut_ptr(), ptr::null_mut(), &mut dict_ptr as *mut _)
}
.upgrade()
.map_err(RsmpegError::CodecOpenError)?;
.upgrade()?;
dict_ptr
};
// If no error, dict's inner pointer is dangling, here we manually drop it by using into_raw().
Expand All @@ -193,8 +194,7 @@ impl AVCodecContext {
.map(|dict_ptr| unsafe { AVDictionary::from_raw(dict_ptr) }))
} else {
unsafe { ffi::avcodec_open2(self.as_mut_ptr(), ptr::null_mut(), ptr::null_mut()) }
.upgrade()
.map_err(RsmpegError::CodecOpenError)?;
.upgrade()?;
Ok(None)
}
}
Expand Down Expand Up @@ -289,8 +289,7 @@ impl AVCodecContext {
packet,
)
}
.upgrade()
.map_err(RsmpegError::AVError)?;
.upgrade()?;

if got_sub == 0 {
return Ok(None);
Expand All @@ -308,8 +307,7 @@ impl AVCodecContext {
subtitle.as_ptr(),
)
}
.upgrade()
.map_err(RsmpegError::AVError)?;
.upgrade()?;
Ok(())
}

Expand All @@ -324,8 +322,7 @@ impl AVCodecContext {
/// not touched.
pub fn apply_codecpar(&mut self, codecpar: &AVCodecParameters) -> Result<()> {
unsafe { ffi::avcodec_parameters_to_context(self.as_mut_ptr(), codecpar.as_ptr()) }
.upgrade()
.map_err(RsmpegError::CodecSetParameterError)?;
.upgrade()?;
Ok(())
}

Expand Down
20 changes: 7 additions & 13 deletions src/avfilter/avfilter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,9 @@ wrap_ref!(AVFilter: ffi::AVFilter);

impl AVFilter {
/// Get a filter definition matching the given name.
pub fn get_by_name(filter_name: &CStr) -> Result<AVFilterRef<'static>> {
let filter = unsafe { ffi::avfilter_get_by_name(filter_name.as_ptr()) }
.upgrade()
.ok_or(RsmpegError::FilterNotFound)?;
Ok(unsafe { AVFilterRef::from_raw(filter) })
pub fn get_by_name(filter_name: &CStr) -> Option<AVFilterRef<'static>> {
let filter = unsafe { ffi::avfilter_get_by_name(filter_name.as_ptr()) }.upgrade()?;
Some(unsafe { AVFilterRef::from_raw(filter) })
}
}

Expand All @@ -43,8 +41,7 @@ impl AVFilterContext {
ffi::AV_OPT_SEARCH_CHILDREN as i32,
)
}
.upgrade()
.map_err(RsmpegError::SetPropertyError)?;
.upgrade()?;
Ok(())
}

Expand All @@ -58,8 +55,7 @@ impl AVFilterContext {
ffi::AV_OPT_SEARCH_CHILDREN as i32,
)
}
.upgrade()
.map_err(RsmpegError::SetPropertyError)?;
.upgrade()?;
Ok(())
}

Expand All @@ -78,8 +74,7 @@ impl AVFilterContext {
let flags = flags.unwrap_or(0);

unsafe { ffi::av_buffersrc_add_frame_flags(self.as_mut_ptr(), frame_ptr, flags) }
.upgrade()
.map_err(RsmpegError::BufferSrcAddFrameError)?;
.upgrade()?;
Ok(())
}

Expand Down Expand Up @@ -281,8 +276,7 @@ impl<'graph> AVFilterGraph {
self.as_ptr() as *mut _,
)
}
.upgrade()
.map_err(RsmpegError::CreateFilterError)?;
.upgrade()?;

let filter_context = NonNull::new(filter_context).unwrap();

Expand Down
12 changes: 4 additions & 8 deletions src/avformat/avformat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,8 +280,7 @@ impl AVFormatContextOutput {
filename.as_ptr(),
)
}
.upgrade()
.map_err(RsmpegError::OpenOutputError)?;
.upgrade()?;

let mut output_format_context =
unsafe { Self::from_raw(NonNull::new(output_format_context).unwrap()) };
Expand Down Expand Up @@ -334,17 +333,15 @@ impl AVFormatContextOutput {
.upgrade()
.map(|x| unsafe { AVDictionary::from_raw(x) });

result.upgrade().map_err(RsmpegError::WriteHeaderError)?;
result.upgrade()?;

Ok(())
}

/// Write the stream trailer to an output media file and free the file
/// private data.
pub fn write_trailer(&mut self) -> Result<()> {
unsafe { ffi::av_write_trailer(self.as_mut_ptr()) }
.upgrade()
.map_err(RsmpegError::WriteTrailerError)?;
unsafe { ffi::av_write_trailer(self.as_mut_ptr()) }.upgrade()?;
Ok(())
}

Expand Down Expand Up @@ -379,8 +376,7 @@ impl AVFormatContextOutput {
/// [`Self::write_frame()`] instead of this function.
pub fn interleaved_write_frame(&mut self, packet: &mut AVPacket) -> Result<()> {
unsafe { ffi::av_interleaved_write_frame(self.as_mut_ptr(), packet.as_mut_ptr()) }
.upgrade()
.map_err(RsmpegError::InterleavedWriteFrameError)?;
.upgrade()?;
Ok(())
}
}
Expand Down
4 changes: 1 addition & 3 deletions src/avformat/avio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ impl AVIOContextURL {
/// the [`AVIOContextURL`] can be used only for writing.
pub fn open(url: &CStr, flags: u32) -> Result<Self> {
let mut io_context = ptr::null_mut();
unsafe { ffi::avio_open(&mut io_context, url.as_ptr(), flags as _) }
.upgrade()
.map_err(RsmpegError::AVIOOpenError)?;
unsafe { ffi::avio_open(&mut io_context, url.as_ptr(), flags as _) }.upgrade()?;
Ok(Self(unsafe {
AVIOContext::from_raw(NonNull::new(io_context).unwrap())
}))
Expand Down
12 changes: 3 additions & 9 deletions src/avutil/dict.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
use crate::{
error::{Result, RsmpegError},
ffi,
shared::*,
};
use crate::{error::Result, ffi, shared::*};

use std::{
ffi::{CStr, CString},
Expand Down Expand Up @@ -98,8 +94,7 @@ impl AVDictionary {
flags as i32,
)
}
.upgrade()
.map_err(RsmpegError::DictionaryParseError)?;
.upgrade()?;
unsafe { self.set_ptr(NonNull::new(dict).unwrap()) };
Ok(self)
}
Expand All @@ -122,8 +117,7 @@ impl AVDictionary {
pub fn get_string(&self, key_val_sep: u8, pairs_sep: u8) -> Result<CString> {
let mut s = ptr::null_mut();
unsafe { ffi::av_dict_get_string(self.as_ptr(), &mut s, key_val_sep as _, pairs_sep as _) }
.upgrade()
.map_err(RsmpegError::DictionaryGetStringError)?;
.upgrade()?;
let result = unsafe { CStr::from_ptr(s).to_owned() };
unsafe {
ffi::av_freep(&mut s as *mut _ as *mut libc::c_void);
Expand Down
9 changes: 2 additions & 7 deletions src/avutil/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@ use std::{
slice,
};

use crate::{
error::{Result, RsmpegError},
ffi,
shared::RetUpgrade,
};
use crate::{error::Result, ffi, shared::RetUpgrade};

/// A read-only file buffer, the file is mmaped when available.
pub struct AVMmap {
Expand All @@ -33,8 +29,7 @@ impl AVMmap {
let mut bufptr = null_mut();
let mut size = 0;
unsafe { ffi::av_file_map(filename.as_ptr(), &mut bufptr, &mut size, 0, null_mut()) }
.upgrade()
.map(RsmpegError::AVError)?;
.upgrade()?;
Ok(Self {
bufptr: NonNull::new(bufptr).unwrap(),
size,
Expand Down
3 changes: 1 addition & 2 deletions src/avutil/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,7 @@ impl AVFrame {
1,
)
}
.upgrade()
.map_err(RsmpegError::AVImageFillArrayError)?;
.upgrade()?;
Ok(())
}

Expand Down
65 changes: 3 additions & 62 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,14 @@ use crate::{avutil::err2str, ffi, shared::AVERROR_EAGAIN};
pub enum RsmpegError {
#[error("AVERROR({0}): `{}`", err2str(*.0).unwrap_or_else(|| "Unknown error code.".to_string()))]
AVError(c_int),
#[error("{0}")]
CustomError(String),

// --------- Unstablized error type below ------

// FFmpeg errors
#[error("Cannot open input file. ({0})")]
OpenInputError(c_int),
#[error("Cannot open output file. ({0})")]
OpenOutputError(c_int),
#[error("Cannot find stream information. ({0})")]
FindStreamInfoError(c_int),
#[error("Cannot write header to output file. ({0})")]
WriteHeaderError(c_int),
#[error("Cannot write trailer to output file. ({0})")]
WriteTrailerError(c_int),

#[error("Failed to open codec. ({0})")]
CodecOpenError(c_int),
#[error("Failed to copy decoder parameters to input decoder context. ({0})")]
CodecSetParameterError(c_int),
#[error("Filter not found.")]
FilterNotFound,
#[error("Create filter instance in a filter graph failed. ({0})")]
CreateFilterError(c_int),
#[error("Set property to a filter context failed. ({0})")]
SetPropertyError(c_int),

// Decoder errors
#[error("Send packet to a codec context failed. ({0})")]
Expand Down Expand Up @@ -77,45 +58,24 @@ pub enum RsmpegError {
BitstreamSendPacketError(c_int),
#[error("Receive packet from a bitstream filter context failed. ({0})")]
BitstreamReceivePacketError(c_int),
#[error("Failed to initialize bitstream filter context. ({0})")]
BitstreamInitializationError(c_int),

#[error("Interleaved write frame to an output format context failed. ({0})")]
InterleavedWriteFrameError(c_int),

#[error("Error while feeding the filtergraph failed. ({0})")]
BufferSrcAddFrameError(c_int),
#[error("Pulling filtered frame from filters failed ({0})")]
BufferSinkGetFrameError(c_int),
#[error("No frames are available at this point")]
BufferSinkDrainError,
#[error("There will be no more output frames on this sink")]
BufferSinkEofError,

#[error("AVDictionary doesn't understand provided string. ({0})")]
DictionaryParseError(c_int),
#[error("AVDictionary failed to get string. ({0})")]
DictionaryGetStringError(c_int),

#[error("AVIO Open failure. ({0})")]
AVIOOpenError(c_int),

#[error("SwsContext scale failed. ({0})")]
SwsScaleError(c_int),

#[error("AVFrame buffer double allocating.")]
AVFrameDoubleAllocatingError,
#[error("AVFrame buffer allocating with incorrect parameters. ({0})")]
AVFrameInvalidAllocatingError(c_int),

#[error("Failed to fill data to image buffer. ({0})")]
AVImageFillArrayError(c_int),

#[error("{0}")]
TryFromIntError(TryFromIntError),

// Non exhaustive
#[error("Unknown error, contact ldm0 when you see this.")]
#[error("Unknown error.")]
Unknown,
}

Expand All @@ -125,30 +85,15 @@ impl RsmpegError {
match self {
Self::AVError(err)
| Self::OpenInputError(err)
| Self::OpenOutputError(err)
| Self::FindStreamInfoError(err)
| Self::WriteHeaderError(err)
| Self::WriteTrailerError(err)
| Self::CodecOpenError(err)
| Self::CodecSetParameterError(err)
| Self::CreateFilterError(err)
| Self::SetPropertyError(err)
| Self::SendPacketError(err)
| Self::ReceiveFrameError(err)
| Self::SendFrameError(err)
| Self::ReceivePacketError(err)
| Self::BitstreamSendPacketError(err)
| Self::BitstreamReceivePacketError(err)
| Self::BitstreamInitializationError(err)
| Self::InterleavedWriteFrameError(err)
| Self::BufferSrcAddFrameError(err)
| Self::BufferSinkGetFrameError(err)
| Self::DictionaryParseError(err)
| Self::DictionaryGetStringError(err)
| Self::AVIOOpenError(err)
| Self::SwsScaleError(err)
| Self::AVFrameInvalidAllocatingError(err)
| Self::AVImageFillArrayError(err) => Some(*err),
| Self::AVFrameInvalidAllocatingError(err) => Some(*err),

Self::DecoderFullError
| Self::BufferSinkDrainError
Expand All @@ -163,11 +108,7 @@ impl RsmpegError {
| Self::EncoderFlushedError
| Self::BitstreamFlushedError => Some(ffi::AVERROR_EOF),

Self::AVFrameDoubleAllocatingError
| Self::FilterNotFound
| Self::CustomError(_)
| Self::TryFromIntError(_)
| Self::Unknown => None,
Self::AVFrameDoubleAllocatingError | Self::TryFromIntError(_) | Self::Unknown => None,
}
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/swscale/swscale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,7 @@ impl SwsContext {
dst_stride,
)
}
.upgrade()
.map_err(RsmpegError::SwsScaleError)?;
.upgrade()?;
Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion tests/misc/avio_writing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ fn encode_write_frame(

match output_format_context.interleaved_write_frame(&mut packet) {
Ok(()) => Ok(()),
Err(RsmpegError::InterleavedWriteFrameError(-22)) => Ok(()),
Err(RsmpegError::AVError(-22)) => Ok(()),
Err(e) => Err(e),
}
.context("Interleaved write frame failed.")?;
Expand Down

0 comments on commit 9d1926a

Please sign in to comment.