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