forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBa31973fTahinli7 days ago3925 commits

codec.rs161 lines, 5.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, VideoFrame};
5use ec_core::packet::Packet;
6use ec_core::registry::{CodecId, CodecParameters, MediaParameters};
7use ec_core::timebase::{TimeBase, Timestamp};
8
9use crate::decoder::{Core, PictureInfo};
10use crate::header::SequenceInfo;
11
12/// MPEG-1/2 video decoder behind the codec registry's packet/frame contract.
13///
14/// Packets are elementary-stream bytes: one or more whole pictures with the
15/// headers in front of them (what a TS/PS demuxer or an `.m2v` splitter
16/// produces). Pictures come back in display order; reordering delay is drained
17/// by [`Decoder::flush`](ec_core::registry::Decoder::flush).
18pub struct Mpeg2Decoder {
19 params: CodecParameters,
20 core: Core,
21 eof: bool,
22 last_info: Option<PictureInfo>,
23}
24
25impl Mpeg2Decoder {
26 /// A decoder for `params`. `extradata`, when present, is parsed as
27 /// elementary-stream headers (sequence header and extensions with start
28 /// codes), so the picture size is known before the first packet.
29 pub fn new(params: CodecParameters) -> Result<Mpeg2Decoder> {
30 if params.codec != CodecId::Mpeg2Video {
31 return Err(Error::unsupported(
32 format!("codec {:?}", params.codec),
33 "this decoder implements MPEG-1/2 video only",
34 ));
35 }
36 let mut d = Mpeg2Decoder {
37 params,
38 core: Core::new(),
39 eof: false,
40 last_info: None,
41 };
42 if let Some(extra) = d.params.extradata.clone() {
43 // Headers only; a refusal here resurfaces with the first picture.
44 let _ = d.core.push_complete(&extra, None);
45 d.refresh_params();
46 }
47 Ok(d)
48 }
49
50 /// Feed arbitrarily chunked elementary-stream bytes. A unit is decoded once
51 /// the next start code has arrived; [`Mpeg2Decoder::flush_stream`] ends the
52 /// stream. `pts` belongs to the first picture that starts in `data`.
53 pub fn send_bytes(&mut self, data: &[u8], pts: Option<Timestamp>) -> Result<()> {
54 self.eof = false;
55 let r = self.core.push(data, pts);
56 self.refresh_params();
57 r
58 }
59
60 /// Decode what is buffered and release the delayed pictures.
61 pub fn flush_stream(&mut self) -> Result<()> {
62 let r = self.core.flush();
63 self.eof = true;
64 self.refresh_params();
65 r
66 }
67
68 /// Take the next decoded picture with its [`PictureInfo`].
69 pub fn pop_picture(&mut self) -> Option<(VideoFrame, PictureInfo)> {
70 self.core.out.pop_front()
71 }
72
73 /// The current sequence header/extension, once seen.
74 pub fn sequence(&self) -> Option<&SequenceInfo> {
75 self.core.seq.as_ref()
76 }
77
78 /// [`PictureInfo`] of the frame last returned by `receive_frame`.
79 pub fn last_picture_info(&self) -> Option<&PictureInfo> {
80 self.last_info.as_ref()
81 }
82
83 /// Pictures dropped because their forward reference was missing (the
84 /// leading B pictures of an open GOP after a seek).
85 pub fn dropped_pictures(&self) -> u64 {
86 self.core.dropped
87 }
88
89 fn refresh_params(&mut self) {
90 let Some(seq) = self.core.seq.as_ref() else {
91 return;
92 };
93 if let MediaParameters::Video(v) = &mut self.params.media {
94 v.width = seq.width;
95 v.height = seq.height;
96 v.format = Some(if seq.chroma_format == 2 {
97 ec_core::frame::PixelFormat::I422
98 } else {
99 ec_core::frame::PixelFormat::I420
100 });
101 v.frame_rate = seq.frame_rate().map(|(n, d)| TimeBase::new(n as i64, d as i64));
102 // Display aspect ratio -> sample aspect ratio.
103 let dar = match seq.aspect_ratio_code {
104 2 => Some((4i64, 3i64)),
105 3 => Some((16, 9)),
106 4 => Some((221, 100)),
107 _ => None,
108 };
109 v.sample_aspect_ratio = if seq.mpeg2 {
110 dar.map(|(n, d)| {
111 let (num, den) = (n * seq.height as i64, d * seq.width as i64);
112 let g = gcd(num, den).max(1);
113 TimeBase::new(num / g, den / g)
114 })
115 } else {
116 None
117 };
118 }
119 }
120}
121
122fn gcd(a: i64, b: i64) -> i64 {
123 if b == 0 { a } else { gcd(b, a % b) }
124}
125
126impl ec_core::registry::Decoder for Mpeg2Decoder {
127 fn codec_parameters(&self) -> &CodecParameters {
128 &self.params
129 }
130
131 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
132 self.eof = false;
133 let pts = packet
134 .pts
135 .map(|ticks| Timestamp::new(ticks, packet.time_base));
136 let r = self.core.push_complete(&packet.data, pts);
137 self.refresh_params();
138 r
139 }
140
141 fn receive_frame(&mut self) -> Result<Frame> {
142 match self.core.out.pop_front() {
143 Some((f, info)) => {
144 self.last_info = Some(info);
145 Ok(Frame::Video(f))
146 }
147 None if self.eof => Err(Error::Eof),
148 None => Err(Error::NeedMore),
149 }
150 }
151
152 fn flush(&mut self) -> Result<()> {
153 self.flush_stream()
154 }
155
156 fn reset(&mut self) {
157 self.core.reset();
158 self.eof = false;
159 self.last_info = None;
160 }
161}