print_insn_sparc (bfd_vma memaddr, disassemble_info *info)

{

  FILE *stream = info->stream;

  bfd_byte buffer[4];

  unsigned long insn;

  sparc_opcode_hash *op;

  /* Nonzero of opcode table has been initialized.  */

  static int opcodes_initialized = 0;

  /* bfd mach number of last call.  */

  static unsigned long current_mach = 0;

  bfd_vma (*getword) (const unsigned char *);

  if (!opcodes_initialized

      || info->mach != current_mach)

    {

      int i;

      current_arch_mask = compute_arch_mask (info->mach);

      if (!opcodes_initialized)

        sorted_opcodes =

          malloc (sparc_num_opcodes * sizeof (sparc_opcode *));

      /* Reset the sorted table so we can resort it.  */

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

        sorted_opcodes[i] = &sparc_opcodes[i];

      qsort ((char *) sorted_opcodes, sparc_num_opcodes,

             sizeof (sorted_opcodes[0]), compare_opcodes);

      build_hash_table (sorted_opcodes, opcode_hash_table, sparc_num_opcodes);

      current_mach = info->mach;

      opcodes_initialized = 1;

    }

  {

    int status =

      (*info->read_memory_func) (memaddr, buffer, sizeof (buffer), info);

    if (status != 0)

      {

        (*info->memory_error_func) (status, memaddr, info);

        return -1;

      }

  }

  /* On SPARClite variants such as DANlite (sparc86x), instructions

     are always big-endian even when the machine is in little-endian mode.  */

  if (info->endian == BFD_ENDIAN_BIG || info->mach == bfd_mach_sparc_sparclite)

    getword = bfd_getb32;

  else

    getword = bfd_getl32;

  insn = getword (buffer);

  info->insn_info_valid = 1;                    /* We do return this info.  */

  info->insn_type = dis_nonbranch;              /* Assume non branch insn.  */

  info->branch_delay_insns = 0;                 /* Assume no delay.  */

  info->target = 0;                             /* Assume no target known.  */

  for (op = opcode_hash_table[HASH_INSN (insn)]; op; op = op->next)

    {

      const sparc_opcode *opcode = op->opcode;

      /* If the insn isn't supported by the current architecture, skip it.  */

      if (! (opcode->architecture & current_arch_mask))

        continue;

      if ((opcode->match & insn) == opcode->match

          && (opcode->lose & insn) == 0)

        {

          /* Nonzero means that we have found an instruction which has

             the effect of adding or or'ing the imm13 field to rs1.  */

          int imm_added_to_rs1 = 0;

          int imm_ored_to_rs1 = 0;

          /* Nonzero means that we have found a plus sign in the args

             field of the opcode table.  */

          int found_plus = 0;

          /* Nonzero means we have an annulled branch.  */

          /* int is_annulled = 0; */ /* see FIXME below */

          /* Do we have an `add' or `or' instruction combining an

             immediate with rs1?  */

          if (opcode->match == 0x80102000) /* or */

            imm_ored_to_rs1 = 1;

          if (opcode->match == 0x80002000) /* add */

            imm_added_to_rs1 = 1;

          if (X_RS1 (insn) != X_RD (insn)

              && strchr (opcode->args, 'r') != NULL)

              /* Can't do simple format if source and dest are different.  */

              continue;

          if (X_RS2 (insn) != X_RD (insn)

              && strchr (opcode->args, 'O') != NULL)

              /* Can't do simple format if source and dest are different.  */

              continue;

          (*info->fprintf_func) (stream, "%s", opcode->name);

          {

            const char *s;

            if (opcode->args[0] != ',')

              (*info->fprintf_func) (stream, " ");

            for (s = opcode->args; *s != '\0'; ++s)

              {

                while (*s == ',')

                  {

                    (*info->fprintf_func) (stream, ",");

                    ++s;

                    switch (*s)

                      {

                      case 'a':

                        (*info->fprintf_func) (stream, "a");

                        /* is_annulled = 1; */ /* see FIXME below */

                        ++s;

                        continue;

                      case 'N':

                        (*info->fprintf_func) (stream, "pn");

                        ++s;

                        continue;

                      case 'T':

                        (*info->fprintf_func) (stream, "pt");

                        ++s;

                        continue;

                      default:

                        break;

                      }

                  }

                (*info->fprintf_func) (stream, " ");

                switch (*s)

                  {

                  case '+':

                    found_plus = 1;

                    /* Fall through.  */

                  default:

                    (*info->fprintf_func) (stream, "%c", *s);

                    break;

                  case '#':

                    (*info->fprintf_func) (stream, "0");

                    break;

#define reg(n)  (*info->fprintf_func) (stream, "%%%s", reg_names[n])

                  case '1':

                  case 'r':

                    reg (X_RS1 (insn));

                    break;

                  case '2':

                  case 'O':

                    reg (X_RS2 (insn));

                    break;

                  case 'd':

                    reg (X_RD (insn));

                    break;

#undef  reg

#define freg(n)         (*info->fprintf_func) (stream, "%%%s", freg_names[n])

#define fregx(n)        (*info->fprintf_func) (stream, "%%%s", freg_names[((n) & ~1) | (((n) & 1) << 5)])

                  case 'e':

                    freg (X_RS1 (insn));

                    break;

                  case 'v':     /* Double/even.  */

                  case 'V':     /* Quad/multiple of 4.  */

                    fregx (X_RS1 (insn));

                    break;

                  case 'f':

                    freg (X_RS2 (insn));

                    break;

                  case 'B':     /* Double/even.  */

                  case 'R':     /* Quad/multiple of 4.  */

                    fregx (X_RS2 (insn));

                    break;

                  case 'g':

                    freg (X_RD (insn));

                    break;

                  case 'H':     /* Double/even.  */

                  case 'J':     /* Quad/multiple of 4.  */

                    fregx (X_RD (insn));

                    break;

#undef  freg

#undef  fregx

#define creg(n) (*info->fprintf_func) (stream, "%%c%u", (unsigned int) (n))

                  case 'b':

                    creg (X_RS1 (insn));

                    break;

                  case 'c':

                    creg (X_RS2 (insn));

                    break;

                  case 'D':

                    creg (X_RD (insn));

                    break;

#undef  creg

                  case 'h':

                    (*info->fprintf_func) (stream, "%%hi(%#x)",

                                           ((unsigned) 0xFFFFFFFF

                                            & ((int) X_IMM22 (insn) << 10)));

                    break;

                  case 'i':     /* 13 bit immediate.  */

                  case 'I':     /* 11 bit immediate.  */

                  case 'j':     /* 10 bit immediate.  */

                    {

                      int imm;

                      if (*s == 'i')

                        imm = X_SIMM (insn, 13);

                      else if (*s == 'I')

                        imm = X_SIMM (insn, 11);

                      else

                        imm = X_SIMM (insn, 10);

                      /* Check to see whether we have a 1+i, and take

                         note of that fact.

                         Note: because of the way we sort the table,

                         we will be matching 1+i rather than i+1,

                         so it is OK to assume that i is after +,

                         not before it.  */

                      if (found_plus)

                        imm_added_to_rs1 = 1;

                      if (imm <= 9)

                        (*info->fprintf_func) (stream, "%d", imm);

                      else

                        (*info->fprintf_func) (stream, "%#x", imm);

                    }

                    break;

                  case 'X':     /* 5 bit unsigned immediate.  */

                  case 'Y':     /* 6 bit unsigned immediate.  */

                    {

                      int imm = X_IMM (insn, *s == 'X' ? 5 : 6);

                      if (imm <= 9)

                        (info->fprintf_func) (stream, "%d", imm);

                      else

                        (info->fprintf_func) (stream, "%#x", (unsigned) imm);

                    }

                    break;

                  case '3':

                    (info->fprintf_func) (stream, "%ld", X_IMM (insn, 3));

                    break;

                  case 'K':

                    {

                      int mask = X_MEMBAR (insn);

                      int bit = 0x40, printed_one = 0;

                      const char *name;

                      if (mask == 0)

                        (info->fprintf_func) (stream, "0");

                      else

                        while (bit)

                          {

                            if (mask & bit)

                              {

                                if (printed_one)

                                  (info->fprintf_func) (stream, "|");

                                name = sparc_decode_membar (bit);

                                (info->fprintf_func) (stream, "%s", name);

                                printed_one = 1;

                              }

                            bit >>= 1;

                          }

                      break;

                    }

                  case 'k':

                    info->target = memaddr + SEX (X_DISP16 (insn), 16) * 4;

                    (*info->print_address_func) (info->target, info);

                    break;

                  case 'G':

                    info->target = memaddr + SEX (X_DISP19 (insn), 19) * 4;

                    (*info->print_address_func) (info->target, info);

                    break;

                  case '6':

                  case '7':

                  case '8':

                  case '9':

                    (*info->fprintf_func) (stream, "%%fcc%c", *s - '6' + '0');

                    break;

                  case 'z':

                    (*info->fprintf_func) (stream, "%%icc");

                    break;

                  case 'Z':

                    (*info->fprintf_func) (stream, "%%xcc");

                    break;

                  case 'E':

                    (*info->fprintf_func) (stream, "%%ccr");

                    break;

                  case 's':

                    (*info->fprintf_func) (stream, "%%fprs");

                    break;

                  case 'o':

                    (*info->fprintf_func) (stream, "%%asi");

                    break;

                  case 'W':

                    (*info->fprintf_func) (stream, "%%tick");

                    break;

                  case 'P':

                    (*info->fprintf_func) (stream, "%%pc");

                    break;

                  case '?':

                    if (X_RS1 (insn) == 31)

                      (*info->fprintf_func) (stream, "%%ver");

                    else if ((unsigned) X_RS1 (insn) < 17)

                      (*info->fprintf_func) (stream, "%%%s",

                                             v9_priv_reg_names[X_RS1 (insn)]);

                    else

                      (*info->fprintf_func) (stream, "%%reserved");

                    break;

                  case '!':

                    if ((unsigned) X_RD (insn) < 17)

                      (*info->fprintf_func) (stream, "%%%s",

                                             v9_priv_reg_names[X_RD (insn)]);

                    else

                      (*info->fprintf_func) (stream, "%%reserved");

                    break;

                  case '$':

                    if ((unsigned) X_RS1 (insn) < 32)

                      (*info->fprintf_func) (stream, "%%%s",

                                             v9_hpriv_reg_names[X_RS1 (insn)]);

                    else

                      (*info->fprintf_func) (stream, "%%reserved");

                    break;

                  case '%':

                    if ((unsigned) X_RD (insn) < 32)

                      (*info->fprintf_func) (stream, "%%%s",

                                             v9_hpriv_reg_names[X_RD (insn)]);

                    else

                      (*info->fprintf_func) (stream, "%%reserved");

                    break;

                  case '/':

                    if (X_RS1 (insn) < 16 || X_RS1 (insn) > 25)

                      (*info->fprintf_func) (stream, "%%reserved");

                    else

                      (*info->fprintf_func) (stream, "%%%s",

                                             v9a_asr_reg_names[X_RS1 (insn)-16]);

                    break;

                  case '_':

                    if (X_RD (insn) < 16 || X_RD (insn) > 25)

                      (*info->fprintf_func) (stream, "%%reserved");

                    else

                      (*info->fprintf_func) (stream, "%%%s",

                                             v9a_asr_reg_names[X_RD (insn)-16]);

                    break;

                  case '*':

                    {

                      const char *name = sparc_decode_prefetch (X_RD (insn));

                      if (name)

                        (*info->fprintf_func) (stream, "%s", name);

                      else

                        (*info->fprintf_func) (stream, "%ld", X_RD (insn));

                      break;

                    }

                  case 'M':

                    (*info->fprintf_func) (stream, "%%asr%ld", X_RS1 (insn));

                    break;

                  case 'm':

                    (*info->fprintf_func) (stream, "%%asr%ld", X_RD (insn));

                    break;

                  case 'L':

                    info->target = memaddr + SEX (X_DISP30 (insn), 30) * 4;

                    (*info->print_address_func) (info->target, info);

                    break;

                  case 'n':

                    (*info->fprintf_func)

                      (stream, "%#x", SEX (X_DISP22 (insn), 22));

                    break;

                  case 'l':

                    info->target = memaddr + SEX (X_DISP22 (insn), 22) * 4;

                    (*info->print_address_func) (info->target, info);

                    break;

                  case 'A':

                    {

                      const char *name;

                      if ((info->mach == bfd_mach_sparc_v8plusa) ||

                          ((info->mach >= bfd_mach_sparc_v9) &&

                           (info->mach <= bfd_mach_sparc_v9b)))

                        name = sparc_decode_asi_v9 (X_ASI (insn));

                      else

                        name = sparc_decode_asi_v8 (X_ASI (insn));

                      if (name)

                        (*info->fprintf_func) (stream, "%s", name);

                      else

                        (*info->fprintf_func) (stream, "(%ld)", X_ASI (insn));

                      break;

                    }

                  case 'C':

                    (*info->fprintf_func) (stream, "%%csr");

                    break;

                  case 'F':

                    (*info->fprintf_func) (stream, "%%fsr");

                    break;

                  case 'p':

                    (*info->fprintf_func) (stream, "%%psr");

                    break;

                  case 'q':

                    (*info->fprintf_func) (stream, "%%fq");

                    break;

                  case 'Q':

                    (*info->fprintf_func) (stream, "%%cq");

                    break;

                  case 't':

                    (*info->fprintf_func) (stream, "%%tbr");

                    break;

                  case 'w':

                    (*info->fprintf_func) (stream, "%%wim");

                    break;

                  case 'x':

                    (*info->fprintf_func) (stream, "%ld",

                                           ((X_LDST_I (insn) << 8)

                                            + X_ASI (insn)));

                    break;

                  case 'y':

                    (*info->fprintf_func) (stream, "%%y");

                    break;

                  case 'u':

                  case 'U':

                    {

                      int val = *s == 'U' ? X_RS1 (insn) : X_RD (insn);

                      const char *name = sparc_decode_sparclet_cpreg (val);

                      if (name)

                        (*info->fprintf_func) (stream, "%s", name);

                      else

                        (*info->fprintf_func) (stream, "%%cpreg(%d)", val);

                      break;

                    }

                  }

              }

          }

          /* If we are adding or or'ing something to rs1, then

             check to see whether the previous instruction was

             a sethi to the same register as in the sethi.

             If so, attempt to print the result of the add or

             or (in this context add and or do the same thing)

             and its symbolic value.  */

          if (imm_ored_to_rs1 || imm_added_to_rs1)

            {

              unsigned long prev_insn;

              int errcode;

              if (memaddr >= 4)

                errcode =

                  (*info->read_memory_func)

                  (memaddr - 4, buffer, sizeof (buffer), info);

              else

                errcode = 1;

              prev_insn = getword (buffer);

              if (errcode == 0)

                {

                  /* If it is a delayed branch, we need to look at the

                     instruction before the delayed branch.  This handles

                     sequences such as:

                     sethi %o1, %hi(_foo), %o1

                     call _printf

                     or %o1, %lo(_foo), %o1  */

                  if (is_delayed_branch (prev_insn))

                    {

                      if (memaddr >= 8)

                        errcode = (*info->read_memory_func)

                          (memaddr - 8, buffer, sizeof (buffer), info);

                      else

                        errcode = 1;

                      prev_insn = getword (buffer);

                    }

                }

              /* If there was a problem reading memory, then assume

                 the previous instruction was not sethi.  */

              if (errcode == 0)

                {

                  /* Is it sethi to the same register?  */

                  if ((prev_insn & 0xc1c00000) == 0x01000000

                      && X_RD (prev_insn) == X_RS1 (insn))

                    {

                      (*info->fprintf_func) (stream, "\t! ");

                      info->target =

                        ((unsigned) 0xFFFFFFFF

                         & ((int) X_IMM22 (prev_insn) << 10));

                      if (imm_added_to_rs1)

                        info->target += X_SIMM (insn, 13);

                      else

                        info->target |= X_SIMM (insn, 13);

                      (*info->print_address_func) (info->target, info);

                      info->insn_type = dis_dref;

                      info->data_size = 4;  /* FIXME!!! */

                    }

                }

            }

          if (opcode->flags & (F_UNBR|F_CONDBR|F_JSR))

            {

                /* FIXME -- check is_annulled flag.  */

              if (opcode->flags & F_UNBR)

                info->insn_type = dis_branch;

              if (opcode->flags & F_CONDBR)

                info->insn_type = dis_condbranch;

              if (opcode->flags & F_JSR)

                info->insn_type = dis_jsr;

              if (opcode->flags & F_DELAYED)

                info->branch_delay_insns = 1;

            }

          return sizeof (buffer);

        }

    }

  info->insn_type = dis_noninsn;        /* Mark as non-valid instruction.  */

  (*info->fprintf_func) (stream, _("unknown"));

  return sizeof (buffer);

}


static int vmstate_subsection_load(QEMUFile *f, const VMStateDescription *vmsd,

                                   void *opaque)

{

    while (qemu_peek_byte(f, 0) == QEMU_VM_SUBSECTION) {

        char idstr[256];

        int ret;

        uint8_t version_id, len, size;

        const VMStateDescription *sub_vmsd;

        len = qemu_peek_byte(f, 1);

        if (len < strlen(vmsd->name) + 1) {

            /* subsection name has be be "section_name/a" */

            return 0;

        }

        size = qemu_peek_buffer(f, (uint8_t *)idstr, len, 2);

        if (size != len) {

            return 0;

        }

        idstr[size] = 0;

        if (strncmp(vmsd->name, idstr, strlen(vmsd->name)) != 0) {

            /* it don't have a valid subsection name */

            return 0;

        }

        sub_vmsd = vmstate_get_subsection(vmsd->subsections, idstr);

        if (sub_vmsd == NULL) {

            return -ENOENT;

        }

        qemu_file_skip(f, 1); /* subsection */

        qemu_file_skip(f, 1); /* len */

        qemu_file_skip(f, len); /* idstr */

        version_id = qemu_get_be32(f);

        ret = vmstate_load_state(f, sub_vmsd, opaque, version_id);

        if (ret) {

            return ret;

        }

    }

    return 0;

}


static int decode_update_thread_context(AVCodecContext *dst,

                                        const AVCodecContext *src)

{

    H264Context *h = dst->priv_data, *h1 = src->priv_data;

    int inited = h->context_initialized, err = 0;

    int context_reinitialized = 0;

    int i, ret;

    if (dst == src || !h1->context_initialized)

        return 0;

    if (inited &&

        (h->width                 != h1->width                 ||

         h->height                != h1->height                ||

         h->mb_width              != h1->mb_width              ||

         h->mb_height             != h1->mb_height             ||

         h->sps.bit_depth_luma    != h1->sps.bit_depth_luma    ||

         h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||

         h->sps.colorspace        != h1->sps.colorspace)) {

        /* set bits_per_raw_sample to the previous value. the check for changed

         * bit depth in h264_set_parameter_from_sps() uses it and sets it to

         * the current value */

        h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;

        av_freep(&h->bipred_scratchpad);

        h->width     = h1->width;

        h->height    = h1->height;

        h->mb_height = h1->mb_height;

        h->mb_width  = h1->mb_width;

        h->mb_num    = h1->mb_num;

        h->mb_stride = h1->mb_stride;

        h->b_stride  = h1->b_stride;

        if ((err = h264_slice_header_init(h, 1)) < 0) {

            av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");

            return err;

        }

        context_reinitialized = 1;

        /* update linesize on resize. The decoder doesn't

         * necessarily call h264_frame_start in the new thread */

        h->linesize   = h1->linesize;

        h->uvlinesize = h1->uvlinesize;

        /* copy block_offset since frame_start may not be called */

        memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));

    }

    if (!inited) {

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

            av_freep(h->sps_buffers + i);

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

            av_freep(h->pps_buffers + i);

        memcpy(h, h1, sizeof(*h1));

        memset(h->sps_buffers, 0, sizeof(h->sps_buffers));

        memset(h->pps_buffers, 0, sizeof(h->pps_buffers));

        memset(&h->er, 0, sizeof(h->er));

        memset(&h->me, 0, sizeof(h->me));

        memset(&h->mb, 0, sizeof(h->mb));

        memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));

        memset(&h->mb_padding, 0, sizeof(h->mb_padding));

        h->context_initialized = 0;

        memset(&h->cur_pic, 0, sizeof(h->cur_pic));

        avcodec_get_frame_defaults(&h->cur_pic.f);

        h->cur_pic.tf.f = &h->cur_pic.f;

        h->avctx             = dst;

        h->DPB               = NULL;

        h->qscale_table_pool = NULL;

        h->mb_type_pool      = NULL;

        h->ref_index_pool    = NULL;

        h->motion_val_pool   = NULL;

        ret = ff_h264_alloc_tables(h);

        if (ret < 0) {

            av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");

            return ret;

        }

        ret = context_init(h);

        if (ret < 0) {

            av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");

            return ret;

        }

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

            h->rbsp_buffer[i]      = NULL;

            h->rbsp_buffer_size[i] = 0;

        }

        h->bipred_scratchpad = NULL;

        h->edge_emu_buffer   = NULL;

        h->thread_context[0] = h;

        h->context_initialized = 1;

    }

    h->avctx->coded_height  = h1->avctx->coded_height;

    h->avctx->coded_width   = h1->avctx->coded_width;

    h->avctx->width         = h1->avctx->width;

    h->avctx->height        = h1->avctx->height;

    h->coded_picture_number = h1->coded_picture_number;

    h->first_field          = h1->first_field;

    h->picture_structure    = h1->picture_structure;

    h->qscale               = h1->qscale;

    h->droppable            = h1->droppable;

    h->data_partitioning    = h1->data_partitioning;

    h->low_delay            = h1->low_delay;

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

        unref_picture(h, &h->DPB[i]);

        if (h1->DPB[i].f.data[0] &&

            (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)

            return ret;

    }

    h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);

    unref_picture(h, &h->cur_pic);

    if ((ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)

        return ret;

    h->workaround_bugs = h1->workaround_bugs;

    h->low_delay       = h1->low_delay;

    h->droppable       = h1->droppable;

    /* frame_start may not be called for the next thread (if it's decoding

     * a bottom field) so this has to be allocated here */

    err = alloc_scratch_buffers(h, h1->linesize);

    if (err < 0)

        return err;

    // extradata/NAL handling

    h->is_avc = h1->is_avc;

    // SPS/PPS

    if ((ret = copy_parameter_set((void **)h->sps_buffers,

                                  (void **)h1->sps_buffers,

                                  MAX_SPS_COUNT, sizeof(SPS))) < 0)

        return ret;

    h->sps = h1->sps;

    if ((ret = copy_parameter_set((void **)h->pps_buffers,

                                  (void **)h1->pps_buffers,

                                  MAX_PPS_COUNT, sizeof(PPS))) < 0)

        return ret;

    h->pps = h1->pps;

    // Dequantization matrices

    // FIXME these are big - can they be only copied when PPS changes?

    copy_fields(h, h1, dequant4_buffer, dequant4_coeff);

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

        h->dequant4_coeff[i] = h->dequant4_buffer[0] +

                               (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);

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

        h->dequant8_coeff[i] = h->dequant8_buffer[0] +

                               (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);

    h->dequant_coeff_pps = h1->dequant_coeff_pps;

    // POC timing

    copy_fields(h, h1, poc_lsb, redundant_pic_count);

    // reference lists

    copy_fields(h, h1, short_ref, cabac_init_idc);

    copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);

    copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);

    copy_picture_range(h->delayed_pic, h1->delayed_pic,

                       MAX_DELAYED_PIC_COUNT + 2, h, h1);

    h->last_slice_type = h1->last_slice_type;

    if (context_reinitialized)

        h264_set_parameter_from_sps(h);

    if (!h->cur_pic_ptr)

        return 0;

    if (!h->droppable) {

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

        h->prev_poc_msb = h->poc_msb;

        h->prev_poc_lsb = h->poc_lsb;

    }

    h->prev_frame_num_offset = h->frame_num_offset;

    h->prev_frame_num        = h->frame_num;

    h->outputed_poc          = h->next_outputed_poc;

    h->recovery_frame        = h1->recovery_frame;

    h->frame_recovered       = h1->frame_recovered;

    return err;

}


static av_cold void sws_init_swscale(SwsContext *c)

{

    enum AVPixelFormat srcFormat = c->srcFormat;

    ff_sws_init_output_funcs(c, &c->yuv2plane1, &c->yuv2planeX,

                             &c->yuv2nv12cX, &c->yuv2packed1,

                             &c->yuv2packed2, &c->yuv2packedX, &c->yuv2anyX);

    ff_sws_init_input_funcs(c);

    if (c->srcBpc == 8) {

        if (c->dstBpc <= 10) {

            c->hyScale = c->hcScale = hScale8To15_c;

            if (c->flags & SWS_FAST_BILINEAR) {

                c->hyscale_fast = hyscale_fast_c;

                c->hcscale_fast = hcscale_fast_c;

            }

        } else {

            c->hyScale = c->hcScale = hScale8To19_c;

        }

    } else {

        c->hyScale = c->hcScale = c->dstBpc > 10 ? hScale16To19_c

                                                 : hScale16To15_c;

    }

    if (c->srcRange != c->dstRange && !isAnyRGB(c->dstFormat)) {

        if (c->dstBpc <= 10) {

            if (c->srcRange) {

                c->lumConvertRange = lumRangeFromJpeg_c;

                c->chrConvertRange = chrRangeFromJpeg_c;

            } else {

                c->lumConvertRange = lumRangeToJpeg_c;

                c->chrConvertRange = chrRangeToJpeg_c;

            }

        } else {

            if (c->srcRange) {

                c->lumConvertRange = lumRangeFromJpeg16_c;

                c->chrConvertRange = chrRangeFromJpeg16_c;

            } else {

                c->lumConvertRange = lumRangeToJpeg16_c;

                c->chrConvertRange = chrRangeToJpeg16_c;

            }

        }

    }

    if (!(isGray(srcFormat) || isGray(c->dstFormat) ||

          srcFormat == AV_PIX_FMT_MONOBLACK || srcFormat == AV_PIX_FMT_MONOWHITE))

        c->needs_hcscale = 1;

}


static target_ulong h_enter(PowerPCCPU *cpu, sPAPRMachineState *spapr,

                            target_ulong opcode, target_ulong *args)

{

    CPUPPCState *env = &cpu->env;

    target_ulong flags = args[0];

    target_ulong pte_index = args[1];

    target_ulong pteh = args[2];

    target_ulong ptel = args[3];

    unsigned apshift, spshift;

    target_ulong raddr;

    target_ulong index;

    uint64_t token;

    apshift = ppc_hash64_hpte_page_shift_noslb(cpu, pteh, ptel, &spshift);

    if (!apshift) {

        /* Bad page size encoding */

        return H_PARAMETER;

    }

    raddr = (ptel & HPTE64_R_RPN) & ~((1ULL << apshift) - 1);

    if (is_ram_address(spapr, raddr)) {

        /* Regular RAM - should have WIMG=0010 */

        if ((ptel & HPTE64_R_WIMG) != HPTE64_R_M) {

            return H_PARAMETER;

        }

    } else {

        /* Looks like an IO address */

        /* FIXME: What WIMG combinations could be sensible for IO?

         * For now we allow WIMG=010x, but are there others? */

        /* FIXME: Should we check against registered IO addresses? */

        if ((ptel & (HPTE64_R_W | HPTE64_R_I | HPTE64_R_M)) != HPTE64_R_I) {

            return H_PARAMETER;

        }

    }

    pteh &= ~0x60ULL;

    if (!valid_pte_index(env, pte_index)) {

        return H_PARAMETER;

    }

    index = 0;

    if (likely((flags & H_EXACT) == 0)) {

        pte_index &= ~7ULL;

        token = ppc_hash64_start_access(cpu, pte_index);

        for (; index < 8; index++) {

            if (!(ppc_hash64_load_hpte0(cpu, token, index) & HPTE64_V_VALID)) {

                break;

            }

        }

        ppc_hash64_stop_access(cpu, token);

        if (index == 8) {

            return H_PTEG_FULL;

        }

    } else {

        token = ppc_hash64_start_access(cpu, pte_index);

        if (ppc_hash64_load_hpte0(cpu, token, 0) & HPTE64_V_VALID) {

            ppc_hash64_stop_access(cpu, token);

            return H_PTEG_FULL;

        }

        ppc_hash64_stop_access(cpu, token);

    }

    ppc_hash64_store_hpte(cpu, pte_index + index,

                          pteh | HPTE64_V_HPTE_DIRTY, ptel);

    args[0] = pte_index + index;

    return H_SUCCESS;

}


static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)

{

    qemu_coroutine_enter(acb->coroutine, NULL);

    qemu_aio_unref(acb);

}


static void vp9_superframe_close(AVBSFContext *ctx)

{

    VP9BSFContext *s = ctx->priv_data;

    int n;

    // free cached data

    for (n = 0; n < s->n_cache; n++)

        av_packet_free(&s->cache[n]);

}


static int decode_i_frame(FourXContext *f, AVFrame *frame, const uint8_t *buf, int length)

{

    int x, y, ret;

    const int width  = f->avctx->width;

    const int height = f->avctx->height;

    const unsigned int bitstream_size = AV_RL32(buf);

    int token_count av_unused;

    unsigned int prestream_size;

    const uint8_t *prestream;

    if (length < bitstream_size + 12) {

        av_log(f->avctx, AV_LOG_ERROR, "packet size too small\n");

        return AVERROR_INVALIDDATA;

    }

    token_count    =     AV_RL32(buf + bitstream_size + 8);

    prestream_size = 4 * AV_RL32(buf + bitstream_size + 4);

    prestream      =             buf + bitstream_size + 12;

    if (prestream_size + bitstream_size + 12 != length

        || bitstream_size > (1 << 26)

        || prestream_size > (1 << 26)) {

        av_log(f->avctx, AV_LOG_ERROR, "size mismatch %d %d %d\n",

               prestream_size, bitstream_size, length);

        return AVERROR_INVALIDDATA;

    }

    prestream = read_huffman_tables(f, prestream, prestream_size);

    if (!prestream) {

        av_log(f->avctx, AV_LOG_ERROR, "Error reading Huffman tables.\n");

        return AVERROR_INVALIDDATA;

    }

    init_get_bits(&f->gb, buf + 4, 8 * bitstream_size);

    prestream_size = length + buf - prestream;

    av_fast_malloc(&f->bitstream_buffer, &f->bitstream_buffer_size,

                   prestream_size + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!f->bitstream_buffer)

        return AVERROR(ENOMEM);

    f->dsp.bswap_buf(f->bitstream_buffer, (const uint32_t*)prestream,

                     prestream_size / 4);

    memset((uint8_t*)f->bitstream_buffer + prestream_size,

           0, FF_INPUT_BUFFER_PADDING_SIZE);

    init_get_bits(&f->pre_gb, f->bitstream_buffer, 8 * prestream_size);

    f->last_dc = 0 * 128 * 8 * 8;

    for (y = 0; y < height; y += 16) {

        for (x = 0; x < width; x += 16) {

            if ((ret = decode_i_mb(f)) < 0)

                return ret;

            idct_put(f, frame, x, y);

        }

    }

    if (get_vlc2(&f->pre_gb, f->pre_vlc.table, ACDC_VLC_BITS, 3) != 256)

        av_log(f->avctx, AV_LOG_ERROR, "end mismatch\n");

    return 0;

}


void virtio_scsi_exit(VirtIODevice *vdev)

{

    virtio_cleanup(vdev);

}


static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                            const AVFrame *frame, int *got_packet_ptr)

{

    AACEncContext *s = avctx->priv_data;

    float **samples = s->planar_samples, *samples2, *la, *overlap;

    ChannelElement *cpe;

    SingleChannelElement *sce;

    int i, its, ch, w, chans, tag, start_ch, ret, frame_bits;

    int ms_mode = 0, is_mode = 0, tns_mode = 0, pred_mode = 0;

    int chan_el_counter[4];

    FFPsyWindowInfo windows[AAC_MAX_CHANNELS];

    if (s->last_frame == 2)

        return 0;

    /* add current frame to queue */

    if (frame) {

        if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)

            return ret;

    }

    copy_input_samples(s, frame);

    if (s->psypp)

        ff_psy_preprocess(s->psypp, s->planar_samples, s->channels);

    if (!avctx->frame_number)

        return 0;

    start_ch = 0;

    for (i = 0; i < s->chan_map[0]; i++) {

        FFPsyWindowInfo* wi = windows + start_ch;

        tag      = s->chan_map[i+1];

        chans    = tag == TYPE_CPE ? 2 : 1;

        cpe      = &s->cpe[i];

        for (ch = 0; ch < chans; ch++) {

            IndividualChannelStream *ics = &cpe->ch[ch].ics;

            int cur_channel = start_ch + ch;

            float clip_avoidance_factor;

            overlap  = &samples[cur_channel][0];

            samples2 = overlap + 1024;

            la       = samples2 + (448+64);

            if (!frame)

                la = NULL;

            if (tag == TYPE_LFE) {

                wi[ch].window_type[0] = ONLY_LONG_SEQUENCE;

                wi[ch].window_shape   = 0;

                wi[ch].num_windows    = 1;

                wi[ch].grouping[0]    = 1;

                /* Only the lowest 12 coefficients are used in a LFE channel.

                 * The expression below results in only the bottom 8 coefficients

                 * being used for 11.025kHz to 16kHz sample rates.

                 */

                ics->num_swb = s->samplerate_index >= 8 ? 1 : 3;

            } else {

                wi[ch] = s->psy.model->window(&s->psy, samples2, la, cur_channel,

                                              ics->window_sequence[0]);

            }

            ics->window_sequence[1] = ics->window_sequence[0];

            ics->window_sequence[0] = wi[ch].window_type[0];

            ics->use_kb_window[1]   = ics->use_kb_window[0];

            ics->use_kb_window[0]   = wi[ch].window_shape;

            ics->num_windows        = wi[ch].num_windows;

            ics->swb_sizes          = s->psy.bands    [ics->num_windows == 8];

            ics->num_swb            = tag == TYPE_LFE ? ics->num_swb : s->psy.num_bands[ics->num_windows == 8];

            ics->swb_offset         = wi[ch].window_type[0] == EIGHT_SHORT_SEQUENCE ?

                                        ff_swb_offset_128 [s->samplerate_index]:

                                        ff_swb_offset_1024[s->samplerate_index];

            ics->tns_max_bands      = wi[ch].window_type[0] == EIGHT_SHORT_SEQUENCE ?

                                        ff_tns_max_bands_128 [s->samplerate_index]:

                                        ff_tns_max_bands_1024[s->samplerate_index];

            clip_avoidance_factor = 0.0f;

            for (w = 0; w < ics->num_windows; w++)

                ics->group_len[w] = wi[ch].grouping[w];

            for (w = 0; w < ics->num_windows; w++) {

                if (wi[ch].clipping[w] > CLIP_AVOIDANCE_FACTOR) {

                    ics->window_clipping[w] = 1;

                    clip_avoidance_factor = FFMAX(clip_avoidance_factor, wi[ch].clipping[w]);

                } else {

                    ics->window_clipping[w] = 0;

                }

            }

            if (clip_avoidance_factor > CLIP_AVOIDANCE_FACTOR) {

                ics->clip_avoidance_factor = CLIP_AVOIDANCE_FACTOR / clip_avoidance_factor;

            } else {

                ics->clip_avoidance_factor = 1.0f;

            }

            apply_window_and_mdct(s, &cpe->ch[ch], overlap);

            if (isnan(cpe->ch->coeffs[0])) {

                av_log(avctx, AV_LOG_ERROR, "Input contains NaN\n");

                return AVERROR(EINVAL);

            }

            avoid_clipping(s, &cpe->ch[ch]);

        }

        start_ch += chans;

    }

    if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels, 0)) < 0)

        return ret;

    frame_bits = its = 0;

    do {

        int target_bits, too_many_bits, too_few_bits;

        init_put_bits(&s->pb, avpkt->data, avpkt->size);

        if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & AV_CODEC_FLAG_BITEXACT))

            put_bitstream_info(s, LIBAVCODEC_IDENT);

        start_ch = 0;

        target_bits = 0;

        memset(chan_el_counter, 0, sizeof(chan_el_counter));

        for (i = 0; i < s->chan_map[0]; i++) {

            FFPsyWindowInfo* wi = windows + start_ch;

            const float *coeffs[2];

            tag      = s->chan_map[i+1];

            chans    = tag == TYPE_CPE ? 2 : 1;

            cpe      = &s->cpe[i];

            cpe->common_window = 0;

            memset(cpe->is_mask, 0, sizeof(cpe->is_mask));

            memset(cpe->ms_mask, 0, sizeof(cpe->ms_mask));

            put_bits(&s->pb, 3, tag);

            put_bits(&s->pb, 4, chan_el_counter[tag]++);

            for (ch = 0; ch < chans; ch++) {

                sce = &cpe->ch[ch];

                coeffs[ch] = sce->coeffs;

                sce->ics.predictor_present = 0;

                memset(&sce->ics.prediction_used, 0, sizeof(sce->ics.prediction_used));

                memset(&sce->tns, 0, sizeof(TemporalNoiseShaping));

                for (w = 0; w < 128; w++)

                    if (sce->band_type[w] > RESERVED_BT)

                        sce->band_type[w] = 0;

            }

            s->psy.bitres.alloc = -1;

            s->psy.bitres.bits = avctx->frame_bits / s->channels;

            s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);

            if (s->psy.bitres.alloc > 0) {

                /* Lambda unused here on purpose, we need to take psy's unscaled allocation */

                target_bits += s->psy.bitres.alloc;

                s->psy.bitres.alloc /= chans;

            }

            s->cur_type = tag;

            for (ch = 0; ch < chans; ch++) {

                s->cur_channel = start_ch + ch;

                s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);

            }

            if (chans > 1

                && wi[0].window_type[0] == wi[1].window_type[0]

                && wi[0].window_shape   == wi[1].window_shape) {

                cpe->common_window = 1;

                for (w = 0; w < wi[0].num_windows; w++) {

                    if (wi[0].grouping[w] != wi[1].grouping[w]) {

                        cpe->common_window = 0;

                        break;

                    }

                }

            }

            for (ch = 0; ch < chans; ch++) { /* TNS and PNS */

                sce = &cpe->ch[ch];

                s->cur_channel = start_ch + ch;

                if (s->options.pns && s->coder->search_for_pns)

                    s->coder->search_for_pns(s, avctx, sce);

                if (s->options.tns && s->coder->search_for_tns)

                    s->coder->search_for_tns(s, sce);

                if (s->options.tns && s->coder->apply_tns_filt)

                    s->coder->apply_tns_filt(s, sce);

                if (sce->tns.present)

                    tns_mode = 1;

            }

            s->cur_channel = start_ch;

            if (s->options.intensity_stereo) { /* Intensity Stereo */

                if (s->coder->search_for_is)

                    s->coder->search_for_is(s, avctx, cpe);

                if (cpe->is_mode) is_mode = 1;

                apply_intensity_stereo(cpe);

            }

            if (s->options.pred) { /* Prediction */

                for (ch = 0; ch < chans; ch++) {

                    sce = &cpe->ch[ch];

                    s->cur_channel = start_ch + ch;

                    if (s->options.pred && s->coder->search_for_pred)

                        s->coder->search_for_pred(s, sce);

                    if (cpe->ch[ch].ics.predictor_present) pred_mode = 1;

                }

                if (s->coder->adjust_common_prediction)

                    s->coder->adjust_common_prediction(s, cpe);

                for (ch = 0; ch < chans; ch++) {

                    sce = &cpe->ch[ch];

                    s->cur_channel = start_ch + ch;

                    if (s->options.pred && s->coder->apply_main_pred)

                        s->coder->apply_main_pred(s, sce);

                }

                s->cur_channel = start_ch;

            }

            if (s->options.stereo_mode) { /* Mid/Side stereo */

                if (s->options.stereo_mode == -1 && s->coder->search_for_ms)

                    s->coder->search_for_ms(s, cpe);

                else if (cpe->common_window)

                    memset(cpe->ms_mask, 1, sizeof(cpe->ms_mask));

                for (w = 0; w < 128; w++)

                    cpe->ms_mask[w] = cpe->is_mask[w] ? 0 : cpe->ms_mask[w];

                apply_mid_side_stereo(cpe);

            }

            adjust_frame_information(cpe, chans);

            if (chans == 2) {

                put_bits(&s->pb, 1, cpe->common_window);

                if (cpe->common_window) {

                    put_ics_info(s, &cpe->ch[0].ics);

                    if (s->coder->encode_main_pred)

                        s->coder->encode_main_pred(s, &cpe->ch[0]);

                    encode_ms_info(&s->pb, cpe);

                    if (cpe->ms_mode) ms_mode = 1;

                }

            }

            for (ch = 0; ch < chans; ch++) {

                s->cur_channel = start_ch + ch;

                encode_individual_channel(avctx, s, &cpe->ch[ch], cpe->common_window);

            }

            start_ch += chans;

        }

        if (avctx->flags & CODEC_FLAG_QSCALE) {

            /* When using a constant Q-scale, don't mess with lambda */

            break;

        }

        /* rate control stuff

         * target either the nominal bitrate, or what psy's bit reservoir says to target

         * whichever is greatest

         */

        frame_bits = put_bits_count(&s->pb);

        target_bits = FFMAX(target_bits, avctx->bit_rate * 1024 / avctx->sample_rate);

        target_bits = FFMIN(target_bits, 6144 * s->channels - 3);

        /* When using ABR, be strict (but only for increasing) */

        too_many_bits = target_bits + target_bits/2;

        too_few_bits = target_bits - target_bits/8;

        if (   its == 0 /* for steady-state Q-scale tracking */

            || (its < 5 && (frame_bits < too_few_bits || frame_bits > too_many_bits))

            || frame_bits >= 6144 * s->channels - 3  )

        {

            float ratio = ((float)target_bits) / frame_bits;

            if (frame_bits >= too_few_bits && frame_bits <= too_many_bits) {

                /*

                 * This path is for steady-state Q-scale tracking

                 * When frame bits fall within the stable range, we still need to adjust

                 * lambda to maintain it like so in a stable fashion (large jumps in lambda

                 * create artifacts and should be avoided), but slowly

                 */

                ratio = sqrtf(sqrtf(ratio));

                ratio = av_clipf(ratio, 0.9f, 1.1f);

            } else {

                /* Not so fast though */

                ratio = sqrtf(ratio);

            }

            s->lambda = FFMIN(s->lambda * ratio, 65536.f);

            /* Keep iterating if we must reduce and lambda is in the sky */

            if (s->lambda < 300.f || ratio > 0.9f) {

                break;

            } else {

                if (is_mode || ms_mode || tns_mode || pred_mode) {

                    for (i = 0; i < s->chan_map[0]; i++) {

                        // Must restore coeffs

                        chans = tag == TYPE_CPE ? 2 : 1;

                        cpe = &s->cpe[i];

                        for (ch = 0; ch < chans; ch++)

                            memcpy(cpe->ch[ch].coeffs, cpe->ch[ch].pcoeffs, sizeof(cpe->ch[ch].coeffs));

                    }

                }

                its++;

            }

        } else {

            break;

        }

    } while (1);

    put_bits(&s->pb, 3, TYPE_END);

    flush_put_bits(&s->pb);

    avctx->frame_bits = put_bits_count(&s->pb);

    if (!frame)

        s->last_frame++;

    ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,

                       &avpkt->duration);

    avpkt->size = put_bits_count(&s->pb) >> 3;

    *got_packet_ptr = 1;

    return 0;

}


PCIDevice *pci_nic_init_nofail(NICInfo *nd, PCIBus *rootbus,

                               const char *default_model,

                               const char *default_devaddr)

{

    Error *err = NULL;

    PCIDevice *res;

    if (qemu_show_nic_models(nd->model, pci_nic_models))

        exit(0);

    res = pci_nic_init(nd, rootbus, default_model, default_devaddr, &err);

    if (!res) {

        error_report_err(err);

        exit(1);

    }

    return res;

}


static int decode_dsw1(uint8_t *frame, int width, int height,

                       const uint8_t *src, const uint8_t *src_end)

{

    const uint8_t *frame_start = frame;

    const uint8_t *frame_end   = frame + width * height;

    int mask = 0x10000, bitbuf = 0;

    int v, offset, count, segments;

    segments = bytestream_get_le16(&src);

    while (segments--) {

        if (mask == 0x10000) {

            if (src >= src_end)

                return -1;

            bitbuf = bytestream_get_le16(&src);

            mask = 1;

        }

        if (src_end - src < 2 || frame_end - frame < 2)

            return -1;

        if (bitbuf & mask) {

            v = bytestream_get_le16(&src);

            offset = (v & 0x1FFF) << 1;

            count = ((v >> 13) + 2) << 1;

            if (frame - offset < frame_start || frame_end - frame < count)

                return -1;

            // can't use av_memcpy_backptr() since it can overwrite following pixels

            for (v = 0; v < count; v++)

                frame[v] = frame[v - offset];

            frame += count;

        } else if (bitbuf & (mask << 1)) {

            frame += bytestream_get_le16(&src);

        } else {

            *frame++ = *src++;

            *frame++ = *src++;

        }

        mask <<= 2;

    }

    return 0;

}


static void draw_slice(HYuvContext *s, AVFrame *frame, int y)

{

    int h, cy, i;

    int offset[AV_NUM_DATA_POINTERS];

    if (s->avctx->draw_horiz_band == NULL)

        return;

    h  = y - s->last_slice_end;

    y -= h;

    if (s->bitstream_bpp == 12)

        cy = y >> 1;

    else

        cy = y;

    offset[0] = frame->linesize[0] * y;

    offset[1] = frame->linesize[1] * cy;

    offset[2] = frame->linesize[2] * cy;

    for (i = 3; i < AV_NUM_DATA_POINTERS; i++)

        offset[i] = 0;

    emms_c();

    s->avctx->draw_horiz_band(s->avctx, frame, offset, y, 3, h);

    s->last_slice_end = y + h;

}


static av_cold int asink_init(AVFilterContext *ctx, const char *args, void *opaque)

{

    BufferSinkContext *buf = ctx->priv;

    AVABufferSinkParams *params;

    if (!opaque) {

        av_log(ctx, AV_LOG_ERROR,

               "No opaque field provided, an AVABufferSinkParams struct is required\n");

        return AVERROR(EINVAL);

    } else

        params = (AVABufferSinkParams *)opaque;

    buf->sample_fmts     = params->sample_fmts;

    buf->channel_layouts = params->channel_layouts;

    buf->packing_fmts    = params->packing_fmts;

    return common_init(ctx);

}


void ff_vc1_mc_4mv_luma(VC1Context *v, int n, int dir, int avg)

{

    MpegEncContext *s = &v->s;

    uint8_t *srcY;

    int dxy, mx, my, src_x, src_y;

    int off;

    int fieldmv = (v->fcm == ILACE_FRAME) ? v->blk_mv_type[s->block_index[n]] : 0;

    int v_edge_pos = s->v_edge_pos >> v->field_mode;

    uint8_t (*luty)[256];

    int use_ic;

    if ((!v->field_mode ||

         (v->ref_field_type[dir] == 1 && v->cur_field_type == 1)) &&

        !v->s.last_picture.f->data[0])

        return;

    mx = s->mv[dir][n][0];

    my = s->mv[dir][n][1];

    if (!dir) {

        if (v->field_mode && (v->cur_field_type != v->ref_field_type[dir]) && v->second_field) {

            srcY = s->current_picture.f->data[0];

            luty = v->curr_luty;

            use_ic = v->curr_use_ic;

        } else {

            srcY = s->last_picture.f->data[0];

            luty = v->last_luty;

            use_ic = v->last_use_ic;

        }

    } else {

        srcY = s->next_picture.f->data[0];

        luty = v->next_luty;

        use_ic = v->next_use_ic;

    }

    if (!srcY) {

        av_log(v->s.avctx, AV_LOG_ERROR, "Referenced frame missing.\n");

        return;

    }

    if (v->field_mode) {

        if (v->cur_field_type != v->ref_field_type[dir])

            my = my - 2 + 4 * v->cur_field_type;

    }

    if (s->pict_type == AV_PICTURE_TYPE_P && n == 3 && v->field_mode) {

        int same_count = 0, opp_count = 0, k;

        int chosen_mv[2][4][2], f;

        int tx, ty;

        for (k = 0; k < 4; k++) {

            f = v->mv_f[0][s->block_index[k] + v->blocks_off];

            chosen_mv[f][f ? opp_count : same_count][0] = s->mv[0][k][0];

            chosen_mv[f][f ? opp_count : same_count][1] = s->mv[0][k][1];

            opp_count  += f;

            same_count += 1 - f;

        }

        f = opp_count > same_count;

        switch (f ? opp_count : same_count) {

        case 4:

            tx = median4(chosen_mv[f][0][0], chosen_mv[f][1][0],

                         chosen_mv[f][2][0], chosen_mv[f][3][0]);

            ty = median4(chosen_mv[f][0][1], chosen_mv[f][1][1],

                         chosen_mv[f][2][1], chosen_mv[f][3][1]);

            break;

        case 3:

            tx = mid_pred(chosen_mv[f][0][0], chosen_mv[f][1][0], chosen_mv[f][2][0]);

            ty = mid_pred(chosen_mv[f][0][1], chosen_mv[f][1][1], chosen_mv[f][2][1]);

            break;

        case 2:

            tx = (chosen_mv[f][0][0] + chosen_mv[f][1][0]) / 2;

            ty = (chosen_mv[f][0][1] + chosen_mv[f][1][1]) / 2;

            break;

        }

        s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][0] = tx;

        s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][1] = ty;

        for (k = 0; k < 4; k++)

            v->mv_f[1][s->block_index[k] + v->blocks_off] = f;

    }

    if (v->fcm == ILACE_FRAME) {  // not sure if needed for other types of picture

        int qx, qy;

        int width  = s->avctx->coded_width;

        int height = s->avctx->coded_height >> 1;

        if (s->pict_type == AV_PICTURE_TYPE_P) {

            s->current_picture.motion_val[1][s->block_index[n] + v->blocks_off][0] = mx;

            s->current_picture.motion_val[1][s->block_index[n] + v->blocks_off][1] = my;

        }

        qx = (s->mb_x * 16) + (mx >> 2);

        qy = (s->mb_y *  8) + (my >> 3);

        if (qx < -17)

            mx -= 4 * (qx + 17);

        else if (qx > width)

            mx -= 4 * (qx - width);

        if (qy < -18)

            my -= 8 * (qy + 18);

        else if (qy > height + 1)

            my -= 8 * (qy - height - 1);

    }

    if ((v->fcm == ILACE_FRAME) && fieldmv)

        off = ((n > 1) ? s->linesize : 0) + (n & 1) * 8;

    else

        off = s->linesize * 4 * (n & 2) + (n & 1) * 8;

    src_x = s->mb_x * 16 + (n & 1) * 8 + (mx >> 2);

    if (!fieldmv)

        src_y = s->mb_y * 16 + (n & 2) * 4 + (my >> 2);

    else

        src_y = s->mb_y * 16 + ((n > 1) ? 1 : 0) + (my >> 2);

    if (v->profile != PROFILE_ADVANCED) {

        src_x = av_clip(src_x, -16, s->mb_width  * 16);

        src_y = av_clip(src_y, -16, s->mb_height * 16);

    } else {

        src_x = av_clip(src_x, -17, s->avctx->coded_width);

        if (v->fcm == ILACE_FRAME) {

            if (src_y & 1)

                src_y = av_clip(src_y, -17, s->avctx->coded_height + 1);

            else

                src_y = av_clip(src_y, -18, s->avctx->coded_height);

        } else {

            src_y = av_clip(src_y, -18, s->avctx->coded_height + 1);

        }

    }

    srcY += src_y * s->linesize + src_x;

    if (v->field_mode && v->ref_field_type[dir])

        srcY += s->current_picture_ptr->f->linesize[0];

    if (fieldmv && !(src_y & 1))

        v_edge_pos--;

    if (fieldmv && (src_y & 1) && src_y < 4)

        src_y--;

    if (v->rangeredfrm || use_ic

        || s->h_edge_pos < 13 || v_edge_pos < 23

        || (unsigned)(src_x - s->mspel) > s->h_edge_pos - (mx & 3) - 8 - s->mspel * 2

        || (unsigned)(src_y - (s->mspel << fieldmv)) > v_edge_pos - (my & 3) - ((8 + s->mspel * 2) << fieldmv)) {

        srcY -= s->mspel * (1 + (s->linesize << fieldmv));

        /* check emulate edge stride and offset */

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer, srcY,

                                 s->linesize, s->linesize,

                                 9 + s->mspel * 2, (9 + s->mspel * 2) << fieldmv,

                                 src_x - s->mspel, src_y - (s->mspel << fieldmv),

                                 s->h_edge_pos, v_edge_pos);

        srcY = s->edge_emu_buffer;

        /* if we deal with range reduction we need to scale source blocks */

        if (v->rangeredfrm) {

            int i, j;

            uint8_t *src;

            src = srcY;

            for (j = 0; j < 9 + s->mspel * 2; j++) {

                for (i = 0; i < 9 + s->mspel * 2; i++)

                    src[i] = ((src[i] - 128) >> 1) + 128;

                src += s->linesize << fieldmv;

            }

        }

        /* if we deal with intensity compensation we need to scale source blocks */

        if (use_ic) {

            int i, j;

            uint8_t *src;

            src = srcY;

            for (j = 0; j < 9 + s->mspel * 2; j++) {

                int f = v->field_mode ? v->ref_field_type[dir] : (((j<<fieldmv)+src_y - (s->mspel << fieldmv)) & 1);

                for (i = 0; i < 9 + s->mspel * 2; i++)

                    src[i] = luty[f][src[i]];

                src += s->linesize << fieldmv;

            }

        }

        srcY += s->mspel * (1 + (s->linesize << fieldmv));

    }

    if (s->mspel) {

        dxy = ((my & 3) << 2) | (mx & 3);

        if (avg)

            v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + off, srcY, s->linesize << fieldmv, v->rnd);

        else

            v->vc1dsp.put_vc1_mspel_pixels_tab[dxy](s->dest[0] + off, srcY, s->linesize << fieldmv, v->rnd);

    } else { // hpel mc - always used for luma

        dxy = (my & 2) | ((mx & 2) >> 1);

        if (!v->rnd)

            s->hdsp.put_pixels_tab[1][dxy](s->dest[0] + off, srcY, s->linesize, 8);

        else

            s->hdsp.put_no_rnd_pixels_tab[1][dxy](s->dest[0] + off, srcY, s->linesize, 8);

    }

}


static int open_f(BlockBackend *blk, int argc, char **argv)

{

    int flags = BDRV_O_UNMAP;

    int readonly = 0;

    bool writethrough = true;

    int c;

    QemuOpts *qopts;

    QDict *opts;

    bool force_share = false;

    while ((c = getopt(argc, argv, "snro:kt:d:U")) != -1) {

        switch (c) {

        case 's':

            flags |= BDRV_O_SNAPSHOT;

            break;

        case 'n':

            flags |= BDRV_O_NOCACHE;

            writethrough = false;

            break;

        case 'r':

            readonly = 1;

            break;

        case 'k':

            flags |= BDRV_O_NATIVE_AIO;

            break;

        case 't':

            if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) < 0) {

                error_report("Invalid cache option: %s", optarg);

                qemu_opts_reset(&empty_opts);

                return 0;

            }

            break;

        case 'd':

            if (bdrv_parse_discard_flags(optarg, &flags) < 0) {

                error_report("Invalid discard option: %s", optarg);

                qemu_opts_reset(&empty_opts);

                return 0;

            }

            break;

        case 'o':

            if (imageOpts) {

                printf("--image-opts and 'open -o' are mutually exclusive\n");

                qemu_opts_reset(&empty_opts);

                return 0;

            }

            if (!qemu_opts_parse_noisily(&empty_opts, optarg, false)) {

                qemu_opts_reset(&empty_opts);

                return 0;

            }

            break;

        case 'U':

            force_share = true;

            break;

        default:

            qemu_opts_reset(&empty_opts);

            return qemuio_command_usage(&open_cmd);

        }

    }

    if (!readonly) {

        flags |= BDRV_O_RDWR;

    }

    if (imageOpts && (optind == argc - 1)) {

        if (!qemu_opts_parse_noisily(&empty_opts, argv[optind], false)) {

            qemu_opts_reset(&empty_opts);

            return 0;

        }

        optind++;

    }

    qopts = qemu_opts_find(&empty_opts, NULL);

    opts = qopts ? qemu_opts_to_qdict(qopts, NULL) : NULL;

    qemu_opts_reset(&empty_opts);

    if (optind == argc - 1) {

        return openfile(argv[optind], flags, writethrough, force_share, opts);

    } else if (optind == argc) {

        return openfile(NULL, flags, writethrough, force_share, opts);

    } else {

        QDECREF(opts);

        return qemuio_command_usage(&open_cmd);

    }

}


int vp78_decode_mb_row_sliced(AVCodecContext *avctx, void *tdata, int jobnr,

                              int threadnr, int is_vp7)

{

    VP8Context *s = avctx->priv_data;

    VP8ThreadData *td = &s->thread_data[jobnr];

    VP8ThreadData *next_td = NULL, *prev_td = NULL;

    VP8Frame *curframe = s->curframe;

    int mb_y, num_jobs = s->num_jobs;

    int ret;

    td->thread_nr = threadnr;

    for (mb_y = jobnr; mb_y < s->mb_height; mb_y += num_jobs) {

        atomic_store(&td->thread_mb_pos, mb_y << 16);

        ret = s->decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr);

        if (ret < 0) {

            update_pos(td, s->mb_height, INT_MAX & 0xFFFF);

            return ret;

        }

        if (s->deblock_filter)

            s->filter_mb_row(avctx, tdata, jobnr, threadnr);

        update_pos(td, mb_y, INT_MAX & 0xFFFF);

        s->mv_min.y -= 64;

        s->mv_max.y -= 64;

        if (avctx->active_thread_type == FF_THREAD_FRAME)

            ff_thread_report_progress(&curframe->tf, mb_y, 0);

    }

    return 0;

}


static void blkverify_aio_bh(void *opaque)

{

    BlkverifyAIOCB *acb = opaque;

    if (acb->buf) {

        qemu_iovec_destroy(&acb->raw_qiov);

        qemu_vfree(acb->buf);

    }

    acb->common.cb(acb->common.opaque, acb->ret);

    qemu_aio_unref(acb);

}


static void vhost_dev_sync_region(struct vhost_dev *dev,

                                  uint64_t mfirst, uint64_t mlast,

                                  uint64_t rfirst, uint64_t rlast)

{

    uint64_t start = MAX(mfirst, rfirst);

    uint64_t end = MIN(mlast, rlast);

    vhost_log_chunk_t *from = dev->log + start / VHOST_LOG_CHUNK;

    vhost_log_chunk_t *to = dev->log + end / VHOST_LOG_CHUNK + 1;

    uint64_t addr = (start / VHOST_LOG_CHUNK) * VHOST_LOG_CHUNK;

    assert(end / VHOST_LOG_CHUNK < dev->log_size);

    assert(start / VHOST_LOG_CHUNK < dev->log_size);

    if (end < start) {

        return;

    }

    for (;from < to; ++from) {

        vhost_log_chunk_t log;

        int bit;

        /* We first check with non-atomic: much cheaper,

         * and we expect non-dirty to be the common case. */

        if (!*from) {

            addr += VHOST_LOG_CHUNK;

            continue;

        }

        /* Data must be read atomically. We don't really

         * need the barrier semantics of __sync

         * builtins, but it's easier to use them than

         * roll our own. */

        log = __sync_fetch_and_and(from, 0);

        while ((bit = sizeof(log) > sizeof(int) ?

                ffsll(log) : ffs(log))) {

            bit -= 1;

            cpu_physical_memory_set_dirty(addr + bit * VHOST_LOG_PAGE);

            log &= ~(0x1ull << bit);

        }

        addr += VHOST_LOG_CHUNK;

    }

}


void hmp_chardev_add(Monitor *mon, const QDict *qdict)

{

    const char *args = qdict_get_str(qdict, "args");

    Error *err = NULL;

    QemuOpts *opts;

    opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"), args, true);

    if (opts == NULL) {

        error_setg(&err, "Parsing chardev args failed");

    } else {

        qemu_chr_new_from_opts(opts, NULL, &err);

    }

    hmp_handle_error(mon, &err);

}


void memory_mapping_filter(MemoryMappingList *list, int64_t begin,

                           int64_t length)

{

    MemoryMapping *cur, *next;

    QTAILQ_FOREACH_SAFE(cur, &list->head, next, next) {

        if (cur->phys_addr >= begin + length ||

            cur->phys_addr + cur->length <= begin) {

            QTAILQ_REMOVE(&list->head, cur, next);

            list->num--;

            continue;

        }

        if (cur->phys_addr < begin) {

            cur->length -= begin - cur->phys_addr;

            if (cur->virt_addr) {

                cur->virt_addr += begin - cur->phys_addr;

            }

            cur->phys_addr = begin;

        }

        if (cur->phys_addr + cur->length > begin + length) {

            cur->length -= cur->phys_addr + cur->length - begin - length;

        }

    }

}


static int Rgb16ToPlanarRgb16Wrapper(SwsContext *c, const uint8_t *src[],

                                     int srcStride[], int srcSliceY, int srcSliceH,

                                     uint8_t *dst[], int dstStride[])

{

    uint16_t *dst2013[] = { (uint16_t *)dst[2], (uint16_t *)dst[0], (uint16_t *)dst[1], (uint16_t *)dst[3] };

    uint16_t *dst1023[] = { (uint16_t *)dst[1], (uint16_t *)dst[0], (uint16_t *)dst[2], (uint16_t *)dst[3] };

    int stride2013[] = { dstStride[2], dstStride[0], dstStride[1], dstStride[3] };

    int stride1023[] = { dstStride[1], dstStride[0], dstStride[2], dstStride[3] };

    const AVPixFmtDescriptor *src_format = av_pix_fmt_desc_get(c->srcFormat);

    const AVPixFmtDescriptor *dst_format = av_pix_fmt_desc_get(c->dstFormat);

    int bpc = dst_format->comp[0].depth;

    int alpha = src_format->flags & AV_PIX_FMT_FLAG_ALPHA;

    int swap = 0;

    if ( HAVE_BIGENDIAN && !(src_format->flags & AV_PIX_FMT_FLAG_BE) ||

        !HAVE_BIGENDIAN &&   src_format->flags & AV_PIX_FMT_FLAG_BE)

        swap++;

    if ( HAVE_BIGENDIAN && !(dst_format->flags & AV_PIX_FMT_FLAG_BE) ||

        !HAVE_BIGENDIAN &&   dst_format->flags & AV_PIX_FMT_FLAG_BE)

        swap += 2;

    if ((dst_format->flags & (AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_RGB)) !=

        (AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_RGB) || bpc < 9) {

        av_log(c, AV_LOG_ERROR, "unsupported conversion to planar RGB %s -> %s\n",

               src_format->name, dst_format->name);

        return srcSliceH;

    }

    switch (c->srcFormat) {

    case AV_PIX_FMT_RGB48LE:

    case AV_PIX_FMT_RGB48BE:

    case AV_PIX_FMT_RGBA64LE:

    case AV_PIX_FMT_RGBA64BE:

        packed16togbra16(src[0] + srcSliceY * srcStride[0], srcStride[0],

                         dst2013, stride2013, srcSliceH, alpha, swap,

                         16 - bpc, c->srcW);

        break;

    case AV_PIX_FMT_BGR48LE:

    case AV_PIX_FMT_BGR48BE:

    case AV_PIX_FMT_BGRA64LE:

    case AV_PIX_FMT_BGRA64BE:

        packed16togbra16(src[0] + srcSliceY * srcStride[0], srcStride[0],

                         dst1023, stride1023, srcSliceH, alpha, swap,

                         16 - bpc, c->srcW);

        break;

    default:

        av_log(c, AV_LOG_ERROR,

               "unsupported conversion to planar RGB %s -> %s\n",

               src_format->name, dst_format->name);

    }

    return srcSliceH;

}


int ff_load_image(uint8_t *data[4], int linesize[4],

                  int *w, int *h, enum AVPixelFormat *pix_fmt,

                  const char *filename, void *log_ctx)

{

    AVInputFormat *iformat = NULL;

    AVFormatContext *format_ctx = NULL;

    AVCodec *codec;

    AVCodecContext *codec_ctx;

    AVFrame *frame;

    int frame_decoded, ret = 0;

    AVPacket pkt;

    av_register_all();

    iformat = av_find_input_format("image2");

    if ((ret = avformat_open_input(&format_ctx, filename, iformat, NULL)) < 0) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Failed to open input file '%s'\n", filename);

        return ret;

    }

    codec_ctx = format_ctx->streams[0]->codec;

    codec = avcodec_find_decoder(codec_ctx->codec_id);

    if (!codec) {

        av_log(log_ctx, AV_LOG_ERROR, "Failed to find codec\n");

        ret = AVERROR(EINVAL);

        goto end;

    }

    if ((ret = avcodec_open2(codec_ctx, codec, NULL)) < 0) {

        av_log(log_ctx, AV_LOG_ERROR, "Failed to open codec\n");

        goto end;

    }

    if (!(frame = avcodec_alloc_frame()) ) {

        av_log(log_ctx, AV_LOG_ERROR, "Failed to alloc frame\n");

        ret = AVERROR(ENOMEM);

        goto end;

    }

    ret = av_read_frame(format_ctx, &pkt);

    if (ret < 0) {

        av_log(log_ctx, AV_LOG_ERROR, "Failed to read frame from file\n");

        goto end;

    }

    ret = avcodec_decode_video2(codec_ctx, frame, &frame_decoded, &pkt);

    if (ret < 0 || !frame_decoded) {

        av_log(log_ctx, AV_LOG_ERROR, "Failed to decode image from file\n");

        goto end;

    }

    ret = 0;

    *w       = frame->width;

    *h       = frame->height;

    *pix_fmt = frame->format;

    if ((ret = av_image_alloc(data, linesize, *w, *h, *pix_fmt, 16)) < 0)

        goto end;

    ret = 0;

    av_image_copy(data, linesize, (const uint8_t **)frame->data, frame->linesize, *pix_fmt, *w, *h);

end:

    avcodec_close(codec_ctx);

    if (format_ctx)

        avformat_close_input(&format_ctx);

    av_freep(&frame);

    if (ret < 0)

        av_log(log_ctx, AV_LOG_ERROR, "Error loading image file '%s'\n", filename);

    return ret;

}


static attribute_align_arg void *frame_worker_thread(void *arg)

{

    PerThreadContext *p = arg;

    FrameThreadContext *fctx = p->parent;

    AVCodecContext *avctx = p->avctx;

    const AVCodec *codec = avctx->codec;

    pthread_mutex_lock(&p->mutex);

    while (1) {

            while (p->state == STATE_INPUT_READY && !fctx->die)

                pthread_cond_wait(&p->input_cond, &p->mutex);

        if (fctx->die) break;

        if (!codec->update_thread_context && (avctx->thread_safe_callbacks || (

#if FF_API_GET_BUFFER

            !avctx->get_buffer &&

#endif

            avctx->get_buffer2 == avcodec_default_get_buffer2)))

            ff_thread_finish_setup(avctx);

        avcodec_get_frame_defaults(&p->frame);

        p->got_frame = 0;

        p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);

        /* many decoders assign whole AVFrames, thus overwriting extended_data;

         * make sure it's set correctly */

        p->frame.extended_data = p->frame.data;

        if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);

        pthread_mutex_lock(&p->progress_mutex);

#if 0 //BUFREF-FIXME

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

            if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {

                p->progress[i][0] = INT_MAX;

                p->progress[i][1] = INT_MAX;

            }

#endif

        p->state = STATE_INPUT_READY;

        pthread_cond_broadcast(&p->progress_cond);

        pthread_cond_signal(&p->output_cond);

        pthread_mutex_unlock(&p->progress_mutex);

    }

    pthread_mutex_unlock(&p->mutex);

    return NULL;

}


static int vnc_client_io_error(VncState *vs, int ret, int last_errno)

{

    if (ret == 0 || ret == -1) {

        if (ret == -1) {

            switch (last_errno) {

                case EINTR:

                case EAGAIN:

#ifdef _WIN32

                case WSAEWOULDBLOCK:

#endif

                    return 0;

                default:

                    break;

            }

        }

	VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);

	qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);

	closesocket(vs->csock);

        qemu_del_timer(vs->timer);

        qemu_free_timer(vs->timer);

        if (vs->input.buffer) qemu_free(vs->input.buffer);

        if (vs->output.buffer) qemu_free(vs->output.buffer);

#ifdef CONFIG_VNC_TLS

	vnc_tls_client_cleanup(vs);

#endif /* CONFIG_VNC_TLS */

        audio_del(vs);

        VncState *p, *parent = NULL;

        for (p = vs->vd->clients; p != NULL; p = p->next) {

            if (p == vs) {

                if (parent)

                    parent->next = p->next;

                else

                    vs->vd->clients = p->next;

                break;

            }

            parent = p;

        }

        if (!vs->vd->clients)

            dcl->idle = 1;

        qemu_free(vs->old_data);

        qemu_free(vs);

	return 0;

    }

    return ret;

}


void pvpanic_init(ISABus *bus)

{

    isa_create_simple(bus, TYPE_ISA_PVPANIC_DEVICE);

}


static void xa_decode(short *out, const unsigned char *in,

    ADPCMChannelStatus *left, ADPCMChannelStatus *right, int inc)

{

    int i, j;

    int shift,filter,f0,f1;

    int s_1,s_2;

    int d,s,t;

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

        shift  = 12 - (in[4+i*2] & 15);

        filter = in[4+i*2] >> 4;

        f0 = xa_adpcm_table[filter][0];

        f1 = xa_adpcm_table[filter][1];

        s_1 = left->sample1;

        s_2 = left->sample2;

        for(j=0;j<28;j++) {

            d = in[16+i+j*4];

            t = (signed char)(d<<4)>>4;

            s = ( t<<shift ) + ((s_1*f0 + s_2*f1+32)>>6);

            s_2 = s_1;

            s_1 = av_clip_int16(s);

            *out = s_1;

            out += inc;

        }

        if (inc==2) { /* stereo */

            left->sample1 = s_1;

            left->sample2 = s_2;

            s_1 = right->sample1;

            s_2 = right->sample2;

            out = out + 1 - 28*2;

        }

        shift  = 12 - (in[5+i*2] & 15);

        filter = in[5+i*2] >> 4;

        f0 = xa_adpcm_table[filter][0];

        f1 = xa_adpcm_table[filter][1];

        for(j=0;j<28;j++) {

            d = in[16+i+j*4];

            t = (signed char)d >> 4;

            s = ( t<<shift ) + ((s_1*f0 + s_2*f1+32)>>6);

            s_2 = s_1;

            s_1 = av_clip_int16(s);

            *out = s_1;

            out += inc;

        }

        if (inc==2) { /* stereo */

            right->sample1 = s_1;

            right->sample2 = s_2;

            out -= 1;

        } else {

            left->sample1 = s_1;

            left->sample2 = s_2;

        }

    }

}


int qemu_fdt_setprop_sized_cells_from_array(void *fdt,

                                            const char *node_path,

                                            const char *property,

                                            int numvalues,

                                            uint64_t *values)

{

    uint32_t *propcells;

    uint64_t value;

    int cellnum, vnum, ncells;

    uint32_t hival;

    propcells = g_new0(uint32_t, numvalues * 2);

    cellnum = 0;

    for (vnum = 0; vnum < numvalues; vnum++) {

        ncells = values[vnum * 2];

        if (ncells != 1 && ncells != 2) {

            return -1;

        }

        value = values[vnum * 2 + 1];

        hival = cpu_to_be32(value >> 32);

        if (ncells > 1) {

            propcells[cellnum++] = hival;

        } else if (hival != 0) {

            return -1;

        }

        propcells[cellnum++] = cpu_to_be32(value);

    }

    return qemu_fdt_setprop(fdt, node_path, property, propcells,

                            cellnum * sizeof(uint32_t));

}


void spapr_core_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,

                         Error **errp)

{

    MachineState *machine = MACHINE(OBJECT(hotplug_dev));

    sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(OBJECT(hotplug_dev));

    sPAPRMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));

    int spapr_max_cores = max_cpus / smp_threads;

    int index;

    Error *local_err = NULL;

    CPUCore *cc = CPU_CORE(dev);

    char *base_core_type = spapr_get_cpu_core_type(machine->cpu_model);

    const char *type = object_get_typename(OBJECT(dev));

    if (strcmp(base_core_type, type)) {

        error_setg(&local_err, "CPU core type should be %s", base_core_type);

        goto out;

    }

    if (!smc->dr_cpu_enabled && dev->hotplugged) {

        error_setg(&local_err, "CPU hotplug not supported for this machine");

        goto out;

    }

    if (cc->nr_threads != smp_threads) {

        error_setg(&local_err, "threads must be %d", smp_threads);

        goto out;

    }

    if (cc->core_id % smp_threads) {

        error_setg(&local_err, "invalid core id %d\n", cc->core_id);

        goto out;

    }

    index = cc->core_id / smp_threads;

    if (index < 0 || index >= spapr_max_cores) {

        error_setg(&local_err, "core id %d out of range", cc->core_id);

        goto out;

    }

    if (spapr->cores[index]) {

        error_setg(&local_err, "core %d already populated", cc->core_id);

        goto out;

    }

out:

    g_free(base_core_type);

    error_propagate(errp, local_err);

}


static void complete_request_vring(VirtIOBlockReq *req, unsigned char status)

{

    stb_p(&req->in->status, status);

    vring_push(&req->dev->dataplane->vring, req->elem,

               req->qiov.size + sizeof(*req->in));

    notify_guest(req->dev->dataplane);

}


static void aux_register_types(void)

{

    type_register_static(&aux_bus_info);

    type_register_static(&aux_slave_type_info);

    type_register_static(&aux_to_i2c_type_info);

}


static inline void RENAME(rgb24toyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,

                                       int width, int height,

                                       int lumStride, int chromStride, int srcStride)

{

    int y;

    const x86_reg chromWidth= width>>1;

    for (y=0; y<height-2; y+=2) {

        int i;

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

            __asm__ volatile(

                "mov                        %2, %%"REG_a"   \n\t"

                "movq  "MANGLE(ff_bgr2YCoeff)", %%mm6       \n\t"

                "movq       "MANGLE(ff_w1111)", %%mm5       \n\t"

                "pxor                    %%mm7, %%mm7       \n\t"

                "lea (%%"REG_a", %%"REG_a", 2), %%"REG_d"   \n\t"

                ".p2align                    4              \n\t"

                "1:                                         \n\t"

                PREFETCH"    64(%0, %%"REG_d")              \n\t"

                "movd          (%0, %%"REG_d"), %%mm0       \n\t"

                "movd         3(%0, %%"REG_d"), %%mm1       \n\t"

                "punpcklbw               %%mm7, %%mm0       \n\t"

                "punpcklbw               %%mm7, %%mm1       \n\t"

                "movd         6(%0, %%"REG_d"), %%mm2       \n\t"

                "movd         9(%0, %%"REG_d"), %%mm3       \n\t"

                "punpcklbw               %%mm7, %%mm2       \n\t"

                "punpcklbw               %%mm7, %%mm3       \n\t"

                "pmaddwd                 %%mm6, %%mm0       \n\t"

                "pmaddwd                 %%mm6, %%mm1       \n\t"

                "pmaddwd                 %%mm6, %%mm2       \n\t"

                "pmaddwd                 %%mm6, %%mm3       \n\t"

#ifndef FAST_BGR2YV12

                "psrad                      $8, %%mm0       \n\t"

                "psrad                      $8, %%mm1       \n\t"

                "psrad                      $8, %%mm2       \n\t"

                "psrad                      $8, %%mm3       \n\t"

#endif

                "packssdw                %%mm1, %%mm0       \n\t"

                "packssdw                %%mm3, %%mm2       \n\t"

                "pmaddwd                 %%mm5, %%mm0       \n\t"

                "pmaddwd                 %%mm5, %%mm2       \n\t"

                "packssdw                %%mm2, %%mm0       \n\t"

                "psraw                      $7, %%mm0       \n\t"

                "movd        12(%0, %%"REG_d"), %%mm4       \n\t"

                "movd        15(%0, %%"REG_d"), %%mm1       \n\t"

                "punpcklbw               %%mm7, %%mm4       \n\t"

                "punpcklbw               %%mm7, %%mm1       \n\t"

                "movd        18(%0, %%"REG_d"), %%mm2       \n\t"

                "movd        21(%0, %%"REG_d"), %%mm3       \n\t"

                "punpcklbw               %%mm7, %%mm2       \n\t"

                "punpcklbw               %%mm7, %%mm3       \n\t"

                "pmaddwd                 %%mm6, %%mm4       \n\t"

                "pmaddwd                 %%mm6, %%mm1       \n\t"

                "pmaddwd                 %%mm6, %%mm2       \n\t"

                "pmaddwd                 %%mm6, %%mm3       \n\t"

#ifndef FAST_BGR2YV12

                "psrad                      $8, %%mm4       \n\t"

                "psrad                      $8, %%mm1       \n\t"

                "psrad                      $8, %%mm2       \n\t"

                "psrad                      $8, %%mm3       \n\t"

#endif

                "packssdw                %%mm1, %%mm4       \n\t"

                "packssdw                %%mm3, %%mm2       \n\t"

                "pmaddwd                 %%mm5, %%mm4       \n\t"

                "pmaddwd                 %%mm5, %%mm2       \n\t"

                "add                       $24, %%"REG_d"   \n\t"

                "packssdw                %%mm2, %%mm4       \n\t"

                "psraw                      $7, %%mm4       \n\t"

                "packuswb                %%mm4, %%mm0       \n\t"

                "paddusb "MANGLE(ff_bgr2YOffset)", %%mm0    \n\t"

                MOVNTQ"                  %%mm0, (%1, %%"REG_a") \n\t"

                "add                        $8,      %%"REG_a"  \n\t"

                " js                        1b                  \n\t"

                : : "r" (src+width*3), "r" (ydst+width), "g" ((x86_reg)-width)

                : "%"REG_a, "%"REG_d

            );

            ydst += lumStride;

            src  += srcStride;

        }

        src -= srcStride*2;

        __asm__ volatile(

            "mov                        %4, %%"REG_a"   \n\t"

            "movq       "MANGLE(ff_w1111)", %%mm5       \n\t"

            "movq  "MANGLE(ff_bgr2UCoeff)", %%mm6       \n\t"

            "pxor                    %%mm7, %%mm7       \n\t"

            "lea (%%"REG_a", %%"REG_a", 2), %%"REG_d"   \n\t"

            "add                 %%"REG_d", %%"REG_d"   \n\t"

            ".p2align                    4              \n\t"

            "1:                                         \n\t"

            PREFETCH"    64(%0, %%"REG_d")              \n\t"

            PREFETCH"    64(%1, %%"REG_d")              \n\t"

#if COMPILE_TEMPLATE_MMXEXT || COMPILE_TEMPLATE_AMD3DNOW

            "movq          (%0, %%"REG_d"), %%mm0       \n\t"

            "movq          (%1, %%"REG_d"), %%mm1       \n\t"

            "movq         6(%0, %%"REG_d"), %%mm2       \n\t"

            "movq         6(%1, %%"REG_d"), %%mm3       \n\t"

            PAVGB"                   %%mm1, %%mm0       \n\t"

            PAVGB"                   %%mm3, %%mm2       \n\t"

            "movq                    %%mm0, %%mm1       \n\t"

            "movq                    %%mm2, %%mm3       \n\t"

            "psrlq                     $24, %%mm0       \n\t"

            "psrlq                     $24, %%mm2       \n\t"

            PAVGB"                   %%mm1, %%mm0       \n\t"

            PAVGB"                   %%mm3, %%mm2       \n\t"

            "punpcklbw               %%mm7, %%mm0       \n\t"

            "punpcklbw               %%mm7, %%mm2       \n\t"

#else

            "movd          (%0, %%"REG_d"), %%mm0       \n\t"

            "movd          (%1, %%"REG_d"), %%mm1       \n\t"

            "movd         3(%0, %%"REG_d"), %%mm2       \n\t"

            "movd         3(%1, %%"REG_d"), %%mm3       \n\t"

            "punpcklbw               %%mm7, %%mm0       \n\t"

            "punpcklbw               %%mm7, %%mm1       \n\t"

            "punpcklbw               %%mm7, %%mm2       \n\t"

            "punpcklbw               %%mm7, %%mm3       \n\t"

            "paddw                   %%mm1, %%mm0       \n\t"

            "paddw                   %%mm3, %%mm2       \n\t"

            "paddw                   %%mm2, %%mm0       \n\t"

            "movd         6(%0, %%"REG_d"), %%mm4       \n\t"

            "movd         6(%1, %%"REG_d"), %%mm1       \n\t"

            "movd         9(%0, %%"REG_d"), %%mm2       \n\t"

            "movd         9(%1, %%"REG_d"), %%mm3       \n\t"

            "punpcklbw               %%mm7, %%mm4       \n\t"

            "punpcklbw               %%mm7, %%mm1       \n\t"

            "punpcklbw               %%mm7, %%mm2       \n\t"

            "punpcklbw               %%mm7, %%mm3       \n\t"

            "paddw                   %%mm1, %%mm4       \n\t"

            "paddw                   %%mm3, %%mm2       \n\t"

            "paddw                   %%mm4, %%mm2       \n\t"

            "psrlw                      $2, %%mm0       \n\t"

            "psrlw                      $2, %%mm2       \n\t"

#endif

            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm1       \n\t"

            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm3       \n\t"

            "pmaddwd                 %%mm0, %%mm1       \n\t"

            "pmaddwd                 %%mm2, %%mm3       \n\t"

            "pmaddwd                 %%mm6, %%mm0       \n\t"

            "pmaddwd                 %%mm6, %%mm2       \n\t"

#ifndef FAST_BGR2YV12

            "psrad                      $8, %%mm0       \n\t"

            "psrad                      $8, %%mm1       \n\t"

            "psrad                      $8, %%mm2       \n\t"

            "psrad                      $8, %%mm3       \n\t"

#endif

            "packssdw                %%mm2, %%mm0       \n\t"

            "packssdw                %%mm3, %%mm1       \n\t"

            "pmaddwd                 %%mm5, %%mm0       \n\t"

            "pmaddwd                 %%mm5, %%mm1       \n\t"

            "packssdw                %%mm1, %%mm0       \n\t" // V1 V0 U1 U0

            "psraw                      $7, %%mm0       \n\t"

#if COMPILE_TEMPLATE_MMXEXT || COMPILE_TEMPLATE_AMD3DNOW

            "movq        12(%0, %%"REG_d"), %%mm4       \n\t"

            "movq        12(%1, %%"REG_d"), %%mm1       \n\t"

            "movq        18(%0, %%"REG_d"), %%mm2       \n\t"

            "movq        18(%1, %%"REG_d"), %%mm3       \n\t"

            PAVGB"                   %%mm1, %%mm4       \n\t"

            PAVGB"                   %%mm3, %%mm2       \n\t"

            "movq                    %%mm4, %%mm1       \n\t"

            "movq                    %%mm2, %%mm3       \n\t"

            "psrlq                     $24, %%mm4       \n\t"

            "psrlq                     $24, %%mm2       \n\t"

            PAVGB"                   %%mm1, %%mm4       \n\t"

            PAVGB"                   %%mm3, %%mm2       \n\t"

            "punpcklbw               %%mm7, %%mm4       \n\t"

            "punpcklbw               %%mm7, %%mm2       \n\t"

#else

            "movd        12(%0, %%"REG_d"), %%mm4       \n\t"

            "movd        12(%1, %%"REG_d"), %%mm1       \n\t"

            "movd        15(%0, %%"REG_d"), %%mm2       \n\t"

            "movd        15(%1, %%"REG_d"), %%mm3       \n\t"

            "punpcklbw               %%mm7, %%mm4       \n\t"

            "punpcklbw               %%mm7, %%mm1       \n\t"

            "punpcklbw               %%mm7, %%mm2       \n\t"

            "punpcklbw               %%mm7, %%mm3       \n\t"

            "paddw                   %%mm1, %%mm4       \n\t"

            "paddw                   %%mm3, %%mm2       \n\t"

            "paddw                   %%mm2, %%mm4       \n\t"

            "movd        18(%0, %%"REG_d"), %%mm5       \n\t"

            "movd        18(%1, %%"REG_d"), %%mm1       \n\t"

            "movd        21(%0, %%"REG_d"), %%mm2       \n\t"

            "movd        21(%1, %%"REG_d"), %%mm3       \n\t"

            "punpcklbw               %%mm7, %%mm5       \n\t"

            "punpcklbw               %%mm7, %%mm1       \n\t"

            "punpcklbw               %%mm7, %%mm2       \n\t"

            "punpcklbw               %%mm7, %%mm3       \n\t"

            "paddw                   %%mm1, %%mm5       \n\t"

            "paddw                   %%mm3, %%mm2       \n\t"

            "paddw                   %%mm5, %%mm2       \n\t"

            "movq       "MANGLE(ff_w1111)", %%mm5       \n\t"

            "psrlw                      $2, %%mm4       \n\t"

            "psrlw                      $2, %%mm2       \n\t"

#endif

            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm1       \n\t"

            "movq  "MANGLE(ff_bgr2VCoeff)", %%mm3       \n\t"

            "pmaddwd                 %%mm4, %%mm1       \n\t"

            "pmaddwd                 %%mm2, %%mm3       \n\t"

            "pmaddwd                 %%mm6, %%mm4       \n\t"

            "pmaddwd                 %%mm6, %%mm2       \n\t"

#ifndef FAST_BGR2YV12

            "psrad                      $8, %%mm4       \n\t"

            "psrad                      $8, %%mm1       \n\t"

            "psrad                      $8, %%mm2       \n\t"

            "psrad                      $8, %%mm3       \n\t"

#endif

            "packssdw                %%mm2, %%mm4       \n\t"

            "packssdw                %%mm3, %%mm1       \n\t"

            "pmaddwd                 %%mm5, %%mm4       \n\t"

            "pmaddwd                 %%mm5, %%mm1       \n\t"

            "add                       $24, %%"REG_d"   \n\t"

            "packssdw                %%mm1, %%mm4       \n\t" // V3 V2 U3 U2

            "psraw                      $7, %%mm4       \n\t"

            "movq                    %%mm0, %%mm1           \n\t"

            "punpckldq               %%mm4, %%mm0           \n\t"

            "punpckhdq               %%mm4, %%mm1           \n\t"

            "packsswb                %%mm1, %%mm0           \n\t"

            "paddb "MANGLE(ff_bgr2UVOffset)", %%mm0         \n\t"

            "movd                    %%mm0, (%2, %%"REG_a") \n\t"

            "punpckhdq               %%mm0, %%mm0           \n\t"

            "movd                    %%mm0, (%3, %%"REG_a") \n\t"

            "add                        $4, %%"REG_a"       \n\t"

            " js                        1b                  \n\t"

            : : "r" (src+chromWidth*6), "r" (src+srcStride+chromWidth*6), "r" (udst+chromWidth), "r" (vdst+chromWidth), "g" (-chromWidth)

            : "%"REG_a, "%"REG_d

        );

        udst += chromStride;

        vdst += chromStride;

        src  += srcStride*2;

    }

    __asm__ volatile(EMMS"       \n\t"

                     SFENCE"     \n\t"

                     :::"memory");

     rgb24toyv12_c(src, ydst, udst, vdst, width, height-y, lumStride, chromStride, srcStride);

}


void helper_stsw(CPUPPCState *env, target_ulong addr, uint32_t nb,

                 uint32_t reg)

{

    int sh;

    for (; nb > 3; nb -= 4) {

        cpu_stl_data(env, addr, env->gpr[reg]);

        reg = (reg + 1) % 32;

        addr = addr_add(env, addr, 4);

    }

    if (unlikely(nb > 0)) {

        for (sh = 24; nb > 0; nb--, sh -= 8) {

            cpu_stb_data(env, addr, (env->gpr[reg] >> sh) & 0xFF);

            addr = addr_add(env, addr, 1);

        }

    }

}


static int loco_decode_plane(LOCOContext *l, uint8_t *data, int width, int height,

                             int stride, const uint8_t *buf, int buf_size, int step)

{

    RICEContext rc;

    int val;

    int i, j;

    if(buf_size<=0)

        return -1;

    init_get_bits8(&rc.gb, buf, buf_size);

    rc.save  = 0;

    rc.run   = 0;

    rc.run2  = 0;

    rc.lossy = l->lossy;

    rc.sum   = 8;

    rc.count = 1;

    /* restore top left pixel */

    val     = loco_get_rice(&rc);

    data[0] = 128 + val;

    /* restore top line */

    for (i = 1; i < width; i++) {

        val = loco_get_rice(&rc);

        data[i * step] = data[i * step - step] + val;

    }

    data += stride;

    for (j = 1; j < height; j++) {

        /* restore left column */

        val = loco_get_rice(&rc);

        data[0] = data[-stride] + val;

        /* restore all other pixels */

        for (i = 1; i < width; i++) {

            val = loco_get_rice(&rc);

            data[i * step] = loco_predict(&data[i * step], stride, step) + val;

        }

        data += stride;

    }

    return (get_bits_count(&rc.gb) + 7) >> 3;

}


void * g_malloc0(size_t size)

{

    return g_malloc(size);

}


static void copy_bits(PutBitContext *pb, UINT8 *src, int length)

{

#if 1

    int bytes= length>>4;

    int bits= length&15;

    int i;

    for(i=0; i<bytes; i++) put_bits(pb, 16, be2me_16(((uint16_t*)src)[i]));

    put_bits(pb, bits, be2me_16(((uint16_t*)src)[i])>>(16-bits));

#else

    int bytes= length>>3;

    int bits= length&7;

    int i;

    for(i=0; i<bytes; i++) put_bits(pb, 8, src[i]);

    put_bits(pb, bits, src[i]>>(8-bits));

#endif

}


static void vb_decode_palette(VBDecContext *c)

{

    int start, size, i;

    start = bytestream_get_byte(&c->stream);

    size = (bytestream_get_byte(&c->stream) - 1) & 0xFF;

    if(start + size > 255){

        av_log(c->avctx, AV_LOG_ERROR, "Palette change runs beyond entry 256\n");

        return;

    }

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

        c->pal[i] = bytestream_get_be24(&c->stream);

}


void sws_freeContext(SwsContext *c)

{

    int i;

    if (!c) return;

    if (c->lumPixBuf) {

        for (i=0; i<c->vLumBufSize; i++)

            av_freep(&c->lumPixBuf[i]);

        av_freep(&c->lumPixBuf);

    }

    if (c->chrPixBuf) {

        for (i=0; i<c->vChrBufSize; i++)

            av_freep(&c->chrPixBuf[i]);

        av_freep(&c->chrPixBuf);

    }

    if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

        for (i=0; i<c->vLumBufSize; i++)

            av_freep(&c->alpPixBuf[i]);

        av_freep(&c->alpPixBuf);

    }

    av_freep(&c->vLumFilter);

    av_freep(&c->vChrFilter);

    av_freep(&c->hLumFilter);

    av_freep(&c->hChrFilter);

#if ARCH_PPC && HAVE_ALTIVEC

    av_freep(&c->vYCoeffsBank);

    av_freep(&c->vCCoeffsBank);

#endif

    av_freep(&c->vLumFilterPos);

    av_freep(&c->vChrFilterPos);

    av_freep(&c->hLumFilterPos);

    av_freep(&c->hChrFilterPos);

#if ARCH_X86 && CONFIG_GPL

#ifdef MAP_ANONYMOUS

    if (c->lumMmx2FilterCode) munmap(c->lumMmx2FilterCode, c->lumMmx2FilterCodeSize);

    if (c->chrMmx2FilterCode) munmap(c->chrMmx2FilterCode, c->chrMmx2FilterCodeSize);

#elif HAVE_VIRTUALALLOC

    if (c->lumMmx2FilterCode) VirtualFree(c->lumMmx2FilterCode, 0, MEM_RELEASE);

    if (c->chrMmx2FilterCode) VirtualFree(c->chrMmx2FilterCode, 0, MEM_RELEASE);

#else

    av_free(c->lumMmx2FilterCode);

    av_free(c->chrMmx2FilterCode);

#endif

    c->lumMmx2FilterCode=NULL;

    c->chrMmx2FilterCode=NULL;

#endif /* ARCH_X86 && CONFIG_GPL */

    av_freep(&c->yuvTable);

    av_free(c);

}


static void pollfds_poll(GArray *pollfds, int nfds, fd_set *rfds,

                         fd_set *wfds, fd_set *xfds)

{

    int i;

    for (i = 0; i < pollfds->len; i++) {

        GPollFD *pfd = &g_array_index(pollfds, GPollFD, i);

        int fd = pfd->fd;

        int revents = 0;

        if (FD_ISSET(fd, rfds)) {

            revents |= G_IO_IN | G_IO_HUP | G_IO_ERR;

        }

        if (FD_ISSET(fd, wfds)) {

            revents |= G_IO_OUT | G_IO_ERR;

        }

        if (FD_ISSET(fd, xfds)) {

            revents |= G_IO_PRI;

        }

        pfd->revents = revents & pfd->events;

    }

}


static void decode_v1_vector(CinepakEncContext *s, AVPicture *sub_pict, mb_info *mb, strip_info *info)

{

    int entry_size = s->pix_fmt == AV_PIX_FMT_YUV420P ? 6 : 4;

    sub_pict->data[0][0] =

            sub_pict->data[0][1] =

            sub_pict->data[0][    sub_pict->linesize[0]] =

            sub_pict->data[0][1+  sub_pict->linesize[0]] = info->v1_codebook[mb->v1_vector*entry_size];

    sub_pict->data[0][2] =

            sub_pict->data[0][3] =

            sub_pict->data[0][2+  sub_pict->linesize[0]] =

            sub_pict->data[0][3+  sub_pict->linesize[0]] = info->v1_codebook[mb->v1_vector*entry_size+1];

    sub_pict->data[0][2*sub_pict->linesize[0]] =

            sub_pict->data[0][1+2*sub_pict->linesize[0]] =

            sub_pict->data[0][  3*sub_pict->linesize[0]] =

            sub_pict->data[0][1+3*sub_pict->linesize[0]] = info->v1_codebook[mb->v1_vector*entry_size+2];

    sub_pict->data[0][2+2*sub_pict->linesize[0]] =

            sub_pict->data[0][3+2*sub_pict->linesize[0]] =

            sub_pict->data[0][2+3*sub_pict->linesize[0]] =

            sub_pict->data[0][3+3*sub_pict->linesize[0]] = info->v1_codebook[mb->v1_vector*entry_size+3];

    if(s->pix_fmt == AV_PIX_FMT_YUV420P) {

        sub_pict->data[1][0] =

            sub_pict->data[1][1] =

            sub_pict->data[1][    sub_pict->linesize[1]] =

            sub_pict->data[1][1+  sub_pict->linesize[1]] = info->v1_codebook[mb->v1_vector*entry_size+4];

        sub_pict->data[2][0] =

            sub_pict->data[2][1] =

            sub_pict->data[2][    sub_pict->linesize[2]] =

            sub_pict->data[2][1+  sub_pict->linesize[2]] = info->v1_codebook[mb->v1_vector*entry_size+5];

    }

}