]> git.sesse.net Git - ffmpeg/blob - libavcodec/proresdec_lgpl.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / proresdec_lgpl.c
1 /*
2  * Apple ProRes compatible decoder
3  *
4  * Copyright (c) 2010-2011 Maxim Poliakovski
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * This is a decoder for Apple ProRes 422 SD/HQ/LT/Proxy and ProRes 4444.
26  * It is used for storing and editing high definition video data in Apple's Final Cut Pro.
27  *
28  * @see http://wiki.multimedia.cx/index.php?title=Apple_ProRes
29  */
30
31 #define A32_BITSTREAM_READER // some ProRes vlc codes require up to 28 bits to be read at once
32
33 #include <stdint.h>
34
35 #include "libavutil/intmath.h"
36 #include "avcodec.h"
37 #include "dsputil.h"
38 #include "get_bits.h"
39
40 #define BITS_PER_SAMPLE 10                              ///< output precision of that decoder
41 #define BIAS     (1 << (BITS_PER_SAMPLE - 1))           ///< bias value for converting signed pixels into unsigned ones
42 #define CLIP_MIN (1 << (BITS_PER_SAMPLE - 8))           ///< minimum value for clipping resulting pixels
43 #define CLIP_MAX (1 << BITS_PER_SAMPLE) - CLIP_MIN - 1  ///< maximum value for clipping resulting pixels
44
45
46 typedef struct {
47     DSPContext dsp;
48     AVFrame    picture;
49     ScanTable  scantable;
50     int        scantable_type;           ///< -1 = uninitialized, 0 = progressive, 1/2 = interlaced
51
52     int        frame_type;               ///< 0 = progressive, 1 = top-field first, 2 = bottom-field first
53     int        pic_format;               ///< 2 = 422, 3 = 444
54     uint8_t    qmat_luma[64];            ///< dequantization matrix for luma
55     uint8_t    qmat_chroma[64];          ///< dequantization matrix for chroma
56     int        qmat_changed;             ///< 1 - global quantization matrices changed
57     int        prev_slice_sf;            ///< scalefactor of the previous decoded slice
58     DECLARE_ALIGNED(16, int16_t, qmat_luma_scaled[64]);
59     DECLARE_ALIGNED(16, int16_t, qmat_chroma_scaled[64]);
60     DECLARE_ALIGNED(16, DCTELEM, blocks[8 * 4 * 64]);
61     int        total_slices;            ///< total number of slices in a picture
62     const uint8_t **slice_data_index;   ///< array of pointers to the data of each slice
63     int        chroma_factor;
64     int        mb_chroma_factor;
65     int        num_chroma_blocks;       ///< number of chrominance blocks in a macroblock
66     int        num_x_slices;
67     int        num_y_slices;
68     int        slice_width_factor;
69     int        slice_height_factor;
70     int        num_x_mbs;
71     int        num_y_mbs;
72 } ProresContext;
73
74
75 static const uint8_t progressive_scan[64] = {
76      0,  1,  8,  9,  2,  3, 10, 11,
77     16, 17, 24, 25, 18, 19, 26, 27,
78      4,  5, 12, 20, 13,  6,  7, 14,
79     21, 28, 29, 22, 15, 23, 30, 31,
80     32, 33, 40, 48, 41, 34, 35, 42,
81     49, 56, 57, 50, 43, 36, 37, 44,
82     51, 58, 59, 52, 45, 38, 39, 46,
83     53, 60, 61, 54, 47, 55, 62, 63
84 };
85
86 static const uint8_t interlaced_scan[64] = {
87      0,  8,  1,  9, 16, 24, 17, 25,
88      2, 10,  3, 11, 18, 26, 19, 27,
89     32, 40, 33, 34, 41, 48, 56, 49,
90     42, 35, 43, 50, 57, 58, 51, 59,
91      4, 12,  5,  6, 13, 20, 28, 21,
92     14,  7, 15, 22, 29, 36, 44, 37,
93     30, 23, 31, 38, 45, 52, 60, 53,
94     46, 39, 47, 54, 61, 62, 55, 63
95 };
96
97
98 static av_cold int decode_init(AVCodecContext *avctx)
99 {
100     ProresContext *ctx = avctx->priv_data;
101
102     ctx->total_slices     = 0;
103     ctx->slice_data_index = 0;
104
105     avctx->pix_fmt = PIX_FMT_YUV422P10; // set default pixel format
106
107     avctx->bits_per_raw_sample = BITS_PER_SAMPLE;
108     dsputil_init(&ctx->dsp, avctx);
109
110     avctx->coded_frame = &ctx->picture;
111     avcodec_get_frame_defaults(&ctx->picture);
112     ctx->picture.type      = AV_PICTURE_TYPE_I;
113     ctx->picture.key_frame = 1;
114
115     ctx->scantable_type = -1;   // set scantable type to uninitialized
116     memset(ctx->qmat_luma, 4, 64);
117     memset(ctx->qmat_chroma, 4, 64);
118     ctx->prev_slice_sf = 0;
119
120     return 0;
121 }
122
123
124 static int decode_frame_header(ProresContext *ctx, const uint8_t *buf,
125                                const int data_size, AVCodecContext *avctx)
126 {
127     int hdr_size, version, width, height, flags;
128     const uint8_t *ptr;
129
130     hdr_size = AV_RB16(buf);
131     if (hdr_size > data_size) {
132         av_log(avctx, AV_LOG_ERROR, "frame data too small\n");
133         return AVERROR_INVALIDDATA;
134     }
135
136     version = AV_RB16(buf + 2);
137     if (version >= 2) {
138         av_log(avctx, AV_LOG_ERROR,
139                "unsupported header version: %d\n", version);
140         return AVERROR_INVALIDDATA;
141     }
142
143     width  = AV_RB16(buf + 8);
144     height = AV_RB16(buf + 10);
145     if (width != avctx->width || height != avctx->height) {
146         av_log(avctx, AV_LOG_ERROR,
147                "picture dimension changed: old: %d x %d, new: %d x %d\n",
148                avctx->width, avctx->height, width, height);
149         return AVERROR_INVALIDDATA;
150     }
151
152     ctx->frame_type = (buf[12] >> 2) & 3;
153     if (ctx->frame_type > 2) {
154         av_log(avctx, AV_LOG_ERROR,
155                "unsupported frame type: %d\n", ctx->frame_type);
156         return AVERROR_INVALIDDATA;
157     }
158
159     ctx->chroma_factor     = (buf[12] >> 6) & 3;
160     ctx->mb_chroma_factor  = ctx->chroma_factor + 2;
161     ctx->num_chroma_blocks = (1 << ctx->chroma_factor) >> 1;
162     switch (ctx->chroma_factor) {
163     case 2:
164         avctx->pix_fmt = PIX_FMT_YUV422P10;
165         break;
166     case 3:
167         avctx->pix_fmt = PIX_FMT_YUV444P10;
168         break;
169     default:
170         av_log(avctx, AV_LOG_ERROR,
171                "unsupported picture format: %d\n", ctx->pic_format);
172         return AVERROR_INVALIDDATA;
173     }
174
175     if (ctx->scantable_type != ctx->frame_type) {
176         if (!ctx->frame_type)
177             ff_init_scantable(ctx->dsp.idct_permutation, &ctx->scantable,
178                               progressive_scan);
179         else
180             ff_init_scantable(ctx->dsp.idct_permutation, &ctx->scantable,
181                               interlaced_scan);
182         ctx->scantable_type = ctx->frame_type;
183     }
184
185     if (ctx->frame_type) {      /* if interlaced */
186         ctx->picture.interlaced_frame = 1;
187         ctx->picture.top_field_first  = ctx->frame_type & 1;
188     }
189
190     ctx->qmat_changed = 0;
191     ptr   = buf + 20;
192     flags = buf[19];
193     if (flags & 2) {
194         if (ptr - buf > hdr_size - 64) {
195             av_log(avctx, AV_LOG_ERROR, "header data too small\n");
196             return AVERROR_INVALIDDATA;
197         }
198         if (memcmp(ctx->qmat_luma, ptr, 64)) {
199             memcpy(ctx->qmat_luma, ptr, 64);
200             ctx->qmat_changed = 1;
201         }
202         ptr += 64;
203     } else {
204         memset(ctx->qmat_luma, 4, 64);
205         ctx->qmat_changed = 1;
206     }
207
208     if (flags & 1) {
209         if (ptr - buf > hdr_size - 64) {
210             av_log(avctx, AV_LOG_ERROR, "header data too small\n");
211             return -1;
212         }
213         if (memcmp(ctx->qmat_chroma, ptr, 64)) {
214             memcpy(ctx->qmat_chroma, ptr, 64);
215             ctx->qmat_changed = 1;
216         }
217     } else {
218         memset(ctx->qmat_chroma, 4, 64);
219         ctx->qmat_changed = 1;
220     }
221
222     return hdr_size;
223 }
224
225
226 static int decode_picture_header(ProresContext *ctx, const uint8_t *buf,
227                                  const int data_size, AVCodecContext *avctx)
228 {
229     int   i, hdr_size, pic_data_size, num_slices;
230     int   slice_width_factor, slice_height_factor;
231     int   remainder, num_x_slices;
232     const uint8_t *data_ptr, *index_ptr;
233
234     hdr_size = data_size > 0 ? buf[0] >> 3 : 0;
235     if (hdr_size < 8 || hdr_size > data_size) {
236         av_log(avctx, AV_LOG_ERROR, "picture header too small\n");
237         return AVERROR_INVALIDDATA;
238     }
239
240     pic_data_size = AV_RB32(buf + 1);
241     if (pic_data_size > data_size) {
242         av_log(avctx, AV_LOG_ERROR, "picture data too small\n");
243         return AVERROR_INVALIDDATA;
244     }
245
246     slice_width_factor  = buf[7] >> 4;
247     slice_height_factor = buf[7] & 0xF;
248     if (slice_width_factor > 3 || slice_height_factor) {
249         av_log(avctx, AV_LOG_ERROR,
250                "unsupported slice dimension: %d x %d\n",
251                1 << slice_width_factor, 1 << slice_height_factor);
252         return AVERROR_INVALIDDATA;
253     }
254
255     ctx->slice_width_factor  = slice_width_factor;
256     ctx->slice_height_factor = slice_height_factor;
257
258     ctx->num_x_mbs = (avctx->width + 15) >> 4;
259     ctx->num_y_mbs = (avctx->height +
260                       (1 << (4 + ctx->picture.interlaced_frame)) - 1) >>
261                      (4 + ctx->picture.interlaced_frame);
262
263     remainder    = ctx->num_x_mbs & ((1 << slice_width_factor) - 1);
264     num_x_slices = (ctx->num_x_mbs >> slice_width_factor) + (remainder & 1) +
265                    ((remainder >> 1) & 1) + ((remainder >> 2) & 1);
266
267     num_slices = num_x_slices * ctx->num_y_mbs;
268     if (num_slices != AV_RB16(buf + 5)) {
269         av_log(avctx, AV_LOG_ERROR, "invalid number of slices\n");
270         return AVERROR_INVALIDDATA;
271     }
272
273     if (ctx->total_slices != num_slices) {
274         av_freep(&ctx->slice_data_index);
275         ctx->slice_data_index = av_malloc((num_slices + 1) * sizeof(uint8_t*));
276         if (!ctx->slice_data_index)
277             return AVERROR(ENOMEM);
278         ctx->total_slices = num_slices;
279     }
280
281     if (hdr_size + num_slices * 2 > data_size) {
282         av_log(avctx, AV_LOG_ERROR, "slice table too small\n");
283         return AVERROR_INVALIDDATA;
284     }
285
286     /* parse slice table allowing quick access to the slice data */
287     index_ptr = buf + hdr_size;
288     data_ptr = index_ptr + num_slices * 2;
289
290     for (i = 0; i < num_slices; i++) {
291         ctx->slice_data_index[i] = data_ptr;
292         data_ptr += AV_RB16(index_ptr + i * 2);
293     }
294     ctx->slice_data_index[i] = data_ptr;
295
296     if (data_ptr > buf + data_size) {
297         av_log(avctx, AV_LOG_ERROR, "out of slice data\n");
298         return -1;
299     }
300
301     return pic_data_size;
302 }
303
304
305 /**
306  * Read an unsigned rice/exp golomb codeword.
307  */
308 static inline int decode_vlc_codeword(GetBitContext *gb, uint8_t codebook)
309 {
310     unsigned int rice_order, exp_order, switch_bits;
311     unsigned int buf, code;
312     int log, prefix_len, len;
313
314     OPEN_READER(re, gb);
315     UPDATE_CACHE(re, gb);
316     buf = GET_CACHE(re, gb);
317
318     /* number of prefix bits to switch between Rice and expGolomb */
319     switch_bits = (codebook & 3) + 1;
320     rice_order  = codebook >> 5;        /* rice code order */
321     exp_order   = (codebook >> 2) & 7;  /* exp golomb code order */
322
323     log = 31 - av_log2(buf); /* count prefix bits (zeroes) */
324
325     if (log < switch_bits) { /* ok, we got a rice code */
326         if (!rice_order) {
327             /* shortcut for faster decoding of rice codes without remainder */
328             code = log;
329             LAST_SKIP_BITS(re, gb, log + 1);
330         } else {
331             prefix_len = log + 1;
332             code = (log << rice_order) + NEG_USR32(buf << prefix_len, rice_order);
333             LAST_SKIP_BITS(re, gb, prefix_len + rice_order);
334         }
335     } else { /* otherwise we got a exp golomb code */
336         len  = (log << 1) - switch_bits + exp_order + 1;
337         code = NEG_USR32(buf, len) - (1 << exp_order) + (switch_bits << rice_order);
338         LAST_SKIP_BITS(re, gb, len);
339     }
340
341     CLOSE_READER(re, gb);
342
343     return code;
344 }
345
346 #define LSB2SIGN(x) (-((x) & 1))
347 #define TOSIGNED(x) (((x) >> 1) ^ LSB2SIGN(x))
348
349 #define FIRST_DC_CB 0xB8 // rice_order = 5, exp_golomb_order = 6, switch_bits = 0
350
351 static uint8_t dc_codebook[4] = {
352     0x04, // rice_order = 0, exp_golomb_order = 1, switch_bits = 0
353     0x28, // rice_order = 1, exp_golomb_order = 2, switch_bits = 0
354     0x4D, // rice_order = 2, exp_golomb_order = 3, switch_bits = 1
355     0x70  // rice_order = 3, exp_golomb_order = 4, switch_bits = 0
356 };
357
358
359 /**
360  * Decode DC coefficients for all blocks in a slice.
361  */
362 static inline void decode_dc_coeffs(GetBitContext *gb, DCTELEM *out,
363                                     int nblocks)
364 {
365     DCTELEM prev_dc;
366     int     i, sign;
367     int16_t delta;
368     unsigned int code;
369
370     code   = decode_vlc_codeword(gb, FIRST_DC_CB);
371     out[0] = prev_dc = TOSIGNED(code);
372
373     out   += 64; /* move to the DC coeff of the next block */
374     delta  = 3;
375
376     for (i = 1; i < nblocks; i++, out += 64) {
377         code = decode_vlc_codeword(gb, dc_codebook[FFMIN(FFABS(delta), 3)]);
378
379         sign     = -(((delta >> 15) & 1) ^ (code & 1));
380         delta    = (((code + 1) >> 1) ^ sign) - sign;
381         prev_dc += delta;
382         out[0]   = prev_dc;
383     }
384 }
385
386
387 static uint8_t ac_codebook[7] = {
388     0x04, // rice_order = 0, exp_golomb_order = 1, switch_bits = 0
389     0x28, // rice_order = 1, exp_golomb_order = 2, switch_bits = 0
390     0x4C, // rice_order = 2, exp_golomb_order = 3, switch_bits = 0
391     0x05, // rice_order = 0, exp_golomb_order = 1, switch_bits = 1
392     0x29, // rice_order = 1, exp_golomb_order = 2, switch_bits = 1
393     0x06, // rice_order = 0, exp_golomb_order = 1, switch_bits = 2
394     0x0A, // rice_order = 0, exp_golomb_order = 2, switch_bits = 2
395 };
396
397 /**
398  * Lookup tables for adaptive switching between codebooks
399  * according with previous run/level value.
400  */
401 static uint8_t run_to_cb_index[16] =
402     { 5, 5, 3, 3, 0, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 2 };
403
404 static uint8_t lev_to_cb_index[10] = { 0, 6, 3, 5, 0, 1, 1, 1, 1, 2 };
405
406
407 /**
408  * Decode AC coefficients for all blocks in a slice.
409  */
410 static inline void decode_ac_coeffs(GetBitContext *gb, DCTELEM *out,
411                                     int blocks_per_slice,
412                                     int plane_size_factor,
413                                     const uint8_t *scan)
414 {
415     int pos, block_mask, run, level, sign, run_cb_index, lev_cb_index;
416     int max_coeffs, bits_left;
417
418     /* set initial prediction values */
419     run   = 4;
420     level = 2;
421
422     max_coeffs = blocks_per_slice << 6;
423     block_mask = blocks_per_slice - 1;
424
425     for (pos = blocks_per_slice - 1; pos < max_coeffs;) {
426         run_cb_index = run_to_cb_index[FFMIN(run, 15)];
427         lev_cb_index = lev_to_cb_index[FFMIN(level, 9)];
428
429         bits_left = get_bits_left(gb);
430         if (bits_left <= 0 || (bits_left <= 8 && !show_bits(gb, bits_left)))
431             return;
432
433         run = decode_vlc_codeword(gb, ac_codebook[run_cb_index]);
434
435         bits_left = get_bits_left(gb);
436         if (bits_left <= 0 || (bits_left <= 8 && !show_bits(gb, bits_left)))
437             return;
438
439         level = decode_vlc_codeword(gb, ac_codebook[lev_cb_index]) + 1;
440
441         pos += run + 1;
442         if (pos >= max_coeffs)
443             break;
444
445         sign = get_sbits(gb, 1);
446         out[((pos & block_mask) << 6) + scan[pos >> plane_size_factor]] =
447             (level ^ sign) - sign;
448     }
449 }
450
451
452 #define CLIP_AND_BIAS(x) (av_clip((x) + BIAS, CLIP_MIN, CLIP_MAX))
453
454 /**
455  * Add bias value, clamp and output pixels of a slice
456  */
457 static void put_pixels(const DCTELEM *in, uint16_t *out, int stride,
458                        int mbs_per_slice, int blocks_per_mb)
459 {
460     int mb, x, y, src_offset, dst_offset;
461     const DCTELEM *src1, *src2;
462     uint16_t *dst1, *dst2;
463
464     src1 = in;
465     src2 = in + (blocks_per_mb << 5);
466     dst1 = out;
467     dst2 = out + (stride << 3);
468
469     for (mb = 0; mb < mbs_per_slice; mb++) {
470         for (y = 0, dst_offset = 0; y < 8; y++, dst_offset += stride) {
471             for (x = 0; x < 8; x++) {
472                 src_offset = (y << 3) + x;
473
474                 dst1[dst_offset + x] = CLIP_AND_BIAS(src1[src_offset]);
475                 dst2[dst_offset + x] = CLIP_AND_BIAS(src2[src_offset]);
476
477                 if (blocks_per_mb > 2) {
478                     dst1[dst_offset + x + 8] =
479                         CLIP_AND_BIAS(src1[src_offset + 64]);
480                     dst2[dst_offset + x + 8] =
481                         CLIP_AND_BIAS(src2[src_offset + 64]);
482                 }
483             }
484         }
485
486         src1 += blocks_per_mb << 6;
487         src2 += blocks_per_mb << 6;
488         dst1 += blocks_per_mb << 2;
489         dst2 += blocks_per_mb << 2;
490     }
491 }
492
493
494 /**
495  * Decode a slice plane (luma or chroma).
496  */
497 static void decode_slice_plane(ProresContext *ctx, const uint8_t *buf,
498                                int data_size, uint16_t *out_ptr,
499                                int linesize, int mbs_per_slice,
500                                int blocks_per_mb, int plane_size_factor,
501                                const int16_t *qmat)
502 {
503     GetBitContext gb;
504     DCTELEM *block_ptr;
505     int i, blk_num, blocks_per_slice;
506
507     blocks_per_slice = mbs_per_slice * blocks_per_mb;
508
509     memset(ctx->blocks, 0, 8 * 4 * 64 * sizeof(*ctx->blocks));
510
511     init_get_bits(&gb, buf, data_size << 3);
512
513     decode_dc_coeffs(&gb, ctx->blocks, blocks_per_slice);
514
515     decode_ac_coeffs(&gb, ctx->blocks, blocks_per_slice,
516                      plane_size_factor, ctx->scantable.permutated);
517
518     /* inverse quantization, inverse transform and output */
519     block_ptr = ctx->blocks;
520
521     for (blk_num = 0; blk_num < blocks_per_slice; blk_num++, block_ptr += 64) {
522         /* TODO: the correct solution shoud be (block_ptr[i] * qmat[i]) >> 1
523          * and the input of the inverse transform should be scaled by 2
524          * in order to avoid rounding errors.
525          * Due to the fact the existing Libav transforms are incompatible with
526          * that input I temporally introduced the coarse solution below... */
527         for (i = 0; i < 64; i++)
528             block_ptr[i] = (block_ptr[i] * qmat[i]) >> 2;
529
530         ctx->dsp.idct(block_ptr);
531     }
532
533     put_pixels(ctx->blocks, out_ptr, linesize >> 1, mbs_per_slice,
534                blocks_per_mb);
535 }
536
537
538 static int decode_slice(ProresContext *ctx, int pic_num, int slice_num,
539                         int mb_x_pos, int mb_y_pos, int mbs_per_slice,
540                         AVCodecContext *avctx)
541 {
542     const uint8_t *buf;
543     uint8_t *y_data, *u_data, *v_data;
544     AVFrame *pic = avctx->coded_frame;
545     int i, sf, slice_width_factor;
546     int slice_data_size, hdr_size, y_data_size, u_data_size, v_data_size;
547     int y_linesize, u_linesize, v_linesize;
548
549     buf             = ctx->slice_data_index[slice_num];
550     slice_data_size = ctx->slice_data_index[slice_num + 1] - buf;
551
552     slice_width_factor = av_log2(mbs_per_slice);
553
554     y_data     = pic->data[0];
555     u_data     = pic->data[1];
556     v_data     = pic->data[2];
557     y_linesize = pic->linesize[0];
558     u_linesize = pic->linesize[1];
559     v_linesize = pic->linesize[2];
560
561     if (pic->interlaced_frame) {
562         if (!(pic_num ^ pic->top_field_first)) {
563             y_data += y_linesize;
564             u_data += u_linesize;
565             v_data += v_linesize;
566         }
567         y_linesize <<= 1;
568         u_linesize <<= 1;
569         v_linesize <<= 1;
570     }
571
572     if (slice_data_size < 6) {
573         av_log(avctx, AV_LOG_ERROR, "slice data too small\n");
574         return AVERROR_INVALIDDATA;
575     }
576
577     /* parse slice header */
578     hdr_size    = buf[0] >> 3;
579     y_data_size = AV_RB16(buf + 2);
580     u_data_size = AV_RB16(buf + 4);
581     v_data_size = slice_data_size - y_data_size - u_data_size - hdr_size;
582
583     if (v_data_size < 0 || hdr_size < 6) {
584         av_log(avctx, AV_LOG_ERROR, "invalid data size\n");
585         return AVERROR_INVALIDDATA;
586     }
587
588     sf = av_clip(buf[1], 1, 224);
589     sf = sf > 128 ? (sf - 96) << 2 : sf;
590
591     /* scale quantization matrixes according with slice's scale factor */
592     /* TODO: this can be SIMD-optimized alot */
593     if (ctx->qmat_changed || sf != ctx->prev_slice_sf) {
594         ctx->prev_slice_sf = sf;
595         for (i = 0; i < 64; i++) {
596             ctx->qmat_luma_scaled[i]   = ctx->qmat_luma[i]   * sf;
597             ctx->qmat_chroma_scaled[i] = ctx->qmat_chroma[i] * sf;
598         }
599     }
600
601     /* decode luma plane */
602     decode_slice_plane(ctx, buf + hdr_size, y_data_size,
603                        (uint16_t*) (y_data + (mb_y_pos << 4) * y_linesize +
604                                     (mb_x_pos << 5)), y_linesize,
605                        mbs_per_slice, 4, slice_width_factor + 2,
606                        ctx->qmat_luma_scaled);
607
608     /* decode U chroma plane */
609     decode_slice_plane(ctx, buf + hdr_size + y_data_size, u_data_size,
610                        (uint16_t*) (u_data + (mb_y_pos << 4) * u_linesize +
611                                     (mb_x_pos << ctx->mb_chroma_factor)),
612                        u_linesize, mbs_per_slice, ctx->num_chroma_blocks,
613                        slice_width_factor + ctx->chroma_factor - 1,
614                        ctx->qmat_chroma_scaled);
615
616     /* decode V chroma plane */
617     decode_slice_plane(ctx, buf + hdr_size + y_data_size + u_data_size,
618                        v_data_size,
619                        (uint16_t*) (v_data + (mb_y_pos << 4) * v_linesize +
620                                     (mb_x_pos << ctx->mb_chroma_factor)),
621                        v_linesize, mbs_per_slice, ctx->num_chroma_blocks,
622                        slice_width_factor + ctx->chroma_factor - 1,
623                        ctx->qmat_chroma_scaled);
624
625     return 0;
626 }
627
628
629 static int decode_picture(ProresContext *ctx, int pic_num,
630                           AVCodecContext *avctx)
631 {
632     int slice_num, slice_width, x_pos, y_pos;
633
634     slice_num = 0;
635
636     for (y_pos = 0; y_pos < ctx->num_y_mbs; y_pos++) {
637         slice_width = 1 << ctx->slice_width_factor;
638
639         for (x_pos = 0; x_pos < ctx->num_x_mbs && slice_width;
640              x_pos += slice_width) {
641             while (ctx->num_x_mbs - x_pos < slice_width)
642                 slice_width >>= 1;
643
644             if (decode_slice(ctx, pic_num, slice_num, x_pos, y_pos,
645                              slice_width, avctx) < 0)
646                 return -1;
647
648             slice_num++;
649         }
650     }
651
652     return 0;
653 }
654
655
656 #define FRAME_ID MKBETAG('i', 'c', 'p', 'f')
657 #define MOVE_DATA_PTR(nbytes) buf += (nbytes); buf_size -= (nbytes)
658
659 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
660                         AVPacket *avpkt)
661 {
662     ProresContext *ctx = avctx->priv_data;
663     AVFrame *picture   = avctx->coded_frame;
664     const uint8_t *buf = avpkt->data;
665     int buf_size       = avpkt->size;
666     int frame_hdr_size, pic_num, pic_data_size;
667
668     /* check frame atom container */
669     if (buf_size < 28 || buf_size < AV_RB32(buf) ||
670         AV_RB32(buf + 4) != FRAME_ID) {
671         av_log(avctx, AV_LOG_ERROR, "invalid frame\n");
672         return AVERROR_INVALIDDATA;
673     }
674
675     MOVE_DATA_PTR(8);
676
677     frame_hdr_size = decode_frame_header(ctx, buf, buf_size, avctx);
678     if (frame_hdr_size < 0)
679         return AVERROR_INVALIDDATA;
680
681     MOVE_DATA_PTR(frame_hdr_size);
682
683     if (picture->data[0])
684         avctx->release_buffer(avctx, picture);
685
686     picture->reference = 0;
687     if (avctx->get_buffer(avctx, picture) < 0)
688         return -1;
689
690     for (pic_num = 0; ctx->picture.interlaced_frame - pic_num + 1; pic_num++) {
691         pic_data_size = decode_picture_header(ctx, buf, buf_size, avctx);
692         if (pic_data_size < 0)
693             return AVERROR_INVALIDDATA;
694
695         if (decode_picture(ctx, pic_num, avctx))
696             return -1;
697
698         MOVE_DATA_PTR(pic_data_size);
699     }
700
701     *data_size       = sizeof(AVPicture);
702     *(AVFrame*) data = *avctx->coded_frame;
703
704     return avpkt->size;
705 }
706
707
708 static av_cold int decode_close(AVCodecContext *avctx)
709 {
710     ProresContext *ctx = avctx->priv_data;
711
712     if (ctx->picture.data[0])
713         avctx->release_buffer(avctx, &ctx->picture);
714
715     av_freep(&ctx->slice_data_index);
716
717     return 0;
718 }
719
720
721 AVCodec ff_prores_lgpl_decoder = {
722     .name           = "prores_lgpl",
723     .type           = AVMEDIA_TYPE_VIDEO,
724     .id             = CODEC_ID_PRORES,
725     .priv_data_size = sizeof(ProresContext),
726     .init           = decode_init,
727     .close          = decode_close,
728     .decode         = decode_frame,
729     .capabilities   = CODEC_CAP_DR1,
730     .long_name      = NULL_IF_CONFIG_SMALL("Apple ProRes (iCodec Pro)")
731 };