• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * ClearVideo decoder
3  * Copyright (c) 2012-2018 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  * ClearVideo decoder
25  */
26 
27 #include "libavutil/mem_internal.h"
28 #include "libavutil/thread.h"
29 
30 #include "avcodec.h"
31 #include "bytestream.h"
32 #include "codec_internal.h"
33 #include "get_bits.h"
34 #include "idctdsp.h"
35 #include "internal.h"
36 #include "mathops.h"
37 #include "clearvideodata.h"
38 
39 #define CLV_VLC_BITS 9
40 
41 typedef struct LevelCodes {
42     VLC         flags_cb;
43     VLC         mv_cb;
44     VLC         bias_cb;
45 } LevelCodes;
46 
47 typedef struct MV {
48     int16_t x, y;
49 } MV;
50 
51 static const MV zero_mv = { 0 };
52 
53 typedef struct MVInfo {
54     int mb_w;
55     int mb_h;
56     int mb_size;
57     int mb_stride;
58     int top;
59     MV  *mv;
60 } MVInfo;
61 
62 typedef struct TileInfo {
63     uint16_t        flags;
64     int16_t         bias;
65     MV              mv;
66     struct TileInfo *child[4];
67 } TileInfo;
68 
69 typedef struct CLVContext {
70     AVCodecContext *avctx;
71     IDCTDSPContext idsp;
72     AVFrame        *pic;
73     AVFrame        *prev;
74     GetBitContext  gb;
75     int            mb_width, mb_height;
76     int            pmb_width, pmb_height;
77     MVInfo         mvi;
78     int            tile_size;
79     int            tile_shift;
80     int            luma_dc_quant, chroma_dc_quant, ac_quant;
81     DECLARE_ALIGNED(16, int16_t, block)[64];
82     int            top_dc[3], left_dc[4];
83 } CLVContext;
84 
85 static VLC        dc_vlc, ac_vlc;
86 static LevelCodes lev[4 + 3 + 3]; // 0..3: Y, 4..6: U, 7..9: V
87 static VLCElem    vlc_buf[16716];
88 
decode_block(CLVContext * ctx,int16_t * blk,int has_ac,int ac_quant)89 static inline int decode_block(CLVContext *ctx, int16_t *blk, int has_ac,
90                                int ac_quant)
91 {
92     GetBitContext *gb = &ctx->gb;
93     int idx = 1, last = 0, val, skip;
94 
95     memset(blk, 0, sizeof(*blk) * 64);
96     blk[0] = get_vlc2(gb, dc_vlc.table, CLV_VLC_BITS, 3);
97 
98     if (!has_ac)
99         return 0;
100 
101     while (idx < 64 && !last) {
102         val = get_vlc2(gb, ac_vlc.table, CLV_VLC_BITS, 2);
103         if (val < 0)
104             return AVERROR_INVALIDDATA;
105         if (val != 0x1BFF) {
106             last =  val >> 12;
107             skip = (val >> 4) & 0xFF;
108             val &= 0xF;
109             if (get_bits1(gb))
110                 val = -val;
111         } else {
112             last = get_bits1(gb);
113             skip = get_bits(gb, 6);
114             val  = get_sbits(gb, 8);
115         }
116         if (val) {
117             int aval = FFABS(val), sign = val < 0;
118             val = ac_quant * (2 * aval + 1);
119             if (!(ac_quant & 1))
120                 val--;
121             if (sign)
122                 val = -val;
123         }
124         idx += skip;
125         if (idx >= 64)
126             return AVERROR_INVALIDDATA;
127         blk[ff_zigzag_direct[idx++]] = val;
128     }
129 
130     return (idx <= 64 && last) ? 0 : -1;
131 }
132 
133 #define DCT_TEMPLATE(blk, step, bias, shift, dshift, OP)                \
134     const int t0 = OP(2841 * blk[1 * step] +  565 * blk[7 * step]);     \
135     const int t1 = OP( 565 * blk[1 * step] - 2841 * blk[7 * step]);     \
136     const int t2 = OP(1609 * blk[5 * step] + 2408 * blk[3 * step]);     \
137     const int t3 = OP(2408 * blk[5 * step] - 1609 * blk[3 * step]);     \
138     const int t4 = OP(1108 * blk[2 * step] - 2676 * blk[6 * step]);     \
139     const int t5 = OP(2676 * blk[2 * step] + 1108 * blk[6 * step]);     \
140     const int t6 = ((blk[0 * step] + blk[4 * step]) * (1 << dshift)) + bias;  \
141     const int t7 = ((blk[0 * step] - blk[4 * step]) * (1 << dshift)) + bias;  \
142     const int t8 = t0 + t2;                                             \
143     const int t9 = t0 - t2;                                             \
144     const int tA = (int)(181U * (t9 + (t1 - t3)) + 0x80) >> 8;          \
145     const int tB = (int)(181U * (t9 - (t1 - t3)) + 0x80) >> 8;          \
146     const int tC = t1 + t3;                                             \
147                                                                         \
148     blk[0 * step] = (t6 + t5 + t8) >> shift;                            \
149     blk[1 * step] = (t7 + t4 + tA) >> shift;                            \
150     blk[2 * step] = (t7 - t4 + tB) >> shift;                            \
151     blk[3 * step] = (t6 - t5 + tC) >> shift;                            \
152     blk[4 * step] = (t6 - t5 - tC) >> shift;                            \
153     blk[5 * step] = (t7 - t4 - tB) >> shift;                            \
154     blk[6 * step] = (t7 + t4 - tA) >> shift;                            \
155     blk[7 * step] = (t6 + t5 - t8) >> shift;                            \
156 
157 #define ROP(x) x
158 #define COP(x) (((x) + 4) >> 3)
159 
clv_dct(int16_t * block)160 static void clv_dct(int16_t *block)
161 {
162     int i;
163     int16_t *ptr;
164 
165     ptr = block;
166     for (i = 0; i < 8; i++) {
167         DCT_TEMPLATE(ptr, 1, 0x80, 8, 11, ROP);
168         ptr += 8;
169     }
170 
171     ptr = block;
172     for (i = 0; i < 8; i++) {
173         DCT_TEMPLATE(ptr, 8, 0x2000, 14, 8, COP);
174         ptr++;
175     }
176 }
177 
decode_mb(CLVContext * c,int x,int y)178 static int decode_mb(CLVContext *c, int x, int y)
179 {
180     int i, has_ac[6], off;
181 
182     for (i = 0; i < 6; i++)
183         has_ac[i] = get_bits1(&c->gb);
184 
185     off = x * 16 + y * 16 * c->pic->linesize[0];
186     for (i = 0; i < 4; i++) {
187         if (decode_block(c, c->block, has_ac[i], c->ac_quant) < 0)
188             return AVERROR_INVALIDDATA;
189         if (!x && !(i & 1)) {
190             c->block[0] += c->top_dc[0];
191             c->top_dc[0] = c->block[0];
192         } else {
193             c->block[0] += c->left_dc[(i & 2) >> 1];
194         }
195         c->left_dc[(i & 2) >> 1] = c->block[0];
196         c->block[0]             *= c->luma_dc_quant;
197         clv_dct(c->block);
198         if (i == 2)
199             off += c->pic->linesize[0] * 8;
200         c->idsp.put_pixels_clamped(c->block,
201                                    c->pic->data[0] + off + (i & 1) * 8,
202                                    c->pic->linesize[0]);
203     }
204 
205     off = x * 8 + y * 8 * c->pic->linesize[1];
206     for (i = 1; i < 3; i++) {
207         if (decode_block(c, c->block, has_ac[i + 3], c->ac_quant) < 0)
208             return AVERROR_INVALIDDATA;
209         if (!x) {
210             c->block[0] += c->top_dc[i];
211             c->top_dc[i] = c->block[0];
212         } else {
213             c->block[0] += c->left_dc[i + 1];
214         }
215         c->left_dc[i + 1] = c->block[0];
216         c->block[0]      *= c->chroma_dc_quant;
217         clv_dct(c->block);
218         c->idsp.put_pixels_clamped(c->block, c->pic->data[i] + off,
219                                    c->pic->linesize[i]);
220     }
221 
222     return 0;
223 }
224 
copy_block(AVCodecContext * avctx,AVFrame * dst,AVFrame * src,int plane,int x,int y,int dx,int dy,int size)225 static int copy_block(AVCodecContext *avctx, AVFrame *dst, AVFrame *src,
226                       int plane, int x, int y, int dx, int dy, int size)
227 {
228     int shift = plane > 0;
229     int sx = x + dx;
230     int sy = y + dy;
231     int sstride, dstride, soff, doff;
232     uint8_t *sbuf, *dbuf;
233     int i;
234 
235     if (x < 0 || sx < 0 || y < 0 || sy < 0 ||
236         x + size > avctx->coded_width >> shift ||
237         y + size > avctx->coded_height >> shift ||
238         sx + size > avctx->coded_width >> shift ||
239         sy + size > avctx->coded_height >> shift)
240         return AVERROR_INVALIDDATA;
241 
242     sstride = src->linesize[plane];
243     dstride = dst->linesize[plane];
244     soff    = sx + sy * sstride;
245     sbuf    = src->data[plane];
246     doff    = x + y * dstride;
247     dbuf    = dst->data[plane];
248 
249     for (i = 0; i < size; i++) {
250         uint8_t *dptr = &dbuf[doff];
251         uint8_t *sptr = &sbuf[soff];
252 
253         memcpy(dptr, sptr, size);
254         doff += dstride;
255         soff += sstride;
256     }
257 
258     return 0;
259 }
260 
copyadd_block(AVCodecContext * avctx,AVFrame * dst,AVFrame * src,int plane,int x,int y,int dx,int dy,int size,int bias)261 static int copyadd_block(AVCodecContext *avctx, AVFrame *dst, AVFrame *src,
262                          int plane, int x, int y, int dx, int dy, int size, int bias)
263 {
264     int shift = plane > 0;
265     int sx = x + dx;
266     int sy = y + dy;
267     int sstride   = src->linesize[plane];
268     int dstride   = dst->linesize[plane];
269     int soff      = sx + sy * sstride;
270     uint8_t *sbuf = src->data[plane];
271     int doff      = x + y * dstride;
272     uint8_t *dbuf = dst->data[plane];
273     int i, j;
274 
275     if (x < 0 || sx < 0 || y < 0 || sy < 0 ||
276         x + size > avctx->coded_width >> shift ||
277         y + size > avctx->coded_height >> shift ||
278         sx + size > avctx->coded_width >> shift ||
279         sy + size > avctx->coded_height >> shift)
280         return AVERROR_INVALIDDATA;
281 
282     for (j = 0; j < size; j++) {
283         uint8_t *dptr = &dbuf[doff];
284         uint8_t *sptr = &sbuf[soff];
285 
286         for (i = 0; i < size; i++) {
287             int val = sptr[i] + bias;
288 
289             dptr[i] = av_clip_uint8(val);
290         }
291 
292         doff += dstride;
293         soff += sstride;
294     }
295 
296     return 0;
297 }
298 
mvi_predict(MVInfo * mvi,int mb_x,int mb_y,MV diff)299 static MV mvi_predict(MVInfo *mvi, int mb_x, int mb_y, MV diff)
300 {
301     MV res, pred_mv;
302     int left_mv, right_mv, top_mv, bot_mv;
303 
304     if (mvi->top) {
305         if (mb_x > 0) {
306             pred_mv = mvi->mv[mvi->mb_stride + mb_x - 1];
307         } else {
308             pred_mv = zero_mv;
309         }
310     } else if ((mb_x == 0) || (mb_x == mvi->mb_w - 1)) {
311         pred_mv = mvi->mv[mb_x];
312     } else {
313         MV A = mvi->mv[mvi->mb_stride + mb_x - 1];
314         MV B = mvi->mv[                 mb_x    ];
315         MV C = mvi->mv[                 mb_x + 1];
316         pred_mv.x = mid_pred(A.x, B.x, C.x);
317         pred_mv.y = mid_pred(A.y, B.y, C.y);
318     }
319 
320     res = pred_mv;
321 
322     left_mv = -((mb_x * mvi->mb_size));
323     right_mv = ((mvi->mb_w - mb_x - 1) * mvi->mb_size);
324     if (res.x < left_mv) {
325         res.x = left_mv;
326     }
327     if (res.x > right_mv) {
328         res.x = right_mv;
329     }
330     top_mv = -((mb_y * mvi->mb_size));
331     bot_mv = ((mvi->mb_h - mb_y - 1) * mvi->mb_size);
332     if (res.y < top_mv) {
333         res.y = top_mv;
334     }
335     if (res.y > bot_mv) {
336         res.y = bot_mv;
337     }
338 
339     mvi->mv[mvi->mb_stride + mb_x].x = res.x + diff.x;
340     mvi->mv[mvi->mb_stride + mb_x].y = res.y + diff.y;
341 
342     return res;
343 }
344 
mvi_reset(MVInfo * mvi,int mb_w,int mb_h,int mb_size)345 static void mvi_reset(MVInfo *mvi, int mb_w, int mb_h, int mb_size)
346 {
347     mvi->top       = 1;
348     mvi->mb_w      = mb_w;
349     mvi->mb_h      = mb_h;
350     mvi->mb_size   = mb_size;
351     mvi->mb_stride = mb_w;
352     memset(mvi->mv, 0, sizeof(MV) * mvi->mb_stride * 2);
353 }
354 
mvi_update_row(MVInfo * mvi)355 static void mvi_update_row(MVInfo *mvi)
356 {
357     int i;
358 
359     mvi->top = 0;
360     for (i = 0 ; i < mvi->mb_stride; i++) {
361         mvi->mv[i] = mvi->mv[mvi->mb_stride + i];
362     }
363 }
364 
decode_tile_info(GetBitContext * gb,const LevelCodes * lc,int level)365 static TileInfo *decode_tile_info(GetBitContext *gb, const LevelCodes *lc, int level)
366 {
367     TileInfo *ti;
368     int i, flags = 0;
369     int16_t bias = 0;
370     MV mv = { 0 };
371 
372     if (lc[level].flags_cb.table) {
373         flags = get_vlc2(gb, lc[level].flags_cb.table, CLV_VLC_BITS, 2);
374     }
375 
376     if (lc[level].mv_cb.table) {
377         uint16_t mv_code = get_vlc2(gb, lc[level].mv_cb.table, CLV_VLC_BITS, 2);
378 
379         if (mv_code != MV_ESC) {
380             mv.x = (int8_t)(mv_code & 0xff);
381             mv.y = (int8_t)(mv_code >> 8);
382         } else {
383             mv.x = get_sbits(gb, 8);
384             mv.y = get_sbits(gb, 8);
385         }
386     }
387 
388     if (lc[level].bias_cb.table) {
389         uint16_t bias_val = get_vlc2(gb, lc[level].bias_cb.table, CLV_VLC_BITS, 2);
390 
391         if (bias_val != BIAS_ESC) {
392             bias = (int16_t)(bias_val);
393         } else {
394             bias = get_sbits(gb, 16);
395         }
396     }
397 
398     ti = av_calloc(1, sizeof(*ti));
399     if (!ti)
400         return NULL;
401 
402     ti->flags = flags;
403     ti->mv = mv;
404     ti->bias = bias;
405 
406     if (ti->flags) {
407         for (i = 0; i < 4; i++) {
408             if (ti->flags & (1 << i)) {
409                 TileInfo *subti = decode_tile_info(gb, lc, level + 1);
410                 ti->child[i] = subti;
411             }
412         }
413     }
414 
415     return ti;
416 }
417 
tile_do_block(AVCodecContext * avctx,AVFrame * dst,AVFrame * src,int plane,int x,int y,int dx,int dy,int size,int bias)418 static int tile_do_block(AVCodecContext *avctx, AVFrame *dst, AVFrame *src,
419                          int plane, int x, int y, int dx, int dy, int size, int bias)
420 {
421     int ret;
422 
423     if (!bias) {
424         ret = copy_block(avctx, dst, src, plane, x, y, dx, dy, size);
425     } else {
426         ret = copyadd_block(avctx, dst, src, plane, x, y, dx, dy, size, bias);
427     }
428 
429     return ret;
430 }
431 
restore_tree(AVCodecContext * avctx,AVFrame * dst,AVFrame * src,int plane,int x,int y,int size,TileInfo * tile,MV root_mv)432 static int restore_tree(AVCodecContext *avctx, AVFrame *dst, AVFrame *src,
433                         int plane, int x, int y, int size,
434                         TileInfo *tile, MV root_mv)
435 {
436     int ret;
437     MV mv;
438 
439     mv.x = root_mv.x + tile->mv.x;
440     mv.y = root_mv.y + tile->mv.y;
441 
442     if (!tile->flags) {
443         ret = tile_do_block(avctx, dst, src, plane, x, y, mv.x, mv.y, size, tile->bias);
444     } else {
445         int i, hsize = size >> 1;
446 
447         for (i = 0; i < 4; i++) {
448             int xoff = (i & 2) == 0 ? 0 : hsize;
449             int yoff = (i & 1) == 0 ? 0 : hsize;
450 
451             if (tile->child[i]) {
452                 ret = restore_tree(avctx, dst, src, plane, x + xoff, y + yoff, hsize, tile->child[i], root_mv);
453                 av_freep(&tile->child[i]);
454             } else {
455                 ret = tile_do_block(avctx, dst, src, plane, x + xoff, y + yoff, mv.x, mv.y, hsize, tile->bias);
456             }
457         }
458     }
459 
460     return ret;
461 }
462 
extend_edges(AVFrame * buf,int tile_size)463 static void extend_edges(AVFrame *buf, int tile_size)
464 {
465     int comp, i, j;
466 
467     for (comp = 0; comp < 3; comp++) {
468         int shift = comp > 0;
469         int w = buf->width  >> shift;
470         int h = buf->height >> shift;
471         int size = comp == 0 ? tile_size : tile_size >> 1;
472         int stride = buf->linesize[comp];
473         uint8_t *framebuf = buf->data[comp];
474 
475         int right  = size - (w & (size - 1));
476         int bottom = size - (h & (size - 1));
477 
478         if ((right == size) && (bottom == size)) {
479             return;
480         }
481         if (right != size) {
482             int off = w;
483             for (j = 0; j < h; j++) {
484                 for (i = 0; i < right; i++) {
485                     framebuf[off + i] = 0x80;
486                 }
487                 off += stride;
488             }
489         }
490         if (bottom != size) {
491             int off = h * stride;
492             for (j = 0; j < bottom; j++) {
493                 for (i = 0; i < stride; i++) {
494                     framebuf[off + i] = 0x80;
495                 }
496                 off += stride;
497             }
498         }
499     }
500 }
501 
clv_decode_frame(AVCodecContext * avctx,AVFrame * rframe,int * got_frame,AVPacket * avpkt)502 static int clv_decode_frame(AVCodecContext *avctx, AVFrame *rframe,
503                             int *got_frame, AVPacket *avpkt)
504 {
505     const uint8_t *buf = avpkt->data;
506     int buf_size = avpkt->size;
507     CLVContext *c = avctx->priv_data;
508     GetByteContext gb;
509     uint32_t frame_type;
510     int i, j, ret;
511     int mb_ret = 0;
512 
513     bytestream2_init(&gb, buf, buf_size);
514     if (avctx->codec_tag == MKTAG('C', 'L', 'V', '1')) {
515         int skip = bytestream2_get_byte(&gb);
516         bytestream2_skip(&gb, (skip + 1) * 8);
517     }
518 
519     frame_type = bytestream2_get_byte(&gb);
520 
521     if ((frame_type & 0x7f) == 0x30) {
522         *got_frame = 0;
523         return buf_size;
524     } else if (frame_type & 0x2) {
525         if (buf_size < c->mb_width * c->mb_height) {
526             av_log(avctx, AV_LOG_ERROR, "Packet too small\n");
527             return AVERROR_INVALIDDATA;
528         }
529 
530         if ((ret = ff_reget_buffer(avctx, c->pic, 0)) < 0)
531             return ret;
532 
533         c->pic->key_frame = 1;
534         c->pic->pict_type = AV_PICTURE_TYPE_I;
535 
536         bytestream2_get_be32(&gb); // frame size;
537         c->ac_quant        = bytestream2_get_byte(&gb);
538         c->luma_dc_quant   = 32;
539         c->chroma_dc_quant = 32;
540 
541         if ((ret = init_get_bits8(&c->gb, buf + bytestream2_tell(&gb),
542                                   buf_size - bytestream2_tell(&gb))) < 0)
543             return ret;
544 
545         for (i = 0; i < 3; i++)
546             c->top_dc[i] = 32;
547         for (i = 0; i < 4; i++)
548             c->left_dc[i] = 32;
549 
550         for (j = 0; j < c->mb_height; j++) {
551             for (i = 0; i < c->mb_width; i++) {
552                 ret = decode_mb(c, i, j);
553                 if (ret < 0)
554                     mb_ret = ret;
555             }
556         }
557         extend_edges(c->pic, c->tile_size);
558     } else {
559         int plane;
560 
561         if (c->pmb_width * c->pmb_height > 8LL*(buf_size - bytestream2_tell(&gb)))
562             return AVERROR_INVALIDDATA;
563 
564         if ((ret = ff_reget_buffer(avctx, c->pic, 0)) < 0)
565             return ret;
566 
567         ret = av_frame_copy(c->pic, c->prev);
568         if (ret < 0)
569             return ret;
570 
571         if ((ret = init_get_bits8(&c->gb, buf + bytestream2_tell(&gb),
572                                   buf_size - bytestream2_tell(&gb))) < 0)
573             return ret;
574 
575         mvi_reset(&c->mvi, c->pmb_width, c->pmb_height, 1 << c->tile_shift);
576 
577         for (j = 0; j < c->pmb_height; j++) {
578             for (i = 0; i < c->pmb_width; i++) {
579                 if (get_bits_left(&c->gb) <= 0)
580                     return AVERROR_INVALIDDATA;
581                 if (get_bits1(&c->gb)) {
582                     MV mv = mvi_predict(&c->mvi, i, j, zero_mv);
583 
584                     for (plane = 0; plane < 3; plane++) {
585                         int16_t x = plane == 0 ? i << c->tile_shift : i << (c->tile_shift - 1);
586                         int16_t y = plane == 0 ? j << c->tile_shift : j << (c->tile_shift - 1);
587                         int16_t size = plane == 0 ? 1 << c->tile_shift : 1 << (c->tile_shift - 1);
588                         int16_t mx = plane == 0 ? mv.x : mv.x / 2;
589                         int16_t my = plane == 0 ? mv.y : mv.y / 2;
590 
591                         ret = copy_block(avctx, c->pic, c->prev, plane, x, y, mx, my, size);
592                         if (ret < 0)
593                             mb_ret = ret;
594                     }
595                 } else {
596                     int x = i << c->tile_shift;
597                     int y = j << c->tile_shift;
598                     int size = 1 << c->tile_shift;
599                     TileInfo *tile;
600                     MV mv, cmv;
601 
602                     tile = decode_tile_info(&c->gb, &lev[0], 0); // Y
603                     if (!tile)
604                         return AVERROR(ENOMEM);
605                     mv = mvi_predict(&c->mvi, i, j, tile->mv);
606                     ret = restore_tree(avctx, c->pic, c->prev, 0, x, y, size, tile, mv);
607                     if (ret < 0)
608                         mb_ret = ret;
609                     x = i << (c->tile_shift - 1);
610                     y = j << (c->tile_shift - 1);
611                     size = 1 << (c->tile_shift - 1);
612                     cmv.x = mv.x + tile->mv.x;
613                     cmv.y = mv.y + tile->mv.y;
614                     cmv.x /= 2;
615                     cmv.y /= 2;
616                     av_freep(&tile);
617                     tile = decode_tile_info(&c->gb, &lev[4], 0); // U
618                     if (!tile)
619                         return AVERROR(ENOMEM);
620                     ret = restore_tree(avctx, c->pic, c->prev, 1, x, y, size, tile, cmv);
621                     if (ret < 0)
622                         mb_ret = ret;
623                     av_freep(&tile);
624                     tile = decode_tile_info(&c->gb, &lev[7], 0); // V
625                     if (!tile)
626                         return AVERROR(ENOMEM);
627                     ret = restore_tree(avctx, c->pic, c->prev, 2, x, y, size, tile, cmv);
628                     if (ret < 0)
629                         mb_ret = ret;
630                     av_freep(&tile);
631                 }
632             }
633             mvi_update_row(&c->mvi);
634         }
635         extend_edges(c->pic, c->tile_size);
636 
637         c->pic->key_frame = 0;
638         c->pic->pict_type = AV_PICTURE_TYPE_P;
639     }
640 
641     if ((ret = av_frame_ref(rframe, c->pic)) < 0)
642         return ret;
643 
644     FFSWAP(AVFrame *, c->pic, c->prev);
645 
646     *got_frame = 1;
647 
648     if (get_bits_left(&c->gb) < 0)
649         av_log(c->avctx, AV_LOG_WARNING, "overread %d\n", -get_bits_left(&c->gb));
650 
651     return mb_ret < 0 ? mb_ret : buf_size;
652 }
653 
build_vlc(VLC * vlc,const uint8_t counts[16],const uint16_t ** syms,unsigned * offset)654 static av_cold void build_vlc(VLC *vlc, const uint8_t counts[16],
655                               const uint16_t **syms, unsigned *offset)
656 {
657     uint8_t lens[MAX_VLC_ENTRIES];
658     unsigned num = 0;
659 
660     for (int i = 0; i < 16; i++) {
661         unsigned count = counts[i];
662         if (count == 255) /* Special case for Y_3 table */
663             count = 303;
664         for (count += num; num < count; num++)
665             lens[num] = i + 1;
666     }
667     vlc->table           = &vlc_buf[*offset];
668     vlc->table_allocated = FF_ARRAY_ELEMS(vlc_buf) - *offset;
669     ff_init_vlc_from_lengths(vlc, CLV_VLC_BITS, num, lens, 1,
670                              *syms, 2, 2, 0, INIT_VLC_STATIC_OVERLONG, NULL);
671     *syms += num;
672     *offset += vlc->table_size;
673 }
674 
clv_init_static(void)675 static av_cold void clv_init_static(void)
676 {
677     const uint16_t *mv_syms = clv_mv_syms, *bias_syms = clv_bias_syms;
678 
679     INIT_VLC_STATIC_FROM_LENGTHS(&dc_vlc, CLV_VLC_BITS, NUM_DC_CODES,
680                                  clv_dc_lens, 1,
681                                  clv_dc_syms, 1, 1, -63, 0, 1104);
682     INIT_VLC_STATIC_FROM_LENGTHS(&ac_vlc, CLV_VLC_BITS, NUM_AC_CODES,
683                                  clv_ac_bits, 1,
684                                  clv_ac_syms, 2, 2, 0, 0, 554);
685     for (unsigned i = 0, j = 0, k = 0, offset = 0;; i++) {
686         if (0x36F & (1 << i)) {
687             build_vlc(&lev[i].mv_cb, clv_mv_len_counts[k], &mv_syms, &offset);
688             k++;
689         }
690         if (i == FF_ARRAY_ELEMS(lev) - 1)
691             break;
692         if (0x1B7 & (1 << i)) {
693             lev[i].flags_cb.table           = &vlc_buf[offset];
694             lev[i].flags_cb.table_allocated = FF_ARRAY_ELEMS(vlc_buf) - offset;
695             ff_init_vlc_from_lengths(&lev[i].flags_cb, CLV_VLC_BITS, 16,
696                                      clv_flags_bits[j], 1,
697                                      clv_flags_syms[j], 1, 1,
698                                      0, INIT_VLC_STATIC_OVERLONG, NULL);
699             offset += lev[i].flags_cb.table_size;
700 
701             build_vlc(&lev[i + 1].bias_cb, clv_bias_len_counts[j],
702                       &bias_syms, &offset);
703             j++;
704         }
705     }
706 }
707 
clv_decode_init(AVCodecContext * avctx)708 static av_cold int clv_decode_init(AVCodecContext *avctx)
709 {
710     static AVOnce init_static_once = AV_ONCE_INIT;
711     CLVContext *const c = avctx->priv_data;
712     int ret, w, h;
713 
714     if (avctx->extradata_size == 110) {
715         c->tile_size = AV_RL32(&avctx->extradata[94]);
716     } else if (avctx->extradata_size == 150) {
717         c->tile_size = AV_RB32(&avctx->extradata[134]);
718     } else if (!avctx->extradata_size) {
719         c->tile_size = 16;
720     } else {
721         av_log(avctx, AV_LOG_ERROR, "Unsupported extradata size: %d\n", avctx->extradata_size);
722         return AVERROR_INVALIDDATA;
723     }
724 
725     c->tile_shift = av_log2(c->tile_size);
726     if (1U << c->tile_shift != c->tile_size || c->tile_shift < 1 || c->tile_shift > 30) {
727         av_log(avctx, AV_LOG_ERROR, "Tile size: %d, is not power of 2 > 1 and < 2^31\n", c->tile_size);
728         return AVERROR_INVALIDDATA;
729     }
730 
731     avctx->pix_fmt = AV_PIX_FMT_YUV420P;
732     w = avctx->width;
733     h = avctx->height;
734     ret = ff_set_dimensions(avctx, FFALIGN(w, 1 << c->tile_shift), FFALIGN(h, 1 << c->tile_shift));
735     if (ret < 0)
736         return ret;
737     avctx->width  = w;
738     avctx->height = h;
739 
740     c->avctx           = avctx;
741     c->mb_width        = FFALIGN(avctx->width,  16) >> 4;
742     c->mb_height       = FFALIGN(avctx->height, 16) >> 4;
743     c->pmb_width       = (w + c->tile_size - 1) >> c->tile_shift;
744     c->pmb_height      = (h + c->tile_size - 1) >> c->tile_shift;
745     c->pic             = av_frame_alloc();
746     c->prev            = av_frame_alloc();
747     c->mvi.mv          = av_calloc(c->pmb_width * 2, sizeof(*c->mvi.mv));
748     if (!c->pic || !c->prev || !c->mvi.mv)
749         return AVERROR(ENOMEM);
750 
751     ff_idctdsp_init(&c->idsp, avctx);
752 
753     ff_thread_once(&init_static_once, clv_init_static);
754 
755     return 0;
756 }
757 
clv_decode_end(AVCodecContext * avctx)758 static av_cold int clv_decode_end(AVCodecContext *avctx)
759 {
760     CLVContext *const c = avctx->priv_data;
761 
762     av_frame_free(&c->prev);
763     av_frame_free(&c->pic);
764 
765     av_freep(&c->mvi.mv);
766 
767     return 0;
768 }
769 
770 const FFCodec ff_clearvideo_decoder = {
771     .p.name         = "clearvideo",
772     .p.long_name    = NULL_IF_CONFIG_SMALL("Iterated Systems ClearVideo"),
773     .p.type         = AVMEDIA_TYPE_VIDEO,
774     .p.id           = AV_CODEC_ID_CLEARVIDEO,
775     .priv_data_size = sizeof(CLVContext),
776     .init           = clv_decode_init,
777     .close          = clv_decode_end,
778     FF_CODEC_DECODE_CB(clv_decode_frame),
779     .p.capabilities = AV_CODEC_CAP_DR1,
780     .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
781 };
782