static void render_slice(Vp3DecodeContext *s, int slice)

{

    int x, y;

    int m, n;

    int i;  /* indicates current fragment */

    int16_t *dequantizer;

    DCTELEM __align16 block[64];

    unsigned char *output_plane;

    unsigned char *last_plane;

    unsigned char *golden_plane;

    int stride;

    int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;

    int upper_motion_limit, lower_motion_limit;

    int motion_halfpel_index;

    uint8_t *motion_source;

    int plane;

    int plane_width;

    int plane_height;

    int slice_height;

    int current_macroblock_entry = slice * s->macroblock_width * 6;

    if (slice >= s->macroblock_height)

        return;

    for (plane = 0; plane < 3; plane++) {

        /* set up plane-specific parameters */

        if (plane == 0) {

            output_plane = s->current_frame.data[0];

            last_plane = s->last_frame.data[0];

            golden_plane = s->golden_frame.data[0];

            stride = s->current_frame.linesize[0];

            if (!s->flipped_image) stride = -stride;

            upper_motion_limit = 7 * s->current_frame.linesize[0];

            lower_motion_limit = s->height * s->current_frame.linesize[0] + s->width - 8;

            y = slice * FRAGMENT_PIXELS * 2;

            plane_width = s->width;

            plane_height = s->height;

            slice_height = y + FRAGMENT_PIXELS * 2;

            i = s->macroblock_fragments[current_macroblock_entry + 0];

        } else if (plane == 1) {

            output_plane = s->current_frame.data[1];

            last_plane = s->last_frame.data[1];

            golden_plane = s->golden_frame.data[1];

            stride = s->current_frame.linesize[1];

            if (!s->flipped_image) stride = -stride;

            upper_motion_limit = 7 * s->current_frame.linesize[1];

            lower_motion_limit = (s->height / 2) * s->current_frame.linesize[1] + (s->width / 2) - 8;

            y = slice * FRAGMENT_PIXELS;

            plane_width = s->width / 2;

            plane_height = s->height / 2;

            slice_height = y + FRAGMENT_PIXELS;

            i = s->macroblock_fragments[current_macroblock_entry + 4];

        } else {

            output_plane = s->current_frame.data[2];

            last_plane = s->last_frame.data[2];

            golden_plane = s->golden_frame.data[2];

            stride = s->current_frame.linesize[2];

            if (!s->flipped_image) stride = -stride;

            upper_motion_limit = 7 * s->current_frame.linesize[2];

            lower_motion_limit = (s->height / 2) * s->current_frame.linesize[2] + (s->width / 2) - 8;

            y = slice * FRAGMENT_PIXELS;

            plane_width = s->width / 2;

            plane_height = s->height / 2;

            slice_height = y + FRAGMENT_PIXELS;

            i = s->macroblock_fragments[current_macroblock_entry + 5];

        }

        if(ABS(stride) > 2048)

            return; //various tables are fixed size

        /* for each fragment row in the slice (both of them)... */

        for (; y < slice_height; y += 8) {

            /* for each fragment in a row... */

            for (x = 0; x < plane_width; x += 8, i++) {

                if ((i < 0) || (i >= s->fragment_count)) {

                    av_log(s->avctx, AV_LOG_ERROR, "  vp3:render_slice(): bad fragment number (%d)\n", i);

                    return;

                }

                /* transform if this block was coded */

                if ((s->all_fragments[i].coding_method != MODE_COPY) &&

                    !((s->avctx->flags & CODEC_FLAG_GRAY) && plane)) {

                    if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||

                        (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))

                        motion_source= golden_plane;

                    else

                        motion_source= last_plane;

                    motion_source += s->all_fragments[i].first_pixel;

                    motion_halfpel_index = 0;

                    /* sort out the motion vector if this fragment is coded

                     * using a motion vector method */

                    if ((s->all_fragments[i].coding_method > MODE_INTRA) &&

                        (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {

                        int src_x, src_y;

                        motion_x = s->all_fragments[i].motion_x;

                        motion_y = s->all_fragments[i].motion_y;

                        if(plane){

                            motion_x= (motion_x>>1) | (motion_x&1);

                            motion_y= (motion_y>>1) | (motion_y&1);

                        }

                        src_x= (motion_x>>1) + x;

                        src_y= (motion_y>>1) + y;

                        if ((motion_x == 127) || (motion_y == 127))

                            av_log(s->avctx, AV_LOG_ERROR, " help! got invalid motion vector! (%X, %X)\n", motion_x, motion_y);

                        motion_halfpel_index = motion_x & 0x01;

                        motion_source += (motion_x >> 1);

                        motion_halfpel_index |= (motion_y & 0x01) << 1;

                        motion_source += ((motion_y >> 1) * stride);

                        if(src_x<0 || src_y<0 || src_x + 9 >= plane_width || src_y + 9 >= plane_height){

                            uint8_t *temp= s->edge_emu_buffer;

                            if(stride<0) temp -= 9*stride;

                            else temp += 9*stride;

                            ff_emulated_edge_mc(temp, motion_source, stride, 9, 9, src_x, src_y, plane_width, plane_height);

                            motion_source= temp;

                        }

                    }

                    /* first, take care of copying a block from either the

                     * previous or the golden frame */

                    if (s->all_fragments[i].coding_method != MODE_INTRA) {

                        /* Note, it is possible to implement all MC cases with

                           put_no_rnd_pixels_l2 which would look more like the

                           VP3 source but this would be slower as

                           put_no_rnd_pixels_tab is better optimzed */

                        if(motion_halfpel_index != 3){

                            s->dsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](

                                output_plane + s->all_fragments[i].first_pixel,

                                motion_source, stride, 8);

                        }else{

                            int d= (motion_x ^ motion_y)>>31; // d is 0 if motion_x and _y have the same sign, else -1

                            s->dsp.put_no_rnd_pixels_l2[1](

                                output_plane + s->all_fragments[i].first_pixel,

                                motion_source - d,

                                motion_source + stride + 1 + d,

                                stride, 8);

                        }

                        dequantizer = s->inter_dequant;

                    }else{

                        if (plane == 0)

                            dequantizer = s->intra_y_dequant;

                        else

                            dequantizer = s->intra_c_dequant;

                    }

                    /* dequantize the DCT coefficients */

                    debug_idct("fragment %d, coding mode %d, DC = %d, dequant = %d:\n",

                        i, s->all_fragments[i].coding_method,

                        DC_COEFF(i), dequantizer[0]);

                    if(s->avctx->idct_algo==FF_IDCT_VP3){

                        Coeff *coeff= s->coeffs + i;

                        memset(block, 0, sizeof(block));

                        while(coeff->next){

                            block[coeff->index]= coeff->coeff * dequantizer[coeff->index];

                            coeff= coeff->next;

                        }

                    }else{

                        Coeff *coeff= s->coeffs + i;

                        memset(block, 0, sizeof(block));

                        while(coeff->next){

                            block[coeff->index]= (coeff->coeff * dequantizer[coeff->index] + 2)>>2;

                            coeff= coeff->next;

                        }

                    }

                    /* invert DCT and place (or add) in final output */

                    if (s->all_fragments[i].coding_method == MODE_INTRA) {

                        if(s->avctx->idct_algo!=FF_IDCT_VP3)

                            block[0] += 128<<3;

                        s->dsp.idct_put(

                            output_plane + s->all_fragments[i].first_pixel,

                            stride,

                            block);

                    } else {

                        s->dsp.idct_add(

                            output_plane + s->all_fragments[i].first_pixel,

                            stride,

                            block);

                    }

                    debug_idct("block after idct_%s():\n",

                        (s->all_fragments[i].coding_method == MODE_INTRA)?

                        "put" : "add");

                    for (m = 0; m < 8; m++) {

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

                            debug_idct(" %3d", *(output_plane +

                                s->all_fragments[i].first_pixel + (m * stride + n)));

                        }

                        debug_idct("\n");

                    }

                    debug_idct("\n");

                } else {

                    /* copy directly from the previous frame */

                    s->dsp.put_pixels_tab[1][0](

                        output_plane + s->all_fragments[i].first_pixel,

                        last_plane + s->all_fragments[i].first_pixel,

                        stride, 8);

                }

            }

        }

    }

    /* future loop filter logic goes here... */

    /* algorithm:

     *   if (slice != 0)

     *     run filter on 1st row of Y slice

     *     run filter on U slice

     *     run filter on V slice

     *   run filter on 2nd row of Y slice

     */

     /* this looks like a good place for slice dispatch... */

     /* algorithm:

      *   if (slice > 0)

      *     dispatch (slice - 1);

      *   if (slice == s->macroblock_height - 1)

      *     dispatch (slice);  // handle last slice

      */

    emms_c();

}


match_insn_m68k (bfd_vma memaddr,

		 disassemble_info * info,

		 const struct m68k_opcode * best,

		 struct private * priv)

{

  unsigned char *save_p;

  unsigned char *p;

  const char *d;

  bfd_byte *buffer = priv->the_buffer;

  fprintf_ftype save_printer = info->fprintf_func;

  void (* save_print_address) (bfd_vma, struct disassemble_info *)

    = info->print_address_func;

  /* Point at first word of argument data,

     and at descriptor for first argument.  */

  p = buffer + 2;

  /* Figure out how long the fixed-size portion of the instruction is.

     The only place this is stored in the opcode table is

     in the arguments--look for arguments which specify fields in the 2nd

     or 3rd words of the instruction.  */

  for (d = best->args; *d; d += 2)

    {

      /* I don't think it is necessary to be checking d[0] here;

	 I suspect all this could be moved to the case statement below.  */

      if (d[0] == '#')

	{

	  if (d[1] == 'l' && p - buffer < 6)

	    p = buffer + 6;

	  else if (p - buffer < 4 && d[1] != 'C' && d[1] != '8')

	    p = buffer + 4;

	}

      if ((d[0] == 'L' || d[0] == 'l') && d[1] == 'w' && p - buffer < 4)

	p = buffer + 4;

      switch (d[1])

	{

	case '1':

	case '2':

	case '3':

	case '7':

	case '8':

	case '9':

	case 'i':

	  if (p - buffer < 4)

	    p = buffer + 4;

	  break;

	case '4':

	case '5':

	case '6':

	  if (p - buffer < 6)

	    p = buffer + 6;

	  break;

	default:

	  break;

	}

    }

  /* pflusha is an exceptions.  It takes no arguments but is two words

     long.  Recognize it by looking at the lower 16 bits of the mask.  */

  if (p - buffer < 4 && (best->match & 0xFFFF) != 0)

    p = buffer + 4;

  /* lpstop is another exception.  It takes a one word argument but is

     three words long.  */

  if (p - buffer < 6

      && (best->match & 0xffff) == 0xffff

      && best->args[0] == '#'

      && best->args[1] == 'w')

    {

      /* Copy the one word argument into the usual location for a one

	 word argument, to simplify printing it.  We can get away with

	 this because we know exactly what the second word is, and we

	 aren't going to print anything based on it.  */

      p = buffer + 6;

      FETCH_DATA (info, p);

      buffer[2] = buffer[4];

      buffer[3] = buffer[5];

    }

  FETCH_DATA (info, p);

  d = best->args;

  save_p = p;

  info->print_address_func = dummy_print_address;

  info->fprintf_func = (fprintf_ftype) dummy_printer;

  /* We scan the operands twice.  The first time we don't print anything,

     but look for errors.  */

  for (; *d; d += 2)

    {

      int eaten = print_insn_arg (d, buffer, p, memaddr + (p - buffer), info);

      if (eaten >= 0)

	p += eaten;

      else if (eaten == -1)

	{

	  info->fprintf_func = save_printer;

	  info->print_address_func = save_print_address;

	  return 0;

	}

      else

	{

	  info->fprintf_func (info->stream,

			      /* xgettext:c-format */

			      _("<internal error in opcode table: %s %s>\n"),

			      best->name,  best->args);

	  info->fprintf_func = save_printer;

	  info->print_address_func = save_print_address;

	  return 2;

	}

    }

  p = save_p;

  info->fprintf_func = save_printer;

  info->print_address_func = save_print_address;

  d = best->args;

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

  if (*d)

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

  while (*d)

    {

      p += print_insn_arg (d, buffer, p, memaddr + (p - buffer), info);

      d += 2;

      if (*d && *(d - 2) != 'I' && *d != 'k')

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

    }

  return p - buffer;

}


static void rcu_qtest_init(void)

{

    struct list_element *new_el;

    int i;

    nthreadsrunning = 0;

    srand(time(0));

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

        new_el = g_new(struct list_element, 1);

        new_el->val = i;

        QLIST_INSERT_HEAD_RCU(&Q_list_head, new_el, entry);

    }

    atomic_add(&n_nodes, RCU_Q_LEN);

}


static void virtio_ccw_bus_class_init(ObjectClass *klass, void *data)

{

    VirtioBusClass *k = VIRTIO_BUS_CLASS(klass);

    BusClass *bus_class = BUS_CLASS(klass);

    bus_class->max_dev = 1;

    k->notify = virtio_ccw_notify;

    k->vmstate_change = virtio_ccw_vmstate_change;

    k->query_guest_notifiers = virtio_ccw_query_guest_notifiers;

    k->set_guest_notifiers = virtio_ccw_set_guest_notifiers;

    k->save_queue = virtio_ccw_save_queue;

    k->load_queue = virtio_ccw_load_queue;

    k->save_config = virtio_ccw_save_config;

    k->load_config = virtio_ccw_load_config;

    k->device_plugged = virtio_ccw_device_plugged;

    k->post_plugged = virtio_ccw_post_plugged;

    k->device_unplugged = virtio_ccw_device_unplugged;

    k->ioeventfd_started = virtio_ccw_ioeventfd_started;

    k->ioeventfd_set_started = virtio_ccw_ioeventfd_set_started;

    k->ioeventfd_disabled = virtio_ccw_ioeventfd_disabled;

    k->ioeventfd_set_disabled = virtio_ccw_ioeventfd_set_disabled;

    k->ioeventfd_assign = virtio_ccw_ioeventfd_assign;

}


static void lan9118_cleanup(NetClientState *nc)

{

    lan9118_state *s = qemu_get_nic_opaque(nc);

    s->nic = NULL;

}


void pci_cirrus_vga_init(PCIBus *bus, DisplayState *ds, uint8_t *vga_ram_base,

                         unsigned long vga_ram_offset, int vga_ram_size)

{

    PCICirrusVGAState *d;

    uint8_t *pci_conf;

    CirrusVGAState *s;

    int device_id;

    device_id = CIRRUS_ID_CLGD5446;

    /* setup PCI configuration registers */

    d = (PCICirrusVGAState *)pci_register_device(bus, "Cirrus VGA",

                                                 sizeof(PCICirrusVGAState),

                                                 -1, NULL, NULL);

    pci_conf = d->dev.config;

    pci_conf[0x00] = (uint8_t) (PCI_VENDOR_CIRRUS & 0xff);

    pci_conf[0x01] = (uint8_t) (PCI_VENDOR_CIRRUS >> 8);

    pci_conf[0x02] = (uint8_t) (device_id & 0xff);

    pci_conf[0x03] = (uint8_t) (device_id >> 8);

    pci_conf[0x04] = PCI_COMMAND_IOACCESS | PCI_COMMAND_MEMACCESS;

    pci_conf[0x0a] = PCI_CLASS_SUB_VGA;

    pci_conf[0x0b] = PCI_CLASS_BASE_DISPLAY;

    pci_conf[0x0e] = PCI_CLASS_HEADERTYPE_00h;

    /* setup VGA */

    s = &d->cirrus_vga;

    vga_common_init((VGAState *)s,

                    ds, vga_ram_base, vga_ram_offset, vga_ram_size);

    cirrus_init_common(s, device_id, 1);

    s->console = graphic_console_init(s->ds, s->update, s->invalidate,

                                      s->screen_dump, s->text_update, s);

    s->pci_dev = (PCIDevice *)d;

    /* setup memory space */

    /* memory #0 LFB */

    /* memory #1 memory-mapped I/O */

    /* XXX: s->vram_size must be a power of two */

    pci_register_io_region((PCIDevice *)d, 0, 0x2000000,

			   PCI_ADDRESS_SPACE_MEM_PREFETCH, cirrus_pci_lfb_map);

    if (device_id == CIRRUS_ID_CLGD5446) {

        pci_register_io_region((PCIDevice *)d, 1, CIRRUS_PNPMMIO_SIZE,

                               PCI_ADDRESS_SPACE_MEM, cirrus_pci_mmio_map);

    }

    /* XXX: ROM BIOS */

}


static void spapr_io_write(void *opaque, hwaddr addr,

                           uint64_t data, unsigned size)

{

    switch (size) {

    case 1:

        cpu_outb(addr, data);

        return;

    case 2:

        cpu_outw(addr, data);

        return;

    case 4:

        cpu_outl(addr, data);

        return;

    }

    assert(0);

}


static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);

    int buflen = 0;

    if (req->cmd.buf[1] & 0x2) {

        /* Command support data - optional, not implemented */

        BADF("optional INQUIRY command support request not implemented\n");

        return -1;

    }

    if (req->cmd.buf[1] & 0x1) {

        /* Vital product data */

        uint8_t page_code = req->cmd.buf[2];

        if (req->cmd.xfer < 4) {

            BADF("Error: Inquiry (EVPD[%02X]) buffer size %zd is "

                 "less than 4\n", page_code, req->cmd.xfer);

            return -1;

        }

        if (bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM) {

            outbuf[buflen++] = 5;

        } else {

            outbuf[buflen++] = 0;

        }

        outbuf[buflen++] = page_code ; // this page

        outbuf[buflen++] = 0x00;

        switch (page_code) {

        case 0x00: /* Supported page codes, mandatory */

            DPRINTF("Inquiry EVPD[Supported pages] "

                    "buffer size %zd\n", req->cmd.xfer);

            outbuf[buflen++] = 4;    // number of pages

            outbuf[buflen++] = 0x00; // list of supported pages (this page)

            outbuf[buflen++] = 0x80; // unit serial number

            outbuf[buflen++] = 0x83; // device identification

            outbuf[buflen++] = 0xb0; // block device characteristics

            break;

        case 0x80: /* Device serial number, optional */

        {

            const char *serial = req->dev->conf.dinfo->serial ?

                req->dev->conf.dinfo->serial : "0";

            int l = strlen(serial);

            if (l > req->cmd.xfer)

                l = req->cmd.xfer;

            if (l > 20)

                l = 20;

            DPRINTF("Inquiry EVPD[Serial number] "

                    "buffer size %zd\n", req->cmd.xfer);

            outbuf[buflen++] = l;

            memcpy(outbuf+buflen, serial, l);

            buflen += l;

            break;

        }

        case 0x83: /* Device identification page, mandatory */

        {

            int max_len = 255 - 8;

            int id_len = strlen(bdrv_get_device_name(s->bs));

            if (id_len > max_len)

                id_len = max_len;

            DPRINTF("Inquiry EVPD[Device identification] "

                    "buffer size %zd\n", req->cmd.xfer);

            outbuf[buflen++] = 3 + id_len;

            outbuf[buflen++] = 0x2; // ASCII

            outbuf[buflen++] = 0;   // not officially assigned

            outbuf[buflen++] = 0;   // reserved

            outbuf[buflen++] = id_len; // length of data following

            memcpy(outbuf+buflen, bdrv_get_device_name(s->bs), id_len);

            buflen += id_len;

            break;

        }

        case 0xb0: /* block device characteristics */

        {

            unsigned int min_io_size = s->qdev.conf.min_io_size >> 9;

            unsigned int opt_io_size = s->qdev.conf.opt_io_size >> 9;

            /* required VPD size with unmap support */

            outbuf[3] = buflen = 0x3c;

            memset(outbuf + 4, 0, buflen - 4);

            /* optimal transfer length granularity */

            outbuf[6] = (min_io_size >> 8) & 0xff;

            outbuf[7] = min_io_size & 0xff;

            /* optimal transfer length */

            outbuf[12] = (opt_io_size >> 24) & 0xff;

            outbuf[13] = (opt_io_size >> 16) & 0xff;

            outbuf[14] = (opt_io_size >> 8) & 0xff;

            outbuf[15] = opt_io_size & 0xff;

            break;

        }

        default:

            BADF("Error: unsupported Inquiry (EVPD[%02X]) "

                 "buffer size %zd\n", page_code, req->cmd.xfer);

            return -1;

        }

        /* done with EVPD */

        return buflen;

    }

    /* Standard INQUIRY data */

    if (req->cmd.buf[2] != 0) {

        BADF("Error: Inquiry (STANDARD) page or code "

             "is non-zero [%02X]\n", req->cmd.buf[2]);

        return -1;

    }

    /* PAGE CODE == 0 */

    if (req->cmd.xfer < 5) {

        BADF("Error: Inquiry (STANDARD) buffer size %zd "

             "is less than 5\n", req->cmd.xfer);

        return -1;

    }

    buflen = req->cmd.xfer;

    if (buflen > SCSI_MAX_INQUIRY_LEN)

        buflen = SCSI_MAX_INQUIRY_LEN;

    memset(outbuf, 0, buflen);

    if (req->lun || req->cmd.buf[1] >> 5) {

        outbuf[0] = 0x7f;	/* LUN not supported */

        return buflen;

    }

    if (bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM) {

        outbuf[0] = 5;

        outbuf[1] = 0x80;

        memcpy(&outbuf[16], "QEMU CD-ROM     ", 16);

    } else {

        outbuf[0] = 0;

        memcpy(&outbuf[16], "QEMU HARDDISK   ", 16);

    }

    memcpy(&outbuf[8], "QEMU    ", 8);

    memcpy(&outbuf[32], s->version ? s->version : QEMU_VERSION, 4);

    /*

     * We claim conformance to SPC-3, which is required for guests

     * to ask for modern features like READ CAPACITY(16) or the

     * block characteristics VPD page by default.  Not all of SPC-3

     * is actually implemented, but we're good enough.

     */

    outbuf[2] = 5;

    outbuf[3] = 2; /* Format 2 */

    if (buflen > 36) {

        outbuf[4] = buflen - 5; /* Additional Length = (Len - 1) - 4 */

    } else {

        /* If the allocation length of CDB is too small,

               the additional length is not adjusted */

        outbuf[4] = 36 - 5;

    }

    /* Sync data transfer and TCQ.  */

    outbuf[7] = 0x10 | (req->bus->tcq ? 0x02 : 0);

    return buflen;

}


static AddressSpace *memory_region_to_address_space(MemoryRegion *mr)

{

    AddressSpace *as;

    while (mr->container) {

        mr = mr->container;

    }

    QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {

        if (mr == as->root) {

            return as;

        }

    }

    abort();

}


static void bastardized_rice_decompress(ALACContext *alac,

                                 int32_t *output_buffer,

                                 int output_size,

                                 int readsamplesize, /* arg_10 */

                                 int rice_initialhistory, /* arg424->b */

                                 int rice_kmodifier, /* arg424->d */

                                 int rice_historymult, /* arg424->c */

                                 int rice_kmodifier_mask /* arg424->e */

        )

{

    int output_count;

    unsigned int history = rice_initialhistory;

    int sign_modifier = 0;

    for (output_count = 0; output_count < output_size; output_count++) {

        int32_t x;

        int32_t x_modified;

        int32_t final_val;

        /* read x - number of 1s before 0 represent the rice */

        x = get_unary_0_9(&alac->gb);

        if (x > 8) { /* RICE THRESHOLD */

            /* use alternative encoding */

            x = get_bits(&alac->gb, readsamplesize);

        } else {

            /* standard rice encoding */

            int extrabits;

            int k; /* size of extra bits */

            /* read k, that is bits as is */

            k = 31 - count_leading_zeros((history >> 9) + 3);

            if (k >= rice_kmodifier)

                k = rice_kmodifier;

            if (k != 1) {

                extrabits = show_bits(&alac->gb, k);

                /* multiply x by 2^k - 1, as part of their strange algorithm */

                x = (x << k) - x;

                if (extrabits > 1) {

                    x += extrabits - 1;

                    skip_bits(&alac->gb, k);

                } else

                    skip_bits(&alac->gb, k - 1);

            }

        }

        x_modified = sign_modifier + x;

        final_val = (x_modified + 1) / 2;

        if (x_modified & 1) final_val *= -1;

        output_buffer[output_count] = final_val;

        sign_modifier = 0;

        /* now update the history */

        history += x_modified * rice_historymult

                   - ((history * rice_historymult) >> 9);

        if (x_modified > 0xffff)

            history = 0xffff;

        /* special case: there may be compressed blocks of 0 */

        if ((history < 128) && (output_count+1 < output_size)) {

            int block_size;

            sign_modifier = 1;

            x = get_unary_0_9(&alac->gb);

            if (x > 8) {

                block_size = get_bits(&alac->gb, 16);

            } else {

                int k;

                int extrabits;

                k = count_leading_zeros(history) + ((history + 16) >> 6 /* / 64 */) - 24;

                extrabits = show_bits(&alac->gb, k);

                block_size = (((1 << k) - 1) & rice_kmodifier_mask) * x

                           + extrabits - 1;

                if (extrabits < 2) {

                    x = 1 - extrabits;

                    block_size += x;

                    skip_bits(&alac->gb, k - 1);

                } else {

                    skip_bits(&alac->gb, k);

                }

            }

            if (block_size > 0) {

                memset(&output_buffer[output_count+1], 0, block_size * 4);

                output_count += block_size;

            }

            if (block_size > 0xffff)

                sign_modifier = 0;

            history = 0;

        }

    }

}


void OPPROTO op_int_im(void)

{

    EIP = PARAM1;

    raise_exception(EXCP0D_GPF);

}


static inline TCGv gen_ld16s(TCGv addr, int index)

{

    TCGv tmp = new_tmp();

    tcg_gen_qemu_ld16s(tmp, addr, index);

    return tmp;

}


static av_cold int vc2_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                                      const AVFrame *frame, int *got_packet_ptr)

{

    int ret;

    int max_frame_bytes, sig_size = 256;

    VC2EncContext *s = avctx->priv_data;

    const char aux_data[] = LIBAVCODEC_IDENT;

    const int aux_data_size = sizeof(aux_data);

    const int header_size = 100 + aux_data_size;

    int64_t r_bitrate = avctx->bit_rate >> (s->interlaced);

    s->avctx = avctx;

    s->size_scaler = 1;

    s->prefix_bytes = 0;

    s->last_parse_code = 0;

    s->next_parse_offset = 0;

    /* Rate control */

    max_frame_bytes = (av_rescale(r_bitrate, s->avctx->time_base.num,

                                  s->avctx->time_base.den) >> 3) - header_size;

    /* Find an appropriate size scaler */

    while (sig_size > 255) {

        s->slice_max_bytes = FFALIGN(av_rescale(max_frame_bytes, 1,

                                     s->num_x*s->num_y), s->size_scaler);

        s->slice_max_bytes += 4 + s->prefix_bytes;

        sig_size = s->slice_max_bytes/s->size_scaler; /* Signalled slize size */

        s->size_scaler <<= 1;

    }

    s->slice_min_bytes = s->slice_max_bytes - s->slice_max_bytes*(s->tolerance/100.0f);

    ret = ff_alloc_packet2(avctx, avpkt, max_frame_bytes*3, 0);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");

        return ret;

    } else {

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

    }

    encode_frame(s, frame, aux_data, s->interlaced);

    if (s->interlaced)

        encode_frame(s, frame, NULL, 2);

    flush_put_bits(&s->pb);

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

    *got_packet_ptr = 1;

    return 0;

}


static inline int xhci_running(XHCIState *xhci)

{

    return !(xhci->usbsts & USBSTS_HCH) && !xhci->intr[0].er_full;

}


static int local_utimensat(FsContext *s, V9fsPath *fs_path,

                           const struct timespec *buf)

{

    char *buffer;

    int ret;

    char *path = fs_path->data;

    buffer = rpath(s, path);

    ret = qemu_utimens(buffer, buf);

    g_free(buffer);

    return ret;

}


static int qemu_chr_open_stdio(QemuOpts *opts, CharDriverState **_chr)

{

    CharDriverState *chr;

    if (stdio_nb_clients >= STDIO_MAX_CLIENTS) {

        return -EBUSY;

    }

    if (stdio_nb_clients == 0) {

        old_fd0_flags = fcntl(0, F_GETFL);

        tcgetattr (0, &oldtty);

        fcntl(0, F_SETFL, O_NONBLOCK);

        atexit(term_exit);

    }

    chr = qemu_chr_open_fd(0, 1);

    chr->chr_close = qemu_chr_close_stdio;

    chr->chr_set_echo = qemu_chr_set_echo_stdio;

    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);

    stdio_nb_clients++;

    stdio_allow_signal = qemu_opt_get_bool(opts, "signal",

                                           display_type != DT_NOGRAPHIC);

    qemu_chr_fe_set_echo(chr, false);

    *_chr = chr;

    return 0;

}


static int qemu_gluster_reopen_prepare(BDRVReopenState *state,

                                       BlockReopenQueue *queue, Error **errp)

{

    int ret = 0;

    BDRVGlusterReopenState *reop_s;

    GlusterConf *gconf = NULL;

    int open_flags = 0;

    assert(state != NULL);

    assert(state->bs != NULL);

    state->opaque = g_malloc0(sizeof(BDRVGlusterReopenState));

    reop_s = state->opaque;

    qemu_gluster_parse_flags(state->flags, &open_flags);

    gconf = g_malloc0(sizeof(GlusterConf));

    reop_s->glfs = qemu_gluster_init(gconf, state->bs->filename, errp);

    if (reop_s->glfs == NULL) {

        ret = -errno;

        goto exit;

    }

    reop_s->fd = glfs_open(reop_s->glfs, gconf->image, open_flags);

    if (reop_s->fd == NULL) {

        /* reops->glfs will be cleaned up in _abort */

        ret = -errno;

        goto exit;

    }

exit:

    /* state->opaque will be freed in either the _abort or _commit */

    qemu_gluster_gconf_free(gconf);

    return ret;

}


static void cabac_reinit(HEVCLocalContext *lc)

{

    skip_bytes(&lc->cc, 0);

}


static int write_option(void *optctx, const OptionDef *po, const char *opt,

                        const char *arg)

{

    /* new-style options contain an offset into optctx, old-style address of

     * a global var*/

    void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?

                (uint8_t *)optctx + po->u.off : po->u.dst_ptr;

    int *dstcount;

    if (po->flags & OPT_SPEC) {

        SpecifierOpt **so = dst;

        char *p = strchr(opt, ':');

        dstcount = (int *)(so + 1);

        *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);

        (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");

        dst = &(*so)[*dstcount - 1].u;

    }

    if (po->flags & OPT_STRING) {

        char *str;

        str = av_strdup(arg);

        av_freep(dst);

        *(char **)dst = str;

    } else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {

        *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);

    } else if (po->flags & OPT_INT64) {

        *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);

    } else if (po->flags & OPT_TIME) {

        *(int64_t *)dst = parse_time_or_die(opt, arg, 1);

    } else if (po->flags & OPT_FLOAT) {

        *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);

    } else if (po->flags & OPT_DOUBLE) {

        *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);

    } else if (po->u.func_arg) {

        int ret = po->u.func_arg(optctx, opt, arg);

        if (ret < 0) {

            av_log(NULL, AV_LOG_ERROR,

                   "Failed to set value '%s' for option '%s'\n", arg, opt);

            return ret;

        }

    }

    if (po->flags & OPT_EXIT)

        exit(0);

    return 0;

}


static uint32_t serial_ioport_read(void *opaque, uint32_t addr)

{

    SerialState *s = opaque;

    uint32_t ret;

    addr &= 7;

    switch(addr) {

    default:

    case 0:

        if (s->lcr & UART_LCR_DLAB) {

            ret = s->divider & 0xff;

        } else {

            ret = s->rbr;

            s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);

            serial_update_irq(s);

            if (!(s->mcr & UART_MCR_LOOP)) {

                /* in loopback mode, don't receive any data */

                qemu_chr_accept_input(s->chr);

            }

        }

        break;

    case 1:

        if (s->lcr & UART_LCR_DLAB) {

            ret = (s->divider >> 8) & 0xff;

        } else {

            ret = s->ier;

        }

        break;

    case 2:

        ret = s->iir;

        /* reset THR pending bit */

        if ((ret & 0x7) == UART_IIR_THRI)

            s->thr_ipending = 0;

        serial_update_irq(s);

        break;

    case 3:

        ret = s->lcr;

        break;

    case 4:

        ret = s->mcr;

        break;

    case 5:

        ret = s->lsr;

        break;

    case 6:

        if (s->mcr & UART_MCR_LOOP) {

            /* in loopback, the modem output pins are connected to the

               inputs */

            ret = (s->mcr & 0x0c) << 4;

            ret |= (s->mcr & 0x02) << 3;

            ret |= (s->mcr & 0x01) << 5;

        } else {

            ret = s->msr;

        }

        break;

    case 7:

        ret = s->scr;

        break;

    }

#ifdef DEBUG_SERIAL

    printf("serial: read addr=0x%02x val=0x%02x\n", addr, ret);

#endif

    return ret;

}


e1000e_init_msix(E1000EState *s)

{

    PCIDevice *d = PCI_DEVICE(s);

    int res = msix_init(PCI_DEVICE(s), E1000E_MSIX_VEC_NUM,

                        &s->msix,

                        E1000E_MSIX_IDX, E1000E_MSIX_TABLE,

                        &s->msix,

                        E1000E_MSIX_IDX, E1000E_MSIX_PBA,

                        0xA0);

    if (res < 0) {

        trace_e1000e_msix_init_fail(res);

    } else {

        if (!e1000e_use_msix_vectors(s, E1000E_MSIX_VEC_NUM)) {

            msix_uninit(d, &s->msix, &s->msix);

        }

    }

}


static int RENAME(resample_linear)(ResampleContext *c,

                                   DELEM *dst, const DELEM *src,

                                   int n, int update_ctx)

{

    int dst_index;

    int index= c->index;

    int frac= c->frac;

    int sample_index = index >> c->phase_shift;

#if FILTER_SHIFT == 0

    double inv_src_incr = 1.0 / c->src_incr;

#endif

    index &= c->phase_mask;

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

        FELEM *filter = ((FELEM *) c->filter_bank) + c->filter_alloc * index;

        FELEM2 val=0, v2 = 0;

        int i;

        for (i = 0; i < c->filter_length; i++) {

            val += src[sample_index + i] * (FELEM2)filter[i];

            v2  += src[sample_index + i] * (FELEM2)filter[i + c->filter_alloc];

        }

#ifdef FELEML

        val += (v2 - val) * (FELEML) frac / c->src_incr;

#else

#    if FILTER_SHIFT == 0

        val += (v2 - val) * inv_src_incr * frac;

#    else

        val += (v2 - val) / c->src_incr * frac;

#    endif

#endif

        OUT(dst[dst_index], val);

        frac += c->dst_incr_mod;

        index += c->dst_incr_div;

        if (frac >= c->src_incr) {

            frac -= c->src_incr;

            index++;

        }

        sample_index += index >> c->phase_shift;

        index &= c->phase_mask;

    }

    if(update_ctx){

        c->frac= frac;

        c->index= index;

    }

    return sample_index;

}


int ff_h263_resync(MpegEncContext *s){

    int left, ret;

    if(s->codec_id==CODEC_ID_MPEG4)

        skip_bits1(&s->gb);

    align_get_bits(&s->gb);

    if(show_bits(&s->gb, 16)==0){

        if(s->codec_id==CODEC_ID_MPEG4)

            ret= mpeg4_decode_video_packet_header(s);

        else

            ret= h263_decode_gob_header(s);

        if(ret>=0)

            return 0;

    }

    //ok, its not where its supposed to be ...

    s->gb= s->last_resync_gb;

    align_get_bits(&s->gb);

    left= s->gb.size*8 - get_bits_count(&s->gb);

    for(;left>16+1+5+5; left-=8){

        if(show_bits(&s->gb, 16)==0){

            GetBitContext bak= s->gb;

            if(s->codec_id==CODEC_ID_MPEG4)

                ret= mpeg4_decode_video_packet_header(s);

            else

                ret= h263_decode_gob_header(s);

            if(ret>=0)

                return 0;

            s->gb= bak;

        }

        skip_bits(&s->gb, 8);

    }

    return -1;

}


static void aio_write_done(void *opaque, int ret)

{

    struct aio_ctx *ctx = opaque;

    struct timeval t2;

    gettimeofday(&t2, NULL);

    if (ret < 0) {

        printf("aio_write failed: %s\n", strerror(-ret));

        goto out;

    }

    if (ctx->qflag) {

        goto out;

    }

    /* Finally, report back -- -C gives a parsable format */

    t2 = tsub(t2, ctx->t1);

    print_report("wrote", &t2, ctx->offset, ctx->qiov.size,

                 ctx->qiov.size, 1, ctx->Cflag);

out:

    qemu_io_free(ctx->buf);

    g_free(ctx);

}


static void add_pixels_clamped2_c(const DCTELEM *block, uint8_t *restrict pixels,

                          int line_size)

{

    int i;

    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    /* read the pixels */

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

        pixels[0] = cm[pixels[0] + block[0]];

        pixels[1] = cm[pixels[1] + block[1]];

        pixels += line_size;

        block += 8;

    }

}


static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)

{

    Jpeg2000CodingStyle *codsty = s->codsty;

    Jpeg2000QuantStyle *qntsty  = s->qntsty;

    uint8_t *properties         = s->properties;

    for (;;) {

        int len, ret = 0;

        uint16_t marker;

        int oldpos;

        if (bytestream2_get_bytes_left(&s->g) < 2) {

            av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");

            break;

        }

        marker = bytestream2_get_be16u(&s->g);

        oldpos = bytestream2_tell(&s->g);

        if (marker == JPEG2000_EOC)

            break;

        if (bytestream2_get_bytes_left(&s->g) < 2)

            return AVERROR_INVALIDDATA;

        len = bytestream2_get_be16u(&s->g);

        switch (marker) {

        case JPEG2000_SIZ:

            ret = get_siz(s);

            break;

        case JPEG2000_COC:

            ret = get_coc(s, codsty, properties);

            break;

        case JPEG2000_COD:

            ret = get_cod(s, codsty, properties);

            break;

        case JPEG2000_QCC:

            ret = get_qcc(s, len, qntsty, properties);

            break;

        case JPEG2000_QCD:

            ret = get_qcd(s, len, qntsty, properties);

            break;

        case JPEG2000_SOT:

            ret = get_sot(s, len);

            break;

        case JPEG2000_COM:

            // the comment is ignored

            bytestream2_skip(&s->g, len - 2);

            break;

        case JPEG2000_TLM:

            // Tile-part lengths

            ret = get_tlm(s, len);

            break;

        default:

            av_log(s->avctx, AV_LOG_ERROR,

                   "unsupported marker 0x%.4X at pos 0x%X\n",

                   marker, bytestream2_tell(&s->g) - 4);

            bytestream2_skip(&s->g, len - 2);

            break;

        }

        if (((bytestream2_tell(&s->g) - oldpos != len) && (marker != JPEG2000_SOT)) || ret) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "error during processing marker segment %.4x\n", marker);

            return ret ? ret : -1;

        }

    }

    return 0;

}


static void ehci_reset(void *opaque)

{

    EHCIState *s = opaque;

    int i;

    USBDevice *devs[NB_PORTS];

    trace_usb_ehci_reset();

    /*

     * Do the detach before touching portsc, so that it correctly gets send to

     * us or to our companion based on PORTSC_POWNER before the reset.

     */

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

        devs[i] = s->ports[i].dev;

        if (devs[i] && devs[i]->attached) {

            usb_detach(&s->ports[i]);

        }

    }

    memset(&s->mmio[OPREGBASE], 0x00, MMIO_SIZE - OPREGBASE);

    s->usbcmd = NB_MAXINTRATE << USBCMD_ITC_SH;

    s->usbsts = USBSTS_HALT;

    s->usbsts_pending = 0;

    s->usbsts_frindex = 0;

    s->astate = EST_INACTIVE;

    s->pstate = EST_INACTIVE;

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

        if (s->companion_ports[i]) {

            s->portsc[i] = PORTSC_POWNER | PORTSC_PPOWER;

        } else {

            s->portsc[i] = PORTSC_PPOWER;

        }

        if (devs[i] && devs[i]->attached) {

            usb_attach(&s->ports[i]);

            usb_device_reset(devs[i]);

        }

    }

    ehci_queues_rip_all(s, 0);

    ehci_queues_rip_all(s, 1);

    qemu_del_timer(s->frame_timer);

    qemu_bh_cancel(s->async_bh);

}


void OPPROTO op_POWER_slq (void)

{

    uint32_t msk = -1, tmp;

    msk = msk << (T1 & 0x1FUL);

    if (T1 & 0x20UL)

        msk = ~msk;

    T1 &= 0x1FUL;

    tmp = rotl32(T0, T1);

    T0 = tmp & msk;

    env->spr[SPR_MQ] = tmp;

    RETURN();

}


int ff_MPV_lowest_referenced_row(MpegEncContext *s, int dir)

{

    int my_max = INT_MIN, my_min = INT_MAX, qpel_shift = !s->quarter_sample;

    int my, off, i, mvs;

    if (s->picture_structure != PICT_FRAME) goto unhandled;

    switch (s->mv_type) {

        case MV_TYPE_16X16:

            mvs = 1;

            break;

        case MV_TYPE_16X8:

            mvs = 2;

            break;

        case MV_TYPE_8X8:

            mvs = 4;

            break;

        default:

            goto unhandled;

    }

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

        my = s->mv[dir][i][1]<<qpel_shift;

        my_max = FFMAX(my_max, my);

        my_min = FFMIN(my_min, my);

    }

    off = (FFMAX(-my_min, my_max) + 63) >> 6;

    return FFMIN(FFMAX(s->mb_y + off, 0), s->mb_height-1);

unhandled:

    return s->mb_height-1;

}


static inline int snake_search(MpegEncContext * s, int *best, int dmin,

                                       UINT8 *new_pic, UINT8 *old_pic, int pic_stride,

                                       int pred_x, int pred_y, UINT16 *mv_penalty, int quant,

                                       int xmin, int ymin, int xmax, int ymax, int shift)

{

    int dir=0;

    int c=1;

    static int x_dir[8]= {1,1,0,-1,-1,-1, 0, 1};

    static int y_dir[8]= {0,1,1, 1, 0,-1,-1,-1};

    int fails=0;

    int last_d[2]={dmin, dmin};

/*static int good=0;

static int bad=0;

static int point=0;

point++;

if(256*256*256*64%point==0)

{

    printf("%d %d %d\n", good, bad, point);

}*/

    for(;;){

        int x= best[0];

        int y= best[1];

        int d;

        x+=x_dir[dir];

        y+=y_dir[dir];

        if(x>=xmin && x<=xmax && y>=ymin && y<=ymax){

            d = pix_abs16x16(new_pic, old_pic + (x) + (y)*pic_stride, pic_stride);

            d += (mv_penalty[((x)<<shift)-pred_x] + mv_penalty[((y)<<shift)-pred_y])*quant;

        }else{

            d = dmin + 10000; //FIXME smarter boundary handling

        }

        if(d<dmin){

            best[0]=x;

            best[1]=y;

            dmin=d;

            if(last_d[1] - last_d[0] > last_d[0] - d) c= -c;

            dir+=c;

            fails=0;

//good++;

            last_d[1]=last_d[0];

            last_d[0]=d;

        }else{

//bad++;

            if(fails){

                if(fails>=3) return dmin;

            }else{

                c= -c;

            }

            dir+=c*2;

            fails++;

        }

        dir&=7;

    }

}


static int qio_channel_command_close(QIOChannel *ioc,

                                     Error **errp)

{

    QIOChannelCommand *cioc = QIO_CHANNEL_COMMAND(ioc);

    int rv = 0;

    /* We close FDs before killing, because that

     * gives a better chance of clean shutdown

     */

    if (close(cioc->writefd) < 0) {

        rv = -1;

    }

    if (close(cioc->readfd) < 0) {

        rv = -1;

    }

#ifndef WIN32

    if (qio_channel_command_abort(cioc, errp) < 0) {

        return -1;

    }

#endif

    if (rv < 0) {

        error_setg_errno(errp, errno, "%s",

                         "Unable to close command");

    }

    return rv;

}


AVFixedDSPContext * avpriv_alloc_fixed_dsp(int bit_exact)
{
    AVFixedDSPContext * fdsp = av_malloc(sizeof(AVFixedDSPContext));
    fdsp->vector_fmul_window_scaled = vector_fmul_window_fixed_scaled_c;
    fdsp->vector_fmul_window = vector_fmul_window_fixed_c;
    return fdsp;
}


static av_always_inline void encode_mb_internal(MpegEncContext *s,

                                                int motion_x, int motion_y,

                                                int mb_block_height,

                                                int mb_block_count)

{

    int16_t weight[8][64];

    int16_t orig[8][64];

    const int mb_x = s->mb_x;

    const int mb_y = s->mb_y;

    int i;

    int skip_dct[8];

    int dct_offset = s->linesize * 8; // default for progressive frames

    uint8_t *ptr_y, *ptr_cb, *ptr_cr;

    ptrdiff_t wrap_y, wrap_c;

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

        skip_dct[i] = s->skipdct;

    if (s->adaptive_quant) {

        const int last_qp = s->qscale;

        const int mb_xy = mb_x + mb_y * s->mb_stride;

        s->lambda = s->lambda_table[mb_xy];

        update_qscale(s);

        if (!(s->mpv_flags & FF_MPV_FLAG_QP_RD)) {

            s->qscale = s->current_picture_ptr->qscale_table[mb_xy];

            s->dquant = s->qscale - last_qp;

            if (s->out_format == FMT_H263) {

                s->dquant = av_clip(s->dquant, -2, 2);

                if (s->codec_id == AV_CODEC_ID_MPEG4) {

                    if (!s->mb_intra) {

                        if (s->pict_type == AV_PICTURE_TYPE_B) {

                            if (s->dquant & 1 || s->mv_dir & MV_DIRECT)

                                s->dquant = 0;

                        }

                        if (s->mv_type == MV_TYPE_8X8)

                            s->dquant = 0;

                    }

                }

            }

        }

        ff_set_qscale(s, last_qp + s->dquant);

    } else if (s->mpv_flags & FF_MPV_FLAG_QP_RD)

        ff_set_qscale(s, s->qscale + s->dquant);

    wrap_y = s->linesize;

    wrap_c = s->uvlinesize;

    ptr_y  = s->new_picture.f.data[0] +

             (mb_y * 16 * wrap_y)              + mb_x * 16;

    ptr_cb = s->new_picture.f.data[1] +

             (mb_y * mb_block_height * wrap_c) + mb_x * 8;

    ptr_cr = s->new_picture.f.data[2] +

             (mb_y * mb_block_height * wrap_c) + mb_x * 8;

    if (mb_x * 16 + 16 > s->width || mb_y * 16 + 16 > s->height) {

        uint8_t *ebuf = s->edge_emu_buffer + 32;

        s->vdsp.emulated_edge_mc(ebuf, ptr_y,

                                 wrap_y, wrap_y,

                                 16, 16, mb_x * 16, mb_y * 16,

                                 s->width, s->height);

        ptr_y = ebuf;

        s->vdsp.emulated_edge_mc(ebuf + 18 * wrap_y, ptr_cb,

                                 wrap_c, wrap_c,

                                 8, mb_block_height, mb_x * 8, mb_y * 8,

                                 s->width >> 1, s->height >> 1);

        ptr_cb = ebuf + 18 * wrap_y;

        s->vdsp.emulated_edge_mc(ebuf + 18 * wrap_y + 8, ptr_cr,

                                 wrap_c, wrap_c,

                                 8, mb_block_height, mb_x * 8, mb_y * 8,

                                 s->width >> 1, s->height >> 1);

        ptr_cr = ebuf + 18 * wrap_y + 8;

    }

    if (s->mb_intra) {

        if (s->flags & CODEC_FLAG_INTERLACED_DCT) {

            int progressive_score, interlaced_score;

            s->interlaced_dct = 0;

            progressive_score = s->dsp.ildct_cmp[4](s, ptr_y,

                                                    NULL, wrap_y, 8) +

                                s->dsp.ildct_cmp[4](s, ptr_y + wrap_y * 8,

                                                    NULL, wrap_y, 8) - 400;

            if (progressive_score > 0) {

                interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y,

                                                       NULL, wrap_y * 2, 8) +

                                   s->dsp.ildct_cmp[4](s, ptr_y + wrap_y,

                                                       NULL, wrap_y * 2, 8);

                if (progressive_score > interlaced_score) {

                    s->interlaced_dct = 1;

                    dct_offset = wrap_y;

                    wrap_y <<= 1;

                    if (s->chroma_format == CHROMA_422)

                        wrap_c <<= 1;

                }

            }

        }

        s->dsp.get_pixels(s->block[0], ptr_y                  , wrap_y);

        s->dsp.get_pixels(s->block[1], ptr_y              + 8 , wrap_y);

        s->dsp.get_pixels(s->block[2], ptr_y + dct_offset     , wrap_y);

        s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8 , wrap_y);

        if (s->flags & CODEC_FLAG_GRAY) {

            skip_dct[4] = 1;

            skip_dct[5] = 1;

        } else {

            s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);

            s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);

            if (!s->chroma_y_shift) { /* 422 */

                s->dsp.get_pixels(s->block[6],

                                  ptr_cb + (dct_offset >> 1), wrap_c);

                s->dsp.get_pixels(s->block[7],

                                  ptr_cr + (dct_offset >> 1), wrap_c);

            }

        }

    } else {

        op_pixels_func (*op_pix)[4];

        qpel_mc_func (*op_qpix)[16];

        uint8_t *dest_y, *dest_cb, *dest_cr;

        dest_y  = s->dest[0];

        dest_cb = s->dest[1];

        dest_cr = s->dest[2];

        if ((!s->no_rounding) || s->pict_type == AV_PICTURE_TYPE_B) {

            op_pix  = s->hdsp.put_pixels_tab;

            op_qpix = s->dsp.put_qpel_pixels_tab;

        } else {

            op_pix  = s->hdsp.put_no_rnd_pixels_tab;

            op_qpix = s->dsp.put_no_rnd_qpel_pixels_tab;

        }

        if (s->mv_dir & MV_DIR_FORWARD) {

            ff_MPV_motion(s, dest_y, dest_cb, dest_cr, 0,

                          s->last_picture.f.data,

                          op_pix, op_qpix);

            op_pix  = s->hdsp.avg_pixels_tab;

            op_qpix = s->dsp.avg_qpel_pixels_tab;

        }

        if (s->mv_dir & MV_DIR_BACKWARD) {

            ff_MPV_motion(s, dest_y, dest_cb, dest_cr, 1,

                          s->next_picture.f.data,

                          op_pix, op_qpix);

        }

        if (s->flags & CODEC_FLAG_INTERLACED_DCT) {

            int progressive_score, interlaced_score;

            s->interlaced_dct = 0;

            progressive_score = s->dsp.ildct_cmp[0](s, dest_y,

                                                    ptr_y,              wrap_y,

                                                    8) +

                                s->dsp.ildct_cmp[0](s, dest_y + wrap_y * 8,

                                                    ptr_y + wrap_y * 8, wrap_y,

                                                    8) - 400;

            if (s->avctx->ildct_cmp == FF_CMP_VSSE)

                progressive_score -= 400;

            if (progressive_score > 0) {

                interlaced_score = s->dsp.ildct_cmp[0](s, dest_y,

                                                       ptr_y,

                                                       wrap_y * 2, 8) +

                                   s->dsp.ildct_cmp[0](s, dest_y + wrap_y,

                                                       ptr_y + wrap_y,

                                                       wrap_y * 2, 8);

                if (progressive_score > interlaced_score) {

                    s->interlaced_dct = 1;

                    dct_offset = wrap_y;

                    wrap_y <<= 1;

                    if (s->chroma_format == CHROMA_422)

                        wrap_c <<= 1;

                }

            }

        }

        s->dsp.diff_pixels(s->block[0], ptr_y, dest_y, wrap_y);

        s->dsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);

        s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset,

                           dest_y + dct_offset, wrap_y);

        s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8,

                           dest_y + dct_offset + 8, wrap_y);

        if (s->flags & CODEC_FLAG_GRAY) {

            skip_dct[4] = 1;

            skip_dct[5] = 1;

        } else {

            s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);

            s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);

            if (!s->chroma_y_shift) { /* 422 */

                s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset >> 1),

                                   dest_cb + (dct_offset >> 1), wrap_c);

                s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset >> 1),

                                   dest_cr + (dct_offset >> 1), wrap_c);

            }

        }

        /* pre quantization */

        if (s->current_picture.mc_mb_var[s->mb_stride * mb_y + mb_x] <

                2 * s->qscale * s->qscale) {

            // FIXME optimize

            if (s->dsp.sad[1](NULL, ptr_y , dest_y,

                              wrap_y, 8) < 20 * s->qscale)

                skip_dct[0] = 1;

            if (s->dsp.sad[1](NULL, ptr_y + 8,

                              dest_y + 8, wrap_y, 8) < 20 * s->qscale)

                skip_dct[1] = 1;

            if (s->dsp.sad[1](NULL, ptr_y + dct_offset,

                              dest_y + dct_offset, wrap_y, 8) < 20 * s->qscale)

                skip_dct[2] = 1;

            if (s->dsp.sad[1](NULL, ptr_y + dct_offset + 8,

                              dest_y + dct_offset + 8,

                              wrap_y, 8) < 20 * s->qscale)

                skip_dct[3] = 1;

            if (s->dsp.sad[1](NULL, ptr_cb, dest_cb,

                              wrap_c, 8) < 20 * s->qscale)

                skip_dct[4] = 1;

            if (s->dsp.sad[1](NULL, ptr_cr, dest_cr,

                              wrap_c, 8) < 20 * s->qscale)

                skip_dct[5] = 1;

            if (!s->chroma_y_shift) { /* 422 */

                if (s->dsp.sad[1](NULL, ptr_cb + (dct_offset >> 1),

                                  dest_cb + (dct_offset >> 1),

                                  wrap_c, 8) < 20 * s->qscale)

                    skip_dct[6] = 1;

                if (s->dsp.sad[1](NULL, ptr_cr + (dct_offset >> 1),

                                  dest_cr + (dct_offset >> 1),

                                  wrap_c, 8) < 20 * s->qscale)

                    skip_dct[7] = 1;

            }

        }

    }

    if (s->quantizer_noise_shaping) {

        if (!skip_dct[0])

            get_visual_weight(weight[0], ptr_y                 , wrap_y);

        if (!skip_dct[1])

            get_visual_weight(weight[1], ptr_y              + 8, wrap_y);

        if (!skip_dct[2])

            get_visual_weight(weight[2], ptr_y + dct_offset    , wrap_y);

        if (!skip_dct[3])

            get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);

        if (!skip_dct[4])

            get_visual_weight(weight[4], ptr_cb                , wrap_c);

        if (!skip_dct[5])

            get_visual_weight(weight[5], ptr_cr                , wrap_c);

        if (!s->chroma_y_shift) { /* 422 */

            if (!skip_dct[6])

                get_visual_weight(weight[6], ptr_cb + (dct_offset >> 1),

                                  wrap_c);

            if (!skip_dct[7])

                get_visual_weight(weight[7], ptr_cr + (dct_offset >> 1),

                                  wrap_c);

        }

        memcpy(orig[0], s->block[0], sizeof(int16_t) * 64 * mb_block_count);

    }

    /* DCT & quantize */

    assert(s->out_format != FMT_MJPEG || s->qscale == 8);

    {

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

            if (!skip_dct[i]) {

                int overflow;

                s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);

                // FIXME we could decide to change to quantizer instead of

                // clipping

                // JS: I don't think that would be a good idea it could lower

                //     quality instead of improve it. Just INTRADC clipping

                //     deserves changes in quantizer

                if (overflow)

                    clip_coeffs(s, s->block[i], s->block_last_index[i]);

            } else

                s->block_last_index[i] = -1;

        }

        if (s->quantizer_noise_shaping) {

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

                if (!skip_dct[i]) {

                    s->block_last_index[i] =

                        dct_quantize_refine(s, s->block[i], weight[i],

                                            orig[i], i, s->qscale);

                }

            }

        }

        if (s->luma_elim_threshold && !s->mb_intra)

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

                dct_single_coeff_elimination(s, i, s->luma_elim_threshold);

        if (s->chroma_elim_threshold && !s->mb_intra)

            for (i = 4; i < mb_block_count; i++)

                dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);

        if (s->mpv_flags & FF_MPV_FLAG_CBP_RD) {

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

                if (s->block_last_index[i] == -1)

                    s->coded_score[i] = INT_MAX / 256;

            }

        }

    }

    if ((s->flags & CODEC_FLAG_GRAY) && s->mb_intra) {

        s->block_last_index[4] =

        s->block_last_index[5] = 0;

        s->block[4][0] =

        s->block[5][0] = (1024 + s->c_dc_scale / 2) / s->c_dc_scale;

    }

    // non c quantize code returns incorrect block_last_index FIXME

    if (s->alternate_scan && s->dct_quantize != ff_dct_quantize_c) {

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

            int j;

            if (s->block_last_index[i] > 0) {

                for (j = 63; j > 0; j--) {

                    if (s->block[i][s->intra_scantable.permutated[j]])

                        break;

                }

                s->block_last_index[i] = j;

            }

        }

    }

    /* huffman encode */

    switch(s->codec_id){ //FIXME funct ptr could be slightly faster

    case AV_CODEC_ID_MPEG1VIDEO:

    case AV_CODEC_ID_MPEG2VIDEO:

        if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)

            ff_mpeg1_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case AV_CODEC_ID_MPEG4:

        if (CONFIG_MPEG4_ENCODER)

            ff_mpeg4_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case AV_CODEC_ID_MSMPEG4V2:

    case AV_CODEC_ID_MSMPEG4V3:

    case AV_CODEC_ID_WMV1:

        if (CONFIG_MSMPEG4_ENCODER)

            ff_msmpeg4_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case AV_CODEC_ID_WMV2:

        if (CONFIG_WMV2_ENCODER)

            ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case AV_CODEC_ID_H261:

        if (CONFIG_H261_ENCODER)

            ff_h261_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case AV_CODEC_ID_H263:

    case AV_CODEC_ID_H263P:

    case AV_CODEC_ID_FLV1:

    case AV_CODEC_ID_RV10:

    case AV_CODEC_ID_RV20:

        if (CONFIG_H263_ENCODER)

            ff_h263_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case AV_CODEC_ID_MJPEG:

        if (CONFIG_MJPEG_ENCODER)

            ff_mjpeg_encode_mb(s, s->block);

        break;

    default:

        assert(0);

    }

}


void sh_intc_register_sources(struct intc_desc *desc,

			      struct intc_vect *vectors,

			      int nr_vectors,

			      struct intc_group *groups,

			      int nr_groups)

{

    unsigned int i, k;

    struct intc_source *s;

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

	struct intc_vect *vect = vectors + i;

	sh_intc_register_source(desc, vect->enum_id, groups, nr_groups);

	s = sh_intc_source(desc, vect->enum_id);

	if (s)

	    s->vect = vect->vect;

#ifdef DEBUG_INTC_SOURCES

	printf("sh_intc: registered source %d -> 0x%04x (%d/%d)\n",

	       vect->enum_id, s->vect, s->enable_count, s->enable_max);

#endif

    }

    if (groups) {

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

	    struct intc_group *gr = groups + i;

	    s = sh_intc_source(desc, gr->enum_id);

	    s->next_enum_id = gr->enum_ids[0];

	    for (k = 1; k < ARRAY_SIZE(gr->enum_ids); k++) {

                if (!gr->enum_ids[k])

                    continue;

		s = sh_intc_source(desc, gr->enum_ids[k - 1]);

		s->next_enum_id = gr->enum_ids[k];

	    }

#ifdef DEBUG_INTC_SOURCES

	    printf("sh_intc: registered group %d (%d/%d)\n",

		   gr->enum_id, s->enable_count, s->enable_max);

#endif

	}

    }

}


void sparc64_get_context(CPUSPARCState *env)

{

    abi_ulong ucp_addr;

    struct target_ucontext *ucp;

    target_mc_gregset_t *grp;

    target_mcontext_t *mcp;

    abi_ulong fp, i7, w_addr;

    int err;

    unsigned int i;

    target_sigset_t target_set;

    sigset_t set;

    ucp_addr = env->regwptr[UREG_I0];

    if (!lock_user_struct(VERIFY_WRITE, ucp, ucp_addr, 0)) {

        goto do_sigsegv;

    }

    mcp = &ucp->tuc_mcontext;

    grp = &mcp->mc_gregs;

    /* Skip over the trap instruction, first. */

    env->pc = env->npc;

    env->npc += 4;

    err = 0;

    do_sigprocmask(0, NULL, &set);

    host_to_target_sigset_internal(&target_set, &set);

    if (TARGET_NSIG_WORDS == 1) {

        __put_user(target_set.sig[0],

                   (abi_ulong *)&ucp->tuc_sigmask);

    } else {

        abi_ulong *src, *dst;

        src = target_set.sig;

        dst = ucp->tuc_sigmask.sig;

        for (i = 0; i < TARGET_NSIG_WORDS; i++, dst++, src++) {

            __put_user(*src, dst);

        }

        if (err)

            goto do_sigsegv;

    }

    /* XXX: tstate must be saved properly */

    //    __put_user(env->tstate, &((*grp)[MC_TSTATE]));

    __put_user(env->pc, &((*grp)[MC_PC]));

    __put_user(env->npc, &((*grp)[MC_NPC]));

    __put_user(env->y, &((*grp)[MC_Y]));

    __put_user(env->gregs[1], &((*grp)[MC_G1]));

    __put_user(env->gregs[2], &((*grp)[MC_G2]));

    __put_user(env->gregs[3], &((*grp)[MC_G3]));

    __put_user(env->gregs[4], &((*grp)[MC_G4]));

    __put_user(env->gregs[5], &((*grp)[MC_G5]));

    __put_user(env->gregs[6], &((*grp)[MC_G6]));

    __put_user(env->gregs[7], &((*grp)[MC_G7]));

    __put_user(env->regwptr[UREG_I0], &((*grp)[MC_O0]));

    __put_user(env->regwptr[UREG_I1], &((*grp)[MC_O1]));

    __put_user(env->regwptr[UREG_I2], &((*grp)[MC_O2]));

    __put_user(env->regwptr[UREG_I3], &((*grp)[MC_O3]));

    __put_user(env->regwptr[UREG_I4], &((*grp)[MC_O4]));

    __put_user(env->regwptr[UREG_I5], &((*grp)[MC_O5]));

    __put_user(env->regwptr[UREG_I6], &((*grp)[MC_O6]));

    __put_user(env->regwptr[UREG_I7], &((*grp)[MC_O7]));

    w_addr = TARGET_STACK_BIAS+env->regwptr[UREG_I6];

    fp = i7 = 0;

    if (get_user(fp, w_addr + offsetof(struct target_reg_window, ins[6]),

                 abi_ulong) != 0) {

        goto do_sigsegv;

    }

    if (get_user(i7, w_addr + offsetof(struct target_reg_window, ins[7]),

                 abi_ulong) != 0) {

        goto do_sigsegv;

    }

    __put_user(fp, &(mcp->mc_fp));

    __put_user(i7, &(mcp->mc_i7));

    {

        uint32_t *dst = ucp->tuc_mcontext.mc_fpregs.mcfpu_fregs.sregs;

        for (i = 0; i < 64; i++, dst++) {

            if (i & 1) {

                __put_user(env->fpr[i/2].l.lower, dst);

            } else {

                __put_user(env->fpr[i/2].l.upper, dst);

            }

        }

    }

    __put_user(env->fsr, &(mcp->mc_fpregs.mcfpu_fsr));

    __put_user(env->gsr, &(mcp->mc_fpregs.mcfpu_gsr));

    __put_user(env->fprs, &(mcp->mc_fpregs.mcfpu_fprs));

    if (err)

        goto do_sigsegv;

    unlock_user_struct(ucp, ucp_addr, 1);

    return;

do_sigsegv:

    unlock_user_struct(ucp, ucp_addr, 1);

    force_sig(TARGET_SIGSEGV);

}


void av_close_input_file(AVFormatContext *s)

{

    int i;

    if (s->iformat->read_close)

        s->iformat->read_close(s);

    for(i=0;i<s->nb_streams;i++) {

        av_free(s->streams[i]);

    }

    if (s->packet_buffer) {

        AVPacketList *p, *p1;

        p = s->packet_buffer;

        while (p != NULL) {

            p1 = p->next;

            av_free_packet(&p->pkt);

            av_free(p);

            p = p1;

        }

        s->packet_buffer = NULL;

    }

    if (!(s->iformat->flags & AVFMT_NOFILE)) {

        url_fclose(&s->pb);

    }

    av_free(s->priv_data);

    av_free(s);

}


void stw_tce(VIOsPAPRDevice *dev, uint64_t taddr, uint32_t val)

{

    val = tswap32(val);

    spapr_tce_dma_write(dev, taddr, &val, sizeof(val));

}


static inline void RENAME(rgb32to24)(const uint8_t *src,uint8_t *dst,long src_size)

{

  uint8_t *dest = dst;

  const uint8_t *s = src;

  const uint8_t *end;

#ifdef HAVE_MMX

  const uint8_t *mm_end;

#endif

  end = s + src_size;

#ifdef HAVE_MMX

  __asm __volatile(PREFETCH"	%0"::"m"(*s):"memory");

  mm_end = end - 31;

  while(s < mm_end)

  {

    __asm __volatile(

	PREFETCH"	32%1\n\t"

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

	"movq	8%1, %%mm1\n\t"

	"movq	16%1, %%mm4\n\t"

	"movq	24%1, %%mm5\n\t"

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

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

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

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

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

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

	"psrlq	$8, %%mm6\n\t"

	"psrlq	$8, %%mm7\n\t"

	"pand	%2, %%mm0\n\t"

	"pand	%2, %%mm1\n\t"

	"pand	%2, %%mm4\n\t"

	"pand	%2, %%mm5\n\t"

	"pand	%3, %%mm2\n\t"

	"pand	%3, %%mm3\n\t"

	"pand	%3, %%mm6\n\t"

	"pand	%3, %%mm7\n\t"

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

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

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

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

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

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

	"psllq	$48, %%mm2\n\t"

	"psllq	$32, %%mm3\n\t"

	"pand	%4, %%mm2\n\t"

	"pand	%5, %%mm3\n\t"

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

	"psrlq	$16, %%mm1\n\t"

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

	"psllq	$16, %%mm5\n\t"

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

	"pand	%6, %%mm5\n\t"

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

	MOVNTQ"	%%mm0, %0\n\t"

	MOVNTQ"	%%mm1, 8%0\n\t"

	MOVNTQ"	%%mm4, 16%0"

	:"=m"(*dest)

	:"m"(*s),"m"(mask24l),

	 "m"(mask24h),"m"(mask24hh),"m"(mask24hhh),"m"(mask24hhhh)

	:"memory");

    dest += 24;

    s += 32;

  }

  __asm __volatile(SFENCE:::"memory");

  __asm __volatile(EMMS:::"memory");

#endif

  while(s < end)

  {

#ifdef WORDS_BIGENDIAN

    /* RGB32 (= A,B,G,R) -> RGB24 (= R,G,B) */

    s++;

    dest[2] = *s++;

    dest[1] = *s++;

    dest[0] = *s++;

    dest += 3;

#else

    *dest++ = *s++;

    *dest++ = *s++;

    *dest++ = *s++;

    s++;

#endif

  }

}


static void term_exit(void)

{

    tcsetattr(0, TCSANOW, &oldtty);

}


static inline int ohci_put_hcca(OHCIState *ohci,

                                uint32_t addr, struct ohci_hcca *hcca)

{

    cpu_physical_memory_write(addr + ohci->localmem_base, hcca, sizeof(*hcca));

    return 1;

}


static int vqf_read_seek(AVFormatContext *s,

                         int stream_index, int64_t timestamp, int flags)

{

    VqfContext *c = s->priv_data;

    AVStream *st;

    int ret;

    int64_t pos;

    st = s->streams[stream_index];

    pos = av_rescale_rnd(timestamp * st->codec->bit_rate,

                         st->time_base.num,

                         st->time_base.den * (int64_t)c->frame_bit_len,

                         (flags & AVSEEK_FLAG_BACKWARD) ?

                                                   AV_ROUND_DOWN : AV_ROUND_UP);

    pos *= c->frame_bit_len;

    st->cur_dts = av_rescale(pos, st->time_base.den,

                             st->codec->bit_rate * (int64_t)st->time_base.num);

    if ((ret = avio_seek(s->pb, ((pos-7) >> 3) + s->internal->data_offset, SEEK_SET)) < 0)

        return ret;

    c->remaining_bits = -7 - ((pos-7)&7);

    return 0;

}


void qemu_spice_destroy_host_primary(SimpleSpiceDisplay *ssd)

{

    dprint(1, "%s:\n", __FUNCTION__);

    qemu_mutex_unlock_iothread();

    ssd->worker->destroy_primary_surface(ssd->worker, 0);

    qemu_mutex_lock_iothread();

}


static void copy_context_reset(AVCodecContext *avctx)
{
    av_opt_free(avctx);
    av_freep(&avctx->rc_override);
    av_freep(&avctx->intra_matrix);
    av_freep(&avctx->inter_matrix);
    av_freep(&avctx->extradata);
    av_freep(&avctx->subtitle_header);
    av_buffer_unref(&avctx->hw_frames_ctx);
    avctx->subtitle_header_size = 0;
    avctx->extradata_size = 0;
}


int ff_audio_mix_init(AVAudioResampleContext *avr)

{

    int ret;

    if (avr->internal_sample_fmt != AV_SAMPLE_FMT_S16P &&

        avr->internal_sample_fmt != AV_SAMPLE_FMT_FLTP) {

        av_log(avr, AV_LOG_ERROR, "Unsupported internal format for "

               "mixing: %s\n",

               av_get_sample_fmt_name(avr->internal_sample_fmt));

        return AVERROR(EINVAL);

    }

    /* build matrix if the user did not already set one */

    if (!avr->am->matrix) {

        int i, j;

        char in_layout_name[128];

        char out_layout_name[128];

        double *matrix_dbl = av_mallocz(avr->out_channels * avr->in_channels *

                                        sizeof(*matrix_dbl));

        if (!matrix_dbl)

            return AVERROR(ENOMEM);

        ret = avresample_build_matrix(avr->in_channel_layout,

                                      avr->out_channel_layout,

                                      avr->center_mix_level,

                                      avr->surround_mix_level,

                                      avr->lfe_mix_level, 1, matrix_dbl,

                                      avr->in_channels,

                                      avr->matrix_encoding);

        if (ret < 0) {

            av_free(matrix_dbl);

            return ret;

        }

        av_get_channel_layout_string(in_layout_name, sizeof(in_layout_name),

                                     avr->in_channels, avr->in_channel_layout);

        av_get_channel_layout_string(out_layout_name, sizeof(out_layout_name),

                                     avr->out_channels, avr->out_channel_layout);

        av_log(avr, AV_LOG_DEBUG, "audio_mix: %s to %s\n",

               in_layout_name, out_layout_name);

        for (i = 0; i < avr->out_channels; i++) {

            for (j = 0; j < avr->in_channels; j++) {

                av_log(avr, AV_LOG_DEBUG, "  %0.3f ",

                       matrix_dbl[i * avr->in_channels + j]);

            }

            av_log(avr, AV_LOG_DEBUG, "\n");

        }

        ret = avresample_set_matrix(avr, matrix_dbl, avr->in_channels);

        if (ret < 0) {

            av_free(matrix_dbl);

            return ret;

        }

        av_free(matrix_dbl);

    }

    avr->am->fmt          = avr->internal_sample_fmt;

    avr->am->coeff_type   = avr->mix_coeff_type;

    avr->am->in_layout    = avr->in_channel_layout;

    avr->am->out_layout   = avr->out_channel_layout;

    avr->am->in_channels  = avr->in_channels;

    avr->am->out_channels = avr->out_channels;

    ret = mix_function_init(avr->am);

    if (ret < 0)

        return ret;

    return 0;

}


static inline void RENAME(rgb16ToY)(uint8_t *dst, uint8_t *src, int width)

{

	int i;

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

	{

		int d= ((uint16_t*)src)[i];

		int r= d&0x1F;

		int g= (d>>5)&0x3F;

		int b= (d>>11)&0x1F;

		dst[i]= ((2*RY*r + GY*g + 2*BY*b)>>(RGB2YUV_SHIFT-2)) + 16;

	}

}


static void aux_slave_dev_print(Monitor *mon, DeviceState *dev, int indent)

{

    AUXBus *bus = AUX_BUS(qdev_get_parent_bus(dev));

    AUXSlave *s;

    /* Don't print anything if the device is I2C "bridge". */

    if (aux_bus_is_bridge(bus, dev)) {

        return;

    }

    s = AUX_SLAVE(dev);

    monitor_printf(mon, "%*smemory " TARGET_FMT_plx "/" TARGET_FMT_plx "\n",

                   indent, "",

                   object_property_get_int(OBJECT(s->mmio), "addr", NULL),

                   memory_region_size(s->mmio));

}


void palette8tobgr16(const uint8_t *src, uint8_t *dst, unsigned num_pixels, const uint8_t *palette)

{

	unsigned i;

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

		((uint16_t *)dst)[i] = bswap_16(((uint16_t *)palette)[ src[i] ]);

}


static int vda_h264_decode_slice(AVCodecContext *avctx,

                                 const uint8_t *buffer,

                                 uint32_t size)

{

    VDAContext *vda                     = avctx->internal->hwaccel_priv_data;

    struct vda_context *vda_ctx         = avctx->hwaccel_context;

    void *tmp;

    if (!vda_ctx->decoder)

        return -1;

    tmp = av_fast_realloc(vda->bitstream,

                          &vda->allocated_size,

                          vda->bitstream_size + size + 4);

    if (!tmp)

        return AVERROR(ENOMEM);

    vda->bitstream = tmp;

    AV_WB32(vda->bitstream + vda->bitstream_size, size);

    memcpy(vda->bitstream + vda->bitstream_size + 4, buffer, size);

    vda->bitstream_size += size + 4;

    return 0;

}


static void print_tag(const char *str, unsigned int tag, int size)

{

    dprintf(NULL, "%s: tag=%c%c%c%c size=0x%x\n",

           str, tag & 0xff,

           (tag >> 8) & 0xff,

           (tag >> 16) & 0xff,

           (tag >> 24) & 0xff,

           size);

}


static void h264_loop_filter_strength_mmx2( int16_t bS[2][4][4], uint8_t nnz[40], int8_t ref[2][40], int16_t mv[2][40][2],

                                            int bidir, int edges, int step, int mask_mv0, int mask_mv1, int field ) {

    __asm__ volatile(

        "movq %0, %%mm7 \n"

        "movq %1, %%mm6 \n"

        ::"m"(ff_pb_1), "m"(ff_pb_3)

    );

    if(field)

        __asm__ volatile(

            "movq %0, %%mm6 \n"

            ::"m"(ff_pb_3_1)

        );

    __asm__ volatile(

        "movq  %%mm6, %%mm5 \n"

        "paddb %%mm5, %%mm5 \n"

    :);

    // could do a special case for dir==0 && edges==1, but it only reduces the

    // average filter time by 1.2%

    step  <<= 3;

    edges <<= 3;

    h264_loop_filter_strength_iteration_mmx2(bS, nnz, ref, mv, bidir, edges, step, mask_mv1, 1, -8,  0);

    h264_loop_filter_strength_iteration_mmx2(bS, nnz, ref, mv, bidir,    32,    8, mask_mv0, 0, -1, -1);

    __asm__ volatile(

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

        "movq  8(%0), %%mm1 \n\t"

        "movq 16(%0), %%mm2 \n\t"

        "movq 24(%0), %%mm3 \n\t"

        TRANSPOSE4(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4)

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

        "movq %%mm3,  8(%0) \n\t"

        "movq %%mm4, 16(%0) \n\t"

        "movq %%mm2, 24(%0) \n\t"

        ::"r"(bS[0])

        :"memory"

    );

}


int avfilter_copy_frame_props(AVFilterBufferRef *dst, const AVFrame *src)

{

    dst->pts    = src->pts;

    dst->pos    = av_frame_get_pkt_pos(src);

    dst->format = src->format;

    switch (dst->type) {

    case AVMEDIA_TYPE_VIDEO:

        dst->video->w                   = src->width;

        dst->video->h                   = src->height;

        dst->video->sample_aspect_ratio = src->sample_aspect_ratio;

        dst->video->interlaced          = src->interlaced_frame;

        dst->video->top_field_first     = src->top_field_first;

        dst->video->key_frame           = src->key_frame;

        dst->video->pict_type           = src->pict_type;

        av_freep(&dst->video->qp_table);

        dst->video->qp_table_linesize = 0;

        if (src->qscale_table) {

            int qsize = src->qstride ? src->qstride * ((src->height+15)/16) : (src->width+15)/16;

            dst->video->qp_table        = av_malloc(qsize);

            if(!dst->video->qp_table)

                return AVERROR(ENOMEM);

            dst->video->qp_table_linesize       = src->qstride;

            memcpy(dst->video->qp_table, src->qscale_table, qsize);

        }

        break;

    case AVMEDIA_TYPE_AUDIO:

        dst->audio->sample_rate         = src->sample_rate;

        dst->audio->channel_layout      = src->channel_layout;

        break;

    default:

        return AVERROR(EINVAL);

    }

    return 0;

}


void coroutine_fn qemu_coroutine_yield(void)

{

    Coroutine *self = qemu_coroutine_self();

    Coroutine *to = self->caller;

    trace_qemu_coroutine_yield(self, to);

    if (!to) {

        fprintf(stderr, "Co-routine is yielding to no one\n");

        abort();

    }

    self->caller = NULL;

    coroutine_swap(self, to);

}


int ff_probe_input_buffer(ByteIOContext **pb, AVInputFormat **fmt,

                          const char *filename, void *logctx,

                          unsigned int offset, unsigned int max_probe_size)

{

    AVProbeData pd = { filename ? filename : "", NULL, -offset };

    unsigned char *buf = NULL;

    int probe_size;

    if (!max_probe_size) {

        max_probe_size = PROBE_BUF_MAX;

    } else if (max_probe_size > PROBE_BUF_MAX) {

        max_probe_size = PROBE_BUF_MAX;

    } else if (max_probe_size < PROBE_BUF_MIN) {

        return AVERROR(EINVAL);

    }

    if (offset >= max_probe_size) {

        return AVERROR(EINVAL);

    }

    for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt; probe_size<<=1){

        int ret, score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;

        int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;

        if (probe_size < offset) {

            continue;

        }

        /* read probe data */

        buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);

        if ((ret = get_buffer(*pb, buf + buf_offset, probe_size - buf_offset)) < 0) {

            av_free(buf);

            return ret;

        }

        pd.buf_size += ret;

        pd.buf = &buf[offset];

        memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);

        /* guess file format */

        *fmt = av_probe_input_format2(&pd, 1, &score);

        if(*fmt){

            if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration

                av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);

            }else

                av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);

        }

    }

    av_free(buf);

    if (url_fseek(*pb, 0, SEEK_SET) < 0) {

        url_fclose(*pb);

        if (url_fopen(pb, filename, URL_RDONLY) < 0)

            return AVERROR(EIO);

    }

    return 0;

}


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

{

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

    KeyValueList *keylist, *head = NULL, *tmp = NULL;

    int has_hold_time = qdict_haskey(qdict, "hold-time");

    int hold_time = qdict_get_try_int(qdict, "hold-time", -1);

    Error *err = NULL;

    char keyname_buf[16];

    char *separator;

    int keyname_len;

    while (1) {

        separator = strchr(keys, '-');

        keyname_len = separator ? separator - keys : strlen(keys);

        pstrcpy(keyname_buf, sizeof(keyname_buf), keys);

        /* Be compatible with old interface, convert user inputted "<" */

        if (!strncmp(keyname_buf, "<", 1) && keyname_len == 1) {

            pstrcpy(keyname_buf, sizeof(keyname_buf), "less");

            keyname_len = 4;

        }

        keyname_buf[keyname_len] = 0;

        keylist = g_malloc0(sizeof(*keylist));

        keylist->value = g_malloc0(sizeof(*keylist->value));

        if (!head) {

            head = keylist;

        }

        if (tmp) {

            tmp->next = keylist;

        }

        tmp = keylist;

        if (strstart(keyname_buf, "0x", NULL)) {

            char *endp;

            int value = strtoul(keyname_buf, &endp, 0);

            if (*endp != '\0') {

                goto err_out;

            }

            keylist->value->type = KEY_VALUE_KIND_NUMBER;

            keylist->value->u.number = value;

        } else {

            int idx = index_from_key(keyname_buf);

            if (idx == Q_KEY_CODE__MAX) {

                goto err_out;

            }

            keylist->value->type = KEY_VALUE_KIND_QCODE;

            keylist->value->u.qcode = idx;

        }

        if (!separator) {

            break;

        }

        keys = separator + 1;

    }

    qmp_send_key(head, has_hold_time, hold_time, &err);

    hmp_handle_error(mon, &err);

out:

    qapi_free_KeyValueList(head);

    return;

err_out:

    monitor_printf(mon, "invalid parameter: %s\n", keyname_buf);

    goto out;

}


static void s390_cpu_class_init(ObjectClass *oc, void *data)

{

    S390CPUClass *scc = S390_CPU_CLASS(oc);

    CPUClass *cc = CPU_CLASS(scc);

    DeviceClass *dc = DEVICE_CLASS(oc);

    scc->parent_realize = dc->realize;

    dc->realize = s390_cpu_realizefn;

    scc->parent_reset = cc->reset;

    cc->reset = s390_cpu_reset;

    cc->do_interrupt = s390_cpu_do_interrupt;

    cc->dump_state = s390_cpu_dump_state;

    cc->set_pc = s390_cpu_set_pc;

    cc->gdb_read_register = s390_cpu_gdb_read_register;

    cc->gdb_write_register = s390_cpu_gdb_write_register;

#ifndef CONFIG_USER_ONLY

    cc->get_phys_page_debug = s390_cpu_get_phys_page_debug;

#endif

    dc->vmsd = &vmstate_s390_cpu;

    cc->gdb_num_core_regs = S390_NUM_REGS;

}


static void hpet_device_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = hpet_realize;

    dc->reset = hpet_reset;

    dc->vmsd = &vmstate_hpet;

    dc->props = hpet_device_properties;

}


static void vp8_filter_mb_row(AVCodecContext *avctx, void *tdata,

                              int jobnr, int threadnr)

{

    VP8Context *s = avctx->priv_data;

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

    int mb_x, mb_y = td->thread_mb_pos >> 16, num_jobs = s->num_jobs;

    AVFrame *curframe = s->curframe->tf.f;

    VP8Macroblock *mb;

    VP8ThreadData *prev_td, *next_td;

    uint8_t *dst[3] = {

        curframe->data[0] + 16 * mb_y * s->linesize,

        curframe->data[1] +  8 * mb_y * s->uvlinesize,

        curframe->data[2] +  8 * mb_y * s->uvlinesize

    };

    if (s->mb_layout == 1)

        mb = s->macroblocks_base + ((s->mb_width + 1) * (mb_y + 1) + 1);

    else

        mb = s->macroblocks + (s->mb_height - mb_y - 1) * 2;

    if (mb_y == 0)

        prev_td = td;

    else

        prev_td = &s->thread_data[(jobnr + num_jobs - 1) % num_jobs];

    if (mb_y == s->mb_height - 1)

        next_td = td;

    else

        next_td = &s->thread_data[(jobnr + 1) % num_jobs];

    for (mb_x = 0; mb_x < s->mb_width; mb_x++, mb++) {

        VP8FilterStrength *f = &td->filter_strength[mb_x];

        if (prev_td != td)

            check_thread_pos(td, prev_td,

                             (mb_x + 1) + (s->mb_width + 3), mb_y - 1);

        if (next_td != td)

            if (next_td != &s->thread_data[0])

                check_thread_pos(td, next_td, mb_x + 1, mb_y + 1);

        if (num_jobs == 1) {

            if (s->filter.simple)

                backup_mb_border(s->top_border[mb_x + 1], dst[0],

                                 NULL, NULL, s->linesize, 0, 1);

            else

                backup_mb_border(s->top_border[mb_x + 1], dst[0],

                                 dst[1], dst[2], s->linesize, s->uvlinesize, 0);

        }

        if (s->filter.simple)

            filter_mb_simple(s, dst[0], f, mb_x, mb_y);

        else

            filter_mb(s, dst, f, mb_x, mb_y);

        dst[0] += 16;

        dst[1] += 8;

        dst[2] += 8;

        update_pos(td, mb_y, (s->mb_width + 3) + mb_x);

    }

}


static int cllc_decode_frame(AVCodecContext *avctx, void *data,

                             int *got_picture_ptr, AVPacket *avpkt)

{

    CLLCContext *ctx = avctx->priv_data;

    AVFrame *pic = data;

    uint8_t *src = avpkt->data;

    uint32_t info_tag, info_offset;

    int data_size;

    GetBitContext gb;

    int coding_type, ret;

    /* Skip the INFO header if present */

    info_offset = 0;

    info_tag    = AV_RL32(src);

    if (info_tag == MKTAG('I', 'N', 'F', 'O')) {

        info_offset = AV_RL32(src + 4);

        if (info_offset > UINT32_MAX - 8 || info_offset + 8 > avpkt->size) {

            av_log(avctx, AV_LOG_ERROR,

                   "Invalid INFO header offset: 0x%08"PRIX32" is too large.\n",

                   info_offset);

            return AVERROR_INVALIDDATA;

        }

        info_offset += 8;

        src         += info_offset;

        av_log(avctx, AV_LOG_DEBUG, "Skipping INFO chunk.\n");

    }

    data_size = (avpkt->size - info_offset) & ~1;

    /* Make sure our bswap16'd buffer is big enough */

    av_fast_padded_malloc(&ctx->swapped_buf,

                          &ctx->swapped_buf_size, data_size);

    if (!ctx->swapped_buf) {

        av_log(avctx, AV_LOG_ERROR, "Could not allocate swapped buffer.\n");

        return AVERROR(ENOMEM);

    }

    /* bswap16 the buffer since CLLC's bitreader works in 16-bit words */

    ctx->bdsp.bswap16_buf((uint16_t *) ctx->swapped_buf, (uint16_t *) src,

                          data_size / 2);

    init_get_bits(&gb, ctx->swapped_buf, data_size * 8);

    /*

     * Read in coding type. The types are as follows:

     *

     * 0 - YUY2

     * 1 - BGR24 (Triples)

     * 2 - BGR24 (Quads)

     * 3 - BGRA

     */

    coding_type = (AV_RL32(src) >> 8) & 0xFF;

    av_log(avctx, AV_LOG_DEBUG, "Frame coding type: %d\n", coding_type);

    switch (coding_type) {

    case 0:

        avctx->pix_fmt             = AV_PIX_FMT_YUV422P;

        avctx->bits_per_raw_sample = 8;

        ret = ff_get_buffer(avctx, pic, 0);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer.\n");

            return ret;

        }

        ret = decode_yuv_frame(ctx, &gb, pic);

        if (ret < 0)

            return ret;

        break;

    case 1:

    case 2:

        avctx->pix_fmt             = AV_PIX_FMT_RGB24;

        avctx->bits_per_raw_sample = 8;

        ret = ff_get_buffer(avctx, pic, 0);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer.\n");

            return ret;

        }

        ret = decode_rgb24_frame(ctx, &gb, pic);

        if (ret < 0)

            return ret;

        break;

    case 3:

        avctx->pix_fmt             = AV_PIX_FMT_ARGB;

        avctx->bits_per_raw_sample = 8;

        ret = ff_get_buffer(avctx, pic, 0);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer.\n");

            return ret;

        }

        ret = decode_argb_frame(ctx, &gb, pic);

        if (ret < 0)

            return ret;

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Unknown coding type: %d.\n", coding_type);

        return AVERROR_INVALIDDATA;

    }

    pic->key_frame = 1;

    pic->pict_type = AV_PICTURE_TYPE_I;

    *got_picture_ptr = 1;

    return avpkt->size;

}


static void test_event_c(TestEventData *data,

                         const void *unused)

{

    QDict *d, *d_data, *d_b;

    UserDefOne b;

    UserDefZero z;

    z.integer = 2;

    b.base = &z;

    b.string = g_strdup("test1");

    b.has_enum1 = false;

    d_b = qdict_new();

    qdict_put(d_b, "integer", qint_from_int(2));

    qdict_put(d_b, "string", qstring_from_str("test1"));

    d_data = qdict_new();

    qdict_put(d_data, "a", qint_from_int(1));

    qdict_put(d_data, "b", d_b);

    qdict_put(d_data, "c", qstring_from_str("test2"));

    d = data->expect;

    qdict_put(d, "event", qstring_from_str("EVENT_C"));

    qdict_put(d, "data", d_data);

    qapi_event_send_event_c(true, 1, true, &b, "test2", &error_abort);

    g_free(b.string);

}


static void enable_logging(void)

{

    ga_enable_logging(ga_state);

}


static void h264_v_loop_filter_luma_c(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0)

{

    h264_loop_filter_luma_c(pix, stride, 1, alpha, beta, tc0);

}


static void qemu_aio_wait_nonblocking(void)

{

    qemu_notify_event();

    qemu_aio_wait();

}


void qmp_block_job_set_speed(const char *device, int64_t value, Error **errp)

{

    BlockJob *job = find_block_job(device);

    if (!job) {

        error_set(errp, QERR_DEVICE_NOT_ACTIVE, device);

        return;

    }

    if (block_job_set_speed(job, value) < 0) {

        error_set(errp, QERR_NOT_SUPPORTED);

    }

}


int virtqueue_pop(VirtQueue *vq, VirtQueueElement *elem)

{

    unsigned int i, head, max;

    hwaddr desc_pa = vq->vring.desc;

    VirtIODevice *vdev = vq->vdev;

    if (!virtqueue_num_heads(vq, vq->last_avail_idx))

        return 0;

    /* When we start there are none of either input nor output. */

    elem->out_num = elem->in_num = 0;

    max = vq->vring.num;

    i = head = virtqueue_get_head(vq, vq->last_avail_idx++);

    if (virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {

        vring_set_avail_event(vq, vq->last_avail_idx);

    }

    if (vring_desc_flags(vdev, desc_pa, i) & VRING_DESC_F_INDIRECT) {

        if (vring_desc_len(vdev, desc_pa, i) % sizeof(VRingDesc)) {

            error_report("Invalid size for indirect buffer table");

            exit(1);

        }

        /* loop over the indirect descriptor table */

        max = vring_desc_len(vdev, desc_pa, i) / sizeof(VRingDesc);

        desc_pa = vring_desc_addr(vdev, desc_pa, i);

        i = 0;

    }

    /* Collect all the descriptors */

    do {

        struct iovec *sg;

        if (vring_desc_flags(vdev, desc_pa, i) & VRING_DESC_F_WRITE) {

            if (elem->in_num >= ARRAY_SIZE(elem->in_sg)) {

                error_report("Too many write descriptors in indirect table");

                exit(1);

            }

            elem->in_addr[elem->in_num] = vring_desc_addr(vdev, desc_pa, i);

            sg = &elem->in_sg[elem->in_num++];

        } else {

            if (elem->out_num >= ARRAY_SIZE(elem->out_sg)) {

                error_report("Too many read descriptors in indirect table");

                exit(1);

            }

            elem->out_addr[elem->out_num] = vring_desc_addr(vdev, desc_pa, i);

            sg = &elem->out_sg[elem->out_num++];

        }

        sg->iov_len = vring_desc_len(vdev, desc_pa, i);

        /* If we've got too many, that implies a descriptor loop. */

        if ((elem->in_num + elem->out_num) > max) {

            error_report("Looped descriptor");

            exit(1);

        }

    } while ((i = virtqueue_next_desc(vdev, desc_pa, i, max)) != max);

    /* Now map what we have collected */

    virtqueue_map(elem);

    elem->index = head;

    vq->inuse++;

    trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);

    return elem->in_num + elem->out_num;

}


void qemu_main_loop_start(void)

{

    qemu_system_ready = 1;

    qemu_cond_broadcast(&qemu_system_cond);

}


static void spr_read_tbl (DisasContext *ctx, int gprn, int sprn)

{

    if (use_icount) {

        gen_io_start();

    }

    gen_helper_load_tbl(cpu_gpr[gprn], cpu_env);

    if (use_icount) {

        gen_io_end();

        gen_stop_exception(ctx);

    }

}


static void arm_cpu_initfn(Object *obj)

{

    CPUState *cs = CPU(obj);

    ARMCPU *cpu = ARM_CPU(obj);

    static bool inited;

    cs->env_ptr = &cpu->env;

    cpu_exec_init(&cpu->env);

    cpu->cp_regs = g_hash_table_new_full(g_int_hash, g_int_equal,

                                         g_free, g_free);

#ifndef CONFIG_USER_ONLY

    /* Our inbound IRQ and FIQ lines */

    if (kvm_enabled()) {

        /* VIRQ and VFIQ are unused with KVM but we add them to maintain

         * the same interface as non-KVM CPUs.

         */

        qdev_init_gpio_in(DEVICE(cpu), arm_cpu_kvm_set_irq, 4);

    } else {

        qdev_init_gpio_in(DEVICE(cpu), arm_cpu_set_irq, 4);

    }

    cpu->gt_timer[GTIMER_PHYS] = timer_new(QEMU_CLOCK_VIRTUAL, GTIMER_SCALE,

                                                arm_gt_ptimer_cb, cpu);

    cpu->gt_timer[GTIMER_VIRT] = timer_new(QEMU_CLOCK_VIRTUAL, GTIMER_SCALE,

                                                arm_gt_vtimer_cb, cpu);

    qdev_init_gpio_out(DEVICE(cpu), cpu->gt_timer_outputs,

                       ARRAY_SIZE(cpu->gt_timer_outputs));

#endif

    /* DTB consumers generally don't in fact care what the 'compatible'

     * string is, so always provide some string and trust that a hypothetical

     * picky DTB consumer will also provide a helpful error message.

     */

    cpu->dtb_compatible = "qemu,unknown";

    cpu->psci_version = 1; /* By default assume PSCI v0.1 */

    cpu->kvm_target = QEMU_KVM_ARM_TARGET_NONE;

    if (tcg_enabled() && !inited) {

        inited = true;

        arm_translate_init();

    }

}


uint32_t ide_status_read(void *opaque, uint32_t addr)

{

    IDEBus *bus = opaque;

    IDEState *s = idebus_active_if(bus);

    int ret;

    if ((!bus->ifs[0].bs && !bus->ifs[1].bs) ||

        (s != bus->ifs && !s->bs))

        ret = 0;

    else

        ret = s->status;

#ifdef DEBUG_IDE

    printf("ide: read status addr=0x%x val=%02x\n", addr, ret);

#endif

    return ret;

}


static int net_slirp_init(Monitor *mon, VLANState *vlan, const char *model,

                          const char *name, int restricted,

                          const char *vnetwork, const char *vhost,

                          const char *vhostname, const char *tftp_export,

                          const char *bootfile, const char *vdhcp_start,

                          const char *vnameserver, const char *smb_export,

                          const char *vsmbserver)

{

    /* default settings according to historic slirp */

    struct in_addr net  = { .s_addr = htonl(0x0a000200) }; /* 10.0.2.0 */

    struct in_addr mask = { .s_addr = htonl(0xffffff00) }; /* 255.255.255.0 */

    struct in_addr host = { .s_addr = htonl(0x0a000202) }; /* 10.0.2.2 */

    struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; /* 10.0.2.15 */

    struct in_addr dns  = { .s_addr = htonl(0x0a000203) }; /* 10.0.2.3 */

#ifndef _WIN32

    struct in_addr smbsrv = { .s_addr = 0 };

#endif

    SlirpState *s;

    char buf[20];

    uint32_t addr;

    int shift;

    char *end;

    if (!tftp_export) {

        tftp_export = legacy_tftp_prefix;

    }

    if (!bootfile) {

        bootfile = legacy_bootp_filename;

    }

    if (vnetwork) {

        if (get_str_sep(buf, sizeof(buf), &vnetwork, '/') < 0) {

            if (!inet_aton(vnetwork, &net)) {

                return -1;

            }

            addr = ntohl(net.s_addr);

            if (!(addr & 0x80000000)) {

                mask.s_addr = htonl(0xff000000); /* class A */

            } else if ((addr & 0xfff00000) == 0xac100000) {

                mask.s_addr = htonl(0xfff00000); /* priv. 172.16.0.0/12 */

            } else if ((addr & 0xc0000000) == 0x80000000) {

                mask.s_addr = htonl(0xffff0000); /* class B */

            } else if ((addr & 0xffff0000) == 0xc0a80000) {

                mask.s_addr = htonl(0xffff0000); /* priv. 192.168.0.0/16 */

            } else if ((addr & 0xffff0000) == 0xc6120000) {

                mask.s_addr = htonl(0xfffe0000); /* tests 198.18.0.0/15 */

            } else if ((addr & 0xe0000000) == 0xe0000000) {

                mask.s_addr = htonl(0xffffff00); /* class C */

            } else {

                mask.s_addr = htonl(0xfffffff0); /* multicast/reserved */

            }

        } else {

            if (!inet_aton(buf, &net)) {

                return -1;

            }

            shift = strtol(vnetwork, &end, 10);

            if (*end != '\0') {

                if (!inet_aton(vnetwork, &mask)) {

                    return -1;

                }

            } else if (shift < 4 || shift > 32) {

                return -1;

            } else {

                mask.s_addr = htonl(0xffffffff << (32 - shift));

            }

        }

        net.s_addr &= mask.s_addr;

        host.s_addr = net.s_addr | (htonl(0x0202) & ~mask.s_addr);

        dhcp.s_addr = net.s_addr | (htonl(0x020f) & ~mask.s_addr);

        dns.s_addr  = net.s_addr | (htonl(0x0203) & ~mask.s_addr);

    }

    if (vhost && !inet_aton(vhost, &host)) {

        return -1;

    }

    if ((host.s_addr & mask.s_addr) != net.s_addr) {

        return -1;

    }

    if (vdhcp_start && !inet_aton(vdhcp_start, &dhcp)) {

        return -1;

    }

    if ((dhcp.s_addr & mask.s_addr) != net.s_addr ||

        dhcp.s_addr == host.s_addr || dhcp.s_addr == dns.s_addr) {

        return -1;

    }

    if (vnameserver && !inet_aton(vnameserver, &dns)) {

        return -1;

    }

    if ((dns.s_addr & mask.s_addr) != net.s_addr ||

        dns.s_addr == host.s_addr) {

        return -1;

    }

#ifndef _WIN32

    if (vsmbserver && !inet_aton(vsmbserver, &smbsrv)) {

        return -1;

    }

#endif

    s = qemu_mallocz(sizeof(SlirpState));

    s->slirp = slirp_init(restricted, net, mask, host, vhostname,

                          tftp_export, bootfile, dhcp, dns, s);

    TAILQ_INSERT_TAIL(&slirp_stacks, s, entry);

    while (slirp_configs) {

        struct slirp_config_str *config = slirp_configs;

        if (config->flags & SLIRP_CFG_HOSTFWD) {

            slirp_hostfwd(s, mon, config->str,

                          config->flags & SLIRP_CFG_LEGACY);

        } else {

            slirp_guestfwd(s, mon, config->str,

                           config->flags & SLIRP_CFG_LEGACY);

        }

        slirp_configs = config->next;

        qemu_free(config);

    }

#ifndef _WIN32

    if (!smb_export) {

        smb_export = legacy_smb_export;

    }

    if (smb_export) {

        slirp_smb(s, mon, smb_export, smbsrv);

    }

#endif

    s->vc = qemu_new_vlan_client(vlan, model, name, NULL, slirp_receive, NULL,

                                 net_slirp_cleanup, s);

    snprintf(s->vc->info_str, sizeof(s->vc->info_str),

             "net=%s, restricted=%c", inet_ntoa(net), restricted ? 'y' : 'n');

    return 0;

}


int av_opt_set_pixel_fmt(void *obj, const char *name, enum AVPixelFormat fmt, int search_flags)

{

    return set_format(obj, name, fmt, search_flags, AV_OPT_TYPE_PIXEL_FMT, "pixel", AV_PIX_FMT_NB-1);

}