]> git.sesse.net Git - ffmpeg/blob - libavcodec/cfhd.c
avcodec/cfhd: move if/else out of loop in inverse transform
[ffmpeg] / libavcodec / cfhd.c
1 /*
2  * Copyright (c) 2015-2016 Kieran Kunhya <kieran@kunhya.com>
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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 "bytestream.h"
35 #include "get_bits.h"
36 #include "internal.h"
37 #include "thread.h"
38 #include "cfhd.h"
39
40 #define ALPHA_COMPAND_DC_OFFSET 256
41 #define ALPHA_COMPAND_GAIN 9400
42
43 enum CFHDParam {
44     SampleType       =   1,
45     SampleIndexTable =   2,
46     BitstreamMarker  =   4,
47     TransformType    =  10,
48     ChannelCount     =  12,
49     SubbandCount     =  14,
50     ImageWidth       =  20,
51     ImageHeight      =  21,
52     LowpassWidth     =  27,
53     LowpassHeight    =  28,
54     LowpassPrecision =  35,
55     HighpassWidth    =  41,
56     HighpassHeight   =  42,
57     SubbandNumber    =  48,
58     Quantization     =  53,
59     BandHeader       =  55,
60     ChannelNumber    =  62,
61     SampleFlags      =  68,
62     EncodedFormat    =  84,
63     BitsPerComponent = 101,
64     ChannelWidth     = 104,
65     ChannelHeight    = 105,
66     PrescaleShift    = 109,
67 };
68
69
70
71 static av_cold int cfhd_init(AVCodecContext *avctx)
72 {
73     CFHDContext *s = avctx->priv_data;
74
75     avctx->bits_per_raw_sample = 10;
76     s->avctx                   = avctx;
77
78     return ff_cfhd_init_vlcs(s);
79 }
80
81 static void init_plane_defaults(CFHDContext *s)
82 {
83     s->subband_num        = 0;
84     s->level              = 0;
85     s->subband_num_actual = 0;
86 }
87
88 static void init_peak_table_defaults(CFHDContext *s)
89 {
90     s->peak.level  = 0;
91     s->peak.offset = 0;
92     memset(&s->peak.base, 0, sizeof(s->peak.base));
93 }
94
95 static void init_frame_defaults(CFHDContext *s)
96 {
97     s->coded_width       = 0;
98     s->coded_height      = 0;
99     s->cropped_height    = 0;
100     s->bpc               = 10;
101     s->channel_cnt       = 4;
102     s->subband_cnt       = SUBBAND_COUNT;
103     s->channel_num       = 0;
104     s->lowpass_precision = 16;
105     s->quantisation      = 1;
106     s->wavelet_depth     = 3;
107     s->pshift            = 1;
108     s->codebook          = 0;
109     s->difference_coding = 0;
110     s->progressive       = 0;
111     init_plane_defaults(s);
112     init_peak_table_defaults(s);
113 }
114
115 /* TODO: merge with VLC tables or use LUT */
116 static inline int dequant_and_decompand(int level, int quantisation, int codebook)
117 {
118     if (codebook == 0 || codebook == 1) {
119         int64_t abslevel = abs(level);
120         if (level < 264)
121             return (abslevel + ((768 * abslevel * abslevel * abslevel) / (255 * 255 * 255))) *
122                FFSIGN(level) * quantisation;
123         else
124             return level * quantisation;
125     } else
126         return level * quantisation;
127 }
128
129 static inline void difference_coding(int16_t *band, int width, int height)
130 {
131
132     int i,j;
133     for (i = 0; i < height; i++) {
134         for (j = 1; j < width; j++) {
135           band[j] += band[j-1];
136         }
137         band += width;
138     }
139 }
140
141 static inline void peak_table(int16_t *band, Peak *peak, int length)
142 {
143     int i;
144     for (i = 0; i < length; i++)
145         if (abs(band[i]) > peak->level)
146             band[i] = bytestream2_get_le16(&peak->base);
147 }
148
149 static inline void process_alpha(int16_t *alpha, int width)
150 {
151     int i, channel;
152     for (i = 0; i < width; i++) {
153         channel   = alpha[i];
154         channel  -= ALPHA_COMPAND_DC_OFFSET;
155         channel <<= 3;
156         channel  *= ALPHA_COMPAND_GAIN;
157         channel >>= 16;
158         channel   = av_clip_uintp2(channel, 12);
159         alpha[i]  = channel;
160     }
161 }
162
163 static inline void process_bayer(AVFrame *frame)
164 {
165     const int linesize = frame->linesize[0];
166     uint16_t *r = (uint16_t *)frame->data[0];
167     uint16_t *g1 = (uint16_t *)(frame->data[0] + 2);
168     uint16_t *g2 = (uint16_t *)(frame->data[0] + frame->linesize[0]);
169     uint16_t *b = (uint16_t *)(frame->data[0] + frame->linesize[0] + 2);
170     const int mid = 2048;
171
172     for (int y = 0; y < frame->height >> 1; y++) {
173         for (int x = 0; x < frame->width; x += 2) {
174             int R, G1, G2, B;
175             int g, rg, bg, gd;
176
177             g  = r[x];
178             rg = g1[x];
179             bg = g2[x];
180             gd = b[x];
181             gd -= mid;
182
183             R  = (rg - mid) * 2 + g;
184             G1 = g + gd;
185             G2 = g - gd;
186             B  = (bg - mid) * 2 + g;
187
188             R  = av_clip_uintp2(R  * 16, 16);
189             G1 = av_clip_uintp2(G1 * 16, 16);
190             G2 = av_clip_uintp2(G2 * 16, 16);
191             B  = av_clip_uintp2(B  * 16, 16);
192
193             r[x]  = R;
194             g1[x] = G1;
195             g2[x] = G2;
196             b[x]  = B;
197         }
198
199         r  += linesize;
200         g1 += linesize;
201         g2 += linesize;
202         b  += linesize;
203     }
204 }
205
206 static inline void filter(int16_t *output, ptrdiff_t out_stride,
207                           int16_t *low, ptrdiff_t low_stride,
208                           int16_t *high, ptrdiff_t high_stride,
209                           int len, int clip)
210 {
211     int16_t tmp;
212     int i;
213
214     tmp = (11*low[0*low_stride] - 4*low[1*low_stride] + low[2*low_stride] + 4) >> 3;
215     output[(2*0+0)*out_stride] = (tmp + high[0*high_stride]) >> 1;
216     if (clip)
217         output[(2*0+0)*out_stride] = av_clip_uintp2_c(output[(2*0+0)*out_stride], clip);
218
219     tmp = ( 5*low[0*low_stride] + 4*low[1*low_stride] - low[2*low_stride] + 4) >> 3;
220     output[(2*0+1)*out_stride] = (tmp - high[0*high_stride]) >> 1;
221     if (clip)
222         output[(2*0+1)*out_stride] = av_clip_uintp2_c(output[(2*0+1)*out_stride], clip);
223
224     for (i = 1; i < len - 1; i++) {
225         tmp = (low[(i-1)*low_stride] - low[(i+1)*low_stride] + 4) >> 3;
226         output[(2*i+0)*out_stride] = (tmp + low[i*low_stride] + high[i*high_stride]) >> 1;
227         if (clip)
228             output[(2*i+0)*out_stride] = av_clip_uintp2_c(output[(2*i+0)*out_stride], clip);
229
230         tmp = (low[(i+1)*low_stride] - low[(i-1)*low_stride] + 4) >> 3;
231         output[(2*i+1)*out_stride] = (tmp + low[i*low_stride] - high[i*high_stride]) >> 1;
232         if (clip)
233             output[(2*i+1)*out_stride] = av_clip_uintp2_c(output[(2*i+1)*out_stride], clip);
234     }
235
236     tmp = ( 5*low[i*low_stride] + 4*low[(i-1)*low_stride] - low[(i-2)*low_stride] + 4) >> 3;
237     output[(2*i+0)*out_stride] = (tmp + high[i*high_stride]) >> 1;
238     if (clip)
239         output[(2*i+0)*out_stride] = av_clip_uintp2_c(output[(2*i+0)*out_stride], clip);
240
241     tmp = (11*low[i*low_stride] - 4*low[(i-1)*low_stride] + low[(i-2)*low_stride] + 4) >> 3;
242     output[(2*i+1)*out_stride] = (tmp - high[i*high_stride]) >> 1;
243     if (clip)
244         output[(2*i+1)*out_stride] = av_clip_uintp2_c(output[(2*i+1)*out_stride], clip);
245 }
246
247 static inline void interlaced_vertical_filter(int16_t *output, int16_t *low, int16_t *high,
248                          int width, int linesize, int plane)
249 {
250     int i;
251     int16_t even, odd;
252     for (i = 0; i < width; i++) {
253         even = (low[i] - high[i])/2;
254         odd  = (low[i] + high[i])/2;
255         output[i]            = av_clip_uintp2(even, 10);
256         output[i + linesize] = av_clip_uintp2(odd, 10);
257     }
258 }
259 static void horiz_filter(int16_t *output, int16_t *low, int16_t *high,
260                          int width)
261 {
262     filter(output, 1, low, 1, high, 1, width, 0);
263 }
264
265 static void horiz_filter_clip(int16_t *output, int16_t *low, int16_t *high,
266                               int width, int clip)
267 {
268     filter(output, 1, low, 1, high, 1, width, clip);
269 }
270
271 static void horiz_filter_clip_bayer(int16_t *output, int16_t *low, int16_t *high,
272                                     int width, int clip)
273 {
274     filter(output, 2, low, 1, high, 1, width, clip);
275 }
276
277 static void vert_filter(int16_t *output, ptrdiff_t out_stride,
278                         int16_t *low, ptrdiff_t low_stride,
279                         int16_t *high, ptrdiff_t high_stride, int len)
280 {
281     filter(output, out_stride, low, low_stride, high, high_stride, len, 0);
282 }
283
284 static void free_buffers(CFHDContext *s)
285 {
286     int i, j;
287
288     for (i = 0; i < FF_ARRAY_ELEMS(s->plane); i++) {
289         av_freep(&s->plane[i].idwt_buf);
290         av_freep(&s->plane[i].idwt_tmp);
291
292         for (j = 0; j < 9; j++)
293             s->plane[i].subband[j] = NULL;
294
295         for (j = 0; j < 8; j++)
296             s->plane[i].l_h[j] = NULL;
297     }
298     s->a_height = 0;
299     s->a_width  = 0;
300 }
301
302 static int alloc_buffers(AVCodecContext *avctx)
303 {
304     CFHDContext *s = avctx->priv_data;
305     int i, j, ret, planes;
306     int chroma_x_shift, chroma_y_shift;
307     unsigned k;
308
309     if (s->coded_format == AV_PIX_FMT_BAYER_RGGB16) {
310         s->coded_width *= 2;
311         s->coded_height *= 2;
312     }
313
314     if ((ret = ff_set_dimensions(avctx, s->coded_width, s->coded_height)) < 0)
315         return ret;
316     avctx->pix_fmt = s->coded_format;
317
318     if ((ret = av_pix_fmt_get_chroma_sub_sample(s->coded_format,
319                                                 &chroma_x_shift,
320                                                 &chroma_y_shift)) < 0)
321         return ret;
322     planes = av_pix_fmt_count_planes(s->coded_format);
323     if (s->coded_format == AV_PIX_FMT_BAYER_RGGB16) {
324         planes = 4;
325         chroma_x_shift = 1;
326         chroma_y_shift = 1;
327     }
328
329     for (i = 0; i < planes; i++) {
330         int w8, h8, w4, h4, w2, h2;
331         int width  = i ? avctx->width  >> chroma_x_shift : avctx->width;
332         int height = i ? avctx->height >> chroma_y_shift : avctx->height;
333         ptrdiff_t stride = FFALIGN(width  / 8, 8) * 8;
334         if (chroma_y_shift)
335             height = FFALIGN(height / 8, 2) * 8;
336         s->plane[i].width  = width;
337         s->plane[i].height = height;
338         s->plane[i].stride = stride;
339
340         w8 = FFALIGN(s->plane[i].width  / 8, 8);
341         h8 = height / 8;
342         w4 = w8 * 2;
343         h4 = h8 * 2;
344         w2 = w4 * 2;
345         h2 = h4 * 2;
346
347         s->plane[i].idwt_buf =
348             av_mallocz_array(height * stride, sizeof(*s->plane[i].idwt_buf));
349         s->plane[i].idwt_tmp =
350             av_malloc_array(height * stride, sizeof(*s->plane[i].idwt_tmp));
351         if (!s->plane[i].idwt_buf || !s->plane[i].idwt_tmp)
352             return AVERROR(ENOMEM);
353
354         s->plane[i].subband[0] = s->plane[i].idwt_buf;
355         s->plane[i].subband[1] = s->plane[i].idwt_buf + 2 * w8 * h8;
356         s->plane[i].subband[2] = s->plane[i].idwt_buf + 1 * w8 * h8;
357         s->plane[i].subband[3] = s->plane[i].idwt_buf + 3 * w8 * h8;
358         s->plane[i].subband[4] = s->plane[i].idwt_buf + 2 * w4 * h4;
359         s->plane[i].subband[5] = s->plane[i].idwt_buf + 1 * w4 * h4;
360         s->plane[i].subband[6] = s->plane[i].idwt_buf + 3 * w4 * h4;
361         s->plane[i].subband[7] = s->plane[i].idwt_buf + 2 * w2 * h2;
362         s->plane[i].subband[8] = s->plane[i].idwt_buf + 1 * w2 * h2;
363         s->plane[i].subband[9] = s->plane[i].idwt_buf + 3 * w2 * h2;
364
365         for (j = 0; j < DWT_LEVELS; j++) {
366             for (k = 0; k < FF_ARRAY_ELEMS(s->plane[i].band[j]); k++) {
367                 s->plane[i].band[j][k].a_width  = w8 << j;
368                 s->plane[i].band[j][k].a_height = h8 << j;
369             }
370         }
371
372         /* ll2 and ll1 commented out because they are done in-place */
373         s->plane[i].l_h[0] = s->plane[i].idwt_tmp;
374         s->plane[i].l_h[1] = s->plane[i].idwt_tmp + 2 * w8 * h8;
375         // s->plane[i].l_h[2] = ll2;
376         s->plane[i].l_h[3] = s->plane[i].idwt_tmp;
377         s->plane[i].l_h[4] = s->plane[i].idwt_tmp + 2 * w4 * h4;
378         // s->plane[i].l_h[5] = ll1;
379         s->plane[i].l_h[6] = s->plane[i].idwt_tmp;
380         s->plane[i].l_h[7] = s->plane[i].idwt_tmp + 2 * w2 * h2;
381     }
382
383     s->a_height = s->coded_height;
384     s->a_width  = s->coded_width;
385     s->a_format = s->coded_format;
386
387     return 0;
388 }
389
390 static int cfhd_decode(AVCodecContext *avctx, void *data, int *got_frame,
391                        AVPacket *avpkt)
392 {
393     CFHDContext *s = avctx->priv_data;
394     GetByteContext gb;
395     ThreadFrame frame = { .f = data };
396     AVFrame *pic = data;
397     int ret = 0, i, j, planes, plane, got_buffer = 0;
398     int16_t *coeff_data;
399
400     s->coded_format = AV_PIX_FMT_YUV422P10;
401     init_frame_defaults(s);
402     planes = av_pix_fmt_count_planes(s->coded_format);
403
404     bytestream2_init(&gb, avpkt->data, avpkt->size);
405
406     while (bytestream2_get_bytes_left(&gb) > 4) {
407         /* Bit weird but implement the tag parsing as the spec says */
408         uint16_t tagu   = bytestream2_get_be16(&gb);
409         int16_t tag     = (int16_t)tagu;
410         int8_t tag8     = (int8_t)(tagu >> 8);
411         uint16_t abstag = abs(tag);
412         int8_t abs_tag8 = abs(tag8);
413         uint16_t data   = bytestream2_get_be16(&gb);
414         if (abs_tag8 >= 0x60 && abs_tag8 <= 0x6f) {
415             av_log(avctx, AV_LOG_DEBUG, "large len %x\n", ((tagu & 0xff) << 16) | data);
416         } else if (tag == SampleFlags) {
417             av_log(avctx, AV_LOG_DEBUG, "Progressive?%"PRIu16"\n", data);
418             s->progressive = data & 0x0001;
419         } else if (tag == ImageWidth) {
420             av_log(avctx, AV_LOG_DEBUG, "Width %"PRIu16"\n", data);
421             s->coded_width = data;
422         } else if (tag == ImageHeight) {
423             av_log(avctx, AV_LOG_DEBUG, "Height %"PRIu16"\n", data);
424             s->coded_height = data;
425         } else if (tag == 101) {
426             av_log(avctx, AV_LOG_DEBUG, "Bits per component: %"PRIu16"\n", data);
427             if (data < 1 || data > 31) {
428                 av_log(avctx, AV_LOG_ERROR, "Bits per component %d is invalid\n", data);
429                 ret = AVERROR(EINVAL);
430                 break;
431             }
432             s->bpc = data;
433         } else if (tag == ChannelCount) {
434             av_log(avctx, AV_LOG_DEBUG, "Channel Count: %"PRIu16"\n", data);
435             s->channel_cnt = data;
436             if (data > 4) {
437                 av_log(avctx, AV_LOG_ERROR, "Channel Count of %"PRIu16" is unsupported\n", data);
438                 ret = AVERROR_PATCHWELCOME;
439                 break;
440             }
441         } else if (tag == SubbandCount) {
442             av_log(avctx, AV_LOG_DEBUG, "Subband Count: %"PRIu16"\n", data);
443             if (data != SUBBAND_COUNT) {
444                 av_log(avctx, AV_LOG_ERROR, "Subband Count of %"PRIu16" is unsupported\n", data);
445                 ret = AVERROR_PATCHWELCOME;
446                 break;
447             }
448         } else if (tag == ChannelNumber) {
449             s->channel_num = data;
450             av_log(avctx, AV_LOG_DEBUG, "Channel number %"PRIu16"\n", data);
451             if (s->channel_num >= planes) {
452                 av_log(avctx, AV_LOG_ERROR, "Invalid channel number\n");
453                 ret = AVERROR(EINVAL);
454                 break;
455             }
456             init_plane_defaults(s);
457         } else if (tag == SubbandNumber) {
458             if (s->subband_num != 0 && data == 1)  // hack
459                 s->level++;
460             av_log(avctx, AV_LOG_DEBUG, "Subband number %"PRIu16"\n", data);
461             s->subband_num = data;
462             if (s->level >= DWT_LEVELS) {
463                 av_log(avctx, AV_LOG_ERROR, "Invalid level\n");
464                 ret = AVERROR(EINVAL);
465                 break;
466             }
467             if (s->subband_num > 3) {
468                 av_log(avctx, AV_LOG_ERROR, "Invalid subband number\n");
469                 ret = AVERROR(EINVAL);
470                 break;
471             }
472         } else if (tag == 51) {
473             av_log(avctx, AV_LOG_DEBUG, "Subband number actual %"PRIu16"\n", data);
474             s->subband_num_actual = data;
475             if (s->subband_num_actual >= 10) {
476                 av_log(avctx, AV_LOG_ERROR, "Invalid subband number actual\n");
477                 ret = AVERROR(EINVAL);
478                 break;
479             }
480         } else if (tag == LowpassPrecision)
481             av_log(avctx, AV_LOG_DEBUG, "Lowpass precision bits: %"PRIu16"\n", data);
482         else if (tag == Quantization) {
483             s->quantisation = data;
484             av_log(avctx, AV_LOG_DEBUG, "Quantisation: %"PRIu16"\n", data);
485         } else if (tag == PrescaleShift) {
486             s->prescale_shift[0] = (data >> 0) & 0x7;
487             s->prescale_shift[1] = (data >> 3) & 0x7;
488             s->prescale_shift[2] = (data >> 6) & 0x7;
489             av_log(avctx, AV_LOG_DEBUG, "Prescale shift (VC-5): %x\n", data);
490         } else if (tag == LowpassWidth) {
491             av_log(avctx, AV_LOG_DEBUG, "Lowpass width %"PRIu16"\n", data);
492             if (data < 3 || data > s->plane[s->channel_num].band[0][0].a_width) {
493                 av_log(avctx, AV_LOG_ERROR, "Invalid lowpass width\n");
494                 ret = AVERROR(EINVAL);
495                 break;
496             }
497             s->plane[s->channel_num].band[0][0].width  = data;
498             s->plane[s->channel_num].band[0][0].stride = data;
499         } else if (tag == LowpassHeight) {
500             av_log(avctx, AV_LOG_DEBUG, "Lowpass height %"PRIu16"\n", data);
501             if (data < 3 || data > s->plane[s->channel_num].band[0][0].a_height) {
502                 av_log(avctx, AV_LOG_ERROR, "Invalid lowpass height\n");
503                 ret = AVERROR(EINVAL);
504                 break;
505             }
506             s->plane[s->channel_num].band[0][0].height = data;
507         } else if (tag == SampleType)
508             av_log(avctx, AV_LOG_DEBUG, "Sample type? %"PRIu16"\n", data);
509         else if (tag == TransformType) {
510             if (data != 0) {
511                 avpriv_report_missing_feature(avctx, "Transform type of %"PRIu16, data);
512                 ret = AVERROR_PATCHWELCOME;
513                 break;
514             }
515             av_log(avctx, AV_LOG_DEBUG, "Transform-type? %"PRIu16"\n", data);
516         } else if (abstag >= 0x4000 && abstag <= 0x40ff) {
517             if (abstag == 0x4001)
518                 s->peak.level = 0;
519             av_log(avctx, AV_LOG_DEBUG, "Small chunk length %d %s\n", data * 4, tag < 0 ? "optional" : "required");
520             bytestream2_skipu(&gb, data * 4);
521         } else if (tag == 23) {
522             av_log(avctx, AV_LOG_DEBUG, "Skip frame\n");
523             avpriv_report_missing_feature(avctx, "Skip frame");
524             ret = AVERROR_PATCHWELCOME;
525             break;
526         } else if (tag == SampleIndexTable) {
527             av_log(avctx, AV_LOG_DEBUG, "tag=2 header - skipping %i tag/value pairs\n", data);
528             if (data > bytestream2_get_bytes_left(&gb) / 4) {
529                 av_log(avctx, AV_LOG_ERROR, "too many tag/value pairs (%d)\n", data);
530                 ret = AVERROR_INVALIDDATA;
531                 break;
532             }
533             for (i = 0; i < data; i++) {
534                 uint16_t tag2 = bytestream2_get_be16(&gb);
535                 uint16_t val2 = bytestream2_get_be16(&gb);
536                 av_log(avctx, AV_LOG_DEBUG, "Tag/Value = %x %x\n", tag2, val2);
537             }
538         } else if (tag == HighpassWidth) {
539             av_log(avctx, AV_LOG_DEBUG, "Highpass width %i channel %i level %i subband %i\n", data, s->channel_num, s->level, s->subband_num);
540             if (data < 3) {
541                 av_log(avctx, AV_LOG_ERROR, "Invalid highpass width\n");
542                 ret = AVERROR(EINVAL);
543                 break;
544             }
545             s->plane[s->channel_num].band[s->level][s->subband_num].width  = data;
546             s->plane[s->channel_num].band[s->level][s->subband_num].stride = FFALIGN(data, 8);
547         } else if (tag == HighpassHeight) {
548             av_log(avctx, AV_LOG_DEBUG, "Highpass height %i\n", data);
549             if (data < 3) {
550                 av_log(avctx, AV_LOG_ERROR, "Invalid highpass height\n");
551                 ret = AVERROR(EINVAL);
552                 break;
553             }
554             s->plane[s->channel_num].band[s->level][s->subband_num].height = data;
555         } else if (tag == 49) {
556             av_log(avctx, AV_LOG_DEBUG, "Highpass width2 %i\n", data);
557             if (data < 3) {
558                 av_log(avctx, AV_LOG_ERROR, "Invalid highpass width2\n");
559                 ret = AVERROR(EINVAL);
560                 break;
561             }
562             s->plane[s->channel_num].band[s->level][s->subband_num].width  = data;
563             s->plane[s->channel_num].band[s->level][s->subband_num].stride = FFALIGN(data, 8);
564         } else if (tag == 50) {
565             av_log(avctx, AV_LOG_DEBUG, "Highpass height2 %i\n", data);
566             if (data < 3) {
567                 av_log(avctx, AV_LOG_ERROR, "Invalid highpass height2\n");
568                 ret = AVERROR(EINVAL);
569                 break;
570             }
571             s->plane[s->channel_num].band[s->level][s->subband_num].height = data;
572         } else if (tag == 71) {
573             s->codebook = data;
574             av_log(avctx, AV_LOG_DEBUG, "Codebook %i\n", s->codebook);
575         } else if (tag == 72) {
576             s->codebook = data & 0xf;
577             s->difference_coding = (data >> 4) & 1;
578             av_log(avctx, AV_LOG_DEBUG, "Other codebook? %i\n", s->codebook);
579         } else if (tag == 70) {
580             av_log(avctx, AV_LOG_DEBUG, "Subsampling or bit-depth flag? %i\n", data);
581             if (!(data == 10 || data == 12)) {
582                 av_log(avctx, AV_LOG_ERROR, "Invalid bits per channel\n");
583                 ret = AVERROR(EINVAL);
584                 break;
585             }
586             s->bpc = data;
587         } else if (tag == EncodedFormat) {
588             av_log(avctx, AV_LOG_DEBUG, "Sample format? %i\n", data);
589             if (data == 1) {
590                 s->coded_format = AV_PIX_FMT_YUV422P10;
591             } else if (data == 2) {
592                 s->coded_format = AV_PIX_FMT_BAYER_RGGB16;
593             } else if (data == 3) {
594                 s->coded_format = AV_PIX_FMT_GBRP12;
595             } else if (data == 4) {
596                 s->coded_format = AV_PIX_FMT_GBRAP12;
597             } else {
598                 avpriv_report_missing_feature(avctx, "Sample format of %"PRIu16, data);
599                 ret = AVERROR_PATCHWELCOME;
600                 break;
601             }
602             planes = data == 2 ? 4 : av_pix_fmt_count_planes(s->coded_format);
603         } else if (tag == -85) {
604             av_log(avctx, AV_LOG_DEBUG, "Cropped height %"PRIu16"\n", data);
605             s->cropped_height = data;
606         } else if (tag == -75) {
607             s->peak.offset &= ~0xffff;
608             s->peak.offset |= (data & 0xffff);
609             s->peak.base    = gb;
610             s->peak.level   = 0;
611         } else if (tag == -76) {
612             s->peak.offset &= 0xffff;
613             s->peak.offset |= (data & 0xffffU)<<16;
614             s->peak.base    = gb;
615             s->peak.level   = 0;
616         } else if (tag == -74 && s->peak.offset) {
617             s->peak.level = data;
618             bytestream2_seek(&s->peak.base, s->peak.offset - 4, SEEK_CUR);
619         } else
620             av_log(avctx, AV_LOG_DEBUG,  "Unknown tag %i data %x\n", tag, data);
621
622         /* Some kind of end of header tag */
623         if (tag == BitstreamMarker && data == 0x1a4a && s->coded_width && s->coded_height &&
624             s->coded_format != AV_PIX_FMT_NONE) {
625             if (s->a_width != s->coded_width || s->a_height != s->coded_height ||
626                 s->a_format != s->coded_format) {
627                 free_buffers(s);
628                 if ((ret = alloc_buffers(avctx)) < 0) {
629                     free_buffers(s);
630                     return ret;
631                 }
632             }
633             ret = ff_set_dimensions(avctx, s->coded_width, s->coded_height);
634             if (ret < 0)
635                 return ret;
636             if (s->cropped_height) {
637                 unsigned height = s->cropped_height << (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16);
638                 if (avctx->height < height)
639                     return AVERROR_INVALIDDATA;
640                 avctx->height = height;
641             }
642             frame.f->width =
643             frame.f->height = 0;
644
645             if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
646                 return ret;
647
648             s->coded_width = 0;
649             s->coded_height = 0;
650             s->coded_format = AV_PIX_FMT_NONE;
651             got_buffer = 1;
652         }
653         coeff_data = s->plane[s->channel_num].subband[s->subband_num_actual];
654
655         /* Lowpass coefficients */
656         if (tag == BitstreamMarker && data == 0xf0f && s->a_width && s->a_height) {
657             int lowpass_height = s->plane[s->channel_num].band[0][0].height;
658             int lowpass_width  = s->plane[s->channel_num].band[0][0].width;
659             int lowpass_a_height = s->plane[s->channel_num].band[0][0].a_height;
660             int lowpass_a_width  = s->plane[s->channel_num].band[0][0].a_width;
661
662             if (!got_buffer) {
663                 av_log(avctx, AV_LOG_ERROR, "No end of header tag found\n");
664                 ret = AVERROR(EINVAL);
665                 goto end;
666             }
667
668             if (lowpass_height > lowpass_a_height || lowpass_width > lowpass_a_width ||
669                 lowpass_a_width * lowpass_a_height * sizeof(int16_t) > bytestream2_get_bytes_left(&gb)) {
670                 av_log(avctx, AV_LOG_ERROR, "Too many lowpass coefficients\n");
671                 ret = AVERROR(EINVAL);
672                 goto end;
673             }
674
675             av_log(avctx, AV_LOG_DEBUG, "Start of lowpass coeffs component %d height:%d, width:%d\n", s->channel_num, lowpass_height, lowpass_width);
676             for (i = 0; i < lowpass_height; i++) {
677                 for (j = 0; j < lowpass_width; j++)
678                     coeff_data[j] = bytestream2_get_be16u(&gb);
679
680                 coeff_data += lowpass_width;
681             }
682
683             /* Align to mod-4 position to continue reading tags */
684             bytestream2_seek(&gb, bytestream2_tell(&gb) & 3, SEEK_CUR);
685
686             /* Copy last line of coefficients if odd height */
687             if (lowpass_height & 1) {
688                 memcpy(&coeff_data[lowpass_height * lowpass_width],
689                        &coeff_data[(lowpass_height - 1) * lowpass_width],
690                        lowpass_width * sizeof(*coeff_data));
691             }
692
693             av_log(avctx, AV_LOG_DEBUG, "Lowpass coefficients %d\n", lowpass_width * lowpass_height);
694         }
695
696         if (tag == BandHeader && s->subband_num_actual != 255 && s->a_width && s->a_height) {
697             int highpass_height = s->plane[s->channel_num].band[s->level][s->subband_num].height;
698             int highpass_width  = s->plane[s->channel_num].band[s->level][s->subband_num].width;
699             int highpass_a_width = s->plane[s->channel_num].band[s->level][s->subband_num].a_width;
700             int highpass_a_height = s->plane[s->channel_num].band[s->level][s->subband_num].a_height;
701             int highpass_stride = s->plane[s->channel_num].band[s->level][s->subband_num].stride;
702             int expected;
703             int a_expected = highpass_a_height * highpass_a_width;
704             int level, run, coeff;
705             int count = 0, bytes;
706
707             if (!got_buffer) {
708                 av_log(avctx, AV_LOG_ERROR, "No end of header tag found\n");
709                 ret = AVERROR(EINVAL);
710                 goto end;
711             }
712
713             if (highpass_height > highpass_a_height || highpass_width > highpass_a_width || a_expected < highpass_height * (uint64_t)highpass_stride) {
714                 av_log(avctx, AV_LOG_ERROR, "Too many highpass coefficients\n");
715                 ret = AVERROR(EINVAL);
716                 goto end;
717             }
718             expected = highpass_height * highpass_stride;
719
720             av_log(avctx, AV_LOG_DEBUG, "Start subband coeffs plane %i level %i codebook %i expected %i\n", s->channel_num, s->level, s->codebook, expected);
721
722             init_get_bits(&s->gb, gb.buffer, bytestream2_get_bytes_left(&gb) * 8);
723             {
724                 OPEN_READER(re, &s->gb);
725                 if (!s->codebook) {
726                     while (1) {
727                         UPDATE_CACHE(re, &s->gb);
728                         GET_RL_VLC(level, run, re, &s->gb, s->table_9_rl_vlc,
729                                    VLC_BITS, 3, 1);
730
731                         /* escape */
732                         if (level == 64)
733                             break;
734
735                         count += run;
736
737                         if (count > expected)
738                             break;
739
740                         coeff = dequant_and_decompand(level, s->quantisation, 0);
741                         for (i = 0; i < run; i++)
742                             *coeff_data++ = coeff;
743                     }
744                 } else {
745                     while (1) {
746                         UPDATE_CACHE(re, &s->gb);
747                         GET_RL_VLC(level, run, re, &s->gb, s->table_18_rl_vlc,
748                                    VLC_BITS, 3, 1);
749
750                         /* escape */
751                         if (level == 255 && run == 2)
752                             break;
753
754                         count += run;
755
756                         if (count > expected)
757                             break;
758
759                         coeff = dequant_and_decompand(level, s->quantisation, s->codebook);
760                         for (i = 0; i < run; i++)
761                             *coeff_data++ = coeff;
762                     }
763                 }
764                 CLOSE_READER(re, &s->gb);
765             }
766
767             if (count > expected) {
768                 av_log(avctx, AV_LOG_ERROR, "Escape codeword not found, probably corrupt data\n");
769                 ret = AVERROR(EINVAL);
770                 goto end;
771             }
772             if (s->peak.level)
773                 peak_table(coeff_data - count, &s->peak, count);
774             if (s->difference_coding)
775                 difference_coding(s->plane[s->channel_num].subband[s->subband_num_actual], highpass_width, highpass_height);
776
777             bytes = FFALIGN(AV_CEIL_RSHIFT(get_bits_count(&s->gb), 3), 4);
778             if (bytes > bytestream2_get_bytes_left(&gb)) {
779                 av_log(avctx, AV_LOG_ERROR, "Bitstream overread error\n");
780                 ret = AVERROR(EINVAL);
781                 goto end;
782             } else
783                 bytestream2_seek(&gb, bytes, SEEK_CUR);
784
785             av_log(avctx, AV_LOG_DEBUG, "End subband coeffs %i extra %i\n", count, count - expected);
786             s->codebook = 0;
787
788             /* Copy last line of coefficients if odd height */
789             if (highpass_height & 1) {
790                 memcpy(&coeff_data[highpass_height * highpass_stride],
791                        &coeff_data[(highpass_height - 1) * highpass_stride],
792                        highpass_stride * sizeof(*coeff_data));
793             }
794         }
795     }
796
797     if (!s->a_width || !s->a_height || s->a_format == AV_PIX_FMT_NONE ||
798         s->coded_width || s->coded_height || s->coded_format != AV_PIX_FMT_NONE) {
799         av_log(avctx, AV_LOG_ERROR, "Invalid dimensions\n");
800         ret = AVERROR(EINVAL);
801         goto end;
802     }
803
804     if (!got_buffer) {
805         av_log(avctx, AV_LOG_ERROR, "No end of header tag found\n");
806         ret = AVERROR(EINVAL);
807         goto end;
808     }
809
810     planes = av_pix_fmt_count_planes(avctx->pix_fmt);
811     if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16) {
812         if (!s->progressive)
813             return AVERROR_INVALIDDATA;
814         planes = 4;
815     }
816
817     for (plane = 0; plane < planes && !ret; plane++) {
818         /* level 1 */
819         int lowpass_height  = s->plane[plane].band[0][0].height;
820         int lowpass_width   = s->plane[plane].band[0][0].width;
821         int highpass_stride = s->plane[plane].band[0][1].stride;
822         int act_plane = plane == 1 ? 2 : plane == 2 ? 1 : plane;
823         ptrdiff_t dst_linesize;
824         int16_t *low, *high, *output, *dst;
825
826         if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16) {
827             act_plane = 0;
828             dst_linesize = pic->linesize[act_plane];
829         } else {
830             dst_linesize = pic->linesize[act_plane] / 2;
831         }
832
833         if (lowpass_height > s->plane[plane].band[0][0].a_height || lowpass_width > s->plane[plane].band[0][0].a_width ||
834             !highpass_stride || s->plane[plane].band[0][1].width > s->plane[plane].band[0][1].a_width) {
835             av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n");
836             ret = AVERROR(EINVAL);
837             goto end;
838         }
839
840         av_log(avctx, AV_LOG_DEBUG, "Decoding level 1 plane %i %i %i %i\n", plane, lowpass_height, lowpass_width, highpass_stride);
841
842         low    = s->plane[plane].subband[0];
843         high   = s->plane[plane].subband[2];
844         output = s->plane[plane].l_h[0];
845         for (i = 0; i < lowpass_width; i++) {
846             vert_filter(output, lowpass_width, low, lowpass_width, high, highpass_stride, lowpass_height);
847             low++;
848             high++;
849             output++;
850         }
851
852         low    = s->plane[plane].subband[1];
853         high   = s->plane[plane].subband[3];
854         output = s->plane[plane].l_h[1];
855
856         for (i = 0; i < lowpass_width; i++) {
857             // note the stride of "low" is highpass_stride
858             vert_filter(output, lowpass_width, low, highpass_stride, high, highpass_stride, lowpass_height);
859             low++;
860             high++;
861             output++;
862         }
863
864         low    = s->plane[plane].l_h[0];
865         high   = s->plane[plane].l_h[1];
866         output = s->plane[plane].subband[0];
867         for (i = 0; i < lowpass_height * 2; i++) {
868             horiz_filter(output, low, high, lowpass_width);
869             low    += lowpass_width;
870             high   += lowpass_width;
871             output += lowpass_width * 2;
872         }
873         if (s->bpc == 12) {
874             output = s->plane[plane].subband[0];
875             for (i = 0; i < lowpass_height * 2; i++) {
876                 for (j = 0; j < lowpass_width * 2; j++)
877                     output[j] *= 4;
878
879                 output += lowpass_width * 2;
880             }
881         }
882
883         /* level 2 */
884         lowpass_height  = s->plane[plane].band[1][1].height;
885         lowpass_width   = s->plane[plane].band[1][1].width;
886         highpass_stride = s->plane[plane].band[1][1].stride;
887
888         if (lowpass_height > s->plane[plane].band[1][1].a_height || lowpass_width > s->plane[plane].band[1][1].a_width ||
889             !highpass_stride || s->plane[plane].band[1][1].width > s->plane[plane].band[1][1].a_width) {
890             av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n");
891             ret = AVERROR(EINVAL);
892             goto end;
893         }
894
895         av_log(avctx, AV_LOG_DEBUG, "Level 2 plane %i %i %i %i\n", plane, lowpass_height, lowpass_width, highpass_stride);
896
897         low    = s->plane[plane].subband[0];
898         high   = s->plane[plane].subband[5];
899         output = s->plane[plane].l_h[3];
900         for (i = 0; i < lowpass_width; i++) {
901             vert_filter(output, lowpass_width, low, lowpass_width, high, highpass_stride, lowpass_height);
902             low++;
903             high++;
904             output++;
905         }
906
907         low    = s->plane[plane].subband[4];
908         high   = s->plane[plane].subband[6];
909         output = s->plane[plane].l_h[4];
910         for (i = 0; i < lowpass_width; i++) {
911             vert_filter(output, lowpass_width, low, highpass_stride, high, highpass_stride, lowpass_height);
912             low++;
913             high++;
914             output++;
915         }
916
917         low    = s->plane[plane].l_h[3];
918         high   = s->plane[plane].l_h[4];
919         output = s->plane[plane].subband[0];
920         for (i = 0; i < lowpass_height * 2; i++) {
921             horiz_filter(output, low, high, lowpass_width);
922             low    += lowpass_width;
923             high   += lowpass_width;
924             output += lowpass_width * 2;
925         }
926
927         output = s->plane[plane].subband[0];
928         for (i = 0; i < lowpass_height * 2; i++) {
929             for (j = 0; j < lowpass_width * 2; j++)
930                 output[j] *= 4;
931
932             output += lowpass_width * 2;
933         }
934
935         /* level 3 */
936         lowpass_height  = s->plane[plane].band[2][1].height;
937         lowpass_width   = s->plane[plane].band[2][1].width;
938         highpass_stride = s->plane[plane].band[2][1].stride;
939
940         if (lowpass_height > s->plane[plane].band[2][1].a_height || lowpass_width > s->plane[plane].band[2][1].a_width ||
941             !highpass_stride || s->plane[plane].band[2][1].width > s->plane[plane].band[2][1].a_width) {
942             av_log(avctx, AV_LOG_ERROR, "Invalid plane dimensions\n");
943             ret = AVERROR(EINVAL);
944             goto end;
945         }
946
947         av_log(avctx, AV_LOG_DEBUG, "Level 3 plane %i %i %i %i\n", plane, lowpass_height, lowpass_width, highpass_stride);
948         if (s->progressive) {
949             low    = s->plane[plane].subband[0];
950             high   = s->plane[plane].subband[8];
951             output = s->plane[plane].l_h[6];
952             for (i = 0; i < lowpass_width; i++) {
953                 vert_filter(output, lowpass_width, low, lowpass_width, high, highpass_stride, lowpass_height);
954                 low++;
955                 high++;
956                 output++;
957             }
958
959             low    = s->plane[plane].subband[7];
960             high   = s->plane[plane].subband[9];
961             output = s->plane[plane].l_h[7];
962             for (i = 0; i < lowpass_width; i++) {
963                 vert_filter(output, lowpass_width, low, highpass_stride, high, highpass_stride, lowpass_height);
964                 low++;
965                 high++;
966                 output++;
967             }
968
969             dst = (int16_t *)pic->data[act_plane];
970             if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16) {
971                 if (plane & 1)
972                     dst++;
973                 if (plane > 1)
974                     dst += pic->linesize[act_plane] >> 1;
975             }
976             low  = s->plane[plane].l_h[6];
977             high = s->plane[plane].l_h[7];
978
979             if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16 &&
980                 (lowpass_height * 2 > avctx->coded_height / 2 ||
981                  lowpass_width  * 2 > avctx->coded_width  / 2    )
982                 ) {
983                 ret = AVERROR_INVALIDDATA;
984                 goto end;
985             }
986
987             for (i = 0; i < lowpass_height * 2; i++) {
988                 if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16)
989                     horiz_filter_clip_bayer(dst, low, high, lowpass_width, s->bpc);
990                 else
991                     horiz_filter_clip(dst, low, high, lowpass_width, s->bpc);
992                 if (avctx->pix_fmt == AV_PIX_FMT_GBRAP12 && act_plane == 3)
993                     process_alpha(dst, lowpass_width * 2);
994                 low  += lowpass_width;
995                 high += lowpass_width;
996                 dst  += dst_linesize;
997             }
998         } else {
999             av_log(avctx, AV_LOG_DEBUG, "interlaced frame ? %d", pic->interlaced_frame);
1000             pic->interlaced_frame = 1;
1001             low    = s->plane[plane].subband[0];
1002             high   = s->plane[plane].subband[7];
1003             output = s->plane[plane].l_h[6];
1004             for (i = 0; i < lowpass_height; i++) {
1005                 horiz_filter(output, low, high, lowpass_width);
1006                 low    += lowpass_width;
1007                 high   += lowpass_width;
1008                 output += lowpass_width * 2;
1009             }
1010
1011             low    = s->plane[plane].subband[8];
1012             high   = s->plane[plane].subband[9];
1013             output = s->plane[plane].l_h[7];
1014             for (i = 0; i < lowpass_height; i++) {
1015                 horiz_filter(output, low, high, lowpass_width);
1016                 low    += lowpass_width;
1017                 high   += lowpass_width;
1018                 output += lowpass_width * 2;
1019             }
1020
1021             dst  = (int16_t *)pic->data[act_plane];
1022             low  = s->plane[plane].l_h[6];
1023             high = s->plane[plane].l_h[7];
1024             for (i = 0; i < lowpass_height; i++) {
1025                 interlaced_vertical_filter(dst, low, high, lowpass_width * 2,  pic->linesize[act_plane]/2, act_plane);
1026                 low  += lowpass_width * 2;
1027                 high += lowpass_width * 2;
1028                 dst  += pic->linesize[act_plane];
1029             }
1030         }
1031     }
1032
1033
1034     if (avctx->pix_fmt == AV_PIX_FMT_BAYER_RGGB16)
1035         process_bayer(pic);
1036 end:
1037     if (ret < 0)
1038         return ret;
1039
1040     *got_frame = 1;
1041     return avpkt->size;
1042 }
1043
1044 static av_cold int cfhd_close(AVCodecContext *avctx)
1045 {
1046     CFHDContext *s = avctx->priv_data;
1047
1048     free_buffers(s);
1049
1050     ff_free_vlc(&s->vlc_9);
1051     ff_free_vlc(&s->vlc_18);
1052
1053     return 0;
1054 }
1055
1056 AVCodec ff_cfhd_decoder = {
1057     .name             = "cfhd",
1058     .long_name        = NULL_IF_CONFIG_SMALL("Cineform HD"),
1059     .type             = AVMEDIA_TYPE_VIDEO,
1060     .id               = AV_CODEC_ID_CFHD,
1061     .priv_data_size   = sizeof(CFHDContext),
1062     .init             = cfhd_init,
1063     .close            = cfhd_close,
1064     .decode           = cfhd_decode,
1065     .capabilities     = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS,
1066     .caps_internal    = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
1067 };