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