Skip to main content

fdk_aac/
dec.rs

1use std::fmt::{self, Display, Debug};
2use std::os::raw::{c_uint, c_int};
3
4use fdk_aac_sys as sys;
5
6pub use sys::CStreamInfo as StreamInfo;
7
8#[derive(Clone, Copy, PartialEq, Eq)]
9pub struct DecoderError(sys::AAC_DECODER_ERROR);
10
11impl DecoderError {
12    pub const OUT_OF_MEMORY: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_OUT_OF_MEMORY);
13    pub const UNKNOWN: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNKNOWN);
14    pub const TRANSPORT_SYNC_ERROR: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_TRANSPORT_SYNC_ERROR);
15    pub const NOT_ENOUGH_BITS: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_NOT_ENOUGH_BITS);
16    pub const INVALID_HANDLE: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_INVALID_HANDLE);
17    pub const UNSUPPORTED_AOT: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_AOT);
18    pub const UNSUPPORTED_FORMAT: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_FORMAT);
19    pub const UNSUPPORTED_ER_FORMAT: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_ER_FORMAT);
20    pub const UNSUPPORTED_EPCONFIG: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_EPCONFIG);
21    pub const UNSUPPORTED_MULTILAYER: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_MULTILAYER);
22    pub const UNSUPPORTED_CHANNELCONFIG: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_CHANNELCONFIG);
23    pub const UNSUPPORTED_SAMPLINGRATE: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_SAMPLINGRATE);
24    pub const INVALID_SBR_CONFIG: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_INVALID_SBR_CONFIG);
25    pub const SET_PARAM_FAIL: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_SET_PARAM_FAIL);
26    pub const NEED_TO_RESTART: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_NEED_TO_RESTART);
27    pub const OUTPUT_BUFFER_TOO_SMALL: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_OUTPUT_BUFFER_TOO_SMALL);
28    pub const TRANSPORT_ERROR: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_TRANSPORT_ERROR);
29    pub const PARSE_ERROR: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_PARSE_ERROR);
30    pub const UNSUPPORTED_EXTENSION_PAYLOAD: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_EXTENSION_PAYLOAD);
31    pub const DECODE_FRAME_ERROR: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_DECODE_FRAME_ERROR);
32    pub const CRC_ERROR: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_CRC_ERROR);
33    pub const INVALID_CODE_BOOK: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_INVALID_CODE_BOOK);
34    pub const UNSUPPORTED_PREDICTION: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_PREDICTION);
35    pub const UNSUPPORTED_CCE: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_CCE);
36    pub const UNSUPPORTED_LFE: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_LFE);
37    pub const UNSUPPORTED_GAIN_CONTROL_DATA: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_GAIN_CONTROL_DATA);
38    pub const UNSUPPORTED_SBA: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_SBA);
39    pub const TNS_READ_ERROR: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_TNS_READ_ERROR);
40    pub const RVLC_ERROR: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_RVLC_ERROR);
41    pub const ANC_DATA_ERROR: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_ANC_DATA_ERROR);
42    pub const TOO_SMALL_ANC_BUFFER: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_TOO_SMALL_ANC_BUFFER);
43    pub const TOO_MANY_ANC_ELEMENTS: DecoderError = DecoderError(sys::AAC_DECODER_ERROR_AAC_DEC_TOO_MANY_ANC_ELEMENTS);
44
45    pub fn message(&self) -> &'static str {
46        match self.0 {
47            sys::AAC_DECODER_ERROR_AAC_DEC_OK => "No error occurred. Output buffer is valid and error free.",
48            sys::AAC_DECODER_ERROR_AAC_DEC_OUT_OF_MEMORY => "Heap returned NULL pointer. Output buffer is invalid.",
49            sys::AAC_DECODER_ERROR_AAC_DEC_UNKNOWN => "Error condition is of unknown reason, or from a another module. Output buffer is invalid.",
50            sys::AAC_DECODER_ERROR_aac_dec_sync_error_start => "Synchronization errors. Output buffer is invalid.",
51            sys::AAC_DECODER_ERROR_AAC_DEC_TRANSPORT_SYNC_ERROR => "The transport decoder had synchronization problems. Do not exit decoding. Just feed new bitstream data.",
52            sys::AAC_DECODER_ERROR_AAC_DEC_NOT_ENOUGH_BITS => "The input buffer ran out of bits.",
53            sys::AAC_DECODER_ERROR_aac_dec_init_error_start => "Initialization errors. Output buffer is invalid.",
54            sys::AAC_DECODER_ERROR_AAC_DEC_INVALID_HANDLE => "The handle passed to the function call was invalid (NULL).",
55            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_AOT => "The AOT found in the configuration is not supported.",
56            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_FORMAT => "The bitstream format is not supported. ",
57            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_ER_FORMAT => "The error resilience tool format is not supported.",
58            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_EPCONFIG => "The error protection format is not supported.",
59            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_MULTILAYER => "More than one layer for AAC scalable is not supported.",
60            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_CHANNELCONFIG => "The channel configuration (either number or arrangement) is not supported.",
61            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_SAMPLINGRATE => "The sample rate specified in the configuration is not supported.",
62            sys::AAC_DECODER_ERROR_AAC_DEC_INVALID_SBR_CONFIG => "The SBR configuration is not supported.",
63            sys::AAC_DECODER_ERROR_AAC_DEC_SET_PARAM_FAIL => "The parameter could not be set. Either the value was out of range or the parameter does  not exist.",
64            sys::AAC_DECODER_ERROR_AAC_DEC_NEED_TO_RESTART => "The decoder needs to be restarted, since the required configuration change cannot be performed.",
65            sys::AAC_DECODER_ERROR_AAC_DEC_OUTPUT_BUFFER_TOO_SMALL => "The provided output buffer is too small.",
66            sys::AAC_DECODER_ERROR_aac_dec_decode_error_start => "Decode errors. Output buffer is valid but concealed.",
67            sys::AAC_DECODER_ERROR_AAC_DEC_TRANSPORT_ERROR => "The transport decoder encountered an unexpected error.",
68            sys::AAC_DECODER_ERROR_AAC_DEC_PARSE_ERROR => "Error while parsing the bitstream. Most probably it is corrupted, or the system crashed.",
69            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_EXTENSION_PAYLOAD => "Error while parsing the extension payload of the bitstream. The extension payload type found is not supported.",
70            sys::AAC_DECODER_ERROR_AAC_DEC_DECODE_FRAME_ERROR => "The parsed bitstream value is out of range. Most probably the bitstream is corrupt, or the system crashed.",
71            sys::AAC_DECODER_ERROR_AAC_DEC_CRC_ERROR => "The embedded CRC did not match.",
72            sys::AAC_DECODER_ERROR_AAC_DEC_INVALID_CODE_BOOK => "An invalid codebook was signaled. Most probably the bitstream is corrupt, or the system  crashed.",
73            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_PREDICTION => "Predictor found, but not supported in the AAC Low Complexity profile. Most probably the bitstream is corrupt, or has a wrong format.",
74            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_CCE => "A CCE element was found which is not supported. Most probably the bitstream is corrupt, or has a wrong format.",
75            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_LFE => "A LFE element was found which is not supported. Most probably the bitstream is corrupt, or has a wrong format.",
76            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_GAIN_CONTROL_DATA => "Gain control data found but not supported. Most probably the bitstream is corrupt, or has a wrong format.",
77            sys::AAC_DECODER_ERROR_AAC_DEC_UNSUPPORTED_SBA => "SBA found, but currently not supported in the BSAC profile.",
78            sys::AAC_DECODER_ERROR_AAC_DEC_TNS_READ_ERROR => "Error while reading TNS data. Most probably the bitstream is corrupt or the system crashed.",
79            sys::AAC_DECODER_ERROR_AAC_DEC_RVLC_ERROR => "Error while decoding error resilient data.",
80            sys::AAC_DECODER_ERROR_aac_dec_anc_data_error_start => "Ancillary data errors. Output buffer is valid.",
81            sys::AAC_DECODER_ERROR_AAC_DEC_ANC_DATA_ERROR => "Non severe error concerning the ancillary data handling.",
82            sys::AAC_DECODER_ERROR_AAC_DEC_TOO_SMALL_ANC_BUFFER => "The registered ancillary data buffer is too small to receive the parsed data.",
83            sys::AAC_DECODER_ERROR_AAC_DEC_TOO_MANY_ANC_ELEMENTS => "More than the allowed number of ancillary data elements should be written to buffer.",
84            _ => "Unknown error",
85        }
86    }
87}
88
89impl Debug for DecoderError {
90    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
91        write!(f, "DecoderError {{ code: {:?}, message: {:?} }}", self.0 as c_int, self.message())
92    }
93}
94
95impl Display for DecoderError {
96    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
97        write!(f, "{}", self.message())
98    }
99}
100
101fn check(e: sys::AACENC_ERROR) -> Result<(), DecoderError> {
102    if e == sys::AAC_DECODER_ERROR_AAC_DEC_OK {
103        Ok(())
104    } else {
105        Err(DecoderError(e))
106    }
107}
108
109#[derive(Debug)]
110pub struct Decoder {
111    handle: sys::HANDLE_AACDECODER,
112}
113
114unsafe impl Send for Decoder {}
115unsafe impl Sync for Decoder {}
116
117impl Decoder {
118    pub fn new(transport: Transport) -> Self {
119        let handle = match transport {
120            Transport::Raw => {
121                unsafe { sys::aacDecoder_Open(sys::TRANSPORT_TYPE_TT_MP4_RAW, 1) }
122            }
123            Transport::Adts => {
124                unsafe { sys::aacDecoder_Open(sys::TRANSPORT_TYPE_TT_MP4_ADTS, 1) }
125            }
126        };
127
128        Decoder { handle }
129    }
130
131    pub fn config_raw(&mut self, audio_specic_config: &[u8]) -> Result<(), DecoderError> {
132        unsafe {
133            let mut asc_ptr = audio_specic_config.as_ptr() as *mut u8;
134            let asc_len = audio_specic_config.len() as c_uint;
135            check(sys::aacDecoder_ConfigRaw(self.handle, &mut asc_ptr as *mut _, &asc_len as *const _))
136        }
137    }
138
139    pub fn set_min_output_channels(&mut self, channels: usize) -> Result<(), DecoderError> {
140        unsafe {
141            check(sys::aacDecoder_SetParam(self.handle,
142                sys::AACDEC_PARAM_AAC_PCM_MIN_OUTPUT_CHANNELS,
143                channels as i32))
144        }
145    }
146
147    pub fn set_max_output_channels(&mut self, channels: usize) -> Result<(), DecoderError> {
148        unsafe {
149            check(sys::aacDecoder_SetParam(self.handle,
150                sys::AACDEC_PARAM_AAC_PCM_MAX_OUTPUT_CHANNELS,
151                channels as i32))
152        }
153    }
154
155    pub fn fill(&mut self, data: &[u8]) -> Result<usize, DecoderError> {
156        unsafe {
157            let mut data_ptr = data.as_ptr() as *const u8 as *mut u8;
158            let data_len = data.len() as c_uint;
159            let mut bytes_valid: c_uint = data_len;
160
161            check(sys::aacDecoder_Fill(self.handle,
162                &mut data_ptr as *mut _,
163                &data_len as *const _,
164                &mut bytes_valid as *mut _))?;
165
166            Ok(data.len() - bytes_valid as usize)
167        }
168    }
169
170    pub fn decode_frame(&mut self, pcm: &mut [i16]) -> Result<(), DecoderError> {
171        unsafe {
172            check(sys::aacDecoder_DecodeFrame(self.handle,
173                pcm.as_mut_ptr() as *mut i16,
174                pcm.len() as c_int,
175                0))
176        }
177    }
178
179    pub fn decoded_frame_size(&self) -> usize {
180        let stream_info = self.stream_info();
181
182        stream_info.numChannels as usize * stream_info.frameSize as usize
183    }
184
185    pub fn stream_info(&self) -> &StreamInfo {
186        unsafe { &*sys::aacDecoder_GetStreamInfo(self.handle) }
187    }
188}
189
190impl Drop for Decoder {
191    fn drop(&mut self) {
192        unsafe { sys::aacDecoder_Close(self.handle); }
193    }
194}
195
196#[derive(Clone, Copy, Debug)]
197pub enum Transport {
198    Raw,
199    Adts,
200}