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