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