obu.c 48.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
/*
 * Copyright © 2018, VideoLAN and dav1d authors
 * Copyright © 2018, Two Orioles, LLC
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>

#include "dav1d/data.h"

#include "common/intops.h"

#include "src/decode.h"
#include "src/getbits.h"
#include "src/levels.h"
#include "src/obu.h"
#include "src/ref.h"
#include "src/warpmv.h"

46 47 48
static int parse_seq_hdr(Dav1dContext *const c, GetBits *const gb,
                         Av1SequenceHeader *const hdr)
{
49 50 51 52
    const uint8_t *const init_ptr = gb->ptr;

#define DEBUG_SEQ_HDR 0

53
    hdr->profile = dav1d_get_bits(gb, 3);
54
    if (hdr->profile > 2) goto error;
55 56 57 58 59
#if DEBUG_SEQ_HDR
    printf("SEQHDR: post-profile: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

60 61
    hdr->still_picture = dav1d_get_bits(gb, 1);
    hdr->reduced_still_picture_header = dav1d_get_bits(gb, 1);
62 63 64 65 66 67 68 69 70 71 72 73
    if (hdr->reduced_still_picture_header && !hdr->still_picture) goto error;
#if DEBUG_SEQ_HDR
    printf("SEQHDR: post-stillpicture_flags: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

    if (hdr->reduced_still_picture_header) {
        hdr->timing_info_present = 0;
        hdr->decoder_model_info_present = 0;
        hdr->display_model_info_present = 0;
        hdr->num_operating_points = 1;
        hdr->operating_points[0].idc = 0;
74 75
        hdr->operating_points[0].major_level = dav1d_get_bits(gb, 3);
        hdr->operating_points[0].minor_level = dav1d_get_bits(gb, 2);
76 77 78 79
        hdr->operating_points[0].tier = 0;
        hdr->operating_points[0].decoder_model_param_present = 0;
        hdr->operating_points[0].display_model_param_present = 0;
    } else {
80
        hdr->timing_info_present = dav1d_get_bits(gb, 1);
81
        if (hdr->timing_info_present) {
82 83 84
            hdr->num_units_in_tick = dav1d_get_bits(gb, 32);
            hdr->time_scale = dav1d_get_bits(gb, 32);
            hdr->equal_picture_interval = dav1d_get_bits(gb, 1);
85
            if (hdr->equal_picture_interval)
86
                hdr->num_ticks_per_picture = dav1d_get_vlc(gb) + 1;
87

88
            hdr->decoder_model_info_present = dav1d_get_bits(gb, 1);
89
            if (hdr->decoder_model_info_present) {
90 91 92 93
                hdr->encoder_decoder_buffer_delay_length = dav1d_get_bits(gb, 5) + 1;
                hdr->num_units_in_decoding_tick = dav1d_get_bits(gb, 32);
                hdr->buffer_removal_delay_length = dav1d_get_bits(gb, 5) + 1;
                hdr->frame_presentation_delay_length = dav1d_get_bits(gb, 5) + 1;
94 95 96 97 98 99 100 101 102
            }
        } else {
            hdr->decoder_model_info_present = 0;
        }
#if DEBUG_SEQ_HDR
        printf("SEQHDR: post-timinginfo: off=%ld\n",
               (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

103 104
        hdr->display_model_info_present = dav1d_get_bits(gb, 1);
        hdr->num_operating_points = dav1d_get_bits(gb, 5) + 1;
105
        for (int i = 0; i < hdr->num_operating_points; i++) {
106 107
            struct Av1SequenceHeaderOperatingPoint *const op =
                &hdr->operating_points[i];
108 109 110 111
            op->idc = dav1d_get_bits(gb, 12);
            op->major_level = 2 + dav1d_get_bits(gb, 3);
            op->minor_level = dav1d_get_bits(gb, 2);
            op->tier = op->major_level > 3 ? dav1d_get_bits(gb, 1) : 0;
112
            op->decoder_model_param_present =
113
                hdr->decoder_model_info_present && dav1d_get_bits(gb, 1);
114 115
            if (op->decoder_model_param_present) {
                op->decoder_buffer_delay =
116
                    dav1d_get_bits(gb, hdr->encoder_decoder_buffer_delay_length);
117
                op->encoder_buffer_delay =
118 119
                    dav1d_get_bits(gb, hdr->encoder_decoder_buffer_delay_length);
                op->low_delay_mode = dav1d_get_bits(gb, 1);
120 121
            }
            op->display_model_param_present =
122
                hdr->display_model_info_present && dav1d_get_bits(gb, 1);
123
            if (op->display_model_param_present) {
124
                op->initial_display_delay = dav1d_get_bits(gb, 4) + 1;
125 126 127 128 129 130 131 132
            }
        }
#if DEBUG_SEQ_HDR
        printf("SEQHDR: post-operating-points: off=%ld\n",
               (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif
    }

133 134 135 136
    hdr->width_n_bits = dav1d_get_bits(gb, 4) + 1;
    hdr->height_n_bits = dav1d_get_bits(gb, 4) + 1;
    hdr->max_width = dav1d_get_bits(gb, hdr->width_n_bits) + 1;
    hdr->max_height = dav1d_get_bits(gb, hdr->height_n_bits) + 1;
137 138 139 140 141
#if DEBUG_SEQ_HDR
    printf("SEQHDR: post-size: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif
    hdr->frame_id_numbers_present =
142
        hdr->reduced_still_picture_header ? 0 : dav1d_get_bits(gb, 1);
143
    if (hdr->frame_id_numbers_present) {
144 145
        hdr->delta_frame_id_n_bits = dav1d_get_bits(gb, 4) + 2;
        hdr->frame_id_n_bits = dav1d_get_bits(gb, 3) + hdr->delta_frame_id_n_bits + 1;
146 147 148 149 150 151
    }
#if DEBUG_SEQ_HDR
    printf("SEQHDR: post-frame-id-numbers-present: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

152 153 154
    hdr->sb128 = dav1d_get_bits(gb, 1);
    hdr->filter_intra = dav1d_get_bits(gb, 1);
    hdr->intra_edge_filter = dav1d_get_bits(gb, 1);
155 156 157 158 159 160 161 162 163 164 165 166
    if (hdr->reduced_still_picture_header) {
        hdr->inter_intra = 0;
        hdr->masked_compound = 0;
        hdr->warped_motion = 0;
        hdr->dual_filter = 0;
        hdr->order_hint = 0;
        hdr->jnt_comp = 0;
        hdr->ref_frame_mvs = 0;
        hdr->order_hint_n_bits = 0;
        hdr->screen_content_tools = ADAPTIVE;
        hdr->force_integer_mv = ADAPTIVE;
    } else {
167 168 169 170 171
        hdr->inter_intra = dav1d_get_bits(gb, 1);
        hdr->masked_compound = dav1d_get_bits(gb, 1);
        hdr->warped_motion = dav1d_get_bits(gb, 1);
        hdr->dual_filter = dav1d_get_bits(gb, 1);
        hdr->order_hint = dav1d_get_bits(gb, 1);
172
        if (hdr->order_hint) {
173 174
            hdr->jnt_comp = dav1d_get_bits(gb, 1);
            hdr->ref_frame_mvs = dav1d_get_bits(gb, 1);
175 176 177 178 179
        } else {
            hdr->jnt_comp = 0;
            hdr->ref_frame_mvs = 0;
            hdr->order_hint_n_bits = 0;
        }
180
        hdr->screen_content_tools = dav1d_get_bits(gb, 1) ? ADAPTIVE : dav1d_get_bits(gb, 1);
181 182 183 184 185
    #if DEBUG_SEQ_HDR
        printf("SEQHDR: post-screentools: off=%ld\n",
               (gb->ptr - init_ptr) * 8 - gb->bits_left);
    #endif
        hdr->force_integer_mv = hdr->screen_content_tools ?
186
                                dav1d_get_bits(gb, 1) ? ADAPTIVE : dav1d_get_bits(gb, 1) : 2;
187
        if (hdr->order_hint)
188
            hdr->order_hint_n_bits = dav1d_get_bits(gb, 3) + 1;
189
    }
190 191 192
    hdr->super_res = dav1d_get_bits(gb, 1);
    hdr->cdef = dav1d_get_bits(gb, 1);
    hdr->restoration = dav1d_get_bits(gb, 1);
193 194 195 196 197
#if DEBUG_SEQ_HDR
    printf("SEQHDR: post-featurebits: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

198
    const int hbd = dav1d_get_bits(gb, 1);
skal's avatar
skal committed
199
    hdr->bpc = hdr->profile == 2 && hbd ? 10U + 2 * dav1d_get_bits(gb, 1) : 8U + 2 * hbd;
200
    hdr->hbd = hdr->bpc > 8;
201 202
    const int monochrome = hdr->profile != 1 ? dav1d_get_bits(gb, 1) : 0;
    hdr->color_description_present = dav1d_get_bits(gb, 1);
203
    if (hdr->color_description_present) {
204 205 206
        hdr->pri = dav1d_get_bits(gb, 8);
        hdr->trc = dav1d_get_bits(gb, 8);
        hdr->mtrx = dav1d_get_bits(gb, 8);
207 208 209 210 211 212
    } else {
        hdr->pri = DAV1D_COLOR_PRI_UNKNOWN;
        hdr->trc = DAV1D_TRC_UNKNOWN;
        hdr->mtrx = DAV1D_MC_UNKNOWN;
    }
    if (monochrome) {
213
        hdr->color_range = dav1d_get_bits(gb, 1);
214 215 216 217 218 219 220 221 222 223 224 225
        hdr->layout = DAV1D_PIXEL_LAYOUT_I400;
        hdr->chr = DAV1D_CHR_UNKNOWN;
        hdr->separate_uv_delta_q = 0;
    } else if (hdr->pri == DAV1D_COLOR_PRI_BT709 &&
               hdr->trc == DAV1D_TRC_SRGB &&
               hdr->mtrx == DAV1D_MC_IDENTITY)
    {
        hdr->layout = DAV1D_PIXEL_LAYOUT_I444;
        hdr->color_range = 1;
        if (hdr->profile != 1 && !(hdr->profile == 2 && hdr->bpc == 12))
            goto error;
    } else {
226
        hdr->color_range = dav1d_get_bits(gb, 1);
227 228 229 230 231
        switch (hdr->profile) {
        case 0: hdr->layout = DAV1D_PIXEL_LAYOUT_I420; break;
        case 1: hdr->layout = DAV1D_PIXEL_LAYOUT_I444; break;
        case 2:
            if (hdr->bpc == 12) {
232 233 234 235
                hdr->layout = dav1d_get_bits(gb, 1) ?
                              dav1d_get_bits(gb, 1) ? DAV1D_PIXEL_LAYOUT_I420 :
                                                      DAV1D_PIXEL_LAYOUT_I422 :
                                                      DAV1D_PIXEL_LAYOUT_I444;
236 237 238 239 240
            } else
                hdr->layout = DAV1D_PIXEL_LAYOUT_I422;
            break;
        }
        if (hdr->layout == DAV1D_PIXEL_LAYOUT_I420)
241 242
            hdr->chr = dav1d_get_bits(gb, 2);
        hdr->separate_uv_delta_q = dav1d_get_bits(gb, 1);
243 244 245 246 247 248
    }
#if DEBUG_SEQ_HDR
    printf("SEQHDR: post-colorinfo: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

249
    hdr->film_grain_present = dav1d_get_bits(gb, 1);
250 251 252 253 254
#if DEBUG_SEQ_HDR
    printf("SEQHDR: post-filmgrain: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

255
    dav1d_get_bits(gb, 1); // dummy bit
256

257
    return dav1d_flush_get_bits(gb) - init_ptr;
258 259 260 261 262 263 264 265 266 267 268 269 270 271

error:
    fprintf(stderr, "Error parsing sequence header\n");
    return -EINVAL;
}

static int read_frame_size(Dav1dContext *const c, GetBits *const gb,
                           const int use_ref)
{
    const Av1SequenceHeader *const seqhdr = &c->seq_hdr;
    Av1FrameHeader *const hdr = &c->frame_hdr;

    if (use_ref) {
        for (int i = 0; i < 7; i++) {
272
            if (dav1d_get_bits(gb, 1)) {
273 274 275 276 277 278 279 280 281 282 283 284 285
                Dav1dThreadPicture *const ref =
                    &c->refs[c->frame_hdr.refidx[i]].p;
                if (!ref->p.data[0]) return -1;
                // FIXME render_* may be wrong
                hdr->render_width = hdr->width = ref->p.p.w;
                hdr->render_height = hdr->height = ref->p.p.h;
                hdr->super_res = 0; // FIXME probably wrong
                return 0;
            }
        }
    }

    if (hdr->frame_size_override) {
286 287
        hdr->width = dav1d_get_bits(gb, seqhdr->width_n_bits) + 1;
        hdr->height = dav1d_get_bits(gb, seqhdr->height_n_bits) + 1;
288 289 290 291
    } else {
        hdr->width = seqhdr->max_width;
        hdr->height = seqhdr->max_height;
    }
292
    hdr->super_res = seqhdr->super_res && dav1d_get_bits(gb, 1);
293
    if (hdr->super_res) return -1; // FIXME
294
    hdr->have_render_size = dav1d_get_bits(gb, 1);
295
    if (hdr->have_render_size) {
296 297
        hdr->render_width = dav1d_get_bits(gb, seqhdr->width_n_bits) + 1;
        hdr->render_height = dav1d_get_bits(gb, seqhdr->height_n_bits) + 1;
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    } else {
        hdr->render_width = hdr->width;
        hdr->render_height = hdr->height;
    }
    return 0;
}

static inline int tile_log2(int sz, int tgt) {
    int k;
    for (k = 0; (sz << k) < tgt; k++) ;
    return k;
}

static const Av1LoopfilterModeRefDeltas default_mode_ref_deltas = {
    .mode_delta = { 0, 0 },
    .ref_delta = { 1, 0, 0, 0, -1, 0, -1, -1 },
};

static int parse_frame_hdr(Dav1dContext *const c, GetBits *const gb,
                           const int have_trailing_bit)
{
    const uint8_t *const init_ptr = gb->ptr;
    const Av1SequenceHeader *const seqhdr = &c->seq_hdr;
    Av1FrameHeader *const hdr = &c->frame_hdr;
    int res;

#define DEBUG_FRAME_HDR 0

    hdr->show_existing_frame =
327
        !seqhdr->reduced_still_picture_header && dav1d_get_bits(gb, 1);
328 329 330 331 332
#if DEBUG_FRAME_HDR
    printf("HDR: post-show_existing_frame: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif
    if (hdr->show_existing_frame) {
333
        hdr->existing_frame_idx = dav1d_get_bits(gb, 3);
334 335
        if (seqhdr->decoder_model_info_present && !seqhdr->equal_picture_interval)
            hdr->frame_presentation_delay = dav1d_get_bits(gb, seqhdr->frame_presentation_delay_length);
336
        if (seqhdr->frame_id_numbers_present)
337
            hdr->frame_id = dav1d_get_bits(gb, seqhdr->frame_id_n_bits);
338 339 340
        goto end;
    }

341 342
    hdr->frame_type = seqhdr->reduced_still_picture_header ? DAV1D_FRAME_TYPE_KEY : dav1d_get_bits(gb, 2);
    hdr->show_frame = seqhdr->reduced_still_picture_header || dav1d_get_bits(gb, 1);
343 344 345 346
    if (hdr->show_frame) {
        if (seqhdr->decoder_model_info_present && !seqhdr->equal_picture_interval)
            hdr->frame_presentation_delay = dav1d_get_bits(gb, seqhdr->frame_presentation_delay_length);
    } else
347
        hdr->showable_frame = dav1d_get_bits(gb, 1);
348
    hdr->error_resilient_mode =
349 350
        (hdr->frame_type == DAV1D_FRAME_TYPE_KEY && hdr->show_frame) ||
        hdr->frame_type == DAV1D_FRAME_TYPE_SWITCH ||
351
        seqhdr->reduced_still_picture_header || dav1d_get_bits(gb, 1);
352 353 354 355
#if DEBUG_FRAME_HDR
    printf("HDR: post-frametype_bits: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif
356
    hdr->disable_cdf_update = dav1d_get_bits(gb, 1);
357
    hdr->allow_screen_content_tools = seqhdr->screen_content_tools == ADAPTIVE ?
358
                                 dav1d_get_bits(gb, 1) : seqhdr->screen_content_tools;
359 360
    if (hdr->allow_screen_content_tools)
        hdr->force_integer_mv = seqhdr->force_integer_mv == ADAPTIVE ?
361
                                dav1d_get_bits(gb, 1) : seqhdr->force_integer_mv;
362 363 364 365 366
    else
        hdr->force_integer_mv = 0;

    if (!(hdr->frame_type & 1))
        hdr->force_integer_mv = 1;
367 368

    if (seqhdr->frame_id_numbers_present)
369
        hdr->frame_id = dav1d_get_bits(gb, seqhdr->frame_id_n_bits);
370 371

    hdr->frame_size_override = seqhdr->reduced_still_picture_header ? 0 :
372
                               hdr->frame_type == DAV1D_FRAME_TYPE_SWITCH ? 1 : dav1d_get_bits(gb, 1);
373 374 375 376 377
#if DEBUG_FRAME_HDR
    printf("HDR: post-frame_size_override_flag: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif
    hdr->frame_offset = seqhdr->order_hint ?
378
                        dav1d_get_bits(gb, seqhdr->order_hint_n_bits) : 0;
379
    hdr->primary_ref_frame = !hdr->error_resilient_mode && hdr->frame_type & 1 ?
380
                             dav1d_get_bits(gb, 3) : PRIMARY_REF_NONE;
381

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    if (seqhdr->decoder_model_info_present) {
        hdr->buffer_removal_time_present = dav1d_get_bits(gb, 1);
        if (hdr->buffer_removal_time_present) {
            for (int i = 0; i < c->seq_hdr.num_operating_points; i++) {
                const struct Av1SequenceHeaderOperatingPoint *const seqop = &seqhdr->operating_points[i];
                struct Av1FrameHeaderOperatingPoint *const op = &hdr->operating_points[i];
                if (seqop->decoder_model_param_present) {
                    int in_temporal_layer = (seqop->idc >>  0 /* FIXME: temporal_id */ ) & 1;
                    int in_spatial_layer  = (seqop->idc >> (0 /* FIXME: spatial_id */ + 8)) & 1;
                    if (!seqop->idc || in_temporal_layer || in_spatial_layer)
                        op->buffer_removal_time = dav1d_get_bits(gb, seqhdr->buffer_removal_delay_length);
                }
            }
        }
    }

James Almer's avatar
James Almer committed
398 399 400 401 402
    if (hdr->frame_type == DAV1D_FRAME_TYPE_KEY ||
        hdr->frame_type == DAV1D_FRAME_TYPE_INTRA)
    {
        hdr->refresh_frame_flags = (hdr->frame_type == DAV1D_FRAME_TYPE_KEY &&
                                    hdr->show_frame) ? 0xff : dav1d_get_bits(gb, 8);
403 404 405
        if (hdr->refresh_frame_flags != 0xff && hdr->error_resilient_mode && seqhdr->order_hint)
            for (int i = 0; i < 8; i++)
                dav1d_get_bits(gb, seqhdr->order_hint_n_bits);
406 407
        if ((res = read_frame_size(c, gb, 0)) < 0) goto error;
        hdr->allow_intrabc = hdr->allow_screen_content_tools &&
408
                             /* FIXME: no superres scaling && */ dav1d_get_bits(gb, 1);
409 410
        hdr->use_ref_frame_mvs = 0;
    } else {
James Almer's avatar
James Almer committed
411 412 413 414 415 416 417 418 419 420 421 422 423
        hdr->allow_intrabc = 0;
        hdr->refresh_frame_flags = hdr->frame_type == DAV1D_FRAME_TYPE_SWITCH ? 0xff :
                                   dav1d_get_bits(gb, 8);
        if (hdr->error_resilient_mode && seqhdr->order_hint)
            for (int i = 0; i < 8; i++)
                dav1d_get_bits(gb, seqhdr->order_hint_n_bits);
        hdr->frame_ref_short_signaling =
            seqhdr->order_hint && dav1d_get_bits(gb, 1);
        if (hdr->frame_ref_short_signaling) goto error; // FIXME
        for (int i = 0; i < 7; i++) {
            hdr->refidx[i] = dav1d_get_bits(gb, 3);
            if (seqhdr->frame_id_numbers_present)
                dav1d_get_bits(gb, seqhdr->delta_frame_id_n_bits);
424
        }
James Almer's avatar
James Almer committed
425 426 427 428 429 430 431 432 433 434
        const int use_ref = !hdr->error_resilient_mode &&
                            hdr->frame_size_override;
        if ((res = read_frame_size(c, gb, use_ref)) < 0) goto error;
        hdr->hp = !hdr->force_integer_mv && dav1d_get_bits(gb, 1);
        hdr->subpel_filter_mode = dav1d_get_bits(gb, 1) ? FILTER_SWITCHABLE :
                                                          dav1d_get_bits(gb, 2);
        hdr->switchable_motion_mode = dav1d_get_bits(gb, 1);
        hdr->use_ref_frame_mvs = !hdr->error_resilient_mode &&
            seqhdr->ref_frame_mvs && seqhdr->order_hint &&
            hdr->frame_type & 1 && dav1d_get_bits(gb, 1);
435 436 437 438 439 440 441
    }
#if DEBUG_FRAME_HDR
    printf("HDR: post-frametype-specific-bits: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

    hdr->refresh_context = !seqhdr->reduced_still_picture_header &&
442
                           !hdr->disable_cdf_update && !dav1d_get_bits(gb, 1);
443 444 445 446 447 448
#if DEBUG_FRAME_HDR
    printf("HDR: post-refresh_context: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

    // tile data
449
    hdr->tiling.uniform = dav1d_get_bits(gb, 1);
450 451 452 453 454 455 456 457 458 459 460 461 462
    const int sbsz_min1 = (64 << seqhdr->sb128) - 1;
    int sbsz_log2 = 6 + seqhdr->sb128;
    int sbw = (hdr->width + sbsz_min1) >> sbsz_log2;
    int sbh = (hdr->height + sbsz_min1) >> sbsz_log2;
    int max_tile_width_sb = 4096 >> sbsz_log2, max_tile_height_sb;
    int max_tile_area_sb = 4096 * 2304 >> (2 * sbsz_log2);
    hdr->tiling.min_log2_cols = tile_log2(max_tile_width_sb, sbw);
    hdr->tiling.max_log2_cols = tile_log2(1, imin(sbw, 1024));
    hdr->tiling.max_log2_rows = tile_log2(1, imin(sbh, 1024));
    int min_log2_tiles = imax(tile_log2(max_tile_area_sb, sbw * sbh),
                              hdr->tiling.min_log2_cols);
    if (hdr->tiling.uniform) {
        for (hdr->tiling.log2_cols = hdr->tiling.min_log2_cols;
463
             hdr->tiling.log2_cols < hdr->tiling.max_log2_cols && dav1d_get_bits(gb, 1);
464 465 466 467 468 469 470 471 472 473
             hdr->tiling.log2_cols++) ;
        const int tile_w = 1 + ((sbw - 1) >> hdr->tiling.log2_cols);
        hdr->tiling.cols = 0;
        for (int sbx = 0; sbx < sbw; sbx += tile_w, hdr->tiling.cols++)
            hdr->tiling.col_start_sb[hdr->tiling.cols] = sbx;
        hdr->tiling.min_log2_rows =
            imax(min_log2_tiles - hdr->tiling.log2_cols, 0);
        max_tile_height_sb = sbh >> hdr->tiling.min_log2_rows;

        for (hdr->tiling.log2_rows = hdr->tiling.min_log2_rows;
474
             hdr->tiling.log2_rows < hdr->tiling.max_log2_rows && dav1d_get_bits(gb, 1);
475 476 477 478 479 480 481 482 483
             hdr->tiling.log2_rows++) ;
        const int tile_h = 1 + ((sbh - 1) >> hdr->tiling.log2_rows);
        hdr->tiling.rows = 0;
        for (int sby = 0; sby < sbh; sby += tile_h, hdr->tiling.rows++)
            hdr->tiling.row_start_sb[hdr->tiling.rows] = sby;
    } else {
        hdr->tiling.cols = 0;
        int widest_tile = 0, max_tile_area_sb = sbw * sbh;
        for (int sbx = 0; sbx < sbw; hdr->tiling.cols++) {
484 485 486 487
            const int tile_width_sb = imin(sbw - sbx, max_tile_width_sb);
            const int tile_w = (tile_width_sb > 1) ?
                                   1 + dav1d_get_uniform(gb, tile_width_sb) :
                                   1;
488 489 490 491 492 493 494 495 496 497
            hdr->tiling.col_start_sb[hdr->tiling.cols] = sbx;
            sbx += tile_w;
            widest_tile = imax(widest_tile, tile_w);
        }
        hdr->tiling.log2_cols = tile_log2(1, hdr->tiling.cols);
        if (min_log2_tiles) max_tile_area_sb >>= min_log2_tiles + 1;
        max_tile_height_sb = imax(max_tile_area_sb / widest_tile, 1);

        hdr->tiling.rows = 0;
        for (int sby = 0; sby < sbh; hdr->tiling.rows++) {
498 499 500 501
            const int tile_height_sb = imin(sbh - sby, max_tile_height_sb);
            const int tile_h = (tile_height_sb > 1) ?
                                   1 + dav1d_get_uniform(gb, tile_height_sb) :
                                   1;
502 503 504 505 506 507 508 509
            hdr->tiling.row_start_sb[hdr->tiling.rows] = sby;
            sby += tile_h;
        }
        hdr->tiling.log2_rows = tile_log2(1, hdr->tiling.rows);
    }
    hdr->tiling.col_start_sb[hdr->tiling.cols] = sbw;
    hdr->tiling.row_start_sb[hdr->tiling.rows] = sbh;
    if (hdr->tiling.log2_cols || hdr->tiling.log2_rows) {
510 511
        hdr->tiling.update = dav1d_get_bits(gb, hdr->tiling.log2_cols +
                                                hdr->tiling.log2_rows);
512 513
        if (hdr->tiling.update >= hdr->tiling.cols * hdr->tiling.rows)
            goto error;
514
        hdr->tiling.n_bytes = dav1d_get_bits(gb, 2) + 1;
515 516 517 518 519 520 521 522 523
    } else {
        hdr->tiling.n_bytes = hdr->tiling.update = 0;
    }
#if DEBUG_FRAME_HDR
    printf("HDR: post-tiling: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

    // quant data
524 525
    hdr->quant.yac = dav1d_get_bits(gb, 8);
    hdr->quant.ydc_delta = dav1d_get_bits(gb, 1) ? dav1d_get_sbits(gb, 6) : 0;
526
    if (seqhdr->layout != DAV1D_PIXEL_LAYOUT_I400) {
527 528
        hdr->quant.udc_delta = dav1d_get_bits(gb, 1) ? dav1d_get_sbits(gb, 6) : 0;
        hdr->quant.uac_delta = dav1d_get_bits(gb, 1) ? dav1d_get_sbits(gb, 6) : 0;
529
        if (seqhdr->separate_uv_delta_q) {
530 531
            hdr->quant.vdc_delta = dav1d_get_bits(gb, 1) ? dav1d_get_sbits(gb, 6) : 0;
            hdr->quant.vac_delta = dav1d_get_bits(gb, 1) ? dav1d_get_sbits(gb, 6) : 0;
532 533 534 535 536 537 538 539 540
        } else {
            hdr->quant.vdc_delta = hdr->quant.udc_delta;
            hdr->quant.vac_delta = hdr->quant.uac_delta;
        }
    }
#if DEBUG_FRAME_HDR
    printf("HDR: post-quant: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif
541
    hdr->quant.qm = dav1d_get_bits(gb, 1);
542
    if (hdr->quant.qm) {
543 544
        hdr->quant.qm_y = dav1d_get_bits(gb, 4);
        hdr->quant.qm_u = dav1d_get_bits(gb, 4);
skal's avatar
skal committed
545 546 547
        hdr->quant.qm_v =
            seqhdr->separate_uv_delta_q ? (int)dav1d_get_bits(gb, 4) :
                                          hdr->quant.qm_u;
548 549 550 551 552 553 554
    }
#if DEBUG_FRAME_HDR
    printf("HDR: post-qm: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

    // segmentation data
555
    hdr->segmentation.enabled = dav1d_get_bits(gb, 1);
556 557 558 559 560 561
    if (hdr->segmentation.enabled) {
        if (hdr->primary_ref_frame == PRIMARY_REF_NONE) {
            hdr->segmentation.update_map = 1;
            hdr->segmentation.temporal = 0;
            hdr->segmentation.update_data = 1;
        } else {
562
            hdr->segmentation.update_map = dav1d_get_bits(gb, 1);
563
            hdr->segmentation.temporal =
564 565
                hdr->segmentation.update_map ? dav1d_get_bits(gb, 1) : 0;
            hdr->segmentation.update_data = dav1d_get_bits(gb, 1);
566 567 568 569 570 571 572 573
        }

        if (hdr->segmentation.update_data) {
            hdr->segmentation.seg_data.preskip = 0;
            hdr->segmentation.seg_data.last_active_segid = -1;
            for (int i = 0; i < NUM_SEGMENTS; i++) {
                Av1SegmentationData *const seg =
                    &hdr->segmentation.seg_data.d[i];
574 575
                if (dav1d_get_bits(gb, 1)) {
                    seg->delta_q = dav1d_get_sbits(gb, 8);
576 577 578 579
                    hdr->segmentation.seg_data.last_active_segid = i;
                } else {
                    seg->delta_q = 0;
                }
580 581
                if (dav1d_get_bits(gb, 1)) {
                    seg->delta_lf_y_v = dav1d_get_sbits(gb, 6);
582 583 584 585
                    hdr->segmentation.seg_data.last_active_segid = i;
                } else {
                    seg->delta_lf_y_v = 0;
                }
586 587
                if (dav1d_get_bits(gb, 1)) {
                    seg->delta_lf_y_h = dav1d_get_sbits(gb, 6);
588 589 590 591
                    hdr->segmentation.seg_data.last_active_segid = i;
                } else {
                    seg->delta_lf_y_h = 0;
                }
592 593
                if (dav1d_get_bits(gb, 1)) {
                    seg->delta_lf_u = dav1d_get_sbits(gb, 6);
594 595 596 597
                    hdr->segmentation.seg_data.last_active_segid = i;
                } else {
                    seg->delta_lf_u = 0;
                }
598 599
                if (dav1d_get_bits(gb, 1)) {
                    seg->delta_lf_v = dav1d_get_sbits(gb, 6);
600 601 602 603
                    hdr->segmentation.seg_data.last_active_segid = i;
                } else {
                    seg->delta_lf_v = 0;
                }
604 605
                if (dav1d_get_bits(gb, 1)) {
                    seg->ref = dav1d_get_bits(gb, 3);
606 607 608 609 610
                    hdr->segmentation.seg_data.last_active_segid = i;
                    hdr->segmentation.seg_data.preskip = 1;
                } else {
                    seg->ref = -1;
                }
611
                if ((seg->skip = dav1d_get_bits(gb, 1))) {
612 613 614
                    hdr->segmentation.seg_data.last_active_segid = i;
                    hdr->segmentation.seg_data.preskip = 1;
                }
615
                if ((seg->globalmv = dav1d_get_bits(gb, 1))) {
616 617 618 619
                    hdr->segmentation.seg_data.last_active_segid = i;
                    hdr->segmentation.seg_data.preskip = 1;
                }
            }
620 621
        } else if (hdr->primary_ref_frame == PRIMARY_REF_NONE) {
            memset(&hdr->segmentation.seg_data, 0, sizeof(Av1SegmentationDataSet));
622 623 624 625
        } else {
            const int pri_ref = hdr->refidx[hdr->primary_ref_frame];
            hdr->segmentation.seg_data = c->refs[pri_ref].seg_data;
        }
626 627
    } else if (hdr->primary_ref_frame == PRIMARY_REF_NONE) {
        memset(&hdr->segmentation.seg_data, 0, sizeof(Av1SegmentationDataSet));
628 629 630 631 632 633 634 635 636 637
    } else {
        const int pri_ref = hdr->refidx[hdr->primary_ref_frame];
        hdr->segmentation.seg_data = c->refs[pri_ref].seg_data;
    }
#if DEBUG_FRAME_HDR
    printf("HDR: post-segmentation: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

    // delta q
638 639
    hdr->delta.q.present = hdr->quant.yac ? dav1d_get_bits(gb, 1) : 0;
    hdr->delta.q.res_log2 = hdr->delta.q.present ? dav1d_get_bits(gb, 2) : 0;
640
    hdr->delta.lf.present = hdr->delta.q.present && !hdr->allow_intrabc &&
641 642 643
                            dav1d_get_bits(gb, 1);
    hdr->delta.lf.res_log2 = hdr->delta.lf.present ? dav1d_get_bits(gb, 2) : 0;
    hdr->delta.lf.multi = hdr->delta.lf.present ? dav1d_get_bits(gb, 1) : 0;
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
#if DEBUG_FRAME_HDR
    printf("HDR: post-delta_q_lf_flags: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

    // derive lossless flags
    const int delta_lossless = !hdr->quant.ydc_delta && !hdr->quant.udc_delta &&
        !hdr->quant.uac_delta && !hdr->quant.vdc_delta && !hdr->quant.vac_delta;
    hdr->all_lossless = 1;
    for (int i = 0; i < NUM_SEGMENTS; i++) {
        hdr->segmentation.qidx[i] = hdr->segmentation.enabled ?
            iclip_u8(hdr->quant.yac + hdr->segmentation.seg_data.d[i].delta_q) :
            hdr->quant.yac;
        hdr->segmentation.lossless[i] =
            !hdr->segmentation.qidx[i] && delta_lossless;
        hdr->all_lossless &= hdr->segmentation.lossless[i];
    }

    // loopfilter
    if (hdr->all_lossless || hdr->allow_intrabc) {
        hdr->loopfilter.level_y[0] = hdr->loopfilter.level_y[1] = 0;
        hdr->loopfilter.level_u = hdr->loopfilter.level_v = 0;
        hdr->loopfilter.sharpness = 0;
        hdr->loopfilter.mode_ref_delta_enabled = 1;
        hdr->loopfilter.mode_ref_delta_update = 1;
        hdr->loopfilter.mode_ref_deltas = default_mode_ref_deltas;
    } else {
671 672
        hdr->loopfilter.level_y[0] = dav1d_get_bits(gb, 6);
        hdr->loopfilter.level_y[1] = dav1d_get_bits(gb, 6);
673 674 675
        if (seqhdr->layout != DAV1D_PIXEL_LAYOUT_I400 &&
            (hdr->loopfilter.level_y[0] || hdr->loopfilter.level_y[1]))
        {
676 677
            hdr->loopfilter.level_u = dav1d_get_bits(gb, 6);
            hdr->loopfilter.level_v = dav1d_get_bits(gb, 6);
678
        }
679
        hdr->loopfilter.sharpness = dav1d_get_bits(gb, 3);
680 681 682 683 684 685 686

        if (hdr->primary_ref_frame == PRIMARY_REF_NONE) {
            hdr->loopfilter.mode_ref_deltas = default_mode_ref_deltas;
        } else {
            const int ref = hdr->refidx[hdr->primary_ref_frame];
            hdr->loopfilter.mode_ref_deltas = c->refs[ref].lf_mode_ref_deltas;
        }
687
        hdr->loopfilter.mode_ref_delta_enabled = dav1d_get_bits(gb, 1);
688
        if (hdr->loopfilter.mode_ref_delta_enabled) {
689
            hdr->loopfilter.mode_ref_delta_update = dav1d_get_bits(gb, 1);
690 691
            if (hdr->loopfilter.mode_ref_delta_update) {
                for (int i = 0; i < 8; i++)
692
                    if (dav1d_get_bits(gb, 1))
693
                        hdr->loopfilter.mode_ref_deltas.ref_delta[i] =
694
                            dav1d_get_sbits(gb, 6);
695
                for (int i = 0; i < 2; i++)
696
                    if (dav1d_get_bits(gb, 1))
697
                        hdr->loopfilter.mode_ref_deltas.mode_delta[i] =
698
                            dav1d_get_sbits(gb, 6);
699 700 701 702 703 704 705 706 707 708
            }
        }
    }
#if DEBUG_FRAME_HDR
    printf("HDR: post-lpf: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

    // cdef
    if (!hdr->all_lossless && seqhdr->cdef && !hdr->allow_intrabc) {
709 710
        hdr->cdef.damping = dav1d_get_bits(gb, 2) + 3;
        hdr->cdef.n_bits = dav1d_get_bits(gb, 2);
711
        for (int i = 0; i < (1 << hdr->cdef.n_bits); i++) {
712
            hdr->cdef.y_strength[i] = dav1d_get_bits(gb, 6);
713
            if (seqhdr->layout != DAV1D_PIXEL_LAYOUT_I400)
714
                hdr->cdef.uv_strength[i] = dav1d_get_bits(gb, 6);
715 716 717 718 719 720 721 722 723 724 725 726 727
        }
    } else {
        hdr->cdef.n_bits = 0;
        hdr->cdef.y_strength[0] = 0;
        hdr->cdef.uv_strength[0] = 0;
    }
#if DEBUG_FRAME_HDR
    printf("HDR: post-cdef: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

    // restoration
    if (!hdr->all_lossless && seqhdr->restoration && !hdr->allow_intrabc) {
728
        hdr->restoration.type[0] = dav1d_get_bits(gb, 2);
729
        if (seqhdr->layout != DAV1D_PIXEL_LAYOUT_I400) {
730 731
            hdr->restoration.type[1] = dav1d_get_bits(gb, 2);
            hdr->restoration.type[2] = dav1d_get_bits(gb, 2);
732 733 734
        } else {
            hdr->restoration.type[1] =
            hdr->restoration.type[2] = RESTORATION_NONE;
735 736 737 738 739 740 741
        }

        if (hdr->restoration.type[0] || hdr->restoration.type[1] ||
            hdr->restoration.type[2])
        {
            // Log2 of the restoration unit size.
            hdr->restoration.unit_size[0] = 6 + seqhdr->sb128;
742
            if (dav1d_get_bits(gb, 1)) {
743 744
                hdr->restoration.unit_size[0]++;
                if (!seqhdr->sb128)
745
                    hdr->restoration.unit_size[0] += dav1d_get_bits(gb, 1);
746 747 748 749 750
            }
            hdr->restoration.unit_size[1] = hdr->restoration.unit_size[0];
            if ((hdr->restoration.type[1] || hdr->restoration.type[2]) &&
                seqhdr->layout == DAV1D_PIXEL_LAYOUT_I420)
            {
751
                hdr->restoration.unit_size[1] -= dav1d_get_bits(gb, 1);
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
            }
        } else {
            hdr->restoration.unit_size[0] = 8;
        }
    } else {
        hdr->restoration.type[0] = RESTORATION_NONE;
        hdr->restoration.type[1] = RESTORATION_NONE;
        hdr->restoration.type[2] = RESTORATION_NONE;
    }
#if DEBUG_FRAME_HDR
    printf("HDR: post-restoration: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

    hdr->txfm_mode = hdr->all_lossless ? TX_4X4_ONLY :
767
                     dav1d_get_bits(gb, 1) ? TX_SWITCHABLE : TX_LARGEST;
768 769 770 771
#if DEBUG_FRAME_HDR
    printf("HDR: post-txfmmode: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif
772
    hdr->switchable_comp_refs = hdr->frame_type & 1 ? dav1d_get_bits(gb, 1) : 0;
773 774 775 776 777
#if DEBUG_FRAME_HDR
    printf("HDR: post-refmode: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif
    hdr->skip_mode_allowed = 0;
778
    if (hdr->switchable_comp_refs && hdr->frame_type & 1 && seqhdr->order_hint) {
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
        const unsigned poc = hdr->frame_offset;
        unsigned off_before[2] = { 0xFFFFFFFF, 0xFFFFFFFF };
        int off_after = -1;
        int off_before_idx[2], off_after_idx;
        for (int i = 0; i < 7; i++) {
            const unsigned refpoc = c->refs[hdr->refidx[i]].p.p.poc;

            const int diff = get_poc_diff(seqhdr->order_hint_n_bits, refpoc, poc);
            if (diff > 0) {
                if (off_after == -1 || get_poc_diff(seqhdr->order_hint_n_bits,
                                                    off_after, refpoc) > 0)
                {
                    off_after = refpoc;
                    off_after_idx = i;
                }
            } else if (diff < 0) {
                if (off_before[0] == 0xFFFFFFFFU ||
                    get_poc_diff(seqhdr->order_hint_n_bits,
                                 refpoc, off_before[0]) > 0)
                {
                    off_before[1] = off_before[0];
                    off_before[0] = refpoc;
                    off_before_idx[1] = off_before_idx[0];
                    off_before_idx[0] = i;
                } else if (refpoc != off_before[0] &&
                           (off_before[1] == 0xFFFFFFFFU ||
                            get_poc_diff(seqhdr->order_hint_n_bits,
                                         refpoc, off_before[1]) > 0))
                {
                    off_before[1] = refpoc;
                    off_before_idx[1] = i;
                }
            }
        }

        if (off_before[0] != 0xFFFFFFFFU && off_after != -1) {
815 816
            hdr->skip_mode_refs[0] = imin(off_before_idx[0], off_after_idx);
            hdr->skip_mode_refs[1] = imax(off_before_idx[0], off_after_idx);
817 818 819 820
            hdr->skip_mode_allowed = 1;
        } else if (off_before[0] != 0xFFFFFFFFU &&
                   off_before[1] != 0xFFFFFFFFU)
        {
821 822
            hdr->skip_mode_refs[0] = imin(off_before_idx[0], off_before_idx[1]);
            hdr->skip_mode_refs[1] = imax(off_before_idx[0], off_before_idx[1]);
823 824 825
            hdr->skip_mode_allowed = 1;
        }
    }
826
    hdr->skip_mode_enabled = hdr->skip_mode_allowed ? dav1d_get_bits(gb, 1) : 0;
827 828 829 830 831
#if DEBUG_FRAME_HDR
    printf("HDR: post-extskip: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif
    hdr->warp_motion = !hdr->error_resilient_mode && hdr->frame_type & 1 &&
832
        seqhdr->warped_motion && dav1d_get_bits(gb, 1);
833 834 835 836
#if DEBUG_FRAME_HDR
    printf("HDR: post-warpmotionbit: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif
837
    hdr->reduced_txtp_set = dav1d_get_bits(gb, 1);
838 839 840 841 842 843
#if DEBUG_FRAME_HDR
    printf("HDR: post-reducedtxtpset: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

    for (int i = 0; i < 7; i++)
844
        hdr->gmv[i] = dav1d_default_wm_params;
845 846 847

    if (hdr->frame_type & 1) {
        for (int i = 0; i < 7; i++) {
848 849 850
            hdr->gmv[i].type = !dav1d_get_bits(gb, 1) ? WM_TYPE_IDENTITY :
                                dav1d_get_bits(gb, 1) ? WM_TYPE_ROT_ZOOM :
                                dav1d_get_bits(gb, 1) ? WM_TYPE_TRANSLATION :
851 852 853 854 855
                                                  WM_TYPE_AFFINE;

            if (hdr->gmv[i].type == WM_TYPE_IDENTITY) continue;

            const WarpedMotionParams *const ref_gmv =
856
                hdr->primary_ref_frame == PRIMARY_REF_NONE ? &dav1d_default_wm_params :
857 858 859 860 861 862 863
                &c->refs[hdr->refidx[hdr->primary_ref_frame]].gmv[i];
            int32_t *const mat = hdr->gmv[i].matrix;
            const int32_t *const ref_mat = ref_gmv->matrix;
            int bits, shift;

            if (hdr->gmv[i].type >= WM_TYPE_ROT_ZOOM) {
                mat[2] = (1 << 16) + 2 *
864 865
                    dav1d_get_bits_subexp(gb, (ref_mat[2] - (1 << 16)) >> 1, 12);
                mat[3] = 2 * dav1d_get_bits_subexp(gb, ref_mat[3] >> 1, 12);
866 867 868 869 870 871 872 873 874

                bits = 12;
                shift = 10;
            } else {
                bits = 9 - !hdr->hp;
                shift = 13 + !hdr->hp;
            }

            if (hdr->gmv[i].type == WM_TYPE_AFFINE) {
875
                mat[4] = 2 * dav1d_get_bits_subexp(gb, ref_mat[4] >> 1, 12);
876
                mat[5] = (1 << 16) + 2 *
877
                    dav1d_get_bits_subexp(gb, (ref_mat[5] - (1 << 16)) >> 1, 12);
878 879 880 881 882
            } else {
                mat[4] = -mat[3];
                mat[5] = mat[2];
            }

883 884
            mat[0] = dav1d_get_bits_subexp(gb, ref_mat[0] >> shift, bits) * (1 << shift);
            mat[1] = dav1d_get_bits_subexp(gb, ref_mat[1] >> shift, bits) * (1 << shift);
885

886
            if (dav1d_get_shear_params(&hdr->gmv[i]))
887 888 889 890 891 892 893 894
                goto error;
        }
    }
#if DEBUG_FRAME_HDR
    printf("HDR: post-gmv: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

895 896
    hdr->film_grain.present = seqhdr->film_grain_present &&
                              (hdr->show_frame || hdr->showable_frame) &&
897
                              dav1d_get_bits(gb, 1);
898
    if (hdr->film_grain.present) {
899 900
        hdr->film_grain.seed = dav1d_get_bits(gb, 16);
        hdr->film_grain.update = hdr->frame_type != DAV1D_FRAME_TYPE_INTER || dav1d_get_bits(gb, 1);
901
        if (!hdr->film_grain.update) {
902
            const int refidx = dav1d_get_bits(gb, 3);
903 904 905 906 907 908 909 910 911
            int i;
            for (i = 0; i < 7; i++)
                if (hdr->refidx[i] == refidx)
                    break;
            if (i == 7) goto error;
            hdr->film_grain.data = c->refs[refidx].film_grain;
        } else {
            Av1FilmGrainData *const fgd = &hdr->film_grain.data;

912
            fgd->num_y_points = dav1d_get_bits(gb, 4);
913 914
            if (fgd->num_y_points > 14) goto error;
            for (int i = 0; i < fgd->num_y_points; i++) {
915
                fgd->y_points[i][0] = dav1d_get_bits(gb, 8);
916 917
                if (i && fgd->y_points[i - 1][0] >= fgd->y_points[i][0])
                    goto error;
918
                fgd->y_points[i][1] = dav1d_get_bits(gb, 8);
919 920 921
            }

            fgd->chroma_scaling_from_luma =
922
                seqhdr->layout != DAV1D_PIXEL_LAYOUT_I400 && dav1d_get_bits(gb, 1);
923 924 925 926 927 928
            if (seqhdr->layout == DAV1D_PIXEL_LAYOUT_I400 ||
                fgd->chroma_scaling_from_luma ||
                (seqhdr->layout == DAV1D_PIXEL_LAYOUT_I420 && !fgd->num_y_points))
            {
                fgd->num_uv_points[0] = fgd->num_uv_points[1] = 0;
            } else for (int pl = 0; pl < 2; pl++) {
929
                fgd->num_uv_points[pl] = dav1d_get_bits(gb, 4);
930 931
                if (fgd->num_uv_points[pl] > 10) goto error;
                for (int i = 0; i < fgd->num_uv_points[pl]; i++) {
932
                    fgd->uv_points[pl][i][0] = dav1d_get_bits(gb, 8);
933 934
                    if (i && fgd->uv_points[pl][i - 1][0] >= fgd->uv_points[pl][i][0])
                        goto error;
935
                    fgd->uv_points[pl][i][1] = dav1d_get_bits(gb, 8);
936 937 938 939 940 941 942 943 944
                }
            }

            if (seqhdr->layout == DAV1D_PIXEL_LAYOUT_I420 &&
                !!fgd->num_uv_points[0] != !!fgd->num_uv_points[1])
            {
                goto error;
            }

945 946
            fgd->scaling_shift = dav1d_get_bits(gb, 2) + 8;
            fgd->ar_coeff_lag = dav1d_get_bits(gb, 2);
947 948 949
            const int num_y_pos = 2 * fgd->ar_coeff_lag * (fgd->ar_coeff_lag + 1);
            if (fgd->num_y_points)
                for (int i = 0; i < num_y_pos; i++)
950
                    fgd->ar_coeffs_y[i] = dav1d_get_bits(gb, 8) - 128;
951 952 953 954
            for (int pl = 0; pl < 2; pl++)
                if (fgd->num_uv_points[pl] || fgd->chroma_scaling_from_luma) {
                    const int num_uv_pos = num_y_pos + !!fgd->num_y_points;
                    for (int i = 0; i < num_uv_pos; i++)
955
                        fgd->ar_coeffs_uv[pl][i] = dav1d_get_bits(gb, 8) - 128;
956
                }
957 958
            fgd->ar_coeff_shift = dav1d_get_bits(gb, 2) + 6;
            fgd->grain_scale_shift = dav1d_get_bits(gb, 2);
959 960
            for (int pl = 0; pl < 2; pl++)
                if (fgd->num_uv_points[pl]) {
961 962 963
                    fgd->uv_mult[pl] = dav1d_get_bits(gb, 8);
                    fgd->uv_luma_mult[pl] = dav1d_get_bits(gb, 8);
                    fgd->uv_offset[pl] = dav1d_get_bits(gb, 9);
964
                }
965 966
            fgd->overlap_flag = dav1d_get_bits(gb, 1);
            fgd->clip_to_restricted_range = dav1d_get_bits(gb, 1);
967 968 969 970 971 972 973 974 975 976 977 978
        }
    } else {
        memset(&hdr->film_grain.data, 0, sizeof(hdr->film_grain));
    }
#if DEBUG_FRAME_HDR
    printf("HDR: post-filmgrain: off=%ld\n",
           (gb->ptr - init_ptr) * 8 - gb->bits_left);
#endif

end:

    if (have_trailing_bit)
979
        dav1d_get_bits(gb, 1); // dummy bit
980

981
    return dav1d_flush_get_bits(gb) - init_ptr;
982 983 984 985 986 987 988 989 990 991

error:
    fprintf(stderr, "Error parsing frame header\n");
    return -EINVAL;
}

static int parse_tile_hdr(Dav1dContext *const c, GetBits *const gb) {
    const uint8_t *const init_ptr = gb->ptr;

    int have_tile_pos = 0;
992 993
    const int n_tiles = c->frame_hdr.tiling.cols * c->frame_hdr.tiling.rows;
    if (n_tiles > 1)
994
        have_tile_pos = dav1d_get_bits(gb, 1);
995 996

    if (have_tile_pos) {
997 998
        const int n_bits = c->frame_hdr.tiling.log2_cols +
                           c->frame_hdr.tiling.log2_rows;
999 1000
        c->tile[c->n_tile_data].start = dav1d_get_bits(gb, n_bits);
        c->tile[c->n_tile_data].end = dav1d_get_bits(gb, n_bits);
1001 1002
    } else {
        c->tile[c->n_tile_data].start = 0;
1003
        c->tile[c->n_tile_data].end = n_tiles - 1;
1004 1005
    }

1006
    return dav1d_flush_get_bits(gb) - init_ptr;
1007 1008
}

1009
int dav1d_parse_obus(Dav1dContext *const c, Dav1dData *const in) {
1010 1011 1012
    GetBits gb;
    int res;

1013
    dav1d_init_get_bits(&gb, in->data, in->sz);
1014 1015

    // obu header
1016 1017 1018 1019
    dav1d_get_bits(&gb, 1); // obu_forbidden_bit
    const enum ObuType type = dav1d_get_bits(&gb, 4);
    const int has_extension = dav1d_get_bits(&gb, 1);
    const int has_length_field = dav1d_get_bits(&gb, 1);
1020
    if (!has_length_field) goto error;
1021
    dav1d_get_bits(&gb, 1); // reserved
1022
    if (has_extension) {
1023 1024 1025
        dav1d_get_bits(&gb, 3); // temporal_layer_id
        dav1d_get_bits(&gb, 2); // enhancement_layer_id
        dav1d_get_bits(&gb, 3); // reserved
1026 1027 1028
    }

    // obu length field
1029
    unsigned len = 0, more, i = 0;
1030
    do {
1031
        more = dav1d_get_bits(&gb, 1);
1032 1033 1034 1035 1036
        unsigned bits = dav1d_get_bits(&gb, 7);
        if (i <= 3 || (i == 4 && bits < (1 << 4)))
            len |= bits << (i * 7);
        else if (bits)
            goto error;
1037 1038 1039 1040
        if (more && ++i == 8) goto error;
    } while (more);
    if (gb.error) goto error;

1041 1042 1043
    unsigned off = dav1d_flush_get_bits(&gb) - in->data;
    const unsigned init_off = off;
    if (len > in->sz - off) goto error;
1044 1045

    switch (type) {
1046 1047 1048
    case OBU_SEQ_HDR: {
        Av1SequenceHeader hdr, *const hdr_ptr = c->have_seq_hdr ? &hdr : &c->seq_hdr;
        memset(hdr_ptr, 0, sizeof(*hdr_ptr));
1049
        c->have_frame_hdr = 0;
1050 1051
        if ((res = parse_seq_hdr(c, &gb, hdr_ptr)) < 0) {
            c->have_seq_hdr = 0;
1052
            return res;
1053 1054 1055 1056 1057 1058 1059 1060 1061
        }
        if ((unsigned)res != len) {
            c->have_seq_hdr = 0;
            goto error;
        }
        if (c->have_seq_hdr && memcmp(&hdr, &c->seq_hdr, sizeof(hdr))) {
            for (int i = 0; i < 8; i++) {
                if (c->refs[i].p.p.data[0])
                    dav1d_thread_picture_unref(&c->refs[i].p);
1062 1063
                dav1d_ref_dec(&c->refs[i].segmap);
                dav1d_ref_dec(&c->refs[i].refmvs);
1064 1065 1066 1067 1068
                if (c->cdf[i].cdf)
                    dav1d_cdf_thread_unref(&c->cdf[i]);
            }
            c->seq_hdr = hdr;
        }
1069 1070
        c->have_seq_hdr = 1;
        break;
1071
    }
1072 1073 1074
    case OBU_REDUNDANT_FRAME_HDR:
        if (c->have_frame_hdr) break;
        // fall-through
1075 1076
    case OBU_FRAME:
    case OBU_FRAME_HDR:
1077
        c->have_frame_hdr = 0;
1078
        if (!c->have_seq_hdr) goto error;
1079
        if ((res = parse_frame_hdr(c, &gb, type != OBU_FRAME)) < 0)
1080 1081 1082 1083 1084
            return res;
        c->have_frame_hdr = 1;
        for (int n = 0; n < c->n_tile_data; n++)
            dav1d_data_unref(&c->tile[n].data);
        c->n_tile_data = 0;
1085
        c->n_tiles = 0;
1086
        if (type != OBU_FRAME) break;
1087
        if (c->frame_hdr.show_existing_frame) goto error;
1088 1089 1090 1091 1092 1093 1094 1095
        off += res;
        // fall-through
    case OBU_TILE_GRP:
        if (!c->have_frame_hdr) goto error;
        if (c->n_tile_data >= 256) goto error;
        if ((res = parse_tile_hdr(c, &gb)) < 0)
            return res;
        off += res;
1096 1097
        if (off > len + init_off)
            goto error;
1098 1099 1100 1101
        dav1d_ref_inc(in->ref);
        c->tile[c->n_tile_data].data.ref = in->ref;
        c->tile[c->n_tile_data].data.data = in->data + off;
        c->tile[c->n_tile_data].data.sz = len + init_off - off;
1102
        // ensure tile groups are in order and sane, see 6.10.1
1103
        if (c->tile[c->n_tile_data].start > c->tile[c->n_tile_data].end ||
1104
            c->tile[c->n_tile_data].start != c->n_tiles)
1105
        {
1106 1107 1108
            for (int i = 0; i <= c->n_tile_data; i++)
                dav1d_data_unref(&c->tile[i].data);
            c->n_tile_data = 0;
1109
            c->n_tiles = 0;
1110 1111
            goto error;
        }
1112 1113
        c->n_tiles += 1 + c->tile[c->n_tile_data].end -
                          c->tile[c->n_tile_data].start;
1114 1115 1116 1117 1118 1119 1120 1121
        c->n_tile_data++;
        break;
    case OBU_PADDING:
    case OBU_TD:
    case OBU_METADATA:
        // ignore OBUs we don't care about
        break;
    default:
1122
        fprintf(stderr, "Unknown OBU type %d of size %u\n", type, len);
1123 1124 1125 1126
        return -EINVAL;
    }

    if (c->have_seq_hdr && c->have_frame_hdr &&
1127
        c->n_tiles == c->frame_hdr.tiling.cols * c->frame_hdr.tiling.rows)
1128
    {
1129 1130
        if (!c->n_tile_data)
            return -EINVAL;
1131 1132
        if ((res = dav1d_submit_frame(c)) < 0)
            return res;
1133 1134
        assert(!c->n_tile_data);
        c->have_frame_hdr = 0;
1135
        c->n_tiles = 0;
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
    } else if (c->have_seq_hdr && c->have_frame_hdr &&
               c->frame_hdr.show_existing_frame)
    {
        if (c->n_fc == 1) {
            dav1d_picture_ref(&c->out,
                              &c->refs[c->frame_hdr.existing_frame_idx].p.p);
        } else {
            // need to append this to the frame output queue
            const unsigned next = c->frame_thread.next++;
            if (c->frame_thread.next == c->n_fc)
                c->frame_thread.next = 0;

            Dav1dFrameContext *const f = &c->fc[next];
            pthread_mutex_lock(&f->frame_thread.td.lock);
            while (f->n_tile_data > 0)
                pthread_cond_wait(&f->frame_thread.td.cond,
                                  &f->frame_thread.td.lock);
            Dav1dThreadPicture *const out_delayed =
                &c->frame_thread.out_delayed[next];
            if (out_delayed->p.data[0]) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
1156
                if (out_delayed->visible && !out_delayed->flushed)
1157 1158 1159 1160 1161 1162
                    dav1d_picture_ref(&c->out, &out_delayed->p);
                dav1d_thread_picture_unref(out_delayed);
            }
            dav1d_thread_picture_ref(out_delayed,
                                     &c->refs[c->frame_hdr.existing_frame_idx].p);
            out_delayed->visible = 1;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
1163
            out_delayed->flushed = 0;
1164 1165 1166
            pthread_mutex_unlock(&f->frame_thread.td.lock);
        }
        c->have_frame_hdr = 0;
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
        if (c->refs[c->frame_hdr.existing_frame_idx].p.p.p.type == DAV1D_FRAME_TYPE_KEY) {
            const int r = c->frame_hdr.existing_frame_idx;
            for (int i = 0; i < 8; i++) {
                if (i == c->frame_hdr.existing_frame_idx) continue;

                if (c->refs[i].p.p.data[0])
                    dav1d_thread_picture_unref(&c->refs[i].p);
                dav1d_thread_picture_ref(&c->refs[i].p, &c->refs[r].p);

                if (c->cdf[i].cdf) dav1d_cdf_thread_unref(&c->cdf[i]);
                dav1d_init_states(&c->cdf[i], c->refs[r].qidx);

                c->refs[i].lf_mode_ref_deltas = c->refs[r].lf_mode_ref_deltas;
                c->refs[i].seg_data = c->refs[r].seg_data;
                for (int j = 0; j < 7; j++)
                    c->refs[i].gmv[j] = dav1d_default_wm_params;
                c->refs[i].film_grain = c->refs[r].film_grain;

1185
                dav1d_ref_dec(&c->refs[i].segmap);
1186 1187 1188
                c->refs[i].segmap = c->refs[r].segmap;
                if (c->refs[r].segmap)
                    dav1d_ref_inc(c->refs[r].segmap);
1189
                dav1d_ref_dec(&c->refs[i].refmvs);
1190 1191 1192
                c->refs[i].qidx = c->refs[r].qidx;
            }
        }
1193 1194 1195 1196 1197 1198 1199 1200
    }

    return len + init_off;

error:
    fprintf(stderr, "Error parsing OBU data\n");
    return -EINVAL;
}