static av_always_inline void FUNC(intra_pred)(HEVCContext *s, int x0, int y0,

                                              int log2_size, int c_idx)

{

#define PU(x) \

    ((x) >> s->ps.sps->log2_min_pu_size)

#define MVF(x, y) \

    (s->ref->tab_mvf[(x) + (y) * min_pu_width])

#define MVF_PU(x, y) \

    MVF(PU(x0 + ((x) << hshift)), PU(y0 + ((y) << vshift)))

#define IS_INTRA(x, y) \

    (MVF_PU(x, y).pred_flag == PF_INTRA)

#define MIN_TB_ADDR_ZS(x, y) \

    s->ps.pps->min_tb_addr_zs[(y) * (s->ps.sps->tb_mask+2) + (x)]

#define EXTEND(ptr, val, len)         \

do {                                  \

    pixel4 pix = PIXEL_SPLAT_X4(val); \

    for (i = 0; i < (len); i += 4)    \

        AV_WN4P(ptr + i, pix);        \

} while (0)

#define EXTEND_RIGHT_CIP(ptr, start, length)                                   \

        for (i = start; i < (start) + (length); i += 4)                        \

            if (!IS_INTRA(i, -1))                                              \

                AV_WN4P(&ptr[i], a);                                           \

            else                                                               \

                a = PIXEL_SPLAT_X4(ptr[i+3])

#define EXTEND_LEFT_CIP(ptr, start, length) \

        for (i = start; i > (start) - (length); i--) \

            if (!IS_INTRA(i - 1, -1)) \

                ptr[i - 1] = ptr[i]

#define EXTEND_UP_CIP(ptr, start, length)                                      \

        for (i = (start); i > (start) - (length); i -= 4)                      \

            if (!IS_INTRA(-1, i - 3))                                          \

                AV_WN4P(&ptr[i - 3], a);                                       \

            else                                                               \

                a = PIXEL_SPLAT_X4(ptr[i - 3])

#define EXTEND_DOWN_CIP(ptr, start, length)                                    \

        for (i = start; i < (start) + (length); i += 4)                        \

            if (!IS_INTRA(-1, i))                                              \

                AV_WN4P(&ptr[i], a);                                           \

            else                                                               \

                a = PIXEL_SPLAT_X4(ptr[i + 3])

    HEVCLocalContext *lc = s->HEVClc;

    int i;

    int hshift = s->ps.sps->hshift[c_idx];

    int vshift = s->ps.sps->vshift[c_idx];

    int size = (1 << log2_size);

    int size_in_luma_h = size << hshift;

    int size_in_tbs_h  = size_in_luma_h >> s->ps.sps->log2_min_tb_size;

    int size_in_luma_v = size << vshift;

    int size_in_tbs_v  = size_in_luma_v >> s->ps.sps->log2_min_tb_size;

    int x = x0 >> hshift;

    int y = y0 >> vshift;

    int x_tb = (x0 >> s->ps.sps->log2_min_tb_size) & s->ps.sps->tb_mask;

    int y_tb = (y0 >> s->ps.sps->log2_min_tb_size) & s->ps.sps->tb_mask;

    int cur_tb_addr = MIN_TB_ADDR_ZS(x_tb, y_tb);

    ptrdiff_t stride = s->frame->linesize[c_idx] / sizeof(pixel);

    pixel *src = (pixel*)s->frame->data[c_idx] + x + y * stride;

    int min_pu_width = s->ps.sps->min_pu_width;

    enum IntraPredMode mode = c_idx ? lc->tu.intra_pred_mode_c :

                              lc->tu.intra_pred_mode;

    pixel4 a;

    pixel  left_array[2 * MAX_TB_SIZE + 1];

    pixel  filtered_left_array[2 * MAX_TB_SIZE + 1];

    pixel  top_array[2 * MAX_TB_SIZE + 1];

    pixel  filtered_top_array[2 * MAX_TB_SIZE + 1];

    pixel  *left          = left_array + 1;

    pixel  *top           = top_array  + 1;

    pixel  *filtered_left = filtered_left_array + 1;

    pixel  *filtered_top  = filtered_top_array  + 1;

    int cand_bottom_left = lc->na.cand_bottom_left && cur_tb_addr > MIN_TB_ADDR_ZS( x_tb - 1, (y_tb + size_in_tbs_v) & s->ps.sps->tb_mask);

    int cand_left        = lc->na.cand_left;

    int cand_up_left     = lc->na.cand_up_left;

    int cand_up          = lc->na.cand_up;

    int cand_up_right    = lc->na.cand_up_right    && cur_tb_addr > MIN_TB_ADDR_ZS((x_tb + size_in_tbs_h) & s->ps.sps->tb_mask, y_tb - 1);

    int bottom_left_size = (FFMIN(y0 + 2 * size_in_luma_v, s->ps.sps->height) -

                           (y0 + size_in_luma_v)) >> vshift;

    int top_right_size   = (FFMIN(x0 + 2 * size_in_luma_h, s->ps.sps->width) -

                           (x0 + size_in_luma_h)) >> hshift;

    if (s->ps.pps->constrained_intra_pred_flag == 1) {

        int size_in_luma_pu_v = PU(size_in_luma_v);

        int size_in_luma_pu_h = PU(size_in_luma_h);

        int on_pu_edge_x    = !av_mod_uintp2(x0, s->ps.sps->log2_min_pu_size);

        int on_pu_edge_y    = !av_mod_uintp2(y0, s->ps.sps->log2_min_pu_size);

        if (!size_in_luma_pu_h)

            size_in_luma_pu_h++;

        if (cand_bottom_left == 1 && on_pu_edge_x) {

            int x_left_pu   = PU(x0 - 1);

            int y_bottom_pu = PU(y0 + size_in_luma_v);

            int max = FFMIN(size_in_luma_pu_v, s->ps.sps->min_pu_height - y_bottom_pu);

            cand_bottom_left = 0;

            for (i = 0; i < max; i += 2)

                cand_bottom_left |= (MVF(x_left_pu, y_bottom_pu + i).pred_flag == PF_INTRA);

        }

        if (cand_left == 1 && on_pu_edge_x) {

            int x_left_pu   = PU(x0 - 1);

            int y_left_pu   = PU(y0);

            int max = FFMIN(size_in_luma_pu_v, s->ps.sps->min_pu_height - y_left_pu);

            cand_left = 0;

            for (i = 0; i < max; i += 2)

                cand_left |= (MVF(x_left_pu, y_left_pu + i).pred_flag == PF_INTRA);

        }

        if (cand_up_left == 1) {

            int x_left_pu   = PU(x0 - 1);

            int y_top_pu    = PU(y0 - 1);

            cand_up_left = MVF(x_left_pu, y_top_pu).pred_flag == PF_INTRA;

        }

        if (cand_up == 1 && on_pu_edge_y) {

            int x_top_pu    = PU(x0);

            int y_top_pu    = PU(y0 - 1);

            int max = FFMIN(size_in_luma_pu_h, s->ps.sps->min_pu_width - x_top_pu);

            cand_up = 0;

            for (i = 0; i < max; i += 2)

                cand_up |= (MVF(x_top_pu + i, y_top_pu).pred_flag == PF_INTRA);

        }

        if (cand_up_right == 1 && on_pu_edge_y) {

            int y_top_pu    = PU(y0 - 1);

            int x_right_pu  = PU(x0 + size_in_luma_h);

            int max = FFMIN(size_in_luma_pu_h, s->ps.sps->min_pu_width - x_right_pu);

            cand_up_right = 0;

            for (i = 0; i < max; i += 2)

                cand_up_right |= (MVF(x_right_pu + i, y_top_pu).pred_flag == PF_INTRA);

        }

        memset(left, 128, 2 * MAX_TB_SIZE*sizeof(pixel));

        memset(top , 128, 2 * MAX_TB_SIZE*sizeof(pixel));

        top[-1] = 128;

    }

    if (cand_up_left) {

        left[-1] = POS(-1, -1);

        top[-1]  = left[-1];

    }

    if (cand_up)

        memcpy(top, src - stride, size * sizeof(pixel));

    if (cand_up_right) {

        memcpy(top + size, src - stride + size, size * sizeof(pixel));

        EXTEND(top + size + top_right_size, POS(size + top_right_size - 1, -1),

               size - top_right_size);

    }

    if (cand_left)

        for (i = 0; i < size; i++)

            left[i] = POS(-1, i);

    if (cand_bottom_left) {

        for (i = size; i < size + bottom_left_size; i++)

            left[i] = POS(-1, i);

        EXTEND(left + size + bottom_left_size, POS(-1, size + bottom_left_size - 1),

               size - bottom_left_size);

    }

    if (s->ps.pps->constrained_intra_pred_flag == 1) {

        if (cand_bottom_left || cand_left || cand_up_left || cand_up || cand_up_right) {

            int size_max_x = x0 + ((2 * size) << hshift) < s->ps.sps->width ?

                                    2 * size : (s->ps.sps->width - x0) >> hshift;

            int size_max_y = y0 + ((2 * size) << vshift) < s->ps.sps->height ?

                                    2 * size : (s->ps.sps->height - y0) >> vshift;

            int j = size + (cand_bottom_left? bottom_left_size: 0) -1;

            if (!cand_up_right) {

                size_max_x = x0 + ((size) << hshift) < s->ps.sps->width ?

                                                    size : (s->ps.sps->width - x0) >> hshift;

            }

            if (!cand_bottom_left) {

                size_max_y = y0 + (( size) << vshift) < s->ps.sps->height ?

                                                     size : (s->ps.sps->height - y0) >> vshift;

            }

            if (cand_bottom_left || cand_left || cand_up_left) {

                while (j > -1 && !IS_INTRA(-1, j))

                    j--;

                if (!IS_INTRA(-1, j)) {

                    j = 0;

                    while (j < size_max_x && !IS_INTRA(j, -1))

                        j++;

                    EXTEND_LEFT_CIP(top, j, j + 1);

                    left[-1] = top[-1];

                }

            } else {

                j = 0;

                while (j < size_max_x && !IS_INTRA(j, -1))

                    j++;

                if (j > 0)

                    if (x0 > 0) {

                        EXTEND_LEFT_CIP(top, j, j + 1);

                    } else {

                        EXTEND_LEFT_CIP(top, j, j);

                        top[-1] = top[0];

                    }

                left[-1] = top[-1];

            }

            left[-1] = top[-1];

            if (cand_bottom_left || cand_left) {

                a = PIXEL_SPLAT_X4(left[-1]);

                EXTEND_DOWN_CIP(left, 0, size_max_y);

            }

            if (!cand_left)

                EXTEND(left, left[-1], size);

            if (!cand_bottom_left)

                EXTEND(left + size, left[size - 1], size);

            if (x0 != 0 && y0 != 0) {

                a = PIXEL_SPLAT_X4(left[size_max_y - 1]);

                EXTEND_UP_CIP(left, size_max_y - 1, size_max_y);

                if (!IS_INTRA(-1, - 1))

                    left[-1] = left[0];

            } else if (x0 == 0) {

                EXTEND(left, 0, size_max_y);

            } else {

                a = PIXEL_SPLAT_X4(left[size_max_y - 1]);

                EXTEND_UP_CIP(left, size_max_y - 1, size_max_y);

            }

            top[-1] = left[-1];

            if (y0 != 0) {

                a = PIXEL_SPLAT_X4(left[-1]);

                EXTEND_RIGHT_CIP(top, 0, size_max_x);

            }

        }

    }

    // Infer the unavailable samples

    if (!cand_bottom_left) {

        if (cand_left) {

            EXTEND(left + size, left[size - 1], size);

        } else if (cand_up_left) {

            EXTEND(left, left[-1], 2 * size);

            cand_left = 1;

        } else if (cand_up) {

            left[-1] = top[0];

            EXTEND(left, left[-1], 2 * size);

            cand_up_left = 1;

            cand_left    = 1;

        } else if (cand_up_right) {

            EXTEND(top, top[size], size);

            left[-1] = top[size];

            EXTEND(left, left[-1], 2 * size);

            cand_up      = 1;

            cand_up_left = 1;

            cand_left    = 1;

        } else { // No samples available

            left[-1] = (1 << (BIT_DEPTH - 1));

            EXTEND(top,  left[-1], 2 * size);

            EXTEND(left, left[-1], 2 * size);

        }

    }

    if (!cand_left)

        EXTEND(left, left[size], size);

    if (!cand_up_left) {

        left[-1] = left[0];

    }

    if (!cand_up)

        EXTEND(top, left[-1], size);

    if (!cand_up_right)

        EXTEND(top + size, top[size - 1], size);

    top[-1] = left[-1];

    // Filtering process

    if (!s->ps.sps->intra_smoothing_disabled_flag && (c_idx == 0  || s->ps.sps->chroma_format_idc == 3)) {

        if (mode != INTRA_DC && size != 4){

            int intra_hor_ver_dist_thresh[] = { 7, 1, 0 };

            int min_dist_vert_hor = FFMIN(FFABS((int)(mode - 26U)),

                                          FFABS((int)(mode - 10U)));

            if (min_dist_vert_hor > intra_hor_ver_dist_thresh[log2_size - 3]) {

                int threshold = 1 << (BIT_DEPTH - 5);

                if (s->ps.sps->sps_strong_intra_smoothing_enable_flag && c_idx == 0 &&

                    log2_size == 5 &&

                    FFABS(top[-1]  + top[63]  - 2 * top[31])  < threshold &&

                    FFABS(left[-1] + left[63] - 2 * left[31]) < threshold) {

                    // We can't just overwrite values in top because it could be

                    // a pointer into src

                    filtered_top[-1] = top[-1];

                    filtered_top[63] = top[63];

                    for (i = 0; i < 63; i++)

                        filtered_top[i] = ((64 - (i + 1)) * top[-1] +

                                           (i + 1)  * top[63] + 32) >> 6;

                    for (i = 0; i < 63; i++)

                        left[i] = ((64 - (i + 1)) * left[-1] +

                                   (i + 1)  * left[63] + 32) >> 6;

                    top = filtered_top;

                } else {

                    filtered_left[2 * size - 1] = left[2 * size - 1];

                    filtered_top[2 * size - 1]  = top[2 * size - 1];

                    for (i = 2 * size - 2; i >= 0; i--)

                        filtered_left[i] = (left[i + 1] + 2 * left[i] +

                                            left[i - 1] + 2) >> 2;

                    filtered_top[-1]  =

                    filtered_left[-1] = (left[0] + 2 * left[-1] + top[0] + 2) >> 2;

                    for (i = 2 * size - 2; i >= 0; i--)

                        filtered_top[i] = (top[i + 1] + 2 * top[i] +

                                           top[i - 1] + 2) >> 2;

                    left = filtered_left;

                    top  = filtered_top;

                }

            }

        }

    }

    switch (mode) {

    case INTRA_PLANAR:

        s->hpc.pred_planar[log2_size - 2]((uint8_t *)src, (uint8_t *)top,

                                          (uint8_t *)left, stride);

        break;

    case INTRA_DC:

        s->hpc.pred_dc((uint8_t *)src, (uint8_t *)top,

                       (uint8_t *)left, stride, log2_size, c_idx);

        break;

    default:

        s->hpc.pred_angular[log2_size - 2]((uint8_t *)src, (uint8_t *)top,

                                           (uint8_t *)left, stride, c_idx,

                                           mode);

        break;

    }

}


static void end_last_frame(AVFilterContext *ctx)

{

    TileContext *tile    = ctx->priv;

    AVFilterLink *outlink = ctx->outputs[0];

    AVFilterBufferRef *out_buf = outlink->out_buf;

    outlink->out_buf = NULL;

    ff_start_frame(outlink, out_buf);

    while (tile->current < tile->nb_frames)

        draw_blank_frame(ctx, out_buf);

    ff_draw_slice(outlink, 0, out_buf->video->h, 1);

    ff_end_frame(outlink);

    tile->current = 0;

}


void av_register_output_format(AVOutputFormat *format)

{

    AVOutputFormat **p = &first_oformat;

    while (*p != NULL)

        p = &(*p)->next;

    *p = format;

    format->next = NULL;

}


static void decode_32Bit_opc(CPUTriCoreState *env, DisasContext *ctx)

{

    int op1;

    int32_t r1, r2, r3;

    int32_t address, const16;

    int8_t b, const4;

    int32_t bpos;

    TCGv temp, temp2, temp3;

    op1 = MASK_OP_MAJOR(ctx->opcode);

    /* handle JNZ.T opcode only being 7 bit long */

    if (unlikely((op1 & 0x7f) == OPCM_32_BRN_JTT)) {

        op1 = OPCM_32_BRN_JTT;

    }

    switch (op1) {

/* ABS-format */

    case OPCM_32_ABS_LDW:

        decode_abs_ldw(env, ctx);

    case OPCM_32_ABS_LDB:

        decode_abs_ldb(env, ctx);

    case OPCM_32_ABS_LDMST_SWAP:

        decode_abs_ldst_swap(env, ctx);

    case OPCM_32_ABS_LDST_CONTEXT:

        decode_abs_ldst_context(env, ctx);

    case OPCM_32_ABS_STORE:

        decode_abs_store(env, ctx);

    case OPCM_32_ABS_STOREB_H:

        decode_abs_storeb_h(env, ctx);

    case OPC1_32_ABS_STOREQ:

        address = MASK_OP_ABS_OFF18(ctx->opcode);

        r1 = MASK_OP_ABS_S1D(ctx->opcode);

        temp = tcg_const_i32(EA_ABS_FORMAT(address));

        temp2 = tcg_temp_new();

        tcg_gen_shri_tl(temp2, cpu_gpr_d[r1], 16);

        tcg_gen_qemu_st_tl(temp2, temp, ctx->mem_idx, MO_LEUW);

        tcg_temp_free(temp2);

        tcg_temp_free(temp);

    case OPC1_32_ABS_LD_Q:

        address = MASK_OP_ABS_OFF18(ctx->opcode);

        r1 = MASK_OP_ABS_S1D(ctx->opcode);

        temp = tcg_const_i32(EA_ABS_FORMAT(address));

        tcg_gen_qemu_ld_tl(cpu_gpr_d[r1], temp, ctx->mem_idx, MO_LEUW);

        tcg_gen_shli_tl(cpu_gpr_d[r1], cpu_gpr_d[r1], 16);

        tcg_temp_free(temp);

    case OPC1_32_ABS_LEA:

        address = MASK_OP_ABS_OFF18(ctx->opcode);

        r1 = MASK_OP_ABS_S1D(ctx->opcode);

        tcg_gen_movi_tl(cpu_gpr_a[r1], EA_ABS_FORMAT(address));

/* ABSB-format */

    case OPC1_32_ABSB_ST_T:

        address = MASK_OP_ABS_OFF18(ctx->opcode);

        b = MASK_OP_ABSB_B(ctx->opcode);

        bpos = MASK_OP_ABSB_BPOS(ctx->opcode);

        temp = tcg_const_i32(EA_ABS_FORMAT(address));

        temp2 = tcg_temp_new();

        tcg_gen_qemu_ld_tl(temp2, temp, ctx->mem_idx, MO_UB);

        tcg_gen_andi_tl(temp2, temp2, ~(0x1u << bpos));

        tcg_gen_ori_tl(temp2, temp2, (b << bpos));

        tcg_gen_qemu_st_tl(temp2, temp, ctx->mem_idx, MO_UB);

        tcg_temp_free(temp);

        tcg_temp_free(temp2);

/* B-format */

    case OPC1_32_B_CALL:

    case OPC1_32_B_CALLA:

    case OPC1_32_B_J:

    case OPC1_32_B_JA:

    case OPC1_32_B_JL:

    case OPC1_32_B_JLA:

        address = MASK_OP_B_DISP24(ctx->opcode);

        gen_compute_branch(ctx, op1, 0, 0, 0, address);

/* Bit-format */

    case OPCM_32_BIT_ANDACC:

        decode_bit_andacc(env, ctx);

    case OPCM_32_BIT_LOGICAL_T1:

        decode_bit_logical_t(env, ctx);

    case OPCM_32_BIT_INSERT:

        decode_bit_insert(env, ctx);

    case OPCM_32_BIT_LOGICAL_T2:

        decode_bit_logical_t2(env, ctx);

    case OPCM_32_BIT_ORAND:

        decode_bit_orand(env, ctx);

    case OPCM_32_BIT_SH_LOGIC1:

        decode_bit_sh_logic1(env, ctx);

    case OPCM_32_BIT_SH_LOGIC2:

        decode_bit_sh_logic2(env, ctx);

    /* BO Format */

    case OPCM_32_BO_ADDRMODE_POST_PRE_BASE:

        decode_bo_addrmode_post_pre_base(env, ctx);

    case OPCM_32_BO_ADDRMODE_BITREVERSE_CIRCULAR:

        decode_bo_addrmode_bitreverse_circular(env, ctx);

    case OPCM_32_BO_ADDRMODE_LD_POST_PRE_BASE:

        decode_bo_addrmode_ld_post_pre_base(env, ctx);

    case OPCM_32_BO_ADDRMODE_LD_BITREVERSE_CIRCULAR:

        decode_bo_addrmode_ld_bitreverse_circular(env, ctx);

    case OPCM_32_BO_ADDRMODE_STCTX_POST_PRE_BASE:

        decode_bo_addrmode_stctx_post_pre_base(env, ctx);

    case OPCM_32_BO_ADDRMODE_LDMST_BITREVERSE_CIRCULAR:

        decode_bo_addrmode_ldmst_bitreverse_circular(env, ctx);

/* BOL-format */

    case OPC1_32_BOL_LD_A_LONGOFF:

    case OPC1_32_BOL_LD_W_LONGOFF:

    case OPC1_32_BOL_LEA_LONGOFF:

    case OPC1_32_BOL_ST_W_LONGOFF:

    case OPC1_32_BOL_ST_A_LONGOFF:

        decode_bol_opc(env, ctx, op1);

/* BRC Format */

    case OPCM_32_BRC_EQ_NEQ:

    case OPCM_32_BRC_GE:

    case OPCM_32_BRC_JLT:

    case OPCM_32_BRC_JNE:

        const4 = MASK_OP_BRC_CONST4_SEXT(ctx->opcode);

        address = MASK_OP_BRC_DISP15_SEXT(ctx->opcode);

        r1 = MASK_OP_BRC_S1(ctx->opcode);

        gen_compute_branch(ctx, op1, r1, 0, const4, address);

/* BRN Format */

    case OPCM_32_BRN_JTT:

        address = MASK_OP_BRN_DISP15_SEXT(ctx->opcode);

        r1 = MASK_OP_BRN_S1(ctx->opcode);

        gen_compute_branch(ctx, op1, r1, 0, 0, address);

/* BRR Format */

    case OPCM_32_BRR_EQ_NEQ:

    case OPCM_32_BRR_ADDR_EQ_NEQ:

    case OPCM_32_BRR_GE:

    case OPCM_32_BRR_JLT:

    case OPCM_32_BRR_JNE:

    case OPCM_32_BRR_JNZ:

    case OPCM_32_BRR_LOOP:

        address = MASK_OP_BRR_DISP15_SEXT(ctx->opcode);

        r2 = MASK_OP_BRR_S2(ctx->opcode);

        r1 = MASK_OP_BRR_S1(ctx->opcode);

        gen_compute_branch(ctx, op1, r1, r2, 0, address);

/* RC Format */

    case OPCM_32_RC_LOGICAL_SHIFT:

        decode_rc_logical_shift(env, ctx);

    case OPCM_32_RC_ACCUMULATOR:

        decode_rc_accumulator(env, ctx);

    case OPCM_32_RC_SERVICEROUTINE:

        decode_rc_serviceroutine(env, ctx);

    case OPCM_32_RC_MUL:

        decode_rc_mul(env, ctx);

/* RCPW Format */

    case OPCM_32_RCPW_MASK_INSERT:

        decode_rcpw_insert(env, ctx);

/* RCRR Format */

    case OPC1_32_RCRR_INSERT:

        r1 = MASK_OP_RCRR_S1(ctx->opcode);

        r2 = MASK_OP_RCRR_S3(ctx->opcode);

        r3 = MASK_OP_RCRR_D(ctx->opcode);

        const16 = MASK_OP_RCRR_CONST4(ctx->opcode);

        temp = tcg_const_i32(const16);

        temp2 = tcg_temp_new(); /* width*/

        temp3 = tcg_temp_new(); /* pos */

        tcg_gen_andi_tl(temp2, cpu_gpr_d[r3+1], 0x1f);

        tcg_gen_andi_tl(temp3, cpu_gpr_d[r3], 0x1f);

        gen_insert(cpu_gpr_d[r2], cpu_gpr_d[r1], temp, temp2, temp3);

        tcg_temp_free(temp);

        tcg_temp_free(temp2);

        tcg_temp_free(temp3);

/* RCRW Format */

    case OPCM_32_RCRW_MASK_INSERT:

        decode_rcrw_insert(env, ctx);

/* RCR Format */

    case OPCM_32_RCR_COND_SELECT:

        decode_rcr_cond_select(env, ctx);

    case OPCM_32_RCR_MADD:

        decode_rcr_madd(env, ctx);

    case OPCM_32_RCR_MSUB:

        decode_rcr_msub(env, ctx);

/* RLC Format */

    case OPC1_32_RLC_ADDI:

    case OPC1_32_RLC_ADDIH:

    case OPC1_32_RLC_ADDIH_A:

    case OPC1_32_RLC_MFCR:

    case OPC1_32_RLC_MOV:

    case OPC1_32_RLC_MOV_64:

    case OPC1_32_RLC_MOV_U:

    case OPC1_32_RLC_MOV_H:

    case OPC1_32_RLC_MOVH_A:

    case OPC1_32_RLC_MTCR:

        decode_rlc_opc(env, ctx, op1);

    }

}


AVFilterBufferRef *avfilter_get_video_buffer_ref_from_frame(const AVFrame *frame,

                                                            int perms)

{

    AVFilterBufferRef *picref =

        avfilter_get_video_buffer_ref_from_arrays(frame->data, frame->linesize, perms,

                                                  frame->width, frame->height,

                                                  frame->format);

    if (!picref)

        return NULL;

    avfilter_copy_frame_props(picref, frame);

    return picref;

}


void *g_realloc(void *ptr, size_t size)

{

    size_t old_size, copy;

    void *new_ptr;

    if (!ptr)

        return g_malloc(size);

    old_size = *(size_t *)((char *)ptr - 16);

    copy = old_size < size ? old_size : size;

    new_ptr = g_malloc(size);

    memcpy(new_ptr, ptr, copy);

    g_free(ptr);

    return new_ptr;

}


static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)

{

    AVStream *st;

    OutputStream *ost;

    AVCodecContext *audio_enc;

    ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);

    st  = ost->st;

    audio_enc = st->codec;

    audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;

    if (!ost->stream_copy) {

        char *sample_fmt = NULL;

        MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);

        MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);

        if (sample_fmt &&

            (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {

            av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);

            exit_program(1);

        }

        MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);

    }

    return ost;

}


static int pcx_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
                            AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int buf_size       = avpkt->size;
    AVFrame *const p   = data;
    int compressed, xmin, ymin, xmax, ymax;
    unsigned int w, h, bits_per_pixel, bytes_per_line, nplanes, stride, y, x,
                 bytes_per_scanline;
    uint8_t *ptr;
    const uint8_t *buf_end = buf + buf_size;
    const uint8_t *bufstart = buf;
    uint8_t *scanline;
    int ret = -1;
    if (buf[0] != 0x0a || buf[1] > 5) {
        av_log(avctx, AV_LOG_ERROR, "this is not PCX encoded data\n");
    compressed = buf[2];
    xmin       = AV_RL16(buf + 4);
    ymin       = AV_RL16(buf + 6);
    xmax       = AV_RL16(buf + 8);
    ymax       = AV_RL16(buf + 10);
    if (xmax < xmin || ymax < ymin) {
        av_log(avctx, AV_LOG_ERROR, "invalid image dimensions\n");
    w = xmax - xmin + 1;
    h = ymax - ymin + 1;
    bits_per_pixel     = buf[3];
    bytes_per_line     = AV_RL16(buf + 66);
    nplanes            = buf[65];
    bytes_per_scanline = nplanes * bytes_per_line;
    if (bytes_per_scanline < (w * bits_per_pixel * nplanes + 7) / 8 ||
        (!compressed && bytes_per_scanline > buf_size / h)) {
        av_log(avctx, AV_LOG_ERROR, "PCX data is corrupted\n");
    switch ((nplanes << 8) + bits_per_pixel) {
    case 0x0308:
        avctx->pix_fmt = AV_PIX_FMT_RGB24;
        break;
    case 0x0108:
    case 0x0104:
    case 0x0102:
    case 0x0101:
    case 0x0401:
    case 0x0301:
    case 0x0201:
        avctx->pix_fmt = AV_PIX_FMT_PAL8;
        break;
    default:
        av_log(avctx, AV_LOG_ERROR, "invalid PCX file\n");
    buf += 128;
    if ((ret = ff_set_dimensions(avctx, w, h)) < 0)
        return ret;
    if ((ret = ff_get_buffer(avctx, p, 0)) < 0) {
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
        return ret;
    p->pict_type = AV_PICTURE_TYPE_I;
    ptr    = p->data[0];
    stride = p->linesize[0];
    scanline = av_malloc(bytes_per_scanline + AV_INPUT_BUFFER_PADDING_SIZE);
    if (!scanline)
        return AVERROR(ENOMEM);
    if (nplanes == 3 && bits_per_pixel == 8) {
        for (y = 0; y < h; y++) {
            buf = pcx_rle_decode(buf, buf_end,
                                 scanline, bytes_per_scanline, compressed);
            for (x = 0; x < w; x++) {
                ptr[3 * x]     = scanline[x];
                ptr[3 * x + 1] = scanline[x + bytes_per_line];
                ptr[3 * x + 2] = scanline[x + (bytes_per_line << 1)];
            ptr += stride;
    } else if (nplanes == 1 && bits_per_pixel == 8) {
        const uint8_t *palstart = bufstart + buf_size - 769;
        if (buf_size < 769) {
            av_log(avctx, AV_LOG_ERROR, "File is too short\n");
            ret = avctx->err_recognition & AV_EF_EXPLODE ?
                  AVERROR_INVALIDDATA : buf_size;
            goto end;
        for (y = 0; y < h; y++, ptr += stride) {
            buf = pcx_rle_decode(buf, buf_end,
                                 scanline, bytes_per_scanline, compressed);
            memcpy(ptr, scanline, w);
        if (buf != palstart) {
            av_log(avctx, AV_LOG_WARNING, "image data possibly corrupted\n");
            buf = palstart;
        if (*buf++ != 12) {
            av_log(avctx, AV_LOG_ERROR, "expected palette after image data\n");
            ret = avctx->err_recognition & AV_EF_EXPLODE ?
                  AVERROR_INVALIDDATA : buf_size;
            goto end;
    } else if (nplanes == 1) {   /* all packed formats, max. 16 colors */
        GetBitContext s;
        for (y = 0; y < h; y++) {
            init_get_bits(&s, scanline, bytes_per_scanline << 3);
            buf = pcx_rle_decode(buf, buf_end,
                                 scanline, bytes_per_scanline, compressed);
            for (x = 0; x < w; x++)
                ptr[x] = get_bits(&s, bits_per_pixel);
            ptr += stride;
    } else {    /* planar, 4, 8 or 16 colors */
        int i;
        for (y = 0; y < h; y++) {
            buf = pcx_rle_decode(buf, buf_end,
                                 scanline, bytes_per_scanline, compressed);
            for (x = 0; x < w; x++) {
                int m = 0x80 >> (x & 7), v = 0;
                for (i = nplanes - 1; i >= 0; i--) {
                    v <<= 1;
                    v  += !!(scanline[i * bytes_per_line + (x >> 3)] & m);
                ptr[x] = v;
            ptr += stride;
    if (nplanes == 1 && bits_per_pixel == 8) {
        pcx_palette(&buf, (uint32_t *)p->data[1], 256);
    } else if (bits_per_pixel < 8) {
        const uint8_t *palette = bufstart + 16;
        pcx_palette(&palette, (uint32_t *)p->data[1], 16);
    *got_frame = 1;
    ret = buf - bufstart;
end:
    av_free(scanline);
    return ret;


static void ioport_write(void *opaque, uint32_t addr, uint32_t val)

{

    PCIQXLDevice *d = opaque;

    uint32_t io_port = addr - d->io_base;

    switch (io_port) {

    case QXL_IO_RESET:

    case QXL_IO_SET_MODE:

    case QXL_IO_MEMSLOT_ADD:

    case QXL_IO_MEMSLOT_DEL:

    case QXL_IO_CREATE_PRIMARY:

        break;

    default:

        if (d->mode == QXL_MODE_NATIVE || d->mode == QXL_MODE_COMPAT)

            break;

        dprint(d, 1, "%s: unexpected port 0x%x in vga mode\n", __FUNCTION__, io_port);

        return;

    }

    switch (io_port) {

    case QXL_IO_UPDATE_AREA:

    {

        QXLRect update = d->ram->update_area;

        qemu_mutex_unlock_iothread();

        d->ssd.worker->update_area(d->ssd.worker, d->ram->update_surface,

                                   &update, NULL, 0, 0);

        qemu_mutex_lock_iothread();

        break;

    }

    case QXL_IO_NOTIFY_CMD:

        d->ssd.worker->wakeup(d->ssd.worker);

        break;

    case QXL_IO_NOTIFY_CURSOR:

        d->ssd.worker->wakeup(d->ssd.worker);

        break;

    case QXL_IO_UPDATE_IRQ:

        qxl_set_irq(d);

        break;

    case QXL_IO_NOTIFY_OOM:

        if (!SPICE_RING_IS_EMPTY(&d->ram->release_ring)) {

            break;

        }

        pthread_yield();

        if (!SPICE_RING_IS_EMPTY(&d->ram->release_ring)) {

            break;

        }

        d->oom_running = 1;

        d->ssd.worker->oom(d->ssd.worker);

        d->oom_running = 0;

        break;

    case QXL_IO_SET_MODE:

        dprint(d, 1, "QXL_SET_MODE %d\n", val);

        qxl_set_mode(d, val, 0);

        break;

    case QXL_IO_LOG:

        if (d->guestdebug) {

            fprintf(stderr, "qxl/guest: %s", d->ram->log_buf);

        }

        break;

    case QXL_IO_RESET:

        dprint(d, 1, "QXL_IO_RESET\n");

        qxl_hard_reset(d, 0);

        break;

    case QXL_IO_MEMSLOT_ADD:

        PANIC_ON(val >= NUM_MEMSLOTS);

        PANIC_ON(d->guest_slots[val].active);

        d->guest_slots[val].slot = d->ram->mem_slot;

        qxl_add_memslot(d, val, 0);

        break;

    case QXL_IO_MEMSLOT_DEL:

        qxl_del_memslot(d, val);

        break;

    case QXL_IO_CREATE_PRIMARY:

        PANIC_ON(val != 0);

        dprint(d, 1, "QXL_IO_CREATE_PRIMARY\n");

        d->guest_primary.surface = d->ram->create_surface;

        qxl_create_guest_primary(d, 0);

        break;

    case QXL_IO_DESTROY_PRIMARY:

        PANIC_ON(val != 0);

        dprint(d, 1, "QXL_IO_DESTROY_PRIMARY\n");

        qxl_destroy_primary(d);

        break;

    case QXL_IO_DESTROY_SURFACE_WAIT:

        d->ssd.worker->destroy_surface_wait(d->ssd.worker, val);

        break;

    case QXL_IO_DESTROY_ALL_SURFACES:

        d->ssd.worker->destroy_surfaces(d->ssd.worker);

        break;

    default:

        fprintf(stderr, "%s: ioport=0x%x, abort()\n", __FUNCTION__, io_port);

        abort();

    }

}


static int h264_slice_header_parse(H264Context *h, H264SliceContext *sl)

{

    const SPS *sps;

    const PPS *pps;

    unsigned int first_mb_in_slice;

    unsigned int pps_id;

    int ret;

    unsigned int slice_type, tmp, i;

    int last_pic_structure, last_pic_droppable;

    int needs_reinit = 0;

    int field_pic_flag, bottom_field_flag;

    int frame_num, droppable, picture_structure;

    int mb_aff_frame = 0;

    first_mb_in_slice = get_ue_golomb(&sl->gb);

    if (first_mb_in_slice == 0) { // FIXME better field boundary detection

        if (h->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {

            ff_h264_field_end(h, sl, 1);

        }

        h->current_slice = 0;

        if (!h->first_field) {

            if (h->cur_pic_ptr && !h->droppable) {

                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,

                                          h->picture_structure == PICT_BOTTOM_FIELD);

            }

            h->cur_pic_ptr = NULL;

        }

    }

    slice_type = get_ue_golomb_31(&sl->gb);

    if (slice_type > 9) {

        av_log(h->avctx, AV_LOG_ERROR,

               "slice type %d too large at %d\n",

               slice_type, first_mb_in_slice);

        return AVERROR_INVALIDDATA;

    }

    if (slice_type > 4) {

        slice_type -= 5;

        sl->slice_type_fixed = 1;

    } else

        sl->slice_type_fixed = 0;

    slice_type         = ff_h264_golomb_to_pict_type[slice_type];

    sl->slice_type     = slice_type;

    sl->slice_type_nos = slice_type & 3;

    if (h->nal_unit_type  == NAL_IDR_SLICE &&

        sl->slice_type_nos != AV_PICTURE_TYPE_I) {

        av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");

        return AVERROR_INVALIDDATA;

    }

    pps_id = get_ue_golomb(&sl->gb);

    if (pps_id >= MAX_PPS_COUNT) {

        av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);

        return AVERROR_INVALIDDATA;

    }

    if (!h->ps.pps_list[pps_id]) {

        av_log(h->avctx, AV_LOG_ERROR,

               "non-existing PPS %u referenced\n",

               pps_id);

        return AVERROR_INVALIDDATA;

    }

    if (!h->setup_finished) {

        h->ps.pps = (const PPS*)h->ps.pps_list[pps_id]->data;

    } else if (h->ps.pps != (const PPS*)h->ps.pps_list[pps_id]->data) {

        av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");

        return AVERROR_INVALIDDATA;

    }

    if (!h->ps.sps_list[h->ps.pps->sps_id]) {

        av_log(h->avctx, AV_LOG_ERROR,

               "non-existing SPS %u referenced\n",

               h->ps.pps->sps_id);

        return AVERROR_INVALIDDATA;

    }

    if (h->ps.sps != (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data) {

        h->ps.sps = (SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data;

        if (h->bit_depth_luma    != h->ps.sps->bit_depth_luma ||

            h->chroma_format_idc != h->ps.sps->chroma_format_idc)

            needs_reinit         = 1;

    }

    pps = h->ps.pps;

    sps = h->ps.sps;

    if (!h->setup_finished) {

        h->avctx->profile = ff_h264_get_profile(sps);

        h->avctx->level   = sps->level_idc;

        h->avctx->refs    = sps->ref_frame_count;

        if (h->mb_width  != sps->mb_width ||

            h->mb_height != sps->mb_height * (2 - sps->frame_mbs_only_flag))

            needs_reinit = 1;

        h->mb_width  = sps->mb_width;

        h->mb_height = sps->mb_height * (2 - sps->frame_mbs_only_flag);

        h->mb_num    = h->mb_width * h->mb_height;

        h->mb_stride = h->mb_width + 1;

        h->b_stride = h->mb_width * 4;

        h->chroma_y_shift = sps->chroma_format_idc <= 1; // 400 uses yuv420p

        h->width  = 16 * h->mb_width;

        h->height = 16 * h->mb_height;

        ret = init_dimensions(h);

        if (ret < 0)

            return ret;

        if (sps->video_signal_type_present_flag) {

            h->avctx->color_range = sps->full_range ? AVCOL_RANGE_JPEG

                : AVCOL_RANGE_MPEG;

            if (sps->colour_description_present_flag) {

                if (h->avctx->colorspace != sps->colorspace)

                    needs_reinit = 1;

                h->avctx->color_primaries = sps->color_primaries;

                h->avctx->color_trc       = sps->color_trc;

                h->avctx->colorspace      = sps->colorspace;

            }

        }

    }

    if (h->context_initialized && needs_reinit) {

        h->context_initialized = 0;

        if (sl != h->slice_ctx) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "changing width %d -> %d / height %d -> %d on "

                   "slice %d\n",

                   h->width, h->avctx->coded_width,

                   h->height, h->avctx->coded_height,

                   h->current_slice + 1);

            return AVERROR_INVALIDDATA;

        }

        ff_h264_flush_change(h);

        if ((ret = get_pixel_format(h)) < 0)

            return ret;

        h->avctx->pix_fmt = ret;

        av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "

               "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);

        if ((ret = h264_slice_header_init(h)) < 0) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "h264_slice_header_init() failed\n");

            return ret;

        }

    }

    if (!h->context_initialized) {

        if (sl != h->slice_ctx) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "Cannot (re-)initialize context during parallel decoding.\n");

            return AVERROR_PATCHWELCOME;

        }

        if ((ret = get_pixel_format(h)) < 0)

            return ret;

        h->avctx->pix_fmt = ret;

        if ((ret = h264_slice_header_init(h)) < 0) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "h264_slice_header_init() failed\n");

            return ret;

        }

    }

    frame_num = get_bits(&sl->gb, sps->log2_max_frame_num);

    if (!h->setup_finished)

        h->poc.frame_num = frame_num;

    sl->mb_mbaff       = 0;

    last_pic_structure = h->picture_structure;

    last_pic_droppable = h->droppable;

    droppable = h->nal_ref_idc == 0;

    if (sps->frame_mbs_only_flag) {

        picture_structure = PICT_FRAME;

    } else {

        field_pic_flag = get_bits1(&sl->gb);

        if (field_pic_flag) {

            bottom_field_flag = get_bits1(&sl->gb);

            picture_structure = PICT_TOP_FIELD + bottom_field_flag;

        } else {

            picture_structure = PICT_FRAME;

            mb_aff_frame      = sps->mb_aff;

        }

    }

    if (!h->setup_finished) {

        h->droppable         = droppable;

        h->picture_structure = picture_structure;

        h->mb_aff_frame      = mb_aff_frame;

    }

    sl->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;

    if (h->current_slice != 0) {

        if (last_pic_structure != picture_structure ||

            last_pic_droppable != droppable) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "Changing field mode (%d -> %d) between slices is not allowed\n",

                   last_pic_structure, h->picture_structure);

            return AVERROR_INVALIDDATA;

        } else if (!h->cur_pic_ptr) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "unset cur_pic_ptr on slice %d\n",

                   h->current_slice + 1);

            return AVERROR_INVALIDDATA;

        }

    } else {

        /* Shorten frame num gaps so we don't have to allocate reference

         * frames just to throw them away */

        if (h->poc.frame_num != h->poc.prev_frame_num) {

            int unwrap_prev_frame_num = h->poc.prev_frame_num;

            int max_frame_num         = 1 << sps->log2_max_frame_num;

            if (unwrap_prev_frame_num > h->poc.frame_num)

                unwrap_prev_frame_num -= max_frame_num;

            if ((h->poc.frame_num - unwrap_prev_frame_num) > sps->ref_frame_count) {

                unwrap_prev_frame_num = (h->poc.frame_num - sps->ref_frame_count) - 1;

                if (unwrap_prev_frame_num < 0)

                    unwrap_prev_frame_num += max_frame_num;

                h->poc.prev_frame_num = unwrap_prev_frame_num;

            }

        }

        /* See if we have a decoded first field looking for a pair...

         * Here, we're using that to see if we should mark previously

         * decode frames as "finished".

         * We have to do that before the "dummy" in-between frame allocation,

         * since that can modify s->current_picture_ptr. */

        if (h->first_field) {

            assert(h->cur_pic_ptr);

            assert(h->cur_pic_ptr->f->buf[0]);

            assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);

            /* figure out if we have a complementary field pair */

            if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {

                /* Previous field is unmatched. Don't display it, but let it

                 * remain for reference if marked as such. */

                if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {

                    ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,

                                              last_pic_structure == PICT_TOP_FIELD);

                }

            } else {

                if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {

                    /* This and previous field were reference, but had

                     * different frame_nums. Consider this field first in

                     * pair. Throw away previous field except for reference

                     * purposes. */

                    if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {

                        ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,

                                                  last_pic_structure == PICT_TOP_FIELD);

                    }

                } else {

                    /* Second field in complementary pair */

                    if (!((last_pic_structure   == PICT_TOP_FIELD &&

                           h->picture_structure == PICT_BOTTOM_FIELD) ||

                          (last_pic_structure   == PICT_BOTTOM_FIELD &&

                           h->picture_structure == PICT_TOP_FIELD))) {

                        av_log(h->avctx, AV_LOG_ERROR,

                               "Invalid field mode combination %d/%d\n",

                               last_pic_structure, h->picture_structure);

                        h->picture_structure = last_pic_structure;

                        h->droppable         = last_pic_droppable;

                        return AVERROR_INVALIDDATA;

                    } else if (last_pic_droppable != h->droppable) {

                        avpriv_request_sample(h->avctx,

                                              "Found reference and non-reference fields in the same frame, which");

                        h->picture_structure = last_pic_structure;

                        h->droppable         = last_pic_droppable;

                        return AVERROR_PATCHWELCOME;

                    }

                }

            }

        }

        while (h->poc.frame_num != h->poc.prev_frame_num &&

               h->poc.frame_num != (h->poc.prev_frame_num + 1) % (1 << sps->log2_max_frame_num)) {

            H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;

            av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",

                   h->poc.frame_num, h->poc.prev_frame_num);

            ret = initialize_cur_frame(h);

            if (ret < 0) {

                h->first_field = 0;

                return ret;

            }

            h->poc.prev_frame_num++;

            h->poc.prev_frame_num        %= 1 << sps->log2_max_frame_num;

            h->cur_pic_ptr->frame_num = h->poc.prev_frame_num;

            ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);

            ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);

            ret = ff_generate_sliding_window_mmcos(h, 1);

            if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))

                return ret;

            ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);

            if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))

                return ret;

            /* Error concealment: If a ref is missing, copy the previous ref

             * in its place.

             * FIXME: Avoiding a memcpy would be nice, but ref handling makes

             * many assumptions about there being no actual duplicates.

             * FIXME: This does not copy padding for out-of-frame motion

             * vectors.  Given we are concealing a lost frame, this probably

             * is not noticeable by comparison, but it should be fixed. */

            if (h->short_ref_count) {

                if (prev &&

                    h->short_ref[0]->f->width == prev->f->width &&

                    h->short_ref[0]->f->height == prev->f->height &&

                    h->short_ref[0]->f->format == prev->f->format) {

                    av_image_copy(h->short_ref[0]->f->data,

                                  h->short_ref[0]->f->linesize,

                                  (const uint8_t **)prev->f->data,

                                  prev->f->linesize,

                                  prev->f->format,

                                  h->mb_width  * 16,

                                  h->mb_height * 16);

                    h->short_ref[0]->poc = prev->poc + 2;

                }

                h->short_ref[0]->frame_num = h->poc.prev_frame_num;

            }

        }

        /* See if we have a decoded first field looking for a pair...

         * We're using that to see whether to continue decoding in that

         * frame, or to allocate a new one. */

        if (h->first_field) {

            assert(h->cur_pic_ptr);

            assert(h->cur_pic_ptr->f->buf[0]);

            assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);

            /* figure out if we have a complementary field pair */

            if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {

                /* Previous field is unmatched. Don't display it, but let it

                 * remain for reference if marked as such. */

                h->cur_pic_ptr = NULL;

                h->first_field = FIELD_PICTURE(h);

            } else {

                if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {

                    /* This and the previous field had different frame_nums.

                     * Consider this field first in pair. Throw away previous

                     * one except for reference purposes. */

                    h->first_field = 1;

                    h->cur_pic_ptr = NULL;

                } else {

                    /* Second field in complementary pair */

                    h->first_field = 0;

                }

            }

        } else {

            /* Frame or first field in a potentially complementary pair */

            h->first_field = FIELD_PICTURE(h);

        }

        if (!FIELD_PICTURE(h) || h->first_field) {

            if (h264_frame_start(h) < 0) {

                h->first_field = 0;

                return AVERROR_INVALIDDATA;

            }

        } else {

            release_unused_pictures(h, 0);

        }

    }

    assert(h->mb_num == h->mb_width * h->mb_height);

    if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||

        first_mb_in_slice >= h->mb_num) {

        av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");

        return AVERROR_INVALIDDATA;

    }

    sl->resync_mb_x = sl->mb_x =  first_mb_in_slice % h->mb_width;

    sl->resync_mb_y = sl->mb_y = (first_mb_in_slice / h->mb_width) <<

                                 FIELD_OR_MBAFF_PICTURE(h);

    if (h->picture_structure == PICT_BOTTOM_FIELD)

        sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;

    assert(sl->mb_y < h->mb_height);

    if (h->picture_structure == PICT_FRAME) {

        h->curr_pic_num = h->poc.frame_num;

        h->max_pic_num  = 1 << sps->log2_max_frame_num;

    } else {

        h->curr_pic_num = 2 * h->poc.frame_num + 1;

        h->max_pic_num  = 1 << (sps->log2_max_frame_num + 1);

    }

    if (h->nal_unit_type == NAL_IDR_SLICE)

        get_ue_golomb(&sl->gb); /* idr_pic_id */

    if (sps->poc_type == 0) {

        int poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);

        if (!h->setup_finished)

            h->poc.poc_lsb = poc_lsb;

        if (pps->pic_order_present == 1 && h->picture_structure == PICT_FRAME) {

            int delta_poc_bottom = get_se_golomb(&sl->gb);

            if (!h->setup_finished)

                h->poc.delta_poc_bottom = delta_poc_bottom;

        }

    }

    if (sps->poc_type == 1 && !sps->delta_pic_order_always_zero_flag) {

        int delta_poc = get_se_golomb(&sl->gb);

        if (!h->setup_finished)

            h->poc.delta_poc[0] = delta_poc;

        if (pps->pic_order_present == 1 && h->picture_structure == PICT_FRAME) {

            delta_poc = get_se_golomb(&sl->gb);

            if (!h->setup_finished)

                h->poc.delta_poc[1] = delta_poc;

        }

    }

    if (!h->setup_finished)

        ff_h264_init_poc(h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc,

                         sps, &h->poc, h->picture_structure, h->nal_ref_idc);

    if (pps->redundant_pic_cnt_present)

        sl->redundant_pic_count = get_ue_golomb(&sl->gb);

    if (sl->slice_type_nos == AV_PICTURE_TYPE_B)

        sl->direct_spatial_mv_pred = get_bits1(&sl->gb);

    ret = ff_h264_parse_ref_count(&sl->list_count, sl->ref_count,

                                  &sl->gb, pps, sl->slice_type_nos,

                                  h->picture_structure);

    if (ret < 0)

        return ret;

    if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {

       ret = ff_h264_decode_ref_pic_list_reordering(h, sl);

       if (ret < 0) {

           sl->ref_count[1] = sl->ref_count[0] = 0;

           return ret;

       }

    }

    sl->pwt.use_weight = 0;

    for (i = 0; i < 2; i++) {

        sl->pwt.luma_weight_flag[i]   = 0;

        sl->pwt.chroma_weight_flag[i] = 0;

    }

    if ((pps->weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||

        (pps->weighted_bipred_idc == 1 &&

         sl->slice_type_nos == AV_PICTURE_TYPE_B))

        ff_h264_pred_weight_table(&sl->gb, sps, sl->ref_count,

                                  sl->slice_type_nos, &sl->pwt);

    // If frame-mt is enabled, only update mmco tables for the first slice

    // in a field. Subsequent slices can temporarily clobber h->mmco_index

    // or h->mmco, which will cause ref list mix-ups and decoding errors

    // further down the line. This may break decoding if the first slice is

    // corrupt, thus we only do this if frame-mt is enabled.

    if (h->nal_ref_idc) {

        ret = ff_h264_decode_ref_pic_marking(h, &sl->gb,

                                             !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||

                                             h->current_slice == 0);

        if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))

            return AVERROR_INVALIDDATA;

    }

    if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {

        tmp = get_ue_golomb_31(&sl->gb);

        if (tmp > 2) {

            av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);

            return AVERROR_INVALIDDATA;

        }

        sl->cabac_init_idc = tmp;

    }

    sl->last_qscale_diff = 0;

    tmp = pps->init_qp + get_se_golomb(&sl->gb);

    if (tmp > 51 + 6 * (sps->bit_depth_luma - 8)) {

        av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);

        return AVERROR_INVALIDDATA;

    }

    sl->qscale       = tmp;

    sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);

    sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);

    // FIXME qscale / qp ... stuff

    if (sl->slice_type == AV_PICTURE_TYPE_SP)

        get_bits1(&sl->gb); /* sp_for_switch_flag */

    if (sl->slice_type == AV_PICTURE_TYPE_SP ||

        sl->slice_type == AV_PICTURE_TYPE_SI)

        get_se_golomb(&sl->gb); /* slice_qs_delta */

    sl->deblocking_filter     = 1;

    sl->slice_alpha_c0_offset = 0;

    sl->slice_beta_offset     = 0;

    if (pps->deblocking_filter_parameters_present) {

        tmp = get_ue_golomb_31(&sl->gb);

        if (tmp > 2) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "deblocking_filter_idc %u out of range\n", tmp);

            return AVERROR_INVALIDDATA;

        }

        sl->deblocking_filter = tmp;

        if (sl->deblocking_filter < 2)

            sl->deblocking_filter ^= 1;  // 1<->0

        if (sl->deblocking_filter) {

            sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2;

            sl->slice_beta_offset     = get_se_golomb(&sl->gb) * 2;

            if (sl->slice_alpha_c0_offset >  12 ||

                sl->slice_alpha_c0_offset < -12 ||

                sl->slice_beta_offset >  12     ||

                sl->slice_beta_offset < -12) {

                av_log(h->avctx, AV_LOG_ERROR,

                       "deblocking filter parameters %d %d out of range\n",

                       sl->slice_alpha_c0_offset, sl->slice_beta_offset);

                return AVERROR_INVALIDDATA;

            }

        }

    }

    return 0;

}


int ffurl_shutdown(URLContext *h, int flags)

{

    if (!h->prot->url_shutdown)

        return AVERROR(EINVAL);

    return h->prot->url_shutdown(h, flags);

}


static void i82378_init(DeviceState *dev, I82378State *s)

{

    ISABus *isabus = DO_UPCAST(ISABus, qbus, qdev_get_child_bus(dev, "isa.0"));

    ISADevice *pit;

    qemu_irq *out0_irq;

    /* This device has:

       2 82C59 (irq)

       1 82C54 (pit)

       2 82C37 (dma)

       NMI

       Utility Bus Support Registers

       All devices accept byte access only, except timer

     */

    qdev_init_gpio_out(dev, s->out, 2);

    qdev_init_gpio_in(dev, i82378_request_pic_irq, 16);

    /* Workaround the fact that i8259 is not qdev'ified... */

    out0_irq = qemu_allocate_irqs(i82378_request_out0_irq, s, 1);

    /* 2 82C59 (irq) */

    s->i8259 = i8259_init(isabus, *out0_irq);

    isa_bus_irqs(isabus, s->i8259);

    /* 1 82C54 (pit) */

    pit = pit_init(isabus, 0x40, 0, NULL);

    /* speaker */

    pcspk_init(isabus, pit);

    /* 2 82C37 (dma) */

    DMA_init(1, &s->out[1]);

    isa_create_simple(isabus, "i82374");

    /* timer */

    isa_create_simple(isabus, "mc146818rtc");

}


static void realview_init(ram_addr_t ram_size, int vga_ram_size,

                     const char *boot_device, DisplayState *ds,

                     const char *kernel_filename, const char *kernel_cmdline,

                     const char *initrd_filename, const char *cpu_model)

{

    CPUState *env;

    qemu_irq *pic;

    void *scsi_hba;

    PCIBus *pci_bus;

    NICInfo *nd;

    int n;

    int done_smc = 0;

    qemu_irq cpu_irq[4];

    int ncpu;

    int index;

    if (!cpu_model)

        cpu_model = "arm926";

    /* FIXME: obey smp_cpus.  */

    if (strcmp(cpu_model, "arm11mpcore") == 0) {

        ncpu = 4;

    } else {

        ncpu = 1;

    }

    for (n = 0; n < ncpu; n++) {

        env = cpu_init(cpu_model);

        if (!env) {

            fprintf(stderr, "Unable to find CPU definition\n");

            exit(1);

        }

        pic = arm_pic_init_cpu(env);

        cpu_irq[n] = pic[ARM_PIC_CPU_IRQ];

        if (n > 0) {

            /* Set entry point for secondary CPUs.  This assumes we're using

               the init code from arm_boot.c.  Real hardware resets all CPUs

               the same.  */

            env->regs[15] = 0x80000000;

        }

    }

    /* ??? RAM should repeat to fill physical memory space.  */

    /* SDRAM at address zero.  */

    cpu_register_physical_memory(0, ram_size, IO_MEM_RAM);

    arm_sysctl_init(0x10000000, 0xc1400400);

    if (ncpu == 1) {

        /* ??? The documentation says GIC1 is nFIQ and either GIC2 or GIC3

           is nIRQ (there are inconsistencies).  However Linux 2.6.17 expects

           GIC1 to be nIRQ and ignores all the others, so do that for now.  */

        pic = realview_gic_init(0x10040000, cpu_irq[0]);

    } else {

        pic = mpcore_irq_init(cpu_irq);

    }

    pl050_init(0x10006000, pic[20], 0);

    pl050_init(0x10007000, pic[21], 1);

    pl011_init(0x10009000, pic[12], serial_hds[0], PL011_ARM);

    pl011_init(0x1000a000, pic[13], serial_hds[1], PL011_ARM);

    pl011_init(0x1000b000, pic[14], serial_hds[2], PL011_ARM);

    pl011_init(0x1000c000, pic[15], serial_hds[3], PL011_ARM);

    /* DMA controller is optional, apparently.  */

    pl080_init(0x10030000, pic[24], 2);

    sp804_init(0x10011000, pic[4]);

    sp804_init(0x10012000, pic[5]);

    pl110_init(ds, 0x10020000, pic[23], 1);

    index = drive_get_index(IF_SD, 0, 0);

    if (index == -1) {

        fprintf(stderr, "qemu: missing SecureDigital card\n");

        exit(1);

    }

    pl181_init(0x10005000, drives_table[index].bdrv, pic[17], pic[18]);

    pl031_init(0x10017000, pic[10]);

    pci_bus = pci_vpb_init(pic, 48, 1);

    if (usb_enabled) {

        usb_ohci_init_pci(pci_bus, 3, -1);

    }

    if (drive_get_max_bus(IF_SCSI) > 0) {

        fprintf(stderr, "qemu: too many SCSI bus\n");

        exit(1);

    }

    scsi_hba = lsi_scsi_init(pci_bus, -1);

    for (n = 0; n < LSI_MAX_DEVS; n++) {

        index = drive_get_index(IF_SCSI, 0, n);

        if (index == -1)

            continue;

        lsi_scsi_attach(scsi_hba, drives_table[index].bdrv, n);

    }

    for(n = 0; n < nb_nics; n++) {

        nd = &nd_table[n];

        if (!nd->model)

            nd->model = done_smc ? "rtl8139" : "smc91c111";

        if (strcmp(nd->model, "smc91c111") == 0) {

            smc91c111_init(nd, 0x4e000000, pic[28]);

        } else {

            pci_nic_init(pci_bus, nd, -1);

        }

    }

    /* Memory map for RealView Emulation Baseboard:  */

    /* 0x10000000 System registers.  */

    /*  0x10001000 System controller.  */

    /*  0x10002000 Two-Wire Serial Bus.  */

    /* 0x10003000 Reserved.  */

    /*  0x10004000 AACI.  */

    /*  0x10005000 MCI.  */

    /* 0x10006000 KMI0.  */

    /* 0x10007000 KMI1.  */

    /*  0x10008000 Character LCD.  */

    /* 0x10009000 UART0.  */

    /* 0x1000a000 UART1.  */

    /* 0x1000b000 UART2.  */

    /* 0x1000c000 UART3.  */

    /*  0x1000d000 SSPI.  */

    /*  0x1000e000 SCI.  */

    /* 0x1000f000 Reserved.  */

    /*  0x10010000 Watchdog.  */

    /* 0x10011000 Timer 0+1.  */

    /* 0x10012000 Timer 2+3.  */

    /*  0x10013000 GPIO 0.  */

    /*  0x10014000 GPIO 1.  */

    /*  0x10015000 GPIO 2.  */

    /* 0x10016000 Reserved.  */

    /* 0x10017000 RTC.  */

    /*  0x10018000 DMC.  */

    /*  0x10019000 PCI controller config.  */

    /*  0x10020000 CLCD.  */

    /* 0x10030000 DMA Controller.  */

    /* 0x10040000 GIC1.  */

    /* 0x10050000 GIC2.  */

    /* 0x10060000 GIC3.  */

    /* 0x10070000 GIC4.  */

    /*  0x10080000 SMC.  */

    /*  0x40000000 NOR flash.  */

    /*  0x44000000 DoC flash.  */

    /*  0x48000000 SRAM.  */

    /*  0x4c000000 Configuration flash.  */

    /* 0x4e000000 Ethernet.  */

    /*  0x4f000000 USB.  */

    /*  0x50000000 PISMO.  */

    /*  0x54000000 PISMO.  */

    /*  0x58000000 PISMO.  */

    /*  0x5c000000 PISMO.  */

    /* 0x60000000 PCI.  */

    /* 0x61000000 PCI Self Config.  */

    /* 0x62000000 PCI Config.  */

    /* 0x63000000 PCI IO.  */

    /* 0x64000000 PCI mem 0.  */

    /* 0x68000000 PCI mem 1.  */

    /* 0x6c000000 PCI mem 2.  */

    realview_binfo.ram_size = ram_size;

    realview_binfo.kernel_filename = kernel_filename;

    realview_binfo.kernel_cmdline = kernel_cmdline;

    realview_binfo.initrd_filename = initrd_filename;

    realview_binfo.nb_cpus = ncpu;

    arm_load_kernel(first_cpu, &realview_binfo);

    /* ??? Hack to map an additional page of ram for the secondary CPU

       startup code.  I guess this works on real hardware because the

       BootROM happens to be in ROM/flash or in memory that isn't clobbered

       until after Linux boots the secondary CPUs.  */

    cpu_register_physical_memory(0x80000000, 0x1000, IO_MEM_RAM + ram_size);

}


QString *qstring_from_substr(const char *str, int start, int end)

{

    QString *qstring;

    qstring = g_malloc(sizeof(*qstring));

    qstring->length = end - start + 1;

    qstring->capacity = qstring->length;

    qstring->string = g_malloc(qstring->capacity + 1);

    memcpy(qstring->string, str + start, qstring->length);

    qstring->string[qstring->length] = 0;

    QOBJECT_INIT(qstring, &qstring_type);

    return qstring;

}


static void test_source_wait_event_notifier(void)

{

    EventNotifierTestData data = { .n = 0, .active = 1 };

    event_notifier_init(&data.e, false);

    aio_set_event_notifier(ctx, &data.e, event_ready_cb);

    g_assert(g_main_context_iteration(NULL, false));

    g_assert_cmpint(data.n, ==, 0);

    g_assert_cmpint(data.active, ==, 1);

    event_notifier_set(&data.e);

    g_assert(g_main_context_iteration(NULL, false));

    g_assert_cmpint(data.n, ==, 1);

    g_assert_cmpint(data.active, ==, 0);

    while (g_main_context_iteration(NULL, false));

    g_assert_cmpint(data.n, ==, 1);

    g_assert_cmpint(data.active, ==, 0);

    aio_set_event_notifier(ctx, &data.e, NULL);

    while (g_main_context_iteration(NULL, false));

    g_assert_cmpint(data.n, ==, 1);

    event_notifier_cleanup(&data.e);

}


static int coroutine_fn is_allocated_base(BlockDriverState *top,

                                          BlockDriverState *base,

                                          int64_t sector_num,

                                          int nb_sectors, int *pnum)

{

    BlockDriverState *intermediate;

    int ret, n;

    ret = bdrv_co_is_allocated(top, sector_num, nb_sectors, &n);

    if (ret) {

        *pnum = n;

        return ret;

    }

    /*

     * Is the unallocated chunk [sector_num, n] also

     * unallocated between base and top?

     */

    intermediate = top->backing_hd;

    while (intermediate != base) {

        int pnum_inter;

        ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,

                                   &pnum_inter);

        if (ret < 0) {

            return ret;

        } else if (ret) {

            *pnum = pnum_inter;

            return 0;

        }

        /*

         * [sector_num, nb_sectors] is unallocated on top but intermediate

         * might have

         *

         * [sector_num+x, nr_sectors] allocated.

         */

        if (n > pnum_inter) {

            n = pnum_inter;

        }

        intermediate = intermediate->backing_hd;

    }

    *pnum = n;

    return 1;

}


static DisplayType select_display(const char *p)

{

    Error *err = NULL;

    const char *opts;

    DisplayType display = DT_DEFAULT;

    if (strstart(p, "sdl", &opts)) {

#ifdef CONFIG_SDL

        display = DT_SDL;

        while (*opts) {

            const char *nextopt;

            if (strstart(opts, ",frame=", &nextopt)) {

                opts = nextopt;

                if (strstart(opts, "on", &nextopt)) {

                    no_frame = 0;

                } else if (strstart(opts, "off", &nextopt)) {

                    no_frame = 1;

                } else {

                    goto invalid_sdl_args;

                }

            } else if (strstart(opts, ",alt_grab=", &nextopt)) {

                opts = nextopt;

                if (strstart(opts, "on", &nextopt)) {

                    alt_grab = 1;

                } else if (strstart(opts, "off", &nextopt)) {

                    alt_grab = 0;

                } else {

                    goto invalid_sdl_args;

                }

            } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {

                opts = nextopt;

                if (strstart(opts, "on", &nextopt)) {

                    ctrl_grab = 1;

                } else if (strstart(opts, "off", &nextopt)) {

                    ctrl_grab = 0;

                } else {

                    goto invalid_sdl_args;

                }

            } else if (strstart(opts, ",window_close=", &nextopt)) {

                opts = nextopt;

                if (strstart(opts, "on", &nextopt)) {

                    no_quit = 0;

                } else if (strstart(opts, "off", &nextopt)) {

                    no_quit = 1;

                } else {

                    goto invalid_sdl_args;

                }

            } else if (strstart(opts, ",gl=", &nextopt)) {

                opts = nextopt;

                if (strstart(opts, "on", &nextopt)) {

                    request_opengl = 1;

                } else if (strstart(opts, "off", &nextopt)) {

                    request_opengl = 0;

                } else {

                    goto invalid_sdl_args;

                }

            } else {

            invalid_sdl_args:

                fprintf(stderr, "Invalid SDL option string: %s\n", p);

                exit(1);

            }

            opts = nextopt;

        }

#else

        fprintf(stderr, "SDL support is disabled\n");

        exit(1);

#endif

    } else if (strstart(p, "vnc", &opts)) {

#ifdef CONFIG_VNC

        if (*opts == '=') {

            if (vnc_parse(opts + 1, &err) == NULL) {

                error_report_err(err);

                exit(1);

            }

        } else {

            fprintf(stderr, "VNC requires a display argument vnc=<display>\n");

            exit(1);

        }

#else

        fprintf(stderr, "VNC support is disabled\n");

        exit(1);

#endif

    } else if (strstart(p, "curses", &opts)) {

#ifdef CONFIG_CURSES

        display = DT_CURSES;

#else

        fprintf(stderr, "Curses support is disabled\n");

        exit(1);

#endif

    } else if (strstart(p, "gtk", &opts)) {

#ifdef CONFIG_GTK

        display = DT_GTK;

        while (*opts) {

            const char *nextopt;

            if (strstart(opts, ",grab_on_hover=", &nextopt)) {

                opts = nextopt;

                if (strstart(opts, "on", &nextopt)) {

                    grab_on_hover = true;

                } else if (strstart(opts, "off", &nextopt)) {

                    grab_on_hover = false;

                } else {

                    goto invalid_gtk_args;

                }

            } else if (strstart(opts, ",gl=", &nextopt)) {

                opts = nextopt;

                if (strstart(opts, "on", &nextopt)) {

                    request_opengl = 1;

                } else if (strstart(opts, "off", &nextopt)) {

                    request_opengl = 0;

                } else {

                    goto invalid_gtk_args;

                }

            } else {

            invalid_gtk_args:

                fprintf(stderr, "Invalid GTK option string: %s\n", p);

                exit(1);

            }

            opts = nextopt;

        }

#else

        fprintf(stderr, "GTK support is disabled\n");

        exit(1);

#endif

    } else if (strstart(p, "none", &opts)) {

        display = DT_NONE;

    } else {

        fprintf(stderr, "Unknown display type: %s\n", p);

        exit(1);

    }

    return display;

}


static int get_packetheader(NUTContext *nut, ByteIOContext *bc, int prefix_length, int calculate_checksum)

{

    int64_t start, size, last_size;

    start= url_ftell(bc) - prefix_length;

    if(start != nut->packet_start + nut->written_packet_size){

        av_log(nut->avf, AV_LOG_ERROR, "get_packetheader called at weird position\n");

        return -1;

    }

    if(calculate_checksum)

        init_checksum(bc, update_adler32, 0);

    size= get_v(bc);

    last_size= get_v(bc);

    if(nut->written_packet_size != last_size){

        av_log(nut->avf, AV_LOG_ERROR, "packet size missmatch %d != %lld at %lld\n", nut->written_packet_size, last_size, start);

        return -1;

    }

    nut->last_packet_start = nut->packet_start;

    nut->packet_start = start;

    nut->written_packet_size= size;

    return size;

}


static void megasas_unmap_frame(MegasasState *s, MegasasCmd *cmd)

{

    PCIDevice *p = PCI_DEVICE(s);

    pci_dma_unmap(p, cmd->frame, cmd->pa_size, 0, 0);

    cmd->frame = NULL;

    cmd->pa = 0;

    clear_bit(cmd->index, s->frame_map);

}


int v9fs_co_open2(V9fsState *s, V9fsFidState *fidp, char *fullname, gid_t gid,

                  int flags, int mode)

{

    int err;

    FsCred cred;

    cred_init(&cred);

    cred.fc_mode = mode & 07777;

    cred.fc_uid = fidp->uid;

    cred.fc_gid = gid;

    v9fs_co_run_in_worker(

        {

            fidp->fs.fd = s->ops->open2(&s->ctx, fullname, flags, &cred);

            err = 0;

            if (fidp->fs.fd == -1) {

                err = -errno;

            }

        });

    if (!err) {

        total_open_fd++;

        if (total_open_fd > open_fd_hw) {

            v9fs_reclaim_fd(s);

        }

    }

    return err;

}


static int receive_filter(VirtIONet *n, const uint8_t *buf, int size)

{

    static const uint8_t bcast[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};

    static const uint8_t vlan[] = {0x81, 0x00};

    uint8_t *ptr = (uint8_t *)buf;

    int i;

    if (n->promisc)

        return 1;

    if (!memcmp(&ptr[12], vlan, sizeof(vlan))) {

        int vid = be16_to_cpup((uint16_t *)(ptr + 14)) & 0xfff;

        if (!(n->vlans[vid >> 5] & (1U << (vid & 0x1f))))

            return 0;

    }

    if ((ptr[0] & 1) && n->allmulti)

        return 1;

    if (!memcmp(ptr, bcast, sizeof(bcast)))

        return 1;

    if (!memcmp(ptr, n->mac, ETH_ALEN))

        return 1;

    for (i = 0; i < n->mac_table.in_use; i++) {

        if (!memcmp(ptr, &n->mac_table.macs[i * ETH_ALEN], ETH_ALEN))

            return 1;

    }

    return 0;

}


static int output_packet(InputStream *ist, int ist_index,

                         OutputStream *ost_table, int nb_ostreams,

                         const AVPacket *pkt)

{

    AVFormatContext *os;

    OutputStream *ost;

    int ret, i;

    int got_output;

    void *buffer_to_free = NULL;

    static unsigned int samples_size= 0;

    AVSubtitle subtitle, *subtitle_to_free;

    int64_t pkt_pts = AV_NOPTS_VALUE;

#if CONFIG_AVFILTER

    int frame_available;

#endif

    float quality;

    AVPacket avpkt;

    int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);

    if(ist->next_pts == AV_NOPTS_VALUE)

        ist->next_pts= ist->pts;

    if (pkt == NULL) {

        /* EOF handling */

        av_init_packet(&avpkt);

        avpkt.data = NULL;

        avpkt.size = 0;

        goto handle_eof;

    } else {

        avpkt = *pkt;

    }

    if(pkt->dts != AV_NOPTS_VALUE)

        ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);

    if(pkt->pts != AV_NOPTS_VALUE)

        pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);

    //while we have more to decode or while the decoder did output something on EOF

    while (avpkt.size > 0 || (!pkt && got_output)) {

        uint8_t *data_buf, *decoded_data_buf;

        int data_size, decoded_data_size;

        AVFrame *decoded_frame, *filtered_frame;

    handle_eof:

        ist->pts= ist->next_pts;

        if(avpkt.size && avpkt.size != pkt->size)

            av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,

                   "Multiple frames in a packet from stream %d\n", pkt->stream_index);

            ist->showed_multi_packet_warning=1;

        /* decode the packet if needed */

        decoded_frame    = filtered_frame = NULL;

        decoded_data_buf = NULL; /* fail safe */

        decoded_data_size= 0;

        data_buf  = avpkt.data;

        data_size = avpkt.size;

        subtitle_to_free = NULL;

        if (ist->decoding_needed) {

            switch(ist->st->codec->codec_type) {

            case AVMEDIA_TYPE_AUDIO:{

                if(pkt && samples_size < FFMAX(pkt->size * bps, AVCODEC_MAX_AUDIO_FRAME_SIZE)) {

                    samples_size = FFMAX(pkt->size * bps, AVCODEC_MAX_AUDIO_FRAME_SIZE);

                    av_free(samples);

                    samples= av_malloc(samples_size);

                }

                decoded_data_size= samples_size;

                    /* XXX: could avoid copy if PCM 16 bits with same

                       endianness as CPU */

                ret = avcodec_decode_audio3(ist->st->codec, samples, &decoded_data_size,

                                            &avpkt);

                if (ret < 0)

                    return ret;

                avpkt.data += ret;

                avpkt.size -= ret;

                data_size   = ret;

                got_output  = decoded_data_size > 0;

                /* Some bug in mpeg audio decoder gives */

                /* decoded_data_size < 0, it seems they are overflows */

                if (!got_output) {

                    /* no audio frame */

                    continue;

                }

                decoded_data_buf = (uint8_t *)samples;

                ist->next_pts += ((int64_t)AV_TIME_BASE/bps * decoded_data_size) /

                    (ist->st->codec->sample_rate * ist->st->codec->channels);

                break;}

            case AVMEDIA_TYPE_VIDEO:

                    decoded_data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;

                    if (!(decoded_frame = avcodec_alloc_frame()))

                        return AVERROR(ENOMEM);

                    avpkt.pts = pkt_pts;

                    avpkt.dts = ist->pts;

                    pkt_pts = AV_NOPTS_VALUE;

                    ret = avcodec_decode_video2(ist->st->codec,

                                                decoded_frame, &got_output, &avpkt);

                    quality = same_quant ? decoded_frame->quality : 0;

                    if (ret < 0)

                        goto fail;

                    if (!got_output) {

                        /* no picture yet */

                        av_freep(&decoded_frame);

                        goto discard_packet;

                    }

                    ist->next_pts = ist->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,

                                                                 decoded_frame->pkt_dts);

                    if (ist->st->codec->time_base.num != 0) {

                        int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;

                        ist->next_pts += ((int64_t)AV_TIME_BASE *

                                          ist->st->codec->time_base.num * ticks) /

                            ist->st->codec->time_base.den;

                    }

                    avpkt.size = 0;

                    buffer_to_free = NULL;

                    pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);

                    break;

            case AVMEDIA_TYPE_SUBTITLE:

                ret = avcodec_decode_subtitle2(ist->st->codec,

                                               &subtitle, &got_output, &avpkt);

                if (ret < 0)

                    return ret;

                if (!got_output) {

                    goto discard_packet;

                }

                subtitle_to_free = &subtitle;

                avpkt.size = 0;

                break;

            default:

                return -1;

            }

        } else {

            switch(ist->st->codec->codec_type) {

            case AVMEDIA_TYPE_AUDIO:

                ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /

                    ist->st->codec->sample_rate;

                break;

            case AVMEDIA_TYPE_VIDEO:

                if (ist->st->codec->time_base.num != 0) {

                    int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;

                    ist->next_pts += ((int64_t)AV_TIME_BASE *

                                      ist->st->codec->time_base.num * ticks) /

                        ist->st->codec->time_base.den;

                }

                break;

            }

            avpkt.size = 0;

        }

        // preprocess audio (volume)

        if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            if (audio_volume != 256) {

                switch (ist->st->codec->sample_fmt) {

                case AV_SAMPLE_FMT_U8:

                {

                    uint8_t *volp = samples;

                    for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                        int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;

                        *volp++ = av_clip_uint8(v);

                    }

                    break;

                }

                case AV_SAMPLE_FMT_S16:

                {

                short *volp;

                volp = samples;

                for(i=0;i<(decoded_data_size / sizeof(short));i++) {

                    int v = ((*volp) * audio_volume + 128) >> 8;

                    *volp++ = av_clip_int16(v);

                }

                break;

                }

                case AV_SAMPLE_FMT_S32:

                {

                    int32_t *volp = samples;

                    for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                        int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);

                        *volp++ = av_clipl_int32(v);

                    }

                    break;

                }

                case AV_SAMPLE_FMT_FLT:

                {

                    float *volp = samples;

                    float scale = audio_volume / 256.f;

                    for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                        *volp++ *= scale;

                    }

                    break;

                }

                case AV_SAMPLE_FMT_DBL:

                {

                    double *volp = samples;

                    double scale = audio_volume / 256.;

                    for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {

                        *volp++ *= scale;

                    }

                    break;

                }

                default:

                    av_log(NULL, AV_LOG_FATAL,

                           "Audio volume adjustment on sample format %s is not supported.\n",

                           av_get_sample_fmt_name(ist->st->codec->sample_fmt));

                    exit_program(1);

                }

            }

        }

        /* frame rate emulation */

        if (input_files[ist->file_index].rate_emu) {

            int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);

            int64_t now = av_gettime() - ist->start;

            if (pts > now)

                usleep(pts - now);

        }

        /* if output time reached then transcode raw format,

           encode packets and output them */

        for (i = 0; i < nb_ostreams; i++) {

            OutputFile *of = &output_files[ost_table[i].file_index];

            int frame_size;

            ost = &ost_table[i];

            if (ost->source_index != ist_index)

                continue;

            if (of->start_time && ist->pts < of->start_time)

                continue;

            if (of->recording_time != INT64_MAX &&

                av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,

                              (AVRational){1, 1000000}) >= 0) {

                ost->is_past_recording_time = 1;

                continue;

            }

#if CONFIG_AVFILTER

            if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&

                ost->input_video_filter) {

                AVRational sar;

                if (ist->st->sample_aspect_ratio.num)

                    sar = ist->st->sample_aspect_ratio;

                else

                    sar = ist->st->codec->sample_aspect_ratio;

                av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, ist->pts, sar);

                if (!(filtered_frame = avcodec_alloc_frame())) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

            }

            frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||

                !ost->output_video_filter || avfilter_poll_frame(ost->output_video_filter->inputs[0]);

            while (frame_available) {

                AVRational ist_pts_tb;

                if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ost->output_video_filter)

                    get_filtered_video_frame(ost->output_video_filter, filtered_frame, &ost->picref, &ist_pts_tb);

                if (ost->picref)

                    ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);

#else

                filtered_frame = decoded_frame;

#endif

                os = output_files[ost->file_index].ctx;

                /* set the input output pts pairs */

                //ost->sync_ipts = (double)(ist->pts + input_files[ist->file_index].ts_offset - start_time)/ AV_TIME_BASE;

                if (ost->encoding_needed) {

                    av_assert0(ist->decoding_needed);

                    switch(ost->st->codec->codec_type) {

                    case AVMEDIA_TYPE_AUDIO:

                        do_audio_out(os, ost, ist, decoded_data_buf, decoded_data_size);

                        break;

                    case AVMEDIA_TYPE_VIDEO:

#if CONFIG_AVFILTER

                        if (ost->picref->video && !ost->frame_aspect_ratio)

                            ost->st->codec->sample_aspect_ratio = ost->picref->video->pixel_aspect;

#endif

                        do_video_out(os, ost, ist, filtered_frame, &frame_size,

                                     same_quant ? quality : ost->st->codec->global_quality);

                        if (vstats_filename && frame_size)

                            do_video_stats(os, ost, frame_size);

                        break;

                    case AVMEDIA_TYPE_SUBTITLE:

                        do_subtitle_out(os, ost, ist, &subtitle,

                                        pkt->pts);

                        break;

                    default:

                        abort();

                    }

                } else {

                    AVPacket opkt;

                    int64_t ost_tb_start_time= av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);

                    av_init_packet(&opkt);

                    if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) && !copy_initial_nonkeyframes)

#if !CONFIG_AVFILTER

                        continue;

#else

                        goto cont;

#endif

                    /* no reencoding needed : output the packet directly */

                    /* force the input stream PTS */

                    if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)

                        audio_size += data_size;

                    else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

                        video_size += data_size;

                        ost->sync_opts++;

                    }

                    opkt.stream_index= ost->index;

                    if(pkt->pts != AV_NOPTS_VALUE)

                        opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;

                    else

                        opkt.pts= AV_NOPTS_VALUE;

                    if (pkt->dts == AV_NOPTS_VALUE)

                        opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);

                    else

                        opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);

                    opkt.dts -= ost_tb_start_time;

                    opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);

                    opkt.flags= pkt->flags;

                    //FIXME remove the following 2 lines they shall be replaced by the bitstream filters

                    if(   ost->st->codec->codec_id != CODEC_ID_H264

                       && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO

                       && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO

                       ) {

                        if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & AV_PKT_FLAG_KEY))

                            opkt.destruct= av_destruct_packet;

                    } else {

                        opkt.data = data_buf;

                        opkt.size = data_size;

                    }

                    write_frame(os, &opkt, ost->st->codec, ost->bitstream_filters);

                    ost->st->codec->frame_number++;

                    ost->frame_number++;

                    av_free_packet(&opkt);

                }

#if CONFIG_AVFILTER

                cont:

                frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&

                                   ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);

                if (ost->picref)

                    avfilter_unref_buffer(ost->picref);

            }

            av_freep(&filtered_frame);

#endif

            }

fail:

        av_free(buffer_to_free);

        /* XXX: allocate the subtitles in the codec ? */

        if (subtitle_to_free) {

            avsubtitle_free(subtitle_to_free);

            subtitle_to_free = NULL;

        }

        av_freep(&decoded_frame);

        if (ret < 0)

            return ret;

    }

 discard_packet:

    return 0;

}


static void gen_tlbsx_440(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    t0 = tcg_temp_new();

    gen_addr_reg_index(ctx, t0);

    gen_helper_440_tlbsx(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);

    tcg_temp_free(t0);

    if (Rc(ctx->opcode)) {

        int l1 = gen_new_label();

        tcg_gen_trunc_tl_i32(cpu_crf[0], cpu_so);

        tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_gpr[rD(ctx->opcode)], -1, l1);

        tcg_gen_ori_i32(cpu_crf[0], cpu_crf[0], 0x02);

        gen_set_label(l1);

    }

#endif

}


GSource *iohandler_get_g_source(void)

{

    iohandler_init();

    return aio_get_g_source(iohandler_ctx);

}


int ff_mpeg1_find_frame_end(ParseContext *pc, const uint8_t *buf, int buf_size)

{

    int i;

    uint32_t state= pc->state;

    /* EOF considered as end of frame */

    if (buf_size == 0)

        return 0;

/*

 0  frame start         -> 1/4

 1  first_SEQEXT        -> 0/2

 2  first field start   -> 3/0

 3  second_SEQEXT       -> 2/0

 4  searching end

*/

    for(i=0; i<buf_size; i++){

        assert(pc->frame_start_found>=0 && pc->frame_start_found<=4);

        if(pc->frame_start_found&1){

            if(state == EXT_START_CODE && (buf[i]&0xF0) != 0x80)

                pc->frame_start_found--;

            else if(state == EXT_START_CODE+2){

                if((buf[i]&3) == 3) pc->frame_start_found= 0;

                else                pc->frame_start_found= (pc->frame_start_found+1)&3;

            }

            state++;

        }else{

            i= ff_find_start_code(buf+i, buf+buf_size, &state) - buf - 1;

            if(pc->frame_start_found==0 && state >= SLICE_MIN_START_CODE && state <= SLICE_MAX_START_CODE){

                i++;

                pc->frame_start_found=4;

            }

            if(state == SEQ_END_CODE){

                pc->state=-1;

                return i+1;

            }

            if(pc->frame_start_found==2 && state == SEQ_START_CODE)

                pc->frame_start_found= 0;

            if(pc->frame_start_found<4 && state == EXT_START_CODE)

                pc->frame_start_found++;

            if(pc->frame_start_found == 4 && (state&0xFFFFFF00) == 0x100){

                if(state < SLICE_MIN_START_CODE || state > SLICE_MAX_START_CODE){

                    pc->frame_start_found=0;

                    pc->state=-1;

                    return i-3;

                }

            }

        }

    }

    pc->state= state;

    return END_NOT_FOUND;

}