Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / 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 "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     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     av_assert2(mb < 32);
266     if ((d < 1) || (d > TM2_DELTAS) || (mb < 1)) {
267         av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect delta table: %i deltas x %i bits\n", d, mb);
268         return AVERROR_INVALIDDATA;
269     }
270
271     for (i = 0; i < d; i++) {
272         v = get_bits_long(&ctx->gb, mb);
273         if (v & (1 << (mb - 1)))
274             ctx->deltas[stream_id][i] = v - (1 << mb);
275         else
276             ctx->deltas[stream_id][i] = v;
277     }
278     for (; i < TM2_DELTAS; i++)
279         ctx->deltas[stream_id][i] = 0;
280
281     return 0;
282 }
283
284 static int tm2_read_stream(TM2Context *ctx, const uint8_t *buf, int stream_id, int buf_size)
285 {
286     int i, ret;
287     int skip = 0;
288     int len, toks, pos;
289     TM2Codes codes;
290     GetByteContext gb;
291
292     if (buf_size < 4) {
293         av_log(ctx->avctx, AV_LOG_ERROR, "not enough space for len left\n");
294         return AVERROR_INVALIDDATA;
295     }
296
297     /* get stream length in dwords */
298     bytestream2_init(&gb, buf, buf_size);
299     len  = bytestream2_get_be32(&gb);
300     skip = len * 4 + 4;
301
302     if (len == 0)
303         return 4;
304
305     if (len >= INT_MAX/4-1 || len < 0 || skip > buf_size) {
306         av_log(ctx->avctx, AV_LOG_ERROR, "invalid stream size\n");
307         return AVERROR_INVALIDDATA;
308     }
309
310     toks = bytestream2_get_be32(&gb);
311     if (toks & 1) {
312         len = bytestream2_get_be32(&gb);
313         if (len == TM2_ESCAPE) {
314             len = bytestream2_get_be32(&gb);
315         }
316         if (len > 0) {
317             pos = bytestream2_tell(&gb);
318             if (skip <= pos)
319                 return AVERROR_INVALIDDATA;
320             init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8);
321             if ((ret = tm2_read_deltas(ctx, stream_id)) < 0)
322                 return ret;
323             bytestream2_skip(&gb, ((get_bits_count(&ctx->gb) + 31) >> 5) << 2);
324         }
325     }
326     /* skip unused fields */
327     len = bytestream2_get_be32(&gb);
328     if (len == TM2_ESCAPE) { /* some unknown length - could be escaped too */
329         bytestream2_skip(&gb, 8); /* unused by decoder */
330     } else {
331         bytestream2_skip(&gb, 4); /* unused by decoder */
332     }
333
334     pos = bytestream2_tell(&gb);
335     if (skip <= pos)
336         return AVERROR_INVALIDDATA;
337     init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8);
338     if ((ret = tm2_build_huff_table(ctx, &codes)) < 0)
339         return ret;
340     bytestream2_skip(&gb, ((get_bits_count(&ctx->gb) + 31) >> 5) << 2);
341
342     toks >>= 1;
343     /* check if we have sane number of tokens */
344     if ((toks < 0) || (toks > 0xFFFFFF)) {
345         av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect number of tokens: %i\n", toks);
346         tm2_free_codes(&codes);
347         return AVERROR_INVALIDDATA;
348     }
349     ret = av_reallocp_array(&ctx->tokens[stream_id], toks, sizeof(int));
350     if (ret < 0) {
351         ctx->tok_lens[stream_id] = 0;
352         return ret;
353     }
354     ctx->tok_lens[stream_id] = toks;
355     len = bytestream2_get_be32(&gb);
356     if (len > 0) {
357         pos = bytestream2_tell(&gb);
358         if (skip <= pos)
359             return AVERROR_INVALIDDATA;
360         init_get_bits(&ctx->gb, buf + pos, (skip - pos) * 8);
361         for (i = 0; i < toks; i++) {
362             if (get_bits_left(&ctx->gb) <= 0) {
363                 av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect number of tokens: %i\n", toks);
364                 return AVERROR_INVALIDDATA;
365             }
366             ctx->tokens[stream_id][i] = tm2_get_token(&ctx->gb, &codes);
367             if (stream_id <= TM2_MOT && ctx->tokens[stream_id][i] >= TM2_DELTAS || ctx->tokens[stream_id][i]<0) {
368                 av_log(ctx->avctx, AV_LOG_ERROR, "Invalid delta token index %d for type %d, n=%d\n",
369                        ctx->tokens[stream_id][i], stream_id, i);
370                 return AVERROR_INVALIDDATA;
371             }
372         }
373     } else {
374         for (i = 0; i < toks; i++) {
375             ctx->tokens[stream_id][i] = codes.recode[0];
376             if (stream_id <= TM2_MOT && ctx->tokens[stream_id][i] >= TM2_DELTAS) {
377                 av_log(ctx->avctx, AV_LOG_ERROR, "Invalid delta token index %d for type %d, n=%d\n",
378                        ctx->tokens[stream_id][i], stream_id, i);
379                 return AVERROR_INVALIDDATA;
380             }
381         }
382     }
383     tm2_free_codes(&codes);
384
385     return skip;
386 }
387
388 static inline int GET_TOK(TM2Context *ctx,int type)
389 {
390     if (ctx->tok_ptrs[type] >= ctx->tok_lens[type]) {
391         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]);
392         return 0;
393     }
394     if (type <= TM2_MOT) {
395         if (ctx->tokens[type][ctx->tok_ptrs[type]] >= TM2_DELTAS) {
396             av_log(ctx->avctx, AV_LOG_ERROR, "token %d is too large\n", ctx->tokens[type][ctx->tok_ptrs[type]]);
397             return 0;
398         }
399         return ctx->deltas[type][ctx->tokens[type][ctx->tok_ptrs[type]++]];
400     }
401     return ctx->tokens[type][ctx->tok_ptrs[type]++];
402 }
403
404 /* blocks decoding routines */
405
406 /* common Y, U, V pointers initialisation */
407 #define TM2_INIT_POINTERS() \
408     int *last, *clast; \
409     int *Y, *U, *V;\
410     int Ystride, Ustride, Vstride;\
411 \
412     Ystride = ctx->y_stride;\
413     Vstride = ctx->uv_stride;\
414     Ustride = ctx->uv_stride;\
415     Y = (ctx->cur?ctx->Y2:ctx->Y1) + by * 4 * Ystride + bx * 4;\
416     V = (ctx->cur?ctx->V2:ctx->V1) + by * 2 * Vstride + bx * 2;\
417     U = (ctx->cur?ctx->U2:ctx->U1) + by * 2 * Ustride + bx * 2;\
418     last = ctx->last + bx * 4;\
419     clast = ctx->clast + bx * 4;
420
421 #define TM2_INIT_POINTERS_2() \
422     int *Yo, *Uo, *Vo;\
423     int oYstride, oUstride, oVstride;\
424 \
425     TM2_INIT_POINTERS();\
426     oYstride = Ystride;\
427     oVstride = Vstride;\
428     oUstride = Ustride;\
429     Yo = (ctx->cur?ctx->Y1:ctx->Y2) + by * 4 * oYstride + bx * 4;\
430     Vo = (ctx->cur?ctx->V1:ctx->V2) + by * 2 * oVstride + bx * 2;\
431     Uo = (ctx->cur?ctx->U1:ctx->U2) + by * 2 * oUstride + bx * 2;
432
433 /* recalculate last and delta values for next blocks */
434 #define TM2_RECALC_BLOCK(CHR, stride, last, CD) {\
435     CD[0] = CHR[1] - last[1];\
436     CD[1] = (int)CHR[stride + 1] - (int)CHR[1];\
437     last[0] = (int)CHR[stride + 0];\
438     last[1] = (int)CHR[stride + 1];}
439
440 /* common operations - add deltas to 4x4 block of luma or 2x2 blocks of chroma */
441 static inline void tm2_apply_deltas(TM2Context *ctx, int* Y, int stride, int *deltas, int *last)
442 {
443     int ct, d;
444     int i, j;
445
446     for (j = 0; j < 4; j++){
447         ct = ctx->D[j];
448         for (i = 0; i < 4; i++){
449             d        = deltas[i + j * 4];
450             ct      += d;
451             last[i] += ct;
452             Y[i]     = av_clip_uint8(last[i]);
453         }
454         Y        += stride;
455         ctx->D[j] = ct;
456     }
457 }
458
459 static inline void tm2_high_chroma(int *data, int stride, int *last, int *CD, int *deltas)
460 {
461     int i, j;
462     for (j = 0; j < 2; j++) {
463         for (i = 0; i < 2; i++)  {
464             CD[j]   += deltas[i + j * 2];
465             last[i] += CD[j];
466             data[i]  = last[i];
467         }
468         data += stride;
469     }
470 }
471
472 static inline void tm2_low_chroma(int *data, int stride, int *clast, int *CD, int *deltas, int bx)
473 {
474     int t;
475     int l;
476     int prev;
477
478     if (bx > 0)
479         prev = clast[-3];
480     else
481         prev = 0;
482     t        = (CD[0] + CD[1]) >> 1;
483     l        = (prev - CD[0] - CD[1] + clast[1]) >> 1;
484     CD[1]    = CD[0] + CD[1] - t;
485     CD[0]    = t;
486     clast[0] = l;
487
488     tm2_high_chroma(data, stride, clast, CD, deltas);
489 }
490
491 static inline void tm2_hi_res_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
492 {
493     int i;
494     int deltas[16];
495     TM2_INIT_POINTERS();
496
497     /* hi-res chroma */
498     for (i = 0; i < 4; i++) {
499         deltas[i]     = GET_TOK(ctx, TM2_C_HI);
500         deltas[i + 4] = GET_TOK(ctx, TM2_C_HI);
501     }
502     tm2_high_chroma(U, Ustride, clast,     ctx->CD,     deltas);
503     tm2_high_chroma(V, Vstride, clast + 2, ctx->CD + 2, deltas + 4);
504
505     /* hi-res luma */
506     for (i = 0; i < 16; i++)
507         deltas[i] = GET_TOK(ctx, TM2_L_HI);
508
509     tm2_apply_deltas(ctx, Y, Ystride, deltas, last);
510 }
511
512 static inline void tm2_med_res_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
513 {
514     int i;
515     int deltas[16];
516     TM2_INIT_POINTERS();
517
518     /* low-res chroma */
519     deltas[0] = GET_TOK(ctx, TM2_C_LO);
520     deltas[1] = deltas[2] = deltas[3] = 0;
521     tm2_low_chroma(U, Ustride, clast, ctx->CD, deltas, bx);
522
523     deltas[0] = GET_TOK(ctx, TM2_C_LO);
524     deltas[1] = deltas[2] = deltas[3] = 0;
525     tm2_low_chroma(V, Vstride, clast + 2, ctx->CD + 2, deltas, bx);
526
527     /* hi-res luma */
528     for (i = 0; i < 16; i++)
529         deltas[i] = GET_TOK(ctx, TM2_L_HI);
530
531     tm2_apply_deltas(ctx, Y, Ystride, deltas, last);
532 }
533
534 static inline void tm2_low_res_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
535 {
536     int i;
537     int t1, t2;
538     int deltas[16];
539     TM2_INIT_POINTERS();
540
541     /* low-res chroma */
542     deltas[0] = GET_TOK(ctx, TM2_C_LO);
543     deltas[1] = deltas[2] = deltas[3] = 0;
544     tm2_low_chroma(U, Ustride, clast, ctx->CD, deltas, bx);
545
546     deltas[0] = GET_TOK(ctx, TM2_C_LO);
547     deltas[1] = deltas[2] = deltas[3] = 0;
548     tm2_low_chroma(V, Vstride, clast + 2, ctx->CD + 2, deltas, bx);
549
550     /* low-res luma */
551     for (i = 0; i < 16; i++)
552         deltas[i] = 0;
553
554     deltas[ 0] = GET_TOK(ctx, TM2_L_LO);
555     deltas[ 2] = GET_TOK(ctx, TM2_L_LO);
556     deltas[ 8] = GET_TOK(ctx, TM2_L_LO);
557     deltas[10] = GET_TOK(ctx, TM2_L_LO);
558
559     if (bx > 0)
560         last[0] = (last[-1] - ctx->D[0] - ctx->D[1] - ctx->D[2] - ctx->D[3] + last[1]) >> 1;
561     else
562         last[0] = (last[1]  - ctx->D[0] - ctx->D[1] - ctx->D[2] - ctx->D[3])>> 1;
563     last[2] = (last[1] + last[3]) >> 1;
564
565     t1 = ctx->D[0] + ctx->D[1];
566     ctx->D[0] = t1 >> 1;
567     ctx->D[1] = t1 - (t1 >> 1);
568     t2 = ctx->D[2] + ctx->D[3];
569     ctx->D[2] = t2 >> 1;
570     ctx->D[3] = t2 - (t2 >> 1);
571
572     tm2_apply_deltas(ctx, Y, Ystride, deltas, last);
573 }
574
575 static inline void tm2_null_res_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
576 {
577     int i;
578     int ct;
579     int left, right, diff;
580     int deltas[16];
581     TM2_INIT_POINTERS();
582
583     /* null chroma */
584     deltas[0] = deltas[1] = deltas[2] = deltas[3] = 0;
585     tm2_low_chroma(U, Ustride, clast, ctx->CD, deltas, bx);
586
587     deltas[0] = deltas[1] = deltas[2] = deltas[3] = 0;
588     tm2_low_chroma(V, Vstride, clast + 2, ctx->CD + 2, deltas, bx);
589
590     /* null luma */
591     for (i = 0; i < 16; i++)
592         deltas[i] = 0;
593
594     ct = ctx->D[0] + ctx->D[1] + ctx->D[2] + ctx->D[3];
595
596     if (bx > 0)
597         left = last[-1] - ct;
598     else
599         left = 0;
600
601     right   = last[3];
602     diff    = right - left;
603     last[0] = left + (diff >> 2);
604     last[1] = left + (diff >> 1);
605     last[2] = right - (diff >> 2);
606     last[3] = right;
607     {
608         int tp = left;
609
610         ctx->D[0] = (tp + (ct >> 2)) - left;
611         left     += ctx->D[0];
612         ctx->D[1] = (tp + (ct >> 1)) - left;
613         left     += ctx->D[1];
614         ctx->D[2] = ((tp + ct) - (ct >> 2)) - left;
615         left     += ctx->D[2];
616         ctx->D[3] = (tp + ct) - left;
617     }
618     tm2_apply_deltas(ctx, Y, Ystride, deltas, last);
619 }
620
621 static inline void tm2_still_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
622 {
623     int i, j;
624     TM2_INIT_POINTERS_2();
625
626     /* update chroma */
627     for (j = 0; j < 2; j++) {
628         for (i = 0; i < 2; i++){
629             U[i] = Uo[i];
630             V[i] = Vo[i];
631         }
632         U  += Ustride; V += Vstride;
633         Uo += oUstride; Vo += oVstride;
634     }
635     U -= Ustride * 2;
636     V -= Vstride * 2;
637     TM2_RECALC_BLOCK(U, Ustride, clast, ctx->CD);
638     TM2_RECALC_BLOCK(V, Vstride, (clast + 2), (ctx->CD + 2));
639
640     /* update deltas */
641     ctx->D[0] = Yo[3] - last[3];
642     ctx->D[1] = Yo[3 + oYstride] - Yo[3];
643     ctx->D[2] = Yo[3 + oYstride * 2] - Yo[3 + oYstride];
644     ctx->D[3] = Yo[3 + oYstride * 3] - Yo[3 + oYstride * 2];
645
646     for (j = 0; j < 4; j++) {
647         for (i = 0; i < 4; i++) {
648             Y[i]    = Yo[i];
649             last[i] = Yo[i];
650         }
651         Y  += Ystride;
652         Yo += oYstride;
653     }
654 }
655
656 static inline void tm2_update_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
657 {
658     int i, j;
659     int d;
660     TM2_INIT_POINTERS_2();
661
662     /* update chroma */
663     for (j = 0; j < 2; j++) {
664         for (i = 0; i < 2; i++) {
665             U[i] = Uo[i] + GET_TOK(ctx, TM2_UPD);
666             V[i] = Vo[i] + GET_TOK(ctx, TM2_UPD);
667         }
668         U  += Ustride;
669         V  += Vstride;
670         Uo += oUstride;
671         Vo += oVstride;
672     }
673     U -= Ustride * 2;
674     V -= Vstride * 2;
675     TM2_RECALC_BLOCK(U, Ustride, clast, ctx->CD);
676     TM2_RECALC_BLOCK(V, Vstride, (clast + 2), (ctx->CD + 2));
677
678     /* update deltas */
679     ctx->D[0] = Yo[3] - last[3];
680     ctx->D[1] = Yo[3 + oYstride] - Yo[3];
681     ctx->D[2] = Yo[3 + oYstride * 2] - Yo[3 + oYstride];
682     ctx->D[3] = Yo[3 + oYstride * 3] - Yo[3 + oYstride * 2];
683
684     for (j = 0; j < 4; j++) {
685         d = last[3];
686         for (i = 0; i < 4; i++) {
687             Y[i]    = Yo[i] + GET_TOK(ctx, TM2_UPD);
688             last[i] = Y[i];
689         }
690         ctx->D[j] = last[3] - d;
691         Y  += Ystride;
692         Yo += oYstride;
693     }
694 }
695
696 static inline void tm2_motion_block(TM2Context *ctx, AVFrame *pic, int bx, int by)
697 {
698     int i, j;
699     int mx, my;
700     TM2_INIT_POINTERS_2();
701
702     mx = GET_TOK(ctx, TM2_MOT);
703     my = GET_TOK(ctx, TM2_MOT);
704     mx = av_clip(mx, -(bx * 4 + 4), ctx->avctx->width  - bx * 4);
705     my = av_clip(my, -(by * 4 + 4), ctx->avctx->height - by * 4);
706
707     if (4*bx+mx<0 || 4*by+my<0 || 4*bx+mx+4 > ctx->avctx->width || 4*by+my+4 > ctx->avctx->height) {
708         av_log(ctx->avctx, AV_LOG_ERROR, "MV out of picture\n");
709         return;
710     }
711
712     Yo += my * oYstride + mx;
713     Uo += (my >> 1) * oUstride + (mx >> 1);
714     Vo += (my >> 1) * oVstride + (mx >> 1);
715
716     /* copy chroma */
717     for (j = 0; j < 2; j++) {
718         for (i = 0; i < 2; i++) {
719             U[i] = Uo[i];
720             V[i] = Vo[i];
721         }
722         U  += Ustride;
723         V  += Vstride;
724         Uo += oUstride;
725         Vo += oVstride;
726     }
727     U -= Ustride * 2;
728     V -= Vstride * 2;
729     TM2_RECALC_BLOCK(U, Ustride, clast, ctx->CD);
730     TM2_RECALC_BLOCK(V, Vstride, (clast + 2), (ctx->CD + 2));
731
732     /* copy luma */
733     for (j = 0; j < 4; j++) {
734         for (i = 0; i < 4; i++) {
735             Y[i] = Yo[i];
736         }
737         Y  += Ystride;
738         Yo += oYstride;
739     }
740     /* calculate deltas */
741     Y -= Ystride * 4;
742     ctx->D[0] = Y[3] - last[3];
743     ctx->D[1] = Y[3 + Ystride] - Y[3];
744     ctx->D[2] = Y[3 + Ystride * 2] - Y[3 + Ystride];
745     ctx->D[3] = Y[3 + Ystride * 3] - Y[3 + Ystride * 2];
746     for (i = 0; i < 4; i++)
747         last[i] = Y[i + Ystride * 3];
748 }
749
750 static int tm2_decode_blocks(TM2Context *ctx, AVFrame *p)
751 {
752     int i, j;
753     int w = ctx->avctx->width, h = ctx->avctx->height, bw = w >> 2, bh = h >> 2, cw = w >> 1;
754     int type;
755     int keyframe = 1;
756     int *Y, *U, *V;
757     uint8_t *dst;
758
759     for (i = 0; i < TM2_NUM_STREAMS; i++)
760         ctx->tok_ptrs[i] = 0;
761
762     if (ctx->tok_lens[TM2_TYPE]<bw*bh) {
763         av_log(ctx->avctx,AV_LOG_ERROR,"Got %i tokens for %i blocks\n",ctx->tok_lens[TM2_TYPE],bw*bh);
764         return AVERROR_INVALIDDATA;
765     }
766
767     memset(ctx->last, 0, 4 * bw * sizeof(int));
768     memset(ctx->clast, 0, 4 * bw * sizeof(int));
769
770     for (j = 0; j < bh; j++) {
771         memset(ctx->D, 0, 4 * sizeof(int));
772         memset(ctx->CD, 0, 4 * sizeof(int));
773         for (i = 0; i < bw; i++) {
774             type = GET_TOK(ctx, TM2_TYPE);
775             switch(type) {
776             case TM2_HI_RES:
777                 tm2_hi_res_block(ctx, p, i, j);
778                 break;
779             case TM2_MED_RES:
780                 tm2_med_res_block(ctx, p, i, j);
781                 break;
782             case TM2_LOW_RES:
783                 tm2_low_res_block(ctx, p, i, j);
784                 break;
785             case TM2_NULL_RES:
786                 tm2_null_res_block(ctx, p, i, j);
787                 break;
788             case TM2_UPDATE:
789                 tm2_update_block(ctx, p, i, j);
790                 keyframe = 0;
791                 break;
792             case TM2_STILL:
793                 tm2_still_block(ctx, p, i, j);
794                 keyframe = 0;
795                 break;
796             case TM2_MOTION:
797                 tm2_motion_block(ctx, p, i, j);
798                 keyframe = 0;
799                 break;
800             default:
801                 av_log(ctx->avctx, AV_LOG_ERROR, "Skipping unknown block type %i\n", type);
802             }
803         }
804     }
805
806     /* copy data from our buffer to AVFrame */
807     Y = (ctx->cur?ctx->Y2:ctx->Y1);
808     U = (ctx->cur?ctx->U2:ctx->U1);
809     V = (ctx->cur?ctx->V2:ctx->V1);
810     dst = p->data[0];
811     for (j = 0; j < h; j++) {
812         for (i = 0; i < w; i++) {
813             int y = Y[i], u = U[i >> 1], v = V[i >> 1];
814             dst[3*i+0] = av_clip_uint8(y + v);
815             dst[3*i+1] = av_clip_uint8(y);
816             dst[3*i+2] = av_clip_uint8(y + u);
817         }
818
819         /* horizontal edge extension */
820         Y[-4]    = Y[-3]    = Y[-2]    = Y[-1] = Y[0];
821         Y[w + 3] = Y[w + 2] = Y[w + 1] = Y[w]  = Y[w - 1];
822
823         /* vertical edge extension */
824         if (j == 0) {
825             memcpy(Y - 4 - 1 * ctx->y_stride, Y - 4, ctx->y_stride);
826             memcpy(Y - 4 - 2 * ctx->y_stride, Y - 4, ctx->y_stride);
827             memcpy(Y - 4 - 3 * ctx->y_stride, Y - 4, ctx->y_stride);
828             memcpy(Y - 4 - 4 * ctx->y_stride, Y - 4, ctx->y_stride);
829         } else if (j == h - 1) {
830             memcpy(Y - 4 + 1 * ctx->y_stride, Y - 4, ctx->y_stride);
831             memcpy(Y - 4 + 2 * ctx->y_stride, Y - 4, ctx->y_stride);
832             memcpy(Y - 4 + 3 * ctx->y_stride, Y - 4, ctx->y_stride);
833             memcpy(Y - 4 + 4 * ctx->y_stride, Y - 4, ctx->y_stride);
834         }
835
836         Y += ctx->y_stride;
837         if (j & 1) {
838             /* horizontal edge extension */
839             U[-2]     = U[-1] = U[0];
840             V[-2]     = V[-1] = V[0];
841             U[cw + 1] = U[cw] = U[cw - 1];
842             V[cw + 1] = V[cw] = V[cw - 1];
843
844             /* vertical edge extension */
845             if (j == 1) {
846                 memcpy(U - 2 - 1 * ctx->uv_stride, U - 2, ctx->uv_stride);
847                 memcpy(V - 2 - 1 * ctx->uv_stride, V - 2, ctx->uv_stride);
848                 memcpy(U - 2 - 2 * ctx->uv_stride, U - 2, ctx->uv_stride);
849                 memcpy(V - 2 - 2 * ctx->uv_stride, V - 2, ctx->uv_stride);
850             } else if (j == h - 1) {
851                 memcpy(U - 2 + 1 * ctx->uv_stride, U - 2, ctx->uv_stride);
852                 memcpy(V - 2 + 1 * ctx->uv_stride, V - 2, ctx->uv_stride);
853                 memcpy(U - 2 + 2 * ctx->uv_stride, U - 2, ctx->uv_stride);
854                 memcpy(V - 2 + 2 * ctx->uv_stride, V - 2, ctx->uv_stride);
855             }
856
857             U += ctx->uv_stride;
858             V += ctx->uv_stride;
859         }
860         dst += p->linesize[0];
861     }
862
863     return keyframe;
864 }
865
866 static const int tm2_stream_order[TM2_NUM_STREAMS] = {
867     TM2_C_HI, TM2_C_LO, TM2_L_HI, TM2_L_LO, TM2_UPD, TM2_MOT, TM2_TYPE
868 };
869
870 #define TM2_HEADER_SIZE 40
871
872 static int decode_frame(AVCodecContext *avctx,
873                         void *data, int *got_frame,
874                         AVPacket *avpkt)
875 {
876     TM2Context * const l = avctx->priv_data;
877     const uint8_t *buf   = avpkt->data;
878     int buf_size         = avpkt->size & ~3;
879     AVFrame * const p    = l->pic;
880     int offset           = TM2_HEADER_SIZE;
881     int i, t, ret;
882
883     av_fast_padded_malloc(&l->buffer, &l->buffer_size, buf_size);
884     if (!l->buffer) {
885         av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n");
886         return AVERROR(ENOMEM);
887     }
888
889     if ((ret = ff_reget_buffer(avctx, p)) < 0)
890         return ret;
891
892     l->bdsp.bswap_buf((uint32_t *) l->buffer, (const uint32_t *) buf,
893                       buf_size >> 2);
894
895     if ((ret = tm2_read_header(l, l->buffer)) < 0) {
896         return ret;
897     }
898
899     for (i = 0; i < TM2_NUM_STREAMS; i++) {
900         if (offset >= buf_size) {
901             av_log(avctx, AV_LOG_ERROR, "no space for tm2_read_stream\n");
902             return AVERROR_INVALIDDATA;
903         }
904
905         t = tm2_read_stream(l, l->buffer + offset, tm2_stream_order[i],
906                             buf_size - offset);
907         if (t < 0) {
908             int j = tm2_stream_order[i];
909             memset(l->tokens[j], 0, sizeof(**l->tokens) * l->tok_lens[j]);
910             return t;
911         }
912         offset += t;
913     }
914     p->key_frame = tm2_decode_blocks(l, p);
915     if (p->key_frame)
916         p->pict_type = AV_PICTURE_TYPE_I;
917     else
918         p->pict_type = AV_PICTURE_TYPE_P;
919
920     l->cur = !l->cur;
921     *got_frame      = 1;
922     ret = av_frame_ref(data, l->pic);
923
924     return (ret < 0) ? ret : buf_size;
925 }
926
927 static av_cold int decode_init(AVCodecContext *avctx)
928 {
929     TM2Context * const l = avctx->priv_data;
930     int i, w = avctx->width, h = avctx->height;
931
932     if ((avctx->width & 3) || (avctx->height & 3)) {
933         av_log(avctx, AV_LOG_ERROR, "Width and height must be multiple of 4\n");
934         return AVERROR(EINVAL);
935     }
936
937     l->avctx       = avctx;
938     avctx->pix_fmt = AV_PIX_FMT_BGR24;
939
940     l->pic = av_frame_alloc();
941     if (!l->pic)
942         return AVERROR(ENOMEM);
943
944     ff_bswapdsp_init(&l->bdsp);
945
946     l->last  = av_malloc_array(w >> 2, 4 * sizeof(*l->last) );
947     l->clast = av_malloc_array(w >> 2, 4 * sizeof(*l->clast));
948
949     for (i = 0; i < TM2_NUM_STREAMS; i++) {
950         l->tokens[i] = NULL;
951         l->tok_lens[i] = 0;
952     }
953
954     w += 8;
955     h += 8;
956     l->Y1_base = av_calloc(w * h, sizeof(*l->Y1_base));
957     l->Y2_base = av_calloc(w * h, sizeof(*l->Y2_base));
958     l->y_stride = w;
959     w = (w + 1) >> 1;
960     h = (h + 1) >> 1;
961     l->U1_base = av_calloc(w * h, sizeof(*l->U1_base));
962     l->V1_base = av_calloc(w * h, sizeof(*l->V1_base));
963     l->U2_base = av_calloc(w * h, sizeof(*l->U2_base));
964     l->V2_base = av_calloc(w * h, sizeof(*l->V1_base));
965     l->uv_stride = w;
966     l->cur = 0;
967     if (!l->Y1_base || !l->Y2_base || !l->U1_base ||
968         !l->V1_base || !l->U2_base || !l->V2_base ||
969         !l->last    || !l->clast) {
970         av_freep(&l->Y1_base);
971         av_freep(&l->Y2_base);
972         av_freep(&l->U1_base);
973         av_freep(&l->U2_base);
974         av_freep(&l->V1_base);
975         av_freep(&l->V2_base);
976         av_freep(&l->last);
977         av_freep(&l->clast);
978         av_frame_free(&l->pic);
979         return AVERROR(ENOMEM);
980     }
981     l->Y1 = l->Y1_base + l->y_stride  * 4 + 4;
982     l->Y2 = l->Y2_base + l->y_stride  * 4 + 4;
983     l->U1 = l->U1_base + l->uv_stride * 2 + 2;
984     l->U2 = l->U2_base + l->uv_stride * 2 + 2;
985     l->V1 = l->V1_base + l->uv_stride * 2 + 2;
986     l->V2 = l->V2_base + l->uv_stride * 2 + 2;
987
988     return 0;
989 }
990
991 static av_cold int decode_end(AVCodecContext *avctx)
992 {
993     TM2Context * const l = avctx->priv_data;
994     int i;
995
996     av_free(l->last);
997     av_free(l->clast);
998     for (i = 0; i < TM2_NUM_STREAMS; i++)
999         av_free(l->tokens[i]);
1000     if (l->Y1) {
1001         av_free(l->Y1_base);
1002         av_free(l->U1_base);
1003         av_free(l->V1_base);
1004         av_free(l->Y2_base);
1005         av_free(l->U2_base);
1006         av_free(l->V2_base);
1007     }
1008     av_freep(&l->buffer);
1009     l->buffer_size = 0;
1010
1011     av_frame_free(&l->pic);
1012
1013     return 0;
1014 }
1015
1016 AVCodec ff_truemotion2_decoder = {
1017     .name           = "truemotion2",
1018     .long_name      = NULL_IF_CONFIG_SMALL("Duck TrueMotion 2.0"),
1019     .type           = AVMEDIA_TYPE_VIDEO,
1020     .id             = AV_CODEC_ID_TRUEMOTION2,
1021     .priv_data_size = sizeof(TM2Context),
1022     .init           = decode_init,
1023     .close          = decode_end,
1024     .decode         = decode_frame,
1025     .capabilities   = CODEC_CAP_DR1,
1026 };