From 9d1926aa0195c3e9c0fac78b6812d3015b7108a2 Mon Sep 17 00:00:00 2001 From: Donough Liu Date: Fri, 5 Apr 2024 06:09:06 +0800 Subject: [PATCH] Remove unnecessary RsmpegError discriminants (#170) --- src/avcodec/bitstream.rs | 8 ++--- src/avcodec/codec.rs | 17 ++++------ src/avfilter/avfilter.rs | 20 ++++-------- src/avformat/avformat.rs | 12 +++---- src/avformat/avio.rs | 4 +-- src/avutil/dict.rs | 12 ++----- src/avutil/file.rs | 9 ++---- src/avutil/frame.rs | 3 +- src/error.rs | 65 ++------------------------------------ src/swscale/swscale.rs | 3 +- tests/misc/avio_writing.rs | 2 +- 11 files changed, 32 insertions(+), 123 deletions(-) diff --git a/src/avcodec/bitstream.rs b/src/avcodec/bitstream.rs index 6519566..bfdb97c 100644 --- a/src/avcodec/bitstream.rs +++ b/src/avcodec/bitstream.rs @@ -169,12 +169,8 @@ impl AVBSFContextUninit { /// but after you set input parameters via /// [`AVBSFContextUninit::set_par_in`]. pub fn init(mut self) -> Result { - 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`]. diff --git a/src/avcodec/codec.rs b/src/avcodec/codec.rs index 24d1214..1614e89 100644 --- a/src/avcodec/codec.rs +++ b/src/avcodec/codec.rs @@ -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) -> Result> { if let Some(mut dict) = dict { let dict_ptr = { @@ -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(). @@ -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) } } @@ -289,8 +289,7 @@ impl AVCodecContext { packet, ) } - .upgrade() - .map_err(RsmpegError::AVError)?; + .upgrade()?; if got_sub == 0 { return Ok(None); @@ -308,8 +307,7 @@ impl AVCodecContext { subtitle.as_ptr(), ) } - .upgrade() - .map_err(RsmpegError::AVError)?; + .upgrade()?; Ok(()) } @@ -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(()) } diff --git a/src/avfilter/avfilter.rs b/src/avfilter/avfilter.rs index 25badde..1dea390 100644 --- a/src/avfilter/avfilter.rs +++ b/src/avfilter/avfilter.rs @@ -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> { - 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> { + let filter = unsafe { ffi::avfilter_get_by_name(filter_name.as_ptr()) }.upgrade()?; + Some(unsafe { AVFilterRef::from_raw(filter) }) } } @@ -43,8 +41,7 @@ impl AVFilterContext { ffi::AV_OPT_SEARCH_CHILDREN as i32, ) } - .upgrade() - .map_err(RsmpegError::SetPropertyError)?; + .upgrade()?; Ok(()) } @@ -58,8 +55,7 @@ impl AVFilterContext { ffi::AV_OPT_SEARCH_CHILDREN as i32, ) } - .upgrade() - .map_err(RsmpegError::SetPropertyError)?; + .upgrade()?; Ok(()) } @@ -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(()) } @@ -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(); diff --git a/src/avformat/avformat.rs b/src/avformat/avformat.rs index c9b0579..ff3db6e 100644 --- a/src/avformat/avformat.rs +++ b/src/avformat/avformat.rs @@ -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()) }; @@ -334,7 +333,7 @@ impl AVFormatContextOutput { .upgrade() .map(|x| unsafe { AVDictionary::from_raw(x) }); - result.upgrade().map_err(RsmpegError::WriteHeaderError)?; + result.upgrade()?; Ok(()) } @@ -342,9 +341,7 @@ impl AVFormatContextOutput { /// 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(()) } @@ -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(()) } } diff --git a/src/avformat/avio.rs b/src/avformat/avio.rs index 40bb731..2683f07 100644 --- a/src/avformat/avio.rs +++ b/src/avformat/avio.rs @@ -31,9 +31,7 @@ impl AVIOContextURL { /// the [`AVIOContextURL`] can be used only for writing. pub fn open(url: &CStr, flags: u32) -> Result { 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()) })) diff --git a/src/avutil/dict.rs b/src/avutil/dict.rs index d4bc200..ce4a6f9 100644 --- a/src/avutil/dict.rs +++ b/src/avutil/dict.rs @@ -1,8 +1,4 @@ -use crate::{ - error::{Result, RsmpegError}, - ffi, - shared::*, -}; +use crate::{error::Result, ffi, shared::*}; use std::{ ffi::{CStr, CString}, @@ -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) } @@ -122,8 +117,7 @@ impl AVDictionary { pub fn get_string(&self, key_val_sep: u8, pairs_sep: u8) -> Result { 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); diff --git a/src/avutil/file.rs b/src/avutil/file.rs index 67e6d5f..c0dc8df 100644 --- a/src/avutil/file.rs +++ b/src/avutil/file.rs @@ -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 { @@ -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, diff --git a/src/avutil/frame.rs b/src/avutil/frame.rs index b3c1477..e279036 100644 --- a/src/avutil/frame.rs +++ b/src/avutil/frame.rs @@ -128,8 +128,7 @@ impl AVFrame { 1, ) } - .upgrade() - .map_err(RsmpegError::AVImageFillArrayError)?; + .upgrade()?; Ok(()) } diff --git a/src/error.rs b/src/error.rs index d74c8ff..7cffa5a 100644 --- a/src/error.rs +++ b/src/error.rs @@ -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})")] @@ -77,14 +58,7 @@ 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")] @@ -92,30 +66,16 @@ pub enum RsmpegError { #[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, } @@ -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 @@ -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, } } } diff --git a/src/swscale/swscale.rs b/src/swscale/swscale.rs index 3f1e2f0..a2e98aa 100644 --- a/src/swscale/swscale.rs +++ b/src/swscale/swscale.rs @@ -131,8 +131,7 @@ impl SwsContext { dst_stride, ) } - .upgrade() - .map_err(RsmpegError::SwsScaleError)?; + .upgrade()?; Ok(()) } diff --git a/tests/misc/avio_writing.rs b/tests/misc/avio_writing.rs index 36c0e11..aa814f9 100644 --- a/tests/misc/avio_writing.rs +++ b/tests/misc/avio_writing.rs @@ -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.")?;