forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

lib.rs330 lines, 11.7 KiBHistoryRawDownload
1//! Motion JPEG video decoder.
2//!
3//! A packet is one JPEG (or two, for field-coded MJPEG-A / AVI interlaced video). It is decoded
4//! straight to planar YUV at the file's own subsampling by [`ec_image::jpeg::decode_yuv`]: no
5//! chroma upsampling, no RGB round trip. The planes are byte-identical to libavcodec's `mjpeg`
6//! decoder (`yuvj420p`, `yuvj422p`, `yuvj444p`, `gray`).
7//!
8//! Frames are always tagged full range (JFIF), whatever the container says: MJPEG is full range.
9//!
10//! What this handles beyond a still JPEG: packets with no DHT (AVI1/MJPG, which rely on the
11//! Annex K tables), restart markers, progressive frames, and two-field packets, which are woven
12//! into one frame and flagged interlaced.
13//!
14//! Refused by name: 12-bit precision, arithmetic/lossless/hierarchical JPEG, CMYK, RGB-coded
15//! frames, and sampling layouts with no pixel format (4:4:0, 4:1:1, 4:1:0).
16#![forbid(unsafe_code)]
17
18use std::collections::VecDeque;
19
20use ec_core::error::{Error, Result};
21use ec_core::frame::{ColorInfo, Frame, Interlace, PixelFormat, Plane, VideoFrame};
22use ec_core::packet::Packet;
23use ec_core::registry::{CodecId, CodecParameters, MediaParameters};
24use ec_core::timebase::Timestamp;
25use ec_image::Limits;
26use ec_image::jpeg::{Subsampling, YuvImage};
27
28/// Largest picture accepted by default (matches the still decoder's order of magnitude).
29const DEFAULT_LIMITS: Limits = Limits {
30 max_pixels: 16384 * 16384,
31 max_alloc: 1 << 30,
32 max_total_alloc: 1 << 31,
33};
34
35/// Motion JPEG decoder behind the codec registry's packet/frame contract.
36pub struct MjpegDecoder {
37 params: CodecParameters,
38 field_order: Interlace,
39 limits: Limits,
40 out: VecDeque<VideoFrame>,
41 eof: bool,
42}
43
44impl MjpegDecoder {
45 /// A decoder for `params` (`CodecId::Mjpeg`). The container's coded height steers
46 /// two-field detection: a packet holding two JPEGs of half that height is one interlaced
47 /// frame (libavcodec's rule); a packet whose JPEG already has the container's height is
48 /// decoded as its first image only.
49 pub fn new(params: CodecParameters) -> Result<MjpegDecoder> {
50 if params.codec != CodecId::Mjpeg {
51 return Err(Error::unsupported(
52 format!("codec {:?}", params.codec),
53 "this decoder implements Motion JPEG only",
54 ));
55 }
56 Ok(MjpegDecoder {
57 params,
58 field_order: Interlace::TopFieldFirst,
59 limits: DEFAULT_LIMITS,
60 out: VecDeque::new(),
61 eof: false,
62 })
63 }
64
65 /// Which field the first JPEG of a two-field packet is. Default top field first (QuickTime
66 /// `mjpa`, Matroska); libavcodec's AVI path (`MJPG` tag) takes the first image as the
67 /// bottom field, so an AVI caller passes [`Interlace::BottomFieldFirst`] (or reads a
68 /// container `fiel` atom).
69 pub fn set_field_order(&mut self, order: Interlace) {
70 self.field_order = if order.is_interlaced() {
71 order
72 } else {
73 Interlace::TopFieldFirst
74 };
75 }
76
77 /// Replace the size limits applied to every picture.
78 pub fn set_limits(&mut self, limits: Limits) {
79 self.limits = limits;
80 }
81
82 /// Decode one packet to one frame.
83 pub fn decode(&mut self, data: &[u8], pts: Option<Timestamp>) -> Result<VideoFrame> {
84 let container_height = match &self.params.media {
85 MediaParameters::Video(v) => v.height,
86 _ => 0,
87 };
88 let container_color = match &self.params.media {
89 MediaParameters::Video(v) => v.color,
90 _ => ColorInfo::default(),
91 };
92 let mut frame = decode_frame(data, container_height, self.field_order, self.limits)?;
93 frame.pts = pts;
94 // JFIF is BT.601 and full range. A container's matrix is kept when it states one;
95 // its range claim is not: MJPEG is full range.
96 frame.color = ColorInfo {
97 primaries: container_color.primaries,
98 transfer: container_color.transfer,
99 matrix: if container_color.matrix == 2 {
100 5
101 } else {
102 container_color.matrix
103 },
104 full_range: true,
105 };
106 if let MediaParameters::Video(v) = &mut self.params.media {
107 v.width = frame.width;
108 if !frame.interlace.is_interlaced() || v.height == 0 {
109 v.height = frame.height;
110 }
111 v.format = Some(frame.format);
112 }
113 Ok(frame)
114 }
115}
116
117fn format_of(s: Subsampling) -> PixelFormat {
118 match s {
119 Subsampling::Gray => PixelFormat::Gray8,
120 Subsampling::Yuv420 => PixelFormat::I420,
121 Subsampling::Yuv422 => PixelFormat::I422,
122 Subsampling::Yuv444 => PixelFormat::I444,
123 }
124}
125
126/// Decode one MJPEG packet. `container_height` is the coded height the container states
127/// (0 when unknown); `first_field` names the first image's field for two-field packets.
128pub fn decode_frame(
129 data: &[u8],
130 container_height: u32,
131 first_field: Interlace,
132 limits: Limits,
133) -> Result<VideoFrame> {
134 let converted;
135 let data = if is_mjpegb(data) {
136 converted = mjpegb_to_jpeg(data)?;
137 &converted[..]
138 } else {
139 data
140 };
141 let first = ec_image::jpeg::decode_yuv(data, limits)?;
142 let rest = &data[first.end.min(data.len())..];
143 let second_at = rest.windows(2).position(|w| w == [0xff, 0xd8]);
144 let two_fields =
145 second_at.is_some() && (container_height == 0 || container_height != first.height);
146 if let (true, Some(at)) = (two_fields, second_at) {
147 let second = ec_image::jpeg::decode_yuv(&rest[at..], limits)?;
148 if second.width != first.width
149 || second.height != first.height
150 || second.subsampling != first.subsampling
151 {
152 return Err(Error::corrupt(
153 "MJPEG: the two fields differ in size or layout",
154 ));
155 }
156 return weave(first, second, first_field);
157 }
158 let format = format_of(first.subsampling);
159 let (width, height) = (first.width, first.height);
160 let planes = first
161 .planes
162 .into_iter()
163 .map(|p| Plane::new(p.data, p.width))
164 .collect();
165 let mut f = VideoFrame::try_new(format, width, height, planes)?;
166 f.color = jfif_color();
167 f.interlace = Interlace::Progressive;
168 Ok(f)
169}
170
171/// True for an MJPEG-B (QuickTime `mjpb`) packet: four zero bytes, then `mjpg`.
172fn is_mjpegb(data: &[u8]) -> bool {
173 data.len() > 40 && data[..4] == [0; 4] && &data[4..8] == b"mjpg"
174}
175
176/// Rewrap an MJPEG-B packet as ordinary baseline JPEG (one per field, concatenated).
177///
178/// A field starts with ten big-endian words: reserved 0, `mjpg`, field size, padded field
179/// size, then the offsets (from the field start) of the second field, DQT, DHT, SOF, SOS and the
180/// entropy-coded data. The DQT/DHT/SOF/SOS blocks keep their 16-bit length but lose their
181/// marker; a zero offset means the block is absent. The scan data carries no FF 00 stuffing. The second field, when present, is a
182/// complete field of the same shape at `second_field_offs`.
183fn mjpegb_to_jpeg(data: &[u8]) -> Result<Vec<u8>> {
184 let bad = |what: &str| Error::corrupt(format!("MJPEG-B: {what}"));
185 let word = |d: &[u8], i: usize| -> Result<usize> {
186 d.get(i * 4..i * 4 + 4)
187 .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize)
188 .ok_or_else(|| bad("short header"))
189 };
190 let mut out = Vec::with_capacity(data.len() + 64);
191 let mut base = 0usize;
192 for pass in 0..2 {
193 let f = &data[base..];
194 if f.len() < 40 || f[4..8] != *b"mjpg" {
195 return Err(bad("bad field header"));
196 }
197 let size = word(f, 2)?.min(f.len());
198 let (second, dqt, dht, sof, sos, sod) = (
199 word(f, 4)?,
200 word(f, 5)?,
201 word(f, 6)?,
202 word(f, 7)?,
203 word(f, 8)?,
204 word(f, 9)?,
205 );
206 let f = &f[..size];
207 out.extend_from_slice(&[0xff, 0xd8]);
208 let mut end_of_sos = 0;
209 for (off, marker) in [(dqt, 0xdb), (dht, 0xc4), (sof, 0xc0), (sos, 0xda)] {
210 if off == 0 {
211 continue;
212 }
213 let len = f
214 .get(off..off + 2)
215 .map(|b| usize::from(u16::from_be_bytes([b[0], b[1]])))
216 .ok_or_else(|| bad("block offset past the field"))?;
217 let seg = f
218 .get(off..off + len)
219 .ok_or_else(|| bad("block past the field"))?;
220 out.extend_from_slice(&[0xff, marker]);
221 out.extend_from_slice(seg);
222 if marker == 0xda {
223 end_of_sos = off + len;
224 }
225 }
226 if sos == 0 {
227 return Err(bad("field without a scan header"));
228 }
229 let start = if sod >= end_of_sos { sod } else { end_of_sos };
230 let scan = f
231 .get(start..)
232 .ok_or_else(|| bad("scan data past the field"))?;
233 // MJPEG-B entropy data is not byte-stuffed; ordinary JPEG needs FF 00 for every FF.
234 for &b in scan {
235 out.push(b);
236 if b == 0xff {
237 out.push(0);
238 }
239 }
240 out.extend_from_slice(&[0xff, 0xd9]);
241 if pass == 0 {
242 if second == 0 || base != 0 || second >= data.len() {
243 break;
244 }
245 base = second;
246 }
247 }
248 Ok(out)
249}
250
251fn jfif_color() -> ColorInfo {
252 ColorInfo {
253 primaries: 2,
254 transfer: 2,
255 matrix: 5,
256 full_range: true,
257 }
258}
259
260/// Interleave two field images into one frame.
261fn weave(first: YuvImage, second: YuvImage, first_field: Interlace) -> Result<VideoFrame> {
262 let format = format_of(first.subsampling);
263 let height = first
264 .height
265 .checked_mul(2)
266 .ok_or_else(|| Error::corrupt("MJPEG: height overflow"))?;
267 let width = first.width;
268 let geometry = format.plane_geometry(width, height);
269 let first_odd = first_field == Interlace::BottomFieldFirst;
270 let mut planes = Vec::with_capacity(geometry.len());
271 for (i, (row_bytes, rows)) in geometry.into_iter().enumerate() {
272 let (a, b) = (&first.planes[i], &second.planes[i]);
273 let mut data = vec![0u8; row_bytes * rows];
274 for (k, field) in [a, b].into_iter().enumerate() {
275 // The first image goes on the odd lines when it is the bottom field.
276 let parity = if (k == 0) == first_odd { 1 } else { 0 };
277 for y in 0..field.height {
278 let dst = 2 * y + parity;
279 if dst >= rows {
280 break;
281 }
282 data[dst * row_bytes..(dst + 1) * row_bytes]
283 .copy_from_slice(&field.data[y * field.width..y * field.width + row_bytes]);
284 }
285 }
286 planes.push(Plane::new(data, row_bytes));
287 }
288 let mut f = VideoFrame::try_new(format, width, height, planes)?;
289 f.color = jfif_color();
290 f.interlace = if first_odd {
291 Interlace::BottomFieldFirst
292 } else {
293 Interlace::TopFieldFirst
294 };
295 Ok(f)
296}
297
298impl ec_core::registry::Decoder for MjpegDecoder {
299 fn codec_parameters(&self) -> &CodecParameters {
300 &self.params
301 }
302
303 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
304 self.eof = false;
305 let pts = packet
306 .pts
307 .map(|ticks| Timestamp::new(ticks, packet.time_base));
308 let frame = self.decode(&packet.data, pts)?;
309 self.out.push_back(frame);
310 Ok(())
311 }
312
313 fn receive_frame(&mut self) -> Result<Frame> {
314 match self.out.pop_front() {
315 Some(f) => Ok(Frame::Video(f)),
316 None if self.eof => Err(Error::Eof),
317 None => Err(Error::NeedMore),
318 }
319 }
320
321 fn flush(&mut self) -> Result<()> {
322 self.eof = true;
323 Ok(())
324 }
325
326 fn reset(&mut self) {
327 self.out.clear();
328 self.eof = false;
329 }
330}