]> git.sesse.net Git - ffmpeg/blob - libavcodec/cfhd.c
Drop Windows XP support remnants
[ffmpeg] / libavcodec / cfhd.c
1 /*
2  * Copyright (c) 2015-2016 Kieran Kunhya <kieran@kunhya.com>
3  *
4  * This file is part of Libav.
5  *
6  * Libav is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * Libav is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with Libav; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * Cineform HD video decoder
24  */
25
26 #include "libavutil/attributes.h"
27 #include "libavutil/buffer.h"
28 #include "libavutil/common.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/opt.h"
32
33 #include "avcodec.h"
34 #include "bitstream.h"
35 #include "bytestream.h"
36 #include "internal.h"
37 #include "thread.h"
38 #include "cfhd.h"
39
40 enum CFHDParam {
41     ChannelCount     =  12,
42     SubbandCount     =  14,
43     ImageWidth       =  20,
44     ImageHeight      =  21,
45     LowpassPrecision =  35,
46     SubbandNumber    =  48,
47     Quantization     =  53,
48     ChannelNumber    =  62,
49     BitsPerComponent = 101,
50     ChannelWidth     = 104,
51     ChannelHeight    = 105,
52     PrescaleShift    = 109,
53 };
54
55 static av_cold int cfhd_init(AVCodecContext *avctx)
56 {
57     CFHDContext *s = avctx->priv_data;
58
59     memset(s, 0, sizeof(*s));
60
61     s->avctx                   = avctx;
62     avctx->bits_per_raw_sample = 10;
63
64     return ff_cfhd_init_vlcs(s);
65 }
66
67 static void init_plane_defaults(CFHDContext *s)
68 {
69     s->subband_num        = 0;
70     s->level              = 0;
71     s->subband_num_actual = 0;
72 }
73
74 static void init_frame_defaults(CFHDContext *s)
75 {
76     s->coded_format      = AV_PIX_FMT_YUV422P10;
77     s->coded_width       = 0;
78     s->coded_height      = 0;
79     s->cropped_height    = 0;
80     s->bpc               = 10;
81     s->channel_cnt       = 4;
82     s->subband_cnt       = SUBBAND_COUNT;
83     s->channel_num       = 0;
84     s->lowpass_precision = 16;
85     s->quantisation      = 1;
86     s->prescale_shift[0] = 0;
87     s->prescale_shift[1] = 0;
88     s->prescale_shift[2] = 0;
89     s->wavelet_depth     = 3;
90     s->pshift            = 1;
91     s->codebook          = 0;
92     init_plane_defaults(s);
93 }
94
95 /* TODO: merge with VLC tables or use LUT */
96 static inline int dequant_and_decompand(int level, int quantisation)
97 {
98     int64_t abslevel = abs(level);
99     return (abslevel + ((768 * abslevel * abslevel * abslevel) / (255 * 255 * 255))) *
100            FFSIGN(level) * quantisation;
101 }
102
103 static inline void filter(int16_t *output, ptrdiff_t out_stride,
104                           int16_t *low, ptrdiff_t low_stride,
105                           int16_t *high, ptrdiff_t high_stride,
106                           int len, int clip)
107 {
108     int16_t tmp;
109     int i;
110
111     for (i = 0; i < len; i++) {
112         if (i == 0) {
113             tmp = (11 * low[0 * low_stride] - 4 * low[1 * low_stride] + low[2 * low_stride] + 4) >> 3;
114             output[(2 * i + 0) * out_stride] = (tmp + high[0 * high_stride]) >> 1;
115         } else if (i == len - 1) {
116             tmp = (5 * low[i * low_stride] + 4 * low[(i - 1) * low_stride] - low[(i - 2) * low_stride] + 4) >> 3;
117             output[(2 * i + 0) * out_stride] = (tmp + high[i * high_stride]) >> 1;
118         } else {
119             tmp = (low[(i - 1) * low_stride] - low[(i + 1) * low_stride] + 4) >> 3;
120             output[(2 * i + 0) * out_stride] = (tmp + low[i * low_stride] + high[i * high_stride]) >> 1;
121         }
122         if (clip)
123             output[(2 * i + 0) * out_stride] = av_clip_uintp2_c(output[(2 * i + 0) * out_stride], clip);
124
125         if (i == 0) {
126             tmp = (5 * low[0 * low_stride] + 4 * low[1 * low_stride] - low[2 * low_stride] + 4) >> 3;
127             output[(2 * i + 1) * out_stride] = (tmp - high[0 * high_stride]) >> 1;
128         } else if (i == len - 1) {
129             tmp = (11 * low[i * low_stride] - 4 * low[(i - 1) * low_stride] + low[(i - 2) * low_stride] + 4) >> 3;
130             output[(2 * i + 1) * out_stride] = (tmp - high[i * high_stride]) >> 1;
131         } else {
132             tmp = (low[(i + 1) * low_stride] - low[(i - 1) * low_stride] + 4) >> 3;
133             output[(2 * i + 1) * out_stride] = (tmp + low[i * low_stride] - high[i * high_stride]) >> 1;
134         }
135         if (clip)
136             output[(2 * i + 1) * out_stride] = av_clip_uintp2_c(output[(2 * i + 1) * out_stride], clip);
137     }
138 }
139
140 static void horiz_filter(int16_t *output, int16_t *low, int16_t *high,
141                          int width)
142 {
143     filter(output, 1, low, 1, high, 1, width, 0);
144 }
145
146 static void horiz_filter_clip(int16_t *output, int16_t *low, int16_t *high,
147                               int width, int clip)
148 {
149     filter(output, 1, low, 1, high, 1, width, clip);
150 }
151
152 static void vert_filter(int16_t *output, ptrdiff_t out_stride,
153                         int16_t *low, ptrdiff_t low_stride,
154                         int16_t *high, ptrdiff_t high_stride, int len)
155 {
156     filter(output, out_stride, low, low_stride, high, high_stride, len, 0);
157 }
158
159 static void free_buffers(CFHDContext *s)
160 {
161     unsigned i;
162
163     for (i = 0; i < FF_ARRAY_ELEMS(s->plane); i++) {
164         av_freep(&s->plane[i].idwt_buf);
165         av_freep(&s->plane[i].idwt_tmp);
166     }
167     s->a_height = 0;
168     s->a_width  = 0;
169 }
170
171 static int alloc_buffers(CFHDContext *s)
172 {
173     int i, j, ret, planes;
174     int chroma_x_shift, chroma_y_shift;
175     unsigned k;
176
177     if ((ret = av_pix_fmt_get_chroma_sub_sample(s->coded_format,
178                                                 &chroma_x_shift,
179                                                 &chroma_y_shift)) < 0)
180         return ret;
181     planes = av_pix_fmt_count_planes(s->coded_format);
182
183     for (i = 0; i < planes; i++) {
184         int w8, h8, w4, h4, w2, h2;
185         int width  = i ? s->coded_width  >> chroma_x_shift : s->coded_width;
186         int height = i ? s->coded_height >> chroma_y_shift : s->coded_height;
187         ptrdiff_t stride = FFALIGN(width  / 8, 8) * 8;
188         height           = FFALIGN(height / 8, 2) * 8;
189         s->plane[i].width  = width;
190         s->plane[i].height = height;
191         s->plane[i].stride = stride;
192
193         w8 = FFALIGN(s->plane[i].width  / 8, 8);
194         h8 = FFALIGN(s->plane[i].height / 8, 2);
195         w4 = w8 * 2;
196         h4 = h8 * 2;
197         w2 = w4 * 2;
198         h2 = h4 * 2;
199
200         s->plane[i].idwt_buf =
201             av_malloc_array(height * stride, sizeof(*s->plane[i].idwt_buf));
202         s->plane[i].idwt_tmp =
203             av_malloc_array(height * stride, sizeof(*s->plane[i].idwt_tmp));
204         if (!s->plane[i].idwt_buf || !s->plane[i].idwt_tmp)
205             return AVERROR(ENOMEM);
206
207         s->plane[i].subband[0] = s->plane[i].idwt_buf;
208         s->plane[i].subband[1] = s->plane[i].idwt_buf + 2 * w8 * h8;
209         s->plane[i].subband[2] = s->plane[i].idwt_buf + 1 * w8 * h8;
210         s->plane[i].subband[3] = s->plane[i].idwt_buf + 3 * w8 * h8;
211         s->plane[i].subband[4] = s->plane[i].idwt_buf + 2 * w4 * h4;
212         s->plane[i].subband[5] = s->plane[i].idwt_buf + 1 * w4 * h4;
213         s->plane[i].subband[6] = s->plane[i].idwt_buf + 3 * w4 * h4;
214         s->plane[i].subband[7] = s->plane[i].idwt_buf + 2 * w2 * h2;
215         s->plane[i].subband[8] = s->plane[i].idwt_buf + 1 * w2 * h2;
216         s->plane[i].subband[9] = s->plane[i].idwt_buf + 3 * w2 * h2;
217
218         for (j = 0; j < DWT_LEVELS; j++) {
219             for (k = 0; k < FF_ARRAY_ELEMS(s->plane[i].band[j]); k++) {
220                 s->plane[i].band[j][k].a_width  = w8 << j;
221                 s->plane[i].band[j][k].a_height = h8 << j;
222             }
223         }
224
225         /* ll2 and ll1 commented out because they are done in-place */
226         s->plane[i].l_h[0] = s->plane[i].idwt_tmp;
227         s->plane[i].l_h[1] = s->plane[i].idwt_tmp + 2 * w8 * h8;
228         // s->plane[i].l_h[2] = ll2;
229         s->plane[i].l_h[3] = s->plane[i].idwt_tmp;
230         s->plane[i].l_h[4] = s->plane[i].idwt_tmp + 2 * w4 * h4;
231         // s->plane[i].l_h[5] = ll1;
232         s->plane[i].l_h[6] = s->plane[i].idwt_tmp;
233         s->plane[i].l_h[7] = s->plane[i].idwt_tmp + 2 * w2 * h2;
234     }
235
236     s->a_height = s->coded_height;
237     s->a_width  = s->coded_width;
238     s->a_format = s->coded_format;
239
240     return 0;
241 }
242
243 static int parse_tag(CFHDContext *s, GetByteContext *gb,
244                      int16_t *tag_, uint16_t *value, int *planes)
245 {
246     /* Bit weird but implement the tag parsing as the spec says */
247     uint16_t tagu   = bytestream2_get_be16(gb);
248     int16_t tag     = tagu;
249     int8_t tag8     = tagu >> 8;
250     uint16_t abstag = abs(tag);
251     int8_t abs_tag8 = abs(tag8);
252     uint16_t data   = bytestream2_get_be16(gb);
253     *tag_ = tag;
254     *value = data;
255
256     if (abs_tag8 >= 0x60 && abs_tag8 <= 0x6F) {
257         av_log(s->avctx, AV_LOG_DEBUG, "large len %"PRIX16"\n",
258                ((tagu & 0xFF) << 16) | data);
259         return 0;
260     } else if (abstag >= 0x4000 && abstag <= 0x40FF) {
261         av_log(s->avctx, AV_LOG_DEBUG, "Small chunk length %"PRIu16" %s\n",
262                data * 4, tag < 0 ? "optional" : "required");
263         bytestream2_skipu(gb, data * 4);
264         return 0;
265     }
266
267     switch (tag) {
268     case 1:
269         av_log(s->avctx, AV_LOG_DEBUG, "Sample type? %"PRIu16"\n", data);
270         break;
271     case 2:
272     {
273         int i;
274         av_log(s->avctx, AV_LOG_DEBUG,
275                "tag=2 header - skipping %"PRIu16" tag/value pairs\n", data);
276         if (data > bytestream2_get_bytes_left(gb) / 4) {
277             av_log(s->avctx, AV_LOG_ERROR,
278                    "Too many tag/value pairs (%"PRIu16")\n", data);
279             return AVERROR_INVALIDDATA;
280         }
281         for (i = 0; i < data; i++) {
282             uint16_t tag2 = bytestream2_get_be16(gb);
283             uint16_t val2 = bytestream2_get_be16(gb);
284             av_log(s->avctx, AV_LOG_DEBUG, "Tag/Value = %"PRIX16" %"PRIX16"\n",
285                    tag2, val2);
286         }
287         break;
288     }
289     case 10:
290         if (data != 0) {
291             avpriv_report_missing_feature(s->avctx, "Transform type %"PRIu16, data);
292             return AVERROR_PATCHWELCOME;
293         }
294         av_log(s->avctx, AV_LOG_DEBUG, "Transform-type? %"PRIu16"\n", data);
295         break;
296     case ChannelCount:
297         av_log(s->avctx, AV_LOG_DEBUG, "Channel count: %"PRIu16"\n", data);
298         if (data > 4) {
299             avpriv_report_missing_feature(s->avctx, "Channel count %"PRIu16, data);
300             return AVERROR_PATCHWELCOME;
301         }
302         s->channel_cnt = data;
303         break;
304     case SubbandCount:
305         av_log(s->avctx, AV_LOG_DEBUG, "Subband count: %"PRIu16"\n", data);
306         if (data != SUBBAND_COUNT) {
307             avpriv_report_missing_feature(s->avctx, "Subband count %"PRIu16, data);
308             return AVERROR_PATCHWELCOME;
309         }
310         break;
311     case ImageWidth:
312         av_log(s->avctx, AV_LOG_DEBUG, "Width %"PRIu16"\n", data);
313         s->coded_width = data;
314         break;
315     case ImageHeight:
316         av_log(s->avctx, AV_LOG_DEBUG, "Height %"PRIu16"\n", data);
317         s->coded_height = data;
318         break;
319     case 23:
320         avpriv_report_missing_feature(s->avctx, "Skip frame");
321         return AVERROR_PATCHWELCOME;
322     case 27:
323         av_log(s->avctx, AV_LOG_DEBUG, "Lowpass width %"PRIu16"\n", data);
324         if (data < 2 || data > s->plane[s->channel_num].band[0][0].a_width) {
325             av_log(s->avctx, AV_LOG_ERROR, "Invalid lowpass width\n");
326             return AVERROR_INVALIDDATA;
327         }
328         s->plane[s->channel_num].band[0][0].width  = data;
329         s->plane[s->channel_num].band[0][0].stride = data;
330         break;
331     case 28:
332         av_log(s->avctx, AV_LOG_DEBUG, "Lowpass height %"PRIu16"\n", data);
333         if (data < 2 || data > s->plane[s->channel_num].band[0][0].a_height) {
334             av_log(s->avctx, AV_LOG_ERROR, "Invalid lowpass height\n");
335             return AVERROR_INVALIDDATA;
336         }
337         s->plane[s->channel_num].band[0][0].height = data;
338         break;
339     case LowpassPrecision:
340         av_log(s->avctx, AV_LOG_DEBUG, "Lowpass precision bits: %"PRIu16"\n", data);
341         break;
342     case 41:
343     case 49:
344         av_log(s->avctx, AV_LOG_DEBUG,
345                "Highpass width%s %"PRIu16" channel %i level %i subband %i\n",
346                tag == 49 ? "2" : "", data,
347                s->channel_num, s->level, s->subband_num);
348         if (data < 2) {
349             av_log(s->avctx, AV_LOG_ERROR, "Invalid highpass width%s\n", tag == 49 ? "2" : "");
350             return AVERROR_INVALIDDATA;
351         }
352         s->plane[s->channel_num].band[s->level][s->subband_num].width  = data;
353         s->plane[s->channel_num].band[s->level][s->subband_num].stride = FFALIGN(data, 8);
354         break;
355     case 42:
356     case 50:
357         av_log(s->avctx, AV_LOG_DEBUG, "Highpass height%s %"PRIu16"\n", tag == 50 ? "2" : "", data);
358         if (data < 2) {
359             av_log(s->avctx, AV_LOG_ERROR, "Invalid highpass height%s\n", tag == 50 ? "2" : "");
360             return AVERROR_INVALIDDATA;
361         }
362         s->plane[s->channel_num].band[s->level][s->subband_num].height = data;
363         break;
364     case SubbandNumber:
365         av_log(s->avctx, AV_LOG_DEBUG, "Subband number %"PRIu16"\n", data);
366         if (data > 3) {
367             av_log(s->avctx, AV_LOG_ERROR, "Invalid subband number\n");
368             return AVERROR_INVALIDDATA;
369         }
370         if (s->subband_num != 0 && data == 1) {
371             if (s->level + 1 >= DWT_LEVELS) {
372                 av_log(s->avctx, AV_LOG_ERROR, "Invalid level\n");
373                 return AVERROR_INVALIDDATA;
374             }
375
376             s->level++;
377         }
378         s->subband_num = data;
379         break;
380     case 51:
381         av_log(s->avctx, AV_LOG_DEBUG, "Subband number actual %"PRIu16"\n", data);
382         if (data >= SUBBAND_COUNT) {
383             av_log(s->avctx, AV_LOG_ERROR, "Invalid subband number actual\n");
384             return AVERROR_INVALIDDATA;
385         }
386         s->subband_num_actual = data;
387         break;
388     case Quantization:
389         s->quantisation = data;
390         av_log(s->avctx, AV_LOG_DEBUG, "Quantisation: %"PRIu16"\n", data);
391         break;
392     case ChannelNumber:
393         av_log(s->avctx, AV_LOG_DEBUG, "Channel number %"PRIu16"\n", data);
394         if (data >= *planes) {
395             av_log(s->avctx, AV_LOG_ERROR, "Invalid channel number\n");
396             return AVERROR_INVALIDDATA;
397         }
398         s->channel_num = data;
399         init_plane_defaults(s);
400         break;
401     case 70:
402         av_log(s->avctx, AV_LOG_DEBUG,
403                "Subsampling or bit-depth flag? %"PRIu16"\n", data);
404         if (!(data == 10 || data == 12)) {
405             av_log(s->avctx, AV_LOG_ERROR, "Invalid bits per channel\n");
406             return AVERROR_INVALIDDATA;
407         }
408         s->bpc = data;
409         break;
410     case 71:
411         s->codebook = data;
412         av_log(s->avctx, AV_LOG_DEBUG, "Codebook %i\n", s->codebook);
413         break;
414     case 72:
415         s->codebook = data;
416         av_log(s->avctx, AV_LOG_DEBUG, "Other codebook? %i\n", s->codebook);
417         break;
418     case 84:
419         av_log(s->avctx, AV_LOG_DEBUG, "Sample format? %"PRIu16"\n", data);
420         switch (data) {
421         case 1:
422             s->coded_format = AV_PIX_FMT_YUV422P10;
423             break;
424         case 3:
425             s->coded_format = AV_PIX_FMT_GBRP12;
426             break;
427         case 4:
428             s->coded_format = AV_PIX_FMT_GBRAP12;
429             break;
430         default:
431             avpriv_report_missing_feature(s->avctx, "Sample format %"PRIu16, data);
432             return AVERROR_PATCHWELCOME;
433         }
434         *planes = av_pix_fmt_count_planes(s->coded_format);
435         break;
436     case -85:
437         av_log(s->avctx, AV_LOG_DEBUG, "Cropped height %"PRIu16"\n", data);
438         s->cropped_height = data;
439         break;
440     case 101:
441         av_log(s->avctx, AV_LOG_DEBUG, "Bits per component: %"PRIu16"\n", data);
442         s->bpc = data;
443         break;
444     case PrescaleShift:
445         s->prescale_shift[0] = (data >> 0) & 0x7;
446         s->prescale_shift[1] = (data >> 3) & 0x7;
447         s->prescale_shift[2] = (data >> 6) & 0x7;
448         av_log(s->avctx, AV_LOG_DEBUG, "Prescale shift (VC-5): %"PRIX16"\n", data);
449         break;
450     default:
451         av_log(s->avctx, AV_LOG_DEBUG, "Unknown tag %"PRIu16" data %"PRIX16"\n",
452                tag, data);
453     }
454
455     return 0;
456 }
457
458 static int read_lowpass_coeffs(CFHDContext *s, GetByteContext *gb,
459                                int16_t *coeff_data)
460 {
461     int i, j;
462     int lowpass_height   = s->plane[s->channel_num].band[0][0].height;
463     int lowpass_width    = s->plane[s->channel_num].band[0][0].width;
464     int lowpass_a_height = s->plane[s->channel_num].band[0][0].a_height;
465     int lowpass_a_width  = s->plane[s->channel_num].band[0][0].a_width;
466
467     if (lowpass_height > lowpass_a_height ||
468         lowpass_width  > lowpass_a_width  ||
469         lowpass_a_width * lowpass_a_height * sizeof(*coeff_data) > bytestream2_get_bytes_left(gb)) {
470         av_log(s->avctx, AV_LOG_ERROR, "Too many lowpass coefficients\n");
471         return AVERROR_INVALIDDATA;
472     }
473
474     av_log(s->avctx, AV_LOG_DEBUG,
475            "Start of lowpass coeffs component %d height:%d, width:%d\n",
476            s->channel_num, lowpass_height, lowpass_width);
477     for (i = 0; i < lowpass_height; i++) {
478         for (j = 0; j < lowpass_width; j++)
479             coeff_data[j] = bytestream2_get_be16u(gb);
480
481         coeff_data += lowpass_width;
482     }
483
484     /* Align to mod-4 position to continue reading tags */
485     bytestream2_seek(gb, bytestream2_tell(gb) & 3, SEEK_CUR);
486
487     /* Copy last coefficient line if height is odd. */
488     if (lowpass_height & 1) {
489         int16_t *last_line = &coeff_data[lowpass_height * lowpass_width];
490         memcpy(last_line, &last_line[-lowpass_width],
491                lowpass_width * sizeof(*coeff_data));
492     }
493
494     av_log(s->avctx, AV_LOG_DEBUG, "Lowpass coefficients %i\n",
495            lowpass_width * lowpass_height);
496
497     return 0;
498 }
499
500 #define DECODE_SUBBAND_COEFFS(TABLE, COND)                              \
501     while (1) {                                                         \
502         int level, run, coeff;                                          \
503         BITSTREAM_RL_VLC(level, run, &s->bc, s->TABLE, VLC_BITS, 3);    \
504                                                                         \
505         /* escape */                                                    \
506         if (COND)                                                       \
507             break;                                                      \
508                                                                         \
509         count += run;                                                   \
510                                                                         \
511         if (count > expected) {                                         \
512             av_log(s->avctx, AV_LOG_ERROR, "Escape codeword not found, " \
513                    "probably corrupt data\n");                          \
514             return AVERROR_INVALIDDATA;                                 \
515         }                                                               \
516                                                                         \
517         coeff = dequant_and_decompand(level, s->quantisation);          \
518         for (i = 0; i < run; i++)                                       \
519             *coeff_data++ = coeff;                                      \
520     }                                                                   \
521
522 static int read_highpass_coeffs(CFHDContext *s, GetByteContext *gb,
523                                 int16_t *coeff_data)
524 {
525     int i, ret;
526     int highpass_height       = s->plane[s->channel_num].band[s->level][s->subband_num].height;
527     int highpass_width        = s->plane[s->channel_num].band[s->level][s->subband_num].width;
528     int highpass_a_width      = s->plane[s->channel_num].band[s->level][s->subband_num].a_width;
529     int highpass_a_height     = s->plane[s->channel_num].band[s->level][s->subband_num].a_height;
530     ptrdiff_t highpass_stride = s->plane[s->channel_num].band[s->level][s->subband_num].stride;
531     int expected   = highpass_height   * highpass_stride;
532     int a_expected = highpass_a_height * highpass_a_width;
533     int count = 0;
534     unsigned bytes;
535
536     if (highpass_height > highpass_a_height ||
537         highpass_width  > highpass_a_width  ||
538         a_expected      < expected) {
539         av_log(s->avctx, AV_LOG_ERROR, "Too many highpass coefficients\n");
540         return AVERROR_INVALIDDATA;
541     }
542
543     av_log(s->avctx, AV_LOG_DEBUG,
544            "Start subband coeffs plane %i level %i codebook %i expected %i\n",
545            s->channel_num, s->level, s->codebook, expected);
546
547     if ((ret = bitstream_init8(&s->bc, gb->buffer,
548                                bytestream2_get_bytes_left(gb))) < 0)
549         return ret;
550     if (!s->codebook) {
551         DECODE_SUBBAND_COEFFS(table_9_rl_vlc, level == 64)
552     } else {
553         DECODE_SUBBAND_COEFFS(table_18_rl_vlc, level == 255 && run == 2)
554     }
555
556     bytes = FFALIGN(AV_CEIL_RSHIFT(bitstream_tell(&s->bc), 3), 4);
557     if (bytes > bytestream2_get_bytes_left(gb)) {
558         av_log(s->avctx, AV_LOG_ERROR, "Bitstream overread error\n");
559         return AVERROR_INVALIDDATA;
560     } else
561         bytestream2_seek(gb, bytes, SEEK_CUR);
562
563     av_log(s->avctx, AV_LOG_DEBUG, "End subband coeffs %i extra %i\n",
564            count, count - expected);
565     s->codebook = 0;
566
567     /* Copy last coefficient line if height is odd. */
568     if (highpass_height & 1) {
569         int16_t *last_line = &coeff_data[expected];
570         memcpy(last_line, &last_line[-highpass_stride],
571                highpass_stride * sizeof(*coeff_data));
572     }
573
574     return 0;
575 }
576
577 static int reconstruct_level(CFHDContext *s, AVFrame *pic, int plane, int level)
578 {
579     int i, j, idx = level - 1, idx2 = level > 1 ? 1 : 0;
580     int16_t *low, *high, *output, *dst;
581     int lowpass_height        = s->plane[plane].band[idx][idx2].height;
582     int lowpass_width         = s->plane[plane].band[idx][idx2].width;
583     ptrdiff_t highpass_stride = s->plane[plane].band[idx][1].stride;
584
585     if (lowpass_height                     > s->plane[plane].band[idx][idx2].a_height ||
586         lowpass_width                      > s->plane[plane].band[idx][idx2].a_width  ||
587         s->plane[plane].band[idx][1].width > s->plane[plane].band[idx][1].a_width     ||
588         !highpass_stride) {
589         av_log(s->avctx, AV_LOG_ERROR, "Invalid plane dimensions\n");
590         return AVERROR_INVALIDDATA;
591     }
592
593     av_log(s->avctx, AV_LOG_DEBUG, "Level %d plane %i %i %i %ti\n",
594            level, plane, lowpass_height, lowpass_width, highpass_stride);
595
596     low    = s->plane[plane].subband[0];
597     high   = s->plane[plane].subband[2 + 3 * idx];
598     output = s->plane[plane].l_h[3 * idx];
599     for (i = 0; i < lowpass_width; i++) {
600         vert_filter(output, lowpass_width, low, lowpass_width, high,
601                     highpass_stride, lowpass_height);
602         low++;
603         high++;
604         output++;
605     }
606
607     low    = s->plane[plane].subband[1 + 3 * idx];
608     high   = s->plane[plane].subband[3 + 3 * idx];
609     output = s->plane[plane].l_h[1 + 3 * idx];
610     for (i = 0; i < lowpass_width; i++) {
611         // note the stride of "low" is highpass_stride
612         vert_filter(output, lowpass_width, low, highpass_stride, high,
613                     highpass_stride, lowpass_height);
614         low++;
615         high++;
616         output++;
617     }
618
619     low  = s->plane[plane].l_h[0 + 3 * idx];
620     high = s->plane[plane].l_h[1 + 3 * idx];
621
622     if (level != 3) {
623         output = s->plane[plane].subband[0];
624         for (i = 0; i < lowpass_height * 2; i++) {
625             horiz_filter(output, low, high, lowpass_width);
626             low    += lowpass_width;
627             high   += lowpass_width;
628             output += lowpass_width * 2;
629         }
630         if (s->bpc == 12 || level == 2) {
631             output = s->plane[plane].subband[0];
632             for (i = 0; i < lowpass_height * 2; i++) {
633                 for (j = 0; j < lowpass_width * 2; j++)
634                     output[j] <<= 2;
635
636                 output += lowpass_width * 2;
637             }
638         }
639     } else {
640         int act_plane = plane == 1 ? 2 : plane == 2 ? 1 : plane;
641         dst = (int16_t *)pic->data[act_plane];
642         for (i = 0; i < lowpass_height * 2; i++) {
643             horiz_filter_clip(dst, low, high, lowpass_width, s->bpc);
644             low  += lowpass_width;
645             high += lowpass_width;
646             dst  += pic->linesize[act_plane] / 2;
647         }
648     }
649
650     return 0;
651 }
652
653 static int cfhd_decode(AVCodecContext *avctx, void *data, int *got_frame,
654                        AVPacket *avpkt)
655 {
656     CFHDContext *s = avctx->priv_data;
657     GetByteContext gb;
658     ThreadFrame frame = { .f = data };
659     int ret = 0, planes, plane;
660     int16_t tag;
661     uint16_t value;
662
663     init_frame_defaults(s);
664     planes = av_pix_fmt_count_planes(s->coded_format);
665
666     bytestream2_init(&gb, avpkt->data, avpkt->size);
667
668     while (bytestream2_get_bytes_left(&gb) > 4) {
669         if ((ret = parse_tag(s, &gb, &tag, &value, &planes)) < 0)
670             return ret;
671
672         /* Some kind of end of header tag */
673         if (tag == 4 && value == 0x1A4A)
674             break;
675     }
676
677     if (s->coded_width <= 0 || s->coded_height <= 0 || s->coded_format == AV_PIX_FMT_NONE) {
678         av_log(avctx, AV_LOG_ERROR, "Video dimensions/format missing or invalid\n");
679         return AVERROR_INVALIDDATA;
680     }
681
682     ret = ff_set_dimensions(s->avctx, s->coded_width, s->coded_height);
683     if (ret < 0)
684         return ret;
685     if (s->cropped_height)
686         s->avctx->height = s->cropped_height;
687
688     s->avctx->pix_fmt = s->coded_format;
689
690     if (s->a_width != s->coded_width || s->a_height != s->coded_height ||
691         s->a_format != s->coded_format) {
692         free_buffers(s);
693         if ((ret = alloc_buffers(s)) < 0) {
694             free_buffers(s);
695             return ret;
696         }
697     }
698
699     if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
700         return ret;
701
702     s->coded_width  = 0;
703     s->coded_height = 0;
704     s->coded_format = AV_PIX_FMT_NONE;
705
706     while (bytestream2_get_bytes_left(&gb) > 4) {
707         int16_t *coeff_data;
708
709         if ((ret = parse_tag(s, &gb, &tag, &value, &planes)) < 0)
710             return ret;
711
712         coeff_data = s->plane[s->channel_num].subband[s->subband_num_actual];
713         if (tag == 4 && value == 0x0F0F) {
714             if ((ret = read_lowpass_coeffs(s, &gb, coeff_data)) < 0)
715                 return ret;
716         } else if (tag == 55 && s->subband_num_actual != 255) {
717             if ((ret = read_highpass_coeffs(s, &gb, coeff_data)) < 0)
718                 return ret;
719         }
720     }
721
722     if (s->coded_width || s->coded_height || s->coded_format != AV_PIX_FMT_NONE) {
723         av_log(avctx, AV_LOG_ERROR, "Invalid dimensions\n");
724         return AVERROR_INVALIDDATA;
725     }
726
727     planes = av_pix_fmt_count_planes(avctx->pix_fmt);
728     for (plane = 0; plane < planes; plane++) {
729         /* level 1 */
730         if ((ret = reconstruct_level(s, data, plane, 1)) < 0)
731             return ret;
732
733         /* level 2 */
734         if ((ret = reconstruct_level(s, data, plane, 2)) < 0)
735             return ret;
736
737         /* level 3 */
738         if ((ret = reconstruct_level(s, data, plane, 3)) < 0)
739             return ret;
740     }
741
742     *got_frame = 1;
743     return avpkt->size;
744 }
745
746 static av_cold int cfhd_close(AVCodecContext *avctx)
747 {
748     CFHDContext *s = avctx->priv_data;
749
750     free_buffers(s);
751
752     ff_free_vlc(&s->vlc_9);
753     ff_free_vlc(&s->vlc_18);
754
755     return 0;
756 }
757
758 AVCodec ff_cfhd_decoder = {
759     .name             = "cfhd",
760     .long_name        = NULL_IF_CONFIG_SMALL("Cineform HD"),
761     .type             = AVMEDIA_TYPE_VIDEO,
762     .id               = AV_CODEC_ID_CFHD,
763     .priv_data_size   = sizeof(CFHDContext),
764     .init             = cfhd_init,
765     .init_thread_copy = ONLY_IF_THREADS_ENABLED(cfhd_init),
766     .close            = cfhd_close,
767     .decode           = cfhd_decode,
768     .capabilities     = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS,
769     .caps_internal    = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
770 };