]> git.sesse.net Git - ffmpeg/blob - libavcodec/av1dec.c
avcodec/av1dec: support exporting Film Grain params as frame side data
[ffmpeg] / libavcodec / av1dec.c
1 /*
2  * AV1 video decoder
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 #include "libavutil/film_grain_params.h"
22 #include "libavutil/pixdesc.h"
23 #include "avcodec.h"
24 #include "av1dec.h"
25 #include "bytestream.h"
26 #include "hwconfig.h"
27 #include "internal.h"
28 #include "profiles.h"
29
30 static uint32_t inverse_recenter(int r, uint32_t v)
31 {
32     if (v > 2 * r)
33         return v;
34     else if (v & 1)
35         return r - ((v + 1) >> 1);
36     else
37         return r + (v >> 1);
38 }
39
40 static uint32_t decode_unsigned_subexp_with_ref(uint32_t sub_exp,
41                                                 int mx, int r)
42 {
43     if ((r << 1) <= mx) {
44         return inverse_recenter(r, sub_exp);
45     } else {
46         return mx - 1 - inverse_recenter(mx - 1 - r, sub_exp);
47     }
48 }
49
50 static int32_t decode_signed_subexp_with_ref(uint32_t sub_exp, int low,
51                                              int high, int r)
52 {
53     int32_t x = decode_unsigned_subexp_with_ref(sub_exp, high - low, r - low);
54     return x + low;
55 }
56
57 static void read_global_param(AV1DecContext *s, int type, int ref, int idx)
58 {
59     uint8_t primary_frame, prev_frame;
60     uint32_t abs_bits, prec_bits, round, prec_diff, sub, mx;
61     int32_t r, prev_gm_param;
62
63     primary_frame = s->raw_frame_header->primary_ref_frame;
64     prev_frame = s->raw_frame_header->ref_frame_idx[primary_frame];
65     abs_bits = AV1_GM_ABS_ALPHA_BITS;
66     prec_bits = AV1_GM_ALPHA_PREC_BITS;
67
68     /* setup_past_independence() sets PrevGmParams to default values. We can
69      * simply point to the current's frame gm_params as they will be initialized
70      * with defaults at this point.
71      */
72     if (s->raw_frame_header->primary_ref_frame == AV1_PRIMARY_REF_NONE)
73         prev_gm_param = s->cur_frame.gm_params[ref][idx];
74     else
75         prev_gm_param = s->ref[prev_frame].gm_params[ref][idx];
76
77     if (idx < 2) {
78         if (type == AV1_WARP_MODEL_TRANSLATION) {
79             abs_bits = AV1_GM_ABS_TRANS_ONLY_BITS -
80                 !s->raw_frame_header->allow_high_precision_mv;
81             prec_bits = AV1_GM_TRANS_ONLY_PREC_BITS -
82                 !s->raw_frame_header->allow_high_precision_mv;
83         } else {
84             abs_bits = AV1_GM_ABS_TRANS_BITS;
85             prec_bits = AV1_GM_TRANS_PREC_BITS;
86         }
87     }
88     round = (idx % 3) == 2 ? (1 << AV1_WARPEDMODEL_PREC_BITS) : 0;
89     prec_diff = AV1_WARPEDMODEL_PREC_BITS - prec_bits;
90     sub = (idx % 3) == 2 ? (1 << prec_bits) : 0;
91     mx = 1 << abs_bits;
92     r = (prev_gm_param >> prec_diff) - sub;
93
94     s->cur_frame.gm_params[ref][idx] =
95         (decode_signed_subexp_with_ref(s->raw_frame_header->gm_params[ref][idx],
96                                        -mx, mx + 1, r) << prec_diff) + round;
97 }
98
99 /**
100 * update gm type/params, since cbs already implemented part of this funcation,
101 * so we don't need to full implement spec.
102 */
103 static void global_motion_params(AV1DecContext *s)
104 {
105     const AV1RawFrameHeader *header = s->raw_frame_header;
106     int type, ref;
107
108     for (ref = AV1_REF_FRAME_LAST; ref <= AV1_REF_FRAME_ALTREF; ref++) {
109         s->cur_frame.gm_type[ref] = AV1_WARP_MODEL_IDENTITY;
110         for (int i = 0; i < 6; i++)
111             s->cur_frame.gm_params[ref][i] = (i % 3 == 2) ?
112                                              1 << AV1_WARPEDMODEL_PREC_BITS : 0;
113     }
114     if (header->frame_type == AV1_FRAME_KEY ||
115         header->frame_type == AV1_FRAME_INTRA_ONLY)
116         return;
117
118     for (ref = AV1_REF_FRAME_LAST; ref <= AV1_REF_FRAME_ALTREF; ref++) {
119         if (header->is_global[ref]) {
120             if (header->is_rot_zoom[ref]) {
121                 type = AV1_WARP_MODEL_ROTZOOM;
122             } else {
123                 type = header->is_translation[ref] ? AV1_WARP_MODEL_TRANSLATION
124                                                    : AV1_WARP_MODEL_AFFINE;
125             }
126         } else {
127             type = AV1_WARP_MODEL_IDENTITY;
128         }
129         s->cur_frame.gm_type[ref] = type;
130
131         if (type >= AV1_WARP_MODEL_ROTZOOM) {
132             read_global_param(s, type, ref, 2);
133             read_global_param(s, type, ref, 3);
134             if (type == AV1_WARP_MODEL_AFFINE) {
135                 read_global_param(s, type, ref, 4);
136                 read_global_param(s, type, ref, 5);
137             } else {
138                 s->cur_frame.gm_params[ref][4] = -s->cur_frame.gm_params[ref][3];
139                 s->cur_frame.gm_params[ref][5] = s->cur_frame.gm_params[ref][2];
140             }
141         }
142         if (type >= AV1_WARP_MODEL_TRANSLATION) {
143             read_global_param(s, type, ref, 0);
144             read_global_param(s, type, ref, 1);
145         }
146     }
147 }
148
149 static int get_relative_dist(const AV1RawSequenceHeader *seq,
150                              unsigned int a, unsigned int b)
151 {
152     unsigned int diff = a - b;
153     unsigned int m = 1 << seq->order_hint_bits_minus_1;
154     return (diff & (m - 1)) - (diff & m);
155 }
156
157 static void skip_mode_params(AV1DecContext *s)
158 {
159     const AV1RawFrameHeader *header = s->raw_frame_header;
160     const AV1RawSequenceHeader *seq = s->raw_seq;
161
162     int forward_idx,  backward_idx;
163     int forward_hint, backward_hint;
164     int second_forward_idx, second_forward_hint;
165     int ref_hint, dist, i;
166
167     if (!header->skip_mode_present)
168         return;
169
170     forward_idx  = -1;
171     backward_idx = -1;
172     for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
173         ref_hint = s->ref[header->ref_frame_idx[i]].raw_frame_header->order_hint;
174         dist = get_relative_dist(seq, ref_hint, header->order_hint);
175         if (dist < 0) {
176             if (forward_idx < 0 ||
177                 get_relative_dist(seq, ref_hint, forward_hint) > 0) {
178                 forward_idx  = i;
179                 forward_hint = ref_hint;
180             }
181         } else if (dist > 0) {
182             if (backward_idx < 0 ||
183                 get_relative_dist(seq, ref_hint, backward_hint) < 0) {
184                 backward_idx  = i;
185                 backward_hint = ref_hint;
186             }
187         }
188     }
189
190     if (forward_idx < 0) {
191         return;
192     } else if (backward_idx >= 0) {
193         s->cur_frame.skip_mode_frame_idx[0] =
194             AV1_REF_FRAME_LAST + FFMIN(forward_idx, backward_idx);
195         s->cur_frame.skip_mode_frame_idx[1] =
196             AV1_REF_FRAME_LAST + FFMAX(forward_idx, backward_idx);
197         return;
198     }
199
200     second_forward_idx = -1;
201     for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
202         ref_hint = s->ref[header->ref_frame_idx[i]].raw_frame_header->order_hint;
203         if (get_relative_dist(seq, ref_hint, forward_hint) < 0) {
204             if (second_forward_idx < 0 ||
205                 get_relative_dist(seq, ref_hint, second_forward_hint) > 0) {
206                 second_forward_idx  = i;
207                 second_forward_hint = ref_hint;
208             }
209         }
210     }
211
212     if (second_forward_idx < 0)
213         return;
214
215     s->cur_frame.skip_mode_frame_idx[0] =
216         AV1_REF_FRAME_LAST + FFMIN(forward_idx, second_forward_idx);
217     s->cur_frame.skip_mode_frame_idx[1] =
218         AV1_REF_FRAME_LAST + FFMAX(forward_idx, second_forward_idx);
219 }
220
221 static void coded_lossless_param(AV1DecContext *s)
222 {
223     const AV1RawFrameHeader *header = s->raw_frame_header;
224     int i;
225
226     if (header->delta_q_y_dc || header->delta_q_u_ac ||
227         header->delta_q_u_dc || header->delta_q_v_ac ||
228         header->delta_q_v_dc) {
229         s->cur_frame.coded_lossless = 0;
230         return;
231     }
232
233     s->cur_frame.coded_lossless = 1;
234     for (i = 0; i < AV1_MAX_SEGMENTS; i++) {
235         int qindex;
236         if (header->feature_enabled[i][AV1_SEG_LVL_ALT_Q]) {
237             qindex = (header->base_q_idx +
238                       header->feature_value[i][AV1_SEG_LVL_ALT_Q]);
239         } else {
240             qindex = header->base_q_idx;
241         }
242         qindex = av_clip_uintp2(qindex, 8);
243
244         if (qindex) {
245             s->cur_frame.coded_lossless = 0;
246             return;
247         }
248     }
249 }
250
251 static void load_grain_params(AV1DecContext *s)
252 {
253     const AV1RawFrameHeader *header = s->raw_frame_header;
254     const AV1RawFilmGrainParams *film_grain = &header->film_grain, *src;
255     AV1RawFilmGrainParams *dst = &s->cur_frame.film_grain;
256
257     if (!film_grain->apply_grain)
258         return;
259
260     if (film_grain->update_grain) {
261         memcpy(dst, film_grain, sizeof(*dst));
262         return;
263     }
264
265     src = &s->ref[film_grain->film_grain_params_ref_idx].film_grain;
266
267     memcpy(dst, src, sizeof(*dst));
268     dst->grain_seed = film_grain->grain_seed;
269 }
270
271 static int init_tile_data(AV1DecContext *s)
272
273 {
274     int cur_tile_num =
275         s->raw_frame_header->tile_cols * s->raw_frame_header->tile_rows;
276     if (s->tile_num < cur_tile_num) {
277         int ret = av_reallocp_array(&s->tile_group_info, cur_tile_num,
278                                     sizeof(TileGroupInfo));
279         if (ret < 0) {
280             s->tile_num = 0;
281             return ret;
282         }
283     }
284     s->tile_num = cur_tile_num;
285
286     return 0;
287 }
288
289 static int get_tiles_info(AVCodecContext *avctx, const AV1RawTileGroup *tile_group)
290 {
291     AV1DecContext *s = avctx->priv_data;
292     GetByteContext gb;
293     uint16_t tile_num, tile_row, tile_col;
294     uint32_t size = 0, size_bytes = 0;
295
296     bytestream2_init(&gb, tile_group->tile_data.data,
297                      tile_group->tile_data.data_size);
298     s->tg_start = tile_group->tg_start;
299     s->tg_end = tile_group->tg_end;
300
301     for (tile_num = tile_group->tg_start; tile_num <= tile_group->tg_end; tile_num++) {
302         tile_row = tile_num / s->raw_frame_header->tile_cols;
303         tile_col = tile_num % s->raw_frame_header->tile_cols;
304
305         if (tile_num == tile_group->tg_end) {
306             s->tile_group_info[tile_num].tile_size = bytestream2_get_bytes_left(&gb);
307             s->tile_group_info[tile_num].tile_offset = bytestream2_tell(&gb);
308             s->tile_group_info[tile_num].tile_row = tile_row;
309             s->tile_group_info[tile_num].tile_column = tile_col;
310             return 0;
311         }
312         size_bytes = s->raw_frame_header->tile_size_bytes_minus1 + 1;
313         if (bytestream2_get_bytes_left(&gb) < size_bytes)
314             return AVERROR_INVALIDDATA;
315         size = 0;
316         for (int i = 0; i < size_bytes; i++)
317             size |= bytestream2_get_byteu(&gb) << 8 * i;
318         if (bytestream2_get_bytes_left(&gb) <= size)
319             return AVERROR_INVALIDDATA;
320         size++;
321
322         s->tile_group_info[tile_num].tile_size = size;
323         s->tile_group_info[tile_num].tile_offset = bytestream2_tell(&gb);
324         s->tile_group_info[tile_num].tile_row = tile_row;
325         s->tile_group_info[tile_num].tile_column = tile_col;
326
327         bytestream2_skipu(&gb, size);
328     }
329
330     return 0;
331
332 }
333
334 static int get_pixel_format(AVCodecContext *avctx)
335 {
336     AV1DecContext *s = avctx->priv_data;
337     const AV1RawSequenceHeader *seq = s->raw_seq;
338     uint8_t bit_depth;
339     int ret;
340     enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
341 #define HWACCEL_MAX (CONFIG_AV1_DXVA2_HWACCEL + \
342                      CONFIG_AV1_D3D11VA_HWACCEL * 2 + \
343                      CONFIG_AV1_NVDEC_HWACCEL + \
344                      CONFIG_AV1_VAAPI_HWACCEL)
345     enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmtp = pix_fmts;
346
347     if (seq->seq_profile == 2 && seq->color_config.high_bitdepth)
348         bit_depth = seq->color_config.twelve_bit ? 12 : 10;
349     else if (seq->seq_profile <= 2)
350         bit_depth = seq->color_config.high_bitdepth ? 10 : 8;
351     else {
352         av_log(avctx, AV_LOG_ERROR,
353                "Unknown AV1 profile %d.\n", seq->seq_profile);
354         return -1;
355     }
356
357     if (!seq->color_config.mono_chrome) {
358         // 4:4:4 x:0 y:0, 4:2:2 x:1 y:0, 4:2:0 x:1 y:1
359         if (seq->color_config.subsampling_x == 0 &&
360             seq->color_config.subsampling_y == 0) {
361             if (bit_depth == 8)
362                 pix_fmt = AV_PIX_FMT_YUV444P;
363             else if (bit_depth == 10)
364                 pix_fmt = AV_PIX_FMT_YUV444P10;
365             else if (bit_depth == 12)
366                 pix_fmt = AV_PIX_FMT_YUV444P12;
367             else
368                 av_log(avctx, AV_LOG_WARNING, "Unknown AV1 pixel format.\n");
369         } else if (seq->color_config.subsampling_x == 1 &&
370                    seq->color_config.subsampling_y == 0) {
371             if (bit_depth == 8)
372                 pix_fmt = AV_PIX_FMT_YUV422P;
373             else if (bit_depth == 10)
374                 pix_fmt = AV_PIX_FMT_YUV422P10;
375             else if (bit_depth == 12)
376                 pix_fmt = AV_PIX_FMT_YUV422P12;
377             else
378                 av_log(avctx, AV_LOG_WARNING, "Unknown AV1 pixel format.\n");
379         } else if (seq->color_config.subsampling_x == 1 &&
380                    seq->color_config.subsampling_y == 1) {
381             if (bit_depth == 8)
382                 pix_fmt = AV_PIX_FMT_YUV420P;
383             else if (bit_depth == 10)
384                 pix_fmt = AV_PIX_FMT_YUV420P10;
385             else if (bit_depth == 12)
386                 pix_fmt = AV_PIX_FMT_YUV420P12;
387             else
388                 av_log(avctx, AV_LOG_WARNING, "Unknown AV1 pixel format.\n");
389         }
390     } else {
391         if (bit_depth == 8)
392             pix_fmt = AV_PIX_FMT_GRAY8;
393         else if (bit_depth == 10)
394             pix_fmt = AV_PIX_FMT_GRAY10;
395         else if (bit_depth == 12)
396             pix_fmt = AV_PIX_FMT_GRAY12;
397         else
398             av_log(avctx, AV_LOG_WARNING, "Unknown AV1 pixel format.\n");
399     }
400
401     av_log(avctx, AV_LOG_DEBUG, "AV1 decode get format: %s.\n",
402            av_get_pix_fmt_name(pix_fmt));
403
404     if (pix_fmt == AV_PIX_FMT_NONE)
405         return -1;
406     s->pix_fmt = pix_fmt;
407
408     switch (s->pix_fmt) {
409     case AV_PIX_FMT_YUV420P:
410 #if CONFIG_AV1_DXVA2_HWACCEL
411         *fmtp++ = AV_PIX_FMT_DXVA2_VLD;
412 #endif
413 #if CONFIG_AV1_D3D11VA_HWACCEL
414         *fmtp++ = AV_PIX_FMT_D3D11VA_VLD;
415         *fmtp++ = AV_PIX_FMT_D3D11;
416 #endif
417 #if CONFIG_AV1_NVDEC_HWACCEL
418         *fmtp++ = AV_PIX_FMT_CUDA;
419 #endif
420 #if CONFIG_AV1_VAAPI_HWACCEL
421         *fmtp++ = AV_PIX_FMT_VAAPI;
422 #endif
423         break;
424     case AV_PIX_FMT_YUV420P10:
425 #if CONFIG_AV1_DXVA2_HWACCEL
426         *fmtp++ = AV_PIX_FMT_DXVA2_VLD;
427 #endif
428 #if CONFIG_AV1_D3D11VA_HWACCEL
429         *fmtp++ = AV_PIX_FMT_D3D11VA_VLD;
430         *fmtp++ = AV_PIX_FMT_D3D11;
431 #endif
432 #if CONFIG_AV1_NVDEC_HWACCEL
433         *fmtp++ = AV_PIX_FMT_CUDA;
434 #endif
435 #if CONFIG_AV1_VAAPI_HWACCEL
436         *fmtp++ = AV_PIX_FMT_VAAPI;
437 #endif
438         break;
439     case AV_PIX_FMT_GRAY8:
440 #if CONFIG_AV1_NVDEC_HWACCEL
441         *fmtp++ = AV_PIX_FMT_CUDA;
442 #endif
443         break;
444     case AV_PIX_FMT_GRAY10:
445 #if CONFIG_AV1_NVDEC_HWACCEL
446         *fmtp++ = AV_PIX_FMT_CUDA;
447 #endif
448         break;
449     }
450
451     *fmtp++ = s->pix_fmt;
452     *fmtp = AV_PIX_FMT_NONE;
453
454     ret = ff_thread_get_format(avctx, pix_fmts);
455     if (ret < 0)
456         return ret;
457
458     /**
459      * check if the HW accel is inited correctly. If not, return un-implemented.
460      * Since now the av1 decoder doesn't support native decode, if it will be
461      * implemented in the future, need remove this check.
462      */
463     if (!avctx->hwaccel) {
464         av_log(avctx, AV_LOG_ERROR, "Your platform doesn't suppport"
465                " hardware accelerated AV1 decoding.\n");
466         return AVERROR(ENOSYS);
467     }
468
469     avctx->pix_fmt = ret;
470
471     return 0;
472 }
473
474 static void av1_frame_unref(AVCodecContext *avctx, AV1Frame *f)
475 {
476     ff_thread_release_buffer(avctx, &f->tf);
477     av_buffer_unref(&f->hwaccel_priv_buf);
478     f->hwaccel_picture_private = NULL;
479     av_buffer_unref(&f->header_ref);
480     f->raw_frame_header = NULL;
481     f->spatial_id = f->temporal_id = 0;
482     memset(f->skip_mode_frame_idx, 0,
483            2 * sizeof(uint8_t));
484     memset(&f->film_grain, 0, sizeof(f->film_grain));
485     f->coded_lossless = 0;
486 }
487
488 static int av1_frame_ref(AVCodecContext *avctx, AV1Frame *dst, const AV1Frame *src)
489 {
490     int ret;
491
492     ret = ff_thread_ref_frame(&dst->tf, &src->tf);
493     if (ret < 0)
494         return ret;
495
496     dst->header_ref = av_buffer_ref(src->header_ref);
497     if (!dst->header_ref)
498         goto fail;
499
500     dst->raw_frame_header = src->raw_frame_header;
501
502     if (src->hwaccel_picture_private) {
503         dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
504         if (!dst->hwaccel_priv_buf)
505             goto fail;
506         dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
507     }
508
509     dst->spatial_id = src->spatial_id;
510     dst->temporal_id = src->temporal_id;
511     memcpy(dst->gm_type,
512            src->gm_type,
513            AV1_NUM_REF_FRAMES * sizeof(uint8_t));
514     memcpy(dst->gm_params,
515            src->gm_params,
516            AV1_NUM_REF_FRAMES * 6 * sizeof(int32_t));
517     memcpy(dst->skip_mode_frame_idx,
518            src->skip_mode_frame_idx,
519            2 * sizeof(uint8_t));
520     memcpy(&dst->film_grain,
521            &src->film_grain,
522            sizeof(dst->film_grain));
523     dst->coded_lossless = src->coded_lossless;
524
525     return 0;
526
527 fail:
528     av1_frame_unref(avctx, dst);
529     return AVERROR(ENOMEM);
530 }
531
532 static av_cold int av1_decode_free(AVCodecContext *avctx)
533 {
534     AV1DecContext *s = avctx->priv_data;
535
536     for (int i = 0; i < FF_ARRAY_ELEMS(s->ref); i++) {
537         av1_frame_unref(avctx, &s->ref[i]);
538         av_frame_free(&s->ref[i].tf.f);
539     }
540     av1_frame_unref(avctx, &s->cur_frame);
541     av_frame_free(&s->cur_frame.tf.f);
542
543     av_buffer_unref(&s->seq_ref);
544     av_buffer_unref(&s->header_ref);
545     av_freep(&s->tile_group_info);
546
547     ff_cbs_fragment_free(&s->current_obu);
548     ff_cbs_close(&s->cbc);
549
550     return 0;
551 }
552
553 static int set_context_with_sequence(AVCodecContext *avctx,
554                                      const AV1RawSequenceHeader *seq)
555 {
556     int width = seq->max_frame_width_minus_1 + 1;
557     int height = seq->max_frame_height_minus_1 + 1;
558
559     avctx->profile = seq->seq_profile;
560     avctx->level = seq->seq_level_idx[0];
561
562     avctx->color_range =
563         seq->color_config.color_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
564     avctx->color_primaries = seq->color_config.color_primaries;
565     avctx->colorspace = seq->color_config.color_primaries;
566     avctx->color_trc = seq->color_config.transfer_characteristics;
567
568     switch (seq->color_config.chroma_sample_position) {
569     case AV1_CSP_VERTICAL:
570         avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
571         break;
572     case AV1_CSP_COLOCATED:
573         avctx->chroma_sample_location = AVCHROMA_LOC_TOPLEFT;
574         break;
575     }
576
577     if (avctx->width != width || avctx->height != height) {
578         int ret = ff_set_dimensions(avctx, width, height);
579         if (ret < 0)
580             return ret;
581     }
582     avctx->sample_aspect_ratio = (AVRational) { 1, 1 };
583
584     if (seq->timing_info.num_units_in_display_tick &&
585         seq->timing_info.time_scale) {
586         av_reduce(&avctx->framerate.den, &avctx->framerate.num,
587                   seq->timing_info.num_units_in_display_tick,
588                   seq->timing_info.time_scale,
589                   INT_MAX);
590         if (seq->timing_info.equal_picture_interval)
591             avctx->ticks_per_frame = seq->timing_info.num_ticks_per_picture_minus_1 + 1;
592     }
593
594     return 0;
595 }
596
597 static int update_context_with_frame_header(AVCodecContext *avctx,
598                                             const AV1RawFrameHeader *header)
599 {
600     AVRational aspect_ratio;
601     int width = header->frame_width_minus_1 + 1;
602     int height = header->frame_height_minus_1 + 1;
603     int r_width = header->render_width_minus_1 + 1;
604     int r_height = header->render_height_minus_1 + 1;
605     int ret;
606
607     if (avctx->width != width || avctx->height != height) {
608         ret = ff_set_dimensions(avctx, width, height);
609         if (ret < 0)
610             return ret;
611     }
612
613     av_reduce(&aspect_ratio.num, &aspect_ratio.den,
614               (int64_t)height * r_width,
615               (int64_t)width * r_height,
616               INT_MAX);
617
618     if (av_cmp_q(avctx->sample_aspect_ratio, aspect_ratio)) {
619         ret = ff_set_sar(avctx, aspect_ratio);
620         if (ret < 0)
621             return ret;
622     }
623
624     return 0;
625 }
626
627 static av_cold int av1_decode_init(AVCodecContext *avctx)
628 {
629     AV1DecContext *s = avctx->priv_data;
630     AV1RawSequenceHeader *seq;
631     int ret;
632
633     s->avctx = avctx;
634     s->pix_fmt = AV_PIX_FMT_NONE;
635
636     for (int i = 0; i < FF_ARRAY_ELEMS(s->ref); i++) {
637         s->ref[i].tf.f = av_frame_alloc();
638         if (!s->ref[i].tf.f) {
639             av_log(avctx, AV_LOG_ERROR,
640                    "Failed to allocate reference frame buffer %d.\n", i);
641             return AVERROR(ENOMEM);
642         }
643     }
644
645     s->cur_frame.tf.f = av_frame_alloc();
646     if (!s->cur_frame.tf.f) {
647         av_log(avctx, AV_LOG_ERROR,
648                "Failed to allocate current frame buffer.\n");
649         return AVERROR(ENOMEM);
650     }
651
652     ret = ff_cbs_init(&s->cbc, AV_CODEC_ID_AV1, avctx);
653     if (ret < 0)
654         return ret;
655
656     if (avctx->extradata && avctx->extradata_size) {
657         ret = ff_cbs_read_extradata_from_codec(s->cbc,
658                                                &s->current_obu,
659                                                avctx);
660         if (ret < 0) {
661             av_log(avctx, AV_LOG_WARNING, "Failed to read extradata.\n");
662             return ret;
663         }
664
665         seq = ((CodedBitstreamAV1Context *)(s->cbc->priv_data))->sequence_header;
666         if (!seq) {
667             av_log(avctx, AV_LOG_WARNING, "No sequence header available.\n");
668             goto end;
669         }
670
671         ret = set_context_with_sequence(avctx, seq);
672         if (ret < 0) {
673             av_log(avctx, AV_LOG_WARNING, "Failed to set decoder context.\n");
674             goto end;
675         }
676
677         end:
678         ff_cbs_fragment_reset(&s->current_obu);
679     }
680
681     return ret;
682 }
683
684 static int av1_frame_alloc(AVCodecContext *avctx, AV1Frame *f)
685 {
686     AV1DecContext *s = avctx->priv_data;
687     AV1RawFrameHeader *header= s->raw_frame_header;
688     AVFrame *frame;
689     int ret;
690
691     ret = update_context_with_frame_header(avctx, header);
692     if (ret < 0) {
693         av_log(avctx, AV_LOG_ERROR, "Failed to update context with frame header\n");
694         return ret;
695     }
696
697     f->header_ref = av_buffer_ref(s->header_ref);
698     if (!f->header_ref)
699         return AVERROR(ENOMEM);
700
701     f->raw_frame_header = s->raw_frame_header;
702
703     if ((ret = ff_thread_get_buffer(avctx, &f->tf, AV_GET_BUFFER_FLAG_REF)) < 0)
704         goto fail;
705
706     frame = f->tf.f;
707     frame->key_frame = header->frame_type == AV1_FRAME_KEY;
708
709     switch (header->frame_type) {
710     case AV1_FRAME_KEY:
711     case AV1_FRAME_INTRA_ONLY:
712         frame->pict_type = AV_PICTURE_TYPE_I;
713         break;
714     case AV1_FRAME_INTER:
715         frame->pict_type = AV_PICTURE_TYPE_P;
716         break;
717     case AV1_FRAME_SWITCH:
718         frame->pict_type = AV_PICTURE_TYPE_SP;
719         break;
720     }
721
722     if (avctx->hwaccel) {
723         const AVHWAccel *hwaccel = avctx->hwaccel;
724         if (hwaccel->frame_priv_data_size) {
725             f->hwaccel_priv_buf =
726                 av_buffer_allocz(hwaccel->frame_priv_data_size);
727             if (!f->hwaccel_priv_buf) {
728                 ret = AVERROR(ENOMEM);
729                 goto fail;
730             }
731             f->hwaccel_picture_private = f->hwaccel_priv_buf->data;
732         }
733     }
734     return 0;
735
736 fail:
737     av1_frame_unref(avctx, f);
738     return ret;
739 }
740
741 static int export_film_grain(AVCodecContext *avctx, AVFrame *frame)
742 {
743     AV1DecContext *s = avctx->priv_data;
744     const AV1RawFilmGrainParams *film_grain = &s->cur_frame.film_grain;
745     AVFilmGrainParams *fgp;
746     AVFilmGrainAOMParams *aom;
747
748     if (!film_grain->apply_grain)
749         return 0;
750
751     fgp = av_film_grain_params_create_side_data(frame);
752     if (!fgp)
753         return AVERROR(ENOMEM);
754
755     fgp->type = AV_FILM_GRAIN_PARAMS_AV1;
756     fgp->seed = film_grain->grain_seed;
757
758     aom = &fgp->codec.aom;
759     aom->chroma_scaling_from_luma = film_grain->chroma_scaling_from_luma;
760     aom->scaling_shift = film_grain->grain_scaling_minus_8 + 8;
761     aom->ar_coeff_lag = film_grain->ar_coeff_lag;
762     aom->ar_coeff_shift = film_grain->ar_coeff_shift_minus_6 + 6;
763     aom->grain_scale_shift = film_grain->grain_scale_shift;
764     aom->overlap_flag = film_grain->overlap_flag;
765     aom->limit_output_range = film_grain->clip_to_restricted_range;
766
767     aom->num_y_points = film_grain->num_y_points;
768     for (int i = 0; i < film_grain->num_y_points; i++) {
769         aom->y_points[i][0] = film_grain->point_y_value[i];
770         aom->y_points[i][1] = film_grain->point_y_scaling[i];
771     }
772     aom->num_uv_points[0] = film_grain->num_cb_points;
773     for (int i = 0; i < film_grain->num_cb_points; i++) {
774         aom->uv_points[0][i][0] = film_grain->point_cb_value[i];
775         aom->uv_points[0][i][1] = film_grain->point_cb_scaling[i];
776     }
777     aom->num_uv_points[1] = film_grain->num_cr_points;
778     for (int i = 0; i < film_grain->num_cr_points; i++) {
779         aom->uv_points[1][i][0] = film_grain->point_cr_value[i];
780         aom->uv_points[1][i][1] = film_grain->point_cr_scaling[i];
781     }
782
783     for (int i = 0; i < 24; i++) {
784         aom->ar_coeffs_y[i] = film_grain->ar_coeffs_y_plus_128[i] - 128;
785     }
786     for (int i = 0; i < 25; i++) {
787         aom->ar_coeffs_uv[0][i] = film_grain->ar_coeffs_cb_plus_128[i] - 128;
788         aom->ar_coeffs_uv[1][i] = film_grain->ar_coeffs_cr_plus_128[i] - 128;
789     }
790
791     aom->uv_mult[0] = film_grain->cb_mult;
792     aom->uv_mult[1] = film_grain->cr_mult;
793     aom->uv_mult_luma[0] = film_grain->cb_luma_mult;
794     aom->uv_mult_luma[1] = film_grain->cr_luma_mult;
795     aom->uv_offset[0] = film_grain->cb_offset;
796     aom->uv_offset[1] = film_grain->cr_offset;
797
798     return 0;
799 }
800
801 static int set_output_frame(AVCodecContext *avctx, AVFrame *frame,
802                             const AVPacket *pkt, int *got_frame)
803 {
804     AV1DecContext *s = avctx->priv_data;
805     const AVFrame *srcframe = s->cur_frame.tf.f;
806     int ret;
807
808     ret = av_frame_ref(frame, srcframe);
809     if (ret < 0)
810         return ret;
811
812     if (avctx->export_side_data & AV_CODEC_EXPORT_DATA_FILM_GRAIN) {
813         ret = export_film_grain(avctx, frame);
814         if (ret < 0) {
815             av_frame_unref(frame);
816             return ret;
817         }
818     }
819
820     frame->pts = pkt->pts;
821     frame->pkt_dts = pkt->dts;
822     frame->pkt_size = pkt->size;
823
824     *got_frame = 1;
825
826     return 0;
827 }
828
829 static int update_reference_list(AVCodecContext *avctx)
830 {
831     AV1DecContext *s = avctx->priv_data;
832     const AV1RawFrameHeader *header = s->raw_frame_header;
833     int ret;
834
835     for (int i = 0; i < AV1_NUM_REF_FRAMES; i++) {
836         if (header->refresh_frame_flags & (1 << i)) {
837             if (s->ref[i].tf.f->buf[0])
838                 av1_frame_unref(avctx, &s->ref[i]);
839             if ((ret = av1_frame_ref(avctx, &s->ref[i], &s->cur_frame)) < 0) {
840                 av_log(avctx, AV_LOG_ERROR,
841                        "Failed to update frame %d in reference list\n", i);
842                 return ret;
843             }
844         }
845     }
846     return 0;
847 }
848
849 static int get_current_frame(AVCodecContext *avctx)
850 {
851     AV1DecContext *s = avctx->priv_data;
852     int ret;
853
854     if (s->cur_frame.tf.f->buf[0])
855         av1_frame_unref(avctx, &s->cur_frame);
856
857     ret = av1_frame_alloc(avctx, &s->cur_frame);
858     if (ret < 0) {
859         av_log(avctx, AV_LOG_ERROR,
860                "Failed to allocate space for current frame.\n");
861         return ret;
862     }
863
864     ret = init_tile_data(s);
865     if (ret < 0) {
866         av_log(avctx, AV_LOG_ERROR, "Failed to init tile data.\n");
867         return ret;
868     }
869
870     global_motion_params(s);
871     skip_mode_params(s);
872     coded_lossless_param(s);
873     load_grain_params(s);
874
875     return ret;
876 }
877
878 static int av1_decode_frame(AVCodecContext *avctx, void *frame,
879                             int *got_frame, AVPacket *pkt)
880 {
881     AV1DecContext *s = avctx->priv_data;
882     AV1RawTileGroup *raw_tile_group = NULL;
883     int ret;
884
885     ret = ff_cbs_read_packet(s->cbc, &s->current_obu, pkt);
886     if (ret < 0) {
887         av_log(avctx, AV_LOG_ERROR, "Failed to read packet.\n");
888         goto end;
889     }
890     av_log(avctx, AV_LOG_DEBUG, "Total obu for this frame:%d.\n",
891            s->current_obu.nb_units);
892
893     for (int i = 0; i < s->current_obu.nb_units; i++) {
894         CodedBitstreamUnit *unit = &s->current_obu.units[i];
895         AV1RawOBU *obu = unit->content;
896         const AV1RawOBUHeader *header;
897
898         if (!obu)
899             continue;
900
901         header = &obu->header;
902         av_log(avctx, AV_LOG_DEBUG, "Obu idx:%d, obu type:%d.\n", i, unit->type);
903
904         switch (unit->type) {
905         case AV1_OBU_SEQUENCE_HEADER:
906             av_buffer_unref(&s->seq_ref);
907             s->seq_ref = av_buffer_ref(unit->content_ref);
908             if (!s->seq_ref) {
909                 ret = AVERROR(ENOMEM);
910                 goto end;
911             }
912
913             s->raw_seq = &obu->obu.sequence_header;
914
915             ret = set_context_with_sequence(avctx, s->raw_seq);
916             if (ret < 0) {
917                 av_log(avctx, AV_LOG_ERROR, "Failed to set context.\n");
918                 s->raw_seq = NULL;
919                 goto end;
920             }
921
922             if (s->pix_fmt == AV_PIX_FMT_NONE) {
923                 ret = get_pixel_format(avctx);
924                 if (ret < 0) {
925                     av_log(avctx, AV_LOG_ERROR,
926                            "Failed to get pixel format.\n");
927                     s->raw_seq = NULL;
928                     goto end;
929                 }
930             }
931
932             if (avctx->hwaccel && avctx->hwaccel->decode_params) {
933                 ret = avctx->hwaccel->decode_params(avctx, unit->type, unit->data,
934                                                     unit->data_size);
935                 if (ret < 0) {
936                     av_log(avctx, AV_LOG_ERROR, "HW accel decode params fail.\n");
937                     s->raw_seq = NULL;
938                     goto end;
939                 }
940             }
941             break;
942         case AV1_OBU_REDUNDANT_FRAME_HEADER:
943             if (s->raw_frame_header)
944                 break;
945         // fall-through
946         case AV1_OBU_FRAME:
947         case AV1_OBU_FRAME_HEADER:
948             if (!s->raw_seq) {
949                 av_log(avctx, AV_LOG_ERROR, "Missing Sequence Header.\n");
950                 ret = AVERROR_INVALIDDATA;
951                 goto end;
952             }
953
954             av_buffer_unref(&s->header_ref);
955             s->header_ref = av_buffer_ref(unit->content_ref);
956             if (!s->header_ref) {
957                 ret = AVERROR(ENOMEM);
958                 goto end;
959             }
960
961             if (unit->type == AV1_OBU_FRAME)
962                 s->raw_frame_header = &obu->obu.frame.header;
963             else
964                 s->raw_frame_header = &obu->obu.frame_header;
965
966             if (s->raw_frame_header->show_existing_frame) {
967                 if (s->cur_frame.tf.f->buf[0])
968                     av1_frame_unref(avctx, &s->cur_frame);
969
970                 ret = av1_frame_ref(avctx, &s->cur_frame,
971                                     &s->ref[s->raw_frame_header->frame_to_show_map_idx]);
972                 if (ret < 0) {
973                     av_log(avctx, AV_LOG_ERROR, "Failed to get reference frame.\n");
974                     goto end;
975                 }
976
977                 ret = update_reference_list(avctx);
978                 if (ret < 0) {
979                     av_log(avctx, AV_LOG_ERROR, "Failed to update reference list.\n");
980                     goto end;
981                 }
982
983                 ret = set_output_frame(avctx, frame, pkt, got_frame);
984                 if (ret < 0)
985                     av_log(avctx, AV_LOG_ERROR, "Set output frame error.\n");
986
987                 s->raw_frame_header = NULL;
988
989                 goto end;
990             }
991
992             ret = get_current_frame(avctx);
993             if (ret < 0) {
994                 av_log(avctx, AV_LOG_ERROR, "Get current frame error\n");
995                 goto end;
996             }
997
998             s->cur_frame.spatial_id  = header->spatial_id;
999             s->cur_frame.temporal_id = header->temporal_id;
1000
1001             if (avctx->hwaccel) {
1002                 ret = avctx->hwaccel->start_frame(avctx, unit->data,
1003                                                   unit->data_size);
1004                 if (ret < 0) {
1005                     av_log(avctx, AV_LOG_ERROR, "HW accel start frame fail.\n");
1006                     goto end;
1007                 }
1008             }
1009             if (unit->type != AV1_OBU_FRAME)
1010                 break;
1011         // fall-through
1012         case AV1_OBU_TILE_GROUP:
1013             if (!s->raw_frame_header) {
1014                 av_log(avctx, AV_LOG_ERROR, "Missing Frame Header.\n");
1015                 ret = AVERROR_INVALIDDATA;
1016                 goto end;
1017             }
1018
1019             if (unit->type == AV1_OBU_FRAME)
1020                 raw_tile_group = &obu->obu.frame.tile_group;
1021             else
1022                 raw_tile_group = &obu->obu.tile_group;
1023
1024             ret = get_tiles_info(avctx, raw_tile_group);
1025             if (ret < 0)
1026                 goto end;
1027
1028             if (avctx->hwaccel) {
1029                 ret = avctx->hwaccel->decode_slice(avctx,
1030                                                    raw_tile_group->tile_data.data,
1031                                                    raw_tile_group->tile_data.data_size);
1032                 if (ret < 0) {
1033                     av_log(avctx, AV_LOG_ERROR,
1034                            "HW accel decode slice fail.\n");
1035                     goto end;
1036                 }
1037             }
1038             break;
1039         case AV1_OBU_TILE_LIST:
1040         case AV1_OBU_TEMPORAL_DELIMITER:
1041         case AV1_OBU_PADDING:
1042         case AV1_OBU_METADATA:
1043             break;
1044         default:
1045             av_log(avctx, AV_LOG_DEBUG,
1046                    "Unknown obu type: %d (%"SIZE_SPECIFIER" bits).\n",
1047                    unit->type, unit->data_size);
1048         }
1049
1050         if (raw_tile_group && (s->tile_num == raw_tile_group->tg_end + 1)) {
1051             if (avctx->hwaccel) {
1052                 ret = avctx->hwaccel->end_frame(avctx);
1053                 if (ret < 0) {
1054                     av_log(avctx, AV_LOG_ERROR, "HW accel end frame fail.\n");
1055                     goto end;
1056                 }
1057             }
1058
1059             ret = update_reference_list(avctx);
1060             if (ret < 0) {
1061                 av_log(avctx, AV_LOG_ERROR, "Failed to update reference list.\n");
1062                 goto end;
1063             }
1064
1065             if (s->raw_frame_header->show_frame) {
1066                 ret = set_output_frame(avctx, frame, pkt, got_frame);
1067                 if (ret < 0) {
1068                     av_log(avctx, AV_LOG_ERROR, "Set output frame error\n");
1069                     goto end;
1070                 }
1071             }
1072             raw_tile_group = NULL;
1073             s->raw_frame_header = NULL;
1074         }
1075     }
1076
1077 end:
1078     ff_cbs_fragment_reset(&s->current_obu);
1079     if (ret < 0)
1080         s->raw_frame_header = NULL;
1081     return ret;
1082 }
1083
1084 static void av1_decode_flush(AVCodecContext *avctx)
1085 {
1086     AV1DecContext *s = avctx->priv_data;
1087
1088     for (int i = 0; i < FF_ARRAY_ELEMS(s->ref); i++)
1089         av1_frame_unref(avctx, &s->ref[i]);
1090
1091     av1_frame_unref(avctx, &s->cur_frame);
1092     s->raw_frame_header = NULL;
1093     s->raw_seq = NULL;
1094
1095     ff_cbs_flush(s->cbc);
1096 }
1097
1098 AVCodec ff_av1_decoder = {
1099     .name                  = "av1",
1100     .long_name             = NULL_IF_CONFIG_SMALL("Alliance for Open Media AV1"),
1101     .type                  = AVMEDIA_TYPE_VIDEO,
1102     .id                    = AV_CODEC_ID_AV1,
1103     .priv_data_size        = sizeof(AV1DecContext),
1104     .init                  = av1_decode_init,
1105     .close                 = av1_decode_free,
1106     .decode                = av1_decode_frame,
1107     .capabilities          = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_AVOID_PROBING,
1108     .caps_internal         = FF_CODEC_CAP_INIT_THREADSAFE |
1109                              FF_CODEC_CAP_INIT_CLEANUP |
1110                              FF_CODEC_CAP_SETS_PKT_DTS,
1111     .flush                 = av1_decode_flush,
1112     .profiles              = NULL_IF_CONFIG_SMALL(ff_av1_profiles),
1113     .hw_configs            = (const AVCodecHWConfigInternal * []) {
1114 #if CONFIG_AV1_DXVA2_HWACCEL
1115         HWACCEL_DXVA2(av1),
1116 #endif
1117 #if CONFIG_AV1_D3D11VA_HWACCEL
1118         HWACCEL_D3D11VA(av1),
1119 #endif
1120 #if CONFIG_AV1_D3D11VA2_HWACCEL
1121         HWACCEL_D3D11VA2(av1),
1122 #endif
1123 #if CONFIG_AV1_NVDEC_HWACCEL
1124         HWACCEL_NVDEC(av1),
1125 #endif
1126 #if CONFIG_AV1_VAAPI_HWACCEL
1127         HWACCEL_VAAPI(av1),
1128 #endif
1129         NULL
1130     },
1131 };