static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,

                            QDict *options, Error **errp)

{

    int ret, open_flags;

    const char *filename;

    const char *driver_name = NULL;

    const char *node_name = NULL;

    QemuOpts *opts;

    BlockDriver *drv;

    Error *local_err = NULL;

    assert(bs->file == NULL);

    assert(options != NULL && bs->options != options);

    opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail_opts;

    }

    driver_name = qemu_opt_get(opts, "driver");

    drv = bdrv_find_format(driver_name);

    assert(drv != NULL);

    if (file != NULL) {

        filename = file->bs->filename;

    } else {

        filename = qdict_get_try_str(options, "filename");

    }

    if (drv->bdrv_needs_filename && !filename) {

        error_setg(errp, "The '%s' block driver requires a file name",

                   drv->format_name);

        ret = -EINVAL;

        goto fail_opts;

    }

    trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,

                           drv->format_name);

    node_name = qemu_opt_get(opts, "node-name");

    bdrv_assign_node_name(bs, node_name, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail_opts;

    }

    bs->read_only = !(bs->open_flags & BDRV_O_RDWR);

    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {

        error_setg(errp,

                   !bs->read_only && bdrv_is_whitelisted(drv, true)

                        ? "Driver '%s' can only be used for read-only devices"

                        : "Driver '%s' is not whitelisted",

                   drv->format_name);

        ret = -ENOTSUP;

        goto fail_opts;

    }

    assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */

    if (bs->open_flags & BDRV_O_COPY_ON_READ) {

        if (!bs->read_only) {

            bdrv_enable_copy_on_read(bs);

        } else {

            error_setg(errp, "Can't use copy-on-read on read-only device");

            ret = -EINVAL;

            goto fail_opts;

        }

    }

    if (filename != NULL) {

        pstrcpy(bs->filename, sizeof(bs->filename), filename);

    } else {

        bs->filename[0] = '\0';

    }

    pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);

    bs->drv = drv;

    bs->opaque = g_malloc0(drv->instance_size);

    /* Apply cache mode options */

    update_flags_from_options(&bs->open_flags, opts);

    /* Open the image, either directly or using a protocol */

    open_flags = bdrv_open_flags(bs, bs->open_flags);

    if (drv->bdrv_file_open) {

        assert(file == NULL);

        assert(!drv->bdrv_needs_filename || filename != NULL);

        ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);

    } else {

        if (file == NULL) {

            error_setg(errp, "Can't use '%s' as a block driver for the "

                       "protocol level", drv->format_name);

            ret = -EINVAL;

            goto free_and_fail;

        }

        bs->file = file;

        ret = drv->bdrv_open(bs, options, open_flags, &local_err);

    }

    if (ret < 0) {

        if (local_err) {

            error_propagate(errp, local_err);

        } else if (bs->filename[0]) {

            error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);

        } else {

            error_setg_errno(errp, -ret, "Could not open image");

        }

        goto free_and_fail;

    }

    ret = refresh_total_sectors(bs, bs->total_sectors);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not refresh total sector count");

        goto free_and_fail;

    }

    bdrv_refresh_limits(bs, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto free_and_fail;

    }

    assert(bdrv_opt_mem_align(bs) != 0);

    assert(bdrv_min_mem_align(bs) != 0);

    assert(is_power_of_2(bs->request_alignment) || bdrv_is_sg(bs));

    qemu_opts_del(opts);

    return 0;

free_and_fail:

    bs->file = NULL;

    g_free(bs->opaque);

    bs->opaque = NULL;

    bs->drv = NULL;

fail_opts:

    qemu_opts_del(opts);

    return ret;

}


static void test_visitor_out_enum_errors(TestOutputVisitorData *data,

                                         const void *unused)

{

    EnumOne i, bad_values[] = { ENUM_ONE__MAX, -1 };

    Error *err;

    for (i = 0; i < ARRAY_SIZE(bad_values) ; i++) {

        err = NULL;

        visit_type_EnumOne(data->ov, "unused", &bad_values[i], &err);

        g_assert(err);

        error_free(err);

        visitor_reset(data);

    }

}


static size_t v9fs_unpack(void *dst, struct iovec *out_sg, int out_num,

                          size_t offset, size_t size)

{

    return v9fs_packunpack(dst, out_sg, out_num, offset, size, 0);

}


print_with_operands (const struct cris_opcode *opcodep,

		     unsigned int insn,

		     unsigned char *buffer,

		     bfd_vma addr,

		     disassemble_info *info,

		     /* If a prefix insn was before this insn (and is supposed

			to be output as an address), here is a description of

			it.  */

		     const struct cris_opcode *prefix_opcodep,

		     unsigned int prefix_insn,

		     unsigned char *prefix_buffer,

		     bfd_boolean with_reg_prefix)

{

  /* Get a buffer of somewhat reasonable size where we store

     intermediate parts of the insn.  */

  char temp[sizeof (".d [$r13=$r12-2147483648],$r10") * 2];

  char *tp = temp;

  static const char mode_char[] = "bwd?";

  const char *s;

  const char *cs;

  struct cris_disasm_data *disdata

    = (struct cris_disasm_data *) info->private_data;

  /* Print out the name first thing we do.  */

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

  cs = opcodep->args;

  s = cs;

  /* Ignore any prefix indicator.  */

  if (*s == 'p')

    s++;

  if (*s == 'm' || *s == 'M' || *s == 'z')

    {

      *tp++ = '.';

      /* Get the size-letter.  */

      *tp++ = *s == 'M'

	? (insn & 0x8000 ? 'd'

	   : insn & 0x4000 ? 'w' : 'b')

	: mode_char[(insn >> 4) & (*s == 'z' ? 1 : 3)];

      /* Ignore the size and the space character that follows.  */

      s += 2;

    }

  /* Add a space if this isn't a long-branch, because for those will add

     the condition part of the name later.  */

  if (opcodep->match != (BRANCH_PC_LOW + BRANCH_INCR_HIGH * 256))

    *tp++ = ' ';

  /* Fill in the insn-type if deducible from the name (and there's no

     better way).  */

  if (opcodep->name[0] == 'j')

    {

      if (CONST_STRNEQ (opcodep->name, "jsr"))

	/* It's "jsr" or "jsrc".  */

	info->insn_type = dis_jsr;

      else

	/* Any other jump-type insn is considered a branch.  */

	info->insn_type = dis_branch;

    }

  /* We might know some more fields right now.  */

  info->branch_delay_insns = opcodep->delayed;

  /* Handle operands.  */

  for (; *s; s++)

    {

    switch (*s)

      {

      case 'T':

	tp = format_sup_reg ((insn >> 12) & 15, tp, with_reg_prefix);

	break;

      case 'A':

	if (with_reg_prefix)

	  *tp++ = REGISTER_PREFIX_CHAR;

	*tp++ = 'a';

	*tp++ = 'c';

	*tp++ = 'r';

	break;

      case '[':

      case ']':

      case ',':

	*tp++ = *s;

	break;

      case '!':

	/* Ignore at this point; used at earlier stages to avoid

	   recognition if there's a prefix at something that in other

	   ways looks like a "pop".  */

	break;

      case 'd':

	/* Ignore.  This is an optional ".d " on the large one of

	   relaxable insns.  */

	break;

      case 'B':

	/* This was the prefix that made this a "push".  We've already

	   handled it by recognizing it, so signal that the prefix is

	   handled by setting it to NULL.  */

	prefix_opcodep = NULL;

	break;

      case 'D':

      case 'r':

	tp = format_reg (disdata, insn & 15, tp, with_reg_prefix);

	break;

      case 'R':

	tp = format_reg (disdata, (insn >> 12) & 15, tp, with_reg_prefix);

	break;

      case 'n':

	{

	  /* Like N but pc-relative to the start of the insn.  */

	  unsigned long number

	    = (buffer[2] + buffer[3] * 256 + buffer[4] * 65536

	       + buffer[5] * 0x1000000 + addr);

	  /* Finish off and output previous formatted bytes.  */

	  *tp = 0;

	  if (temp[0])

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

	  tp = temp;

	  (*info->print_address_func) ((bfd_vma) number, info);

	}

	break;

      case 'u':

	{

	  /* Like n but the offset is bits <3:0> in the instruction.  */

	  unsigned long number = (buffer[0] & 0xf) * 2 + addr;

	  /* Finish off and output previous formatted bytes.  */

	  *tp = 0;

	  if (temp[0])

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

	  tp = temp;

	  (*info->print_address_func) ((bfd_vma) number, info);

	}

	break;

      case 'N':

      case 'y':

      case 'Y':

      case 'S':

      case 's':

	/* Any "normal" memory operand.  */

	if ((insn & 0x400) && (insn & 15) == 15 && prefix_opcodep == NULL)

	  {

	    /* We're looking at [pc+], i.e. we need to output an immediate

	       number, where the size can depend on different things.  */

	    long number;

	    int signedp

	      = ((*cs == 'z' && (insn & 0x20))

		 || opcodep->match == BDAP_QUICK_OPCODE);

	    int nbytes;

	    if (opcodep->imm_oprnd_size == SIZE_FIX_32)

	      nbytes = 4;

	    else if (opcodep->imm_oprnd_size == SIZE_SPEC_REG)

	      {

		const struct cris_spec_reg *sregp

		  = spec_reg_info ((insn >> 12) & 15, disdata->distype);

		/* A NULL return should have been as a non-match earlier,

		   so catch it as an internal error in the error-case

		   below.  */

		if (sregp == NULL)

		  /* Whatever non-valid size.  */

		  nbytes = 42;

		else

		  /* PC is always incremented by a multiple of two.

		     For CRISv32, immediates are always 4 bytes for

		     special registers.  */

		  nbytes = disdata->distype == cris_dis_v32

		    ? 4 : (sregp->reg_size + 1) & ~1;

	      }

	    else

	      {

		int mode_size = 1 << ((insn >> 4) & (*cs == 'z' ? 1 : 3));

		if (mode_size == 1)

		  nbytes = 2;

		else

		  nbytes = mode_size;

	      }

	    switch (nbytes)

	      {

	      case 1:

		number = buffer[2];

		if (signedp && number > 127)

		  number -= 256;

		break;

	      case 2:

		number = buffer[2] + buffer[3] * 256;

		if (signedp && number > 32767)

		  number -= 65536;

		break;

	      case 4:

		number

		  = buffer[2] + buffer[3] * 256 + buffer[4] * 65536

		  + buffer[5] * 0x1000000;

		break;

	      default:

		strcpy (tp, "bug");

		tp += 3;

		number = 42;

	      }

	    if ((*cs == 'z' && (insn & 0x20))

		|| (opcodep->match == BDAP_QUICK_OPCODE

		    && (nbytes <= 2 || buffer[1 + nbytes] == 0)))

	      tp = format_dec (number, tp, signedp);

	    else

	      {

		unsigned int highbyte = (number >> 24) & 0xff;

		/* Either output this as an address or as a number.  If it's

		   a dword with the same high-byte as the address of the

		   insn, assume it's an address, and also if it's a non-zero

		   non-0xff high-byte.  If this is a jsr or a jump, then

		   it's definitely an address.  */

		if (nbytes == 4

		    && (highbyte == ((addr >> 24) & 0xff)

			|| (highbyte != 0 && highbyte != 0xff)

			|| info->insn_type == dis_branch

			|| info->insn_type == dis_jsr))

		  {

		    /* Finish off and output previous formatted bytes.  */

		    *tp = 0;

		    tp = temp;

		    if (temp[0])

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

		    (*info->print_address_func) ((bfd_vma) number, info);

		    info->target = number;

		  }

		else

		  tp = format_hex (number, tp, disdata);

	      }

	  }

	else

	  {

	    /* Not an immediate number.  Then this is a (possibly

	       prefixed) memory operand.  */

	    if (info->insn_type != dis_nonbranch)

	      {

		int mode_size

		  = 1 << ((insn >> 4)

			  & (opcodep->args[0] == 'z' ? 1 : 3));

		int size;

		info->insn_type = dis_dref;

		info->flags |= CRIS_DIS_FLAG_MEMREF;

		if (opcodep->imm_oprnd_size == SIZE_FIX_32)

		  size = 4;

		else if (opcodep->imm_oprnd_size == SIZE_SPEC_REG)

		  {

		    const struct cris_spec_reg *sregp

		      = spec_reg_info ((insn >> 12) & 15, disdata->distype);

		    /* FIXME: Improve error handling; should have been caught

		       earlier.  */

		    if (sregp == NULL)

		      size = 4;

		    else

		      size = sregp->reg_size;

		  }

		else

		  size = mode_size;

		info->data_size = size;

	      }

	    *tp++ = '[';

	    if (prefix_opcodep

		/* We don't match dip with a postincremented field

		   as a side-effect address mode.  */

		&& ((insn & 0x400) == 0

		    || prefix_opcodep->match != DIP_OPCODE))

	      {

		if (insn & 0x400)

		  {

		    tp = format_reg (disdata, insn & 15, tp, with_reg_prefix);

		    *tp++ = '=';

		  }

		/* We mainly ignore the prefix format string when the

		   address-mode syntax is output.  */

		switch (prefix_opcodep->match)

		  {

		  case DIP_OPCODE:

		    /* It's [r], [r+] or [pc+].  */

		    if ((prefix_insn & 0x400) && (prefix_insn & 15) == 15)

		      {

			/* It's [pc+].  This cannot possibly be anything

			   but an address.  */

			unsigned long number

			  = prefix_buffer[2] + prefix_buffer[3] * 256

			  + prefix_buffer[4] * 65536

			  + prefix_buffer[5] * 0x1000000;

			info->target = (bfd_vma) number;

			/* Finish off and output previous formatted

			   data.  */

			*tp = 0;

			tp = temp;

			if (temp[0])

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

			(*info->print_address_func) ((bfd_vma) number, info);

		      }

		    else

		      {

			/* For a memref in an address, we use target2.

			   In this case, target is zero.  */

			info->flags

			  |= (CRIS_DIS_FLAG_MEM_TARGET2_IS_REG

			      | CRIS_DIS_FLAG_MEM_TARGET2_MEM);

			info->target2 = prefix_insn & 15;

			*tp++ = '[';

			tp = format_reg (disdata, prefix_insn & 15, tp,

					 with_reg_prefix);

			if (prefix_insn & 0x400)

			  *tp++ = '+';

			*tp++ = ']';

		      }

		    break;

		  case BDAP_QUICK_OPCODE:

		    {

		      int number;

		      number = prefix_buffer[0];

		      if (number > 127)

			number -= 256;

		      /* Output "reg+num" or, if num < 0, "reg-num".  */

		      tp = format_reg (disdata, (prefix_insn >> 12) & 15, tp,

				       with_reg_prefix);

		      if (number >= 0)

			*tp++ = '+';

		      tp = format_dec (number, tp, 1);

		      info->flags |= CRIS_DIS_FLAG_MEM_TARGET_IS_REG;

		      info->target = (prefix_insn >> 12) & 15;

		      info->target2 = (bfd_vma) number;

		      break;

		    }

		  case BIAP_OPCODE:

		    /* Output "r+R.m".  */

		    tp = format_reg (disdata, prefix_insn & 15, tp,

				     with_reg_prefix);

		    *tp++ = '+';

		    tp = format_reg (disdata, (prefix_insn >> 12) & 15, tp,

				     with_reg_prefix);

		    *tp++ = '.';

		    *tp++ = mode_char[(prefix_insn >> 4) & 3];

		    info->flags

		      |= (CRIS_DIS_FLAG_MEM_TARGET2_IS_REG

			  | CRIS_DIS_FLAG_MEM_TARGET_IS_REG

			  | ((prefix_insn & 0x8000)

			     ? CRIS_DIS_FLAG_MEM_TARGET2_MULT4

			     : ((prefix_insn & 0x8000)

				? CRIS_DIS_FLAG_MEM_TARGET2_MULT2 : 0)));

		    /* Is it the casejump?  It's a "adds.w [pc+r%d.w],pc".  */

		    if (insn == 0xf83f && (prefix_insn & ~0xf000) == 0x55f)

		      /* Then start interpreting data as offsets.  */

		      case_offset_counter = no_of_case_offsets;

		    break;

		  case BDAP_INDIR_OPCODE:

		    /* Output "r+s.m", or, if "s" is [pc+], "r+s" or

		       "r-s".  */

		    tp = format_reg (disdata, (prefix_insn >> 12) & 15, tp,

				     with_reg_prefix);

		    if ((prefix_insn & 0x400) && (prefix_insn & 15) == 15)

		      {

			long number;

			unsigned int nbytes;

			/* It's a value.  Get its size.  */

			int mode_size = 1 << ((prefix_insn >> 4) & 3);

			if (mode_size == 1)

			  nbytes = 2;

			else

			  nbytes = mode_size;

			switch (nbytes)

			  {

			  case 1:

			    number = prefix_buffer[2];

			    if (number > 127)

			      number -= 256;

			    break;

			  case 2:

			    number = prefix_buffer[2] + prefix_buffer[3] * 256;

			    if (number > 32767)

			      number -= 65536;

			    break;

			  case 4:

			    number

			      = prefix_buffer[2] + prefix_buffer[3] * 256

			      + prefix_buffer[4] * 65536

			      + prefix_buffer[5] * 0x1000000;

			    break;

			  default:

			    strcpy (tp, "bug");

			    tp += 3;

			    number = 42;

			  }

			info->flags |= CRIS_DIS_FLAG_MEM_TARGET_IS_REG;

			info->target2 = (bfd_vma) number;

			/* If the size is dword, then assume it's an

			   address.  */

			if (nbytes == 4)

			  {

			    /* Finish off and output previous formatted

			       bytes.  */

			    *tp++ = '+';

			    *tp = 0;

			    tp = temp;

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

			    (*info->print_address_func) ((bfd_vma) number, info);

			  }

			else

			  {

			    if (number >= 0)

			      *tp++ = '+';

			    tp = format_dec (number, tp, 1);

			  }

		      }

		    else

		      {

			/* Output "r+[R].m" or "r+[R+].m".  */

			*tp++ = '+';

			*tp++ = '[';

			tp = format_reg (disdata, prefix_insn & 15, tp,

					 with_reg_prefix);

			if (prefix_insn & 0x400)

			  *tp++ = '+';

			*tp++ = ']';

			*tp++ = '.';

			*tp++ = mode_char[(prefix_insn >> 4) & 3];

			info->flags

			  |= (CRIS_DIS_FLAG_MEM_TARGET2_IS_REG

			      | CRIS_DIS_FLAG_MEM_TARGET2_MEM

			      | CRIS_DIS_FLAG_MEM_TARGET_IS_REG

			      | (((prefix_insn >> 4) == 2)

				 ? 0

				 : (((prefix_insn >> 4) & 3) == 1

				    ? CRIS_DIS_FLAG_MEM_TARGET2_MEM_WORD

				    : CRIS_DIS_FLAG_MEM_TARGET2_MEM_BYTE)));

		      }

		    break;

		  default:

		    (*info->fprintf_func) (info->stream, "?prefix-bug");

		  }

		/* To mark that the prefix is used, reset it.  */

		prefix_opcodep = NULL;

	      }

	    else

	      {

		tp = format_reg (disdata, insn & 15, tp, with_reg_prefix);

		info->flags |= CRIS_DIS_FLAG_MEM_TARGET_IS_REG;

		info->target = insn & 15;

		if (insn & 0x400)

		  *tp++ = '+';

	      }

	    *tp++ = ']';

	  }

	break;

      case 'x':

	tp = format_reg (disdata, (insn >> 12) & 15, tp, with_reg_prefix);

	*tp++ = '.';

	*tp++ = mode_char[(insn >> 4) & 3];

	break;

      case 'I':

	tp = format_dec (insn & 63, tp, 0);

	break;

      case 'b':

	{

	  int where = buffer[2] + buffer[3] * 256;

	  if (where > 32767)

	    where -= 65536;

	  where += addr + ((disdata->distype == cris_dis_v32) ? 0 : 4);

	  if (insn == BA_PC_INCR_OPCODE)

	    info->insn_type = dis_branch;

	  else

	    info->insn_type = dis_condbranch;

	  info->target = (bfd_vma) where;

	  *tp = 0;

	  tp = temp;

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

				 temp, cris_cc_strings[insn >> 12]);

	  (*info->print_address_func) ((bfd_vma) where, info);

	}

      break;

    case 'c':

      tp = format_dec (insn & 31, tp, 0);

      break;

    case 'C':

      tp = format_dec (insn & 15, tp, 0);

      break;

    case 'o':

      {

	long offset = insn & 0xfe;

	bfd_vma target;

	if (insn & 1)

	  offset |= ~0xff;

	if (opcodep->match == BA_QUICK_OPCODE)

	  info->insn_type = dis_branch;

	else

	  info->insn_type = dis_condbranch;

	target = addr + ((disdata->distype == cris_dis_v32) ? 0 : 2) + offset;

	info->target = target;

	*tp = 0;

	tp = temp;

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

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

      }

      break;

    case 'Q':

    case 'O':

      {

	long number = buffer[0];

	if (number > 127)

	  number = number - 256;

	tp = format_dec (number, tp, 1);

	*tp++ = ',';

	tp = format_reg (disdata, (insn >> 12) & 15, tp, with_reg_prefix);

      }

      break;

    case 'f':

      tp = print_flags (disdata, insn, tp);

      break;

    case 'i':

      tp = format_dec ((insn & 32) ? (insn & 31) | ~31L : insn & 31, tp, 1);

      break;

    case 'P':

      {

	const struct cris_spec_reg *sregp

	  = spec_reg_info ((insn >> 12) & 15, disdata->distype);

	if (sregp->name == NULL)

	  /* Should have been caught as a non-match earlier.  */

	  *tp++ = '?';

	else

	  {

	    if (with_reg_prefix)

	      *tp++ = REGISTER_PREFIX_CHAR;

	    strcpy (tp, sregp->name);

	    tp += strlen (tp);

	  }

      }

      break;

    default:

      strcpy (tp, "???");

      tp += 3;

    }

  }

  *tp = 0;

  if (prefix_opcodep)

    (*info->fprintf_func) (info->stream, " (OOPS unused prefix \"%s: %s\")",

			   prefix_opcodep->name, prefix_opcodep->args);

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

  /* Get info for matching case-tables, if we don't have any active.

     We assume that the last constant seen is used; either in the insn

     itself or in a "move.d const,rN, sub.d rN,rM"-like sequence.  */

  if (TRACE_CASE && case_offset_counter == 0)

    {

      if (CONST_STRNEQ (opcodep->name, "sub"))

	case_offset = last_immediate;

      /* It could also be an "add", if there are negative case-values.  */

      else if (CONST_STRNEQ (opcodep->name, "add"))

	/* The first case is the negated operand to the add.  */

	case_offset = -last_immediate;

      /* A bound insn will tell us the number of cases.  */

      else if (CONST_STRNEQ (opcodep->name, "bound"))

	no_of_case_offsets = last_immediate + 1;

      /* A jump or jsr or branch breaks the chain of insns for a

	 case-table, so assume default first-case again.  */

      else if (info->insn_type == dis_jsr

	       || info->insn_type == dis_branch

	       || info->insn_type == dis_condbranch)

	case_offset = 0;

    }

}


static void socket_start_outgoing_migration(MigrationState *s,

                                            SocketAddressLegacy *saddr,

                                            Error **errp)

{

    QIOChannelSocket *sioc = qio_channel_socket_new();

    struct SocketConnectData *data = g_new0(struct SocketConnectData, 1);

    data->s = s;

    if (saddr->type == SOCKET_ADDRESS_LEGACY_KIND_INET) {

        data->hostname = g_strdup(saddr->u.inet.data->host);

    }

    qio_channel_set_name(QIO_CHANNEL(sioc), "migration-socket-outgoing");

    qio_channel_socket_connect_async(sioc,

                                     saddr,

                                     socket_outgoing_migration,

                                     data,

                                     socket_connect_data_free);

    qapi_free_SocketAddressLegacy(saddr);

}


static void define_aarch64_debug_regs(ARMCPU *cpu)

{

    /* Define breakpoint and watchpoint registers. These do nothing

     * but read as written, for now.

     */

    int i;

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

        ARMCPRegInfo dbgregs[] = {

            { .name = "DBGBVR", .state = ARM_CP_STATE_AA64,

              .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 4,

              .access = PL1_RW,

              .fieldoffset = offsetof(CPUARMState, cp15.dbgbvr[i]) },

            { .name = "DBGBCR", .state = ARM_CP_STATE_AA64,

              .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 5,

              .access = PL1_RW,

              .fieldoffset = offsetof(CPUARMState, cp15.dbgbcr[i]) },

            { .name = "DBGWVR", .state = ARM_CP_STATE_AA64,

              .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 6,

              .access = PL1_RW,

              .fieldoffset = offsetof(CPUARMState, cp15.dbgwvr[i]) },

            { .name = "DBGWCR", .state = ARM_CP_STATE_AA64,

              .opc0 = 2, .opc1 = 0, .crn = 0, .crm = i, .opc2 = 7,

              .access = PL1_RW,

              .fieldoffset = offsetof(CPUARMState, cp15.dbgwcr[i]) },

               REGINFO_SENTINEL

        };

        define_arm_cp_regs(cpu, dbgregs);

    }

}


static void add_pc_test_case(const char *mname)

{

    char *path;

    PlugTestData *data;

    if (!g_str_has_prefix(mname, "pc-")) {

        return;

    }

    data = g_new(PlugTestData, 1);

    data->machine = g_strdup(mname);

    data->cpu_model = "Haswell"; /* 1.3+ theoretically */

    data->sockets = 1;

    data->cores = 3;

    data->threads = 2;

    data->maxcpus = data->sockets * data->cores * data->threads * 2;

    if (g_str_has_suffix(mname, "-1.4") ||

        (strcmp(mname, "pc-1.3") == 0) ||

        (strcmp(mname, "pc-1.2") == 0) ||

        (strcmp(mname, "pc-1.1") == 0) ||

        (strcmp(mname, "pc-1.0") == 0) ||

        (strcmp(mname, "pc-0.15") == 0) ||

        (strcmp(mname, "pc-0.14") == 0) ||

        (strcmp(mname, "pc-0.13") == 0) ||

        (strcmp(mname, "pc-0.12") == 0) ||

        (strcmp(mname, "pc-0.11") == 0) ||

        (strcmp(mname, "pc-0.10") == 0)) {

        path = g_strdup_printf("cpu/%s/init/%ux%ux%u&maxcpus=%u",

                               mname, data->sockets, data->cores,

                               data->threads, data->maxcpus);

        qtest_add_data_func_full(path, data, test_plug_without_cpu_add,

                                 test_data_free);

        g_free(path);

    } else {

        path = g_strdup_printf("cpu/%s/add/%ux%ux%u&maxcpus=%u",

                               mname, data->sockets, data->cores,

                               data->threads, data->maxcpus);

        qtest_add_data_func_full(path, data, test_plug_with_cpu_add,

                                 test_data_free);

        g_free(path);

    }

}


void event_notifier_cleanup(EventNotifier *e)

{

    close(e->fd);

}


static void alpha_translate_init(void)

{

    int i;

    char *p;

    static int done_init = 0;

    if (done_init)

        return;

    cpu_env = tcg_global_reg_new(TCG_TYPE_PTR, TCG_AREG0, "env");

    p = cpu_reg_names;

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

        sprintf(p, "ir%d", i);

        cpu_ir[i] = tcg_global_mem_new(TCG_TYPE_I64, TCG_AREG0,

                                       offsetof(CPUState, ir[i]), p);

        p += (i < 10) ? 4 : 5;

        sprintf(p, "fir%d", i);

        cpu_fir[i] = tcg_global_mem_new(TCG_TYPE_I64, TCG_AREG0,

                                        offsetof(CPUState, fir[i]), p);

        p += (i < 10) ? 5 : 6;

    }

    cpu_pc = tcg_global_mem_new(TCG_TYPE_I64, TCG_AREG0,

                                offsetof(CPUState, pc), "pc");

    cpu_lock = tcg_global_mem_new(TCG_TYPE_I64, TCG_AREG0,

                                  offsetof(CPUState, lock), "lock");

    /* register helpers */

#undef DEF_HELPER

#define DEF_HELPER(ret, name, params) tcg_register_helper(name, #name);

#include "helper.h"

    done_init = 1;

}


static int raw_decode(AVCodecContext *avctx, void *data, int *got_frame,

                      AVPacket *avpkt)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);

    RawVideoContext *context       = avctx->priv_data;

    const uint8_t *buf             = avpkt->data;

    int buf_size                   = avpkt->size;

    int need_copy                  = !avpkt->buf || context->is_2_4_bpp || context->is_yuv2;

    int res;

    AVFrame   *frame   = data;

    AVPicture *picture = data;

    frame->pict_type        = AV_PICTURE_TYPE_I;

    frame->key_frame        = 1;

    frame->reordered_opaque = avctx->reordered_opaque;

    frame->pkt_pts          = avctx->internal->pkt->pts;

    if (buf_size < context->frame_size - (avctx->pix_fmt == AV_PIX_FMT_PAL8 ?

                                          AVPALETTE_SIZE : 0))

        return -1;

    if (need_copy)

        frame->buf[0] = av_buffer_alloc(context->frame_size);

    else

        frame->buf[0] = av_buffer_ref(avpkt->buf);

    if (!frame->buf[0])

        return AVERROR(ENOMEM);

    //2bpp and 4bpp raw in avi and mov (yes this is ugly ...)

    if (context->is_2_4_bpp) {

        int i;

        uint8_t *dst = frame->buf[0]->data;

        buf_size = context->frame_size - AVPALETTE_SIZE;

        if (avctx->bits_per_coded_sample == 4) {

            for (i = 0; 2 * i + 1 < buf_size; i++) {

                dst[2 * i + 0] = buf[i] >> 4;

                dst[2 * i + 1] = buf[i] & 15;

            }

        } else {

            for (i = 0; 4 * i + 3 < buf_size; i++) {

                dst[4 * i + 0] = buf[i] >> 6;

                dst[4 * i + 1] = buf[i] >> 4 & 3;

                dst[4 * i + 2] = buf[i] >> 2 & 3;

                dst[4 * i + 3] = buf[i]      & 3;

            }

        }

        buf = dst;

    } else if (need_copy) {

        memcpy(frame->buf[0]->data, buf, FFMIN(buf_size, context->frame_size));

        buf = frame->buf[0]->data;

    }

    if (avctx->codec_tag == MKTAG('A', 'V', '1', 'x') ||

        avctx->codec_tag == MKTAG('A', 'V', 'u', 'p'))

        buf += buf_size - context->frame_size;

    if ((res = avpicture_fill(picture, buf, avctx->pix_fmt,

                              avctx->width, avctx->height)) < 0)

        return res;

    if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {

        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE,

                                                     NULL);

        if (pal) {

            av_buffer_unref(&context->palette);

            context->palette = av_buffer_alloc(AVPALETTE_SIZE);

            if (!context->palette)

                return AVERROR(ENOMEM);

            memcpy(context->palette->data, pal, AVPALETTE_SIZE);

            frame->palette_has_changed = 1;

        }

    }

    if ((avctx->pix_fmt == AV_PIX_FMT_PAL8 && buf_size < context->frame_size) ||

        (desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)) {

        frame->buf[1]  = av_buffer_ref(context->palette);

        if (!frame->buf[1])

            return AVERROR(ENOMEM);

        frame->data[1] = frame->buf[1]->data;

    }

    if (avctx->pix_fmt == AV_PIX_FMT_BGR24 &&

        ((frame->linesize[0] + 3) & ~3) * avctx->height <= buf_size)

        frame->linesize[0] = (frame->linesize[0] + 3) & ~3;

    if (context->flip)

        flip(avctx, picture);

    if (avctx->codec_tag == MKTAG('Y', 'V', '1', '2') ||

        avctx->codec_tag == MKTAG('Y', 'V', '1', '6') ||

        avctx->codec_tag == MKTAG('Y', 'V', '2', '4') ||

        avctx->codec_tag == MKTAG('Y', 'V', 'U', '9'))

        FFSWAP(uint8_t *, picture->data[1], picture->data[2]);

    if (avctx->codec_tag == AV_RL32("yuv2") &&

        avctx->pix_fmt   == AV_PIX_FMT_YUYV422) {

        int x, y;

        uint8_t *line = picture->data[0];

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

            for (x = 0; x < avctx->width; x++)

                line[2 * x + 1] ^= 0x80;

            line += picture->linesize[0];

        }

    }

    *got_frame = 1;

    return buf_size;

}


static void *data_plane_thread(void *opaque)

{

    VirtIOBlockDataPlane *s = opaque;

    do {

        aio_poll(s->ctx, true);

    } while (!s->stopping || s->num_reqs > 0);

    return NULL;

}


static int ppc_hash32_check_prot(int prot, int rwx)

{

    int ret;

    if (rwx == 2) {

        if (prot & PAGE_EXEC) {

            ret = 0;

        } else {

            ret = -2;

        }

    } else if (rwx) {

        if (prot & PAGE_WRITE) {

            ret = 0;

        } else {

            ret = -2;

        }

    } else {

        if (prot & PAGE_READ) {

            ret = 0;

        } else {

            ret = -2;

        }

    }

    return ret;

}


static void do_inject_mce(Monitor *mon, const QDict *qdict)

{

    CPUState *cenv;

    int cpu_index = qdict_get_int(qdict, "cpu_index");

    int bank = qdict_get_int(qdict, "bank");

    uint64_t status = qdict_get_int(qdict, "status");

    uint64_t mcg_status = qdict_get_int(qdict, "mcg_status");

    uint64_t addr = qdict_get_int(qdict, "addr");

    uint64_t misc = qdict_get_int(qdict, "misc");

    int broadcast = qdict_get_try_bool(qdict, "broadcast", 0);

    for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu) {

        if (cenv->cpu_index == cpu_index && cenv->mcg_cap) {

            cpu_x86_inject_mce(cenv, bank, status, mcg_status, addr, misc,

                               broadcast);

            break;

        }

    }

}


static void spice_register_types(void)

{

    qemu_spice_init();

}


static int pci_grackle_init_device(SysBusDevice *dev)

{

    GrackleState *s;

    int pci_mem_config, pci_mem_data;

    s = FROM_SYSBUS(GrackleState, dev);

    pci_mem_config = cpu_register_io_memory(pci_grackle_config_read,

                                            pci_grackle_config_write, s);

    pci_mem_data = cpu_register_io_memory(pci_grackle_read,

                                          pci_grackle_write,

                                          &s->host_state);

    sysbus_init_mmio(dev, 0x1000, pci_mem_config);

    sysbus_init_mmio(dev, 0x1000, pci_mem_data);

    register_savevm("grackle", 0, 1, pci_grackle_save, pci_grackle_load,

                    &s->host_state);

    qemu_register_reset(pci_grackle_reset, &s->host_state);

    return 0;

}


int qemu_strtoul(const char *nptr, const char **endptr, int base,

                 unsigned long *result)

{

    char *ep;

    int err = 0;

    if (!nptr) {

        if (endptr) {

            *endptr = nptr;

        }

        err = -EINVAL;

    } else {

        errno = 0;

        *result = strtoul(nptr, &ep, base);

        /* Windows returns 1 for negative out-of-range values.  */

        if (errno == ERANGE) {

            *result = -1;

        }

        err = check_strtox_error(nptr, ep, endptr, errno);

    }

    return err;

}


static void rtl8139_cleanup(NetClientState *nc)

{

    RTL8139State *s = qemu_get_nic_opaque(nc);

    s->nic = NULL;

}


static int uhci_handle_td(UHCIState *s, UHCI_TD *td, uint32_t *int_mask,

                          int completion)

{

    uint8_t pid;

    int len = 0, max_len, err, ret = 0;

    /* ??? This is wrong for async completion.  */

    if (td->ctrl & TD_CTRL_IOC) {

        *int_mask |= 0x01;

    }

    if (!(td->ctrl & TD_CTRL_ACTIVE))

        return 1;

    /* TD is active */

    max_len = ((td->token >> 21) + 1) & 0x7ff;

    pid = td->token & 0xff;

    if (completion && (s->async_qh || s->async_frame_addr)) {

        ret = s->usb_packet.len;

        if (ret >= 0) {

            len = ret;

            if (len > max_len) {

                len = max_len;

                ret = USB_RET_BABBLE;

            }

            if (len > 0) {

                /* write the data back */

                cpu_physical_memory_write(td->buffer, s->usb_buf, len);

            }

        } else {

            len = 0;

        }

        s->async_qh = 0;

        s->async_frame_addr = 0;

    } else if (!completion) {

        s->usb_packet.pid = pid;

        s->usb_packet.devaddr = (td->token >> 8) & 0x7f;

        s->usb_packet.devep = (td->token >> 15) & 0xf;

        s->usb_packet.data = s->usb_buf;

        s->usb_packet.len = max_len;

        s->usb_packet.complete_cb = uhci_async_complete_packet;

        s->usb_packet.complete_opaque = s;

        switch(pid) {

        case USB_TOKEN_OUT:

        case USB_TOKEN_SETUP:

            cpu_physical_memory_read(td->buffer, s->usb_buf, max_len);

            ret = uhci_broadcast_packet(s, &s->usb_packet);

            len = max_len;

            break;

        case USB_TOKEN_IN:

            ret = uhci_broadcast_packet(s, &s->usb_packet);

            if (ret >= 0) {

                len = ret;

                if (len > max_len) {

                    len = max_len;

                    ret = USB_RET_BABBLE;

                }

                if (len > 0) {

                    /* write the data back */

                    cpu_physical_memory_write(td->buffer, s->usb_buf, len);

                }

            } else {

                len = 0;

            }

            break;

        default:

            /* invalid pid : frame interrupted */

            s->status |= UHCI_STS_HCPERR;

            uhci_update_irq(s);

            return -1;

        }

    }

    if (ret == USB_RET_ASYNC) {

        return 2;

    }

    if (td->ctrl & TD_CTRL_IOS)

        td->ctrl &= ~TD_CTRL_ACTIVE;

    if (ret >= 0) {

        td->ctrl = (td->ctrl & ~0x7ff) | ((len - 1) & 0x7ff);

        /* The NAK bit may have been set by a previous frame, so clear it

           here.  The docs are somewhat unclear, but win2k relies on this

           behavior.  */

        td->ctrl &= ~(TD_CTRL_ACTIVE | TD_CTRL_NAK);

        if (pid == USB_TOKEN_IN &&

            (td->ctrl & TD_CTRL_SPD) &&

            len < max_len) {

            *int_mask |= 0x02;

            /* short packet: do not update QH */

            return 1;

        } else {

            /* success */

            return 0;

        }

    } else {

        switch(ret) {

        default:

        case USB_RET_NODEV:

        do_timeout:

            td->ctrl |= TD_CTRL_TIMEOUT;

            err = (td->ctrl >> TD_CTRL_ERROR_SHIFT) & 3;

            if (err != 0) {

                err--;

                if (err == 0) {

                    td->ctrl &= ~TD_CTRL_ACTIVE;

                    s->status |= UHCI_STS_USBERR;

                    uhci_update_irq(s);

                }

            }

            td->ctrl = (td->ctrl & ~(3 << TD_CTRL_ERROR_SHIFT)) |

                (err << TD_CTRL_ERROR_SHIFT);

            return 1;

        case USB_RET_NAK:

            td->ctrl |= TD_CTRL_NAK;

            if (pid == USB_TOKEN_SETUP)

                goto do_timeout;

            return 1;

        case USB_RET_STALL:

            td->ctrl |= TD_CTRL_STALL;

            td->ctrl &= ~TD_CTRL_ACTIVE;

            return 1;

        case USB_RET_BABBLE:

            td->ctrl |= TD_CTRL_BABBLE | TD_CTRL_STALL;

            td->ctrl &= ~TD_CTRL_ACTIVE;

            /* frame interrupted */

            return -1;

        }

    }

}


static void option_rom_reset(void *_rrd)

{

    RomResetData *rrd = _rrd;

    cpu_physical_memory_write_rom(rrd->addr, rrd->data, rrd->size);

}


static int v9fs_synth_lremovexattr(FsContext *ctx,

                                   V9fsPath *path, const char *name)

{

    errno = ENOTSUP;

    return -1;

}


static inline int get_phys_addr(CPUState *env, uint32_t address,

                                int access_type, int is_user,

                                uint32_t *phys_ptr, int *prot,

                                target_ulong *page_size)

{

    /* Fast Context Switch Extension.  */

    if (address < 0x02000000)

        address += env->cp15.c13_fcse;

    if ((env->cp15.c1_sys & 1) == 0) {

        /* MMU/MPU disabled.  */

        *phys_ptr = address;

        *prot = PAGE_READ | PAGE_WRITE;

        *page_size = TARGET_PAGE_SIZE;

        return 0;

    } else if (arm_feature(env, ARM_FEATURE_MPU)) {

        *page_size = TARGET_PAGE_SIZE;

	return get_phys_addr_mpu(env, address, access_type, is_user, phys_ptr,

				 prot);

    } else if (env->cp15.c1_sys & (1 << 23)) {

        return get_phys_addr_v6(env, address, access_type, is_user, phys_ptr,

                                prot, page_size);

    } else {

        return get_phys_addr_v5(env, address, access_type, is_user, phys_ptr,

                                prot, page_size);

    }

}


static uint64_t a9_scu_read(void *opaque, target_phys_addr_t offset,

                            unsigned size)

{

    a9mp_priv_state *s = (a9mp_priv_state *)opaque;

    switch (offset) {

    case 0x00: /* Control */

        return s->scu_control;

    case 0x04: /* Configuration */

        return (((1 << s->num_cpu) - 1) << 4) | (s->num_cpu - 1);

    case 0x08: /* CPU Power Status */

        return s->scu_status;

    case 0x09: /* CPU status.  */

        return s->scu_status >> 8;

    case 0x0a: /* CPU status.  */

        return s->scu_status >> 16;

    case 0x0b: /* CPU status.  */

        return s->scu_status >> 24;

    case 0x0c: /* Invalidate All Registers In Secure State */

        return 0;

    case 0x40: /* Filtering Start Address Register */

    case 0x44: /* Filtering End Address Register */

        /* RAZ/WI, like an implementation with only one AXI master */

        return 0;

    case 0x50: /* SCU Access Control Register */

    case 0x54: /* SCU Non-secure Access Control Register */

        /* unimplemented, fall through */

    default:

        return 0;

    }

}


uint32_t ldl_phys(target_phys_addr_t addr)

{

    return ldl_phys_internal(addr, DEVICE_NATIVE_ENDIAN);

}


void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign,

                                               bool set_handler)

{

    if (assign && set_handler) {

        event_notifier_set_handler(&vq->host_notifier, true,

                                   virtio_queue_host_notifier_read);

    } else {

        event_notifier_set_handler(&vq->host_notifier, true, NULL);

    }

    if (!assign) {

        /* Test and clear notifier before after disabling event,

         * in case poll callback didn't have time to run. */

        virtio_queue_host_notifier_read(&vq->host_notifier);

    }

}


bool qemu_clock_use_for_deadline(QEMUClockType type)

{

    return !(use_icount && (type == QEMU_CLOCK_VIRTUAL));

}


static void term_forward_char(void)

{

    if (term_cmd_buf_index < term_cmd_buf_size) {

        term_cmd_buf_index++;

    }

}


static int input_initialise(struct XenDevice *xendev)

{

    struct XenInput *in = container_of(xendev, struct XenInput, c.xendev);

    int rc;

    if (!in->c.con) {

        xen_pv_printf(xendev, 1, "ds not set (yet)\n");

        return -1;

    }

    rc = common_bind(&in->c);

    if (rc != 0)

	return rc;

    qemu_add_kbd_event_handler(xenfb_key_event, in);

    return 0;

}


int audio_pcm_sw_read (SWVoiceIn *sw, void *buf, int size)

{

    HWVoiceIn *hw = sw->hw;

    int samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;

    st_sample_t *src, *dst = sw->buf;

    rpos = audio_pcm_sw_get_rpos_in (sw) % hw->samples;

    live = hw->total_samples_captured - sw->total_hw_samples_acquired;

    if (audio_bug (AUDIO_FUNC, live < 0 || live > hw->samples)) {

        dolog ("live_in=%d hw->samples=%d\n", live, hw->samples);

        return 0;

    }

    samples = size >> sw->info.shift;

    if (!live) {

        return 0;

    }

    swlim = (live * sw->ratio) >> 32;

    swlim = audio_MIN (swlim, samples);

    while (swlim) {

        src = hw->conv_buf + rpos;

        isamp = hw->wpos - rpos;

        /* XXX: <= ? */

        if (isamp <= 0) {

            isamp = hw->samples - rpos;

        }

        if (!isamp) {

            break;

        }

        osamp = swlim;

        if (audio_bug (AUDIO_FUNC, osamp < 0)) {

            dolog ("osamp=%d\n", osamp);

            return 0;

        }

        st_rate_flow (sw->rate, src, dst, &isamp, &osamp);

        swlim -= osamp;

        rpos = (rpos + isamp) % hw->samples;

        dst += osamp;

        ret += osamp;

        total += isamp;

    }

    sw->clip (buf, sw->buf, ret);

    sw->total_hw_samples_acquired += total;

    return ret << sw->info.shift;

}


static void v9fs_wstat_post_chown(V9fsState *s, V9fsWstatState *vs, int err)

{

    V9fsFidState *fidp;

    if (err < 0) {

        goto out;

    }

    if (vs->v9stat.name.size != 0) {

        char *old_name, *new_name;

        char *end;

        old_name = vs->fidp->path.data;

        end = strrchr(old_name, '/');

        if (end) {

            end++;

        } else {

            end = old_name;

        }

        new_name = qemu_mallocz(end - old_name + vs->v9stat.name.size + 1);

        memcpy(new_name, old_name, end - old_name);

        memcpy(new_name + (end - old_name), vs->v9stat.name.data,

                vs->v9stat.name.size);

        vs->nname.data = new_name;

        vs->nname.size = strlen(new_name);

        if (strcmp(new_name, vs->fidp->path.data) != 0) {

            if (v9fs_do_rename(s, &vs->fidp->path, &vs->nname)) {

                err = -errno;

            } else {

                /*

                 * Fixup fid's pointing to the old name to

                 * start pointing to the new name

                 */

                for (fidp = s->fid_list; fidp; fidp = fidp->next) {

                    if (vs->fidp == fidp) {

                        /*

                         * we replace name of this fid towards the end

                         * so that our below strcmp will work

                         */

                        continue;

                    }

                    if (!strncmp(vs->fidp->path.data, fidp->path.data,

                                 strlen(vs->fidp->path.data))) {

                        /* replace the name */

                        v9fs_fix_path(&fidp->path, &vs->nname,

                                      strlen(vs->fidp->path.data));

                    }

                }

                v9fs_string_copy(&vs->fidp->path, &vs->nname);

            }

        }

    }

    v9fs_wstat_post_rename(s, vs, err);

    return;

out:

    v9fs_stat_free(&vs->v9stat);

    complete_pdu(s, vs->pdu, err);

    qemu_free(vs);

}


static int mpeg4video_probe(AVProbeData *probe_packet)

{

    uint32_t temp_buffer= -1;

    int VO=0, VOL=0, VOP = 0, VISO = 0, res=0;

    int i;

    for(i=0; i<probe_packet->buf_size; i++){

        temp_buffer = (temp_buffer<<8) + probe_packet->buf[i];

        if ((temp_buffer & 0xffffff00) != 0x100)

            continue;

        if (temp_buffer == VOP_START_CODE)                         VOP++;

        else if (temp_buffer == VISUAL_OBJECT_START_CODE)          VISO++;

        else if (temp_buffer < 0x120)                              VO++;

        else if (temp_buffer < 0x130)                              VOL++;

        else if (   !(0x1AF < temp_buffer && temp_buffer < 0x1B7)

                 && !(0x1B9 < temp_buffer && temp_buffer < 0x1C4)) res++;

    }

    if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res==0)

        return VOP+VO > 4 ? AVPROBE_SCORE_EXTENSION : AVPROBE_SCORE_EXTENSION/2;

    return 0;

}


static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,

                          int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

                          BlockDriverCompletionFunc *cb, void *opaque)

{

    BDRVRawState *s = bs->opaque;

    return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,

                       cb, opaque, QEMU_AIO_WRITE);

}


static int usb_serial_handle_control(USBDevice *dev, int request, int value,

                                  int index, int length, uint8_t *data)

{

    USBSerialState *s = (USBSerialState *)dev;

    int ret;

    DPRINTF("got control %x, value %x\n",request, value);

    ret = usb_desc_handle_control(dev, request, value, index, length, data);

    if (ret >= 0) {

        return ret;

    }

    ret = 0;

    switch (request) {

    case DeviceRequest | USB_REQ_GET_STATUS:

        data[0] = (0 << USB_DEVICE_SELF_POWERED) |

            (dev->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP);

        data[1] = 0x00;

        ret = 2;

        break;

    case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:

        if (value == USB_DEVICE_REMOTE_WAKEUP) {

            dev->remote_wakeup = 0;

        } else {

            goto fail;

        }

        ret = 0;

        break;

    case DeviceOutRequest | USB_REQ_SET_FEATURE:

        if (value == USB_DEVICE_REMOTE_WAKEUP) {

            dev->remote_wakeup = 1;

        } else {

            goto fail;

        }

        ret = 0;

        break;

    case DeviceRequest | USB_REQ_GET_CONFIGURATION:

        data[0] = 1;

        ret = 1;

        break;

    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:

        ret = 0;

        break;

    case DeviceRequest | USB_REQ_GET_INTERFACE:

        data[0] = 0;

        ret = 1;

        break;

    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:

        ret = 0;

        break;

    case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:

        ret = 0;

        break;

        /* Class specific requests.  */

    case DeviceOutVendor | FTDI_RESET:

        switch (value) {

        case FTDI_RESET_SIO:

            usb_serial_reset(s);

            break;

        case FTDI_RESET_RX:

            s->recv_ptr = 0;

            s->recv_used = 0;

            /* TODO: purge from char device */

            break;

        case FTDI_RESET_TX:

            /* TODO: purge from char device */

            break;

        }

        break;

    case DeviceOutVendor | FTDI_SET_MDM_CTRL:

    {

        static int flags;

        qemu_chr_ioctl(s->cs,CHR_IOCTL_SERIAL_GET_TIOCM, &flags);

        if (value & FTDI_SET_RTS) {

            if (value & FTDI_RTS)

                flags |= CHR_TIOCM_RTS;

            else

                flags &= ~CHR_TIOCM_RTS;

        }

        if (value & FTDI_SET_DTR) {

            if (value & FTDI_DTR)

                flags |= CHR_TIOCM_DTR;

            else

                flags &= ~CHR_TIOCM_DTR;

        }

        qemu_chr_ioctl(s->cs,CHR_IOCTL_SERIAL_SET_TIOCM, &flags);

        break;

    }

    case DeviceOutVendor | FTDI_SET_FLOW_CTRL:

        /* TODO: ioctl */

        break;

    case DeviceOutVendor | FTDI_SET_BAUD: {

        static const int subdivisors8[8] = { 0, 4, 2, 1, 3, 5, 6, 7 };

        int subdivisor8 = subdivisors8[((value & 0xc000) >> 14)

                                     | ((index & 1) << 2)];

        int divisor = value & 0x3fff;

        /* chip special cases */

        if (divisor == 1 && subdivisor8 == 0)

            subdivisor8 = 4;

        if (divisor == 0 && subdivisor8 == 0)

            divisor = 1;

        s->params.speed = (48000000 / 2) / (8 * divisor + subdivisor8);

        qemu_chr_ioctl(s->cs, CHR_IOCTL_SERIAL_SET_PARAMS, &s->params);

        break;

    }

    case DeviceOutVendor | FTDI_SET_DATA:

        switch (value & FTDI_PARITY) {

            case 0:

                s->params.parity = 'N';

                break;

            case FTDI_ODD:

                s->params.parity = 'O';

                break;

            case FTDI_EVEN:

                s->params.parity = 'E';

                break;

            default:

                DPRINTF("unsupported parity %d\n", value & FTDI_PARITY);

                goto fail;

        }

        switch (value & FTDI_STOP) {

            case FTDI_STOP1:

                s->params.stop_bits = 1;

                break;

            case FTDI_STOP2:

                s->params.stop_bits = 2;

                break;

            default:

                DPRINTF("unsupported stop bits %d\n", value & FTDI_STOP);

                goto fail;

        }

        qemu_chr_ioctl(s->cs, CHR_IOCTL_SERIAL_SET_PARAMS, &s->params);

        /* TODO: TX ON/OFF */

        break;

    case DeviceInVendor | FTDI_GET_MDM_ST:

        data[0] = usb_get_modem_lines(s) | 1;

        data[1] = 0;

        ret = 2;

        break;

    case DeviceOutVendor | FTDI_SET_EVENT_CHR:

        /* TODO: handle it */

        s->event_chr = value;

        break;

    case DeviceOutVendor | FTDI_SET_ERROR_CHR:

        /* TODO: handle it */

        s->error_chr = value;

        break;

    case DeviceOutVendor | FTDI_SET_LATENCY:

        s->latency = value;

        break;

    case DeviceInVendor | FTDI_GET_LATENCY:

        data[0] = s->latency;

        ret = 1;

        break;

    default:

    fail:

        DPRINTF("got unsupported/bogus control %x, value %x\n", request, value);

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


static void test_acpi_piix4_tcg_cphp(void)

{

    test_data data;

    memset(&data, 0, sizeof(data));

    data.machine = MACHINE_PC;

    data.variant = ".cphp";

    test_acpi_one("-smp 2,cores=3,sockets=2,maxcpus=6"

                  " -numa node -numa node",

                  &data);

    free_test_data(&data);

}


static void ide_dev_set_bootindex(Object *obj, Visitor *v, const char *name,

                                  void *opaque, Error **errp)

{

    IDEDevice *d = IDE_DEVICE(obj);

    int32_t boot_index;

    Error *local_err = NULL;

    visit_type_int32(v, name, &boot_index, &local_err);

    if (local_err) {

        goto out;

    }

    /* check whether bootindex is present in fw_boot_order list  */

    check_boot_index(boot_index, &local_err);

    if (local_err) {

        goto out;

    }

    /* change bootindex to a new one */

    d->conf.bootindex = boot_index;

    if (d->unit != -1) {

        add_boot_device_path(d->conf.bootindex, &d->qdev,

                             d->unit ? "/disk@1" : "/disk@0");

    }

out:

    if (local_err) {

        error_propagate(errp, local_err);

    }

}


static void virtser_port_device_realize(DeviceState *dev, Error **errp)

{

    VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev);

    VirtIOSerialPortClass *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);

    VirtIOSerialBus *bus = VIRTIO_SERIAL_BUS(qdev_get_parent_bus(dev));

    int max_nr_ports;

    bool plugging_port0;

    Error *err = NULL;

    port->vser = bus->vser;

    port->bh = qemu_bh_new(flush_queued_data_bh, port);

    assert(vsc->have_data);

    /*

     * Is the first console port we're seeing? If so, put it up at

     * location 0. This is done for backward compatibility (old

     * kernel, new qemu).

     */

    plugging_port0 = vsc->is_console && !find_port_by_id(port->vser, 0);

    if (find_port_by_id(port->vser, port->id)) {

        error_setg(errp, "virtio-serial-bus: A port already exists at id %u",

                   port->id);

        return;

    }

    if (port->name != NULL && find_port_by_name(port->name)) {

        error_setg(errp, "virtio-serial-bus: A port already exists by name %s",

                   port->name);

        return;

    }

    if (port->id == VIRTIO_CONSOLE_BAD_ID) {

        if (plugging_port0) {

            port->id = 0;

        } else {

            port->id = find_free_port_id(port->vser);

            if (port->id == VIRTIO_CONSOLE_BAD_ID) {

                error_setg(errp, "virtio-serial-bus: Maximum port limit for "

                                 "this device reached");

                return;

            }

        }

    }

    max_nr_ports = port->vser->serial.max_virtserial_ports;

    if (port->id >= max_nr_ports) {

        error_setg(errp, "virtio-serial-bus: Out-of-range port id specified, "

                         "max. allowed: %u", max_nr_ports - 1);

        return;

    }

    vsc->realize(dev, &err);

    if (err != NULL) {

        error_propagate(errp, err);

        return;

    }

    port->elem.out_num = 0;

}


void *av_malloc(unsigned int size)

{

    void *ptr = NULL;

#if CONFIG_MEMALIGN_HACK

    long diff;

#endif

    /* let's disallow possible ambiguous cases */

    if(size > (INT_MAX-16) )

        return NULL;

#if CONFIG_MEMALIGN_HACK

    ptr = malloc(size+16);

    if(!ptr)

        return ptr;

    diff= ((-(long)ptr - 1)&15) + 1;

    ptr = (char*)ptr + diff;

    ((char*)ptr)[-1]= diff;

#elif HAVE_POSIX_MEMALIGN

    posix_memalign(&ptr,16,size);

#elif HAVE_MEMALIGN

    ptr = memalign(16,size);

    /* Why 64?

       Indeed, we should align it:

         on 4 for 386

         on 16 for 486

         on 32 for 586, PPro - K6-III

         on 64 for K7 (maybe for P3 too).

       Because L1 and L2 caches are aligned on those values.

       But I don't want to code such logic here!

     */

     /* Why 16?

        Because some CPUs need alignment, for example SSE2 on P4, & most RISC CPUs

        it will just trigger an exception and the unaligned load will be done in the

        exception handler or it will just segfault (SSE2 on P4).

        Why not larger? Because I did not see a difference in benchmarks ...

     */

     /* benchmarks with P3

        memalign(64)+1          3071,3051,3032

        memalign(64)+2          3051,3032,3041

        memalign(64)+4          2911,2896,2915

        memalign(64)+8          2545,2554,2550

        memalign(64)+16         2543,2572,2563

        memalign(64)+32         2546,2545,2571

        memalign(64)+64         2570,2533,2558

        BTW, malloc seems to do 8-byte alignment by default here.

     */

#else

    ptr = malloc(size);

#endif

    return ptr;

}


static int do_token_in(USBDevice *s, USBPacket *p)

{

    int request, value, index;

    int ret = 0;

    if (p->devep != 0)

        return s->info->handle_data(s, p);

    request = (s->setup_buf[0] << 8) | s->setup_buf[1];

    value   = (s->setup_buf[3] << 8) | s->setup_buf[2];

    index   = (s->setup_buf[5] << 8) | s->setup_buf[4];

    switch(s->setup_state) {

    case SETUP_STATE_ACK:

        if (!(s->setup_buf[0] & USB_DIR_IN)) {

            ret = s->info->handle_control(s, p, request, value, index,

                                          s->setup_len, s->data_buf);

            if (ret == USB_RET_ASYNC) {

                return USB_RET_ASYNC;

            }

            s->setup_state = SETUP_STATE_IDLE;

            if (ret > 0)

                return 0;

            return ret;

        }

        /* return 0 byte */

        return 0;

    case SETUP_STATE_DATA:

        if (s->setup_buf[0] & USB_DIR_IN) {

            int len = s->setup_len - s->setup_index;

            if (len > p->len)

                len = p->len;

            memcpy(p->data, s->data_buf + s->setup_index, len);

            s->setup_index += len;

            if (s->setup_index >= s->setup_len)

                s->setup_state = SETUP_STATE_ACK;

            return len;

        }

        s->setup_state = SETUP_STATE_IDLE;

        return USB_RET_STALL;

    default:

        return USB_RET_STALL;

    }

}


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

{

    CharDriverState *chr = NULL;

    TCPCharDriver *s = NULL;

    int fd = -1;

    int is_listen;

    int is_waitconnect;

    int do_nodelay;

    int is_unix;

    int is_telnet;

    int ret;

    is_listen      = qemu_opt_get_bool(opts, "server", 0);

    is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);

    is_telnet      = qemu_opt_get_bool(opts, "telnet", 0);

    do_nodelay     = !qemu_opt_get_bool(opts, "delay", 1);

    is_unix        = qemu_opt_get(opts, "path") != NULL;

    if (!is_listen)

        is_waitconnect = 0;

    chr = g_malloc0(sizeof(CharDriverState));

    s = g_malloc0(sizeof(TCPCharDriver));

    if (is_unix) {

        if (is_listen) {

            fd = unix_listen_opts(opts);

        } else {

            fd = unix_connect_opts(opts);

        }

    } else {

        if (is_listen) {

            fd = inet_listen_opts(opts, 0);

        } else {

            fd = inet_connect_opts(opts);

        }

    }

    if (fd < 0) {

        ret = -errno;

        goto fail;

    }

    if (!is_waitconnect)

        socket_set_nonblock(fd);

    s->connected = 0;

    s->fd = -1;

    s->listen_fd = -1;

    s->msgfd = -1;

    s->is_unix = is_unix;

    s->do_nodelay = do_nodelay && !is_unix;

    chr->opaque = s;

    chr->chr_write = tcp_chr_write;

    chr->chr_close = tcp_chr_close;

    chr->get_msgfd = tcp_get_msgfd;

    chr->chr_add_client = tcp_chr_add_client;

    if (is_listen) {

        s->listen_fd = fd;

        qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);

        if (is_telnet)

            s->do_telnetopt = 1;

    } else {

        s->connected = 1;

        s->fd = fd;

        socket_set_nodelay(fd);

        tcp_chr_connect(chr);

    }

    /* for "info chardev" monitor command */

    chr->filename = g_malloc(256);

    if (is_unix) {

        snprintf(chr->filename, 256, "unix:%s%s",

                 qemu_opt_get(opts, "path"),

                 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");

    } else if (is_telnet) {

        snprintf(chr->filename, 256, "telnet:%s:%s%s",

                 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),

                 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");

    } else {

        snprintf(chr->filename, 256, "tcp:%s:%s%s",

                 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),

                 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");

    }

    if (is_listen && is_waitconnect) {

        printf("QEMU waiting for connection on: %s\n",

               chr->filename);

        tcp_chr_accept(chr);

        socket_set_nonblock(s->listen_fd);

    }

    *_chr = chr;

    return 0;

 fail:

    if (fd >= 0)

        closesocket(fd);

    g_free(s);

    g_free(chr);

    return ret;

}


static void imx_serial_write(void *opaque, hwaddr offset,

                             uint64_t value, unsigned size)

{

    IMXSerialState *s = (IMXSerialState *)opaque;

    unsigned char ch;

    DPRINTF("write(offset=0x%" HWADDR_PRIx ", value = 0x%x) to %s\n",

            offset, (unsigned int)value, s->chr ? s->chr->label : "NODEV");

    switch (offset >> 2) {

    case 0x10: /* UTXD */

        ch = value;

        if (s->ucr2 & UCR2_TXEN) {

            if (s->chr) {

                qemu_chr_fe_write(s->chr, &ch, 1);

            }

            s->usr1 &= ~USR1_TRDY;

            imx_update(s);

            s->usr1 |= USR1_TRDY;

            imx_update(s);

        }

        break;

    case 0x20: /* UCR1 */

        s->ucr1 = value & 0xffff;

        DPRINTF("write(ucr1=%x)\n", (unsigned int)value);

        imx_update(s);

        break;

    case 0x21: /* UCR2 */

        /*

         * Only a few bits in control register 2 are implemented as yet.

         * If it's intended to use a real serial device as a back-end, this

         * register will have to be implemented more fully.

         */

        if (!(value & UCR2_SRST)) {

            imx_serial_reset(s);

            imx_update(s);

            value |= UCR2_SRST;

        }

        if (value & UCR2_RXEN) {

            if (!(s->ucr2 & UCR2_RXEN)) {

                if (s->chr) {

                    qemu_chr_accept_input(s->chr);

                }

            }

        }

        s->ucr2 = value & 0xffff;

        break;

    case 0x25: /* USR1 */

        value &= USR1_AWAKE | USR1_AIRINT | USR1_DTRD | USR1_AGTIM |

                 USR1_FRAMERR | USR1_ESCF | USR1_RTSD | USR1_PARTYER;

        s->usr1 &= ~value;

        break;

    case 0x26: /* USR2 */

        /*

         * Writing 1 to some bits clears them; all other

         * values are ignored

         */

        value &= USR2_ADET | USR2_DTRF | USR2_IDLE | USR2_ACST |

                 USR2_RIDELT | USR2_IRINT | USR2_WAKE |

                 USR2_DCDDELT | USR2_RTSF | USR2_BRCD | USR2_ORE;

        s->usr2 &= ~value;

        break;

    /*

     * Linux expects to see what it writes to these registers

     * We don't currently alter the baud rate

     */

    case 0x29: /* UBIR */

        s->ubrc = value & 0xffff;

        break;

    case 0x2a: /* UBMR */

        s->ubmr = value & 0xffff;

        break;

    case 0x2c: /* One ms reg */

        s->onems = value & 0xffff;

        break;

    case 0x24: /* FIFO control register */

        s->ufcr = value & 0xffff;

        break;

    case 0x22: /* UCR3 */

        s->ucr3 = value & 0xffff;

        break;

    case 0x2d: /* UTS1 */

    case 0x23: /* UCR4 */

        qemu_log_mask(LOG_UNIMP, "[%s]%s: Unimplemented reg 0x%"

                      HWADDR_PRIx "\n", TYPE_IMX_SERIAL, __func__, offset);

        /* TODO */

        break;

    default:

        qemu_log_mask(LOG_GUEST_ERROR, "[%s]%s: Bad register at offset 0x%"

                      HWADDR_PRIx "\n", TYPE_IMX_SERIAL, __func__, offset);

    }

}


static void numa_add(const char *optarg)

{

    char option[128];

    char *endptr;

    unsigned long long value, endvalue;

    unsigned long long nodenr;

    value = endvalue = 0ULL;

    optarg = get_opt_name(option, 128, optarg, ',');

    if (*optarg == ',') {

        optarg++;

    }

    if (!strcmp(option, "node")) {

        if (nb_numa_nodes >= MAX_NODES) {

            fprintf(stderr, "qemu: too many NUMA nodes\n");

            exit(1);

        }

        if (get_param_value(option, 128, "nodeid", optarg) == 0) {

            nodenr = nb_numa_nodes;

        } else {

            nodenr = strtoull(option, NULL, 10);

        }

        if (nodenr >= MAX_NODES) {

            fprintf(stderr, "qemu: invalid NUMA nodeid: %llu\n", nodenr);

            exit(1);

        }

        if (get_param_value(option, 128, "mem", optarg) == 0) {

            node_mem[nodenr] = 0;

        } else {

            int64_t sval;

            sval = strtosz(option, &endptr);

            if (sval < 0 || *endptr) {

                fprintf(stderr, "qemu: invalid numa mem size: %s\n", optarg);

                exit(1);

            }

            node_mem[nodenr] = sval;

        }

        if (get_param_value(option, 128, "cpus", optarg) != 0) {

            value = strtoull(option, &endptr, 10);

            if (*endptr == '-') {

                endvalue = strtoull(endptr+1, &endptr, 10);

            } else {

                endvalue = value;

            }

            if (!(endvalue < MAX_CPUMASK_BITS)) {

                endvalue = MAX_CPUMASK_BITS - 1;

                fprintf(stderr,

                    "A max of %d CPUs are supported in a guest\n",

                     MAX_CPUMASK_BITS);

            }

            bitmap_set(node_cpumask[nodenr], value, endvalue-value+1);

        }

        nb_numa_nodes++;

    } else {

        fprintf(stderr, "Invalid -numa option: %s\n", option);

        exit(1);

    }

}


static int sap_read_header(AVFormatContext *s)

{

    struct SAPState *sap = s->priv_data;

    char host[1024], path[1024], url[1024];

    uint8_t recvbuf[RTP_MAX_PACKET_LENGTH];

    int port;

    int ret, i;

    AVInputFormat* infmt;

    if (!ff_network_init())

        return AVERROR(EIO);

    av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,

                 path, sizeof(path), s->filename);

    if (port < 0)

        port = 9875;

    if (!host[0]) {

        /* Listen for announcements on sap.mcast.net if no host was specified */

        av_strlcpy(host, "224.2.127.254", sizeof(host));

    }

    ff_url_join(url, sizeof(url), "udp", NULL, host, port, "?localport=%d",

                port);

    ret = ffurl_open(&sap->ann_fd, url, AVIO_FLAG_READ,

                     &s->interrupt_callback, NULL);

    if (ret)

        goto fail;

    while (1) {

        int addr_type, auth_len;

        int pos;

        ret = ffurl_read(sap->ann_fd, recvbuf, sizeof(recvbuf) - 1);

        if (ret == AVERROR(EAGAIN))

            continue;

        if (ret < 0)

            goto fail;

        recvbuf[ret] = '\0'; /* Null terminate for easier parsing */

        if (ret < 8) {

            av_log(s, AV_LOG_WARNING, "Received too short packet\n");

            continue;

        }

        if ((recvbuf[0] & 0xe0) != 0x20) {

            av_log(s, AV_LOG_WARNING, "Unsupported SAP version packet "

                                      "received\n");

            continue;

        }

        if (recvbuf[0] & 0x04) {

            av_log(s, AV_LOG_WARNING, "Received stream deletion "

                                      "announcement\n");

            continue;

        }

        addr_type = recvbuf[0] & 0x10;

        auth_len  = recvbuf[1];

        sap->hash = AV_RB16(&recvbuf[2]);

        pos = 4;

        if (addr_type)

            pos += 16; /* IPv6 */

        else

            pos += 4; /* IPv4 */

        pos += auth_len * 4;

        if (pos + 4 >= ret) {

            av_log(s, AV_LOG_WARNING, "Received too short packet\n");

            continue;

        }

#define MIME "application/sdp"

        if (strcmp(&recvbuf[pos], MIME) == 0) {

            pos += strlen(MIME) + 1;

        } else if (strncmp(&recvbuf[pos], "v=0\r\n", 5) == 0) {

            // Direct SDP without a mime type

        } else {

            av_log(s, AV_LOG_WARNING, "Unsupported mime type %s\n",

                                      &recvbuf[pos]);

            continue;

        }

        sap->sdp = av_strdup(&recvbuf[pos]);

        break;

    }

    av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sap->sdp);

    ffio_init_context(&sap->sdp_pb, sap->sdp, strlen(sap->sdp), 0, NULL, NULL,

                  NULL, NULL);

    infmt = av_find_input_format("sdp");

    if (!infmt)

        goto fail;

    sap->sdp_ctx = avformat_alloc_context();

    if (!sap->sdp_ctx) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    sap->sdp_ctx->max_delay = s->max_delay;

    sap->sdp_ctx->pb        = &sap->sdp_pb;

    sap->sdp_ctx->interrupt_callback = s->interrupt_callback;

    av_assert0(!sap->sdp_ctx->codec_whitelist && !sap->sdp_ctx->format_whitelist);

    sap->sdp_ctx-> codec_whitelist = av_strdup(s->codec_whitelist);

    sap->sdp_ctx->format_whitelist = av_strdup(s->format_whitelist);

    ret = avformat_open_input(&sap->sdp_ctx, "temp.sdp", infmt, NULL);

    if (ret < 0)

        goto fail;

    if (sap->sdp_ctx->ctx_flags & AVFMTCTX_NOHEADER)

        s->ctx_flags |= AVFMTCTX_NOHEADER;

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

        AVStream *st = avformat_new_stream(s, NULL);

        if (!st) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        st->id = i;

        avcodec_copy_context(st->codec, sap->sdp_ctx->streams[i]->codec);

        st->time_base = sap->sdp_ctx->streams[i]->time_base;

    }

    return 0;

fail:

    sap_read_close(s);

    return ret;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    SysBusDeviceClass *sbc = SYS_BUS_DEVICE_CLASS(klass);

    ARMGICClass *agc = ARM_GIC_CLASS(klass);

    agc->parent_init = sbc->init;

    sbc->init = arm_gic_init;

    dc->no_user = 1;

}


static inline int l2_unscale_group(int steps, int mant, int scale_factor)

{

    int shift, mod, val;

    shift = scale_factor_modshift[scale_factor];

    mod = shift & 3;

    shift >>= 2;

    /* XXX: store the result directly */

    val = (2 * (mant - (steps >> 1))) * scale_factor_mult2[steps >> 2][mod];

    return (val + (1 << (shift - 1))) >> shift;

}


static void init_proc_970 (CPUPPCState *env)

{

    gen_spr_ne_601(env);

    gen_spr_7xx(env);

    /* Time base */

    gen_tbl(env);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_clear,

                 0x60000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_750_HID2, "HID2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_970_HID5, "HID5",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 POWERPC970_HID5_INIT);

    /* Memory management */

    /* XXX: not correct */

    gen_low_BATs(env);

    /* XXX : not implemented */

    spr_register(env, SPR_MMUCFG, "MMUCFG",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000); /* TOFIX */

    /* XXX : not implemented */

    spr_register(env, SPR_MMUCSR0, "MMUCSR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000); /* TOFIX */

    spr_register(env, SPR_HIOR, "SPR_HIOR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0xFFF00000); /* XXX: This is a hack */

#if !defined(CONFIG_USER_ONLY)

    env->excp_prefix = 0xFFF00000;

#endif

#if !defined(CONFIG_USER_ONLY)

    env->slb_nr = 32;

#endif

    init_excp_970(env);

    env->dcache_line_size = 128;

    env->icache_line_size = 128;

    /* Allocate hardware IRQ controller */

    ppc970_irq_init(env);

}


static int mov_write_header(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    MOVMuxContext *mov = s->priv_data;

    AVDictionaryEntry *t;

    int i, hint_track = 0;

    /* Default mode == MP4 */

    mov->mode = MODE_MP4;

    if (s->oformat != NULL) {

        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;

        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;

        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;

        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;

        else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;

        else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;

    }

    /* Set the FRAGMENT flag if any of the fragmentation methods are

     * enabled. */

    if (mov->max_fragment_duration || mov->max_fragment_size ||

        mov->mode == MODE_ISM ||

        mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |

                      FF_MOV_FLAG_FRAG_KEYFRAME |

                      FF_MOV_FLAG_FRAG_CUSTOM))

        mov->flags |= FF_MOV_FLAG_FRAGMENT;

    /* faststart: moov at the beginning of the file, if supported */

    if (mov->flags & FF_MOV_FLAG_FASTSTART) {

        if ((mov->flags & FF_MOV_FLAG_FRAGMENT) ||

            (s->flags & AVFMT_FLAG_CUSTOM_IO)) {

            av_log(s, AV_LOG_WARNING, "The faststart flag is incompatible "

                   "with fragmentation and custom IO, disabling faststart\n");

            mov->flags &= ~FF_MOV_FLAG_FASTSTART;

        }

    }

    /* Non-seekable output is ok if using fragmentation. If ism_lookahead

     * is enabled, we don't support non-seekable output at all. */

    if (!s->pb->seekable &&

        (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {

        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");

        return -1;

    }

    mov_write_ftyp_tag(pb,s);

    if (mov->mode == MODE_PSP) {

        if (s->nb_streams != 2) {

            av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");

            return -1;

        }

        mov_write_uuidprof_tag(pb, s);

    }

    mov->nb_streams = s->nb_streams;

    if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)

        mov->chapter_track = mov->nb_streams++;

    if (mov->flags & FF_MOV_FLAG_RTP_HINT) {

        /* Add hint tracks for each audio and video stream */

        hint_track = mov->nb_streams;

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

            AVStream *st = s->streams[i];

            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||

                st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

                mov->nb_streams++;

            }

        }

    }

    // Reserve an extra stream for chapters for the case where chapters

    // are written in the trailer

    mov->tracks = av_mallocz((mov->nb_streams + 1) * sizeof(*mov->tracks));

    if (!mov->tracks)

        return AVERROR(ENOMEM);

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

        AVStream *st= s->streams[i];

        MOVTrack *track= &mov->tracks[i];

        AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);

        track->enc = st->codec;

        track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);

        if (track->language < 0)

            track->language = 0;

        track->mode = mov->mode;

        track->tag  = mov_find_codec_tag(s, track);

        if (!track->tag) {

            av_log(s, AV_LOG_ERROR, "track %d: could not find tag, "

                   "codec not currently supported in container\n", i);

            goto error;

        }

        /* If hinting of this track is enabled by a later hint track,

         * this is updated. */

        track->hint_track = -1;

        track->start_dts  = AV_NOPTS_VALUE;

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

            if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||

                track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||

                track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {

                if (st->codec->width != 720 || (st->codec->height != 608 && st->codec->height != 512)) {

                    av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");

                    goto error;

                }

                track->height = track->tag >> 24 == 'n' ? 486 : 576;

            }

            track->timescale = st->codec->time_base.den;

            if (track->mode == MODE_MOV && track->timescale > 100000)

                av_log(s, AV_LOG_WARNING,

                       "WARNING codec timebase is very high. If duration is too long,\n"

                       "file may not be playable by quicktime. Specify a shorter timebase\n"

                       "or choose different container.\n");

        } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            track->timescale = st->codec->sample_rate;

            /* set sample_size for PCM and ADPCM */

            if (av_get_bits_per_sample(st->codec->codec_id) ||

                st->codec->codec_id == AV_CODEC_ID_ILBC) {

                if (!st->codec->block_align) {

                    av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set\n", i);

                    goto error;

                }

                track->sample_size = st->codec->block_align;

            }

            /* set audio_vbr for compressed audio */

            if (av_get_bits_per_sample(st->codec->codec_id) < 8) {

                track->audio_vbr = 1;

            }

            if (track->mode != MODE_MOV &&

                track->enc->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {

                av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not supported\n",

                       i, track->enc->sample_rate);

                goto error;

            }

        } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {

            track->timescale = st->codec->time_base.den;

        } else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {

            track->timescale = st->codec->time_base.den;

        }

        if (!track->height)

            track->height = st->codec->height;

        /* The ism specific timescale isn't mandatory, but is assumed by

         * some tools, such as mp4split. */

        if (mov->mode == MODE_ISM)

            track->timescale = 10000000;

        avpriv_set_pts_info(st, 64, 1, track->timescale);

        /* copy extradata if it exists */

        if (st->codec->extradata_size) {

            track->vos_len  = st->codec->extradata_size;

            track->vos_data = av_malloc(track->vos_len);

            memcpy(track->vos_data, st->codec->extradata, track->vos_len);

        }

    }

    enable_tracks(s);

    if (mov->mode == MODE_ISM) {

        /* If no fragmentation options have been set, set a default. */

        if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |

                            FF_MOV_FLAG_FRAG_CUSTOM)) &&

            !mov->max_fragment_duration && !mov->max_fragment_size)

            mov->max_fragment_duration = 5000000;

        mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF;

    }

    if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {

        if (mov->flags & FF_MOV_FLAG_FASTSTART)

            mov->reserved_moov_pos = avio_tell(pb);

        mov_write_mdat_tag(pb, mov);

    }

    if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))

        mov->time = ff_iso8601_to_unix_time(t->value);

    if (mov->time)

        mov->time += 0x7C25B080; // 1970 based -> 1904 based

    if (mov->chapter_track)

        if (mov_create_chapter_track(s, mov->chapter_track) < 0)

            goto error;

    if (mov->flags & FF_MOV_FLAG_RTP_HINT) {

        /* Initialize the hint tracks for each audio and video stream */

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

            AVStream *st = s->streams[i];

            if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||

                st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

                ff_mov_init_hinting(s, hint_track, i);

                hint_track++;

            }

        }

    }

    avio_flush(pb);

    if (mov->flags & FF_MOV_FLAG_ISML)

        mov_write_isml_manifest(pb, mov);

    if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {

        mov_write_moov_tag(pb, mov, s);

        mov->fragments++;

    }

    return 0;

 error:

    mov_free(s);

    return -1;

}


static void arith2_normalise(ArithCoder *c)

{

    while ((c->high >> 15) - (c->low >> 15) < 2) {

        if ((c->low ^ c->high) & 0x10000) {

            c->high  ^= 0x8000;

            c->value ^= 0x8000;

            c->low   ^= 0x8000;

        }

        c->high  = c->high  << 8 & 0xFFFFFF | 0xFF;

        c->value = c->value << 8 & 0xFFFFFF | bytestream2_get_byte(c->gbc.gB);

        c->low   = c->low   << 8 & 0xFFFFFF;

    }

}


static int usb_qdev_init(DeviceState *qdev, DeviceInfo *base)

{

    USBDevice *dev = DO_UPCAST(USBDevice, qdev, qdev);

    USBDeviceInfo *info = DO_UPCAST(USBDeviceInfo, qdev, base);

    int rc;

    pstrcpy(dev->product_desc, sizeof(dev->product_desc), info->product_desc);

    dev->info = info;

    dev->auto_attach = 1;

    QLIST_INIT(&dev->strings);

    rc = usb_claim_port(dev);

    if (rc != 0) {

        goto err;

    }

    rc = dev->info->init(dev);

    if (rc != 0) {

        goto err;

    }

    if (dev->auto_attach) {

        rc = usb_device_attach(dev);

        if (rc != 0) {

            goto err;

        }

    }

    return 0;

err:

    usb_qdev_exit(qdev);

    return rc;

}


void ff_eval_coefs(int *coefs, const int *refl)

{

    int buffer[LPC_ORDER];

    int *b1 = buffer;

    int *b2 = coefs;

    int i, j;

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

        b1[i] = refl[i] * 16;

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

            b1[j] = ((refl[i] * b2[i-j-1]) >> 12) + b2[j];

        FFSWAP(int *, b1, b2);

    }

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

        coefs[i] >>= 4;

}


static int decode_hq_slice(DiracContext *s, DiracSlice *slice, uint8_t *tmp_buf)

{

    int i, level, orientation, quant_idx;

    int qfactor[MAX_DWT_LEVELS][4], qoffset[MAX_DWT_LEVELS][4];

    GetBitContext *gb = &slice->gb;

    SliceCoeffs coeffs_num[MAX_DWT_LEVELS];

    skip_bits_long(gb, 8*s->highquality.prefix_bytes);

    quant_idx = get_bits(gb, 8);

    if (quant_idx > DIRAC_MAX_QUANT_INDEX) {

        av_log(s->avctx, AV_LOG_ERROR, "Invalid quantization index - %i\n", quant_idx);

        return AVERROR_INVALIDDATA;

    }

    /* Slice quantization (slice_quantizers() in the specs) */

    for (level = 0; level < s->wavelet_depth; level++) {

        for (orientation = !!level; orientation < 4; orientation++) {

            const int quant = FFMAX(quant_idx - s->lowdelay.quant[level][orientation], 0);

            qfactor[level][orientation] = ff_dirac_qscale_tab[quant];

            qoffset[level][orientation] = ff_dirac_qoffset_intra_tab[quant] + 2;

        }

    }

    /* Luma + 2 Chroma planes */

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

        int coef_num, coef_par, off = 0;

        int64_t length = s->highquality.size_scaler*get_bits(gb, 8);

        int64_t bits_end = get_bits_count(gb) + 8*length;

        const uint8_t *addr = align_get_bits(gb);

        if (length*8 > get_bits_left(gb)) {

            av_log(s->avctx, AV_LOG_ERROR, "end too far away\n");

            return AVERROR_INVALIDDATA;

        }

        coef_num = subband_coeffs(s, slice->slice_x, slice->slice_y, i, coeffs_num);

        if (s->pshift)

            coef_par = ff_dirac_golomb_read_32bit(s->reader_ctx, addr,

                                                  length, tmp_buf, coef_num);

        else

            coef_par = ff_dirac_golomb_read_16bit(s->reader_ctx, addr,

                                                  length, tmp_buf, coef_num);

        if (coef_num > coef_par) {

            const int start_b = coef_par * (1 << (s->pshift + 1));

            const int end_b   = coef_num * (1 << (s->pshift + 1));

            memset(&tmp_buf[start_b], 0, end_b - start_b);

        }

        for (level = 0; level < s->wavelet_depth; level++) {

            const SliceCoeffs *c = &coeffs_num[level];

            for (orientation = !!level; orientation < 4; orientation++) {

                const SubBand *b1 = &s->plane[i].band[level][orientation];

                uint8_t *buf = b1->ibuf + c->top * b1->stride + (c->left << (s->pshift + 1));

                /* Change to c->tot_h <= 4 for AVX2 dequantization */

                const int qfunc = s->pshift + 2*(c->tot_h <= 2);

                s->diracdsp.dequant_subband[qfunc](&tmp_buf[off], buf, b1->stride,

                                                   qfactor[level][orientation],

                                                   qoffset[level][orientation],

                                                   c->tot_v, c->tot_h);

                off += c->tot << (s->pshift + 1);

            }

        }

        skip_bits_long(gb, bits_end - get_bits_count(gb));

    }

    return 0;

}


static int ff_h261_resync(H261Context *h){

    MpegEncContext * const s = &h->s;

    int left, ret;

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

        ret= h261_decode_gob_header(h);

        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_in_bits - get_bits_count(&s->gb);

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

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

            GetBitContext bak= s->gb;

            ret= h261_decode_gob_header(h);

            if(ret>=0)

                return 0;

            s->gb= bak;

        }

        skip_bits(&s->gb, 8);

    }

    return -1;

}


static int epic_decode_tile(ePICContext *dc, uint8_t *out, int tile_height,

                            int tile_width, int stride)

{

    int x, y;

    uint32_t pix;

    uint32_t *curr_row = NULL, *above_row = NULL, *above2_row;

    for (y = 0; y < tile_height; y++, out += stride) {

        above2_row = above_row;

        above_row  = curr_row;

        curr_row   = (uint32_t *) out;

        for (x = 0, dc->next_run_pos = 0; x < tile_width;) {

            if (dc->els_ctx.err)

                return AVERROR_INVALIDDATA; // bail out in the case of ELS overflow

            pix = curr_row[x - 1]; // get W pixel

            if (y >= 1 && x >= 2 &&

                pix != curr_row[x - 2]  && pix != above_row[x - 1] &&

                pix != above_row[x - 2] && pix != above_row[x] &&

                !epic_cache_entries_for_pixel(&dc->hash, pix)) {

                curr_row[x] = epic_decode_pixel_pred(dc, x, y, curr_row, above_row);

                x++;

            } else {

                int got_pixel, run;

                dc->stack_pos = 0; // empty stack

                if (y < 2 || x < 2 || x == tile_width - 1) {

                    run       = 1;

                    got_pixel = epic_handle_edges(dc, x, y, curr_row, above_row, &pix);

                } else

                    got_pixel = epic_decode_run_length(dc, x, y, tile_width,

                                                       curr_row, above_row,

                                                       above2_row, &pix, &run);

                if (!got_pixel && !epic_predict_from_NW_NE(dc, x, y, run,

                                                           tile_width, curr_row,

                                                           above_row, &pix)) {

                    uint32_t ref_pix = curr_row[x - 1];

                    if (!x || !epic_decode_from_cache(dc, ref_pix, &pix)) {

                        pix = epic_decode_pixel_pred(dc, x, y, curr_row, above_row);

                        if (x) {

                            int ret = epic_add_pixel_to_cache(&dc->hash,

                                                              ref_pix,

                                                              pix);

                            if (ret)

                                return ret;

                        }

                    }

                }

                for (; run > 0; x++, run--)

                    curr_row[x] = pix;

            }

        }

    }

    return 0;

}


int ff_h264_context_init(H264Context *h)

{

    ERContext *er = &h->er;

    int mb_array_size = h->mb_height * h->mb_stride;

    int y_size  = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);

    int c_size  = h->mb_stride * (h->mb_height + 1);

    int yc_size = y_size + 2   * c_size;

    int x, y, i;

    FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],

                      h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)

    FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],

                      h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)

    h->ref_cache[0][scan8[5]  + 1] =

    h->ref_cache[0][scan8[7]  + 1] =

    h->ref_cache[0][scan8[13] + 1] =

    h->ref_cache[1][scan8[5]  + 1] =

    h->ref_cache[1][scan8[7]  + 1] =

    h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;

    if (CONFIG_ERROR_RESILIENCE) {

        /* init ER */

        er->avctx          = h->avctx;

        er->mecc           = &h->mecc;

        er->decode_mb      = h264_er_decode_mb;

        er->opaque         = h;

        er->quarter_sample = 1;

        er->mb_num      = h->mb_num;

        er->mb_width    = h->mb_width;

        er->mb_height   = h->mb_height;

        er->mb_stride   = h->mb_stride;

        er->b8_stride   = h->mb_width * 2 + 1;

        // error resilience code looks cleaner with this

        FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,

                          (h->mb_num + 1) * sizeof(int), fail);

        for (y = 0; y < h->mb_height; y++)

            for (x = 0; x < h->mb_width; x++)

                er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;

        er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *

                                                      h->mb_stride + h->mb_width;

        FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,

                          mb_array_size * sizeof(uint8_t), fail);

        FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);

        memset(er->mbintra_table, 1, mb_array_size);

        FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);

        FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,

                         h->mb_height * h->mb_stride, fail);

        FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base,

                          yc_size * sizeof(int16_t), fail);

        er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;

        er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;

        er->dc_val[2] = er->dc_val[1] + c_size;

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

            h->dc_val_base[i] = 1024;

    }

    return 0;

fail:

    return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us

}


static int thp_read_packet(AVFormatContext *s,

                            AVPacket *pkt)

{

    ThpDemuxContext *thp = s->priv_data;

    AVIOContext *pb = s->pb;

    unsigned int size;

    int ret;

    if (thp->audiosize == 0) {

        /* Terminate when last frame is reached.  */

        if (thp->frame >= thp->framecnt)

            return AVERROR_EOF;

        avio_seek(pb, thp->next_frame, SEEK_SET);

        /* Locate the next frame and read out its size.  */

        thp->next_frame += thp->next_framesz;

        thp->next_framesz = avio_rb32(pb);

                        avio_rb32(pb); /* Previous total size.  */

        size          = avio_rb32(pb); /* Total size of this frame.  */

        /* Store the audiosize so the next time this function is called,

           the audio can be read.  */

        if (thp->has_audio)

            thp->audiosize = avio_rb32(pb); /* Audio size.  */

        else

            thp->frame++;

        ret = av_get_packet(pb, pkt, size);

        if (ret != size) {

            av_free_packet(pkt);

            return AVERROR(EIO);

        }

        pkt->stream_index = thp->video_stream_index;

    } else {

        ret = av_get_packet(pb, pkt, thp->audiosize);

        if (ret != thp->audiosize) {

            av_free_packet(pkt);

            return AVERROR(EIO);

        }

        pkt->stream_index = thp->audio_stream_index;

        if (thp->audiosize >= 8)

            pkt->duration = AV_RB32(&pkt->data[4]);

        thp->audiosize = 0;

        thp->frame++;

    }

    return 0;

}


static int execute_code(AVCodecContext * avctx, int c)

{

    AnsiContext *s = avctx->priv_data;

    int ret, i, width, height;

    switch(c) {

    case 'A': //Cursor Up

        s->y = FFMAX(s->y - (s->nb_args > 0 ? s->args[0]*s->font_height : s->font_height), 0);

        break;

    case 'B': //Cursor Down

        s->y = FFMIN(s->y + (s->nb_args > 0 ? s->args[0]*s->font_height : s->font_height), avctx->height - s->font_height);

        break;

    case 'C': //Cursor Right

        s->x = FFMIN(s->x + (s->nb_args > 0 ? s->args[0]*FONT_WIDTH : FONT_WIDTH), avctx->width  - FONT_WIDTH);

        break;

    case 'D': //Cursor Left

        s->x = FFMAX(s->x - (s->nb_args > 0 ? s->args[0]*FONT_WIDTH : FONT_WIDTH), 0);

        break;

    case 'H': //Cursor Position

    case 'f': //Horizontal and Vertical Position

        s->y = s->nb_args > 0 ? av_clip((s->args[0] - 1)*s->font_height, 0, avctx->height - s->font_height) : 0;

        s->x = s->nb_args > 1 ? av_clip((s->args[1] - 1)*FONT_WIDTH,     0, avctx->width  - FONT_WIDTH) : 0;

        break;

    case 'h': //set creen mode

    case 'l': //reset screen mode

        if (s->nb_args < 2)

            s->args[0] = DEFAULT_SCREEN_MODE;

        width = avctx->width;

        height = avctx->height;

        switch(s->args[0]) {

        case 0: case 1: case 4: case 5: case 13: case 19: //320x200 (25 rows)

            s->font = avpriv_cga_font;

            s->font_height = 8;

            width  = 40<<3;

            height = 25<<3;

            break;

        case 2: case 3: //640x400 (25 rows)

            s->font = avpriv_vga16_font;

            s->font_height = 16;

            width  = 80<<3;

            height = 25<<4;

            break;

        case 6: case 14: //640x200 (25 rows)

            s->font = avpriv_cga_font;

            s->font_height = 8;

            width  = 80<<3;

            height = 25<<3;

            break;

        case 7: //set line wrapping

            break;

        case 15: case 16: //640x350 (43 rows)

            s->font = avpriv_cga_font;

            s->font_height = 8;

            width  = 80<<3;

            height = 43<<3;

            break;

        case 17: case 18: //640x480 (60 rows)

            s->font = avpriv_cga_font;

            s->font_height = 8;

            width  = 80<<3;

            height = 60<<4;

            break;

        default:

            av_log_ask_for_sample(avctx, "unsupported screen mode\n");

        }

        if (width != avctx->width || height != avctx->height) {

            if (s->frame.data[0])

                avctx->release_buffer(avctx, &s->frame);

            avcodec_set_dimensions(avctx, width, height);

            ret = avctx->get_buffer(avctx, &s->frame);

            if (ret < 0) {

                av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

                return ret;

            }

            s->frame.pict_type           = AV_PICTURE_TYPE_I;

            s->frame.palette_has_changed = 1;

            set_palette((uint32_t *)s->frame.data[1]);

            erase_screen(avctx);

        } else if (c == 'l') {

            erase_screen(avctx);

        }

        break;

    case 'J': //Erase in Page

        switch (s->args[0]) {

        case 0:

            erase_line(avctx, s->x, avctx->width - s->x);

            if (s->y < avctx->height - s->font_height)

                memset(s->frame.data[0] + (s->y + s->font_height)*s->frame.linesize[0],

                    DEFAULT_BG_COLOR, (avctx->height - s->y - s->font_height)*s->frame.linesize[0]);

            break;

        case 1:

            erase_line(avctx, 0, s->x);

            if (s->y > 0)

                memset(s->frame.data[0], DEFAULT_BG_COLOR, s->y * s->frame.linesize[0]);

            break;

        case 2:

            erase_screen(avctx);

        }

        break;

    case 'K': //Erase in Line

        switch(s->args[0]) {

        case 0:

            erase_line(avctx, s->x, avctx->width - s->x);

            break;

        case 1:

            erase_line(avctx, 0, s->x);

            break;

        case 2:

            erase_line(avctx, 0, avctx->width);

        }

        break;

    case 'm': //Select Graphics Rendition

        if (s->nb_args == 0) {

            s->nb_args = 1;

            s->args[0] = 0;

        }

        for (i = 0; i < FFMIN(s->nb_args, MAX_NB_ARGS); i++) {

            int m = s->args[i];

            if (m == 0) {

                s->attributes = 0;

                s->fg = DEFAULT_FG_COLOR;

                s->bg = DEFAULT_BG_COLOR;

            } else if (m == 1 || m == 2 || m == 4 || m == 5 || m == 7 || m == 8) {

                s->attributes |= 1 << (m - 1);

            } else if (m >= 30 && m <= 37) {

                s->fg = ansi_to_cga[m - 30];

            } else if (m == 38 && i + 2 < s->nb_args && s->args[i + 1] == 5 && s->args[i + 2] < 256) {

                int index = s->args[i + 2];

                s->fg = index < 16 ? ansi_to_cga[index] : index;

                i += 2;

            } else if (m == 39) {

                s->fg = ansi_to_cga[DEFAULT_FG_COLOR];

            } else if (m >= 40 && m <= 47) {

                s->bg = ansi_to_cga[m - 40];

            } else if (m == 48 && i + 2 < s->nb_args && s->args[i + 1] == 5 && s->args[i + 2] < 256) {

                int index = s->args[i + 2];

                s->bg = index < 16 ? ansi_to_cga[index] : index;

                i += 2;

            } else if (m == 49) {

                s->fg = ansi_to_cga[DEFAULT_BG_COLOR];

            } else {

                av_log_ask_for_sample(avctx, "unsupported rendition parameter\n");

            }

        }

        break;

    case 'n': //Device Status Report

    case 'R': //report current line and column

        /* ignore */

        break;

    case 's': //Save Cursor Position

        s->sx = s->x;

        s->sy = s->y;

        break;

    case 'u': //Restore Cursor Position

        s->x = av_clip(s->sx, 0, avctx->width  - FONT_WIDTH);

        s->y = av_clip(s->sy, 0, avctx->height - s->font_height);

        break;

    default:

        av_log_ask_for_sample(avctx, "unsupported escape code\n");

        break;

    }

    return 0;

}