rsmpeg/avformat/
avio.rs

1use std::{
2    ffi::{c_void, CStr},
3    ops::Deref,
4    ptr::{self, NonNull},
5    slice,
6};
7
8use crate::{
9    avutil::{AVDictionary, AVMem},
10    error::*,
11    ffi,
12    shared::*,
13};
14
15wrap!(AVIOContext: ffi::AVIOContext);
16
17pub struct AVIOContextURL(AVIOContext);
18
19impl Deref for AVIOContextURL {
20    type Target = AVIOContext;
21    fn deref(&self) -> &Self::Target {
22        &self.0
23    }
24}
25impl std::ops::DerefMut for AVIOContextURL {
26    fn deref_mut(&mut self) -> &mut Self::Target {
27        &mut self.0
28    }
29}
30
31impl AVIOContextURL {
32    /// Create and initialize a [`AVIOContextURL`] for accessing the resource indicated
33    /// by url.
34    ///
35    /// When the resource indicated by url has been opened in read+write mode,
36    /// the [`AVIOContextURL`] can be used only for writing.
37    ///
38    /// `options` A dictionary filled with protocol-private options.
39    pub fn open(
40        url: &CStr,
41        flags: u32,
42        options: Option<&mut Option<AVDictionary>>,
43    ) -> Result<Self> {
44        let mut io_context = ptr::null_mut();
45        let mut dummy_options = None;
46        let options = options.unwrap_or(&mut dummy_options);
47        let mut options_ptr = options
48            .as_mut()
49            .map(|x| x.as_mut_ptr())
50            .unwrap_or_else(ptr::null_mut);
51
52        unsafe {
53            ffi::avio_open2(
54                &mut io_context,
55                url.as_ptr(),
56                flags as _,
57                ptr::null(),
58                &mut options_ptr,
59            )
60        }
61        .upgrade()?;
62
63        // Forget the old options since it's ownership is transferred.
64        let mut new_options = options_ptr
65            .upgrade()
66            .map(|x| unsafe { AVDictionary::from_raw(x) });
67        std::mem::swap(options, &mut new_options);
68        std::mem::forget(new_options);
69
70        Ok(Self(unsafe {
71            AVIOContext::from_raw(NonNull::new(io_context).unwrap())
72        }))
73    }
74}
75
76impl Drop for AVIOContextURL {
77    fn drop(&mut self) {
78        unsafe { ffi::avio_close(self.as_mut_ptr()) }
79            .upgrade()
80            .unwrap();
81    }
82}
83
84/// Custom [`AVIOContext`], used for custom IO.
85pub struct AVIOContextCustom {
86    inner: AVIOContext,
87    _opaque: Box<Opaque>,
88}
89
90impl Deref for AVIOContextCustom {
91    type Target = AVIOContext;
92    fn deref(&self) -> &Self::Target {
93        &self.inner
94    }
95}
96
97impl std::ops::DerefMut for AVIOContextCustom {
98    fn deref_mut(&mut self) -> &mut Self::Target {
99        &mut self.inner
100    }
101}
102
103pub type ReadPacketCallback = Box<dyn FnMut(&mut Vec<u8>, &mut [u8]) -> i32 + Send + 'static>;
104pub type WritePacketCallback = Box<dyn FnMut(&mut Vec<u8>, &[u8]) -> i32 + Send + 'static>;
105pub type SeekCallback = Box<dyn FnMut(&mut Vec<u8>, i64, i32) -> i64 + Send + 'static>;
106
107pub struct Opaque {
108    data: Vec<u8>,
109    read_packet: Option<ReadPacketCallback>,
110    write_packet: Option<WritePacketCallback>,
111    seek: Option<SeekCallback>,
112}
113
114impl AVIOContextCustom {
115    /// `write_flag` - set to `false` on read, set to `true` on write.
116    pub fn alloc_context(
117        mut buffer: AVMem,
118        write_flag: bool,
119        data: Vec<u8>,
120        read_packet: Option<ReadPacketCallback>,
121        write_packet: Option<WritePacketCallback>,
122        seek: Option<SeekCallback>,
123    ) -> Self {
124        // According to the documentation of `avio_alloc_context`:
125        //
126        // `buffer`: Memory block for input/output operations via AVIOContext. The
127        // buffer must be allocated with av_malloc() and friends. It may be freed
128        // and replaced with a new buffer by libavformat.
129        //
130        // So this function accepts `AVMem` rather than ordinary `*mut u8`.
131
132        let (read_packet_c, write_packet_c, seek_c) = {
133            use std::os::raw::c_void;
134            // Function is called when the function is given and opaque is not null.
135            unsafe extern "C" fn read_c(opaque: *mut c_void, data: *mut u8, len: i32) -> i32 {
136                let buf = unsafe { slice::from_raw_parts_mut(data, len as usize) };
137                let opaque = unsafe { (opaque as *mut Opaque).as_mut() }.unwrap();
138                opaque.read_packet.as_mut().unwrap()(&mut opaque.data, buf)
139            }
140            #[cfg(not(feature = "ffmpeg7"))]
141            unsafe extern "C" fn write_c(opaque: *mut c_void, data: *mut u8, len: i32) -> i32 {
142                let buf = unsafe { slice::from_raw_parts(data, len as usize) };
143                let opaque = unsafe { (opaque as *mut Opaque).as_mut() }.unwrap();
144                opaque.write_packet.as_mut().unwrap()(&mut opaque.data, buf)
145            }
146            #[cfg(feature = "ffmpeg7")]
147            unsafe extern "C" fn write_c(opaque: *mut c_void, data: *const u8, len: i32) -> i32 {
148                let buf = unsafe { slice::from_raw_parts(data, len as usize) };
149                let opaque = unsafe { (opaque as *mut Opaque).as_mut() }.unwrap();
150                opaque.write_packet.as_mut().unwrap()(&mut opaque.data, buf)
151            }
152            unsafe extern "C" fn seek_c(opaque: *mut c_void, offset: i64, whence: i32) -> i64 {
153                let opaque = unsafe { (opaque as *mut Opaque).as_mut() }.unwrap();
154                opaque.seek.as_mut().unwrap()(&mut opaque.data, offset, whence)
155            }
156
157            (
158                read_packet.is_some().then_some(read_c as _),
159                // Note: If compiler errors here, you might have used wrong feature flag(ffmpeg6|ffmpeg7).
160                write_packet.is_some().then_some(write_c as _),
161                seek.is_some().then_some(seek_c as _),
162            )
163        };
164
165        let mut opaque = Box::new(Opaque {
166            data,
167            read_packet,
168            write_packet,
169            seek,
170        });
171
172        // After reading the implementation, avio_alloc_context only fails on no
173        // memory.
174        let context = unsafe {
175            ffi::avio_alloc_context(
176                buffer.as_mut_ptr(),
177                buffer.len as _,
178                if write_flag { 1 } else { 0 },
179                &mut *opaque as *mut _ as _,
180                read_packet_c,
181                write_packet_c,
182                seek_c,
183            )
184        }
185        .upgrade()
186        .unwrap();
187
188        // If `AVIOContext` allocation successes, buffer is transferred to
189        // `AVIOContext::buffer`, so we don't call drop function of `AVMem`, later
190        // it will be freed in `AVIOContext::drop`.
191        let _ = buffer.into_raw();
192
193        Self {
194            inner: unsafe { AVIOContext::from_raw(context) },
195            _opaque: opaque,
196        }
197    }
198
199    /// Re-take the ownership of the `data` passed in `alloc_context`.
200    /// The `data` inside this will be set to an empty vector.
201    pub fn take_data(&mut self) -> Vec<u8> {
202        std::mem::take(&mut self._opaque.data)
203    }
204
205    /// Get a mutable reference to the data inside this context.
206    pub fn as_mut_data(&mut self) -> &mut Vec<u8> {
207        &mut self._opaque.data
208    }
209}
210
211impl Drop for AVIOContextCustom {
212    fn drop(&mut self) {
213        // Recover the `AVMem` fom the buffer and drop it. We don't attach the
214        // AVMem to this type because according to the documentation, the buffer
215        // pointer may be changed during it's usage.
216        //
217        // There is no need to change self.buffer to null because
218        // avio_context_free is just `av_freep`.
219        if let Some(buffer) = NonNull::new(self.buffer) {
220            let _ = unsafe { AVMem::from_raw(buffer) };
221        }
222        unsafe { ffi::avio_context_free(&mut self.as_mut_ptr()) };
223    }
224}
225
226pub struct AVIOProtocol;
227
228impl AVIOProtocol {
229    /// Return the name of the protocol that will handle the passed URL.
230    pub fn find_protocol_name(url: &CStr) -> Option<&'static CStr> {
231        unsafe {
232            ffi::avio_find_protocol_name(url.as_ptr())
233                .upgrade()
234                .map(|x| CStr::from_ptr(x.as_ptr()))
235        }
236    }
237
238    /// Iterate through names of available output protocols.
239    pub fn outputs() -> AVIOProtocolIter {
240        AVIOProtocolIter {
241            opaque: ptr::null_mut(),
242            output: 1,
243        }
244    }
245
246    /// Iterate through names of available input protocols.
247    pub fn inputs() -> AVIOProtocolIter {
248        AVIOProtocolIter {
249            opaque: ptr::null_mut(),
250            output: 0,
251        }
252    }
253}
254
255pub struct AVIOProtocolIter {
256    opaque: *mut c_void,
257    output: i32,
258}
259
260impl Iterator for AVIOProtocolIter {
261    type Item = &'static CStr;
262
263    fn next(&mut self) -> Option<Self::Item> {
264        unsafe {
265            ffi::avio_enum_protocols(&mut self.opaque, self.output)
266                .upgrade()
267                .map(|x| CStr::from_ptr(x.as_ptr()))
268        }
269    }
270}
271
272#[cfg(test)]
273mod test {
274    use super::*;
275
276    #[test]
277    fn test_iterate_output_protocols() {
278        let outputs = AVIOProtocol::outputs()
279            .map(|x| x.to_str().unwrap())
280            .collect::<Vec<_>>();
281        dbg!(&outputs);
282        assert!(!outputs.is_empty());
283        assert!(outputs.contains(&"file"));
284        assert!(outputs.contains(&"http"));
285        assert!(outputs.contains(&"rtmp"));
286    }
287
288    #[test]
289    fn test_iterate_input_protocols() {
290        let inputs = AVIOProtocol::inputs()
291            .map(|x| x.to_str().unwrap())
292            .collect::<Vec<_>>();
293        dbg!(&inputs);
294        assert!(!inputs.is_empty());
295        assert!(inputs.contains(&"file"));
296        assert!(inputs.contains(&"http"));
297        assert!(inputs.contains(&"async"));
298    }
299}