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