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