forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBc2d94daTahinli6 days ago3964 commits

codec.rs180 lines, 6.3 KiBHistoryRawDownload
1//! The [`ec_core::registry::Decoder`] entry path and a byte-stream API.
2
3use ec_core::error::{Error, Result};
4use ec_core::frame::{Frame, PixelFormat, VideoFrame};
5use ec_core::packet::Packet;
6use ec_core::registry::{CodecId, CodecParameters, MediaParameters};
7use ec_core::timebase::{TimeBase, Timestamp};
8
9use crate::core::{Core, PictureInfo};
10
11/// MPEG-4 Part 2 Visual (Simple and Advanced Simple profile) and H.263 baseline
12/// decoder behind the codec registry's packet/frame contract.
13///
14/// One packet is one access unit (as stored by AVI, MP4/3GP and Matroska); a
15/// DivX/XviD "packed bitstream" packet that carries a P-VOP followed by a
16/// B-VOP is unpacked. The decoder's `extradata` is the VOL header (an `esds`
17/// DecoderSpecificInfo, or the `00 00 01 B0 ...` sequence in AVI).
18///
19/// Pictures come back in display order. Unless the stream sets `low_delay`,
20/// the decoder holds back one reference picture: the first `receive_frame`
21/// answer arrives after the second I/P picture was decoded, and
22/// [`Decoder::flush`](ec_core::registry::Decoder::flush) drains the last one.
23/// B pictures are returned immediately. Timestamps travel with their picture.
24pub struct Mpeg4Decoder {
25 params: CodecParameters,
26 core: Core,
27 eof: bool,
28 last_info: Option<PictureInfo>,
29}
30
31impl Mpeg4Decoder {
32 pub fn new(params: CodecParameters) -> Result<Mpeg4Decoder> {
33 if params.codec == CodecId::MsMpeg4V1 {
34 return Err(Error::unsupported(
35 "MS-MPEG4 version 1",
36 "only versions 2 and 3 are implemented".to_string(),
37 ));
38 }
39 let ms_version = match params.codec {
40 CodecId::MsMpeg4V2 => 2,
41 CodecId::MsMpeg4V3 => 3,
42 _ => 0,
43 };
44 if params.codec != CodecId::Mpeg4Part2 && ms_version == 0 {
45 return Err(Error::unsupported(
46 format!("codec {:?}", params.codec),
47 "this decoder implements MPEG-4 Part 2 / H.263 only",
48 ));
49 }
50 let mut d = Mpeg4Decoder {
51 params,
52 core: Core::new(),
53 eof: false,
54 last_info: None,
55 };
56 if ms_version != 0 {
57 d.core.ms_version = ms_version;
58 d.core.have_vol = true;
59 d.core.vol.low_delay = true;
60 d.core.vol.progressive_sequence = true;
61 if let MediaParameters::Video(v) = &d.params.media
62 && v.width > 0
63 && v.height > 0
64 {
65 let (w, h) = (v.width as usize, v.height as usize);
66 d.core.vol.width = w as u32;
67 d.core.vol.height = h as u32;
68 d.core.set_size(w, h);
69 }
70 d.core.xvid_idct = d.core.force_xvid_idct.unwrap_or(false);
71 } else if let Some(extra) = d.params.extradata.clone() {
72 // Headers only; a refusal here resurfaces with the first picture.
73 let _ = d.core.parse_config(&extra);
74 d.refresh_params();
75 }
76 Ok(d)
77 }
78
79 /// Container FourCC (`XVID`, `DIVX`, `DX50`, ...). FFmpeg uses it to pick
80 /// bug workarounds for encoders that do not identify themselves in user data.
81 pub fn set_fourcc(&mut self, tag: [u8; 4]) {
82 self.core.tag = tag;
83 }
84
85 /// Force the IDCT: `Some(true)` the XviD IDCT, `Some(false)` the simple IDCT.
86 /// `None` (default) follows FFmpeg's `-idct auto`: XviD IDCT when the stream
87 /// identifies as XviD, simple IDCT otherwise.
88 pub fn set_xvid_idct(&mut self, force: Option<bool>) {
89 self.core.force_xvid_idct = force;
90 }
91
92 /// Decode one packet's bytes. `pts` is attached to the picture decoded from it.
93 pub fn send_bytes(&mut self, data: &[u8], pts: Option<Timestamp>) -> Result<()> {
94 self.eof = false;
95 let r = if self.core.ms_version != 0 {
96 self.core.decode_msmpeg4_packet(data, pts)
97 } else {
98 self.core.decode_packet(data, pts)
99 };
100 self.refresh_params();
101 r
102 }
103
104 /// Release the delayed reference picture.
105 pub fn flush_stream(&mut self) -> Result<()> {
106 self.core.flush();
107 self.eof = true;
108 Ok(())
109 }
110
111 /// Take the next decoded picture with its [`PictureInfo`].
112 pub fn pop_picture(&mut self) -> Option<(VideoFrame, PictureInfo)> {
113 self.core.out.pop_front().map(|o| (o.frame, o.info))
114 }
115
116 /// [`PictureInfo`] of the frame last returned by `receive_frame`.
117 pub fn last_picture_info(&self) -> Option<&PictureInfo> {
118 self.last_info.as_ref()
119 }
120
121 /// Whether the stream sets MPEG-4 `low_delay` (no picture reordering delay).
122 pub fn low_delay(&self) -> bool {
123 self.core.vol.low_delay
124 }
125
126 fn refresh_params(&mut self) {
127 if !self.core.have_vol || self.core.w == 0 {
128 return;
129 }
130 let c = &self.core;
131 if let MediaParameters::Video(v) = &mut self.params.media {
132 v.width = c.w as u32;
133 v.height = c.h as u32;
134 v.format = Some(PixelFormat::I420);
135 if !c.is_h263 && c.vol.sar.0 > 0 && c.vol.sar.1 > 0 && c.vol.sar.0 != c.vol.sar.1 {
136 v.sample_aspect_ratio = Some(TimeBase::new(c.vol.sar.0 as i64, c.vol.sar.1 as i64));
137 }
138 if !c.is_h263 && c.vol.time_inc_res > 0 && c.vol.fixed_vop_rate_den > 0 {
139 v.frame_rate = Some(TimeBase::new(
140 c.vol.time_inc_res as i64,
141 c.vol.fixed_vop_rate_den as i64,
142 ));
143 }
144 }
145 }
146}
147
148impl ec_core::registry::Decoder for Mpeg4Decoder {
149 fn codec_parameters(&self) -> &CodecParameters {
150 &self.params
151 }
152
153 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
154 let pts = packet
155 .pts
156 .map(|ticks| Timestamp::new(ticks, packet.time_base));
157 self.send_bytes(&packet.data, pts)
158 }
159
160 fn receive_frame(&mut self) -> Result<Frame> {
161 match self.core.out.pop_front() {
162 Some(o) => {
163 self.last_info = Some(o.info);
164 Ok(Frame::Video(o.frame))
165 }
166 None if self.eof => Err(Error::Eof),
167 None => Err(Error::NeedMore),
168 }
169 }
170
171 fn flush(&mut self) -> Result<()> {
172 self.flush_stream()
173 }
174
175 fn reset(&mut self) {
176 self.core.reset();
177 self.eof = false;
178 self.last_info = None;
179 }
180}