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