]> git.sesse.net Git - ffmpeg/blob - libavcodec/truemotion2.c
Hap decoder and encoder
[ffmpeg] / libavcodec / truemotion2.c
1 /*
2  * Duck/ON2 TrueMotion 2 Decoder
3  * Copyright (c) 2005 Konstantin Shishkov
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * Duck TrueMotion2 decoder.
25  */
26
27 #include <inttypes.h>
28
29 #include "avcodec.h"
30 #include "bswapdsp.h"
31 #include "bytestream.h"
32 #include "get_bits.h"
33 #include "internal.h"
34
35 #define TM2_ESCAPE 0x80000000
36 #define TM2_DELTAS 64
37
38 /* Huffman-coded streams of different types of blocks */
39 enum TM2_STREAMS {
40     TM2_C_HI = 0,
41     TM2_C_LO,
42     TM2_L_HI,
43     TM2_L_LO,
44     TM2_UPD,
45     TM2_MOT,
46     TM2_TYPE,
47     TM2_NUM_STREAMS
48 };
49
50 /* Block types */
51 enum TM2_BLOCKS {
52     TM2_HI_RES = 0,
53     TM2_MED_RES,
54     TM2_LOW_RES,
55     TM2_NULL_RES,
56     TM2_UPDATE,
57     TM2_STILL,
58     TM2_MOTION
59 };
60
61 typedef struct TM2Context {
62     AVCodecContext *avctx;
63     AVFrame *pic;
64
65     GetBitContext gb;
66     BswapDSPContext bdsp;
67
68     /* TM2 streams */
69     int *tokens[TM2_NUM_STREAMS];
70     int tok_lens[TM2_NUM_STREAMS];
71     int tok_ptrs[TM2_NUM_STREAMS];
72     int deltas[TM2_NUM_STREAMS][TM2_DELTAS];
73     /* for blocks decoding */
74     int D[4];
75     int CD[4];
76     int *last;
77     int *clast;
78
79     /* data for current and previous frame */
80     int *Y1_base, *U1_base, *V1_base, *Y2_base, *U2_base, *V2_base;
81     int *Y1, *U1, *V1, *Y2, *U2, *V2;
82     int y_stride, uv_stride;
83     int cur;
84 } TM2Context;
85
86 /**
87 * Huffman codes for each of streams
88 */
89 typedef struct TM2Codes {
90     VLC vlc; ///< table for Libav bitstream reader
91     int bits;
92     int *recode; ///< table for converting from code indexes to values
93     int length;
94 } TM2Codes;
95
96 /**
97 * structure for gathering Huffman codes information
98 */
99 typedef struct TM2Huff {
100     int val_bits; ///< length of literal
101     int max_bits; ///< maximum length of code
102     int min_bits; ///< minimum length of code
103     int nodes; ///< total number of nodes in tree
104     int num; ///< current number filled
105     int max_num; ///< total number of codes
106     int *nums; ///< literals
107     uint32_t *bits; ///< codes
108     int *lens; ///< codelengths
109 } TM2Huff;
110
111 static int tm2_read_tree(TM2Context *ctx, uint32_t prefix, int length, TM2Huff *huff)
112 {
113     int ret;
114     if (length > huff->max_bits) {
115         av_log(ctx->avctx, AV_LOG_ERROR, "Tree exceeded its given depth (%i)\n",
116                huff->max_bits);
117         return AVERROR_INVALIDDATA;
118     }
119
120     if (!get_bits1(&ctx->gb)) { /* literal */
121         if (length == 0) {
122             length = 1;
123         }
124         if (huff->num >= huff->max_num) {
125             av_log(ctx->avctx, AV_LOG_DEBUG, "Too many literals\n");
126             return AVERROR_INVALIDDATA;
127         }
128         huff->nums[huff->num] = get_bits_long(&ctx->gb, huff->val_bits);
129         huff->bits[huff->num] = prefix;
130         huff->lens[huff->num] = length;
131         huff->num++;
132         return 0;
133     } else { /* non-terminal node */
134         if ((ret = tm2_read_tree(ctx, prefix << 1, length + 1, huff)) < 0)
135             return ret;
136         if ((ret = tm2_read_tree(ctx, (prefix << 1) | 1, length + 1, huff)) < 0)
137             return ret;
138     }
139     return 0;
140 }
141
142 static int tm2_build_huff_table(TM2Context *ctx, TM2Codes *code)
143 {
144     TM2Huff huff;
145     int res = 0;
146
147     huff.val_bits = get_bits(&ctx->gb, 5);
148     huff.max_bits = get_bits(&ctx->gb, 5);
149     huff.min_bits = get_bits(&ctx->gb, 5);
150     huff.nodes    = get_bits_long(&ctx->gb, 17);
151     huff.num      = 0;
152
153     /* check for correct codes parameters */
154     if ((huff.val_bits < 1) || (huff.val_bits > 32) ||
155         (huff.max_bits < 0) || (huff.max_bits > 25)) {
156         av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect tree parameters - literal "
157                "length: %i, max code length: %i\n", huff.val_bits, huff.max_bits);
158         return AVERROR_INVALIDDATA;
159     }
160     if ((huff.nodes <= 0) || (huff.nodes > 0x10000)) {
161         av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect number of Huffman tree "
162                "nodes: %i\n", huff.nodes);
163         return AVERROR_INVALIDDATA;
164     }
165     /* one-node tree */
166     if (huff.max_bits == 0)
167         huff.max_bits = 1;
168
169     /* allocate space for codes - it is exactly ceil(nodes / 2) entries */
170     huff.max_num = (huff.nodes + 1) >> 1;
171     huff.nums    = av_mallocz(huff.max_num * sizeof(int));
172     huff.bits    = av_mallocz(huff.max_num * sizeof(uint32_t));
173     huff.lens    = av_mallocz(huff.max_num * sizeof(int));
174     if (!huff.nums || !huff.bits || !huff.lens) {
175         res = AVERROR(ENOMEM);
176         goto out;
177     }
178
179     res = tm2_read_tree(ctx, 0, 0, &huff);
180
181     if (huff.num != huff.max_num) {
182         av_log(ctx->avctx, AV_LOG_ERROR, "Got less codes than expected: %i of %i\n",
183                huff.num, huff.max_num);
184         res = AVERROR_INVALIDDATA;
185     }
186
187     /* convert codes to vlc_table */
188     if (res >= 0) {
189         int i;
190
191         res = init_vlc(&code->vlc, huff.max_bits, huff.max_num,
192                        huff.lens, sizeof(int), sizeof(int),
193                        huff.bits, sizeof(uint32_t), sizeof(uint32_t), 0);
194         if (res < 0)
195             av_log(ctx->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
196         else {
197             code->bits = huff.max_bits;
198             code->length = huff.max_num;
199             code->recode = av_malloc(code->length * sizeof(int));
200             if (!code->recode) {
201                 res = AVERROR(ENOMEM);
202                 goto out;
203             }
204             for (i = 0; i < code->length; i++)
205                 code->recode[i] = huff.nums[i];
206         }
207     }
208
209 out:
210     /* free allocated memory */
211     av_free(huff.nums);
212     av_free(huff.bits);
213     av_free(huff.lens);
214
215     return res;
216 }
217
218 static void tm2_free_codes(TM2Codes *code)
219 {
220     av_free(code->recode);
221     if (code->vlc.table)
222         ff_free_vlc(&code->vlc);
223 }
224
225 static inline int tm2_get_token(GetBitContext *gb, TM2Codes *code)
226 {
227     int val;
228     val = get_vlc2(gb, code->vlc.table, code->bits, 1);
229     return code->recode[val];
230 }
231
232 #define TM2_OLD_HEADER_MAGIC 0x00000100
233 #define TM2_NEW_HEADER_MAGIC 0x00000101
234
235 static inline int tm2_read_header(TM2Context *ctx, const uint8_t *buf)
236 {
237     uint32_t magic = AV_RL32(buf);
238
239     switch (magic) {
240     case TM2_OLD_HEADER_MAGIC:
241         avpriv_request_sample(ctx->avctx, "Old TM2 header");
242         return 0;
243     case TM2_NEW_HEADER_MAGIC:
244         return 0;
245     default:
246         av_log(ctx->avctx, AV_LOG_ERROR, "Not a TM2 header: 0x%08"PRIX32"\n",
247                magic);
248         return AVERROR_INVALIDDATA;
249     }
250 }
251
252 static int tm2_read_deltas(TM2Context *ctx, int stream_id)
253 {
254     int d, mb;
255     int i, v;
256
257     d  = get_bits(&ctx->gb, 9);
258     mb = get_bits(&ctx->gb, 5);
259
260     if ((d < 1) || (d > TM2_DELTAS) || (mb < 1) || (mb > 32)) {
261         av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect delta table: %i deltas x %i bits\n", d, mb);
262         return AVERROR_INVALIDDATA;
263     }
264
265     for (i = 0; i < d; i++) {
266         v = get_bits_long(&ctx->gb, mb);
267         if (v & (1 << (mb - 1)))
268             ctx->deltas[stream_id][i] = v - (1 << mb);
269         else
270             ctx->deltas[stream_id][i] = v;
271     }
272     for (; i < TM2_DELTAS; i++)
273         ctx->deltas[stream_id][i] = 0;
274
275     return 0;
276 }
277
278 static int tm2_read_stream(TM2Context *ctx, const uint8_t *buf, int stream_id, int buf_size)
279 {
280     int i, ret;
281     int skip = 0;
282     int len, toks, pos;
283     TM2Codes codes;
284     GetByteContext gb;
285
286     /* get stream length in dwords */
287     bytestream2_init(&gb, buf, buf_size);
288     len  = bytestream2_get_be32(&gb);
289     skip = len * 4 + 4;
290
291     if (len == 0)
292         return 4;
293
294     if (len >= INT_MAX/4-1 || len < 0 || len > buf_size) {
295         av_log(ctx->avctx, AV_LOG_ERROR, "Error, invalid stream size.\n");
296         return AVERROR_INVALIDDATA;
297     }
298
299     toks = bytestream2_get_be32(&gb);
300     if (toks & 1) {
301         len = bytestream2_get_be32(&gb);
302         if (len == TM2_ESCAPE) {
303             len = bytestream2_get_be32(&gb);
304         }
305         if (len > 0) {
306             pos = bytestream2_tell(&gb);
307             if (skip <= pos)
308                 return AVERROR_INVALIDDATA;
309             init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8);
310             if ((ret = tm2_read_deltas(ctx, stream_id)) < 0)
311                 return ret;
312             bytestream2_skip(&gb, ((get_bits_count(&ctx->gb) + 31) >> 5) << 2);
313         }
314     }
315     /* skip unused fields */
316     len = bytestream2_get_be32(&gb);
317     if (len == TM2_ESCAPE) { /* some unknown length - could be escaped too */
318         bytestream2_skip(&gb, 8); /* unused by decoder */
319     } else {
320         bytestream2_skip(&gb, 4); /* unused by decoder */
321     }
322
323     pos = bytestream2_tell(&gb);
324     if (skip <= pos)
325         return AVERROR_INVALIDDATA;
326     init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8);
327     if ((ret = tm2_build_huff_table(ctx, &codes)) < 0)
328         return ret;
329     bytestream2_skip(&gb, ((get_bits_count(&ctx->gb) + 31) >> 5) << 2);
330
331     toks >>= 1;
332     /* check if we have sane number of tokens */
333     if ((toks < 0) || (toks > 0xFFFFFF)) {
334         av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect number of tokens: %i\n", toks);
335         tm2_free_codes(&codes);
336         return AVERROR_INVALIDDATA;
337     }
338     ctx->tokens[stream_id]   = av_realloc(ctx->tokens[stream_id], toks * sizeof(int));
339     ctx->tok_lens[stream_id] = toks;
340     len = bytestream2_get_be32(&gb);
341     if (len > 0) {
342         pos = bytestream2_tell(&gb);
343         if (skip <= pos)
344             return AVERROR_INVALIDDATA;
345         init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8);
346         for (i = 0; i < toks; i++) {
347             if (get_bits_left(&ctx->gb) <= 0) {
348                 av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect number of tokens: %i\n", toks);
349                 return AVERROR_INVALIDDATA;
350             }
351             ctx->tokens[stream_id][i] = tm2_get_token(&ctx->gb, &codes);
352             if (stream_id <= TM2_MOT && ctx->tokens[stream_id][i] >= TM2_DELTAS) {
353                 av_log(ctx->avctx, AV_LOG_ERROR, "Invalid delta token index %d for type %d, n=%d\n",
354                        ctx->tokens[stream_id][i], stream_id, i);
355                 return AVERROR_INVALIDDATA;
356             }
357         }
358     } else {
359         for (i = 0; i < toks; i++) {
360             ctx->tokens[stream_id][i] = codes.recode[0];
361             if (stream_id <= TM2_MOT && ctx->tokens[stream_id][i] >= TM2_DELTAS) {
362                 av_log(ctx->avctx, AV_LOG_ERROR, "Invalid delta token index %d for type %d, n=%d\n",
363                        ctx->tokens[stream_id][i], stream_id, i);
364                 return AVERROR_INVALIDDATA;
365             }
366         }
367     }
368     tm2_free_codes(&codes);
369
370     return skip;
371 }
372
373 static inline int GET_TOK(TM2Context *ctx,int type)
374 {
375     if (ctx->tok_ptrs[type] >= ctx->tok_lens[type]) {
376         av_log(ctx->avctx, AV_LOG_ERROR, "Read token from stream %i out of bounds (%i>=%i)\n", type, ctx->tok_ptrs[type], ctx->tok_lens[type]);
377         return 0;
378     }
379     if (type <= TM2_MOT)
380         return ctx->deltas[type][ctx->tokens[type][ctx->tok_ptrs[type]++]];
381     return ctx->tokens[type][ctx->tok_ptrs[type]++];
382 }
383
384 /* blocks decoding routines */
385
386 /* common Y, U, V pointers initialisation */
387 #define TM2_INIT_POINTERS() \
388     int *last, *clast; \
389     int *Y, *U, *V;\
390     int Ystride, Ustride, Vstride;\
391 \
392     Ystride = ctx->y_stride;\
393     Vstride = ctx->uv_stride;\
394     Ustride = ctx->uv_stride;\
395     Y = (ctx->cur?ctx->Y2:ctx->Y1) + by * 4 * Ystride + bx * 4;\
396     V = (ctx->cur?ctx->V2:ctx->V1) + by * 2 * Vstride + bx * 2;\
397     U = (ctx->cur?ctx->U2:ctx->U1) + by * 2 * Ustride + bx * 2;\
398     last = ctx->last + bx * 4;\
399     clast = ctx->clast + bx * 4;
400
401 #define TM2_INIT_POINTERS_2() \
402     int *Yo, *Uo, *Vo;\
403     int oYstride, oUstride, oVstride;\
404 \
405     TM2_INIT_POINTERS();\
406     oYstride = Ystride;\
407     oVstride = Vstride;\
408     oUstride = Ustride;\
409     Yo = (ctx->cur?ctx->Y1:ctx->Y2) + by * 4 * oYstride + bx * 4;\
410     Vo = (ctx->cur?ctx->V1:ctx->V2) + by * 2 * oVstride + bx * 2;\
411     Uo = (ctx->cur?ctx->U1:ctx->U2) + by * 2 * oUstride + bx * 2;
412
413 /* recalculate last and delta values for next blocks */
414 #define TM2_RECALC_BLOCK(CHR, stride, last, CD) {\
415     CD[0] = CHR[1] - last[1];\
416     CD[1] = (int)CHR[stride + 1] - (int)CHR[1];\
417     last[0] = (int)CHR[stride + 0];\
418     last[1] = (int)CHR[stride + 1];}
419
420 /* common operations - add deltas to 4x4 block of luma or 2x2 blocks of chroma */
421 static inline void tm2_apply_deltas(TM2Context *ctx, int* Y, int stride, int *deltas, int *last)
422 {
423     int ct, d;
424     int i, j;
425
426     for (j = 0; j < 4; j++){
427         ct = ctx->D[j];
428         for (i = 0; i < 4; i++){
429             d        = deltas[i + j * 4];
430             ct      += d;
431             last[i] += ct;
432             Y[i]     = av_clip_uint8(last[i]);
433         }
434         Y        += stride;
435         ctx->D[j] = ct;
436     }
437 }
438
439 static inline void tm2_high_chroma(int *data, int stride, int *last, int *CD, int *deltas)
440 {
441     int i, j;
442     for (j = 0; j < 2; j++) {
443         for (i = 0; i < 2; i++)  {
444             CD[j]   += deltas[i + j * 2];
445             last[i] += CD[j];
446             data[i]  = last[i];
447         }
448         data += stride;
449     }
450 }
451
452 static inline void tm2_low_chroma(int *data, int stride, int *clast, int *CD, int *deltas, int bx)
453 {
454     int t;
455     int l;
456     int prev;
457
458     if (bx > 0)
459         prev = clast[-3];
460     else
461         prev = 0;
462     t        = (CD[0] + CD[1]) >> 1;
463     l        = (prev - CD[0] - CD[1] + clast[1]) >> 1;
464     CD[1]    = CD[0] + CD[1] - t;
465     CD[0]    = t;
466     clast[0] = l;
467
468     tm2_high_chroma(data, stride, clast, CD, deltas);
469 }
470
471 static inline void tm2_hi_res_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
472 {
473     int i;
474     int deltas[16];
475     TM2_INIT_POINTERS();
476
477     /* hi-res chroma */
478     for (i = 0; i < 4; i++) {
479         deltas[i]     = GET_TOK(ctx, TM2_C_HI);
480         deltas[i + 4] = GET_TOK(ctx, TM2_C_HI);
481     }
482     tm2_high_chroma(U, Ustride, clast,     ctx->CD,     deltas);
483     tm2_high_chroma(V, Vstride, clast + 2, ctx->CD + 2, deltas + 4);
484
485     /* hi-res luma */
486     for (i = 0; i < 16; i++)
487         deltas[i] = GET_TOK(ctx, TM2_L_HI);
488
489     tm2_apply_deltas(ctx, Y, Ystride, deltas, last);
490 }
491
492 static inline void tm2_med_res_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
493 {
494     int i;
495     int deltas[16];
496     TM2_INIT_POINTERS();
497
498     /* low-res chroma */
499     deltas[0] = GET_TOK(ctx, TM2_C_LO);
500     deltas[1] = deltas[2] = deltas[3] = 0;
501     tm2_low_chroma(U, Ustride, clast, ctx->CD, deltas, bx);
502
503     deltas[0] = GET_TOK(ctx, TM2_C_LO);
504     deltas[1] = deltas[2] = deltas[3] = 0;
505     tm2_low_chroma(V, Vstride, clast + 2, ctx->CD + 2, deltas, bx);
506
507     /* hi-res luma */
508     for (i = 0; i < 16; i++)
509         deltas[i] = GET_TOK(ctx, TM2_L_HI);
510
511     tm2_apply_deltas(ctx, Y, Ystride, deltas, last);
512 }
513
514 static inline void tm2_low_res_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
515 {
516     int i;
517     int t1, t2;
518     int deltas[16];
519     TM2_INIT_POINTERS();
520
521     /* low-res chroma */
522     deltas[0] = GET_TOK(ctx, TM2_C_LO);
523     deltas[1] = deltas[2] = deltas[3] = 0;
524     tm2_low_chroma(U, Ustride, clast, ctx->CD, deltas, bx);
525
526     deltas[0] = GET_TOK(ctx, TM2_C_LO);
527     deltas[1] = deltas[2] = deltas[3] = 0;
528     tm2_low_chroma(V, Vstride, clast + 2, ctx->CD + 2, deltas, bx);
529
530     /* low-res luma */
531     for (i = 0; i < 16; i++)
532         deltas[i] = 0;
533
534     deltas[ 0] = GET_TOK(ctx, TM2_L_LO);
535     deltas[ 2] = GET_TOK(ctx, TM2_L_LO);
536     deltas[ 8] = GET_TOK(ctx, TM2_L_LO);
537     deltas[10] = GET_TOK(ctx, TM2_L_LO);
538
539     if (bx > 0)
540         last[0] = (last[-1] - ctx->D[0] - ctx->D[1] - ctx->D[2] - ctx->D[3] + last[1]) >> 1;
541     else
542         last[0] = (last[1]  - ctx->D[0] - ctx->D[1] - ctx->D[2] - ctx->D[3])>> 1;
543     last[2] = (last[1] + last[3]) >> 1;
544
545     t1 = ctx->D[0] + ctx->D[1];
546     ctx->D[0] = t1 >> 1;
547     ctx->D[1] = t1 - (t1 >> 1);
548     t2 = ctx->D[2] + ctx->D[3];
549     ctx->D[2] = t2 >> 1;
550     ctx->D[3] = t2 - (t2 >> 1);
551
552     tm2_apply_deltas(ctx, Y, Ystride, deltas, last);
553 }
554
555 static inline void tm2_null_res_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
556 {
557     int i;
558     int ct;
559     int left, right, diff;
560     int deltas[16];
561     TM2_INIT_POINTERS();
562
563     /* null chroma */
564     deltas[0] = deltas[1] = deltas[2] = deltas[3] = 0;
565     tm2_low_chroma(U, Ustride, clast, ctx->CD, deltas, bx);
566
567     deltas[0] = deltas[1] = deltas[2] = deltas[3] = 0;
568     tm2_low_chroma(V, Vstride, clast + 2, ctx->CD + 2, deltas, bx);
569
570     /* null luma */
571     for (i = 0; i < 16; i++)
572         deltas[i] = 0;
573
574     ct = ctx->D[0] + ctx->D[1] + ctx->D[2] + ctx->D[3];
575
576     if (bx > 0)
577         left = last[-1] - ct;
578     else
579         left = 0;
580
581     right   = last[3];
582     diff    = right - left;
583     last[0] = left + (diff >> 2);
584     last[1] = left + (diff >> 1);
585     last[2] = right - (diff >> 2);
586     last[3] = right;
587     {
588         int tp = left;
589
590         ctx->D[0] = (tp + (ct >> 2)) - left;
591         left     += ctx->D[0];
592         ctx->D[1] = (tp + (ct >> 1)) - left;
593         left     += ctx->D[1];
594         ctx->D[2] = ((tp + ct) - (ct >> 2)) - left;
595         left     += ctx->D[2];
596         ctx->D[3] = (tp + ct) - left;
597     }
598     tm2_apply_deltas(ctx, Y, Ystride, deltas, last);
599 }
600
601 static inline void tm2_still_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
602 {
603     int i, j;
604     TM2_INIT_POINTERS_2();
605
606     /* update chroma */
607     for (j = 0; j < 2; j++) {
608         for (i = 0; i < 2; i++){
609             U[i] = Uo[i];
610             V[i] = Vo[i];
611         }
612         U  += Ustride; V += Vstride;
613         Uo += oUstride; Vo += oVstride;
614     }
615     U -= Ustride * 2;
616     V -= Vstride * 2;
617     TM2_RECALC_BLOCK(U, Ustride, clast, ctx->CD);
618     TM2_RECALC_BLOCK(V, Vstride, (clast + 2), (ctx->CD + 2));
619
620     /* update deltas */
621     ctx->D[0] = Yo[3] - last[3];
622     ctx->D[1] = Yo[3 + oYstride] - Yo[3];
623     ctx->D[2] = Yo[3 + oYstride * 2] - Yo[3 + oYstride];
624     ctx->D[3] = Yo[3 + oYstride * 3] - Yo[3 + oYstride * 2];
625
626     for (j = 0; j < 4; j++) {
627         for (i = 0; i < 4; i++) {
628             Y[i]    = Yo[i];
629             last[i] = Yo[i];
630         }
631         Y  += Ystride;
632         Yo += oYstride;
633     }
634 }
635
636 static inline void tm2_update_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
637 {
638     int i, j;
639     int d;
640     TM2_INIT_POINTERS_2();
641
642     /* update chroma */
643     for (j = 0; j < 2; j++) {
644         for (i = 0; i < 2; i++) {
645             U[i] = Uo[i] + GET_TOK(ctx, TM2_UPD);
646             V[i] = Vo[i] + GET_TOK(ctx, TM2_UPD);
647         }
648         U  += Ustride;
649         V  += Vstride;
650         Uo += oUstride;
651         Vo += oVstride;
652     }
653     U -= Ustride * 2;
654     V -= Vstride * 2;
655     TM2_RECALC_BLOCK(U, Ustride, clast, ctx->CD);
656     TM2_RECALC_BLOCK(V, Vstride, (clast + 2), (ctx->CD + 2));
657
658     /* update deltas */
659     ctx->D[0] = Yo[3] - last[3];
660     ctx->D[1] = Yo[3 + oYstride] - Yo[3];
661     ctx->D[2] = Yo[3 + oYstride * 2] - Yo[3 + oYstride];
662     ctx->D[3] = Yo[3 + oYstride * 3] - Yo[3 + oYstride * 2];
663
664     for (j = 0; j < 4; j++) {
665         d = last[3];
666         for (i = 0; i < 4; i++) {
667             Y[i]    = Yo[i] + GET_TOK(ctx, TM2_UPD);
668             last[i] = Y[i];
669         }
670         ctx->D[j] = last[3] - d;
671         Y  += Ystride;
672         Yo += oYstride;
673     }
674 }
675
676 static inline void tm2_motion_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
677 {
678     int i, j;
679     int mx, my;
680     TM2_INIT_POINTERS_2();
681
682     mx = GET_TOK(ctx, TM2_MOT);
683     my = GET_TOK(ctx, TM2_MOT);
684     mx = av_clip(mx, -(bx * 4 + 4), ctx->avctx->width  - bx * 4);
685     my = av_clip(my, -(by * 4 + 4), ctx->avctx->height - by * 4);
686
687     Yo += my * oYstride + mx;
688     Uo += (my >> 1) * oUstride + (mx >> 1);
689     Vo += (my >> 1) * oVstride + (mx >> 1);
690
691     /* copy chroma */
692     for (j = 0; j < 2; j++) {
693         for (i = 0; i < 2; i++) {
694             U[i] = Uo[i];
695             V[i] = Vo[i];
696         }
697         U  += Ustride;
698         V  += Vstride;
699         Uo += oUstride;
700         Vo += oVstride;
701     }
702     U -= Ustride * 2;
703     V -= Vstride * 2;
704     TM2_RECALC_BLOCK(U, Ustride, clast, ctx->CD);
705     TM2_RECALC_BLOCK(V, Vstride, (clast + 2), (ctx->CD + 2));
706
707     /* copy luma */
708     for (j = 0; j < 4; j++) {
709         for (i = 0; i < 4; i++) {
710             Y[i] = Yo[i];
711         }
712         Y  += Ystride;
713         Yo += oYstride;
714     }
715     /* calculate deltas */
716     Y -= Ystride * 4;
717     ctx->D[0] = Y[3] - last[3];
718     ctx->D[1] = Y[3 + Ystride] - Y[3];
719     ctx->D[2] = Y[3 + Ystride * 2] - Y[3 + Ystride];
720     ctx->D[3] = Y[3 + Ystride * 3] - Y[3 + Ystride * 2];
721     for (i = 0; i < 4; i++)
722         last[i] = Y[i + Ystride * 3];
723 }
724
725 static int tm2_decode_blocks(TM2Context *ctx, AVFrame *p)
726 {
727     int i, j;
728     int w = ctx->avctx->width, h = ctx->avctx->height, bw = w >> 2, bh = h >> 2, cw = w >> 1;
729     int type;
730     int keyframe = 1;
731     int *Y, *U, *V;
732     uint8_t *dst;
733
734     for (i = 0; i < TM2_NUM_STREAMS; i++)
735         ctx->tok_ptrs[i] = 0;
736
737     if (ctx->tok_lens[TM2_TYPE]<bw*bh) {
738         av_log(ctx->avctx,AV_LOG_ERROR,"Got %i tokens for %i blocks\n",ctx->tok_lens[TM2_TYPE],bw*bh);
739         return AVERROR_INVALIDDATA;
740     }
741
742     memset(ctx->last, 0, 4 * bw * sizeof(int));
743     memset(ctx->clast, 0, 4 * bw * sizeof(int));
744
745     for (j = 0; j < bh; j++) {
746         memset(ctx->D, 0, 4 * sizeof(int));
747         memset(ctx->CD, 0, 4 * sizeof(int));
748         for (i = 0; i < bw; i++) {
749             type = GET_TOK(ctx, TM2_TYPE);
750             switch(type) {
751             case TM2_HI_RES:
752                 tm2_hi_res_block(ctx, p, i, j);
753                 break;
754             case TM2_MED_RES:
755                 tm2_med_res_block(ctx, p, i, j);
756                 break;
757             case TM2_LOW_RES:
758                 tm2_low_res_block(ctx, p, i, j);
759                 break;
760             case TM2_NULL_RES:
761                 tm2_null_res_block(ctx, p, i, j);
762                 break;
763             case TM2_UPDATE:
764                 tm2_update_block(ctx, p, i, j);
765                 keyframe = 0;
766                 break;
767             case TM2_STILL:
768                 tm2_still_block(ctx, p, i, j);
769                 keyframe = 0;
770                 break;
771             case TM2_MOTION:
772                 tm2_motion_block(ctx, p, i, j);
773                 keyframe = 0;
774                 break;
775             default:
776                 av_log(ctx->avctx, AV_LOG_ERROR, "Skipping unknown block type %i\n", type);
777             }
778         }
779     }
780
781     /* copy data from our buffer to AVFrame */
782     Y = (ctx->cur?ctx->Y2:ctx->Y1);
783     U = (ctx->cur?ctx->U2:ctx->U1);
784     V = (ctx->cur?ctx->V2:ctx->V1);
785     dst = p->data[0];
786     for (j = 0; j < h; j++) {
787         for (i = 0; i < w; i++) {
788             int y = Y[i], u = U[i >> 1], v = V[i >> 1];
789             dst[3*i+0] = av_clip_uint8(y + v);
790             dst[3*i+1] = av_clip_uint8(y);
791             dst[3*i+2] = av_clip_uint8(y + u);
792         }
793
794         /* horizontal edge extension */
795         Y[-4]    = Y[-3]    = Y[-2]    = Y[-1] = Y[0];
796         Y[w + 3] = Y[w + 2] = Y[w + 1] = Y[w]  = Y[w - 1];
797
798         /* vertical edge extension */
799         if (j == 0) {
800             memcpy(Y - 4 - 1 * ctx->y_stride, Y - 4, ctx->y_stride);
801             memcpy(Y - 4 - 2 * ctx->y_stride, Y - 4, ctx->y_stride);
802             memcpy(Y - 4 - 3 * ctx->y_stride, Y - 4, ctx->y_stride);
803             memcpy(Y - 4 - 4 * ctx->y_stride, Y - 4, ctx->y_stride);
804         } else if (j == h - 1) {
805             memcpy(Y - 4 + 1 * ctx->y_stride, Y - 4, ctx->y_stride);
806             memcpy(Y - 4 + 2 * ctx->y_stride, Y - 4, ctx->y_stride);
807             memcpy(Y - 4 + 3 * ctx->y_stride, Y - 4, ctx->y_stride);
808             memcpy(Y - 4 + 4 * ctx->y_stride, Y - 4, ctx->y_stride);
809         }
810
811         Y += ctx->y_stride;
812         if (j & 1) {
813             /* horizontal edge extension */
814             U[-2]     = U[-1] = U[0];
815             V[-2]     = V[-1] = V[0];
816             U[cw + 1] = U[cw] = U[cw - 1];
817             V[cw + 1] = V[cw] = V[cw - 1];
818
819             /* vertical edge extension */
820             if (j == 1) {
821                 memcpy(U - 2 - 1 * ctx->uv_stride, U - 2, ctx->uv_stride);
822                 memcpy(V - 2 - 1 * ctx->uv_stride, V - 2, ctx->uv_stride);
823                 memcpy(U - 2 - 2 * ctx->uv_stride, U - 2, ctx->uv_stride);
824                 memcpy(V - 2 - 2 * ctx->uv_stride, V - 2, ctx->uv_stride);
825             } else if (j == h - 1) {
826                 memcpy(U - 2 + 1 * ctx->uv_stride, U - 2, ctx->uv_stride);
827                 memcpy(V - 2 + 1 * ctx->uv_stride, V - 2, ctx->uv_stride);
828                 memcpy(U - 2 + 2 * ctx->uv_stride, U - 2, ctx->uv_stride);
829                 memcpy(V - 2 + 2 * ctx->uv_stride, V - 2, ctx->uv_stride);
830             }
831
832             U += ctx->uv_stride;
833             V += ctx->uv_stride;
834         }
835         dst += p->linesize[0];
836     }
837
838     return keyframe;
839 }
840
841 static const int tm2_stream_order[TM2_NUM_STREAMS] = {
842     TM2_C_HI, TM2_C_LO, TM2_L_HI, TM2_L_LO, TM2_UPD, TM2_MOT, TM2_TYPE
843 };
844
845 #define TM2_HEADER_SIZE 40
846
847 static int decode_frame(AVCodecContext *avctx,
848                         void *data, int *got_frame,
849                         AVPacket *avpkt)
850 {
851     TM2Context * const l = avctx->priv_data;
852     const uint8_t *buf   = avpkt->data;
853     int buf_size         = avpkt->size & ~3;
854     AVFrame * const p    = l->pic;
855     int offset           = TM2_HEADER_SIZE;
856     int i, t, ret;
857     uint8_t *swbuf;
858
859     swbuf = av_malloc(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
860     if (!swbuf) {
861         av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n");
862         return AVERROR(ENOMEM);
863     }
864
865     if ((ret = ff_reget_buffer(avctx, p)) < 0) {
866         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
867         av_free(swbuf);
868         return ret;
869     }
870
871     l->bdsp.bswap_buf((uint32_t *) swbuf, (const uint32_t *) buf,
872                       buf_size >> 2);
873
874     if ((ret = tm2_read_header(l, swbuf)) < 0) {
875         av_free(swbuf);
876         return ret;
877     }
878
879     for (i = 0; i < TM2_NUM_STREAMS; i++) {
880         if (offset >= buf_size) {
881             av_free(swbuf);
882             return AVERROR_INVALIDDATA;
883         }
884         t = tm2_read_stream(l, swbuf + offset, tm2_stream_order[i],
885                             buf_size - offset);
886         if (t < 0) {
887             av_free(swbuf);
888             return t;
889         }
890         offset += t;
891     }
892     p->key_frame = tm2_decode_blocks(l, p);
893     if (p->key_frame)
894         p->pict_type = AV_PICTURE_TYPE_I;
895     else
896         p->pict_type = AV_PICTURE_TYPE_P;
897
898     l->cur = !l->cur;
899     *got_frame      = 1;
900     ret = av_frame_ref(data, l->pic);
901     av_free(swbuf);
902
903     return (ret < 0) ? ret : buf_size;
904 }
905
906 static av_cold int decode_init(AVCodecContext *avctx)
907 {
908     TM2Context * const l = avctx->priv_data;
909     int i, w = avctx->width, h = avctx->height;
910
911     if ((avctx->width & 3) || (avctx->height & 3)) {
912         av_log(avctx, AV_LOG_ERROR, "Width and height must be multiple of 4\n");
913         return AVERROR(EINVAL);
914     }
915
916     l->avctx       = avctx;
917     avctx->pix_fmt = AV_PIX_FMT_BGR24;
918
919     l->pic = av_frame_alloc();
920     if (!l->pic)
921         return AVERROR(ENOMEM);
922
923     ff_bswapdsp_init(&l->bdsp);
924
925     l->last  = av_malloc(4 * sizeof(*l->last)  * (w >> 2));
926     l->clast = av_malloc(4 * sizeof(*l->clast) * (w >> 2));
927
928     for (i = 0; i < TM2_NUM_STREAMS; i++) {
929         l->tokens[i] = NULL;
930         l->tok_lens[i] = 0;
931     }
932
933     w += 8;
934     h += 8;
935     l->Y1_base = av_malloc(sizeof(*l->Y1_base) * w * h);
936     l->Y2_base = av_malloc(sizeof(*l->Y2_base) * w * h);
937     l->y_stride = w;
938     w = (w + 1) >> 1;
939     h = (h + 1) >> 1;
940     l->U1_base = av_malloc(sizeof(*l->U1_base) * w * h);
941     l->V1_base = av_malloc(sizeof(*l->V1_base) * w * h);
942     l->U2_base = av_malloc(sizeof(*l->U2_base) * w * h);
943     l->V2_base = av_malloc(sizeof(*l->V1_base) * w * h);
944     l->uv_stride = w;
945     l->cur = 0;
946     if (!l->Y1_base || !l->Y2_base || !l->U1_base ||
947         !l->V1_base || !l->U2_base || !l->V2_base ||
948         !l->last    || !l->clast) {
949         av_freep(&l->Y1_base);
950         av_freep(&l->Y2_base);
951         av_freep(&l->U1_base);
952         av_freep(&l->U2_base);
953         av_freep(&l->V1_base);
954         av_freep(&l->V2_base);
955         av_freep(&l->last);
956         av_freep(&l->clast);
957         return AVERROR(ENOMEM);
958     }
959     l->Y1 = l->Y1_base + l->y_stride  * 4 + 4;
960     l->Y2 = l->Y2_base + l->y_stride  * 4 + 4;
961     l->U1 = l->U1_base + l->uv_stride * 2 + 2;
962     l->U2 = l->U2_base + l->uv_stride * 2 + 2;
963     l->V1 = l->V1_base + l->uv_stride * 2 + 2;
964     l->V2 = l->V2_base + l->uv_stride * 2 + 2;
965
966     return 0;
967 }
968
969 static av_cold int decode_end(AVCodecContext *avctx)
970 {
971     TM2Context * const l = avctx->priv_data;
972     int i;
973
974     av_free(l->last);
975     av_free(l->clast);
976     for (i = 0; i < TM2_NUM_STREAMS; i++)
977         av_free(l->tokens[i]);
978     if (l->Y1) {
979         av_free(l->Y1_base);
980         av_free(l->U1_base);
981         av_free(l->V1_base);
982         av_free(l->Y2_base);
983         av_free(l->U2_base);
984         av_free(l->V2_base);
985     }
986
987     av_frame_free(&l->pic);
988
989     return 0;
990 }
991
992 AVCodec ff_truemotion2_decoder = {
993     .name           = "truemotion2",
994     .long_name      = NULL_IF_CONFIG_SMALL("Duck TrueMotion 2.0"),
995     .type           = AVMEDIA_TYPE_VIDEO,
996     .id             = AV_CODEC_ID_TRUEMOTION2,
997     .priv_data_size = sizeof(TM2Context),
998     .init           = decode_init,
999     .close          = decode_end,
1000     .decode         = decode_frame,
1001     .capabilities   = CODEC_CAP_DR1,
1002 };