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