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