]> git.sesse.net Git - ffmpeg/blob - libavcodec/av1dec.c
avcodec/av1{dec,parser}: move to ff_cbs_read_extradata_from_codec
[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 int init_tile_data(AV1DecContext *s)
251
252 {
253     int cur_tile_num =
254         s->raw_frame_header->tile_cols * s->raw_frame_header->tile_rows;
255     if (s->tile_num < cur_tile_num) {
256         int ret = av_reallocp_array(&s->tile_group_info, cur_tile_num,
257                                     sizeof(TileGroupInfo));
258         if (ret < 0) {
259             s->tile_num = 0;
260             return ret;
261         }
262     }
263     s->tile_num = cur_tile_num;
264
265     return 0;
266 }
267
268 static int get_tiles_info(AVCodecContext *avctx, const AV1RawTileGroup *tile_group)
269 {
270     AV1DecContext *s = avctx->priv_data;
271     GetByteContext gb;
272     uint16_t tile_num, tile_row, tile_col;
273     uint32_t size = 0, size_bytes = 0;
274
275     bytestream2_init(&gb, tile_group->tile_data.data,
276                      tile_group->tile_data.data_size);
277     s->tg_start = tile_group->tg_start;
278     s->tg_end = tile_group->tg_end;
279
280     for (tile_num = tile_group->tg_start; tile_num <= tile_group->tg_end; tile_num++) {
281         tile_row = tile_num / s->raw_frame_header->tile_cols;
282         tile_col = tile_num % s->raw_frame_header->tile_cols;
283
284         if (tile_num == tile_group->tg_end) {
285             s->tile_group_info[tile_num].tile_size = bytestream2_get_bytes_left(&gb);
286             s->tile_group_info[tile_num].tile_offset = bytestream2_tell(&gb);
287             s->tile_group_info[tile_num].tile_row = tile_row;
288             s->tile_group_info[tile_num].tile_column = tile_col;
289             return 0;
290         }
291         size_bytes = s->raw_frame_header->tile_size_bytes_minus1 + 1;
292         if (bytestream2_get_bytes_left(&gb) < size_bytes)
293             return AVERROR_INVALIDDATA;
294         size = 0;
295         for (int i = 0; i < size_bytes; i++)
296             size |= bytestream2_get_byteu(&gb) << 8 * i;
297         if (bytestream2_get_bytes_left(&gb) <= size)
298             return AVERROR_INVALIDDATA;
299         size++;
300
301         s->tile_group_info[tile_num].tile_size = size;
302         s->tile_group_info[tile_num].tile_offset = bytestream2_tell(&gb);
303         s->tile_group_info[tile_num].tile_row = tile_row;
304         s->tile_group_info[tile_num].tile_column = tile_col;
305
306         bytestream2_skipu(&gb, size);
307     }
308
309     return 0;
310
311 }
312
313 static int get_pixel_format(AVCodecContext *avctx)
314 {
315     AV1DecContext *s = avctx->priv_data;
316     const AV1RawSequenceHeader *seq = s->raw_seq;
317     uint8_t bit_depth;
318     int ret;
319     enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
320 #define HWACCEL_MAX (CONFIG_AV1_DXVA2_HWACCEL + \
321                      CONFIG_AV1_D3D11VA_HWACCEL * 2 + \
322                      CONFIG_AV1_NVDEC_HWACCEL + \
323                      CONFIG_AV1_VAAPI_HWACCEL)
324     enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmtp = pix_fmts;
325
326     if (seq->seq_profile == 2 && seq->color_config.high_bitdepth)
327         bit_depth = seq->color_config.twelve_bit ? 12 : 10;
328     else if (seq->seq_profile <= 2)
329         bit_depth = seq->color_config.high_bitdepth ? 10 : 8;
330     else {
331         av_log(avctx, AV_LOG_ERROR,
332                "Unknown AV1 profile %d.\n", seq->seq_profile);
333         return -1;
334     }
335
336     if (!seq->color_config.mono_chrome) {
337         // 4:4:4 x:0 y:0, 4:2:2 x:1 y:0, 4:2:0 x:1 y:1
338         if (seq->color_config.subsampling_x == 0 &&
339             seq->color_config.subsampling_y == 0) {
340             if (bit_depth == 8)
341                 pix_fmt = AV_PIX_FMT_YUV444P;
342             else if (bit_depth == 10)
343                 pix_fmt = AV_PIX_FMT_YUV444P10;
344             else if (bit_depth == 12)
345                 pix_fmt = AV_PIX_FMT_YUV444P12;
346             else
347                 av_log(avctx, AV_LOG_WARNING, "Unknown AV1 pixel format.\n");
348         } else if (seq->color_config.subsampling_x == 1 &&
349                    seq->color_config.subsampling_y == 0) {
350             if (bit_depth == 8)
351                 pix_fmt = AV_PIX_FMT_YUV422P;
352             else if (bit_depth == 10)
353                 pix_fmt = AV_PIX_FMT_YUV422P10;
354             else if (bit_depth == 12)
355                 pix_fmt = AV_PIX_FMT_YUV422P12;
356             else
357                 av_log(avctx, AV_LOG_WARNING, "Unknown AV1 pixel format.\n");
358         } else if (seq->color_config.subsampling_x == 1 &&
359                    seq->color_config.subsampling_y == 1) {
360             if (bit_depth == 8)
361                 pix_fmt = AV_PIX_FMT_YUV420P;
362             else if (bit_depth == 10)
363                 pix_fmt = AV_PIX_FMT_YUV420P10;
364             else if (bit_depth == 12)
365                 pix_fmt = AV_PIX_FMT_YUV420P12;
366             else
367                 av_log(avctx, AV_LOG_WARNING, "Unknown AV1 pixel format.\n");
368         }
369     } else {
370         if (seq->color_config.subsampling_x == 1 &&
371             seq->color_config.subsampling_y == 1)
372             pix_fmt = AV_PIX_FMT_YUV440P;
373         else
374             av_log(avctx, AV_LOG_WARNING, "Unknown AV1 pixel format.\n");
375     }
376
377     av_log(avctx, AV_LOG_DEBUG, "AV1 decode get format: %s.\n",
378            av_get_pix_fmt_name(pix_fmt));
379
380     if (pix_fmt == AV_PIX_FMT_NONE)
381         return -1;
382     s->pix_fmt = pix_fmt;
383
384     switch (s->pix_fmt) {
385     case AV_PIX_FMT_YUV420P:
386 #if CONFIG_AV1_DXVA2_HWACCEL
387         *fmtp++ = AV_PIX_FMT_DXVA2_VLD;
388 #endif
389 #if CONFIG_AV1_D3D11VA_HWACCEL
390         *fmtp++ = AV_PIX_FMT_D3D11VA_VLD;
391         *fmtp++ = AV_PIX_FMT_D3D11;
392 #endif
393 #if CONFIG_AV1_NVDEC_HWACCEL
394         *fmtp++ = AV_PIX_FMT_CUDA;
395 #endif
396 #if CONFIG_AV1_VAAPI_HWACCEL
397         *fmtp++ = AV_PIX_FMT_VAAPI;
398 #endif
399         break;
400     case AV_PIX_FMT_YUV420P10:
401 #if CONFIG_AV1_DXVA2_HWACCEL
402         *fmtp++ = AV_PIX_FMT_DXVA2_VLD;
403 #endif
404 #if CONFIG_AV1_D3D11VA_HWACCEL
405         *fmtp++ = AV_PIX_FMT_D3D11VA_VLD;
406         *fmtp++ = AV_PIX_FMT_D3D11;
407 #endif
408 #if CONFIG_AV1_NVDEC_HWACCEL
409         *fmtp++ = AV_PIX_FMT_CUDA;
410 #endif
411 #if CONFIG_AV1_VAAPI_HWACCEL
412         *fmtp++ = AV_PIX_FMT_VAAPI;
413 #endif
414         break;
415     }
416
417     *fmtp++ = s->pix_fmt;
418     *fmtp = AV_PIX_FMT_NONE;
419
420     ret = ff_thread_get_format(avctx, pix_fmts);
421     if (ret < 0)
422         return ret;
423
424     /**
425      * check if the HW accel is inited correctly. If not, return un-implemented.
426      * Since now the av1 decoder doesn't support native decode, if it will be
427      * implemented in the future, need remove this check.
428      */
429     if (!avctx->hwaccel) {
430         av_log(avctx, AV_LOG_ERROR, "Your platform doesn't suppport"
431                " hardware accelerated AV1 decoding.\n");
432         return AVERROR(ENOSYS);
433     }
434
435     avctx->pix_fmt = ret;
436
437     return 0;
438 }
439
440 static void av1_frame_unref(AVCodecContext *avctx, AV1Frame *f)
441 {
442     ff_thread_release_buffer(avctx, &f->tf);
443     av_buffer_unref(&f->hwaccel_priv_buf);
444     f->hwaccel_picture_private = NULL;
445     av_buffer_unref(&f->header_ref);
446     f->raw_frame_header = NULL;
447     f->spatial_id = f->temporal_id = 0;
448     memset(f->skip_mode_frame_idx, 0,
449            2 * sizeof(uint8_t));
450     f->coded_lossless = 0;
451 }
452
453 static int av1_frame_ref(AVCodecContext *avctx, AV1Frame *dst, const AV1Frame *src)
454 {
455     int ret;
456
457     ret = ff_thread_ref_frame(&dst->tf, &src->tf);
458     if (ret < 0)
459         return ret;
460
461     dst->header_ref = av_buffer_ref(src->header_ref);
462     if (!dst->header_ref)
463         goto fail;
464
465     dst->raw_frame_header = src->raw_frame_header;
466
467     if (src->hwaccel_picture_private) {
468         dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
469         if (!dst->hwaccel_priv_buf)
470             goto fail;
471         dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
472     }
473
474     dst->spatial_id = src->spatial_id;
475     dst->temporal_id = src->temporal_id;
476     memcpy(dst->gm_type,
477            src->gm_type,
478            AV1_NUM_REF_FRAMES * sizeof(uint8_t));
479     memcpy(dst->gm_params,
480            src->gm_params,
481            AV1_NUM_REF_FRAMES * 6 * sizeof(int32_t));
482     memcpy(dst->skip_mode_frame_idx,
483            src->skip_mode_frame_idx,
484            2 * sizeof(uint8_t));
485     dst->coded_lossless = src->coded_lossless;
486
487     return 0;
488
489 fail:
490     av1_frame_unref(avctx, dst);
491     return AVERROR(ENOMEM);
492 }
493
494 static av_cold int av1_decode_free(AVCodecContext *avctx)
495 {
496     AV1DecContext *s = avctx->priv_data;
497
498     for (int i = 0; i < FF_ARRAY_ELEMS(s->ref); i++) {
499         av1_frame_unref(avctx, &s->ref[i]);
500         av_frame_free(&s->ref[i].tf.f);
501     }
502     av1_frame_unref(avctx, &s->cur_frame);
503     av_frame_free(&s->cur_frame.tf.f);
504
505     av_buffer_unref(&s->seq_ref);
506     av_buffer_unref(&s->header_ref);
507     av_freep(&s->tile_group_info);
508
509     ff_cbs_fragment_free(&s->current_obu);
510     ff_cbs_close(&s->cbc);
511
512     return 0;
513 }
514
515 static int set_context_with_sequence(AVCodecContext *avctx,
516                                      const AV1RawSequenceHeader *seq)
517 {
518     int width = seq->max_frame_width_minus_1 + 1;
519     int height = seq->max_frame_height_minus_1 + 1;
520
521     avctx->profile = seq->seq_profile;
522     avctx->level = seq->seq_level_idx[0];
523
524     avctx->color_range =
525         seq->color_config.color_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
526     avctx->color_primaries = seq->color_config.color_primaries;
527     avctx->colorspace = seq->color_config.color_primaries;
528     avctx->color_trc = seq->color_config.transfer_characteristics;
529
530     switch (seq->color_config.chroma_sample_position) {
531     case AV1_CSP_VERTICAL:
532         avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
533         break;
534     case AV1_CSP_COLOCATED:
535         avctx->chroma_sample_location = AVCHROMA_LOC_TOPLEFT;
536         break;
537     }
538
539     if (avctx->width != width || avctx->height != height) {
540         int ret = ff_set_dimensions(avctx, width, height);
541         if (ret < 0)
542             return ret;
543     }
544     avctx->sample_aspect_ratio = (AVRational) { 1, 1 };
545
546     if (seq->timing_info.num_units_in_display_tick &&
547         seq->timing_info.time_scale) {
548         av_reduce(&avctx->framerate.den, &avctx->framerate.num,
549                   seq->timing_info.num_units_in_display_tick,
550                   seq->timing_info.time_scale,
551                   INT_MAX);
552         if (seq->timing_info.equal_picture_interval)
553             avctx->ticks_per_frame = seq->timing_info.num_ticks_per_picture_minus_1 + 1;
554     }
555
556     return 0;
557 }
558
559 static int update_context_with_frame_header(AVCodecContext *avctx,
560                                             const AV1RawFrameHeader *header)
561 {
562     AVRational aspect_ratio;
563     int width = header->frame_width_minus_1 + 1;
564     int height = header->frame_height_minus_1 + 1;
565     int r_width = header->render_width_minus_1 + 1;
566     int r_height = header->render_height_minus_1 + 1;
567     int ret;
568
569     if (avctx->width != width || avctx->height != height) {
570         ret = ff_set_dimensions(avctx, width, height);
571         if (ret < 0)
572             return ret;
573     }
574
575     av_reduce(&aspect_ratio.num, &aspect_ratio.den,
576               (int64_t)height * r_width,
577               (int64_t)width * r_height,
578               INT_MAX);
579
580     if (av_cmp_q(avctx->sample_aspect_ratio, aspect_ratio)) {
581         ret = ff_set_sar(avctx, aspect_ratio);
582         if (ret < 0)
583             return ret;
584     }
585
586     return 0;
587 }
588
589 static av_cold int av1_decode_init(AVCodecContext *avctx)
590 {
591     AV1DecContext *s = avctx->priv_data;
592     AV1RawSequenceHeader *seq;
593     int ret;
594
595     s->avctx = avctx;
596     s->pix_fmt = AV_PIX_FMT_NONE;
597
598     for (int i = 0; i < FF_ARRAY_ELEMS(s->ref); i++) {
599         s->ref[i].tf.f = av_frame_alloc();
600         if (!s->ref[i].tf.f) {
601             av_log(avctx, AV_LOG_ERROR,
602                    "Failed to allocate reference frame buffer %d.\n", i);
603             return AVERROR(ENOMEM);
604         }
605     }
606
607     s->cur_frame.tf.f = av_frame_alloc();
608     if (!s->cur_frame.tf.f) {
609         av_log(avctx, AV_LOG_ERROR,
610                "Failed to allocate current frame buffer.\n");
611         return AVERROR(ENOMEM);
612     }
613
614     ret = ff_cbs_init(&s->cbc, AV_CODEC_ID_AV1, avctx);
615     if (ret < 0)
616         return ret;
617
618     if (avctx->extradata && avctx->extradata_size) {
619         ret = ff_cbs_read_extradata_from_codec(s->cbc,
620                                                &s->current_obu,
621                                                avctx);
622         if (ret < 0) {
623             av_log(avctx, AV_LOG_WARNING, "Failed to read extradata.\n");
624             return ret;
625         }
626
627         seq = ((CodedBitstreamAV1Context *)(s->cbc->priv_data))->sequence_header;
628         if (!seq) {
629             av_log(avctx, AV_LOG_WARNING, "No sequence header available.\n");
630             goto end;
631         }
632
633         ret = set_context_with_sequence(avctx, seq);
634         if (ret < 0) {
635             av_log(avctx, AV_LOG_WARNING, "Failed to set decoder context.\n");
636             goto end;
637         }
638
639         end:
640         ff_cbs_fragment_reset(&s->current_obu);
641     }
642
643     return ret;
644 }
645
646 static int av1_frame_alloc(AVCodecContext *avctx, AV1Frame *f)
647 {
648     AV1DecContext *s = avctx->priv_data;
649     AV1RawFrameHeader *header= s->raw_frame_header;
650     AVFrame *frame;
651     int ret;
652
653     f->header_ref = av_buffer_ref(s->header_ref);
654     if (!f->header_ref)
655         return AVERROR(ENOMEM);
656
657     f->raw_frame_header = s->raw_frame_header;
658
659     ret = update_context_with_frame_header(avctx, header);
660     if (ret < 0) {
661         av_log(avctx, AV_LOG_ERROR, "Failed to update context with frame header\n");
662         return ret;
663     }
664
665     if ((ret = ff_thread_get_buffer(avctx, &f->tf, AV_GET_BUFFER_FLAG_REF)) < 0)
666         return ret;
667
668     frame = f->tf.f;
669     frame->key_frame = header->frame_type == AV1_FRAME_KEY;
670
671     switch (header->frame_type) {
672     case AV1_FRAME_KEY:
673     case AV1_FRAME_INTRA_ONLY:
674         frame->pict_type = AV_PICTURE_TYPE_I;
675         break;
676     case AV1_FRAME_INTER:
677         frame->pict_type = AV_PICTURE_TYPE_P;
678         break;
679     case AV1_FRAME_SWITCH:
680         frame->pict_type = AV_PICTURE_TYPE_SP;
681         break;
682     }
683
684     if (avctx->hwaccel) {
685         const AVHWAccel *hwaccel = avctx->hwaccel;
686         if (hwaccel->frame_priv_data_size) {
687             f->hwaccel_priv_buf =
688                 av_buffer_allocz(hwaccel->frame_priv_data_size);
689             if (!f->hwaccel_priv_buf)
690                 goto fail;
691             f->hwaccel_picture_private = f->hwaccel_priv_buf->data;
692         }
693     }
694     return 0;
695
696 fail:
697     av1_frame_unref(avctx, f);
698     return AVERROR(ENOMEM);
699 }
700
701 static int set_output_frame(AVCodecContext *avctx, AVFrame *frame,
702                             const AVPacket *pkt, int *got_frame)
703 {
704     AV1DecContext *s = avctx->priv_data;
705     const AVFrame *srcframe = s->cur_frame.tf.f;
706     int ret;
707
708     ret = av_frame_ref(frame, srcframe);
709     if (ret < 0)
710         return ret;
711
712     frame->pts = pkt->pts;
713     frame->pkt_dts = pkt->dts;
714     frame->pkt_size = pkt->size;
715
716     *got_frame = 1;
717
718     return 0;
719 }
720
721 static int update_reference_list(AVCodecContext *avctx)
722 {
723     AV1DecContext *s = avctx->priv_data;
724     const AV1RawFrameHeader *header = s->raw_frame_header;
725     int ret;
726
727     for (int i = 0; i < AV1_NUM_REF_FRAMES; i++) {
728         if (header->refresh_frame_flags & (1 << i)) {
729             if (s->ref[i].tf.f->buf[0])
730                 av1_frame_unref(avctx, &s->ref[i]);
731             if ((ret = av1_frame_ref(avctx, &s->ref[i], &s->cur_frame)) < 0) {
732                 av_log(avctx, AV_LOG_ERROR,
733                        "Failed to update frame %d in reference list\n", i);
734                 return ret;
735             }
736         }
737     }
738     return 0;
739 }
740
741 static int get_current_frame(AVCodecContext *avctx)
742 {
743     AV1DecContext *s = avctx->priv_data;
744     int ret;
745
746     if (s->cur_frame.tf.f->buf[0])
747         av1_frame_unref(avctx, &s->cur_frame);
748
749     ret = av1_frame_alloc(avctx, &s->cur_frame);
750     if (ret < 0) {
751         av_log(avctx, AV_LOG_ERROR,
752                "Failed to allocate space for current frame.\n");
753         return ret;
754     }
755
756     ret = init_tile_data(s);
757     if (ret < 0) {
758         av_log(avctx, AV_LOG_ERROR, "Failed to init tile data.\n");
759         return ret;
760     }
761
762     global_motion_params(s);
763     skip_mode_params(s);
764     coded_lossless_param(s);
765
766     return ret;
767 }
768
769 static int av1_decode_frame(AVCodecContext *avctx, void *frame,
770                             int *got_frame, AVPacket *pkt)
771 {
772     AV1DecContext *s = avctx->priv_data;
773     AV1RawTileGroup *raw_tile_group = NULL;
774     int ret;
775
776     ret = ff_cbs_read_packet(s->cbc, &s->current_obu, pkt);
777     if (ret < 0) {
778         av_log(avctx, AV_LOG_ERROR, "Failed to read packet.\n");
779         goto end;
780     }
781     av_log(avctx, AV_LOG_DEBUG, "Total obu for this frame:%d.\n",
782            s->current_obu.nb_units);
783
784     for (int i = 0; i < s->current_obu.nb_units; i++) {
785         CodedBitstreamUnit *unit = &s->current_obu.units[i];
786         AV1RawOBU *obu = unit->content;
787         const AV1RawOBUHeader *header;
788
789         if (!obu)
790             continue;
791
792         header = &obu->header;
793         av_log(avctx, AV_LOG_DEBUG, "Obu idx:%d, obu type:%d.\n", i, unit->type);
794
795         switch (unit->type) {
796         case AV1_OBU_SEQUENCE_HEADER:
797             av_buffer_unref(&s->seq_ref);
798             s->seq_ref = av_buffer_ref(unit->content_ref);
799             if (!s->seq_ref) {
800                 ret = AVERROR(ENOMEM);
801                 goto end;
802             }
803
804             s->raw_seq = &obu->obu.sequence_header;
805
806             ret = set_context_with_sequence(avctx, s->raw_seq);
807             if (ret < 0) {
808                 av_log(avctx, AV_LOG_ERROR, "Failed to set context.\n");
809                 s->raw_seq = NULL;
810                 goto end;
811             }
812
813             if (s->pix_fmt == AV_PIX_FMT_NONE) {
814                 ret = get_pixel_format(avctx);
815                 if (ret < 0) {
816                     av_log(avctx, AV_LOG_ERROR,
817                            "Failed to get pixel format.\n");
818                     s->raw_seq = NULL;
819                     goto end;
820                 }
821             }
822
823             if (avctx->hwaccel && avctx->hwaccel->decode_params) {
824                 ret = avctx->hwaccel->decode_params(avctx, unit->type, unit->data,
825                                                     unit->data_size);
826                 if (ret < 0) {
827                     av_log(avctx, AV_LOG_ERROR, "HW accel decode params fail.\n");
828                     s->raw_seq = NULL;
829                     goto end;
830                 }
831             }
832             break;
833         case AV1_OBU_REDUNDANT_FRAME_HEADER:
834             if (s->raw_frame_header)
835                 break;
836         // fall-through
837         case AV1_OBU_FRAME:
838         case AV1_OBU_FRAME_HEADER:
839             if (!s->raw_seq) {
840                 av_log(avctx, AV_LOG_ERROR, "Missing Sequence Header.\n");
841                 ret = AVERROR_INVALIDDATA;
842                 goto end;
843             }
844
845             av_buffer_unref(&s->header_ref);
846             s->header_ref = av_buffer_ref(unit->content_ref);
847             if (!s->header_ref) {
848                 ret = AVERROR(ENOMEM);
849                 goto end;
850             }
851
852             if (unit->type == AV1_OBU_FRAME)
853                 s->raw_frame_header = &obu->obu.frame.header;
854             else
855                 s->raw_frame_header = &obu->obu.frame_header;
856
857             if (s->raw_frame_header->show_existing_frame) {
858                 if (s->cur_frame.tf.f->buf[0])
859                     av1_frame_unref(avctx, &s->cur_frame);
860
861                 ret = av1_frame_ref(avctx, &s->cur_frame,
862                                     &s->ref[s->raw_frame_header->frame_to_show_map_idx]);
863                 if (ret < 0) {
864                     av_log(avctx, AV_LOG_ERROR, "Failed to get reference frame.\n");
865                     goto end;
866                 }
867
868                 ret = update_reference_list(avctx);
869                 if (ret < 0) {
870                     av_log(avctx, AV_LOG_ERROR, "Failed to update reference list.\n");
871                     goto end;
872                 }
873
874                 ret = set_output_frame(avctx, frame, pkt, got_frame);
875                 if (ret < 0)
876                     av_log(avctx, AV_LOG_ERROR, "Set output frame error.\n");
877
878                 s->raw_frame_header = NULL;
879
880                 goto end;
881             }
882
883             ret = get_current_frame(avctx);
884             if (ret < 0) {
885                 av_log(avctx, AV_LOG_ERROR, "Get current frame error\n");
886                 goto end;
887             }
888
889             s->cur_frame.spatial_id  = header->spatial_id;
890             s->cur_frame.temporal_id = header->temporal_id;
891
892             if (avctx->hwaccel) {
893                 ret = avctx->hwaccel->start_frame(avctx, unit->data,
894                                                   unit->data_size);
895                 if (ret < 0) {
896                     av_log(avctx, AV_LOG_ERROR, "HW accel start frame fail.\n");
897                     goto end;
898                 }
899             }
900             if (unit->type != AV1_OBU_FRAME)
901                 break;
902         // fall-through
903         case AV1_OBU_TILE_GROUP:
904             if (!s->raw_frame_header) {
905                 av_log(avctx, AV_LOG_ERROR, "Missing Frame Header.\n");
906                 ret = AVERROR_INVALIDDATA;
907                 goto end;
908             }
909
910             if (unit->type == AV1_OBU_FRAME)
911                 raw_tile_group = &obu->obu.frame.tile_group;
912             else
913                 raw_tile_group = &obu->obu.tile_group;
914
915             ret = get_tiles_info(avctx, raw_tile_group);
916             if (ret < 0)
917                 goto end;
918
919             if (avctx->hwaccel) {
920                 ret = avctx->hwaccel->decode_slice(avctx,
921                                                    raw_tile_group->tile_data.data,
922                                                    raw_tile_group->tile_data.data_size);
923                 if (ret < 0) {
924                     av_log(avctx, AV_LOG_ERROR,
925                            "HW accel decode slice fail.\n");
926                     goto end;
927                 }
928             }
929             break;
930         case AV1_OBU_TILE_LIST:
931         case AV1_OBU_TEMPORAL_DELIMITER:
932         case AV1_OBU_PADDING:
933         case AV1_OBU_METADATA:
934             break;
935         default:
936             av_log(avctx, AV_LOG_DEBUG,
937                    "Unknown obu type: %d (%"SIZE_SPECIFIER" bits).\n",
938                    unit->type, unit->data_size);
939         }
940
941         if (raw_tile_group && (s->tile_num == raw_tile_group->tg_end + 1)) {
942             if (avctx->hwaccel) {
943                 ret = avctx->hwaccel->end_frame(avctx);
944                 if (ret < 0) {
945                     av_log(avctx, AV_LOG_ERROR, "HW accel end frame fail.\n");
946                     goto end;
947                 }
948             }
949
950             ret = update_reference_list(avctx);
951             if (ret < 0) {
952                 av_log(avctx, AV_LOG_ERROR, "Failed to update reference list.\n");
953                 goto end;
954             }
955
956             if (s->raw_frame_header->show_frame) {
957                 ret = set_output_frame(avctx, frame, pkt, got_frame);
958                 if (ret < 0) {
959                     av_log(avctx, AV_LOG_ERROR, "Set output frame error\n");
960                     goto end;
961                 }
962             }
963             raw_tile_group = NULL;
964             s->raw_frame_header = NULL;
965         }
966     }
967
968 end:
969     ff_cbs_fragment_reset(&s->current_obu);
970     if (ret < 0)
971         s->raw_frame_header = NULL;
972     return ret;
973 }
974
975 static void av1_decode_flush(AVCodecContext *avctx)
976 {
977     AV1DecContext *s = avctx->priv_data;
978
979     for (int i = 0; i < FF_ARRAY_ELEMS(s->ref); i++)
980         av1_frame_unref(avctx, &s->ref[i]);
981
982     av1_frame_unref(avctx, &s->cur_frame);
983     s->raw_frame_header = NULL;
984     s->raw_seq = NULL;
985
986     ff_cbs_flush(s->cbc);
987 }
988
989 AVCodec ff_av1_decoder = {
990     .name                  = "av1",
991     .long_name             = NULL_IF_CONFIG_SMALL("Alliance for Open Media AV1"),
992     .type                  = AVMEDIA_TYPE_VIDEO,
993     .id                    = AV_CODEC_ID_AV1,
994     .priv_data_size        = sizeof(AV1DecContext),
995     .init                  = av1_decode_init,
996     .close                 = av1_decode_free,
997     .decode                = av1_decode_frame,
998     .capabilities          = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_AVOID_PROBING,
999     .caps_internal         = FF_CODEC_CAP_INIT_THREADSAFE |
1000                              FF_CODEC_CAP_INIT_CLEANUP |
1001                              FF_CODEC_CAP_SETS_PKT_DTS,
1002     .flush                 = av1_decode_flush,
1003     .profiles              = NULL_IF_CONFIG_SMALL(ff_av1_profiles),
1004     .hw_configs            = (const AVCodecHWConfigInternal * []) {
1005 #if CONFIG_AV1_DXVA2_HWACCEL
1006         HWACCEL_DXVA2(av1),
1007 #endif
1008 #if CONFIG_AV1_D3D11VA_HWACCEL
1009         HWACCEL_D3D11VA(av1),
1010 #endif
1011 #if CONFIG_AV1_D3D11VA2_HWACCEL
1012         HWACCEL_D3D11VA2(av1),
1013 #endif
1014 #if CONFIG_AV1_NVDEC_HWACCEL
1015         HWACCEL_NVDEC(av1),
1016 #endif
1017 #if CONFIG_AV1_VAAPI_HWACCEL
1018         HWACCEL_VAAPI(av1),
1019 #endif
1020         NULL
1021     },
1022 };