static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)

{

    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);

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

    int32_t len;

    uint8_t command;

    uint8_t *outbuf;

    int rc;

    command = buf[0];

    outbuf = (uint8_t *)r->iov.iov_base;

    DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", req->lun, req->tag, buf[0]);

#ifdef DEBUG_SCSI

    {

        int i;

        for (i = 1; i < r->req.cmd.len; i++) {

            printf(" 0x%02x", buf[i]);

        }

        printf("\n");

    }

#endif

    if (req->lun) {

        /* Only LUN 0 supported.  */

        DPRINTF("Unimplemented LUN %d\n", req->lun);

        if (command != REQUEST_SENSE && command != INQUIRY) {

            scsi_check_condition(r, SENSE_CODE(LUN_NOT_SUPPORTED));

            return 0;

        }

    }

    switch (command) {

    case TEST_UNIT_READY:

    case REQUEST_SENSE:

    case INQUIRY:

    case MODE_SENSE:

    case MODE_SENSE_10:

    case RESERVE:

    case RESERVE_10:

    case RELEASE:

    case RELEASE_10:

    case START_STOP:

    case ALLOW_MEDIUM_REMOVAL:

    case READ_CAPACITY_10:

    case SYNCHRONIZE_CACHE:

    case READ_TOC:

    case GET_CONFIGURATION:

    case SERVICE_ACTION_IN:

    case REPORT_LUNS:

    case VERIFY_10:

        rc = scsi_disk_emulate_command(r, outbuf);

        if (rc < 0) {

            return 0;

        }

        r->iov.iov_len = rc;

        break;

    case READ_6:

    case READ_10:

    case READ_12:

    case READ_16:

        len = r->req.cmd.xfer / s->qdev.blocksize;

        DPRINTF("Read (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len);

        if (r->req.cmd.lba > s->max_lba)

            goto illegal_lba;

        r->sector = r->req.cmd.lba * s->cluster_size;

        r->sector_count = len * s->cluster_size;

        break;

    case WRITE_6:

    case WRITE_10:

    case WRITE_12:

    case WRITE_16:

    case WRITE_VERIFY_10:

    case WRITE_VERIFY_12:

    case WRITE_VERIFY_16:

        len = r->req.cmd.xfer / s->qdev.blocksize;

        DPRINTF("Write %s(sector %" PRId64 ", count %d)\n",

                (command & 0xe) == 0xe ? "And Verify " : "",

                r->req.cmd.lba, len);

        if (r->req.cmd.lba > s->max_lba)

            goto illegal_lba;

        r->sector = r->req.cmd.lba * s->cluster_size;

        r->sector_count = len * s->cluster_size;

        break;

    case MODE_SELECT:

        DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);

        /* We don't support mode parameter changes.

           Allow the mode parameter header + block descriptors only. */

        if (r->req.cmd.xfer > 12) {

            goto fail;

        }

        break;

    case MODE_SELECT_10:

        DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);

        /* We don't support mode parameter changes.

           Allow the mode parameter header + block descriptors only. */

        if (r->req.cmd.xfer > 16) {

            goto fail;

        }

        break;

    case SEEK_6:

    case SEEK_10:

        DPRINTF("Seek(%d) (sector %" PRId64 ")\n", command == SEEK_6 ? 6 : 10,

                r->req.cmd.lba);

        if (r->req.cmd.lba > s->max_lba) {

            goto illegal_lba;

        }

        break;

    case WRITE_SAME_16:

        len = r->req.cmd.xfer / s->qdev.blocksize;

        DPRINTF("WRITE SAME(16) (sector %" PRId64 ", count %d)\n",

                r->req.cmd.lba, len);

        if (r->req.cmd.lba > s->max_lba) {

            goto illegal_lba;

        }

        /*

         * We only support WRITE SAME with the unmap bit set for now.

         */

        if (!(buf[1] & 0x8)) {

            goto fail;

        }

        rc = bdrv_discard(s->bs, r->req.cmd.lba * s->cluster_size,

                          len * s->cluster_size);

        if (rc < 0) {

            /* XXX: better error code ?*/

            goto fail;

        }

        break;

    default:

        DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);

        scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));

        return 0;

    fail:

        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));

        return 0;

    illegal_lba:

        scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));

        return 0;

    }

    if (r->sector_count == 0 && r->iov.iov_len == 0) {

        scsi_req_complete(&r->req, GOOD);

    }

    len = r->sector_count * 512 + r->iov.iov_len;

    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {

        return -len;

    } else {

        if (!r->sector_count)

            r->sector_count = -1;

        return len;

    }

}


static void test_qemu_strtoul_octal(void)

{

    const char *str = "0123";

    char f = 'X';

    const char *endptr = &f;

    unsigned long res = 999;

    int err;

    err = qemu_strtoul(str, &endptr, 8, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 0123);

    g_assert(endptr == str + strlen(str));

    res = 999;

    endptr = &f;

    err = qemu_strtoul(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 0123);

    g_assert(endptr == str + strlen(str));

}


i2c_bus *i2c_init_bus(DeviceState *parent, const char *name)

{

    i2c_bus *bus;

    bus = FROM_QBUS(i2c_bus, qbus_create(BUS_TYPE_I2C, sizeof(i2c_bus),

                                         parent, name));

    register_savevm("i2c_bus", -1, 1, i2c_bus_save, i2c_bus_load, bus);

    return bus;

}


int msix_uninit(PCIDevice *dev, MemoryRegion *bar)

{

    if (!(dev->cap_present & QEMU_PCI_CAP_MSIX))

        return 0;

    pci_del_capability(dev, PCI_CAP_ID_MSIX, MSIX_CAP_LENGTH);

    dev->msix_cap = 0;

    msix_free_irq_entries(dev);

    dev->msix_entries_nr = 0;

    memory_region_del_subregion(bar, &dev->msix_mmio);

    memory_region_destroy(&dev->msix_mmio);

    g_free(dev->msix_table_page);

    dev->msix_table_page = NULL;

    g_free(dev->msix_entry_used);

    dev->msix_entry_used = NULL;

    dev->cap_present &= ~QEMU_PCI_CAP_MSIX;

    return 0;

}


static int rtmp_open(URLContext *s, const char *uri, int flags)

{

    RTMPContext *rt = s->priv_data;

    char proto[8], hostname[256], path[1024], auth[100], *fname;

    char *old_app;

    uint8_t buf[2048];

    int port;

    AVDictionary *opts = NULL;

    int ret;

    if (rt->listen_timeout > 0)

        rt->listen = 1;

    rt->is_input = !(flags & AVIO_FLAG_WRITE);

    av_url_split(proto, sizeof(proto), auth, sizeof(auth),

                 hostname, sizeof(hostname), &port,

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

    if (auth[0]) {

        char *ptr = strchr(auth, ':');

        if (ptr) {

            *ptr = '\0';

            av_strlcpy(rt->username, auth, sizeof(rt->username));

            av_strlcpy(rt->password, ptr + 1, sizeof(rt->password));

        }

    }

    if (rt->listen && strcmp(proto, "rtmp")) {

        av_log(s, AV_LOG_ERROR, "rtmp_listen not available for %s\n",

               proto);

        return AVERROR(EINVAL);

    }

    if (!strcmp(proto, "rtmpt") || !strcmp(proto, "rtmpts")) {

        if (!strcmp(proto, "rtmpts"))

            av_dict_set(&opts, "ffrtmphttp_tls", "1", 1);

        /* open the http tunneling connection */

        ff_url_join(buf, sizeof(buf), "ffrtmphttp", NULL, hostname, port, NULL);

    } else if (!strcmp(proto, "rtmps")) {

        /* open the tls connection */

        if (port < 0)

            port = RTMPS_DEFAULT_PORT;

        ff_url_join(buf, sizeof(buf), "tls", NULL, hostname, port, NULL);

    } else if (!strcmp(proto, "rtmpe") || (!strcmp(proto, "rtmpte"))) {

        if (!strcmp(proto, "rtmpte"))

            av_dict_set(&opts, "ffrtmpcrypt_tunneling", "1", 1);

        /* open the encrypted connection */

        ff_url_join(buf, sizeof(buf), "ffrtmpcrypt", NULL, hostname, port, NULL);

        rt->encrypted = 1;

    } else {

        /* open the tcp connection */

        if (port < 0)

            port = RTMP_DEFAULT_PORT;

        if (rt->listen)

            ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port,

                        "?listen&listen_timeout=%d",

                        rt->listen_timeout * 1000);

        else

            ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);

    }

reconnect:

    if ((ret = ffurl_open(&rt->stream, buf, AVIO_FLAG_READ_WRITE,

                          &s->interrupt_callback, &opts)) < 0) {

        av_log(s , AV_LOG_ERROR, "Cannot open connection %s\n", buf);

        goto fail;

    }

    if (rt->swfverify) {

        if ((ret = rtmp_calc_swfhash(s)) < 0)

            goto fail;

    }

    rt->state = STATE_START;

    if (!rt->listen && (ret = rtmp_handshake(s, rt)) < 0)

        goto fail;

    if (rt->listen && (ret = rtmp_server_handshake(s, rt)) < 0)

        goto fail;

    rt->out_chunk_size = 128;

    rt->in_chunk_size  = 128; // Probably overwritten later

    rt->state = STATE_HANDSHAKED;

    // Keep the application name when it has been defined by the user.

    old_app = rt->app;

    rt->app = av_malloc(APP_MAX_LENGTH);

    if (!rt->app) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    //extract "app" part from path

    if (!strncmp(path, "/ondemand/", 10)) {

        fname = path + 10;

        memcpy(rt->app, "ondemand", 9);

    } else {

        char *next = *path ? path + 1 : path;

        char *p = strchr(next, '/');

        if (!p) {

            fname = next;

            rt->app[0] = '\0';

        } else {

            // make sure we do not mismatch a playpath for an application instance

            char *c = strchr(p + 1, ':');

            fname = strchr(p + 1, '/');

            if (!fname || (c && c < fname)) {

                fname = p + 1;

                av_strlcpy(rt->app, path + 1, p - path);

            } else {

                fname++;

                av_strlcpy(rt->app, path + 1, fname - path - 1);

            }

        }

    }

    if (old_app) {

        // The name of application has been defined by the user, override it.

        av_free(rt->app);

        rt->app = old_app;

    }

    if (!rt->playpath) {

        int len = strlen(fname);

        rt->playpath = av_malloc(PLAYPATH_MAX_LENGTH);

        if (!rt->playpath) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        if (!strchr(fname, ':') && len >= 4 &&

            (!strcmp(fname + len - 4, ".f4v") ||

             !strcmp(fname + len - 4, ".mp4"))) {

            memcpy(rt->playpath, "mp4:", 5);

        } else if (len >= 4 && !strcmp(fname + len - 4, ".flv")) {

            fname[len - 4] = '\0';

        } else {

            rt->playpath[0] = 0;

        }

        av_strlcat(rt->playpath, fname, PLAYPATH_MAX_LENGTH);

    }

    if (!rt->tcurl) {

        rt->tcurl = av_malloc(TCURL_MAX_LENGTH);

        if (!rt->tcurl) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        ff_url_join(rt->tcurl, TCURL_MAX_LENGTH, proto, NULL, hostname,

                    port, "/%s", rt->app);

    }

    if (!rt->flashver) {

        rt->flashver = av_malloc(FLASHVER_MAX_LENGTH);

        if (!rt->flashver) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        if (rt->is_input) {

            snprintf(rt->flashver, FLASHVER_MAX_LENGTH, "%s %d,%d,%d,%d",

                    RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1, RTMP_CLIENT_VER2,

                    RTMP_CLIENT_VER3, RTMP_CLIENT_VER4);

        } else {

            snprintf(rt->flashver, FLASHVER_MAX_LENGTH,

                    "FMLE/3.0 (compatible; %s)", LIBAVFORMAT_IDENT);

        }

    }

    rt->client_report_size = 1048576;

    rt->bytes_read = 0;

    rt->last_bytes_read = 0;

    rt->server_bw = 2500000;

    av_log(s, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n",

           proto, path, rt->app, rt->playpath);

    if (!rt->listen) {

        if ((ret = gen_connect(s, rt)) < 0)

            goto fail;

    } else {

        if (read_connect(s, s->priv_data) < 0)

            goto fail;

        rt->is_input = 1;

    }

    do {

        ret = get_packet(s, 1);

    } while (ret == EAGAIN);

    if (ret < 0)

        goto fail;

    if (rt->do_reconnect) {

        ffurl_close(rt->stream);

        rt->stream       = NULL;

        rt->do_reconnect = 0;

        rt->nb_invokes   = 0;

        memset(rt->prev_pkt, 0, sizeof(rt->prev_pkt));

        free_tracked_methods(rt);

        goto reconnect;

    }

    if (rt->is_input) {

        // generate FLV header for demuxer

        rt->flv_size = 13;

        rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);

        rt->flv_off  = 0;

        memcpy(rt->flv_data, "FLV\1\5\0\0\0\011\0\0\0\0", rt->flv_size);

    } else {

        rt->flv_size = 0;

        rt->flv_data = NULL;

        rt->flv_off  = 0;

        rt->skip_bytes = 13;

    }

    s->max_packet_size = rt->stream->max_packet_size;

    s->is_streamed     = 1;

    return 0;

fail:

    av_dict_free(&opts);

    rtmp_close(s);

    return ret;

}


static always_inline void idct(uint8_t *dst, int stride, int16_t *input, int type)

{

    int16_t *ip = input;

    uint8_t *cm = cropTbl + MAX_NEG_CROP;

    int A_, B_, C_, D_, _Ad, _Bd, _Cd, _Dd, E_, F_, G_, H_;

    int _Ed, _Gd, _Add, _Bdd, _Fd, _Hd;

    int i;

    /* Inverse DCT on the rows now */

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

        /* Check for non-zero values */

        if ( ip[0] | ip[1] | ip[2] | ip[3] | ip[4] | ip[5] | ip[6] | ip[7] ) {

            A_ = M(xC1S7, ip[1]) + M(xC7S1, ip[7]);

            B_ = M(xC7S1, ip[1]) - M(xC1S7, ip[7]);

            C_ = M(xC3S5, ip[3]) + M(xC5S3, ip[5]);

            D_ = M(xC3S5, ip[5]) - M(xC5S3, ip[3]);

            _Ad = M(xC4S4, (A_ - C_));

            _Bd = M(xC4S4, (B_ - D_));

            _Cd = A_ + C_;

            _Dd = B_ + D_;

            E_ = M(xC4S4, (ip[0] + ip[4]));

            F_ = M(xC4S4, (ip[0] - ip[4]));

            G_ = M(xC2S6, ip[2]) + M(xC6S2, ip[6]);

            H_ = M(xC6S2, ip[2]) - M(xC2S6, ip[6]);

            _Ed = E_ - G_;

            _Gd = E_ + G_;

            _Add = F_ + _Ad;

            _Bdd = _Bd - H_;

            _Fd = F_ - _Ad;

            _Hd = _Bd + H_;

            /*  Final sequence of operations over-write original inputs. */

            ip[0] = _Gd + _Cd ;

            ip[7] = _Gd - _Cd ;

            ip[1] = _Add + _Hd;

            ip[2] = _Add - _Hd;

            ip[3] = _Ed + _Dd ;

            ip[4] = _Ed - _Dd ;

            ip[5] = _Fd + _Bdd;

            ip[6] = _Fd - _Bdd;

        }

        ip += 8;            /* next row */

    }

    ip = input;

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

        /* Check for non-zero values (bitwise or faster than ||) */

        if ( ip[1 * 8] | ip[2 * 8] | ip[3 * 8] |

             ip[4 * 8] | ip[5 * 8] | ip[6 * 8] | ip[7 * 8] ) {

            A_ = M(xC1S7, ip[1*8]) + M(xC7S1, ip[7*8]);

            B_ = M(xC7S1, ip[1*8]) - M(xC1S7, ip[7*8]);

            C_ = M(xC3S5, ip[3*8]) + M(xC5S3, ip[5*8]);

            D_ = M(xC3S5, ip[5*8]) - M(xC5S3, ip[3*8]);

            _Ad = M(xC4S4, (A_ - C_));

            _Bd = M(xC4S4, (B_ - D_));

            _Cd = A_ + C_;

            _Dd = B_ + D_;

            E_ = M(xC4S4, (ip[0*8] + ip[4*8]));

            F_ = M(xC4S4, (ip[0*8] - ip[4*8]));

            G_ = M(xC2S6, ip[2*8]) + M(xC6S2, ip[6*8]);

            H_ = M(xC6S2, ip[2*8]) - M(xC2S6, ip[6*8]);

            _Ed = E_ - G_;

            _Gd = E_ + G_;

            _Add = F_ + _Ad;

            _Bdd = _Bd - H_;

            _Fd = F_ - _Ad;

            _Hd = _Bd + H_;

            if(type==1){  //HACK

                _Gd += 16*128;

                _Add+= 16*128;

                _Ed += 16*128;

                _Fd += 16*128;

            }

            _Gd += IdctAdjustBeforeShift;

            _Add += IdctAdjustBeforeShift;

            _Ed += IdctAdjustBeforeShift;

            _Fd += IdctAdjustBeforeShift;

            /* Final sequence of operations over-write original inputs. */

            if(type==0){

                ip[0*8] = (_Gd + _Cd )  >> 4;

                ip[7*8] = (_Gd - _Cd )  >> 4;

                ip[1*8] = (_Add + _Hd ) >> 4;

                ip[2*8] = (_Add - _Hd ) >> 4;

                ip[3*8] = (_Ed + _Dd )  >> 4;

                ip[4*8] = (_Ed - _Dd )  >> 4;

                ip[5*8] = (_Fd + _Bdd ) >> 4;

                ip[6*8] = (_Fd - _Bdd ) >> 4;

            }else if(type==1){

                dst[0*stride] = cm[(_Gd + _Cd )  >> 4];

                dst[7*stride] = cm[(_Gd - _Cd )  >> 4];

                dst[1*stride] = cm[(_Add + _Hd ) >> 4];

                dst[2*stride] = cm[(_Add - _Hd ) >> 4];

                dst[3*stride] = cm[(_Ed + _Dd )  >> 4];

                dst[4*stride] = cm[(_Ed - _Dd )  >> 4];

                dst[5*stride] = cm[(_Fd + _Bdd ) >> 4];

                dst[6*stride] = cm[(_Fd - _Bdd ) >> 4];

            }else{

                dst[0*stride] = cm[dst[0*stride] + ((_Gd + _Cd )  >> 4)];

                dst[7*stride] = cm[dst[7*stride] + ((_Gd - _Cd )  >> 4)];

                dst[1*stride] = cm[dst[1*stride] + ((_Add + _Hd ) >> 4)];

                dst[2*stride] = cm[dst[2*stride] + ((_Add - _Hd ) >> 4)];

                dst[3*stride] = cm[dst[3*stride] + ((_Ed + _Dd )  >> 4)];

                dst[4*stride] = cm[dst[4*stride] + ((_Ed - _Dd )  >> 4)];

                dst[5*stride] = cm[dst[5*stride] + ((_Fd + _Bdd ) >> 4)];

                dst[6*stride] = cm[dst[6*stride] + ((_Fd - _Bdd ) >> 4)];

            }

        } else {

            if(type==0){

                ip[0*8] =

                ip[1*8] =

                ip[2*8] =

                ip[3*8] =

                ip[4*8] =

                ip[5*8] =

                ip[6*8] =

                ip[7*8] = ((xC4S4 * ip[0*8] + (IdctAdjustBeforeShift<<16))>>20);

            }else if(type==1){

                dst[0*stride]=

                dst[1*stride]=

                dst[2*stride]=

                dst[3*stride]=

                dst[4*stride]=

                dst[5*stride]=

                dst[6*stride]=

                dst[7*stride]= 128 + ((xC4S4 * ip[0*8] + (IdctAdjustBeforeShift<<16))>>20);

            }else{

                if(ip[0*8]){

                    int v= ((xC4S4 * ip[0*8] + (IdctAdjustBeforeShift<<16))>>20);

                    dst[0*stride] = cm[dst[0*stride] + v];

                    dst[1*stride] = cm[dst[1*stride] + v];

                    dst[2*stride] = cm[dst[2*stride] + v];

                    dst[3*stride] = cm[dst[3*stride] + v];

                    dst[4*stride] = cm[dst[4*stride] + v];

                    dst[5*stride] = cm[dst[5*stride] + v];

                    dst[6*stride] = cm[dst[6*stride] + v];

                    dst[7*stride] = cm[dst[7*stride] + v];

                }

            }

        }

        ip++;            /* next column */

        dst++;

    }

}


static int seek_test(const char *input_filename, const char *start, const char *end)

{

    AVCodec *codec = NULL;

    AVCodecContext *ctx= NULL;

    AVCodecParameters *origin_par = NULL;

    AVFrame *fr = NULL;

    AVFormatContext *fmt_ctx = NULL;

    int video_stream;

    int result;

    int i, j;

    long int start_ts, end_ts;

    size_of_array = 0;

    number_of_elements = 0;

    crc_array = pts_array = NULL;

    result = avformat_open_input(&fmt_ctx, input_filename, NULL, NULL);

    if (result < 0) {

        av_log(NULL, AV_LOG_ERROR, "Can't open file\n");

        return result;

    }

    result = avformat_find_stream_info(fmt_ctx, NULL);

    if (result < 0) {

        av_log(NULL, AV_LOG_ERROR, "Can't get stream info\n");

        return result;

    }

    start_ts = read_seek_range(start);

    end_ts = read_seek_range(end);

    if ((start_ts < 0) || (end_ts < 0))

        return -1;

    //TODO: add ability to work with audio format

    video_stream = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);

    if (video_stream < 0) {

      av_log(NULL, AV_LOG_ERROR, "Can't find video stream in input file\n");

      return -1;

    }

    origin_par = fmt_ctx->streams[video_stream]->codecpar;

    codec = avcodec_find_decoder(origin_par->codec_id);

    if (!codec) {

        av_log(NULL, AV_LOG_ERROR, "Can't find decoder\n");

        return -1;

    }

    ctx = avcodec_alloc_context3(codec);

    if (!ctx) {

        av_log(NULL, AV_LOG_ERROR, "Can't allocate decoder context\n");

        return AVERROR(ENOMEM);

    }

    result = avcodec_parameters_to_context(ctx, origin_par);

    if (result) {

        av_log(NULL, AV_LOG_ERROR, "Can't copy decoder context\n");

        return result;

    }

    result = avcodec_open2(ctx, codec, NULL);

    if (result < 0) {

        av_log(ctx, AV_LOG_ERROR, "Can't open decoder\n");

        return result;

    }

    fr = av_frame_alloc();

    if (!fr) {

        av_log(NULL, AV_LOG_ERROR, "Can't allocate frame\n");

        return AVERROR(ENOMEM);

    }

    result = compute_crc_of_packets(fmt_ctx, video_stream, ctx, fr, 0, 0, 1);

    if (result != 0)

        return -1;

    for (i = start_ts; i < end_ts; i += 100) {

        for (j = i + 100; j < end_ts; j += 100)

        result = compute_crc_of_packets(fmt_ctx, video_stream, ctx, fr, i, j, 0);

        if (result != 0)

            return -1;

    }

    av_freep(&crc_array);

    av_freep(&pts_array);

    av_frame_free(&fr);

    avcodec_close(ctx);

    avformat_close_input(&fmt_ctx);

    avcodec_free_context(&ctx);

    return 0;

}


static int decode_gop_header(IVI45DecContext *ctx, AVCodecContext *avctx)

{

    int             result, i, p, tile_size, pic_size_indx, mb_size, blk_size;

    int             quant_mat, blk_size_changed = 0;

    IVIBandDesc     *band, *band1, *band2;

    IVIPicConfig    pic_conf;

    ctx->gop_flags = get_bits(&ctx->gb, 8);

    ctx->gop_hdr_size = (ctx->gop_flags & 1) ? get_bits(&ctx->gb, 16) : 0;

    if (ctx->gop_flags & IVI5_IS_PROTECTED)

        ctx->lock_word = get_bits_long(&ctx->gb, 32);

    tile_size = (ctx->gop_flags & 0x40) ? 64 << get_bits(&ctx->gb, 2) : 0;

    if (tile_size > 256) {

        av_log(avctx, AV_LOG_ERROR, "Invalid tile size: %d\n", tile_size);

        return -1;

    }

    /* decode number of wavelet bands */

    /* num_levels * 3 + 1 */

    pic_conf.luma_bands   = get_bits(&ctx->gb, 2) * 3 + 1;

    pic_conf.chroma_bands = get_bits1(&ctx->gb)   * 3 + 1;

    ctx->is_scalable = pic_conf.luma_bands != 1 || pic_conf.chroma_bands != 1;

    if (ctx->is_scalable && (pic_conf.luma_bands != 4 || pic_conf.chroma_bands != 1)) {

        av_log(avctx, AV_LOG_ERROR, "Scalability: unsupported subdivision! Luma bands: %d, chroma bands: %d\n",

               pic_conf.luma_bands, pic_conf.chroma_bands);

        return -1;

    }

    pic_size_indx = get_bits(&ctx->gb, 4);

    if (pic_size_indx == IVI5_PIC_SIZE_ESC) {

        pic_conf.pic_height = get_bits(&ctx->gb, 13);

        pic_conf.pic_width  = get_bits(&ctx->gb, 13);

    } else {

        pic_conf.pic_height = ivi5_common_pic_sizes[pic_size_indx * 2 + 1] << 2;

        pic_conf.pic_width  = ivi5_common_pic_sizes[pic_size_indx * 2    ] << 2;

    }

    if (ctx->gop_flags & 2) {

        av_log(avctx, AV_LOG_ERROR, "YV12 picture format not supported!\n");

        return -1;

    }

    pic_conf.chroma_height = (pic_conf.pic_height + 3) >> 2;

    pic_conf.chroma_width  = (pic_conf.pic_width  + 3) >> 2;

    if (!tile_size) {

        pic_conf.tile_height = pic_conf.pic_height;

        pic_conf.tile_width  = pic_conf.pic_width;

    } else {

        pic_conf.tile_height = pic_conf.tile_width = tile_size;

    }

    /* check if picture layout was changed and reallocate buffers */

    if (ivi_pic_config_cmp(&pic_conf, &ctx->pic_conf)) {

        result = ff_ivi_init_planes(ctx->planes, &pic_conf);

        if (result) {

            av_log(avctx, AV_LOG_ERROR, "Couldn't reallocate color planes!\n");

            return -1;

        }

        ctx->pic_conf = pic_conf;

        blk_size_changed = 1; /* force reallocation of the internal structures */

    }

    for (p = 0; p <= 1; p++) {

        for (i = 0; i < (!p ? pic_conf.luma_bands : pic_conf.chroma_bands); i++) {

            band = &ctx->planes[p].bands[i];

            band->is_halfpel = get_bits1(&ctx->gb);

            mb_size  = get_bits1(&ctx->gb);

            blk_size = 8 >> get_bits1(&ctx->gb);

            mb_size  = blk_size << !mb_size;

            blk_size_changed = mb_size != band->mb_size || blk_size != band->blk_size;

            if (blk_size_changed) {

                band->mb_size  = mb_size;

                band->blk_size = blk_size;

            }

            if (get_bits1(&ctx->gb)) {

                av_log(avctx, AV_LOG_ERROR, "Extended transform info encountered!\n");

                return -1;

            }

            /* select transform function and scan pattern according to plane and band number */

            switch ((p << 2) + i) {

            case 0:

                band->inv_transform = ff_ivi_inverse_slant_8x8;

                band->dc_transform  = ff_ivi_dc_slant_2d;

                band->scan          = ff_zigzag_direct;

                break;

            case 1:

                band->inv_transform = ff_ivi_row_slant8;

                band->dc_transform  = ff_ivi_dc_row_slant;

                band->scan          = ff_ivi_vertical_scan_8x8;

                break;

            case 2:

                band->inv_transform = ff_ivi_col_slant8;

                band->dc_transform  = ff_ivi_dc_col_slant;

                band->scan          = ff_ivi_horizontal_scan_8x8;

                break;

            case 3:

                band->inv_transform = ff_ivi_put_pixels_8x8;

                band->dc_transform  = ff_ivi_put_dc_pixel_8x8;

                band->scan          = ff_ivi_horizontal_scan_8x8;

                break;

            case 4:

                band->inv_transform = ff_ivi_inverse_slant_4x4;

                band->dc_transform  = ff_ivi_dc_slant_2d;

                band->scan          = ff_ivi_direct_scan_4x4;

                break;

            }

            band->is_2d_trans = band->inv_transform == ff_ivi_inverse_slant_8x8 ||

                                band->inv_transform == ff_ivi_inverse_slant_4x4;

            /* select dequant matrix according to plane and band number */

            if (!p) {

                quant_mat = (pic_conf.luma_bands > 1) ? i+1 : 0;

            } else {

                quant_mat = 5;

            }

            if (band->blk_size == 8) {

                band->intra_base  = &ivi5_base_quant_8x8_intra[quant_mat][0];

                band->inter_base  = &ivi5_base_quant_8x8_inter[quant_mat][0];

                band->intra_scale = &ivi5_scale_quant_8x8_intra[quant_mat][0];

                band->inter_scale = &ivi5_scale_quant_8x8_inter[quant_mat][0];

            } else {

                band->intra_base  = ivi5_base_quant_4x4_intra;

                band->inter_base  = ivi5_base_quant_4x4_inter;

                band->intra_scale = ivi5_scale_quant_4x4_intra;

                band->inter_scale = ivi5_scale_quant_4x4_inter;

            }

            if (get_bits(&ctx->gb, 2)) {

                av_log(avctx, AV_LOG_ERROR, "End marker missing!\n");

                return -1;

            }

        }

    }

    /* copy chroma parameters into the 2nd chroma plane */

    for (i = 0; i < pic_conf.chroma_bands; i++) {

        band1 = &ctx->planes[1].bands[i];

        band2 = &ctx->planes[2].bands[i];

        band2->width         = band1->width;

        band2->height        = band1->height;

        band2->mb_size       = band1->mb_size;

        band2->blk_size      = band1->blk_size;

        band2->is_halfpel    = band1->is_halfpel;

        band2->intra_base    = band1->intra_base;

        band2->inter_base    = band1->inter_base;

        band2->intra_scale   = band1->intra_scale;

        band2->inter_scale   = band1->inter_scale;

        band2->scan          = band1->scan;

        band2->inv_transform = band1->inv_transform;

        band2->dc_transform  = band1->dc_transform;

        band2->is_2d_trans   = band1->is_2d_trans;

    }

    /* reallocate internal structures if needed */

    if (blk_size_changed) {

        result = ff_ivi_init_tiles(ctx->planes, pic_conf.tile_width,

                                   pic_conf.tile_height);

        if (result) {

            av_log(avctx, AV_LOG_ERROR,

                   "Couldn't reallocate internal structures!\n");

            return -1;

        }

    }

    if (ctx->gop_flags & 8) {

        if (get_bits(&ctx->gb, 3)) {

            av_log(avctx, AV_LOG_ERROR, "Alignment bits are not zero!\n");

            return -1;

        }

        if (get_bits1(&ctx->gb))

            skip_bits_long(&ctx->gb, 24); /* skip transparency fill color */

    }

    align_get_bits(&ctx->gb);

    skip_bits(&ctx->gb, 23); /* FIXME: unknown meaning */

    /* skip GOP extension if any */

    if (get_bits1(&ctx->gb)) {

        do {

            i = get_bits(&ctx->gb, 16);

        } while (i & 0x8000);

    }

    align_get_bits(&ctx->gb);

    return 0;

}


static int execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count){

    MpegEncContext * const s = &h->s;

    int i, j;

    int current_ref_assigned=0;

    Picture *pic;

    if((s->avctx->debug&FF_DEBUG_MMCO) && mmco_count==0)

        av_log(h->s.avctx, AV_LOG_DEBUG, "no mmco here\n");

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

        int structure, frame_num, unref_pic;

        if(s->avctx->debug&FF_DEBUG_MMCO)

            av_log(h->s.avctx, AV_LOG_DEBUG, "mmco:%d %d %d\n", h->mmco[i].opcode, h->mmco[i].short_pic_num, h->mmco[i].long_arg);

        switch(mmco[i].opcode){

        case MMCO_SHORT2UNUSED:

            if(s->avctx->debug&FF_DEBUG_MMCO)

                av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref short %d count %d\n", h->mmco[i].short_pic_num, h->short_ref_count);

            frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);

            pic = find_short(h, frame_num, &j);

            if (pic) {

                if (unreference_pic(h, pic, structure ^ PICT_FRAME))

                    remove_short_at_index(h, j);

            } else if(s->avctx->debug&FF_DEBUG_MMCO)

                av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref short failure\n");

            break;

        case MMCO_SHORT2LONG:

            if (FIELD_PICTURE && mmco[i].long_arg < h->long_ref_count &&

                    h->long_ref[mmco[i].long_arg]->frame_num ==

                                              mmco[i].short_pic_num / 2) {

                /* do nothing, we've already moved this field pair. */

            } else {

                int frame_num = mmco[i].short_pic_num >> FIELD_PICTURE;

                pic= remove_long(h, mmco[i].long_arg);

                if(pic) unreference_pic(h, pic, 0);

                h->long_ref[ mmco[i].long_arg ]= remove_short(h, frame_num);

                if (h->long_ref[ mmco[i].long_arg ]){

                    h->long_ref[ mmco[i].long_arg ]->long_ref=1;

                    h->long_ref_count++;

                }

            }

            break;

        case MMCO_LONG2UNUSED:

            j = pic_num_extract(h, mmco[i].long_arg, &structure);

            pic = h->long_ref[j];

            if (pic) {

                if (unreference_pic(h, pic, structure ^ PICT_FRAME))

                    remove_long_at_index(h, j);

            } else if(s->avctx->debug&FF_DEBUG_MMCO)

                av_log(h->s.avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");

            break;

        case MMCO_LONG:

            unref_pic = 1;

            if (FIELD_PICTURE && !s->first_field) {

                if (h->long_ref[mmco[i].long_arg] == s->current_picture_ptr) {

                    /* Just mark second field as referenced */

                    unref_pic = 0;

                } else if (s->current_picture_ptr->reference) {

                    /* First field in pair is in short term list or

                     * at a different long term index.

                     * This is not allowed; see 7.4.3, notes 2 and 3.

                     * Report the problem and keep the pair where it is,

                     * and mark this field valid.

                     */

                    av_log(h->s.avctx, AV_LOG_ERROR,

                        "illegal long term reference assignment for second "

                        "field in complementary field pair (first field is "

                        "short term or has non-matching long index)\n");

                    unref_pic = 0;

                }

            }

            if (unref_pic) {

                pic= remove_long(h, mmco[i].long_arg);

                if(pic) unreference_pic(h, pic, 0);

                h->long_ref[ mmco[i].long_arg ]= s->current_picture_ptr;

                h->long_ref[ mmco[i].long_arg ]->long_ref=1;

                h->long_ref_count++;

            }

            s->current_picture_ptr->reference |= s->picture_structure;

            current_ref_assigned=1;

            break;

        case MMCO_SET_MAX_LONG:

            assert(mmco[i].long_arg <= 16);

            // just remove the long term which index is greater than new max

            for(j = mmco[i].long_arg; j<16; j++){

                pic = remove_long(h, j);

                if (pic) unreference_pic(h, pic, 0);

            }

            break;

        case MMCO_RESET:

            while(h->short_ref_count){

                pic= remove_short(h, h->short_ref[0]->frame_num);

                if(pic) unreference_pic(h, pic, 0);

            }

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

                pic= remove_long(h, j);

                if(pic) unreference_pic(h, pic, 0);

            }

            s->current_picture_ptr->poc=

            s->current_picture_ptr->field_poc[0]=

            s->current_picture_ptr->field_poc[1]=

            h->poc_lsb=

            h->poc_msb=

            h->frame_num=

            s->current_picture_ptr->frame_num= 0;

            break;

        default: assert(0);

        }

    }

    if (!current_ref_assigned && FIELD_PICTURE &&

            !s->first_field && s->current_picture_ptr->reference) {

        /* Second field of complementary field pair; the first field of

         * which is already referenced. If short referenced, it

         * should be first entry in short_ref. If not, it must exist

         * in long_ref; trying to put it on the short list here is an

         * error in the encoded bit stream (ref: 7.4.3, NOTE 2 and 3).

         */

        if (h->short_ref_count && h->short_ref[0] == s->current_picture_ptr) {

            /* Just mark the second field valid */

            s->current_picture_ptr->reference = PICT_FRAME;

        } else if (s->current_picture_ptr->long_ref) {

            av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term reference "

                                             "assignment for second field "

                                             "in complementary field pair "

                                             "(first field is long term)\n");

        } else {

            /*

             * First field in reference, but not in any sensible place on our

             * reference lists. This shouldn't happen unless reference

             * handling somewhere else is wrong.

             */

            assert(0);

        }

        current_ref_assigned = 1;

    }

    if(!current_ref_assigned){

        pic= remove_short(h, s->current_picture_ptr->frame_num);

        if(pic){

            unreference_pic(h, pic, 0);

            av_log(h->s.avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");

        }

        if(h->short_ref_count)

            memmove(&h->short_ref[1], &h->short_ref[0], h->short_ref_count*sizeof(Picture*));

        h->short_ref[0]= s->current_picture_ptr;

        h->short_ref[0]->long_ref=0;

        h->short_ref_count++;

        s->current_picture_ptr->reference |= s->picture_structure;

    }

    if (h->long_ref_count + h->short_ref_count > h->sps.ref_frame_count){

        /* We have too many reference frames, probably due to corrupted

         * stream. Need to discard one frame. Prevents overrun of the

         * short_ref and long_ref buffers.

         */

        av_log(h->s.avctx, AV_LOG_ERROR,

               "number of reference frames exceeds max (probably "

               "corrupt input), discarding one\n");

        if (h->long_ref_count && !h->short_ref_count) {

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

                if (h->long_ref[i])

                    break;

            assert(i < 16);

            pic = h->long_ref[i];

            remove_long_at_index(h, i);

        } else {

            pic = h->short_ref[h->short_ref_count - 1];

            remove_short_at_index(h, h->short_ref_count - 1);

        }

        unreference_pic(h, pic, 0);

    }

    print_short_term(h);

    print_long_term(h);

    return 0;

}


void qmp_input_visitor_cleanup(QmpInputVisitor *v)

{

    qobject_decref(v->stack[0].obj);

    g_free(v);

}


static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)

{

    VirtIOBlock *s = VIRTIO_BLK(vdev);

    uint32_t features;

    if (s->dataplane && !(status & (VIRTIO_CONFIG_S_DRIVER |

                                    VIRTIO_CONFIG_S_DRIVER_OK))) {

        virtio_blk_data_plane_stop(s->dataplane);

    }

    if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {

        return;

    }

    features = vdev->guest_features;

    /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send

     * cache flushes.  Thus, the "auto writethrough" behavior is never

     * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.

     * Leaving it enabled would break the following sequence:

     *

     *     Guest started with "-drive cache=writethrough"

     *     Guest sets status to 0

     *     Guest sets DRIVER bit in status field

     *     Guest reads host features (WCE=0, CONFIG_WCE=1)

     *     Guest writes guest features (WCE=0, CONFIG_WCE=1)

     *     Guest writes 1 to the WCE configuration field (writeback mode)

     *     Guest sets DRIVER_OK bit in status field

     *

     * s->bs would erroneously be placed in writethrough mode.

     */

    if (!(features & (1 << VIRTIO_BLK_F_CONFIG_WCE))) {

        aio_context_acquire(bdrv_get_aio_context(s->bs));

        bdrv_set_enable_write_cache(s->bs,

                                    !!(features & (1 << VIRTIO_BLK_F_WCE)));

        aio_context_release(bdrv_get_aio_context(s->bs));

    }

}


static int mkv_write_track(AVFormatContext *s, MatroskaMuxContext *mkv,

                           int i, AVIOContext *pb)

{

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

    AVCodecContext *codec = st->codec;

    ebml_master subinfo, track;

    int native_id = 0;

    int qt_id = 0;

    int bit_depth = av_get_bits_per_sample(codec->codec_id);

    int sample_rate = codec->sample_rate;

    int output_sample_rate = 0;

    int j, ret;

    AVDictionaryEntry *tag;

    // ms precision is the de-facto standard timescale for mkv files

    avpriv_set_pts_info(st, 64, 1, 1000);

    if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {

        mkv->have_attachments = 1;

        return 0;

    }

    if (!bit_depth)

        bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;

    if (codec->codec_id == AV_CODEC_ID_AAC)

        get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);

    track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);

    put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER     , i + 1);

    put_ebml_uint (pb, MATROSKA_ID_TRACKUID        , i + 1);

    put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0);    // no lacing (yet)

    if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))

        put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);

    tag = av_dict_get(st->metadata, "language", NULL, 0);

    put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");

    // The default value for TRACKFLAGDEFAULT is 1, so add element

    // if we need to clear it.

    if (!(st->disposition & AV_DISPOSITION_DEFAULT))

        put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));

    if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->initial_padding) {

        mkv->tracks[i].ts_offset = av_rescale_q(codec->initial_padding,

                                                (AVRational){ 1, codec->sample_rate },

                                                st->time_base);

        put_ebml_uint(pb, MATROSKA_ID_CODECDELAY,

                      av_rescale_q(codec->initial_padding,

                                   (AVRational){ 1, codec->sample_rate },

                                   (AVRational){ 1, 1000000000 }));

    }

    // look for a codec ID string specific to mkv to use,

    // if none are found, use AVI codes

    for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {

        if (ff_mkv_codec_tags[j].id == codec->codec_id) {

            put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);

            native_id = 1;

            break;

        }

    }

    if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||

                                    codec->codec_id == AV_CODEC_ID_VP9 ||

                                    codec->codec_id == AV_CODEC_ID_OPUS ||

                                    codec->codec_id == AV_CODEC_ID_VORBIS)) {

        av_log(s, AV_LOG_ERROR,

               "Only VP8 or VP9 video and Vorbis or Opus audio are supported for WebM.\n");

        return AVERROR(EINVAL);

    }

    switch (codec->codec_type) {

    case AVMEDIA_TYPE_VIDEO:

        put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);

        if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0)

            put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9 / av_q2d(st->avg_frame_rate));

        if (!native_id &&

            ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&

            (!ff_codec_get_tag(ff_codec_bmp_tags,   codec->codec_id) ||

             codec->codec_id == AV_CODEC_ID_SVQ1 ||

             codec->codec_id == AV_CODEC_ID_SVQ3 ||

             codec->codec_id == AV_CODEC_ID_CINEPAK))

            qt_id = 1;

        if (qt_id)

            put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");

        else if (!native_id) {

            // if there is no mkv-specific codec ID, use VFW mode

            put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");

            mkv->tracks[i].write_dts = 1;

        }

        subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);

        // XXX: interlace flag?

        put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);

        put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);

        // check both side data and metadata for stereo information,

        // write the result to the bitstream if any is found

        ret = mkv_write_stereo_mode(s, pb, st, mkv->mode);

        if (ret < 0)

            return ret;

        end_ebml_master(pb, subinfo);

        break;

    case AVMEDIA_TYPE_AUDIO:

        put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);

        if (!native_id)

            // no mkv-specific ID, use ACM mode

            put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");

        subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);

        put_ebml_uint  (pb, MATROSKA_ID_AUDIOCHANNELS    , codec->channels);

        put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);

        if (output_sample_rate)

            put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);

        if (bit_depth)

            put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);

        end_ebml_master(pb, subinfo);

        break;

    case AVMEDIA_TYPE_SUBTITLE:

        put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);

        if (!native_id) {

            av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);

            return AVERROR(ENOSYS);

        }

        break;

    default:

        av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");

        break;

    }

    ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);

    if (ret < 0)

        return ret;

    end_ebml_master(pb, track);

    return 0;

}


static int read_frame_data(ALSDecContext *ctx, unsigned int ra_frame)

{

    ALSSpecificConfig *sconf = &ctx->sconf;

    AVCodecContext *avctx    = ctx->avctx;

    GetBitContext *gb = &ctx->gb;

    unsigned int div_blocks[32];                ///< block sizes.

    unsigned int c;

    unsigned int js_blocks[2];

    uint32_t bs_info = 0;

    // skip the size of the ra unit if present in the frame

    if (sconf->ra_flag == RA_FLAG_FRAMES && ra_frame)

        skip_bits_long(gb, 32);

    if (sconf->mc_coding && sconf->joint_stereo) {

        ctx->js_switch = get_bits1(gb);

        align_get_bits(gb);

    }

    if (!sconf->mc_coding || ctx->js_switch) {

        int independent_bs = !sconf->joint_stereo;

        for (c = 0; c < avctx->channels; c++) {

            js_blocks[0] = 0;

            js_blocks[1] = 0;

            get_block_sizes(ctx, div_blocks, &bs_info);

            // if joint_stereo and block_switching is set, independent decoding

            // is signaled via the first bit of bs_info

            if (sconf->joint_stereo && sconf->block_switching)

                if (bs_info >> 31)

                    independent_bs = 2;

            // if this is the last channel, it has to be decoded independently

            if (c == avctx->channels - 1)

                independent_bs = 1;

            if (independent_bs) {

                if (decode_blocks_ind(ctx, ra_frame, c, div_blocks, js_blocks))

                    return -1;

                independent_bs--;

            } else {

                if (decode_blocks(ctx, ra_frame, c, div_blocks, js_blocks))

                    return -1;

                c++;

            }

            // store carryover raw samples

            memmove(ctx->raw_samples[c] - sconf->max_order,

                    ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,

                    sizeof(*ctx->raw_samples[c]) * sconf->max_order);

        }

    } else { // multi-channel coding

        ALSBlockData   bd;

        int            b;

        int            *reverted_channels = ctx->reverted_channels;

        unsigned int   offset             = 0;

        for (c = 0; c < avctx->channels; c++)

            if (ctx->chan_data[c] < ctx->chan_data_buffer) {

                av_log(ctx->avctx, AV_LOG_ERROR, "Invalid channel data!\n");

                return -1;

            }

        memset(&bd,               0, sizeof(ALSBlockData));

        memset(reverted_channels, 0, sizeof(*reverted_channels) * avctx->channels);

        bd.ra_block         = ra_frame;

        bd.prev_raw_samples = ctx->prev_raw_samples;

        get_block_sizes(ctx, div_blocks, &bs_info);

        for (b = 0; b < ctx->num_blocks; b++) {

            bd.block_length = div_blocks[b];

            for (c = 0; c < avctx->channels; c++) {

                bd.const_block = ctx->const_block + c;

                bd.shift_lsbs  = ctx->shift_lsbs + c;

                bd.opt_order   = ctx->opt_order + c;

                bd.store_prev_samples = ctx->store_prev_samples + c;

                bd.use_ltp     = ctx->use_ltp + c;

                bd.ltp_lag     = ctx->ltp_lag + c;

                bd.ltp_gain    = ctx->ltp_gain[c];

                bd.lpc_cof     = ctx->lpc_cof[c];

                bd.quant_cof   = ctx->quant_cof[c];

                bd.raw_samples = ctx->raw_samples[c] + offset;

                bd.raw_other   = NULL;

                read_block(ctx, &bd);

                if (read_channel_data(ctx, ctx->chan_data[c], c))

                    return -1;

            }

            for (c = 0; c < avctx->channels; c++)

                if (revert_channel_correlation(ctx, &bd, ctx->chan_data,

                                               reverted_channels, offset, c))

                    return -1;

            for (c = 0; c < avctx->channels; c++) {

                bd.const_block = ctx->const_block + c;

                bd.shift_lsbs  = ctx->shift_lsbs + c;

                bd.opt_order   = ctx->opt_order + c;

                bd.store_prev_samples = ctx->store_prev_samples + c;

                bd.use_ltp     = ctx->use_ltp + c;

                bd.ltp_lag     = ctx->ltp_lag + c;

                bd.ltp_gain    = ctx->ltp_gain[c];

                bd.lpc_cof     = ctx->lpc_cof[c];

                bd.quant_cof   = ctx->quant_cof[c];

                bd.raw_samples = ctx->raw_samples[c] + offset;

                decode_block(ctx, &bd);

            }

            memset(reverted_channels, 0, avctx->channels * sizeof(*reverted_channels));

            offset      += div_blocks[b];

            bd.ra_block  = 0;

        }

        // store carryover raw samples

        for (c = 0; c < avctx->channels; c++)

            memmove(ctx->raw_samples[c] - sconf->max_order,

                    ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,

                    sizeof(*ctx->raw_samples[c]) * sconf->max_order);

    }

    // TODO: read_diff_float_data

    return 0;

}


static void fw_cfg_bootsplash(FWCfgState *s)

{

    int boot_splash_time = -1;

    const char *boot_splash_filename = NULL;

    char *p;

    char *filename, *file_data;

    gsize file_size;

    int file_type;

    const char *temp;

    /* get user configuration */

    QemuOptsList *plist = qemu_find_opts("boot-opts");

    QemuOpts *opts = QTAILQ_FIRST(&plist->head);

    if (opts != NULL) {

        temp = qemu_opt_get(opts, "splash");

        if (temp != NULL) {

            boot_splash_filename = temp;

        }

        temp = qemu_opt_get(opts, "splash-time");

        if (temp != NULL) {

            p = (char *)temp;

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

        }

    }

    /* insert splash time if user configurated */

    if (boot_splash_time >= 0) {

        /* validate the input */

        if (boot_splash_time > 0xffff) {

            error_report("splash time is big than 65535, force it to 65535.");

            boot_splash_time = 0xffff;

        }

        /* use little endian format */

        qemu_extra_params_fw[0] = (uint8_t)(boot_splash_time & 0xff);

        qemu_extra_params_fw[1] = (uint8_t)((boot_splash_time >> 8) & 0xff);

        fw_cfg_add_file(s, "etc/boot-menu-wait", qemu_extra_params_fw, 2);

    }

    /* insert splash file if user configurated */

    if (boot_splash_filename != NULL) {

        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, boot_splash_filename);

        if (filename == NULL) {

            error_report("failed to find file '%s'.", boot_splash_filename);

            return;

        }

        /* loading file data */

        file_data = read_splashfile(filename, &file_size, &file_type);

        if (file_data == NULL) {

            g_free(filename);

            return;

        }

        if (boot_splash_filedata != NULL) {

            g_free(boot_splash_filedata);

        }

        boot_splash_filedata = (uint8_t *)file_data;

        boot_splash_filedata_size = file_size;

        /* insert data */

        if (file_type == JPG_FILE) {

            fw_cfg_add_file(s, "bootsplash.jpg",

                    boot_splash_filedata, boot_splash_filedata_size);

        } else {

            fw_cfg_add_file(s, "bootsplash.bmp",

                    boot_splash_filedata, boot_splash_filedata_size);

        }

        g_free(filename);

    }

}


int omap_validate_tipb_mpui_addr(struct omap_mpu_state_s *s,

                target_phys_addr_t addr)

{

    return addr >= 0xe1010000 && addr < 0xe1020004;

}


int tap_open(char *ifname, int ifname_size, int *vnet_hdr,

             int vnet_hdr_required, int mq_required, Error **errp)

{

    struct ifreq ifr;

    int fd, ret;

    int len = sizeof(struct virtio_net_hdr);

    unsigned int features;

    TFR(fd = open(PATH_NET_TUN, O_RDWR));

    if (fd < 0) {

        error_setg_errno(errp, errno, "could not open %s", PATH_NET_TUN);

        return -1;

    }

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

    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;

    if (ioctl(fd, TUNGETFEATURES, &features) == -1) {

        error_report("warning: TUNGETFEATURES failed: %s", strerror(errno));

        features = 0;

    }

    if (features & IFF_ONE_QUEUE) {

        ifr.ifr_flags |= IFF_ONE_QUEUE;

    }

    if (*vnet_hdr) {

        if (features & IFF_VNET_HDR) {

            *vnet_hdr = 1;

            ifr.ifr_flags |= IFF_VNET_HDR;

        } else {

            *vnet_hdr = 0;

        }

        if (vnet_hdr_required && !*vnet_hdr) {

            error_setg(errp, "vnet_hdr=1 requested, but no kernel "

                       "support for IFF_VNET_HDR available");

            close(fd);

            return -1;

        }

        /*

         * Make sure vnet header size has the default value: for a persistent

         * tap it might have been modified e.g. by another instance of qemu.

         * Ignore errors since old kernels do not support this ioctl: in this

         * case the header size implicitly has the correct value.

         */

        ioctl(fd, TUNSETVNETHDRSZ, &len);

    }

    if (mq_required) {

        if (!(features & IFF_MULTI_QUEUE)) {

            error_setg(errp, "multiqueue required, but no kernel "

                       "support for IFF_MULTI_QUEUE available");

            close(fd);

            return -1;

        } else {

            ifr.ifr_flags |= IFF_MULTI_QUEUE;

        }

    }

    if (ifname[0] != '\0')

        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);

    else

        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");

    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);

    if (ret != 0) {

        if (ifname[0] != '\0') {

            error_setg_errno(errp, errno, "could not configure %s (%s)",

                             PATH_NET_TUN, ifr.ifr_name);

        } else {

            error_setg_errno(errp, errno, "could not configure %s",

                             PATH_NET_TUN);

        }

        close(fd);

        return -1;

    }

    pstrcpy(ifname, ifname_size, ifr.ifr_name);

    fcntl(fd, F_SETFL, O_NONBLOCK);

    return fd;

}


static int vnc_refresh_server_surface(VncDisplay *vd)

{

    int width = pixman_image_get_width(vd->guest.fb);

    int height = pixman_image_get_height(vd->guest.fb);

    int y;

    uint8_t *guest_row;

    uint8_t *server_row;

    int cmp_bytes;

    VncState *vs;

    int has_dirty = 0;

    pixman_image_t *tmpbuf = NULL;

    struct timeval tv = { 0, 0 };

    if (!vd->non_adaptive) {

        gettimeofday(&tv, NULL);

        has_dirty = vnc_update_stats(vd, &tv);

    }

    /*

     * Walk through the guest dirty map.

     * Check and copy modified bits from guest to server surface.

     * Update server dirty map.

     */

    cmp_bytes = 64;

    if (cmp_bytes > vnc_server_fb_stride(vd)) {

        cmp_bytes = vnc_server_fb_stride(vd);

    }

    if (vd->guest.format != VNC_SERVER_FB_FORMAT) {

        int width = pixman_image_get_width(vd->server);

        tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);

    }

    guest_row = (uint8_t *)pixman_image_get_data(vd->guest.fb);

    server_row = (uint8_t *)pixman_image_get_data(vd->server);

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

        if (!bitmap_empty(vd->guest.dirty[y], VNC_DIRTY_BITS)) {

            int x;

            uint8_t *guest_ptr;

            uint8_t *server_ptr;

            if (vd->guest.format != VNC_SERVER_FB_FORMAT) {

                qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, y);

                guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);

            } else {

                guest_ptr = guest_row;

            }

            server_ptr = server_row;

            for (x = 0; x + 15 < width;

                    x += 16, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {

                if (!test_and_clear_bit((x / 16), vd->guest.dirty[y]))

                    continue;

                if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0)

                    continue;

                memcpy(server_ptr, guest_ptr, cmp_bytes);

                if (!vd->non_adaptive)

                    vnc_rect_updated(vd, x, y, &tv);

                QTAILQ_FOREACH(vs, &vd->clients, next) {

                    set_bit((x / 16), vs->dirty[y]);

                }

                has_dirty++;

            }

        }

        guest_row  += pixman_image_get_stride(vd->guest.fb);

        server_row += pixman_image_get_stride(vd->server);

    }

    qemu_pixman_image_unref(tmpbuf);

    return has_dirty;

}


QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)

{

    QEMUTimer *ts;

    ts = qemu_mallocz(sizeof(QEMUTimer));

    ts->clock = clock;

    ts->cb = cb;

    ts->opaque = opaque;

    return ts;

}


static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)

{

    PCIDevice *s = container_of(pv, PCIDevice, config);

    uint32_t irq_state[PCI_NUM_PINS];

    int i;

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

        irq_state[i] = qemu_get_be32(f);

        if (irq_state[i] != 0x1 && irq_state[i] != 0) {

            fprintf(stderr, "irq state %d: must be 0 or 1.\n",

                    irq_state[i]);

            return -EINVAL;

        }

    }

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

        pci_set_irq_state(s, i, irq_state[i]);

    }

    return 0;

}


static void test_visitor_in_native_list_uint32(TestInputVisitorData *data,

                                               const void *unused)

{

    test_native_list_integer_helper(data, unused,

                                    USER_DEF_NATIVE_LIST_UNION_KIND_U32);

}


av_cold void ff_vp8dsp_init_armv6(VP8DSPContext *dsp)

{

    dsp->vp8_luma_dc_wht    = ff_vp8_luma_dc_wht_armv6;

    dsp->vp8_luma_dc_wht_dc = ff_vp8_luma_dc_wht_dc_armv6;

    dsp->vp8_idct_add       = ff_vp8_idct_add_armv6;

    dsp->vp8_idct_dc_add    = ff_vp8_idct_dc_add_armv6;

    dsp->vp8_idct_dc_add4y  = ff_vp8_idct_dc_add4y_armv6;

    dsp->vp8_idct_dc_add4uv = ff_vp8_idct_dc_add4uv_armv6;

    dsp->vp8_v_loop_filter16y = ff_vp8_v_loop_filter16_armv6;

    dsp->vp8_h_loop_filter16y = ff_vp8_h_loop_filter16_armv6;

    dsp->vp8_v_loop_filter8uv = ff_vp8_v_loop_filter8uv_armv6;

    dsp->vp8_h_loop_filter8uv = ff_vp8_h_loop_filter8uv_armv6;

    dsp->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16_inner_armv6;

    dsp->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16_inner_armv6;

    dsp->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_armv6;

    dsp->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_armv6;

    dsp->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter16_simple_armv6;

    dsp->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter16_simple_armv6;

    dsp->put_vp8_epel_pixels_tab[0][0][0] = ff_put_vp8_pixels16_armv6;

    dsp->put_vp8_epel_pixels_tab[0][0][2] = ff_put_vp8_epel16_h6_armv6;

    dsp->put_vp8_epel_pixels_tab[0][2][0] = ff_put_vp8_epel16_v6_armv6;

    dsp->put_vp8_epel_pixels_tab[0][2][2] = ff_put_vp8_epel16_h6v6_armv6;

    dsp->put_vp8_epel_pixels_tab[1][0][0] = ff_put_vp8_pixels8_armv6;

    dsp->put_vp8_epel_pixels_tab[1][0][1] = ff_put_vp8_epel8_h4_armv6;

    dsp->put_vp8_epel_pixels_tab[1][0][2] = ff_put_vp8_epel8_h6_armv6;

    dsp->put_vp8_epel_pixels_tab[1][1][0] = ff_put_vp8_epel8_v4_armv6;

    dsp->put_vp8_epel_pixels_tab[1][1][1] = ff_put_vp8_epel8_h4v4_armv6;

    dsp->put_vp8_epel_pixels_tab[1][1][2] = ff_put_vp8_epel8_h6v4_armv6;

    dsp->put_vp8_epel_pixels_tab[1][2][0] = ff_put_vp8_epel8_v6_armv6;

    dsp->put_vp8_epel_pixels_tab[1][2][1] = ff_put_vp8_epel8_h4v6_armv6;

    dsp->put_vp8_epel_pixels_tab[1][2][2] = ff_put_vp8_epel8_h6v6_armv6;

    dsp->put_vp8_epel_pixels_tab[2][0][0] = ff_put_vp8_pixels4_armv6;

    dsp->put_vp8_epel_pixels_tab[2][0][1] = ff_put_vp8_epel4_h4_armv6;

    dsp->put_vp8_epel_pixels_tab[2][0][2] = ff_put_vp8_epel4_h6_armv6;

    dsp->put_vp8_epel_pixels_tab[2][1][0] = ff_put_vp8_epel4_v4_armv6;

    dsp->put_vp8_epel_pixels_tab[2][1][1] = ff_put_vp8_epel4_h4v4_armv6;

    dsp->put_vp8_epel_pixels_tab[2][1][2] = ff_put_vp8_epel4_h6v4_armv6;

    dsp->put_vp8_epel_pixels_tab[2][2][0] = ff_put_vp8_epel4_v6_armv6;

    dsp->put_vp8_epel_pixels_tab[2][2][1] = ff_put_vp8_epel4_h4v6_armv6;

    dsp->put_vp8_epel_pixels_tab[2][2][2] = ff_put_vp8_epel4_h6v6_armv6;

    dsp->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_armv6;

    dsp->put_vp8_bilinear_pixels_tab[0][0][1] = ff_put_vp8_bilin16_h_armv6;

    dsp->put_vp8_bilinear_pixels_tab[0][0][2] = ff_put_vp8_bilin16_h_armv6;

    dsp->put_vp8_bilinear_pixels_tab[0][1][0] = ff_put_vp8_bilin16_v_armv6;

    dsp->put_vp8_bilinear_pixels_tab[0][1][1] = ff_put_vp8_bilin16_hv_armv6;

    dsp->put_vp8_bilinear_pixels_tab[0][1][2] = ff_put_vp8_bilin16_hv_armv6;

    dsp->put_vp8_bilinear_pixels_tab[0][2][0] = ff_put_vp8_bilin16_v_armv6;

    dsp->put_vp8_bilinear_pixels_tab[0][2][1] = ff_put_vp8_bilin16_hv_armv6;

    dsp->put_vp8_bilinear_pixels_tab[0][2][2] = ff_put_vp8_bilin16_hv_armv6;

    dsp->put_vp8_bilinear_pixels_tab[1][0][0] = ff_put_vp8_pixels8_armv6;

    dsp->put_vp8_bilinear_pixels_tab[1][0][1] = ff_put_vp8_bilin8_h_armv6;

    dsp->put_vp8_bilinear_pixels_tab[1][0][2] = ff_put_vp8_bilin8_h_armv6;

    dsp->put_vp8_bilinear_pixels_tab[1][1][0] = ff_put_vp8_bilin8_v_armv6;

    dsp->put_vp8_bilinear_pixels_tab[1][1][1] = ff_put_vp8_bilin8_hv_armv6;

    dsp->put_vp8_bilinear_pixels_tab[1][1][2] = ff_put_vp8_bilin8_hv_armv6;

    dsp->put_vp8_bilinear_pixels_tab[1][2][0] = ff_put_vp8_bilin8_v_armv6;

    dsp->put_vp8_bilinear_pixels_tab[1][2][1] = ff_put_vp8_bilin8_hv_armv6;

    dsp->put_vp8_bilinear_pixels_tab[1][2][2] = ff_put_vp8_bilin8_hv_armv6;

    dsp->put_vp8_bilinear_pixels_tab[2][0][0] = ff_put_vp8_pixels4_armv6;

    dsp->put_vp8_bilinear_pixels_tab[2][0][1] = ff_put_vp8_bilin4_h_armv6;

    dsp->put_vp8_bilinear_pixels_tab[2][0][2] = ff_put_vp8_bilin4_h_armv6;

    dsp->put_vp8_bilinear_pixels_tab[2][1][0] = ff_put_vp8_bilin4_v_armv6;

    dsp->put_vp8_bilinear_pixels_tab[2][1][1] = ff_put_vp8_bilin4_hv_armv6;

    dsp->put_vp8_bilinear_pixels_tab[2][1][2] = ff_put_vp8_bilin4_hv_armv6;

    dsp->put_vp8_bilinear_pixels_tab[2][2][0] = ff_put_vp8_bilin4_v_armv6;

    dsp->put_vp8_bilinear_pixels_tab[2][2][1] = ff_put_vp8_bilin4_hv_armv6;

    dsp->put_vp8_bilinear_pixels_tab[2][2][2] = ff_put_vp8_bilin4_hv_armv6;

}


static int nbd_receive_list(QIOChannel *ioc, const char *want, bool *match,

                            Error **errp)

{

    nbd_opt_reply reply;

    uint32_t len;

    uint32_t namelen;

    char name[NBD_MAX_NAME_SIZE + 1];

    int error;

    if (nbd_receive_option_reply(ioc, NBD_OPT_LIST, &reply, errp) < 0) {

        return -1;

    }

    error = nbd_handle_reply_err(ioc, &reply, errp);

    if (error <= 0) {

        /* The server did not support NBD_OPT_LIST, so set *match on

         * the assumption that any name will be accepted.  */

        *match = true;

        return error;

    }

    len = reply.length;

    if (reply.type == NBD_REP_ACK) {

        if (len != 0) {

            error_setg(errp, "length too long for option end");

            nbd_send_opt_abort(ioc);

            return -1;

        }

        return 0;

    } else if (reply.type != NBD_REP_SERVER) {

        error_setg(errp, "Unexpected reply type %" PRIx32 " expected %x",

                   reply.type, NBD_REP_SERVER);

        nbd_send_opt_abort(ioc);

        return -1;

    }

    if (len < sizeof(namelen) || len > NBD_MAX_BUFFER_SIZE) {

        error_setg(errp, "incorrect option length %" PRIu32, len);

        nbd_send_opt_abort(ioc);

        return -1;

    }

    if (read_sync(ioc, &namelen, sizeof(namelen), errp) < 0) {

        error_prepend(errp, "failed to read option name length");

        nbd_send_opt_abort(ioc);

        return -1;

    }

    namelen = be32_to_cpu(namelen);

    len -= sizeof(namelen);

    if (len < namelen) {

        error_setg(errp, "incorrect option name length");

        nbd_send_opt_abort(ioc);

        return -1;

    }

    if (namelen != strlen(want)) {

        if (drop_sync(ioc, len, errp) < 0) {

            error_prepend(errp, "failed to skip export name with wrong length");

            nbd_send_opt_abort(ioc);

            return -1;

        }

        return 1;

    }

    assert(namelen < sizeof(name));

    if (read_sync(ioc, name, namelen, errp) < 0) {

        error_prepend(errp, "failed to read export name");

        nbd_send_opt_abort(ioc);

        return -1;

    }

    name[namelen] = '\0';

    len -= namelen;

    if (drop_sync(ioc, len, errp) < 0) {

        error_prepend(errp, "failed to read export description");

        nbd_send_opt_abort(ioc);

        return -1;

    }

    if (!strcmp(name, want)) {

        *match = true;

    }

    return 1;

}


static inline void cris_alu_alloc_temps(DisasContext *dc, int size, TCGv *t)

{

	if (size == 4) {

		t[0] = cpu_R[dc->op2];

		t[1] = cpu_R[dc->op1];

	} else {

		t[0] = tcg_temp_new(TCG_TYPE_TL);

		t[1] = tcg_temp_new(TCG_TYPE_TL);

	}

}


START_TEST(simple_varargs)

{

    QObject *embedded_obj;

    QObject *obj;

    LiteralQObject decoded = QLIT_QLIST(((LiteralQObject[]){

            QLIT_QINT(1),

            QLIT_QINT(2),

            QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(32),

                        QLIT_QINT(42),

                        {}})),

            {}}));

    embedded_obj = qobject_from_json("[32, 42]");

    fail_unless(embedded_obj != NULL);

    obj = qobject_from_jsonf("[%d, 2, %p]", 1, embedded_obj);

    fail_unless(obj != NULL);

    fail_unless(compare_litqobj_to_qobj(&decoded, obj) == 1);

    qobject_decref(obj);

}


int pci_device_load(PCIDevice *s, QEMUFile *f)

{

    uint8_t config[PCI_CONFIG_SPACE_SIZE];

    uint32_t version_id;

    int i;

    version_id = qemu_get_be32(f);

    if (version_id > 2)

        return -EINVAL;

    qemu_get_buffer(f, config, sizeof config);

    for (i = 0; i < sizeof config; ++i)

        if ((config[i] ^ s->config[i]) & s->cmask[i] & ~s->wmask[i])

            return -EINVAL;

    memcpy(s->config, config, sizeof config);

    pci_update_mappings(s);

    if (version_id >= 2)

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

            s->irq_state[i] = qemu_get_be32(f);

    return 0;

}


static int usbredir_handle_interrupt_data(USBRedirDevice *dev,

                                           USBPacket *p, uint8_t ep)

{

    if (ep & USB_DIR_IN) {

        /* Input interrupt endpoint, buffered packet input */

        struct buf_packet *intp;

        int status, len;

        if (!dev->endpoint[EP2I(ep)].interrupt_started &&

                !dev->endpoint[EP2I(ep)].interrupt_error) {

            struct usb_redir_start_interrupt_receiving_header start_int = {

                .endpoint = ep,

            };

            /* No id, we look at the ep when receiving a status back */

            usbredirparser_send_start_interrupt_receiving(dev->parser, 0,

                                                          &start_int);

            usbredirparser_do_write(dev->parser);

            DPRINTF("interrupt recv started ep %02X\n", ep);

            dev->endpoint[EP2I(ep)].interrupt_started = 1;

            /* We don't really want to drop interrupt packets ever, but

               having some upper limit to how much we buffer is good. */

            dev->endpoint[EP2I(ep)].bufpq_target_size = 1000;

            dev->endpoint[EP2I(ep)].bufpq_dropping_packets = 0;

        }

        intp = QTAILQ_FIRST(&dev->endpoint[EP2I(ep)].bufpq);

        if (intp == NULL) {

            DPRINTF2("interrupt-token-in ep %02X, no intp\n", ep);

            /* Check interrupt_error for stream errors */

            status = dev->endpoint[EP2I(ep)].interrupt_error;

            dev->endpoint[EP2I(ep)].interrupt_error = 0;

            if (status) {

                return usbredir_handle_status(dev, status, 0);

            }

            return USB_RET_NAK;

        }

        DPRINTF("interrupt-token-in ep %02X status %d len %d\n", ep,

                intp->status, intp->len);

        status = intp->status;

        if (status != usb_redir_success) {

            bufp_free(dev, intp, ep);

            return usbredir_handle_status(dev, status, 0);

        }

        len = intp->len;

        if (len > p->iov.size) {

            ERROR("received int data is larger then packet ep %02X\n", ep);

            bufp_free(dev, intp, ep);

            return USB_RET_BABBLE;

        }

        usb_packet_copy(p, intp->data, len);

        bufp_free(dev, intp, ep);

        return len;

    } else {

        /* Output interrupt endpoint, normal async operation */

        AsyncURB *aurb = async_alloc(dev, p);

        struct usb_redir_interrupt_packet_header interrupt_packet;

        uint8_t buf[p->iov.size];

        DPRINTF("interrupt-out ep %02X len %zd id %u\n", ep, p->iov.size,

                aurb->packet_id);

        interrupt_packet.endpoint  = ep;

        interrupt_packet.length    = p->iov.size;

        aurb->interrupt_packet     = interrupt_packet;

        usb_packet_copy(p, buf, p->iov.size);

        usbredir_log_data(dev, "interrupt data out:", buf, p->iov.size);

        usbredirparser_send_interrupt_packet(dev->parser, aurb->packet_id,

                                        &interrupt_packet, buf, p->iov.size);

        usbredirparser_do_write(dev->parser);

        return USB_RET_ASYNC;

    }

}


void x86_cpu_list (FILE *f, int (*cpu_fprintf)(FILE *f, const char *fmt, ...))

{

    unsigned int i;

    for (i = 0; i < ARRAY_SIZE(x86_defs); i++)

        (*cpu_fprintf)(f, "x86 %16s\n", x86_defs[i].name);

}


void qio_dns_resolver_lookup_result(QIODNSResolver *resolver,

                                    QIOTask *task,

                                    size_t *naddrs,

                                    SocketAddress ***addrs)

{

    struct QIODNSResolverLookupData *data =

        qio_task_get_result_pointer(task);

    size_t i;

    *naddrs = 0;

    *addrs = NULL;

    if (!data) {

        return;

    }

    *naddrs = data->naddrs;

    *addrs = g_new0(SocketAddress *, data->naddrs);

    for (i = 0; i < data->naddrs; i++) {

        (*addrs)[i] = QAPI_CLONE(SocketAddress, data->addrs[i]);

    }

}


void virtio_init_iov_from_pdu(V9fsPDU *pdu, struct iovec **piov,

                              unsigned int *pniov, bool is_write)

{

    V9fsState *s = pdu->s;

    V9fsVirtioState *v = container_of(s, V9fsVirtioState, state);

    VirtQueueElement *elem = &v->elems[pdu->idx];

    if (is_write) {

        *piov = elem->out_sg;

        *pniov = elem->out_num;

    } else {

        *piov = elem->in_sg;

        *pniov = elem->in_num;

    }

}


BlockDriverState *bdrv_next_node(BlockDriverState *bs)

{

    if (!bs) {

        return QTAILQ_FIRST(&graph_bdrv_states);

    }

    return QTAILQ_NEXT(bs, node_list);

}


CPUState *ppc4xx_init (const char *cpu_model,

                       clk_setup_t *cpu_clk, clk_setup_t *tb_clk,

                       uint32_t sysclk)

{

    CPUState *env;

    /* init CPUs */

    env = cpu_init(cpu_model);

    if (!env) {

        fprintf(stderr, "Unable to find PowerPC %s CPU definition\n",

                cpu_model);

        exit(1);

    }

    cpu_clk->cb = NULL; /* We don't care about CPU clock frequency changes */

    cpu_clk->opaque = env;

    /* Set time-base frequency to sysclk */

    tb_clk->cb = ppc_emb_timers_init(env, sysclk);

    tb_clk->opaque = env;

    ppc_dcr_init(env, NULL, NULL);

    /* Register qemu callbacks */

    qemu_register_reset((QEMUResetHandler*)&cpu_reset, env);

    return env;

}


void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)

{

    LIST_REMOVE (e, entries);

    qemu_free (e);

}


static void ps2_mouse_event(DeviceState *dev, QemuConsole *src,

                            InputEvent *evt)

{

    static const int bmap[INPUT_BUTTON__MAX] = {

        [INPUT_BUTTON_LEFT]   = MOUSE_EVENT_LBUTTON,

        [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,

        [INPUT_BUTTON_RIGHT]  = MOUSE_EVENT_RBUTTON,

    };

    PS2MouseState *s = (PS2MouseState *)dev;

    InputMoveEvent *move;

    InputBtnEvent *btn;

    /* check if deltas are recorded when disabled */

    if (!(s->mouse_status & MOUSE_STATUS_ENABLED))

        return;

    switch (evt->type) {

    case INPUT_EVENT_KIND_REL:

        move = evt->u.rel;

        if (move->axis == INPUT_AXIS_X) {

            s->mouse_dx += move->value;

        } else if (move->axis == INPUT_AXIS_Y) {

            s->mouse_dy -= move->value;

        }

        break;

    case INPUT_EVENT_KIND_BTN:

        btn = evt->u.btn;

        if (btn->down) {

            s->mouse_buttons |= bmap[btn->button];

            if (btn->button == INPUT_BUTTON_WHEEL_UP) {

                s->mouse_dz--;

            } else if (btn->button == INPUT_BUTTON_WHEEL_DOWN) {

                s->mouse_dz++;

            }

        } else {

            s->mouse_buttons &= ~bmap[btn->button];

        }

        break;

    default:

        /* keep gcc happy */

        break;

    }

}


static void gdb_accept(void *opaque)

{

    GDBState *s;

    struct sockaddr_in sockaddr;

    socklen_t len;

    int val, fd;

    for(;;) {

        len = sizeof(sockaddr);

        fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);

        if (fd < 0 && errno != EINTR) {

            perror("accept");

            return;

        } else if (fd >= 0) {

            break;

        }

    }

    /* set short latency */

    val = 1;

    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));

    s = &gdbserver_state;

    memset (s, 0, sizeof (GDBState));

    s->env = first_cpu; /* XXX: allow to change CPU */

    s->fd = fd;

    gdb_has_xml = 0;

    gdb_syscall_state = s;

    fcntl(fd, F_SETFL, O_NONBLOCK);

}


bool desc_ring_set_size(DescRing *ring, uint32_t size)

{

    int i;

    if (size < 2 || size > 0x10000 || (size & (size - 1))) {

        DPRINTF("ERROR: ring[%d] size (%d) not a power of 2 "

                "or in range [2, 64K]\n", ring->index, size);

        return false;

    }

    for (i = 0; i < ring->size; i++) {

        if (ring->info[i].buf) {

            g_free(ring->info[i].buf);

        }

    }

    ring->size = size;

    ring->head = ring->tail = 0;

    ring->info = g_realloc(ring->info, size * sizeof(DescInfo));

    if (!ring->info) {

        return false;

    }

    memset(ring->info, 0, size * sizeof(DescInfo));

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

        ring->info[i].ring = ring;

    }

    return true;

}


kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )

{

    kern_return_t       kernResult;

    mach_port_t     masterPort;

    CFMutableDictionaryRef  classesToMatch;

    kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );

    if ( KERN_SUCCESS != kernResult ) {

        printf( "IOMasterPort returned %d\n", kernResult );

    }

    classesToMatch = IOServiceMatching( kIOCDMediaClass );

    if ( classesToMatch == NULL ) {

        printf( "IOServiceMatching returned a NULL dictionary.\n" );

    } else {

    CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );

    }

    kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );

    if ( KERN_SUCCESS != kernResult )

    {

        printf( "IOServiceGetMatchingServices returned %d\n", kernResult );

    }

    return kernResult;

}


static void tcg_out_qemu_st(TCGContext *s, const TCGArg *args, bool is64)

{

    TCGReg datalo, datahi, addrlo;

    TCGReg addrhi __attribute__((unused));

    TCGMemOpIdx oi;

    TCGMemOp opc;

#if defined(CONFIG_SOFTMMU)

    int mem_index;

    TCGMemOp s_bits;

    tcg_insn_unit *label_ptr[2];

#endif

    datalo = *args++;

    datahi = (TCG_TARGET_REG_BITS == 32 && is64 ? *args++ : 0);

    addrlo = *args++;

    addrhi = (TARGET_LONG_BITS > TCG_TARGET_REG_BITS ? *args++ : 0);

    oi = *args++;

    opc = get_memop(oi);

#if defined(CONFIG_SOFTMMU)

    mem_index = get_mmuidx(oi);

    s_bits = opc & MO_SIZE;

    tcg_out_tlb_load(s, addrlo, addrhi, mem_index, s_bits,

                     label_ptr, offsetof(CPUTLBEntry, addr_write));

    /* TLB Hit.  */

    tcg_out_qemu_st_direct(s, datalo, datahi, TCG_REG_L1, 0, 0, opc);

    /* Record the current context of a store into ldst label */

    add_qemu_ldst_label(s, false, oi, datalo, datahi, addrlo, addrhi,

                        s->code_ptr, label_ptr);

#else

    {

        int32_t offset = GUEST_BASE;

        TCGReg base = addrlo;

        int seg = 0;

        /* See comment in tcg_out_qemu_ld re zero-extension of addrlo.  */

        if (GUEST_BASE == 0 || guest_base_flags) {

            seg = guest_base_flags;

            offset = 0;

            if (TCG_TARGET_REG_BITS > TARGET_LONG_BITS) {

                seg |= P_ADDR32;

            }

        } else if (TCG_TARGET_REG_BITS == 64) {

            /* ??? Note that we can't use the same SIB addressing scheme

               as for loads, since we require L0 free for bswap.  */

            if (offset != GUEST_BASE) {

                if (TARGET_LONG_BITS == 32) {

                    tcg_out_ext32u(s, TCG_REG_L0, base);

                    base = TCG_REG_L0;

                }

                tcg_out_movi(s, TCG_TYPE_I64, TCG_REG_L1, GUEST_BASE);

                tgen_arithr(s, ARITH_ADD + P_REXW, TCG_REG_L1, base);

                base = TCG_REG_L1;

                offset = 0;

            } else if (TARGET_LONG_BITS == 32) {

                tcg_out_ext32u(s, TCG_REG_L1, base);

                base = TCG_REG_L1;

            }

        }

        tcg_out_qemu_st_direct(s, datalo, datahi, base, offset, seg, opc);

    }

#endif

}


static int create_header32(DumpState *s)

{

    int ret = 0;

    DiskDumpHeader32 *dh = NULL;

    KdumpSubHeader32 *kh = NULL;

    size_t size;

    int endian = s->dump_info.d_endian;

    uint32_t block_size;

    uint32_t sub_hdr_size;

    uint32_t bitmap_blocks;

    uint32_t status = 0;

    uint64_t offset_note;

    /* write common header, the version of kdump-compressed format is 6th */

    size = sizeof(DiskDumpHeader32);

    dh = g_malloc0(size);

    strncpy(dh->signature, KDUMP_SIGNATURE, strlen(KDUMP_SIGNATURE));

    dh->header_version = cpu_convert_to_target32(6, endian);

    block_size = s->page_size;

    dh->block_size = cpu_convert_to_target32(block_size, endian);

    sub_hdr_size = sizeof(struct KdumpSubHeader32) + s->note_size;

    sub_hdr_size = DIV_ROUND_UP(sub_hdr_size, block_size);

    dh->sub_hdr_size = cpu_convert_to_target32(sub_hdr_size, endian);

    /* dh->max_mapnr may be truncated, full 64bit is in kh.max_mapnr_64 */

    dh->max_mapnr = cpu_convert_to_target32(MIN(s->max_mapnr, UINT_MAX),

                                            endian);

    dh->nr_cpus = cpu_convert_to_target32(s->nr_cpus, endian);

    bitmap_blocks = DIV_ROUND_UP(s->len_dump_bitmap, block_size) * 2;

    dh->bitmap_blocks = cpu_convert_to_target32(bitmap_blocks, endian);

    strncpy(dh->utsname.machine, ELF_MACHINE_UNAME, sizeof(dh->utsname.machine));

    if (s->flag_compress & DUMP_DH_COMPRESSED_ZLIB) {

        status |= DUMP_DH_COMPRESSED_ZLIB;

    }

#ifdef CONFIG_LZO

    if (s->flag_compress & DUMP_DH_COMPRESSED_LZO) {

        status |= DUMP_DH_COMPRESSED_LZO;

    }

#endif

#ifdef CONFIG_SNAPPY

    if (s->flag_compress & DUMP_DH_COMPRESSED_SNAPPY) {

        status |= DUMP_DH_COMPRESSED_SNAPPY;

    }

#endif

    dh->status = cpu_convert_to_target32(status, endian);

    if (write_buffer(s->fd, 0, dh, size) < 0) {

        dump_error(s, "dump: failed to write disk dump header.\n");

        ret = -1;

        goto out;

    }

    /* write sub header */

    size = sizeof(KdumpSubHeader32);

    kh = g_malloc0(size);

    /* 64bit max_mapnr_64 */

    kh->max_mapnr_64 = cpu_convert_to_target64(s->max_mapnr, endian);

    kh->phys_base = cpu_convert_to_target32(PHYS_BASE, endian);

    kh->dump_level = cpu_convert_to_target32(DUMP_LEVEL, endian);

    offset_note = DISKDUMP_HEADER_BLOCKS * block_size + size;

    kh->offset_note = cpu_convert_to_target64(offset_note, endian);

    kh->note_size = cpu_convert_to_target32(s->note_size, endian);

    if (write_buffer(s->fd, DISKDUMP_HEADER_BLOCKS *

                     block_size, kh, size) < 0) {

        dump_error(s, "dump: failed to write kdump sub header.\n");

        ret = -1;

        goto out;

    }

    /* write note */

    s->note_buf = g_malloc0(s->note_size);

    s->note_buf_offset = 0;

    /* use s->note_buf to store notes temporarily */

    if (write_elf32_notes(buf_write_note, s) < 0) {

        ret = -1;

        goto out;

    }

    if (write_buffer(s->fd, offset_note, s->note_buf,

                     s->note_size) < 0) {

        dump_error(s, "dump: failed to write notes");

        ret = -1;

        goto out;

    }

    /* get offset of dump_bitmap */

    s->offset_dump_bitmap = (DISKDUMP_HEADER_BLOCKS + sub_hdr_size) *

                             block_size;

    /* get offset of page */

    s->offset_page = (DISKDUMP_HEADER_BLOCKS + sub_hdr_size + bitmap_blocks) *

                     block_size;

out:

    g_free(dh);

    g_free(kh);

    g_free(s->note_buf);

    return ret;

}


static int mov_read_header(AVFormatContext *s)

{

    MOVContext *mov = s->priv_data;

    AVIOContext *pb = s->pb;

    int err;

    MOVAtom atom = { AV_RL32("root") };

    int i;

    mov->fc = s;

    /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */

    if (pb->seekable)

        atom.size = avio_size(pb);

    else

        atom.size = INT64_MAX;

    /* check MOV header */

    if ((err = mov_read_default(mov, pb, atom)) < 0) {

        av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);

        mov_read_close(s);

        return err;

    }

    if (!mov->found_moov) {

        av_log(s, AV_LOG_ERROR, "moov atom not found\n");

        mov_read_close(s);

        return AVERROR_INVALIDDATA;

    }

    av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));

    if (pb->seekable && mov->chapter_track > 0)

        mov_read_chapters(s);

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

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

        MOVStreamContext *sc = st->priv_data;

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

            if (st->codec->width <= 0 && st->codec->width <= 0) {

                st->codec->width  = sc->width;

                st->codec->height = sc->height;

            }

            if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {

                if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)

                    return err;

            }

        }

    }

    if (mov->trex_data) {

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

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

            MOVStreamContext *sc = st->priv_data;

            if (st->duration > 0)

                st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;

        }

    }

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

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

        MOVStreamContext *sc = st->priv_data;

        switch (st->codec->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            err = ff_replaygain_export(st, s->metadata);

            if (err < 0) {

                mov_read_close(s);

                return err;

            }

            break;

        case AVMEDIA_TYPE_VIDEO:

            if (sc->display_matrix) {

                AVPacketSideData *sd, *tmp;

                tmp = av_realloc_array(st->side_data,

                                       st->nb_side_data + 1, sizeof(*tmp));

                if (!tmp)

                    return AVERROR(ENOMEM);

                st->side_data = tmp;

                st->nb_side_data++;

                sd = &st->side_data[st->nb_side_data - 1];

                sd->type = AV_PKT_DATA_DISPLAYMATRIX;

                sd->size = sizeof(int32_t) * 9;

                sd->data = (uint8_t*)sc->display_matrix;

                sc->display_matrix = NULL;

            }

            break;

        }

    }

    return 0;

}


static uint32_t bitband_readb(void *opaque, target_phys_addr_t offset)

{

    uint8_t v;

    cpu_physical_memory_read(bitband_addr(opaque, offset), &v, 1);

    return (v & (1 << ((offset >> 2) & 7))) != 0;

}


static int imc_decode_frame(AVCodecContext * avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    IMCContext *q = avctx->priv_data;

    int stream_format_code;

    int imc_hdr, i, j;

    int flag;

    int bits, summer;

    int counter, bitscount;

    LOCAL_ALIGNED_16(uint16_t, buf16, [IMC_BLOCK_SIZE / 2]);

    if (buf_size < IMC_BLOCK_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "imc frame too small!\n");

        return -1;

    }

    q->dsp.bswap16_buf(buf16, (const uint16_t*)buf, IMC_BLOCK_SIZE / 2);

    q->out_samples = data;

    init_get_bits(&q->gb, (const uint8_t*)buf16, IMC_BLOCK_SIZE * 8);

    /* Check the frame header */

    imc_hdr = get_bits(&q->gb, 9);

    if (imc_hdr != IMC_FRAME_ID) {

        av_log(avctx, AV_LOG_ERROR, "imc frame header check failed!\n");

        av_log(avctx, AV_LOG_ERROR, "got %x instead of 0x21.\n", imc_hdr);

        return -1;

    }

    stream_format_code = get_bits(&q->gb, 3);

    if(stream_format_code & 1){

        av_log(avctx, AV_LOG_ERROR, "Stream code format %X is not supported\n", stream_format_code);

        return -1;

    }

//    av_log(avctx, AV_LOG_DEBUG, "stream_format_code = %d\n", stream_format_code);

    if (stream_format_code & 0x04)

        q->decoder_reset = 1;

    if(q->decoder_reset) {

        memset(q->out_samples, 0, sizeof(q->out_samples));

        for(i = 0; i < BANDS; i++)q->old_floor[i] = 1.0;

        for(i = 0; i < COEFFS; i++)q->CWdecoded[i] = 0;

        q->decoder_reset = 0;

    }

    flag = get_bits1(&q->gb);

    imc_read_level_coeffs(q, stream_format_code, q->levlCoeffBuf);

    if (stream_format_code & 0x4)

        imc_decode_level_coefficients(q, q->levlCoeffBuf, q->flcoeffs1, q->flcoeffs2);

    else

        imc_decode_level_coefficients2(q, q->levlCoeffBuf, q->old_floor, q->flcoeffs1, q->flcoeffs2);

    memcpy(q->old_floor, q->flcoeffs1, 32 * sizeof(float));

    counter = 0;

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

        if (q->levlCoeffBuf[i] == 16) {

            q->bandWidthT[i] = 0;

            counter++;

        } else

            q->bandWidthT[i] = band_tab[i+1] - band_tab[i];

    }

    memset(q->bandFlagsBuf, 0, BANDS * sizeof(int));

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

        if (q->bandWidthT[i])

            q->bandFlagsBuf[i] = get_bits1(&q->gb);

    }

    imc_calculate_coeffs(q, q->flcoeffs1, q->flcoeffs2, q->bandWidthT, q->flcoeffs3, q->flcoeffs5);

    bitscount = 0;

    /* first 4 bands will be assigned 5 bits per coefficient */

    if (stream_format_code & 0x2) {

        bitscount += 15;

        q->bitsBandT[0] = 5;

        q->CWlengthT[0] = 5;

        q->CWlengthT[1] = 5;

        q->CWlengthT[2] = 5;

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

            bits = (q->levlCoeffBuf[i] == 16) ? 0 : 5;

            q->bitsBandT[i] = bits;

            for(j = band_tab[i]; j < band_tab[i+1]; j++) {

                q->CWlengthT[j] = bits;

                bitscount += bits;

            }

        }

    }

    if(bit_allocation (q, stream_format_code, 512 - bitscount - get_bits_count(&q->gb), flag) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Bit allocations failed\n");

        q->decoder_reset = 1;

        return -1;

    }

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

        q->sumLenArr[i] = 0;

        q->skipFlagRaw[i] = 0;

        for(j = band_tab[i]; j < band_tab[i+1]; j++)

            q->sumLenArr[i] += q->CWlengthT[j];

        if (q->bandFlagsBuf[i])

            if( (((band_tab[i+1] - band_tab[i]) * 1.5) > q->sumLenArr[i]) && (q->sumLenArr[i] > 0))

                q->skipFlagRaw[i] = 1;

    }

    imc_get_skip_coeff(q);

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

        q->flcoeffs6[i] = q->flcoeffs1[i];

        /* band has flag set and at least one coded coefficient */

        if (q->bandFlagsBuf[i] && (band_tab[i+1] - band_tab[i]) != q->skipFlagCount[i]){

                q->flcoeffs6[i] *= q->sqrt_tab[band_tab[i+1] - band_tab[i]] /

                                   q->sqrt_tab[(band_tab[i+1] - band_tab[i] - q->skipFlagCount[i])];

        }

    }

    /* calculate bits left, bits needed and adjust bit allocation */

    bits = summer = 0;

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

        if (q->bandFlagsBuf[i]) {

            for(j = band_tab[i]; j < band_tab[i+1]; j++) {

                if(q->skipFlags[j]) {

                    summer += q->CWlengthT[j];

                    q->CWlengthT[j] = 0;

                }

            }

            bits += q->skipFlagBits[i];

            summer -= q->skipFlagBits[i];

        }

    }

    imc_adjust_bit_allocation(q, summer);

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

        q->sumLenArr[i] = 0;

        for(j = band_tab[i]; j < band_tab[i+1]; j++)

            if (!q->skipFlags[j])

                q->sumLenArr[i] += q->CWlengthT[j];

    }

    memset(q->codewords, 0, sizeof(q->codewords));

    if(imc_get_coeffs(q) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Read coefficients failed\n");

        q->decoder_reset = 1;

        return 0;

    }

    if(inverse_quant_coeff(q, stream_format_code) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Inverse quantization of coefficients failed\n");

        q->decoder_reset = 1;

        return 0;

    }

    memset(q->skipFlags, 0, sizeof(q->skipFlags));

    imc_imdct256(q);

    *data_size = COEFFS * sizeof(float);

    return IMC_BLOCK_SIZE;

}


void av_register_all(void)

{

    static int initialized;

    if (initialized)

        return;

    initialized = 1;

    avcodec_register_all();

    /* (de)muxers */

    REGISTER_MUXER    (A64, a64);

    REGISTER_DEMUXER  (AAC, aac);

    REGISTER_MUXDEMUX (AC3, ac3);

    REGISTER_MUXER    (ADTS, adts);

    REGISTER_DEMUXER  (AEA, aea);

    REGISTER_MUXDEMUX (AIFF, aiff);

    REGISTER_MUXDEMUX (AMR, amr);

    REGISTER_DEMUXER  (ANM, anm);

    REGISTER_DEMUXER  (APC, apc);

    REGISTER_DEMUXER  (APE, ape);

    REGISTER_DEMUXER  (APPLEHTTP, applehttp);

    REGISTER_MUXDEMUX (ASF, asf);

    REGISTER_MUXDEMUX (ASS, ass);

    REGISTER_MUXER    (ASF_STREAM, asf_stream);

    REGISTER_MUXDEMUX (AU, au);

    REGISTER_MUXDEMUX (AVI, avi);

    REGISTER_DEMUXER  (AVISYNTH, avisynth);

    REGISTER_MUXER    (AVM2, avm2);

    REGISTER_DEMUXER  (AVS, avs);

    REGISTER_DEMUXER  (BETHSOFTVID, bethsoftvid);

    REGISTER_DEMUXER  (BFI, bfi);

    REGISTER_DEMUXER  (BINK, bink);

    REGISTER_DEMUXER  (C93, c93);

    REGISTER_DEMUXER  (CAF, caf);

    REGISTER_MUXDEMUX (CAVSVIDEO, cavsvideo);

    REGISTER_DEMUXER  (CDG, cdg);

    REGISTER_MUXER    (CRC, crc);

    REGISTER_MUXDEMUX (DAUD, daud);

    REGISTER_DEMUXER  (DFA, dfa);

    REGISTER_MUXDEMUX (DIRAC, dirac);

    REGISTER_MUXDEMUX (DNXHD, dnxhd);

    REGISTER_DEMUXER  (DSICIN, dsicin);

    REGISTER_MUXDEMUX (DTS, dts);

    REGISTER_MUXDEMUX (DV, dv);

    REGISTER_DEMUXER  (DXA, dxa);

    REGISTER_DEMUXER  (EA, ea);

    REGISTER_DEMUXER  (EA_CDATA, ea_cdata);

    REGISTER_MUXDEMUX (EAC3, eac3);

    REGISTER_MUXDEMUX (FFM, ffm);

    REGISTER_MUXDEMUX (FFMETADATA, ffmetadata);

    REGISTER_MUXDEMUX (FILMSTRIP, filmstrip);

    REGISTER_MUXDEMUX (FLAC, flac);

    REGISTER_DEMUXER  (FLIC, flic);

    REGISTER_MUXDEMUX (FLV, flv);

    REGISTER_DEMUXER  (FOURXM, fourxm);

    REGISTER_MUXER    (FRAMECRC, framecrc);

    REGISTER_MUXER    (FRAMEMD5, framemd5);

    REGISTER_MUXDEMUX (G722, g722);

    REGISTER_MUXER    (GIF, gif);

    REGISTER_DEMUXER  (GSM, gsm);

    REGISTER_MUXDEMUX (GXF, gxf);

    REGISTER_MUXDEMUX (H261, h261);

    REGISTER_MUXDEMUX (H263, h263);

    REGISTER_MUXDEMUX (H264, h264);

    REGISTER_DEMUXER  (IDCIN, idcin);

    REGISTER_DEMUXER  (IFF, iff);

    REGISTER_MUXDEMUX (IMAGE2, image2);

    REGISTER_MUXDEMUX (IMAGE2PIPE, image2pipe);

    REGISTER_DEMUXER  (INGENIENT, ingenient);

    REGISTER_DEMUXER  (IPMOVIE, ipmovie);

    REGISTER_MUXER    (IPOD, ipod);

    REGISTER_DEMUXER  (ISS, iss);

    REGISTER_DEMUXER  (IV8, iv8);

    REGISTER_MUXDEMUX (IVF, ivf);

    REGISTER_DEMUXER  (JV, jv);

    REGISTER_MUXER    (LATM, latm);

    REGISTER_DEMUXER  (LMLM4, lmlm4);

    REGISTER_DEMUXER  (LXF, lxf);

    REGISTER_MUXDEMUX (M4V, m4v);

    REGISTER_MUXER    (MD5, md5);

    REGISTER_MUXDEMUX (MATROSKA, matroska);

    REGISTER_MUXER    (MATROSKA_AUDIO, matroska_audio);

    REGISTER_MUXDEMUX (MJPEG, mjpeg);

    REGISTER_MUXDEMUX (MLP, mlp);

    REGISTER_DEMUXER  (MM, mm);

    REGISTER_MUXDEMUX (MMF, mmf);

    REGISTER_MUXDEMUX (MOV, mov);

    REGISTER_MUXER    (MP2, mp2);

    REGISTER_MUXDEMUX (MP3, mp3);

    REGISTER_MUXER    (MP4, mp4);

    REGISTER_DEMUXER  (MPC, mpc);

    REGISTER_DEMUXER  (MPC8, mpc8);

    REGISTER_MUXER    (MPEG1SYSTEM, mpeg1system);

    REGISTER_MUXER    (MPEG1VCD, mpeg1vcd);

    REGISTER_MUXER    (MPEG1VIDEO, mpeg1video);

    REGISTER_MUXER    (MPEG2DVD, mpeg2dvd);

    REGISTER_MUXER    (MPEG2SVCD, mpeg2svcd);

    REGISTER_MUXER    (MPEG2VIDEO, mpeg2video);

    REGISTER_MUXER    (MPEG2VOB, mpeg2vob);

    REGISTER_DEMUXER  (MPEGPS, mpegps);

    REGISTER_MUXDEMUX (MPEGTS, mpegts);

    REGISTER_DEMUXER  (MPEGTSRAW, mpegtsraw);

    REGISTER_DEMUXER  (MPEGVIDEO, mpegvideo);

    REGISTER_MUXER    (MPJPEG, mpjpeg);

    REGISTER_DEMUXER  (MSNWC_TCP, msnwc_tcp);

    REGISTER_DEMUXER  (MTV, mtv);

    REGISTER_DEMUXER  (MVI, mvi);

    REGISTER_MUXDEMUX (MXF, mxf);

    REGISTER_MUXER    (MXF_D10, mxf_d10);

    REGISTER_DEMUXER  (MXG, mxg);

    REGISTER_DEMUXER  (NC, nc);

    REGISTER_DEMUXER  (NSV, nsv);

    REGISTER_MUXER    (NULL, null);

    REGISTER_MUXDEMUX (NUT, nut);

    REGISTER_DEMUXER  (NUV, nuv);

    REGISTER_MUXDEMUX (OGG, ogg);

    REGISTER_DEMUXER  (OMA, oma);

    REGISTER_MUXDEMUX (PCM_ALAW,  pcm_alaw);

    REGISTER_MUXDEMUX (PCM_MULAW, pcm_mulaw);

    REGISTER_MUXDEMUX (PCM_F64BE, pcm_f64be);

    REGISTER_MUXDEMUX (PCM_F64LE, pcm_f64le);

    REGISTER_MUXDEMUX (PCM_F32BE, pcm_f32be);

    REGISTER_MUXDEMUX (PCM_F32LE, pcm_f32le);

    REGISTER_MUXDEMUX (PCM_S32BE, pcm_s32be);

    REGISTER_MUXDEMUX (PCM_S32LE, pcm_s32le);

    REGISTER_MUXDEMUX (PCM_S24BE, pcm_s24be);

    REGISTER_MUXDEMUX (PCM_S24LE, pcm_s24le);

    REGISTER_MUXDEMUX (PCM_S16BE, pcm_s16be);

    REGISTER_MUXDEMUX (PCM_S16LE, pcm_s16le);

    REGISTER_MUXDEMUX (PCM_S8,    pcm_s8);

    REGISTER_MUXDEMUX (PCM_U32BE, pcm_u32be);

    REGISTER_MUXDEMUX (PCM_U32LE, pcm_u32le);

    REGISTER_MUXDEMUX (PCM_U24BE, pcm_u24be);

    REGISTER_MUXDEMUX (PCM_U24LE, pcm_u24le);

    REGISTER_MUXDEMUX (PCM_U16BE, pcm_u16be);

    REGISTER_MUXDEMUX (PCM_U16LE, pcm_u16le);

    REGISTER_MUXDEMUX (PCM_U8,    pcm_u8);

    REGISTER_MUXER    (PSP, psp);

    REGISTER_DEMUXER  (PVA, pva);

    REGISTER_DEMUXER  (QCP, qcp);

    REGISTER_DEMUXER  (R3D, r3d);

    REGISTER_MUXDEMUX (RAWVIDEO, rawvideo);

    REGISTER_DEMUXER  (RL2, rl2);

    REGISTER_MUXDEMUX (RM, rm);

    REGISTER_MUXDEMUX (ROQ, roq);

    REGISTER_DEMUXER  (RPL, rpl);

    REGISTER_MUXDEMUX (RSO, rso);

    REGISTER_MUXDEMUX (RTP, rtp);

    REGISTER_MUXDEMUX (RTSP, rtsp);

    REGISTER_MUXDEMUX (SAP, sap);

    REGISTER_DEMUXER  (SDP, sdp);

#if CONFIG_RTPDEC

    av_register_rtp_dynamic_payload_handlers();

    av_register_rdt_dynamic_payload_handlers();

#endif

    REGISTER_DEMUXER  (SEGAFILM, segafilm);

    REGISTER_DEMUXER  (SHORTEN, shorten);

    REGISTER_DEMUXER  (SIFF, siff);

    REGISTER_DEMUXER  (SMACKER, smacker);

    REGISTER_DEMUXER  (SOL, sol);

    REGISTER_MUXDEMUX (SOX, sox);

    REGISTER_MUXDEMUX (SPDIF, spdif);

    REGISTER_MUXDEMUX (SRT, srt);

    REGISTER_DEMUXER  (STR, str);

    REGISTER_MUXDEMUX (SWF, swf);

    REGISTER_MUXER    (TG2, tg2);

    REGISTER_MUXER    (TGP, tgp);

    REGISTER_DEMUXER  (THP, thp);

    REGISTER_DEMUXER  (TIERTEXSEQ, tiertexseq);

    REGISTER_DEMUXER  (TMV, tmv);

    REGISTER_MUXDEMUX (TRUEHD, truehd);

    REGISTER_DEMUXER  (TTA, tta);

    REGISTER_DEMUXER  (TXD, txd);

    REGISTER_DEMUXER  (TTY, tty);

    REGISTER_DEMUXER  (VC1, vc1);

    REGISTER_MUXDEMUX (VC1T, vc1t);

    REGISTER_DEMUXER  (VMD, vmd);

    REGISTER_MUXDEMUX (VOC, voc);

    REGISTER_DEMUXER  (VQF, vqf);

    REGISTER_DEMUXER  (W64, w64);

    REGISTER_MUXDEMUX (WAV, wav);

    REGISTER_DEMUXER  (WC3, wc3);

    REGISTER_MUXER    (WEBM, webm);

    REGISTER_DEMUXER  (WSAUD, wsaud);

    REGISTER_DEMUXER  (WSVQA, wsvqa);

    REGISTER_DEMUXER  (WTV, wtv);

    REGISTER_DEMUXER  (WV, wv);

    REGISTER_DEMUXER  (XA, xa);

    REGISTER_DEMUXER  (XMV, xmv);

    REGISTER_DEMUXER  (XWMA, xwma);

    REGISTER_DEMUXER  (YOP, yop);

    REGISTER_MUXDEMUX (YUV4MPEGPIPE, yuv4mpegpipe);

    /* external libraries */

    REGISTER_MUXDEMUX (LIBNUT, libnut);

    /* protocols */

    REGISTER_PROTOCOL (APPLEHTTP, applehttp);

    REGISTER_PROTOCOL (CONCAT, concat);

    REGISTER_PROTOCOL (CRYPTO, crypto);

    REGISTER_PROTOCOL (FILE, file);

    REGISTER_PROTOCOL (GOPHER, gopher);

    REGISTER_PROTOCOL (HTTP, http);

    REGISTER_PROTOCOL (MMSH, mmsh);

    REGISTER_PROTOCOL (MMST, mmst);

    REGISTER_PROTOCOL (MD5,  md5);

    REGISTER_PROTOCOL (PIPE, pipe);

    REGISTER_PROTOCOL (RTMP, rtmp);

#if CONFIG_LIBRTMP

    REGISTER_PROTOCOL (RTMP, rtmpt);

    REGISTER_PROTOCOL (RTMP, rtmpe);

    REGISTER_PROTOCOL (RTMP, rtmpte);

    REGISTER_PROTOCOL (RTMP, rtmps);

#endif

    REGISTER_PROTOCOL (RTP, rtp);

    REGISTER_PROTOCOL (TCP, tcp);

    REGISTER_PROTOCOL (UDP, udp);

}