forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

synth.rs297 lines, 9.6 KiBHistoryRawDownload
1//! Caption stream synthesis for tests and tools: a CEA-608 byte-pair generator, `cc_data`
2//! builders, and SEI / user-data writers that splice captions into existing H.264, HEVC and
3//! MPEG-2 elementary streams.
4
5use crate::ccdata::CcTriplet;
6
7/// Set odd parity on bit 7.
8pub fn parity(b: u8) -> u8 {
9 let b = b & 0x7F;
10 if b.count_ones().is_multiple_of(2) {
11 b | 0x80
12 } else {
13 b
14 }
15}
16
17/// A 608 byte-pair script builder (field 1). Each element is one pair; schedule one pair per frame.
18#[derive(Default, Clone, Debug)]
19pub struct Script608 {
20 /// The pairs, parity already applied.
21 pub pairs: Vec<[u8; 2]>,
22}
23
24impl Script608 {
25 /// Empty script.
26 pub fn new() -> Script608 {
27 Script608::default()
28 }
29
30 /// A control pair, sent twice as the standard asks. `ch2` selects the second data channel.
31 pub fn ctrl(&mut self, b1: u8, b2: u8) -> &mut Self {
32 let p = [parity(b1), parity(b2)];
33 self.pairs.push(p);
34 self.pairs.push(p);
35 self
36 }
37
38 /// RCL (resume caption loading).
39 pub fn rcl(&mut self) -> &mut Self {
40 self.ctrl(0x14, 0x20)
41 }
42 /// ENM (erase non-displayed memory).
43 pub fn enm(&mut self) -> &mut Self {
44 self.ctrl(0x14, 0x2E)
45 }
46 /// EDM (erase displayed memory).
47 pub fn edm(&mut self) -> &mut Self {
48 self.ctrl(0x14, 0x2C)
49 }
50 /// EOC (end of caption).
51 pub fn eoc(&mut self) -> &mut Self {
52 self.ctrl(0x14, 0x2F)
53 }
54 /// CR (carriage return).
55 pub fn cr(&mut self) -> &mut Self {
56 self.ctrl(0x14, 0x2D)
57 }
58 /// RUn (n = 2..=4).
59 pub fn roll_up(&mut self, n: u8) -> &mut Self {
60 self.ctrl(0x14, 0x23 + n)
61 }
62 /// RDC (resume direct captioning, paint-on).
63 pub fn rdc(&mut self) -> &mut Self {
64 self.ctrl(0x14, 0x29)
65 }
66 /// PAC for 1-based `row` (1..=15), `indent` 0,4,..,28 columns, white; `underline` flag.
67 pub fn pac(&mut self, row: usize, indent: usize, underline: bool) -> &mut Self {
68 self.pac_style(row, indent, 0, false, underline)
69 }
70 /// PAC with colour index 0..6 or italics.
71 pub fn pac_style(
72 &mut self,
73 row: usize,
74 indent: usize,
75 color: u8,
76 italic: bool,
77 underline: bool,
78 ) -> &mut Self {
79 let (b1, hi) = match row {
80 1 => (0x11, 0),
81 2 => (0x11, 1),
82 3 => (0x12, 0),
83 4 => (0x12, 1),
84 5 => (0x15, 0),
85 6 => (0x15, 1),
86 7 => (0x16, 0),
87 8 => (0x16, 1),
88 9 => (0x17, 0),
89 10 => (0x17, 1),
90 11 => (0x10, 0),
91 12 => (0x13, 0),
92 13 => (0x13, 1),
93 14 => (0x14, 0),
94 _ => (0x14, 1),
95 };
96 let v: u8 = if indent > 0 {
97 8 + (indent / 4) as u8
98 } else if italic {
99 7
100 } else {
101 color
102 };
103 let b2 = 0x40 + hi * 0x20 + (v << 1) + u8::from(underline);
104 self.ctrl(b1, b2)
105 }
106 /// Mid-row code: colour 0..6, or italics when `italic`.
107 pub fn midrow(&mut self, color: u8, italic: bool, underline: bool) -> &mut Self {
108 let v = if italic { 7 } else { color };
109 self.ctrl(0x11, 0x20 + (v << 1) + u8::from(underline))
110 }
111 /// Special character 0..15 (`0x30 + n`), e.g. 7 is the music note.
112 pub fn special(&mut self, n: u8) -> &mut Self {
113 self.pairs.push([parity(0x11), parity(0x30 + n)]);
114 self
115 }
116 /// Extended character: `set` 0 for 0x12, 1 for 0x13; `n` 0..31. Preceded by a filler char.
117 pub fn extended(&mut self, set: u8, n: u8) -> &mut Self {
118 self.pairs.push([parity(b'?'), 0x80]);
119 self.pairs.push([parity(0x12 + set), parity(0x20 + n)]);
120 self
121 }
122 /// Plain text (basic character set bytes), two chars per pair, padded with a null.
123 pub fn text(&mut self, s: &str) -> &mut Self {
124 for c in s.as_bytes().chunks(2) {
125 self.pairs
126 .push([parity(c[0]), if c.len() > 1 { parity(c[1]) } else { 0x80 }]);
127 }
128 self
129 }
130 /// Null pairs (idle frames).
131 pub fn idle(&mut self, n: usize) -> &mut Self {
132 for _ in 0..n {
133 self.pairs.push([0x80, 0x80]);
134 }
135 self
136 }
137}
138
139/// Lay pairs onto frames starting at `start_frame`: one field 1 triplet per frame. Frames
140/// without a pair stay empty. Returns `frames` entries.
141pub fn schedule(frames: usize, start_frame: usize, pairs: &[[u8; 2]]) -> Vec<Vec<CcTriplet>> {
142 let mut out = vec![Vec::new(); frames];
143 for (i, p) in pairs.iter().enumerate() {
144 if let Some(f) = out.get_mut(start_frame + i) {
145 f.push(CcTriplet {
146 valid: true,
147 cc_type: 0,
148 data: *p,
149 });
150 }
151 }
152 out
153}
154
155/// Serialise `cc_data()` (flags, em_data, triplets, marker).
156pub fn cc_data_bytes(t: &[CcTriplet]) -> Vec<u8> {
157 let mut v = vec![0xC0 | (t.len() as u8 & 0x1F), 0xFF];
158 for x in t {
159 v.push(0xF8 | (u8::from(x.valid) << 2) | (x.cc_type & 3));
160 v.extend_from_slice(&x.data);
161 }
162 v.push(0xFF);
163 v
164}
165
166fn escape(rbsp: &[u8]) -> Vec<u8> {
167 let mut out = Vec::new();
168 let mut zeros = 0;
169 for &b in rbsp {
170 if zeros >= 2 && b <= 3 {
171 out.push(3);
172 zeros = 0;
173 }
174 out.push(b);
175 zeros = if b == 0 { zeros + 1 } else { 0 };
176 }
177 out
178}
179
180/// SEI RBSP carrying one ATSC A/53 T.35 message.
181pub fn sei_rbsp(triplets: &[CcTriplet]) -> Vec<u8> {
182 let cc = cc_data_bytes(triplets);
183 let mut payload = vec![0xB5, 0x00, 0x31, b'G', b'A', b'9', b'4', 0x03];
184 payload.extend(cc);
185 let mut r = vec![4u8];
186 let mut n = payload.len();
187 while n >= 255 {
188 r.push(0xFF);
189 n -= 255;
190 }
191 r.push(n as u8);
192 r.extend(payload);
193 r.push(0x80);
194 r
195}
196
197fn nals(data: &[u8]) -> Vec<(usize, usize)> {
198 // (start of start code, end) ranges for each NAL including its start code
199 let mut starts = Vec::new();
200 let mut i = 0;
201 while i + 3 <= data.len() {
202 if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 {
203 starts.push(i);
204 i += 3;
205 } else {
206 i += 1;
207 }
208 }
209 starts
210 .iter()
211 .enumerate()
212 .map(|(n, &s)| (s, starts.get(n + 1).copied().unwrap_or(data.len())))
213 .collect()
214}
215
216/// Insert an SEI NAL before the first slice of every picture of an Annex B H.264 (`hevc` false)
217/// or HEVC (`hevc` true) stream. `per_picture[k]` is the triplet list of the k-th picture in
218/// decode order; a missing or empty entry inserts nothing.
219pub fn insert_sei(stream: &[u8], hevc: bool, per_picture: &[Vec<CcTriplet>]) -> Vec<u8> {
220 let mut out = Vec::with_capacity(stream.len() + per_picture.len() * 24);
221 let mut pic = 0usize;
222 for (s, e) in nals(stream) {
223 let mut sc = s;
224 while stream[sc] == 0 {
225 sc += 1;
226 }
227 let hdr = sc + 1;
228 let first_slice = if hevc {
229 let ty = (stream[hdr] >> 1) & 0x3F;
230 ty < 32 && stream.get(hdr + 2).is_some_and(|b| b & 0x80 != 0)
231 } else {
232 let ty = stream[hdr] & 0x1F;
233 (ty == 1 || ty == 5) && stream.get(hdr + 1).is_some_and(|b| b & 0x80 != 0)
234 };
235 if first_slice {
236 if let Some(t) = per_picture.get(pic).filter(|t| !t.is_empty()) {
237 out.extend_from_slice(&[0, 0, 0, 1]);
238 if hevc {
239 out.extend_from_slice(&[0x4E, 0x01]);
240 } else {
241 out.push(0x06);
242 }
243 out.extend(escape(&sei_rbsp(t)));
244 }
245 pic += 1;
246 }
247 out.extend_from_slice(&stream[s..e]);
248 }
249 out
250}
251
252/// Insert ATSC `GA94` user data after each picture header / picture coding extension of an
253/// MPEG-2 elementary stream. `per_picture[k]` is the k-th picture in decode order. With `dvd`
254/// the `CC 01 F8` form (field 1 / field 2 pairs only) is written instead.
255pub fn insert_mpeg2_user_data(stream: &[u8], per_picture: &[Vec<CcTriplet>], dvd: bool) -> Vec<u8> {
256 let segs = nals(stream);
257 let mut out = Vec::with_capacity(stream.len() + per_picture.len() * 24);
258 let mut pic = 0usize;
259 let mut pending: Option<usize> = None;
260 for (k, &(s, e)) in segs.iter().enumerate() {
261 out.extend_from_slice(&stream[s..e]);
262 let code = stream[s + 3];
263 let is_ext = code == 0xB5 && stream.get(s + 4).is_some_and(|b| b >> 4 == 8);
264 if code == 0x00 {
265 pending = Some(pic);
266 pic += 1;
267 }
268 let next_is_ext = segs.get(k + 1).is_some_and(|&(s2, _)| {
269 stream[s2 + 3] == 0xB5 && stream.get(s2 + 4).is_some_and(|b| b >> 4 == 8)
270 });
271 if let Some(p) = pending
272 && (is_ext || (code == 0x00 && !next_is_ext))
273 {
274 {
275 pending = None;
276 if let Some(t) = per_picture.get(p).filter(|t| !t.is_empty()) {
277 out.extend_from_slice(&[0, 0, 1, 0xB2]);
278 if dvd {
279 let n = t.len().min(31) as u8;
280 out.extend_from_slice(&[b'C', b'C', 0x01, 0xF8, 0xC0 | (n << 1)]);
281 for x in t {
282 out.extend_from_slice(&[
283 if x.cc_type == 0 { 0xFF } else { 0xFE },
284 x.data[0],
285 x.data[1],
286 ]);
287 }
288 } else {
289 out.extend_from_slice(b"GA94\x03");
290 out.extend(cc_data_bytes(t));
291 }
292 }
293 }
294 }
295 }
296 out
297}