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