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