]> git.nihav.org Git - nihav.git/blame - nihav-duck/src/codecs/truemotion2x.rs
aac: fix intensity and mid/side stereo reconstruction
[nihav.git] / nihav-duck / src / codecs / truemotion2x.rs
CommitLineData
2994c841
KS
1use nihav_core::codecs::*;
2use nihav_core::io::byteio::*;
3
4#[derive(Default)]
5struct Decryptor {
6 key: [u8; 4],
7}
8
9impl Decryptor {
10 fn decrypt(&mut self, buf: &mut [u8]) {
11 let mut pos: u8 = 0;
12 for el in buf.iter_mut() {
13 *el ^= self.key[(pos & 3) as usize];
14 pos = pos.wrapping_add(1);
15 }
16 }
17 fn set_state(&mut self, mut key: u32) {
18 for _ in 0..3 {
19 let bit31 = (key >> 31) & 1;
20 let bit21 = (key >> 21) & 1;
21 let bit01 = (key >> 1) & 1;
22 let nbit0 = !key & 1;
23 key = (key << 1) | (bit31 ^ bit21 ^ bit01 ^ nbit0);
24 }
25 for i in 0..4 {
26 self.key[i] = (key >> (8 * (i ^ 3))) as u8;
27 }
28 }
29}
30
31struct Deltas {
32 tabs: [[i16; 256]; 2],
33 codebook: [[u8; 8]; 256],
34 num_elems: [usize; 256],
35 num_vq: usize,
36 vq_idx: usize,
37 vq_pos: usize,
0cc2044a 38 vq_esc: u8,
2994c841
KS
39}
40
41impl Deltas {
42 fn reset(&mut self, br: &mut ByteReader) -> DecoderResult<()> {
43 let b = br.read_byte()? as usize;
44 self.vq_idx = b;
45 self.vq_pos = 0;
46 Ok(())
47 }
48 fn get_val(&mut self, br: &mut ByteReader) -> DecoderResult<u8> {
49 if self.vq_idx > self.codebook.len() { return Err(DecoderError::ShortData); }
50 let ret = self.codebook[self.vq_idx][self.vq_pos];
51 self.vq_pos += 1;
52 if self.vq_pos == self.num_elems[self.vq_idx] {
53 if br.left() > 0 {
54 self.reset(br)?;
55 } else {
56 self.vq_idx = self.codebook.len() + 1;
57 }
58 }
59 Ok(ret)
60 }
0cc2044a
KS
61 fn remap(val: u16) -> i16 {
62 let hval = (val >> 1) as i16;
63 if (val & 1) == 0 {
64 hval
65 } else {
66 -1 - hval
67 }
68 }
2994c841
KS
69 fn get_int(&mut self, br: &mut ByteReader) -> DecoderResult<i16> {
70 let b = self.get_val(br)?;
0cc2044a 71 if b != self.vq_esc - 1 {
8a7352c0 72 return Ok(Self::remap(u16::from(b)));
0cc2044a
KS
73 }
74 let mut run = 0;
75 let mut val;
8a7352c0 76 let mut pow = u16::from(self.vq_esc);
0cc2044a
KS
77 loop {
78 let b = self.get_val(br)?;
79 run += 1;
80 if b != self.vq_esc - 1 {
8a7352c0 81 val = u16::from(b) * pow;
0cc2044a
KS
82 break;
83 }
8a7352c0 84 pow *= u16::from(self.vq_esc);
0cc2044a
KS
85 }
86
87 for _ in 0..run {
8a7352c0
KS
88 pow /= u16::from(self.vq_esc);
89 let b = u16::from(self.get_val(br)?);
90 val += pow * b;
0cc2044a
KS
91 }
92 Ok(Self::remap(val))
2994c841
KS
93 }
94 fn get_dy(&mut self, br: &mut ByteReader) -> DecoderResult<i16> {
95 let b = self.get_val(br)?;
96 Ok(self.tabs[1][b as usize])
97 }
98 fn get_dc(&mut self, br: &mut ByteReader) -> DecoderResult<i16> {
99 let b = self.get_val(br)?;
100 Ok(self.tabs[0][b as usize])
101 }
102}
103
104impl Default for Deltas {
105 fn default() -> Self {
106 Self {
107 tabs: [[0; 256]; 2],
108 codebook: [[0; 8]; 256],
109 num_elems: [0; 256],
110 num_vq: 0,
111 vq_idx: 0,
112 vq_pos: 0,
0cc2044a 113 vq_esc: 0,
2994c841
KS
114 }
115 }
116}
117
118#[derive(Clone,Copy, Default)]
119struct BlkInfo {
120 btype: u8,
121 mode: u8,
122 mv_x: i16,
123 mv_y: i16,
124}
125
126const NUM_CPARAMS: usize = 25;
127const CPARAM_NONE: u8 = 42;
128const CPARAM_MISSING: u8 = 42 * 2;
0cc2044a 129const CPARAM_MV: u8 = 42 * 3;
2994c841
KS
130
131macro_rules! apply_delta {
132 ($buf:expr, $off:expr, $stride:expr, $hpred: expr, $delta:expr) => {
133 $hpred = $hpred.wrapping_add($delta);
134 $buf[$off] = $buf[$off - $stride].wrapping_add($hpred);
135 };
136}
137macro_rules! copy_line {
138 ($buf:expr, $off:expr, $stride:expr) => {
139 for i in 0..8 {
140 $buf[$off + i] = $buf[$off + i - $stride];
141 }
142 };
143}
144
0cc2044a
KS
145#[derive(Default)]
146struct Frame {
147 ydata: Vec<i16>,
148 udata: Vec<i16>,
149 vdata: Vec<i16>,
150 stride: usize,
151}
152
153impl Frame {
154 fn resize(&mut self, w: usize, h: usize) {
155 self.stride = w;
156 self.ydata.resize(self.stride * (h + 1), 0x80);
157 self.udata.resize(self.stride * (h + 1), 0x80);
158 self.vdata.resize(self.stride * (h + 1), 0x80);
159 }
160}
161
2994c841
KS
162#[derive(Default)]
163struct TM2XDecoder {
2422d969 164 info: NACodecInfoRef,
2994c841
KS
165 width: usize,
166 height: usize,
167 dec_buf: Vec<u8>,
168 version: u8,
0cc2044a 169 is_intra: bool,
2994c841
KS
170 deltas: Deltas,
171 blk_info: Vec<BlkInfo>,
172 tile_size: usize,
173 cparams: [[u8; 8]; NUM_CPARAMS],
0cc2044a
KS
174 cur_frame: Frame,
175 ref_frame: Frame,
2994c841
KS
176}
177
178impl TM2XDecoder {
179 fn new() -> Self { Self::default() }
180 fn output_frame(&mut self, buf: &mut NAVideoBuffer<u8>) {
0cc2044a
KS
181 let mut offs = [ buf.get_offset(0), buf.get_offset(1), buf.get_offset(2) ];
182 let strides = [ buf.get_stride(0), buf.get_stride(1), buf.get_stride(2) ];
1a967e6b 183 let data = buf.get_data_mut().unwrap();
2994c841
KS
184 let dst = data.as_mut_slice();
185
0cc2044a 186 let mut pos = self.cur_frame.stride;
2994c841 187 for _y in 0..self.height {
0cc2044a
KS
188 for x in 0..self.width {
189 let y = self.cur_frame.ydata[pos + x];
190 let u = self.cur_frame.udata[pos + x];
191 let v = self.cur_frame.vdata[pos + x];
192 dst[offs[0] + x] = y.max(0).min(255) as u8;
193 dst[offs[1] + x] = u.max(0).min(255) as u8;
194 dst[offs[2] + x] = v.max(0).min(255) as u8;
195 }
196 for c in 0..3 {
197 offs[c] += strides[c];
2994c841 198 }
0cc2044a 199 pos += self.cur_frame.stride;
2994c841
KS
200 }
201 }
202 fn parse_init(&mut self, version: u8) -> DecoderResult<()> {
203 self.version = version;
204
205 let mut mr = MemoryReader::new_read(&self.dec_buf);
206 let mut br = ByteReader::new(&mut mr);
207 if version > 4 {
208 let _smth = br.read_u32be()?;
209 }
210 let height = br.read_u16be()? as usize;
211 let width = br.read_u16be()? as usize;
212 validate!(width == self.width && height == self.height);
213 if version > 4 {
214 let _smth = br.read_u32be()?;
215 }
216 let _smth = br.read_byte()?;
217 let _nfuncs = br.read_byte()? as usize;
218 let _smth = br.read_u16be()? as usize;
219 let has_mv = br.read_byte()?;
0cc2044a 220 self.is_intra = has_mv == 0;
2994c841
KS
221 if version >= 4 {
222 let _flags = br.read_u16be()?;
223 let id_len = br.read_byte()? as usize;
224 br.read_skip(id_len)?;
225 let _smth1 = br.read_byte()?;
226 let len = br.read_byte()? as usize;
227 br.read_skip(len)?;
228 let _smth = br.read_u32be()?;
229 }
d24468d9 230
2994c841
KS
231 Ok(())
232 }
233 fn parse_tabs(&mut self) -> DecoderResult<()> {
234 let mut mr = MemoryReader::new_read(&self.dec_buf);
235 let mut br = ByteReader::new(&mut mr);
236
237 let idx = br.read_byte()? as usize;
238 validate!(idx < self.deltas.tabs.len());
239 let len = br.read_byte()? as usize;
240 validate!(((len * 2) as i64) == br.left());
241 for i in 0..len {
242 self.deltas.tabs[idx][i] = br.read_u16be()? as i16;
243 }
244
245 Ok(())
246 }
247 fn parse_cb_desc(&mut self, version: u8) -> DecoderResult<()> {
248 let mut mr = MemoryReader::new_read(&self.dec_buf);
249 let mut br = ByteReader::new(&mut mr);
250
251 if version == 0x0A {
0cc2044a
KS
252 self.deltas.vq_esc = br.read_byte()?;
253 validate!(self.deltas.vq_esc > 1);
2994c841
KS
254 let _tag = br.read_u16be()?;
255 }
256 let len = br.read_u16be()? as usize;
257 validate!(len + 3 == (br.left() as usize));
258 let num_entries = br.read_u16be()?;
259 validate!(num_entries == 256);
260 let max_elems = br.read_byte()?;
261 validate!(max_elems > 0 && max_elems <= 8);
262 let mut idx = 0;
263 while br.left() > 0 {
264 validate!(idx < self.deltas.codebook.len());
265 let num_elems = br.read_byte()? as usize;
266 validate!(num_elems <= 8);
267 self.deltas.num_elems[idx] = num_elems;
268 for i in 0..num_elems {
269 self.deltas.codebook[idx][i] = br.read_byte()?;
270 }
271 idx += 1;
272 }
273 validate!(idx == 256);
274 self.deltas.num_vq = idx;
275 Ok(())
276 }
277
47933c6d
KS
278 #[allow(clippy::int_plus_one)]
279 #[allow(clippy::manual_memcpy)]
b7c882c1 280 #[allow(clippy::cognitive_complexity)]
2994c841
KS
281 fn decode_frame(&mut self, src: &[u8]) -> DecoderResult<()> {
282 let mut mr = MemoryReader::new_read(src);
283 let mut br = ByteReader::new(&mut mr);
284
285 self.deltas.reset(&mut br)?;
286 let bw = self.width / 8;
287 let bh = self.height / 8;
288 let ntiles = (bw + self.tile_size - 1) / self.tile_size;
0cc2044a
KS
289 let mut pos = self.cur_frame.stride;
290 let ydata = &mut self.cur_frame.ydata;
291 let udata = &mut self.cur_frame.udata;
292 let vdata = &mut self.cur_frame.vdata;
293 let stride = self.cur_frame.stride;
294 for by in 0..bh {
2994c841
KS
295 for tile in 0..ntiles {
296 let xpos = tile * self.tile_size;
297 let len = self.tile_size.min(bw - xpos);
0cc2044a
KS
298 let mut last_x = 0;
299 let mut last_y = 0;
2994c841
KS
300 for el in self.blk_info.iter_mut().take(len) {
301 let t1 = self.deltas.get_val(&mut br)?;
302 let t2 = self.deltas.get_val(&mut br)?;
2994c841
KS
303 validate!((t1 as usize) < NUM_CPARAMS);
304 validate!(self.cparams[t1 as usize][0] != CPARAM_MISSING);
305 el.btype = t1;
306 el.mode = t2;
307 if t2 > 0 {
308 el.mv_x = self.deltas.get_int(&mut br)?;
309 el.mv_y = self.deltas.get_int(&mut br)?;
0cc2044a
KS
310 last_x = el.mv_x;
311 last_y = el.mv_y;
2994c841 312 } else {
0cc2044a
KS
313 el.mv_x = last_x;
314 el.mv_y = last_y;
2994c841
KS
315 }
316 }
317 for line in 0..8 {
318 let mut ypred = 0i16;
319 let mut upred = 0i16;
320 let mut vpred = 0i16;
321 for x in 0..len {
322 let bx = xpos + x;
323 let op = self.cparams[self.blk_info[x].btype as usize][line];
0cc2044a 324 let cur_off = pos + bx * 8 + line * stride;
2994c841
KS
325 match op {
326 0 => { // y4|y4
327 for i in 0..8 {
328 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 329 apply_delta!(ydata, cur_off + i, stride, ypred, delta);
2994c841 330 }
0cc2044a
KS
331 copy_line!(udata, cur_off, stride);
332 copy_line!(vdata, cur_off, stride);
2994c841
KS
333 upred = 0;
334 vpred = 0;
335 },
336 1 => { // y2|y2
337 for i in 0..8 {
338 if (i & 1) == 0 {
339 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 340 apply_delta!(ydata, cur_off + i, stride, ypred, delta);
2994c841 341 } else {
0cc2044a 342 ydata[cur_off + i] = ydata[cur_off + i - 1];
2994c841
KS
343 }
344 }
0cc2044a
KS
345 copy_line!(udata, cur_off, stride);
346 copy_line!(vdata, cur_off, stride);
2994c841
KS
347 upred = 0;
348 vpred = 0;
349 },
350 2 => { // y1|y1
351 for i in 0..8 {
352 if (i & 3) == 0 {
353 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 354 apply_delta!(ydata, cur_off + i, stride, ypred, delta);
2994c841 355 } else {
0cc2044a 356 ydata[cur_off + i] = ydata[cur_off + i - 1];
2994c841
KS
357 }
358 }
0cc2044a
KS
359 copy_line!(udata, cur_off, stride);
360 copy_line!(vdata, cur_off, stride);
2994c841
KS
361 upred = 0;
362 vpred = 0;
363 },
364 3 => { // y1|0
365 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 366 apply_delta!(ydata, cur_off, stride, ypred, delta);
2994c841 367 for i in 1..8 {
0cc2044a 368 ydata[cur_off + i] = ydata[cur_off];
2994c841 369 }
0cc2044a
KS
370 copy_line!(udata, cur_off, stride);
371 copy_line!(vdata, cur_off, stride);
2994c841
KS
372 upred = 0;
373 vpred = 0;
374 },
375 4 => { // c2y2c2y2|c2y2c2y2
376 for i in (0..8).step_by(2) {
377 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a
KS
378 apply_delta!(udata, cur_off + i + 0, stride, upred, delta);
379 udata[cur_off + i + 1] = udata[cur_off + i];
2994c841 380 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a
KS
381 apply_delta!(vdata, cur_off + i + 0, stride, vpred, delta);
382 vdata[cur_off + i + 1] = vdata[cur_off + i];
2994c841 383 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 384 apply_delta!(ydata, cur_off + i + 0, stride, ypred, delta);
2994c841 385 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 386 apply_delta!(ydata, cur_off + i + 1, stride, ypred, delta);
2994c841
KS
387 }
388 },
389 5 => { // c2y1|c2y1
390 for i in 0..8 {
391 if (i & 3) == 0 {
392 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 393 apply_delta!(udata, cur_off + i, stride, upred, delta);
2994c841 394 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 395 apply_delta!(vdata, cur_off + i, stride, vpred, delta);
2994c841 396 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 397 apply_delta!(ydata, cur_off + i, stride, ypred, delta);
2994c841 398 } else {
0cc2044a
KS
399 udata[cur_off + i] = udata[cur_off + i - 1];
400 vdata[cur_off + i] = vdata[cur_off + i - 1];
401 ydata[cur_off + i] = ydata[cur_off + i - 1];
2994c841
KS
402 }
403 }
404 },
405 6 | 7 => unreachable!(),
406 8 => { // c2y4|c2y4
407 for i in 0..8 {
408 if (i & 3) == 0 {
409 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 410 apply_delta!(udata, cur_off + i, stride, upred, delta);
2994c841 411 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 412 apply_delta!(vdata, cur_off + i, stride, vpred, delta);
2994c841 413 } else {
0cc2044a
KS
414 udata[cur_off + i] = udata[cur_off + i - 1];
415 vdata[cur_off + i] = vdata[cur_off + i - 1];
2994c841
KS
416 }
417 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 418 apply_delta!(ydata, cur_off + i, stride, ypred, delta);
2994c841
KS
419 }
420 },
421 9 => { // c2y2|c2y2
422 for i in 0..8 {
423 if (i & 3) == 0 {
424 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 425 apply_delta!(udata, cur_off + i, stride, upred, delta);
2994c841 426 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 427 apply_delta!(vdata, cur_off + i, stride, vpred, delta);
2994c841 428 } else {
0cc2044a
KS
429 udata[cur_off + i] = udata[cur_off + i - 1];
430 vdata[cur_off + i] = vdata[cur_off + i - 1];
2994c841
KS
431 }
432 if (i & 1) == 0 {
433 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 434 apply_delta!(ydata, cur_off + i, stride, ypred, delta);
2994c841 435 } else {
0cc2044a 436 ydata[cur_off + i] = ydata[cur_off + i - 1];
2994c841
KS
437 }
438 }
439 },
440 10 => { // c2y1|c2y1
441 for i in 0..8 {
442 if (i & 3) == 0 {
443 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 444 apply_delta!(udata, cur_off + i, stride, upred, delta);
2994c841 445 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 446 apply_delta!(vdata, cur_off + i, stride, vpred, delta);
2994c841 447 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 448 apply_delta!(ydata, cur_off + i, stride, ypred, delta);
2994c841 449 } else {
0cc2044a
KS
450 udata[cur_off + i] = udata[cur_off + i - 1];
451 vdata[cur_off + i] = vdata[cur_off + i - 1];
452 ydata[cur_off + i] = ydata[cur_off + i - 1];
2994c841
KS
453 }
454 }
455 },
456 11 => unreachable!(),
457 12 => { // c2y8
458 for i in 0..8 {
459 if i == 0 {
460 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 461 apply_delta!(udata, cur_off + i, stride, upred, delta);
2994c841 462 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 463 apply_delta!(vdata, cur_off + i, stride, vpred, delta);
2994c841 464 } else {
0cc2044a
KS
465 udata[cur_off + i] = udata[cur_off + i - 1];
466 vdata[cur_off + i] = vdata[cur_off + i - 1];
2994c841
KS
467 }
468 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 469 apply_delta!(ydata, cur_off + i, stride, ypred, delta);
2994c841
KS
470 }
471 },
472 13 => { // c2y4
473 for i in 0..8 {
474 if i == 0 {
475 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 476 apply_delta!(udata, cur_off + i, stride, upred, delta);
2994c841 477 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 478 apply_delta!(vdata, cur_off + i, stride, vpred, delta);
2994c841 479 } else {
0cc2044a
KS
480 udata[cur_off + i] = udata[cur_off + i - 1];
481 vdata[cur_off + i] = vdata[cur_off + i - 1];
2994c841
KS
482 }
483 if (i & 1) == 0 {
484 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 485 apply_delta!(ydata, cur_off + i, stride, ypred, delta);
2994c841 486 } else {
0cc2044a 487 ydata[cur_off + i] = ydata[cur_off + i - 1];
2994c841
KS
488 }
489 }
490 },
491 14 => { // c2y2
492 for i in 0..8 {
493 if i == 0 {
494 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 495 apply_delta!(udata, cur_off + i, stride, upred, delta);
2994c841 496 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 497 apply_delta!(vdata, cur_off + i, stride, vpred, delta);
2994c841 498 } else {
0cc2044a
KS
499 udata[cur_off + i] = udata[cur_off + i - 1];
500 vdata[cur_off + i] = vdata[cur_off + i - 1];
2994c841
KS
501 }
502 if (i & 3) == 0 {
503 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 504 apply_delta!(ydata, cur_off + i, stride, ypred, delta);
2994c841 505 } else {
0cc2044a 506 ydata[cur_off + i] = ydata[cur_off + i - 1];
2994c841
KS
507 }
508 }
509 },
510 15 => { // c2y1
511 for i in 0..8 {
512 if i == 0 {
513 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 514 apply_delta!(udata, cur_off + i, stride, upred, delta);
2994c841 515 let delta = self.deltas.get_dc(&mut br)?;
0cc2044a 516 apply_delta!(vdata, cur_off + i, stride, vpred, delta);
2994c841 517 let delta = self.deltas.get_dy(&mut br)?;
0cc2044a 518 apply_delta!(ydata, cur_off + i, stride, ypred, delta);
2994c841 519 } else {
0cc2044a
KS
520 udata[cur_off + i] = udata[cur_off + i - 1];
521 vdata[cur_off + i] = vdata[cur_off + i - 1];
522 ydata[cur_off + i] = ydata[cur_off + i - 1];
2994c841
KS
523 }
524 }
525 },
526 CPARAM_NONE => {
0cc2044a
KS
527 copy_line!(ydata, cur_off, stride);
528 copy_line!(udata, cur_off, stride);
529 copy_line!(vdata, cur_off, stride);
2994c841
KS
530 ypred = 0;
531 upred = 0;
532 vpred = 0;
533 },
0cc2044a
KS
534 CPARAM_MV => {
535 let src_x = (bx as i16) * 8 + self.blk_info[x].mv_x;
536 let src_y = ((by * 8 + line) as i16) + self.blk_info[x].mv_y;
537 validate!(src_x >= 0 && (src_x as usize) + 8 <= self.width);
538 validate!(src_y >= 0 && (src_y as usize) + 1 <= self.height);
539 let ref_off = (src_x as usize) + ((src_y + 1) as usize) * stride;
540 for i in 0..8 {
541 ydata[cur_off + i] = self.ref_frame.ydata[ref_off + i];
542 udata[cur_off + i] = self.ref_frame.udata[ref_off + i];
543 vdata[cur_off + i] = self.ref_frame.vdata[ref_off + i];
544 }
545 ypred = ydata[cur_off + 7] - ydata[cur_off + 7 - stride];
546 upred = udata[cur_off + 7] - udata[cur_off + 7 - stride];
547 vpred = vdata[cur_off + 7] - vdata[cur_off + 7 - stride];
548 },
2994c841
KS
549 _ => unreachable!(),
550 }
551 }
552 }
553 }
0cc2044a 554 pos += 8 * stride;
2994c841
KS
555 }
556
557 Ok(())
558 }
559}
560
561impl NADecoder for TM2XDecoder {
01613464 562 fn init(&mut self, _supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()> {
2994c841 563 if let NACodecTypeInfo::Video(vinfo) = info.get_properties() {
0cc2044a
KS
564 let fmt = NAPixelFormaton::new(ColorModel::YUV(YUVSubmodel::YUVJ),
565 Some(NAPixelChromaton::new(0, 0, false, 8, 0, 0, 1)),
566 Some(NAPixelChromaton::new(0, 0, false, 8, 0, 1, 1)),
567 Some(NAPixelChromaton::new(0, 0, false, 8, 0, 2, 1)),
568 None, None, 0, 3);
569 let myinfo = NACodecTypeInfo::Video(NAVideoInfo::new(vinfo.get_width(), vinfo.get_height(), false, fmt));
2994c841
KS
570 self.width = vinfo.get_width();
571 self.height = vinfo.get_height();
0cc2044a
KS
572 self.cur_frame.resize(self.width, self.height);
573 self.ref_frame.resize(self.width, self.height);
2422d969 574 self.info = NACodecInfo::new_ref(info.get_name(), myinfo, info.get_extradata()).into_ref();
2994c841
KS
575 Ok(())
576 } else {
577 Err(DecoderError::InvalidData)
578 }
579 }
01613464 580 fn decode(&mut self, _supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef> {
2994c841
KS
581 let src = pkt.get_buffer();
582 validate!(src.len() > 8);
583 let mut mr = MemoryReader::new_read(&src);
584 let mut br = ByteReader::new(&mut mr);
585 let mut dec = Decryptor::default();
586
587 let mut initialised = false;
588 let mut got_key = false;
589 let mut data_size = 0;
590 self.cparams = [[CPARAM_MISSING; 8]; NUM_CPARAMS];
0cc2044a 591 self.is_intra = false;
2994c841
KS
592 while br.left() >= 8 {
593 let magic = br.read_u24be()?;
594 let ctype = br.read_byte()?;
595 let size = br.read_u32be()? as usize;
596 validate!(magic == 0xA00001 && br.left() >= (size as i64));
597 if ctype == 0x06 {
598 validate!(size >= 4);
599 let key = br.read_u32be()?;
600 validate!((key as usize) == size - 4);
601 dec.set_state(key);
602 data_size = size - 4;
603 br.read_skip(size - 4)?;
604 got_key = true;
605 continue;
606 }
607 self.dec_buf.resize(size, 0);
608 br.read_buf(&mut self.dec_buf)?;
609 if ctype != 0x0A {
610 dec.decrypt(&mut self.dec_buf);
611 }
612 match ctype {
613 0x08 | 0x0C | 0x10 | 0x11 | 0x15 | 0x16 => {
614 if ctype < 0x15 { // old versions are not encrypted, roll back and zero key
615 dec.decrypt(&mut self.dec_buf);
616 dec.set_state(0);
617 got_key = true;
618 }
619 validate!(got_key && !initialised);
620 match ctype {
621 0x08 => self.parse_init(0)?,
622 0x0C => self.parse_init(1)?,
623 0x10 => self.parse_init(2)?,
624 0x11 => self.parse_init(3)?,
625 0x15 => self.parse_init(4)?,
626 0x16 => self.parse_init(5)?,
627 _ => unreachable!(),
628 };
629 initialised = true;
630 },
631 0x09 => {
632 validate!(initialised);
633 validate!(self.dec_buf.len() == 3);
634 validate!(self.dec_buf[0] == 8);
635 validate!(self.dec_buf[1] > 0);
636 validate!(self.dec_buf[2] == 1);
637 self.tile_size = self.dec_buf[1] as usize;
638 self.blk_info.resize(self.tile_size, BlkInfo::default());
639 },
640 0x0B => {
641 validate!(initialised);
642 validate!(self.dec_buf.len() == 4);
643 let idx = self.dec_buf[3] as usize;
644 validate!(idx < NUM_CPARAMS);
2994c841 645 validate!((self.dec_buf[0] as usize) < TM2X_CODING_PARAMS.len());
0cc2044a
KS
646 if self.dec_buf[0] != 0 {
647 let tab = &TM2X_CODING_PARAMS[self.dec_buf[0] as usize];
648 let m0 = tab[0] as usize;
649 let m1 = tab[1] as usize;
650 let m2 = tab[2] as usize;
651 let m3 = tab[3] as usize;
652 let full_mode = (m2 * 4 + m0) as u8;
653 let lores_mode = m0 as u8;
654 for i in 0..8 {
655 if (i % m1) == 0 && (i % m3) == 0 {
656 self.cparams[idx][i] = full_mode;
657 } else if (i % m1) == 0 {
658 self.cparams[idx][i] = lores_mode;
659 } else {
660 self.cparams[idx][i] = CPARAM_NONE;
661 }
2994c841 662 }
0cc2044a
KS
663 } else {
664 for i in 0..8 { self.cparams[idx][i] = CPARAM_MV; }
2994c841
KS
665 }
666 },
667 0x02 => {
668 validate!(initialised);
669 self.parse_tabs()?;
670 },
671 0x0A => {
672 validate!(initialised);
673 self.parse_cb_desc(0xA)?;
674 },
675 _ => { unimplemented!(); },
676 };
677 }
0cc2044a
KS
678 if !self.is_intra {
679 std::mem::swap(&mut self.cur_frame, &mut self.ref_frame);
680 }
2994c841
KS
681 self.decode_frame(&src[12..][..data_size])?;
682
0cc2044a 683 let myinfo = self.info.get_properties().get_video_info().unwrap();
8a7352c0 684 let bufinfo = alloc_video_buffer(myinfo, 2)?;
2994c841
KS
685 let mut buf = bufinfo.get_vbuf().unwrap();
686
2994c841
KS
687 self.output_frame(&mut buf);
688
689 let mut frm = NAFrame::new_from_pkt(pkt, self.info.clone(), bufinfo);
0cc2044a
KS
690 frm.set_keyframe(self.is_intra);
691 frm.set_frame_type(if self.is_intra { FrameType::I } else { FrameType::P });
171860fc 692 Ok(frm.into_ref())
2994c841 693 }
f9be4e75
KS
694 fn flush(&mut self) {
695 }
2994c841
KS
696}
697
7d57ae2f
KS
698impl NAOptionHandler for TM2XDecoder {
699 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
700 fn set_options(&mut self, _options: &[NAOption]) { }
701 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
702}
703
08a1fab7 704pub fn get_decoder() -> Box<dyn NADecoder + Send> {
2994c841
KS
705 Box::new(TM2XDecoder::new())
706}
707
708#[cfg(test)]
709mod test {
710 use nihav_core::codecs::RegisteredDecoders;
711 use nihav_core::demuxers::RegisteredDemuxers;
ce742854 712 use nihav_codec_support::test::dec_video::*;
78fb6560 713 use crate::duck_register_all_decoders;
e64739f8 714 use nihav_commonfmt::generic_register_all_demuxers;
2994c841
KS
715 #[test]
716 fn test_tm2x() {
717 let mut dmx_reg = RegisteredDemuxers::new();
718 generic_register_all_demuxers(&mut dmx_reg);
719 let mut dec_reg = RegisteredDecoders::new();
78fb6560 720 duck_register_all_decoders(&mut dec_reg);
2994c841 721
886cde48 722 // sample: https://samples.mplayerhq.hu/V-codecs/TM2x.avi
e12643e6
KS
723 test_decoding("avi", "truemotion2x", "assets/Duck/TM2x.avi", None,
724 &dmx_reg, &dec_reg, ExpectedTestResult::MD5Frames(vec![
725 [0x2854e7f3, 0x41e54fd3, 0xd9a16302, 0x580321b2],
726 [0x8e736f59, 0x57c58dc0, 0xe15bad3a, 0xf96e2c5b],
727 [0x12700e7c, 0xfa2d06e0, 0x05b758ba, 0xe79aabb6],
728 [0x29f935f2, 0x2ad0d6d1, 0x2fde19a2, 0x5aa3823b],
729 [0x7f1a787d, 0x77f3ab61, 0x0e584c66, 0x9d1842ea],
730 [0xb5607334, 0xdb149056, 0xe0e3ddb5, 0x19f8e254],
731 [0xb054e4d0, 0x1d241d4f, 0x75fdfe95, 0x9dde8024]]));
2994c841
KS
732 }
733}
734
735const TM2X_CODING_PARAMS: [[u8; 4]; 25] = [
736 [ 0, 0, 0, 0 ], [ 0, 1, 1, 1 ], [ 0, 1, 1, 2 ], [ 0, 1, 2, 4 ], [ 1, 1, 2, 4 ],
737 [ 0, 2, 2, 4 ], [ 1, 2, 2, 4 ], [ 2, 2, 2, 4 ], [ 1, 4, 2, 4 ], [ 2, 4, 2, 4 ],
738 [ 2, 8, 3, 8 ], [ 3, 4, 3, 8 ], [ 3, 8, 3, 8 ], [ 0, 1, 1, 4 ], [ 0, 1, 2, 2 ],
739 [ 0, 2, 1, 4 ], [ 1, 1, 2, 2 ], [ 1, 4, 2, 8 ], [ 2, 2, 3, 4 ], [ 2, 4, 3, 8 ],
740 [ 0, 1, 3, 8 ], [ 1, 2, 3, 8 ], [ 2, 4, 2, 4 ], [ 2, 4, 3, 8 ], [ 3, 8, 3, 8 ]
741];