int main(int argc, char **argv, char **envp)

{

    const char *gdbstub_dev = NULL;

    int i;

    int snapshot, linux_boot;

    const char *icount_option = NULL;

    const char *initrd_filename;

    const char *kernel_filename, *kernel_cmdline;

    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */

    DisplayState *ds;

    DisplayChangeListener *dcl;

    int cyls, heads, secs, translation;

    QemuOpts *hda_opts = NULL, *opts;

    QemuOptsList *olist;

    int optind;

    const char *optarg;

    const char *loadvm = NULL;

    QEMUMachine *machine;

    const char *cpu_model;

    const char *pid_file = NULL;

    const char *incoming = NULL;

#ifdef CONFIG_VNC

    int show_vnc_port = 0;

#endif

    int defconfig = 1;

    const char *log_mask = NULL;

    const char *log_file = NULL;

    GMemVTable mem_trace = {

        .malloc = malloc_and_trace,

        .realloc = realloc_and_trace,

        .free = free_and_trace,

    };

    const char *trace_events = NULL;

    const char *trace_file = NULL;

    atexit(qemu_run_exit_notifiers);

    error_set_progname(argv[0]);

    g_mem_set_vtable(&mem_trace);

    if (!g_thread_supported()) {

#if !GLIB_CHECK_VERSION(2, 31, 0)

        g_thread_init(NULL);

#else

        fprintf(stderr, "glib threading failed to initialize.\n");

        exit(1);

#endif

    }

    runstate_init();

    init_clocks();

    rtc_clock = host_clock;

    qemu_cache_utils_init(envp);

    QLIST_INIT (&vm_change_state_head);

    os_setup_early_signal_handling();

    module_call_init(MODULE_INIT_MACHINE);

    machine = find_default_machine();

    cpu_model = NULL;

    initrd_filename = NULL;

    ram_size = 0;

    snapshot = 0;

    kernel_filename = NULL;

    kernel_cmdline = "";

    cyls = heads = secs = 0;

    translation = BIOS_ATA_TRANSLATION_AUTO;

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

        node_mem[i] = 0;

        node_cpumask[i] = 0;

    }

    nb_numa_nodes = 0;

    nb_nics = 0;

    autostart= 1;

    /* first pass of option parsing */

    optind = 1;

    while (optind < argc) {

        if (argv[optind][0] != '-') {

            /* disk image */

            optind++;

            continue;

        } else {

            const QEMUOption *popt;

            popt = lookup_opt(argc, argv, &optarg, &optind);

            switch (popt->index) {

            case QEMU_OPTION_nodefconfig:

                defconfig=0;

                break;

            }

        }

    }

    if (defconfig) {

        int ret;

        ret = qemu_read_config_file(CONFIG_QEMU_CONFDIR "/qemu.conf");

        if (ret < 0 && ret != -ENOENT) {

            exit(1);

        }

        ret = qemu_read_config_file(arch_config_name);

        if (ret < 0 && ret != -ENOENT) {

            exit(1);

        }

    }

    cpudef_init();

    /* second pass of option parsing */

    optind = 1;

    for(;;) {

        if (optind >= argc)

            break;

        if (argv[optind][0] != '-') {

	    hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);

        } else {

            const QEMUOption *popt;

            popt = lookup_opt(argc, argv, &optarg, &optind);

            if (!(popt->arch_mask & arch_type)) {

                printf("Option %s not supported for this target\n", popt->name);

                exit(1);

            }

            switch(popt->index) {

            case QEMU_OPTION_M:

                machine = machine_parse(optarg);

                break;

            case QEMU_OPTION_cpu:

                /* hw initialization will check this */

                if (*optarg == '?') {

                    list_cpus(stdout, &fprintf, optarg);

                    exit(0);

                } else {

                    cpu_model = optarg;

                }

                break;

            case QEMU_OPTION_initrd:

                initrd_filename = optarg;

                break;

            case QEMU_OPTION_hda:

                {

                    char buf[256];

                    if (cyls == 0)

                        snprintf(buf, sizeof(buf), "%s", HD_OPTS);

                    else

                        snprintf(buf, sizeof(buf),

                                 "%s,cyls=%d,heads=%d,secs=%d%s",

                                 HD_OPTS , cyls, heads, secs,

                                 translation == BIOS_ATA_TRANSLATION_LBA ?

                                 ",trans=lba" :

                                 translation == BIOS_ATA_TRANSLATION_NONE ?

                                 ",trans=none" : "");

                    drive_add(IF_DEFAULT, 0, optarg, buf);

                    break;

                }

            case QEMU_OPTION_hdb:

            case QEMU_OPTION_hdc:

            case QEMU_OPTION_hdd:

                drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,

                          HD_OPTS);

                break;

            case QEMU_OPTION_drive:

                if (drive_def(optarg) == NULL) {

                    exit(1);

                }

	        break;

            case QEMU_OPTION_set:

                if (qemu_set_option(optarg) != 0)

                    exit(1);

	        break;

            case QEMU_OPTION_global:

                if (qemu_global_option(optarg) != 0)

                    exit(1);

	        break;

            case QEMU_OPTION_mtdblock:

                drive_add(IF_MTD, -1, optarg, MTD_OPTS);

                break;

            case QEMU_OPTION_sd:

                drive_add(IF_SD, 0, optarg, SD_OPTS);

                break;

            case QEMU_OPTION_pflash:

                drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);

                break;

            case QEMU_OPTION_snapshot:

                snapshot = 1;

                break;

            case QEMU_OPTION_hdachs:

                {

                    const char *p;

                    p = optarg;

                    cyls = strtol(p, (char **)&p, 0);

                    if (cyls < 1 || cyls > 16383)

                        goto chs_fail;

                    if (*p != ',')

                        goto chs_fail;

                    p++;

                    heads = strtol(p, (char **)&p, 0);

                    if (heads < 1 || heads > 16)

                        goto chs_fail;

                    if (*p != ',')

                        goto chs_fail;

                    p++;

                    secs = strtol(p, (char **)&p, 0);

                    if (secs < 1 || secs > 63)

                        goto chs_fail;

                    if (*p == ',') {

                        p++;

                        if (!strcmp(p, "none"))

                            translation = BIOS_ATA_TRANSLATION_NONE;

                        else if (!strcmp(p, "lba"))

                            translation = BIOS_ATA_TRANSLATION_LBA;

                        else if (!strcmp(p, "auto"))

                            translation = BIOS_ATA_TRANSLATION_AUTO;

                        else

                            goto chs_fail;

                    } else if (*p != '\0') {

                    chs_fail:

                        fprintf(stderr, "qemu: invalid physical CHS format\n");

                        exit(1);

                    }

		    if (hda_opts != NULL) {

                        char num[16];

                        snprintf(num, sizeof(num), "%d", cyls);

                        qemu_opt_set(hda_opts, "cyls", num);

                        snprintf(num, sizeof(num), "%d", heads);

                        qemu_opt_set(hda_opts, "heads", num);

                        snprintf(num, sizeof(num), "%d", secs);

                        qemu_opt_set(hda_opts, "secs", num);

                        if (translation == BIOS_ATA_TRANSLATION_LBA)

                            qemu_opt_set(hda_opts, "trans", "lba");

                        if (translation == BIOS_ATA_TRANSLATION_NONE)

                            qemu_opt_set(hda_opts, "trans", "none");

                    }

                }

                break;

            case QEMU_OPTION_numa:

                if (nb_numa_nodes >= MAX_NODES) {

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

                    exit(1);

                }

                numa_add(optarg);

                break;

            case QEMU_OPTION_display:

                display_type = select_display(optarg);

                break;

            case QEMU_OPTION_nographic:

                display_type = DT_NOGRAPHIC;

                break;

            case QEMU_OPTION_curses:

#ifdef CONFIG_CURSES

                display_type = DT_CURSES;

#else

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

                exit(1);

#endif

                break;

            case QEMU_OPTION_portrait:

                graphic_rotate = 90;

                break;

            case QEMU_OPTION_rotate:

                graphic_rotate = strtol(optarg, (char **) &optarg, 10);

                if (graphic_rotate != 0 && graphic_rotate != 90 &&

                    graphic_rotate != 180 && graphic_rotate != 270) {

                    fprintf(stderr,

                        "qemu: only 90, 180, 270 deg rotation is available\n");

                    exit(1);

                }

                break;

            case QEMU_OPTION_kernel:

                kernel_filename = optarg;

                break;

            case QEMU_OPTION_append:

                kernel_cmdline = optarg;

                break;

            case QEMU_OPTION_cdrom:

                drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);

                break;

            case QEMU_OPTION_boot:

                {

                    static const char * const params[] = {

                        "order", "once", "menu",

                        "splash", "splash-time", NULL

                    };

                    char buf[sizeof(boot_devices)];

                    char *standard_boot_devices;

                    int legacy = 0;

                    if (!strchr(optarg, '=')) {

                        legacy = 1;

                        pstrcpy(buf, sizeof(buf), optarg);

                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {

                        fprintf(stderr,

                                "qemu: unknown boot parameter '%s' in '%s'\n",

                                buf, optarg);

                        exit(1);

                    }

                    if (legacy ||

                        get_param_value(buf, sizeof(buf), "order", optarg)) {

                        validate_bootdevices(buf);

                        pstrcpy(boot_devices, sizeof(boot_devices), buf);

                    }

                    if (!legacy) {

                        if (get_param_value(buf, sizeof(buf),

                                            "once", optarg)) {

                            validate_bootdevices(buf);

                            standard_boot_devices = g_strdup(boot_devices);

                            pstrcpy(boot_devices, sizeof(boot_devices), buf);

                            qemu_register_reset(restore_boot_devices,

                                                standard_boot_devices);

                        }

                        if (get_param_value(buf, sizeof(buf),

                                            "menu", optarg)) {

                            if (!strcmp(buf, "on")) {

                                boot_menu = 1;

                            } else if (!strcmp(buf, "off")) {

                                boot_menu = 0;

                            } else {

                                fprintf(stderr,

                                        "qemu: invalid option value '%s'\n",

                                        buf);

                                exit(1);

                            }

                        }

                        qemu_opts_parse(qemu_find_opts("boot-opts"),

                                        optarg, 0);

                    }

                }

                break;

            case QEMU_OPTION_fda:

            case QEMU_OPTION_fdb:

                drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,

                          optarg, FD_OPTS);

                break;

            case QEMU_OPTION_no_fd_bootchk:

                fd_bootchk = 0;

                break;

            case QEMU_OPTION_netdev:

                if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {

                    exit(1);

                }

                break;

            case QEMU_OPTION_net:

                if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {

                    exit(1);

                }

                break;

#ifdef CONFIG_SLIRP

            case QEMU_OPTION_tftp:

                legacy_tftp_prefix = optarg;

                break;

            case QEMU_OPTION_bootp:

                legacy_bootp_filename = optarg;

                break;

            case QEMU_OPTION_redir:

                if (net_slirp_redir(optarg) < 0)

                    exit(1);

                break;

#endif

            case QEMU_OPTION_bt:

                add_device_config(DEV_BT, optarg);

                break;

            case QEMU_OPTION_audio_help:

                if (!(audio_available())) {

                    printf("Option %s not supported for this target\n", popt->name);

                    exit(1);

                }

                AUD_help ();

                exit (0);

                break;

            case QEMU_OPTION_soundhw:

                if (!(audio_available())) {

                    printf("Option %s not supported for this target\n", popt->name);

                    exit(1);

                }

                select_soundhw (optarg);

                break;

            case QEMU_OPTION_h:

                help(0);

                break;

            case QEMU_OPTION_version:

                version();

                exit(0);

                break;

            case QEMU_OPTION_m: {

                int64_t value;

                char *end;

                value = strtosz(optarg, &end);

                if (value < 0 || *end) {

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

                    exit(1);

                }

                if (value != (uint64_t)(ram_addr_t)value) {

                    fprintf(stderr, "qemu: ram size too large\n");

                    exit(1);

                }

                ram_size = value;

                break;

            }

            case QEMU_OPTION_mempath:

                mem_path = optarg;

                break;

#ifdef MAP_POPULATE

            case QEMU_OPTION_mem_prealloc:

                mem_prealloc = 1;

                break;

#endif

            case QEMU_OPTION_d:

                log_mask = optarg;

                break;

            case QEMU_OPTION_D:

                log_file = optarg;

                break;

            case QEMU_OPTION_s:

                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;

                break;

            case QEMU_OPTION_gdb:

                gdbstub_dev = optarg;

                break;

            case QEMU_OPTION_L:

                data_dir = optarg;

                break;

            case QEMU_OPTION_bios:

                bios_name = optarg;

                break;

            case QEMU_OPTION_singlestep:

                singlestep = 1;

                break;

            case QEMU_OPTION_S:

                autostart = 0;

                break;

	    case QEMU_OPTION_k:

		keyboard_layout = optarg;

		break;

            case QEMU_OPTION_localtime:

                rtc_utc = 0;

                break;

            case QEMU_OPTION_vga:

                select_vgahw (optarg);

                break;

            case QEMU_OPTION_g:

                {

                    const char *p;

                    int w, h, depth;

                    p = optarg;

                    w = strtol(p, (char **)&p, 10);

                    if (w <= 0) {

                    graphic_error:

                        fprintf(stderr, "qemu: invalid resolution or depth\n");

                        exit(1);

                    }

                    if (*p != 'x')

                        goto graphic_error;

                    p++;

                    h = strtol(p, (char **)&p, 10);

                    if (h <= 0)

                        goto graphic_error;

                    if (*p == 'x') {

                        p++;

                        depth = strtol(p, (char **)&p, 10);

                        if (depth != 8 && depth != 15 && depth != 16 &&

                            depth != 24 && depth != 32)

                            goto graphic_error;

                    } else if (*p == '\0') {

                        depth = graphic_depth;

                    } else {

                        goto graphic_error;

                    }

                    graphic_width = w;

                    graphic_height = h;

                    graphic_depth = depth;

                }

                break;

            case QEMU_OPTION_echr:

                {

                    char *r;

                    term_escape_char = strtol(optarg, &r, 0);

                    if (r == optarg)

                        printf("Bad argument to echr\n");

                    break;

                }

            case QEMU_OPTION_monitor:

                monitor_parse(optarg, "readline");

                default_monitor = 0;

                break;

            case QEMU_OPTION_qmp:

                monitor_parse(optarg, "control");

                default_monitor = 0;

                break;

            case QEMU_OPTION_mon:

                opts = qemu_opts_parse(qemu_find_opts("mon"), optarg, 1);

                if (!opts) {

                    exit(1);

                }

                default_monitor = 0;

                break;

            case QEMU_OPTION_chardev:

                opts = qemu_opts_parse(qemu_find_opts("chardev"), optarg, 1);

                if (!opts) {

                    exit(1);

                }

                break;

            case QEMU_OPTION_fsdev:

                olist = qemu_find_opts("fsdev");

                if (!olist) {

                    fprintf(stderr, "fsdev is not supported by this qemu build.\n");

                    exit(1);

                }

                opts = qemu_opts_parse(olist, optarg, 1);

                if (!opts) {

                    fprintf(stderr, "parse error: %s\n", optarg);

                    exit(1);

                }

                break;

            case QEMU_OPTION_virtfs: {

                QemuOpts *fsdev;

                QemuOpts *device;

                const char *writeout;

                olist = qemu_find_opts("virtfs");

                if (!olist) {

                    fprintf(stderr, "virtfs is not supported by this qemu build.\n");

                    exit(1);

                }

                opts = qemu_opts_parse(olist, optarg, 1);

                if (!opts) {

                    fprintf(stderr, "parse error: %s\n", optarg);

                    exit(1);

                }

                if (qemu_opt_get(opts, "fsdriver") == NULL ||

                        qemu_opt_get(opts, "mount_tag") == NULL ||

                        qemu_opt_get(opts, "path") == NULL) {

                    fprintf(stderr, "Usage: -virtfs fsdriver,path=/share_path/,"

                            "[security_model={mapped|passthrough|none}],"

                            "mount_tag=tag.\n");

                    exit(1);

                }

                fsdev = qemu_opts_create(qemu_find_opts("fsdev"),

                                         qemu_opt_get(opts, "mount_tag"), 1);

                if (!fsdev) {

                    fprintf(stderr, "duplicate fsdev id: %s\n",

                            qemu_opt_get(opts, "mount_tag"));

                    exit(1);

                }

                writeout = qemu_opt_get(opts, "writeout");

                if (writeout) {

#ifdef CONFIG_SYNC_FILE_RANGE

                    qemu_opt_set(fsdev, "writeout", writeout);

#else

                    fprintf(stderr, "writeout=immediate not supported on "

                            "this platform\n");

                    exit(1);

#endif

                }

                qemu_opt_set(fsdev, "fsdriver", qemu_opt_get(opts, "fsdriver"));

                qemu_opt_set(fsdev, "path", qemu_opt_get(opts, "path"));

                qemu_opt_set(fsdev, "security_model",

                             qemu_opt_get(opts, "security_model"));

                qemu_opt_set_bool(fsdev, "readonly",

                                qemu_opt_get_bool(opts, "readonly", 0));

                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0);

                qemu_opt_set(device, "driver", "virtio-9p-pci");

                qemu_opt_set(device, "fsdev",

                             qemu_opt_get(opts, "mount_tag"));

                qemu_opt_set(device, "mount_tag",

                             qemu_opt_get(opts, "mount_tag"));

                break;

            }

            case QEMU_OPTION_virtfs_synth: {

                QemuOpts *fsdev;

                QemuOpts *device;

                fsdev = qemu_opts_create(qemu_find_opts("fsdev"), "v_synth", 1);

                if (!fsdev) {

                    fprintf(stderr, "duplicate option: %s\n", "virtfs_synth");

                    exit(1);

                }

                qemu_opt_set(fsdev, "fsdriver", "synth");

                qemu_opt_set(fsdev, "path", "/"); /* ignored */

                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0);

                qemu_opt_set(device, "driver", "virtio-9p-pci");

                qemu_opt_set(device, "fsdev", "v_synth");

                qemu_opt_set(device, "mount_tag", "v_synth");

                break;

            }

            case QEMU_OPTION_serial:

                add_device_config(DEV_SERIAL, optarg);

                default_serial = 0;

                if (strncmp(optarg, "mon:", 4) == 0) {

                    default_monitor = 0;

                }

                break;

            case QEMU_OPTION_watchdog:

                if (watchdog) {

                    fprintf(stderr,

                            "qemu: only one watchdog option may be given\n");

                    return 1;

                }

                watchdog = optarg;

                break;

            case QEMU_OPTION_watchdog_action:

                if (select_watchdog_action(optarg) == -1) {

                    fprintf(stderr, "Unknown -watchdog-action parameter\n");

                    exit(1);

                }

                break;

            case QEMU_OPTION_virtiocon:

                add_device_config(DEV_VIRTCON, optarg);

                default_virtcon = 0;

                if (strncmp(optarg, "mon:", 4) == 0) {

                    default_monitor = 0;

                }

                break;

            case QEMU_OPTION_parallel:

                add_device_config(DEV_PARALLEL, optarg);

                default_parallel = 0;

                if (strncmp(optarg, "mon:", 4) == 0) {

                    default_monitor = 0;

                }

                break;

            case QEMU_OPTION_debugcon:

                add_device_config(DEV_DEBUGCON, optarg);

                break;

	    case QEMU_OPTION_loadvm:

		loadvm = optarg;

		break;

            case QEMU_OPTION_full_screen:

                full_screen = 1;

                break;

#ifdef CONFIG_SDL

            case QEMU_OPTION_no_frame:

                no_frame = 1;

                break;

            case QEMU_OPTION_alt_grab:

                alt_grab = 1;

                break;

            case QEMU_OPTION_ctrl_grab:

                ctrl_grab = 1;

                break;

            case QEMU_OPTION_no_quit:

                no_quit = 1;

                break;

            case QEMU_OPTION_sdl:

                display_type = DT_SDL;

                break;

#else

            case QEMU_OPTION_no_frame:

            case QEMU_OPTION_alt_grab:

            case QEMU_OPTION_ctrl_grab:

            case QEMU_OPTION_no_quit:

            case QEMU_OPTION_sdl:

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

                exit(1);

#endif

            case QEMU_OPTION_pidfile:

                pid_file = optarg;

                break;

            case QEMU_OPTION_win2k_hack:

                win2k_install_hack = 1;

                break;

            case QEMU_OPTION_rtc_td_hack:

                rtc_td_hack = 1;

                break;

            case QEMU_OPTION_acpitable:

                do_acpitable_option(optarg);

                break;

            case QEMU_OPTION_smbios:

                do_smbios_option(optarg);

                break;

            case QEMU_OPTION_enable_kvm:

                olist = qemu_find_opts("machine");

                qemu_opts_reset(olist);

                qemu_opts_parse(olist, "accel=kvm", 0);

                break;

            case QEMU_OPTION_machine:

                olist = qemu_find_opts("machine");

                qemu_opts_reset(olist);

                opts = qemu_opts_parse(olist, optarg, 1);

                if (!opts) {

                    fprintf(stderr, "parse error: %s\n", optarg);

                    exit(1);

                }

                optarg = qemu_opt_get(opts, "type");

                if (optarg) {

                    machine = machine_parse(optarg);

                }

                break;

            case QEMU_OPTION_usb:

                usb_enabled = 1;

                break;

            case QEMU_OPTION_usbdevice:

                usb_enabled = 1;

                add_device_config(DEV_USB, optarg);

                break;

            case QEMU_OPTION_device:

                if (!qemu_opts_parse(qemu_find_opts("device"), optarg, 1)) {

                    exit(1);

                }

                break;

            case QEMU_OPTION_smp:

                smp_parse(optarg);

                if (smp_cpus < 1) {

                    fprintf(stderr, "Invalid number of CPUs\n");

                    exit(1);

                }

                if (max_cpus < smp_cpus) {

                    fprintf(stderr, "maxcpus must be equal to or greater than "

                            "smp\n");

                    exit(1);

                }

                if (max_cpus > 255) {

                    fprintf(stderr, "Unsupported number of maxcpus\n");

                    exit(1);

                }

                break;

	    case QEMU_OPTION_vnc:

#ifdef CONFIG_VNC

                display_remote++;

                vnc_display = optarg;

#else

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

                exit(1);

#endif

                break;

            case QEMU_OPTION_no_acpi:

                acpi_enabled = 0;

                break;

            case QEMU_OPTION_no_hpet:

                no_hpet = 1;

                break;

            case QEMU_OPTION_balloon:

                if (balloon_parse(optarg) < 0) {

                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);

                    exit(1);

                }

                break;

            case QEMU_OPTION_no_reboot:

                no_reboot = 1;

                break;

            case QEMU_OPTION_no_shutdown:

                no_shutdown = 1;

                break;

            case QEMU_OPTION_show_cursor:

                cursor_hide = 0;

                break;

            case QEMU_OPTION_uuid:

                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {

                    fprintf(stderr, "Fail to parse UUID string."

                            " Wrong format.\n");

                    exit(1);

                }

                break;

	    case QEMU_OPTION_option_rom:

		if (nb_option_roms >= MAX_OPTION_ROMS) {

		    fprintf(stderr, "Too many option ROMs\n");

		    exit(1);

		}

                opts = qemu_opts_parse(qemu_find_opts("option-rom"), optarg, 1);

                option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");

                option_rom[nb_option_roms].bootindex =

                    qemu_opt_get_number(opts, "bootindex", -1);

                if (!option_rom[nb_option_roms].name) {

                    fprintf(stderr, "Option ROM file is not specified\n");

                    exit(1);

                }

		nb_option_roms++;

		break;

            case QEMU_OPTION_semihosting:

                semihosting_enabled = 1;

                break;

            case QEMU_OPTION_name:

                qemu_name = g_strdup(optarg);

		 {

		     char *p = strchr(qemu_name, ',');

		     if (p != NULL) {

		        *p++ = 0;

			if (strncmp(p, "process=", 8)) {

			    fprintf(stderr, "Unknown subargument %s to -name\n", p);

			    exit(1);

			}

			p += 8;

			os_set_proc_name(p);

		     }

		 }

                break;

            case QEMU_OPTION_prom_env:

                if (nb_prom_envs >= MAX_PROM_ENVS) {

                    fprintf(stderr, "Too many prom variables\n");

                    exit(1);

                }

                prom_envs[nb_prom_envs] = optarg;

                nb_prom_envs++;

                break;

            case QEMU_OPTION_old_param:

                old_param = 1;

                break;

            case QEMU_OPTION_clock:

                configure_alarms(optarg);

                break;

            case QEMU_OPTION_startdate:

                configure_rtc_date_offset(optarg, 1);

                break;

            case QEMU_OPTION_rtc:

                opts = qemu_opts_parse(qemu_find_opts("rtc"), optarg, 0);

                if (!opts) {

                    exit(1);

                }

                configure_rtc(opts);

                break;

            case QEMU_OPTION_tb_size:

                tcg_tb_size = strtol(optarg, NULL, 0);

                if (tcg_tb_size < 0) {

                    tcg_tb_size = 0;

                }

                break;

            case QEMU_OPTION_icount:

                icount_option = optarg;

                break;

            case QEMU_OPTION_incoming:

                incoming = optarg;

                break;

            case QEMU_OPTION_nodefaults:

                default_serial = 0;

                default_parallel = 0;

                default_virtcon = 0;

                default_monitor = 0;

                default_vga = 0;

                default_net = 0;

                default_floppy = 0;

                default_cdrom = 0;

                default_sdcard = 0;

                break;

            case QEMU_OPTION_xen_domid:

                if (!(xen_available())) {

                    printf("Option %s not supported for this target\n", popt->name);

                    exit(1);

                }

                xen_domid = atoi(optarg);

                break;

            case QEMU_OPTION_xen_create:

                if (!(xen_available())) {

                    printf("Option %s not supported for this target\n", popt->name);

                    exit(1);

                }

                xen_mode = XEN_CREATE;

                break;

            case QEMU_OPTION_xen_attach:

                if (!(xen_available())) {

                    printf("Option %s not supported for this target\n", popt->name);

                    exit(1);

                }

                xen_mode = XEN_ATTACH;

                break;

            case QEMU_OPTION_trace:

            {

                opts = qemu_opts_parse(qemu_find_opts("trace"), optarg, 0);

                if (!opts) {

                    exit(1);

                }

                trace_events = qemu_opt_get(opts, "events");

                trace_file = qemu_opt_get(opts, "file");

                break;

            }

            case QEMU_OPTION_readconfig:

                {

                    int ret = qemu_read_config_file(optarg);

                    if (ret < 0) {

                        fprintf(stderr, "read config %s: %s\n", optarg,

                            strerror(-ret));

                        exit(1);

                    }

                    break;

                }

            case QEMU_OPTION_spice:

                olist = qemu_find_opts("spice");

                if (!olist) {

                    fprintf(stderr, "spice is not supported by this qemu build.\n");

                    exit(1);

                }

                opts = qemu_opts_parse(olist, optarg, 0);

                if (!opts) {

                    fprintf(stderr, "parse error: %s\n", optarg);

                    exit(1);

                }

                break;

            case QEMU_OPTION_writeconfig:

                {

                    FILE *fp;

                    if (strcmp(optarg, "-") == 0) {

                        fp = stdout;

                    } else {

                        fp = fopen(optarg, "w");

                        if (fp == NULL) {

                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));

                            exit(1);

                        }

                    }

                    qemu_config_write(fp);

                    fclose(fp);

                    break;

                }

            default:

                os_parse_cmd_args(popt->index, optarg);

            }

        }

    }

    loc_set_none();

    /* Open the logfile at this point, if necessary. We can't open the logfile

     * when encountering either of the logging options (-d or -D) because the

     * other one may be encountered later on the command line, changing the

     * location or level of logging.

     */

    if (log_mask) {

        if (log_file) {

            set_cpu_log_filename(log_file);

        }

        set_cpu_log(log_mask);

    }

    if (!trace_backend_init(trace_events, trace_file)) {

        exit(1);

    }

    /* If no data_dir is specified then try to find it relative to the

       executable path.  */

    if (!data_dir) {

        data_dir = os_find_datadir(argv[0]);

    }

    /* If all else fails use the install path specified when building. */

    if (!data_dir) {

        data_dir = CONFIG_QEMU_DATADIR;

    }

    if (machine == NULL) {

        fprintf(stderr, "No machine found.\n");

        exit(1);

    }

    /*

     * Default to max_cpus = smp_cpus, in case the user doesn't

     * specify a max_cpus value.

     */

    if (!max_cpus)

        max_cpus = smp_cpus;

    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */

    if (smp_cpus > machine->max_cpus) {

        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "

                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,

                machine->max_cpus);

        exit(1);

    }

    /*

     * Get the default machine options from the machine if it is not already

     * specified either by the configuration file or by the command line.

     */

    if (machine->default_machine_opts) {

        QemuOptsList *list = qemu_find_opts("machine");

        const char *p = NULL;

        if (!QTAILQ_EMPTY(&list->head)) {

            p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");

        }

        if (p == NULL) {

            qemu_opts_reset(list);

            opts = qemu_opts_parse(list, machine->default_machine_opts, 0);

            if (!opts) {

                fprintf(stderr, "parse error for machine %s: %s\n",

                        machine->name, machine->default_machine_opts);

                exit(1);

            }

        }

    }

    qemu_opts_foreach(qemu_find_opts("device"), default_driver_check, NULL, 0);

    qemu_opts_foreach(qemu_find_opts("global"), default_driver_check, NULL, 0);

    if (machine->no_serial) {

        default_serial = 0;

    }

    if (machine->no_parallel) {

        default_parallel = 0;

    }

    if (!machine->use_virtcon) {

        default_virtcon = 0;

    }

    if (machine->no_vga) {

        default_vga = 0;

    }

    if (machine->no_floppy) {

        default_floppy = 0;

    }

    if (machine->no_cdrom) {

        default_cdrom = 0;

    }

    if (machine->no_sdcard) {

        default_sdcard = 0;

    }

    if (display_type == DT_NOGRAPHIC) {

        if (default_parallel)

            add_device_config(DEV_PARALLEL, "null");

        if (default_serial && default_monitor) {

            add_device_config(DEV_SERIAL, "mon:stdio");

        } else if (default_virtcon && default_monitor) {

            add_device_config(DEV_VIRTCON, "mon:stdio");

        } else {

            if (default_serial)

                add_device_config(DEV_SERIAL, "stdio");

            if (default_virtcon)

                add_device_config(DEV_VIRTCON, "stdio");

            if (default_monitor)

                monitor_parse("stdio", "readline");

        }

    } else {

        if (default_serial)

            add_device_config(DEV_SERIAL, "vc:80Cx24C");

        if (default_parallel)

            add_device_config(DEV_PARALLEL, "vc:80Cx24C");

        if (default_monitor)

            monitor_parse("vc:80Cx24C", "readline");

        if (default_virtcon)

            add_device_config(DEV_VIRTCON, "vc:80Cx24C");

    }

    if (default_vga)

        vga_interface_type = VGA_CIRRUS;

    socket_init();

    if (qemu_opts_foreach(qemu_find_opts("chardev"), chardev_init_func, NULL, 1) != 0)

        exit(1);

#ifdef CONFIG_VIRTFS

    if (qemu_opts_foreach(qemu_find_opts("fsdev"), fsdev_init_func, NULL, 1) != 0) {

        exit(1);

    }

#endif

    os_daemonize();

    if (pid_file && qemu_create_pidfile(pid_file) != 0) {

        os_pidfile_error();

        exit(1);

    }

    /* init the memory */

    if (ram_size == 0) {

        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;

    }

    configure_accelerator();

    qemu_init_cpu_loop();

    if (qemu_init_main_loop()) {

        fprintf(stderr, "qemu_init_main_loop failed\n");

        exit(1);

    }

    linux_boot = (kernel_filename != NULL);

    if (!linux_boot && *kernel_cmdline != '\0') {

        fprintf(stderr, "-append only allowed with -kernel option\n");

        exit(1);

    }

    if (!linux_boot && initrd_filename != NULL) {

        fprintf(stderr, "-initrd only allowed with -kernel option\n");

        exit(1);

    }

    os_set_line_buffering();

    if (init_timer_alarm() < 0) {

        fprintf(stderr, "could not initialize alarm timer\n");

        exit(1);

    }

    if (icount_option && (kvm_enabled() || xen_enabled())) {

        fprintf(stderr, "-icount is not allowed with kvm or xen\n");

        exit(1);

    }

    configure_icount(icount_option);

    if (net_init_clients() < 0) {

        exit(1);

    }

    /* init the bluetooth world */

    if (foreach_device_config(DEV_BT, bt_parse))

        exit(1);

    if (!xen_enabled()) {

        /* On 32-bit hosts, QEMU is limited by virtual address space */

        if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {

            fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");

            exit(1);

        }

    }

    cpu_exec_init_all();

    bdrv_init_with_whitelist();

    blk_mig_init();

    /* open the virtual block devices */

    if (snapshot)

        qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot, NULL, 0);

    if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func, &machine->use_scsi, 1) != 0)

        exit(1);

    default_drive(default_cdrom, snapshot, machine->use_scsi,

                  IF_DEFAULT, 2, CDROM_OPTS);

    default_drive(default_floppy, snapshot, machine->use_scsi,

                  IF_FLOPPY, 0, FD_OPTS);

    default_drive(default_sdcard, snapshot, machine->use_scsi,

                  IF_SD, 0, SD_OPTS);

    register_savevm_live(NULL, "ram", 0, 4, NULL, ram_save_live, NULL,

                         ram_load, NULL);

    if (nb_numa_nodes > 0) {

        int i;

        if (nb_numa_nodes > MAX_NODES) {

            nb_numa_nodes = MAX_NODES;

        }

        /* If no memory size if given for any node, assume the default case

         * and distribute the available memory equally across all nodes

         */

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

            if (node_mem[i] != 0)

                break;

        }

        if (i == nb_numa_nodes) {

            uint64_t usedmem = 0;

            /* On Linux, the each node's border has to be 8MB aligned,

             * the final node gets the rest.

             */

            for (i = 0; i < nb_numa_nodes - 1; i++) {

                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);

                usedmem += node_mem[i];

            }

            node_mem[i] = ram_size - usedmem;

        }

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

            if (node_cpumask[i] != 0)

                break;

        }

        /* assigning the VCPUs round-robin is easier to implement, guest OSes

         * must cope with this anyway, because there are BIOSes out there in

         * real machines which also use this scheme.

         */

        if (i == nb_numa_nodes) {

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

                node_cpumask[i % nb_numa_nodes] |= 1 << i;

            }

        }

    }

    if (qemu_opts_foreach(qemu_find_opts("mon"), mon_init_func, NULL, 1) != 0) {

        exit(1);

    }

    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)

        exit(1);

    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)

        exit(1);

    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)

        exit(1);

    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)

        exit(1);

    module_call_init(MODULE_INIT_DEVICE);

    if (qemu_opts_foreach(qemu_find_opts("device"), device_help_func, NULL, 0) != 0)

        exit(0);

    if (watchdog) {

        i = select_watchdog(watchdog);

        if (i > 0)

            exit (i == 1 ? 1 : 0);

    }

    if (machine->compat_props) {

        qdev_prop_register_global_list(machine->compat_props);

    }

    qemu_add_globals();

    qdev_machine_init();

    machine->init(ram_size, boot_devices,

                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);

    cpu_synchronize_all_post_init();

    set_numa_modes();

    current_machine = machine;

    /* init USB devices */

    if (usb_enabled) {

        if (foreach_device_config(DEV_USB, usb_parse) < 0)

            exit(1);

    }

    /* init generic devices */

    if (qemu_opts_foreach(qemu_find_opts("device"), device_init_func, NULL, 1) != 0)

        exit(1);

    net_check_clients();

    /* just use the first displaystate for the moment */

    ds = get_displaystate();

    if (using_spice)

        display_remote++;

    if (display_type == DT_DEFAULT && !display_remote) {

#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)

        display_type = DT_SDL;

#elif defined(CONFIG_VNC)

        vnc_display = "localhost:0,to=99";

        show_vnc_port = 1;

#else

        display_type = DT_NONE;

#endif

    }

    /* init local displays */

    switch (display_type) {

    case DT_NOGRAPHIC:

        break;

#if defined(CONFIG_CURSES)

    case DT_CURSES:

        curses_display_init(ds, full_screen);

        break;

#endif

#if defined(CONFIG_SDL)

    case DT_SDL:

        sdl_display_init(ds, full_screen, no_frame);

        break;

#elif defined(CONFIG_COCOA)

    case DT_SDL:

        cocoa_display_init(ds, full_screen);

        break;

#endif

    default:

        break;

    }

    /* must be after terminal init, SDL library changes signal handlers */

    os_setup_signal_handling();

#ifdef CONFIG_VNC

    /* init remote displays */

    if (vnc_display) {

        vnc_display_init(ds);

        if (vnc_display_open(ds, vnc_display) < 0)

            exit(1);

        if (show_vnc_port) {

            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));

        }

    }

#endif

#ifdef CONFIG_SPICE

    if (using_spice && !qxl_enabled) {

        qemu_spice_display_init(ds);

    }

#endif

    /* display setup */

    dpy_resize(ds);

    dcl = ds->listeners;

    while (dcl != NULL) {

        if (dcl->dpy_refresh != NULL) {

            ds->gui_timer = qemu_new_timer_ms(rt_clock, gui_update, ds);

            qemu_mod_timer(ds->gui_timer, qemu_get_clock_ms(rt_clock));

            break;

        }

        dcl = dcl->next;

    }

    text_consoles_set_display(ds);

    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {

        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",

                gdbstub_dev);

        exit(1);

    }

    qdev_machine_creation_done();

    if (rom_load_all() != 0) {

        fprintf(stderr, "rom loading failed\n");

        exit(1);

    }

    /* TODO: once all bus devices are qdevified, this should be done

     * when bus is created by qdev.c */

    qemu_register_reset(qbus_reset_all_fn, sysbus_get_default());

    qemu_run_machine_init_done_notifiers();

    qemu_system_reset(VMRESET_SILENT);

    if (loadvm) {

        if (load_vmstate(loadvm) < 0) {

            autostart = 0;

        }

    }

    if (incoming) {

        runstate_set(RUN_STATE_INMIGRATE);

        int ret = qemu_start_incoming_migration(incoming);

        if (ret < 0) {

            fprintf(stderr, "Migration failed. Exit code %s(%d), exiting.\n",

                    incoming, ret);

            exit(ret);

        }

    } else if (autostart) {

        vm_start();

    }

    os_setup_post();

    resume_all_vcpus();

    main_loop();

    bdrv_close_all();

    pause_all_vcpus();

    net_cleanup();

    res_free();

    return 0;

}


static int tcp_read(URLContext *h, uint8_t *buf, int size)

{

    TCPContext *s = h->priv_data;

    int size1, len, fd_max;

    fd_set rfds;

    struct timeval tv;

    size1 = size;

    while (size > 0) {

        if (url_interrupt_cb())

            return -EINTR;

        fd_max = s->fd;

        FD_ZERO(&rfds);

        FD_SET(s->fd, &rfds);

        tv.tv_sec = 0;

        tv.tv_usec = 100 * 1000;

        select(fd_max + 1, &rfds, NULL, NULL, &tv);

#ifdef __BEOS__

        len = recv(s->fd, buf, size, 0);

#else

        len = read(s->fd, buf, size);

#endif

        if (len < 0) {

            if (errno != EINTR && errno != EAGAIN)

#ifdef __BEOS__

                return errno;

#else

                return -errno;

#endif

            else

                continue;

        } else if (len == 0) {

            break;

        }

        size -= len;

        buf += len;

    }

    return size1 - size;

}


static int hda_codec_dev_exit(DeviceState *qdev)

{

    HDACodecDevice *dev = HDA_CODEC_DEVICE(qdev);

    HDACodecDeviceClass *cdc = HDA_CODEC_DEVICE_GET_CLASS(dev);

    if (cdc->exit) {

        cdc->exit(dev);

    }

    return 0;

}


static bool virtqueue_map_desc(VirtIODevice *vdev, unsigned int *p_num_sg,

                               hwaddr *addr, struct iovec *iov,

                               unsigned int max_num_sg, bool is_write,

                               hwaddr pa, size_t sz)

{

    bool ok = false;

    unsigned num_sg = *p_num_sg;

    assert(num_sg <= max_num_sg);

    if (!sz) {

        virtio_error(vdev, "virtio: zero sized buffers are not allowed");

        goto out;

    }

    while (sz) {

        hwaddr len = sz;

        if (num_sg == max_num_sg) {

            virtio_error(vdev, "virtio: too many write descriptors in "

                               "indirect table");

            goto out;

        }

        iov[num_sg].iov_base = cpu_physical_memory_map(pa, &len, is_write);

        if (!iov[num_sg].iov_base) {

            virtio_error(vdev, "virtio: bogus descriptor or out of resources");

            goto out;

        }

        iov[num_sg].iov_len = len;

        addr[num_sg] = pa;

        sz -= len;

        pa += len;

        num_sg++;

    }

    ok = true;

out:

    *p_num_sg = num_sg;

    return ok;

}


void i8042_setup_a20_line(ISADevice *dev, qemu_irq *a20_out)

{

    ISAKBDState *isa = I8042(dev);

    KBDState *s = &isa->kbd;

    s->a20_out = a20_out;

}


static int swf_read_header(AVFormatContext *s, AVFormatParameters *ap)

{

    SWFContext *swf = 0;

    ByteIOContext *pb = &s->pb;

    int nbits, len, frame_rate, tag, v;

    offset_t firstTagOff;

    AVStream *ast = 0;

    AVStream *vst = 0;

    swf = av_malloc(sizeof(SWFContext));

    if (!swf)

        return -1;

    s->priv_data = swf;

    tag = get_be32(pb) & 0xffffff00;

    if (tag == MKBETAG('C', 'W', 'S', 0))

    {

        av_log(s, AV_LOG_ERROR, "Compressed SWF format not supported\n");

        return AVERROR_IO;

    }

    if (tag != MKBETAG('F', 'W', 'S', 0))

        return AVERROR_IO;

    get_le32(pb);

    /* skip rectangle size */

    nbits = get_byte(pb) >> 3;

    len = (4 * nbits - 3 + 7) / 8;

    url_fskip(pb, len);

    frame_rate = get_le16(pb);

    get_le16(pb); /* frame count */

    /* The Flash Player converts 8.8 frame rates

       to milliseconds internally. Do the same to get

       a correct framerate */

    swf->ms_per_frame = ( 1000 * 256 ) / frame_rate;

    swf->samples_per_frame = 0;

    swf->ch_id = -1;

    firstTagOff = url_ftell(pb);

    for(;;) {

        tag = get_swf_tag(pb, &len);

        if (tag < 0) {

            if ( ast || vst ) {

                if ( vst && ast ) {

                    vst->codec->time_base.den = ast->codec->sample_rate / swf->samples_per_frame;

                    vst->codec->time_base.num = 1;

                }

                break;

            }

            av_log(s, AV_LOG_ERROR, "No media found in SWF\n");

            return AVERROR_IO;

        }

        if ( tag == TAG_VIDEOSTREAM && !vst) {

            int codec_id;

            swf->ch_id = get_le16(pb);

            get_le16(pb);

            get_le16(pb);

            get_le16(pb);

            get_byte(pb);

            /* Check for FLV1 */

            codec_id = codec_get_id(swf_codec_tags, get_byte(pb));

            if ( codec_id ) {

                vst = av_new_stream(s, 0);

                av_set_pts_info(vst, 24, 1, 1000); /* 24 bit pts in ms */

                vst->codec->codec_type = CODEC_TYPE_VIDEO;

                vst->codec->codec_id = codec_id;

                if ( swf->samples_per_frame ) {

                    vst->codec->time_base.den = 1000. / swf->ms_per_frame;

                    vst->codec->time_base.num = 1;

                }

            }

        } else if ( ( tag == TAG_STREAMHEAD || tag == TAG_STREAMHEAD2 ) && !ast) {

            /* streaming found */

            get_byte(pb);

            v = get_byte(pb);

            swf->samples_per_frame = get_le16(pb);

            if (len!=4)

                url_fskip(pb,len-4);

            /* if mp3 streaming found, OK */

            if ((v & 0x20) != 0) {

                if ( tag == TAG_STREAMHEAD2 ) {

                    get_le16(pb);

                }

                ast = av_new_stream(s, 1);

                av_set_pts_info(ast, 24, 1, 1000); /* 24 bit pts in ms */

                if (!ast)

                    return -ENOMEM;

                if (v & 0x01)

                    ast->codec->channels = 2;

                else

                    ast->codec->channels = 1;

                switch((v>> 2) & 0x03) {

                case 1:

                    ast->codec->sample_rate = 11025;

                    break;

                case 2:

                    ast->codec->sample_rate = 22050;

                    break;

                case 3:

                    ast->codec->sample_rate = 44100;

                    break;

                default:

                    av_free(ast);

                    return AVERROR_IO;

                }

                ast->codec->codec_type = CODEC_TYPE_AUDIO;

                ast->codec->codec_id = CODEC_ID_MP3;

            }

        } else {

            url_fskip(pb, len);

        }

    }

    url_fseek(pb, firstTagOff, SEEK_SET);

    return 0;

}


void ff_weight_h264_pixels16_8_msa(uint8_t *src, int stride,

                                   int height, int log2_denom,

                                   int weight_src, int offset)

{

    avc_wgt_16width_msa(src, stride,

                        height, log2_denom, weight_src, offset);

}


static int decode_dvd_subtitles(DVDSubContext *ctx, AVSubtitle *sub_header,

                                const uint8_t *buf, int buf_size)

{

    int cmd_pos, pos, cmd, x1, y1, x2, y2, offset1, offset2, next_cmd_pos;

    int big_offsets, offset_size, is_8bit = 0;

    const uint8_t *yuv_palette = 0;

    uint8_t colormap[4] = { 0 }, alpha[256] = { 0 };

    int date;

    int i;

    int is_menu = 0;

    if (buf_size < 10)

        return -1;

    memset(sub_header, 0, sizeof(*sub_header));

    if (AV_RB16(buf) == 0) {   /* HD subpicture with 4-byte offsets */

        big_offsets = 1;

        offset_size = 4;

        cmd_pos = 6;

    } else {

        big_offsets = 0;

        offset_size = 2;

        cmd_pos = 2;

    }

    cmd_pos = READ_OFFSET(buf + cmd_pos);

    while (cmd_pos > 0 && cmd_pos < buf_size - 2 - offset_size) {

        date = AV_RB16(buf + cmd_pos);

        next_cmd_pos = READ_OFFSET(buf + cmd_pos + 2);

        av_dlog(NULL, "cmd_pos=0x%04x next=0x%04x date=%d\n",

                cmd_pos, next_cmd_pos, date);

        pos = cmd_pos + 2 + offset_size;

        offset1 = -1;

        offset2 = -1;

        x1 = y1 = x2 = y2 = 0;

        while (pos < buf_size) {

            cmd = buf[pos++];

            av_dlog(NULL, "cmd=%02x\n", cmd);

            switch(cmd) {

            case 0x00:

                /* menu subpicture */

                is_menu = 1;

                break;

            case 0x01:

                /* set start date */

                sub_header->start_display_time = (date << 10) / 90;

                break;

            case 0x02:

                /* set end date */

                sub_header->end_display_time = (date << 10) / 90;

                break;

            case 0x03:

                /* set colormap */

                if ((buf_size - pos) < 2)

                    goto fail;

                colormap[3] = buf[pos] >> 4;

                colormap[2] = buf[pos] & 0x0f;

                colormap[1] = buf[pos + 1] >> 4;

                colormap[0] = buf[pos + 1] & 0x0f;

                pos += 2;

                break;

            case 0x04:

                /* set alpha */

                if ((buf_size - pos) < 2)

                    goto fail;

                alpha[3] = buf[pos] >> 4;

                alpha[2] = buf[pos] & 0x0f;

                alpha[1] = buf[pos + 1] >> 4;

                alpha[0] = buf[pos + 1] & 0x0f;

                pos += 2;

            av_dlog(NULL, "alpha=%x%x%x%x\n", alpha[0],alpha[1],alpha[2],alpha[3]);

                break;

            case 0x05:

            case 0x85:

                if ((buf_size - pos) < 6)

                    goto fail;

                x1 = (buf[pos] << 4) | (buf[pos + 1] >> 4);

                x2 = ((buf[pos + 1] & 0x0f) << 8) | buf[pos + 2];

                y1 = (buf[pos + 3] << 4) | (buf[pos + 4] >> 4);

                y2 = ((buf[pos + 4] & 0x0f) << 8) | buf[pos + 5];

                if (cmd & 0x80)

                    is_8bit = 1;

                av_dlog(NULL, "x1=%d x2=%d y1=%d y2=%d\n", x1, x2, y1, y2);

                pos += 6;

                break;

            case 0x06:

                if ((buf_size - pos) < 4)

                    goto fail;

                offset1 = AV_RB16(buf + pos);

                offset2 = AV_RB16(buf + pos + 2);

                av_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);

                pos += 4;

                break;

            case 0x86:

                if ((buf_size - pos) < 8)

                    goto fail;

                offset1 = AV_RB32(buf + pos);

                offset2 = AV_RB32(buf + pos + 4);

                av_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);

                pos += 8;

                break;

            case 0x83:

                /* HD set palette */

                if ((buf_size - pos) < 768)

                    goto fail;

                yuv_palette = buf + pos;

                pos += 768;

                break;

            case 0x84:

                /* HD set contrast (alpha) */

                if ((buf_size - pos) < 256)

                    goto fail;

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

                    alpha[i] = 0xFF - buf[pos+i];

                pos += 256;

                break;

            case 0xff:

                goto the_end;

            default:

                av_dlog(NULL, "unrecognised subpicture command 0x%x\n", cmd);

                goto the_end;

            }

        }

    the_end:

        if (offset1 >= 0) {

            int w, h;

            uint8_t *bitmap;

            /* decode the bitmap */

            w = x2 - x1 + 1;

            if (w < 0)

                w = 0;

            h = y2 - y1;

            if (h < 0)

                h = 0;

            if (w > 0 && h > 0) {

                if (sub_header->rects != NULL) {

                    for (i = 0; i < sub_header->num_rects; i++) {

                        av_freep(&sub_header->rects[i]->pict.data[0]);

                        av_freep(&sub_header->rects[i]->pict.data[1]);

                        av_freep(&sub_header->rects[i]);

                    }

                    av_freep(&sub_header->rects);

                    sub_header->num_rects = 0;

                }

                bitmap = av_malloc(w * h);

                sub_header->rects = av_mallocz(sizeof(*sub_header->rects));

                sub_header->rects[0] = av_mallocz(sizeof(AVSubtitleRect));

                sub_header->num_rects = 1;

                sub_header->rects[0]->pict.data[0] = bitmap;

                decode_rle(bitmap, w * 2, w, (h + 1) / 2,

                           buf, offset1, buf_size, is_8bit);

                decode_rle(bitmap + w, w * 2, w, h / 2,

                           buf, offset2, buf_size, is_8bit);

                sub_header->rects[0]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);

                if (is_8bit) {

                    if (yuv_palette == 0)

                        goto fail;

                    sub_header->rects[0]->nb_colors = 256;

                    yuv_a_to_rgba(yuv_palette, alpha, (uint32_t*)sub_header->rects[0]->pict.data[1], 256);

                } else {

                    sub_header->rects[0]->nb_colors = 4;

                    guess_palette(ctx,

                                  (uint32_t*)sub_header->rects[0]->pict.data[1],

                                  colormap, alpha, 0xffff00);

                }

                sub_header->rects[0]->x = x1;

                sub_header->rects[0]->y = y1;

                sub_header->rects[0]->w = w;

                sub_header->rects[0]->h = h;

                sub_header->rects[0]->type = SUBTITLE_BITMAP;

                sub_header->rects[0]->pict.linesize[0] = w;

            }

        }

        if (next_cmd_pos == cmd_pos)

            break;

        cmd_pos = next_cmd_pos;

    }

    if (sub_header->num_rects > 0)

        return is_menu;

 fail:

    if (sub_header->rects != NULL) {

        for (i = 0; i < sub_header->num_rects; i++) {

            av_freep(&sub_header->rects[i]->pict.data[0]);

            av_freep(&sub_header->rects[i]->pict.data[1]);

            av_freep(&sub_header->rects[i]);

        }

        av_freep(&sub_header->rects);

        sub_header->num_rects = 0;

    }

    return -1;

}


static int format_name(char *buf, int buf_len, int index)

{

    const char *proto, *dir;

    char *orig_buf_dup = NULL, *mod_buf_dup = NULL;

    int ret = 0;

    if (!av_stristr(buf, "%v"))

        return ret;

    orig_buf_dup = av_strdup(buf);

    if (!orig_buf_dup) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    if (replace_int_data_in_filename(buf, buf_len, orig_buf_dup, 'v', index) < 1) {

        ret = AVERROR(EINVAL);

        goto fail;

    }

    proto = avio_find_protocol_name(orig_buf_dup);

    dir = av_dirname(orig_buf_dup);

    /* if %v is present in the file's directory, create sub-directory */

    if (av_stristr(dir, "%v") && proto && !strcmp(proto, "file")) {

        mod_buf_dup = av_strdup(buf);

        if (!mod_buf_dup) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        dir = av_dirname(mod_buf_dup);

        if (mkdir_p(dir) == -1 && errno != EEXIST) {

            ret = AVERROR(errno);

            goto fail;

        }

    }

fail:

    av_freep(&orig_buf_dup);

    av_freep(&mod_buf_dup);

    return ret;

}


void cpu_reset(CPUSPARCState *env)

{

    if (qemu_loglevel_mask(CPU_LOG_RESET)) {

        qemu_log("CPU Reset (CPU %d)\n", env->cpu_index);

        log_cpu_state(env, 0);

    }

    tlb_flush(env, 1);

    env->cwp = 0;

#ifndef TARGET_SPARC64

    env->wim = 1;

#endif

    env->regwptr = env->regbase + (env->cwp * 16);

#if defined(CONFIG_USER_ONLY)

#ifdef TARGET_SPARC64

    env->cleanwin = env->nwindows - 2;

    env->cansave = env->nwindows - 2;

    env->pstate = PS_RMO | PS_PEF | PS_IE;

    env->asi = 0x82; // Primary no-fault

#endif

#else

#if !defined(TARGET_SPARC64)

    env->psret = 0;

#endif

    env->psrs = 1;

    env->psrps = 1;

    CC_OP = CC_OP_FLAGS;

#ifdef TARGET_SPARC64

    env->pstate = PS_PRIV;

    env->hpstate = HS_PRIV;

    env->tsptr = &env->ts[env->tl & MAXTL_MASK];

    env->lsu = 0;

#else

    env->mmuregs[0] &= ~(MMU_E | MMU_NF);

    env->mmuregs[0] |= env->def->mmu_bm;

#endif

    env->pc = 0;

    env->npc = env->pc + 4;

#endif

}


net_rx_pkt_pull_data(struct NetRxPkt *pkt,

                        const struct iovec *iov, int iovcnt,

                        size_t ploff)

{

    if (pkt->vlan_stripped) {

        net_rx_pkt_iovec_realloc(pkt, iovcnt + 1);

        pkt->vec[0].iov_base = pkt->ehdr_buf;

        pkt->vec[0].iov_len = sizeof(pkt->ehdr_buf);

        pkt->tot_len =

            iov_size(iov, iovcnt) - ploff + sizeof(struct eth_header);

        pkt->vec_len = iov_copy(pkt->vec + 1, pkt->vec_len_total - 1,

                                iov, iovcnt, ploff, pkt->tot_len);

    } else {

        net_rx_pkt_iovec_realloc(pkt, iovcnt);

        pkt->tot_len = iov_size(iov, iovcnt) - ploff;

        pkt->vec_len = iov_copy(pkt->vec, pkt->vec_len_total,

                                iov, iovcnt, ploff, pkt->tot_len);

    }

    eth_get_protocols(pkt->vec, pkt->vec_len, &pkt->isip4, &pkt->isip6,

                      &pkt->isudp, &pkt->istcp,

                      &pkt->l3hdr_off, &pkt->l4hdr_off, &pkt->l5hdr_off,

                      &pkt->ip6hdr_info, &pkt->ip4hdr_info, &pkt->l4hdr_info);

    trace_net_rx_pkt_parsed(pkt->isip4, pkt->isip6, pkt->isudp, pkt->istcp,

                            pkt->l3hdr_off, pkt->l4hdr_off, pkt->l5hdr_off);

}


MigrationState *tcp_start_outgoing_migration(Monitor *mon,

                                             const char *host_port,

                                             int64_t bandwidth_limit,

                                             int detach,

					     int blk,

					     int inc)

{

    struct sockaddr_in addr;

    FdMigrationState *s;

    int ret;

    if (parse_host_port(&addr, host_port) < 0)

        return NULL;

    s = qemu_mallocz(sizeof(*s));

    s->get_error = socket_errno;

    s->write = socket_write;

    s->close = tcp_close;

    s->mig_state.cancel = migrate_fd_cancel;

    s->mig_state.get_status = migrate_fd_get_status;

    s->mig_state.release = migrate_fd_release;

    s->mig_state.blk = blk;

    s->mig_state.shared = inc;

    s->state = MIG_STATE_ACTIVE;

    s->mon = NULL;

    s->bandwidth_limit = bandwidth_limit;

    s->fd = socket(PF_INET, SOCK_STREAM, 0);

    if (s->fd == -1) {

        qemu_free(s);

        return NULL;

    }

    socket_set_nonblock(s->fd);

    if (!detach) {

        migrate_fd_monitor_suspend(s, mon);

    }

    do {

        ret = connect(s->fd, (struct sockaddr *)&addr, sizeof(addr));

        if (ret == -1)

            ret = -(s->get_error(s));

        if (ret == -EINPROGRESS || ret == -EWOULDBLOCK)

            qemu_set_fd_handler2(s->fd, NULL, NULL, tcp_wait_for_connect, s);

    } while (ret == -EINTR);

    if (ret < 0 && ret != -EINPROGRESS && ret != -EWOULDBLOCK) {

        dprintf("connect failed\n");

        close(s->fd);

        qemu_free(s);

        return NULL;

    } else if (ret >= 0)

        migrate_fd_connect(s);

    return &s->mig_state;

}


int main_loop(void *opaque)

{

    struct pollfd ufds[2], *pf, *serial_ufd, *net_ufd, *gdb_ufd;

    int ret, n, timeout;

    uint8_t ch;

    CPUState *env = global_env;

    if (!term_inited) {

        /* initialize terminal only there so that the user has a

           chance to stop QEMU with Ctrl-C before the gdb connection

           is launched */

        term_inited = 1;

        term_init();

    }

    for(;;) {

        ret = cpu_x86_exec(env);

        if (reset_requested)

            break;

        if (ret == EXCP_DEBUG)

            return EXCP_DEBUG;

        /* if hlt instruction, we wait until the next IRQ */

        if (ret == EXCP_HLT)

            timeout = 10;

        else

            timeout = 0;

        /* poll any events */

        serial_ufd = NULL;

        pf = ufds;

        if (!(serial_ports[0].lsr & UART_LSR_DR)) {

            serial_ufd = pf;

            pf->fd = 0;

            pf->events = POLLIN;

            pf++;

        }

        net_ufd = NULL;

        if (net_fd > 0 && ne2000_can_receive(&ne2000_state)) {

            net_ufd = pf;

            pf->fd = net_fd;

            pf->events = POLLIN;

            pf++;

        }

        gdb_ufd = NULL;

        if (gdbstub_fd > 0) {

            gdb_ufd = pf;

            pf->fd = gdbstub_fd;

            pf->events = POLLIN;

            pf++;

        }

        ret = poll(ufds, pf - ufds, timeout);

        if (ret > 0) {

            if (serial_ufd && (serial_ufd->revents & POLLIN)) {

                n = read(0, &ch, 1);

                if (n == 1) {

                    serial_received_byte(&serial_ports[0], ch);

                }

            }

            if (net_ufd && (net_ufd->revents & POLLIN)) {

                uint8_t buf[MAX_ETH_FRAME_SIZE];

                n = read(net_fd, buf, MAX_ETH_FRAME_SIZE);

                if (n > 0) {

                    if (n < 60) {

                        memset(buf + n, 0, 60 - n);

                        n = 60;

                    }

                    ne2000_receive(&ne2000_state, buf, n);

                }

            }

            if (gdb_ufd && (gdb_ufd->revents & POLLIN)) {

                uint8_t buf[1];

                /* stop emulation if requested by gdb */

                n = read(gdbstub_fd, buf, 1);

                if (n == 1)

                    break;

            }

        }

        /* timer IRQ */

        if (timer_irq_pending) {

            pic_set_irq(0, 1);

            pic_set_irq(0, 0);

            timer_irq_pending = 0;

        }

        /* VGA */

        if (gui_refresh_pending) {

            display_state.dpy_refresh(&display_state);

            gui_refresh_pending = 0;

        }

    }

    return EXCP_INTERRUPT;

}


static int ehci_state_executing(EHCIQueue *q)

{

    EHCIPacket *p = QTAILQ_FIRST(&q->packets);

    assert(p != NULL);

    assert(p->qtdaddr == q->qtdaddr);

    ehci_execute_complete(q);

    // 4.10.3

    if (!q->async) {

        int transactCtr = get_field(q->qh.epcap, QH_EPCAP_MULT);

        transactCtr--;

        set_field(&q->qh.epcap, transactCtr, QH_EPCAP_MULT);

        // 4.10.3, bottom of page 82, should exit this state when transaction

        // counter decrements to 0

    }

    /* 4.10.5 */

    if (p->usb_status == USB_RET_NAK) {

        ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);

    } else {

        ehci_set_state(q->ehci, q->async, EST_WRITEBACK);

    }

    ehci_flush_qh(q);

    return 1;

}


static int decode(MimicContext *ctx, int quality, int num_coeffs,

                  int is_iframe)

{

    int y, x, plane, cur_row = 0;

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

        const int is_chroma = !!plane;

        const int qscale = av_clip(10000-quality,is_chroma?1000:2000,10000)<<2;

        const int stride = ctx->flipped_ptrs[ctx->cur_index].linesize[plane];

        const uint8_t *src = ctx->flipped_ptrs[ctx->prev_index].data[plane];

        uint8_t       *dst = ctx->flipped_ptrs[ctx->cur_index ].data[plane];

        for(y = 0; y < ctx->num_vblocks[plane]; y++) {

            for(x = 0; x < ctx->num_hblocks[plane]; x++) {

                /* Check for a change condition in the current block.

                 * - iframes always change.

                 * - Luma plane changes on get_bits1 == 0

                 * - Chroma planes change on get_bits1 == 1 */

                if(is_iframe || get_bits1(&ctx->gb) == is_chroma) {

                    /* Luma planes may use a backreference from the 15 last

                     * frames preceding the previous. (get_bits1 == 1)

                     * Chroma planes don't use backreferences. */

                    if(is_chroma || is_iframe || !get_bits1(&ctx->gb)) {

                        if(!vlc_decode_block(ctx, num_coeffs, qscale))

                            return 0;

                        ctx->dsp.idct_put(dst, stride, ctx->dct_block);

                    } else {

                        unsigned int backref = get_bits(&ctx->gb, 4);

                        int index = (ctx->cur_index+backref)&15;

                        uint8_t *p = ctx->flipped_ptrs[index].data[0];

                        ff_thread_await_progress(&ctx->buf_ptrs[index], cur_row, 0);

                        if(p) {

                            p += src -

                                ctx->flipped_ptrs[ctx->prev_index].data[plane];

                            ctx->dsp.put_pixels_tab[1][0](dst, p, stride, 8);

                        } else {

                            av_log(ctx->avctx, AV_LOG_ERROR,

                                     "No such backreference! Buggy sample.\n");

                        }

                    }

                } else {

                    ff_thread_await_progress(&ctx->buf_ptrs[ctx->prev_index], cur_row, 0);

                    ctx->dsp.put_pixels_tab[1][0](dst, src, stride, 8);

                }

                src += 8;

                dst += 8;

            }

            src += (stride - ctx->num_hblocks[plane])<<3;

            dst += (stride - ctx->num_hblocks[plane])<<3;

            ff_thread_report_progress(&ctx->buf_ptrs[ctx->cur_index], cur_row++, 0);

        }

    }

    return 1;

}


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

{

    UnsharpContext *unsharp = ctx->priv;

    int lmsize_x = 5, cmsize_x = 0;

    int lmsize_y = 5, cmsize_y = 0;

    double lamount = 1.0f, camount = 0.0f;

    if (args)

        sscanf(args, "%d:%d:%lf:%d:%d:%lf", &lmsize_x, &lmsize_y, &lamount,

                                            &cmsize_x, &cmsize_y, &camount);

    if (lmsize_x < 2 || lmsize_y < 2 || cmsize_x < 2 || cmsize_y < 2) {

        av_log(ctx, AV_LOG_ERROR,

               "Invalid value <2 for lmsize_x:%d or lmsize_y:%d or cmsize_x:%d or cmsize_y:%d\n",

               lmsize_x, lmsize_y, cmsize_x, cmsize_y);

        return AVERROR(EINVAL);

    }

    set_filter_param(&unsharp->luma,   lmsize_x, lmsize_y, lamount);

    set_filter_param(&unsharp->chroma, cmsize_x, cmsize_y, camount);

    return 0;

}


static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv)

{

    static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b};

    MXFContext *mxf = s->priv_data;

    AVIOContext *pb = s->pb;

    int64_t end = avio_tell(pb) + klv->length;

    uint64_t size;

    uint64_t orig_size;

    uint64_t plaintext_size;

    uint8_t ivec[16];

    uint8_t tmpbuf[16];

    int index;

    if (!mxf->aesc && s->key && s->keylen == 16) {

        mxf->aesc = av_malloc(av_aes_size);

        if (!mxf->aesc)

            return -1;

        av_aes_init(mxf->aesc, s->key, 128, 1);

    }

    // crypto context

    avio_skip(pb, klv_decode_ber_length(pb));

    // plaintext offset

    klv_decode_ber_length(pb);

    plaintext_size = avio_rb64(pb);

    // source klv key

    klv_decode_ber_length(pb);

    avio_read(pb, klv->key, 16);

    if (!IS_KLV_KEY(klv, mxf_essence_element_key))

        return -1;

    index = mxf_get_stream_index(s, klv);

    if (index < 0)

        return -1;

    // source size

    klv_decode_ber_length(pb);

    orig_size = avio_rb64(pb);

    if (orig_size < plaintext_size)

        return -1;

    // enc. code

    size = klv_decode_ber_length(pb);

    if (size < 32 || size - 32 < orig_size)

        return -1;

    avio_read(pb, ivec, 16);

    avio_read(pb, tmpbuf, 16);

    if (mxf->aesc)

        av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1);

    if (memcmp(tmpbuf, checkv, 16))

        av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n");

    size -= 32;

    size = av_get_packet(pb, pkt, size);

    if (size < 0)

        return size;

    else if (size < plaintext_size)

        return AVERROR_INVALIDDATA;

    size -= plaintext_size;

    if (mxf->aesc)

        av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size],

                     &pkt->data[plaintext_size], size >> 4, ivec, 1);

    av_shrink_packet(pkt, orig_size);

    pkt->stream_index = index;

    avio_skip(pb, end - avio_tell(pb));

    return 0;

}


static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
                                const AVFrame *pic, int *got_packet)
{
    libx265Context *ctx = avctx->priv_data;
    x265_picture x265pic;
    x265_picture x265pic_out = { { 0 } };
    x265_nal *nal;
    uint8_t *dst;
    int payload = 0;
    int nnal;
    int ret;
    int i;
    if (pic) {
        for (i = 0; i < 3; i++) {
           x265pic.planes[i] = pic->data[i];
           x265pic.stride[i] = pic->linesize[i];
        }
        x265pic.pts = pic->pts;
    }
    ret = x265_encoder_encode(ctx->encoder, &nal, &nnal,
                              pic ? &x265pic : NULL, &x265pic_out);
    if (ret < 0)
        return AVERROR_UNKNOWN;
    if (!nnal)
        return 0;
    for (i = 0; i < nnal; i++)
        payload += nal[i].sizeBytes;
    payload += ctx->header_size;
    ret = ff_alloc_packet(pkt, payload);
    if (ret < 0) {
        av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
        return ret;
    }
    dst = pkt->data;
    if (ctx->header) {
        memcpy(dst, ctx->header, ctx->header_size);
        dst += ctx->header_size;
        av_freep(&ctx->header);
        ctx->header_size = 0;
    }
    for (i = 0; i < nnal; i++) {
        memcpy(dst, nal[i].payload, nal[i].sizeBytes);
        dst += nal[i].sizeBytes;
        if (is_keyframe(nal[i].type))
            pkt->flags |= AV_PKT_FLAG_KEY;
    }
    pkt->pts = x265pic_out.pts;
    pkt->dts = x265pic_out.dts;
    *got_packet = 1;
    return 0;
}


static inline TCGv gen_ld16u(TCGv addr, int index)

{

    TCGv tmp = new_tmp();

    tcg_gen_qemu_ld16u(tmp, addr, index);

    return tmp;

}


static int opus_decode_packet(AVCodecContext *avctx, void *data,
                              int *got_frame_ptr, AVPacket *avpkt)
{
    OpusContext *c      = avctx->priv_data;
    AVFrame *frame      = data;
    const uint8_t *buf  = avpkt->data;
    int buf_size        = avpkt->size;
    int coded_samples   = 0;
    int decoded_samples = 0;
    int i, ret;
    /* decode the header of the first sub-packet to find out the sample count */
    if (buf) {
        OpusPacket *pkt = &c->streams[0].packet;
        ret = ff_opus_parse_packet(pkt, buf, buf_size, c->nb_streams > 1);
        if (ret < 0) {
            av_log(avctx, AV_LOG_ERROR, "Error parsing the packet header.\n");
            return ret;
        coded_samples += pkt->frame_count * pkt->frame_duration;
        c->streams[0].silk_samplerate = get_silk_samplerate(pkt->config);
    frame->nb_samples = coded_samples + c->streams[0].delayed_samples;
    /* no input or buffered data => nothing to do */
    if (!frame->nb_samples) {
        *got_frame_ptr = 0;
        return 0;
    /* setup the data buffers */
    ret = ff_get_buffer(avctx, frame, 0);
    if (ret < 0) {
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
        return ret;
    frame->nb_samples = 0;
    for (i = 0; i < avctx->channels; i++) {
        ChannelMap *map = &c->channel_maps[i];
        if (!map->copy)
            c->streams[map->stream_idx].out[map->channel_idx] = (float*)frame->extended_data[i];
    for (i = 0; i < c->nb_streams; i++)
        c->streams[i].out_size = frame->linesize[0];
    /* decode each sub-packet */
    for (i = 0; i < c->nb_streams; i++) {
        OpusStreamContext *s = &c->streams[i];
        if (i && buf) {
            ret = ff_opus_parse_packet(&s->packet, buf, buf_size, i != c->nb_streams - 1);
            if (ret < 0) {
                av_log(avctx, AV_LOG_ERROR, "Error parsing the packet header.\n");
                return ret;
            s->silk_samplerate = get_silk_samplerate(s->packet.config);
        ret = opus_decode_subpacket(&c->streams[i], buf,
                                    s->packet.data_size, coded_samples);
        if (ret < 0)
            return ret;
        if (decoded_samples && ret != decoded_samples) {
            av_log(avctx, AV_LOG_ERROR, "Different numbers of decoded samples "
                   "in a multi-channel stream\n");
        decoded_samples = ret;
        buf      += s->packet.packet_size;
        buf_size -= s->packet.packet_size;
    for (i = 0; i < avctx->channels; i++) {
        ChannelMap *map = &c->channel_maps[i];
        /* handle copied channels */
        if (map->copy) {
            memcpy(frame->extended_data[i],
                   frame->extended_data[map->copy_idx],
                   frame->linesize[0]);
        } else if (map->silence) {
            memset(frame->extended_data[i], 0, frame->linesize[0]);
        if (c->gain_i) {
            c->fdsp.vector_fmul_scalar((float*)frame->extended_data[i],
                                       (float*)frame->extended_data[i],
                                       c->gain, FFALIGN(decoded_samples, 8));
    frame->nb_samples = decoded_samples;
    *got_frame_ptr    = !!decoded_samples;
    return avpkt->size;


int page_check_range(target_ulong start, target_ulong len, int flags)

{

    PageDesc *p;

    target_ulong end;

    target_ulong addr;

    /* This function should never be called with addresses outside the

       guest address space.  If this assert fires, it probably indicates

       a missing call to h2g_valid.  */

#if TARGET_ABI_BITS > L1_MAP_ADDR_SPACE_BITS

    assert(start < ((abi_ulong)1 << L1_MAP_ADDR_SPACE_BITS));

#endif

    if (len == 0) {

        return 0;

    }

    if (start + len - 1 < start) {

        /* We've wrapped around.  */

        return -1;

    }

    /* must do before we loose bits in the next step */

    end = TARGET_PAGE_ALIGN(start + len);

    start = start & TARGET_PAGE_MASK;

    for (addr = start, len = end - start;

         len != 0;

         len -= TARGET_PAGE_SIZE, addr += TARGET_PAGE_SIZE) {

        p = page_find(addr >> TARGET_PAGE_BITS);

        if (!p) {

            return -1;

        }

        if (!(p->flags & PAGE_VALID)) {

            return -1;

        }

        if ((flags & PAGE_READ) && !(p->flags & PAGE_READ)) {

            return -1;

        }

        if (flags & PAGE_WRITE) {

            if (!(p->flags & PAGE_WRITE_ORG)) {

                return -1;

            }

            /* unprotect the page if it was put read-only because it

               contains translated code */

            if (!(p->flags & PAGE_WRITE)) {

                if (!page_unprotect(addr, 0, NULL)) {

                    return -1;

                }

            }

            return 0;

        }

    }

    return 0;

}


static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,

                    unsigned *nb_files_alloc)

{

    ConcatContext *cat = avf->priv_data;

    ConcatFile *file;

    char *url;

    size_t url_len;

    if (cat->safe > 0 && !safe_filename(filename)) {

        av_log(avf, AV_LOG_ERROR, "Unsafe file name '%s'\n", filename);

        return AVERROR(EPERM);

    }

    url_len = strlen(avf->filename) + strlen(filename) + 16;

    if (!(url = av_malloc(url_len)))

        return AVERROR(ENOMEM);

    ff_make_absolute_url(url, url_len, avf->filename, filename);

    av_free(filename);

    if (cat->nb_files >= *nb_files_alloc) {

        size_t n = FFMAX(*nb_files_alloc * 2, 16);

        ConcatFile *new_files;

        if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||

            !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))

            return AVERROR(ENOMEM);

        cat->files = new_files;

        *nb_files_alloc = n;

    }

    file = &cat->files[cat->nb_files++];

    memset(file, 0, sizeof(*file));

    *rfile = file;

    file->url        = url;

    file->start_time = AV_NOPTS_VALUE;

    file->duration   = AV_NOPTS_VALUE;

    return 0;

}


void avfilter_copy_buffer_ref_props(AVFilterBufferRef *dst, AVFilterBufferRef *src)
{
    // copy common properties
    dst->pts             = src->pts;
    dst->pos             = src->pos;
    switch (src->type) {
    case AVMEDIA_TYPE_VIDEO: {
        if (dst->video->qp_table)
            av_freep(&dst->video->qp_table);
        copy_video_props(dst->video, src->video);
        break;
    }
    case AVMEDIA_TYPE_AUDIO: *dst->audio = *src->audio; break;
    default: break;
    }
}


static void test_validate_fail_list(TestInputVisitorData *data,

                                     const void *unused)

{

    UserDefOneList *head = NULL;

    Error *err = NULL;

    Visitor *v;

    v = validate_test_init(data, "[ { 'string': 'string0', 'integer': 42 }, { 'string': 'string1', 'integer': 43 }, { 'string': 'string2', 'integer': 44, 'extra': 'ggg' } ]");

    visit_type_UserDefOneList(v, &head, NULL, &err);

    g_assert(err);

    error_free(err);

    qapi_free_UserDefOneList(head);

}


int ff_find_unused_picture(MpegEncContext *s, int shared){

    int i;

    if(shared){

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

            if(s->picture[i].data[0]==NULL && s->picture[i].type==0) return i;

        }

    }else{

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

            if(s->picture[i].data[0]==NULL && s->picture[i].type!=0) return i; //FIXME

        }

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

            if(s->picture[i].data[0]==NULL) return i;

        }

    }

    assert(0);

    return -1;

}


static void audio_init (PCIBus *pci_bus, qemu_irq *pic)

{

    struct soundhw *c;

    int audio_enabled = 0;

    for (c = soundhw; !audio_enabled && c->name; ++c) {

        audio_enabled = c->enabled;

    }

    if (audio_enabled) {

        AudioState *s;

        s = AUD_init ();

        if (s) {

            for (c = soundhw; c->name; ++c) {

                if (c->enabled) {

                    if (c->isa) {

                        c->init.init_isa (s, pic);

                    }

                    else {

                        if (pci_bus) {

                            c->init.init_pci (pci_bus, s);

                        }

                    }

                }

            }

        }

    }

}


static void destroy_buffers(VADisplay display, VABufferID *buffers, unsigned int n_buffers)

{

    unsigned int i;

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

        if (buffers[i]) {

            vaDestroyBuffer(display, buffers[i]);

            buffers[i] = 0;

        }

    }

}


static void vmxnet3_activate_device(VMXNET3State *s)

{

    int i;

    static const uint32_t VMXNET3_DEF_TX_THRESHOLD = 1;

    hwaddr qdescr_table_pa;

    uint64_t pa;

    uint32_t size;

    /* Verify configuration consistency */

    if (!vmxnet3_verify_driver_magic(s->drv_shmem)) {

        VMW_ERPRN("Device configuration received from driver is invalid");

        return;

    }

    /* Verify if device is active */

    if (s->device_active) {

        VMW_CFPRN("Vmxnet3 device is active");

        return;

    }

    vmxnet3_adjust_by_guest_type(s);

    vmxnet3_update_features(s);

    vmxnet3_update_pm_state(s);

    vmxnet3_setup_rx_filtering(s);

    /* Cache fields from shared memory */

    s->mtu = VMXNET3_READ_DRV_SHARED32(s->drv_shmem, devRead.misc.mtu);

    VMW_CFPRN("MTU is %u", s->mtu);

    s->max_rx_frags =

        VMXNET3_READ_DRV_SHARED16(s->drv_shmem, devRead.misc.maxNumRxSG);

    if (s->max_rx_frags == 0) {

        s->max_rx_frags = 1;

    }

    VMW_CFPRN("Max RX fragments is %u", s->max_rx_frags);

    s->event_int_idx =

        VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.eventIntrIdx);

    assert(vmxnet3_verify_intx(s, s->event_int_idx));

    VMW_CFPRN("Events interrupt line is %u", s->event_int_idx);

    s->auto_int_masking =

        VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.autoMask);

    VMW_CFPRN("Automatic interrupt masking is %d", (int)s->auto_int_masking);

    s->txq_num =

        VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numTxQueues);

    s->rxq_num =

        VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues);

    VMW_CFPRN("Number of TX/RX queues %u/%u", s->txq_num, s->rxq_num);

    vmxnet3_validate_queues(s);

    qdescr_table_pa =

        VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA);

    VMW_CFPRN("TX queues descriptors table is at 0x%" PRIx64, qdescr_table_pa);

    /*

     * Worst-case scenario is a packet that holds all TX rings space so

     * we calculate total size of all TX rings for max TX fragments number

     */

    s->max_tx_frags = 0;

    /* TX queues */

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

        hwaddr qdescr_pa =

            qdescr_table_pa + i * sizeof(struct Vmxnet3_TxQueueDesc);

        /* Read interrupt number for this TX queue */

        s->txq_descr[i].intr_idx =

            VMXNET3_READ_TX_QUEUE_DESCR8(qdescr_pa, conf.intrIdx);

        assert(vmxnet3_verify_intx(s, s->txq_descr[i].intr_idx));

        VMW_CFPRN("TX Queue %d interrupt: %d", i, s->txq_descr[i].intr_idx);

        /* Read rings memory locations for TX queues */

        pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.txRingBasePA);

        size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.txRingSize);

        vmxnet3_ring_init(&s->txq_descr[i].tx_ring, pa, size,

                          sizeof(struct Vmxnet3_TxDesc), false);

        VMXNET3_RING_DUMP(VMW_CFPRN, "TX", i, &s->txq_descr[i].tx_ring);

        s->max_tx_frags += size;

        /* TXC ring */

        pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.compRingBasePA);

        size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.compRingSize);

        vmxnet3_ring_init(&s->txq_descr[i].comp_ring, pa, size,

                          sizeof(struct Vmxnet3_TxCompDesc), true);

        VMXNET3_RING_DUMP(VMW_CFPRN, "TXC", i, &s->txq_descr[i].comp_ring);

        s->txq_descr[i].tx_stats_pa =

            qdescr_pa + offsetof(struct Vmxnet3_TxQueueDesc, stats);

        memset(&s->txq_descr[i].txq_stats, 0,

               sizeof(s->txq_descr[i].txq_stats));

        /* Fill device-managed parameters for queues */

        VMXNET3_WRITE_TX_QUEUE_DESCR32(qdescr_pa,

                                       ctrl.txThreshold,

                                       VMXNET3_DEF_TX_THRESHOLD);

    }

    /* Preallocate TX packet wrapper */

    VMW_CFPRN("Max TX fragments is %u", s->max_tx_frags);

    net_tx_pkt_init(&s->tx_pkt, PCI_DEVICE(s),

                    s->max_tx_frags, s->peer_has_vhdr);

    net_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr);

    /* Read rings memory locations for RX queues */

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

        int j;

        hwaddr qd_pa =

            qdescr_table_pa + s->txq_num * sizeof(struct Vmxnet3_TxQueueDesc) +

            i * sizeof(struct Vmxnet3_RxQueueDesc);

        /* Read interrupt number for this RX queue */

        s->rxq_descr[i].intr_idx =

            VMXNET3_READ_TX_QUEUE_DESCR8(qd_pa, conf.intrIdx);

        assert(vmxnet3_verify_intx(s, s->rxq_descr[i].intr_idx));

        VMW_CFPRN("RX Queue %d interrupt: %d", i, s->rxq_descr[i].intr_idx);

        /* Read rings memory locations */

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

            /* RX rings */

            pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.rxRingBasePA[j]);

            size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.rxRingSize[j]);

            vmxnet3_ring_init(&s->rxq_descr[i].rx_ring[j], pa, size,

                              sizeof(struct Vmxnet3_RxDesc), false);

            VMW_CFPRN("RX queue %d:%d: Base: %" PRIx64 ", Size: %d",

                      i, j, pa, size);

        }

        /* RXC ring */

        pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.compRingBasePA);

        size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.compRingSize);

        vmxnet3_ring_init(&s->rxq_descr[i].comp_ring, pa, size,

                          sizeof(struct Vmxnet3_RxCompDesc), true);

        VMW_CFPRN("RXC queue %d: Base: %" PRIx64 ", Size: %d", i, pa, size);

        s->rxq_descr[i].rx_stats_pa =

            qd_pa + offsetof(struct Vmxnet3_RxQueueDesc, stats);

        memset(&s->rxq_descr[i].rxq_stats, 0,

               sizeof(s->rxq_descr[i].rxq_stats));

    }

    vmxnet3_validate_interrupts(s);

    /* Make sure everything is in place before device activation */

    smp_wmb();

    vmxnet3_reset_mac(s);

    s->device_active = true;

}


bool object_property_get_bool(Object *obj, const char *name,

                              Error **errp)

{

    QObject *ret = object_property_get_qobject(obj, name, errp);

    QBool *qbool;

    bool retval;

    if (!ret) {

        return false;

    }

    qbool = qobject_to_qbool(ret);

    if (!qbool) {

        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name, "boolean");

        retval = false;

    } else {

        retval = qbool_get_bool(qbool);

    }

    QDECREF(qbool);

    return retval;

}


static void mpegts_insert_pcr_only(AVFormatContext *s, AVStream *st)

{

    MpegTSWrite *ts = s->priv_data;

    MpegTSWriteStream *ts_st = st->priv_data;

    uint8_t *q;

    uint8_t buf[TS_PACKET_SIZE];

    q    = buf;

    *q++ = 0x47;

    *q++ = ts_st->pid >> 8;

    *q++ = ts_st->pid;

    *q++ = 0x20 | ts_st->cc;   /* Adaptation only */

    /* Continuity Count field does not increment (see 13818-1 section 2.4.3.3) */

    *q++ = TS_PACKET_SIZE - 5; /* Adaptation Field Length */

    *q++ = 0x10;               /* Adaptation flags: PCR present */

    /* PCR coded into 6 bytes */

    q += write_pcr_bits(q, get_pcr(ts, s->pb));

    /* stuffing bytes */

    memset(q, 0xFF, TS_PACKET_SIZE - (q - buf));

    mpegts_prefix_m2ts_header(s);

    avio_write(s->pb, buf, TS_PACKET_SIZE);


static void disas_extract(DisasContext *s, uint32_t insn)

{

    unsupported_encoding(s, insn);

}


static int dxva2_mpeg2_end_frame(AVCodecContext *avctx)

{

    struct MpegEncContext *s = avctx->priv_data;

    struct dxva2_picture_context *ctx_pic =

        s->current_picture_ptr->hwaccel_picture_private;

    int ret;

    if (ctx_pic->slice_count <= 0 || ctx_pic->bitstream_size <= 0)

        return -1;

    ret = ff_dxva2_common_end_frame(avctx, &s->current_picture_ptr->f,

                                    &ctx_pic->pp, sizeof(ctx_pic->pp),

                                    &ctx_pic->qm, sizeof(ctx_pic->qm),

                                    commit_bitstream_and_slice_buffer);

    if (!ret)

        ff_mpeg_draw_horiz_band(s, 0, avctx->height);

    return ret;

}


static int au_read_header(AVFormatContext *s)

{

    int size;

    unsigned int tag;

    AVIOContext *pb = s->pb;

    unsigned int id, channels, rate;

    int bps;

    enum AVCodecID codec;

    AVStream *st;

    /* check ".snd" header */

    tag = avio_rl32(pb);

    if (tag != MKTAG('.', 's', 'n', 'd'))

        return -1;

    size = avio_rb32(pb); /* header size */

    avio_rb32(pb); /* data size */

    id = avio_rb32(pb);

    rate = avio_rb32(pb);

    channels = avio_rb32(pb);

    codec = ff_codec_get_id(codec_au_tags, id);

    if (codec == AV_CODEC_ID_NONE) {

        av_log_ask_for_sample(s, "unknown or unsupported codec tag: %d\n", id);

        return AVERROR_PATCHWELCOME;

    }

    bps = av_get_bits_per_sample(codec);

    if (!bps) {

        av_log_ask_for_sample(s, "could not determine bits per sample\n");

        return AVERROR_PATCHWELCOME;

    }

    if (channels == 0 || channels > 64) {

        av_log(s, AV_LOG_ERROR, "Invalid number of channels %d\n", channels);

        return AVERROR_INVALIDDATA;

    }

    if (size >= 24) {

        /* skip unused data */

        avio_skip(pb, size - 24);

    }

    /* now we are ready: build format streams */

    st = avformat_new_stream(s, NULL);

    if (!st)

        return -1;

    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    st->codec->codec_tag = id;

    st->codec->codec_id = codec;

    st->codec->channels = channels;

    st->codec->sample_rate = rate;

    st->codec->bit_rate    = channels * rate * bps;

    st->codec->block_align = channels * bps >> 3;

    avpriv_set_pts_info(st, 64, 1, rate);

    return 0;

}


static inline void bink_idct_col(DCTELEM *dest, const DCTELEM *src)

{

    if ((src[8]|src[16]|src[24]|src[32]|src[40]|src[48]|src[56])==0) {

        dest[0]  =

        dest[8]  =

        dest[16] =

        dest[24] =

        dest[32] =

        dest[40] =

        dest[48] =

        dest[56] = src[0];

    } else {

        IDCT_COL(dest, src);

    }

}


static int decode_info_header(NUTContext *nut)

{

    AVFormatContext *s = nut->avf;

    AVIOContext *bc    = s->pb;

    uint64_t tmp, chapter_start, chapter_len;

    unsigned int stream_id_plus1, count;

    int chapter_id, i;

    int64_t value, end;

    char name[256], str_value[1024], type_str[256];

    const char *type;

    int *event_flags;

    AVChapter *chapter      = NULL;

    AVStream *st            = NULL;

    AVDictionary **metadata = NULL;

    int metadata_flag       = 0;

    end  = get_packetheader(nut, bc, 1, INFO_STARTCODE);

    end += avio_tell(bc);

    GET_V(stream_id_plus1, tmp <= s->nb_streams);

    chapter_id    = get_s(bc);

    chapter_start = ffio_read_varlen(bc);

    chapter_len   = ffio_read_varlen(bc);

    count         = ffio_read_varlen(bc);

    if (chapter_id && !stream_id_plus1) {

        int64_t start = chapter_start / nut->time_base_count;

        chapter = avpriv_new_chapter(s, chapter_id,

                                     nut->time_base[chapter_start %

                                                    nut->time_base_count],

                                     start, start + chapter_len, NULL);

        metadata = &chapter->metadata;

    } else if (stream_id_plus1) {

        st       = s->streams[stream_id_plus1 - 1];

        metadata = &st->metadata;

        event_flags = &st->event_flags;

        metadata_flag = AVSTREAM_EVENT_FLAG_METADATA_UPDATED;

    } else {

        metadata = &s->metadata;

        event_flags = &s->event_flags;

        metadata_flag = AVFMT_EVENT_FLAG_METADATA_UPDATED;

    }

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

        get_str(bc, name, sizeof(name));

        value = get_s(bc);

        if (value == -1) {

            type = "UTF-8";

            get_str(bc, str_value, sizeof(str_value));

        } else if (value == -2) {

            get_str(bc, type_str, sizeof(type_str));

            type = type_str;

            get_str(bc, str_value, sizeof(str_value));

        } else if (value == -3) {

            type  = "s";

            value = get_s(bc);

        } else if (value == -4) {

            type  = "t";

            value = ffio_read_varlen(bc);

        } else if (value < -4) {

            type = "r";

            get_s(bc);

        } else {

            type = "v";

        }

        if (stream_id_plus1 > s->nb_streams) {

            av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");

            continue;

        }

        if (!strcmp(type, "UTF-8")) {

            if (chapter_id == 0 && !strcmp(name, "Disposition")) {

                set_disposition_bits(s, str_value, stream_id_plus1 - 1);

                continue;

            }

            if (metadata && av_strcasecmp(name, "Uses") &&

                av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces")) {

                *event_flags |= metadata_flag;

                av_dict_set(metadata, name, str_value, 0);

            }

        }

    }

    if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {

        av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");

        return AVERROR_INVALIDDATA;

    }

    return 0;

}