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