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