static void x86_cpu_parse_featurestr(CPUState *cs, char *features,

                                     Error **errp)

{

    X86CPU *cpu = X86_CPU(cs);

    char *featurestr; /* Single 'key=value" string being parsed */

    /* Features to be added */

    FeatureWordArray plus_features = { 0 };

    /* Features to be removed */

    FeatureWordArray minus_features = { 0 };

    uint32_t numvalue;

    CPUX86State *env = &cpu->env;

    Error *local_err = NULL;

    featurestr = features ? strtok(features, ",") : NULL;

    while (featurestr) {

        char *val;

        if (featurestr[0] == '+') {

            add_flagname_to_bitmaps(featurestr + 1, plus_features);

        } else if (featurestr[0] == '-') {

            add_flagname_to_bitmaps(featurestr + 1, minus_features);

        } else if ((val = strchr(featurestr, '='))) {

            *val = 0; val++;

            feat2prop(featurestr);

            if (!strcmp(featurestr, "xlevel")) {

                char *err;

                char num[32];

                numvalue = strtoul(val, &err, 0);

                if (!*val || *err) {

                    error_setg(&local_err, "bad numerical value %s", val);

                    goto out;

                }

                if (numvalue < 0x80000000) {

                    error_report("xlevel value shall always be >= 0x80000000"

                                 ", fixup will be removed in future versions");

                    numvalue += 0x80000000;

                }

                snprintf(num, sizeof(num), "%" PRIu32, numvalue);

                object_property_parse(OBJECT(cpu), num, featurestr, &local_err);

            } else if (!strcmp(featurestr, "tsc-freq")) {

                int64_t tsc_freq;

                char *err;

                char num[32];

                tsc_freq = strtosz_suffix_unit(val, &err,

                                               STRTOSZ_DEFSUFFIX_B, 1000);

                if (tsc_freq < 0 || *err) {

                    error_setg(&local_err, "bad numerical value %s", val);

                    goto out;

                }

                snprintf(num, sizeof(num), "%" PRId64, tsc_freq);

                object_property_parse(OBJECT(cpu), num, "tsc-frequency",

                                      &local_err);

            } else if (!strcmp(featurestr, "hv-spinlocks")) {

                char *err;

                const int min = 0xFFF;

                char num[32];

                numvalue = strtoul(val, &err, 0);

                if (!*val || *err) {

                    error_setg(&local_err, "bad numerical value %s", val);

                    goto out;

                }

                if (numvalue < min) {

                    error_report("hv-spinlocks value shall always be >= 0x%x"

                            ", fixup will be removed in future versions",

                            min);

                    numvalue = min;

                }

                snprintf(num, sizeof(num), "%" PRId32, numvalue);

                object_property_parse(OBJECT(cpu), num, featurestr, &local_err);

            } else {

                object_property_parse(OBJECT(cpu), val, featurestr, &local_err);

            }

        } else {

            feat2prop(featurestr);

            object_property_parse(OBJECT(cpu), "on", featurestr, &local_err);

        }

        if (local_err) {

            error_propagate(errp, local_err);

            goto out;

        }

        featurestr = strtok(NULL, ",");

    }

    env->features[FEAT_1_EDX] |= plus_features[FEAT_1_EDX];

    env->features[FEAT_1_ECX] |= plus_features[FEAT_1_ECX];

    env->features[FEAT_8000_0001_EDX] |= plus_features[FEAT_8000_0001_EDX];

    env->features[FEAT_8000_0001_ECX] |= plus_features[FEAT_8000_0001_ECX];

    env->features[FEAT_C000_0001_EDX] |= plus_features[FEAT_C000_0001_EDX];

    env->features[FEAT_KVM] |= plus_features[FEAT_KVM];

    env->features[FEAT_SVM] |= plus_features[FEAT_SVM];

    env->features[FEAT_7_0_EBX] |= plus_features[FEAT_7_0_EBX];

    env->features[FEAT_1_EDX] &= ~minus_features[FEAT_1_EDX];

    env->features[FEAT_1_ECX] &= ~minus_features[FEAT_1_ECX];

    env->features[FEAT_8000_0001_EDX] &= ~minus_features[FEAT_8000_0001_EDX];

    env->features[FEAT_8000_0001_ECX] &= ~minus_features[FEAT_8000_0001_ECX];

    env->features[FEAT_C000_0001_EDX] &= ~minus_features[FEAT_C000_0001_EDX];

    env->features[FEAT_KVM] &= ~minus_features[FEAT_KVM];

    env->features[FEAT_SVM] &= ~minus_features[FEAT_SVM];

    env->features[FEAT_7_0_EBX] &= ~minus_features[FEAT_7_0_EBX];

out:

    return;

}


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

                                int *data_size, AVPacket *avpkt)

{

    int buf_size       = avpkt->size;

    FlashSVContext *s  = avctx->priv_data;

    int h_blocks, v_blocks, h_part, v_part, i, j;

    GetBitContext gb;

    /* no supplementary picture */

    if (buf_size == 0)

        return 0;

    if (buf_size < 4)

        return -1;

    init_get_bits(&gb, avpkt->data, buf_size * 8);

    /* start to parse the bitstream */

    s->block_width  = 16 * (get_bits(&gb,  4) + 1);

    s->image_width  =       get_bits(&gb, 12);

    s->block_height = 16 * (get_bits(&gb,  4) + 1);

    s->image_height =       get_bits(&gb, 12);

    if (s->ver == 2) {

        skip_bits(&gb, 6);

        if (get_bits1(&gb)) {

            av_log_missing_feature(avctx, "iframe", 1);

            return AVERROR_PATCHWELCOME;

        if (get_bits1(&gb)) {

            av_log_missing_feature(avctx, "Custom palette", 1);

            return AVERROR_PATCHWELCOME;

    /* calculate number of blocks and size of border (partial) blocks */

    h_blocks = s->image_width  / s->block_width;

    h_part   = s->image_width  % s->block_width;

    v_blocks = s->image_height / s->block_height;

    v_part   = s->image_height % s->block_height;

    /* the block size could change between frames, make sure the buffer

     * is large enough, if not, get a larger one */

    if (s->block_size < s->block_width * s->block_height) {

        int tmpblock_size = 3 * s->block_width * s->block_height;

        s->tmpblock = av_realloc(s->tmpblock, tmpblock_size);

        if (!s->tmpblock) {

            av_log(avctx, AV_LOG_ERROR, "Can't allocate decompression buffer.\n");

            return AVERROR(ENOMEM);

        if (s->ver == 2) {

            s->deflate_block_size = calc_deflate_block_size(tmpblock_size);

            if (s->deflate_block_size <= 0) {

                av_log(avctx, AV_LOG_ERROR, "Can't determine deflate buffer size.\n");

                return -1;

            s->deflate_block = av_realloc(s->deflate_block, s->deflate_block_size);

            if (!s->deflate_block) {

                av_log(avctx, AV_LOG_ERROR, "Can't allocate deflate buffer.\n");

                return AVERROR(ENOMEM);

    s->block_size = s->block_width * s->block_height;

    /* initialize the image size once */

    if (avctx->width == 0 && avctx->height == 0) {

        avctx->width  = s->image_width;

        avctx->height = s->image_height;

    /* check for changes of image width and image height */

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

               "Frame width or height differs from first frame!\n");

        av_log(avctx, AV_LOG_ERROR, "fh = %d, fv %d  vs  ch = %d, cv = %d\n",

               avctx->height, avctx->width, s->image_height, s->image_width);

    /* we care for keyframes only in Screen Video v2 */

    s->is_keyframe = (avpkt->flags & AV_PKT_FLAG_KEY) && (s->ver == 2);

    if (s->is_keyframe) {

        s->keyframedata = av_realloc(s->keyframedata, avpkt->size);

        memcpy(s->keyframedata, avpkt->data, avpkt->size);

        s->blocks = av_realloc(s->blocks,

                               (v_blocks + !!v_part) * (h_blocks + !!h_part)

                               * sizeof(s->blocks[0]));

    av_dlog(avctx, "image: %dx%d block: %dx%d num: %dx%d part: %dx%d\n",

            s->image_width, s->image_height, s->block_width, s->block_height,

            h_blocks, v_blocks, h_part, v_part);

    s->frame.reference    = 3;

    s->frame.buffer_hints = FF_BUFFER_HINTS_VALID    |

                            FF_BUFFER_HINTS_PRESERVE |

                            FF_BUFFER_HINTS_REUSABLE;

    if (avctx->reget_buffer(avctx, &s->frame) < 0) {

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

        return -1;

    /* loop over all block columns */

    for (j = 0; j < v_blocks + (v_part ? 1 : 0); j++) {

        int y_pos  = j * s->block_height; // vertical position in frame

        int cur_blk_height = (j < v_blocks) ? s->block_height : v_part;

        /* loop over all block rows */

        for (i = 0; i < h_blocks + (h_part ? 1 : 0); i++) {

            int x_pos = i * s->block_width; // horizontal position in frame

            int cur_blk_width = (i < h_blocks) ? s->block_width : h_part;

            int has_diff = 0;

            /* get the size of the compressed zlib chunk */

            int size = get_bits(&gb, 16);

            s->color_depth    = 0;

            s->zlibprime_curr = 0;

            s->zlibprime_prev = 0;

            s->diff_start     = 0;

            s->diff_height    = cur_blk_height;

            if (8 * size > get_bits_left(&gb)) {

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

                s->frame.data[0] = NULL;

            if (s->ver == 2 && size) {

                skip_bits(&gb, 3);

                s->color_depth    = get_bits(&gb, 2);

                has_diff          = get_bits1(&gb);

                s->zlibprime_curr = get_bits1(&gb);

                s->zlibprime_prev = get_bits1(&gb);

                if (s->color_depth != 0 && s->color_depth != 2) {

                           "%dx%d invalid color depth %d\n", i, j, s->color_depth);

                if (has_diff) {

                    s->diff_start  = get_bits(&gb, 8);

                    s->diff_height = get_bits(&gb, 8);

                    av_log(avctx, AV_LOG_DEBUG,

                           "%dx%d diff start %d height %d\n",

                           i, j, s->diff_start, s->diff_height);

                    size -= 2;

                if (s->zlibprime_prev)

                    av_log(avctx, AV_LOG_DEBUG, "%dx%d zlibprime_prev\n", i, j);

                if (s->zlibprime_curr) {

                    int col = get_bits(&gb, 8);

                    int row = get_bits(&gb, 8);

                    av_log(avctx, AV_LOG_DEBUG, "%dx%d zlibprime_curr %dx%d\n", i, j, col, row);

                    size -= 2;

                    av_log_missing_feature(avctx, "zlibprime_curr", 1);

                    return AVERROR_PATCHWELCOME;

                size--; // account for flags byte

            if (has_diff) {

                int k;

                int off = (s->image_height - y_pos - 1) * s->frame.linesize[0];

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

                    memcpy(s->frame.data[0] + off - k*s->frame.linesize[0] + x_pos*3,

                           s->keyframe + off - k*s->frame.linesize[0] + x_pos*3,

                           cur_blk_width * 3);

            /* skip unchanged blocks, which have size 0 */

            if (size) {

                if (flashsv_decode_block(avctx, avpkt, &gb, size,

                                         cur_blk_width, cur_blk_height,

                                         x_pos, y_pos,

                                         i + j * (h_blocks + !!h_part)))

                           "error in decompression of block %dx%d\n", i, j);

    if (s->is_keyframe && s->ver == 2) {

            s->keyframe = av_malloc(s->frame.linesize[0] * avctx->height);

                av_log(avctx, AV_LOG_ERROR, "Cannot allocate image data\n");

                return AVERROR(ENOMEM);

        memcpy(s->keyframe, s->frame.data[0], s->frame.linesize[0] * avctx->height);

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = s->frame;

    if ((get_bits_count(&gb) / 8) != buf_size)

        av_log(avctx, AV_LOG_ERROR, "buffer not fully consumed (%d != %d)\n",

               buf_size, (get_bits_count(&gb) / 8));

    /* report that the buffer was completely consumed */

    return buf_size;


static void setup_window(AVFormatContext *s)

{

    XCBGrabContext *c = s->priv_data;

    uint32_t mask     = XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK;

    uint32_t values[] = { 1,

                          XCB_EVENT_MASK_EXPOSURE |

                          XCB_EVENT_MASK_STRUCTURE_NOTIFY };

    xcb_rectangle_t rect = { 0, 0, c->width, c->height };

    c->window = xcb_generate_id(c->conn);

    xcb_create_window(c->conn, XCB_COPY_FROM_PARENT,

                      c->window,

                      c->screen->root,

                      c->x - c->region_border,

                      c->y - c->region_border,

                      c->width + c->region_border * 2,

                      c->height + c->region_border * 2,

                      0,

                      XCB_WINDOW_CLASS_INPUT_OUTPUT,

                      XCB_COPY_FROM_PARENT,

                      mask, values);

#if CONFIG_LIBXCB_SHAPE

    xcb_shape_rectangles(c->conn, XCB_SHAPE_SO_SUBTRACT,

                         XCB_SHAPE_SK_BOUNDING, XCB_CLIP_ORDERING_UNSORTED,

                         c->window,

                         c->region_border, c->region_border,

                         1, &rect);

#endif

    xcb_map_window(c->conn, c->window);

    draw_rectangle(s);

}


static inline void RENAME(rgb16to15)(const uint8_t *src, uint8_t *dst, int src_size)

{

    register const uint8_t* s=src;

    register uint8_t* d=dst;

    register const uint8_t *end;

    const uint8_t *mm_end;

    end = s + src_size;

    __asm__ volatile(PREFETCH"    %0"::"m"(*s));

    __asm__ volatile("movq        %0, %%mm7"::"m"(mask15rg));

    __asm__ volatile("movq        %0, %%mm6"::"m"(mask15b));

    mm_end = end - 15;

    while (s<mm_end) {

        __asm__ volatile(

            PREFETCH"  32%1         \n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

            MOVNTQ"   %%mm2, 8%0"

            :"=m"(*d)

            :"m"(*s)

        );

        d+=16;

        s+=16;

    }

    __asm__ volatile(SFENCE:::"memory");

    __asm__ volatile(EMMS:::"memory");

    mm_end = end - 3;

    while (s < mm_end) {

        register uint32_t x= *((const uint32_t*)s);

        *((uint32_t *)d) = ((x>>1)&0x7FE07FE0) | (x&0x001F001F);

        s+=4;

        d+=4;

    }

    if (s < end) {

        register uint16_t x= *((const uint16_t*)s);

        *((uint16_t *)d) = ((x>>1)&0x7FE0) | (x&0x001F);

    }

}


void ff_ivi_recompose53(const IVIPlaneDesc *plane, uint8_t *dst,

                        const int dst_pitch, const int num_bands)

{

    int             x, y, indx;

    int32_t         p0, p1, p2, p3, tmp0, tmp1, tmp2;

    int32_t         b0_1, b0_2, b1_1, b1_2, b1_3, b2_1, b2_2, b2_3, b2_4, b2_5, b2_6;

    int32_t         b3_1, b3_2, b3_3, b3_4, b3_5, b3_6, b3_7, b3_8, b3_9;

    int32_t         pitch, back_pitch;

    const IDWTELEM *b0_ptr, *b1_ptr, *b2_ptr, *b3_ptr;

    /* all bands should have the same pitch */

    pitch = plane->bands[0].pitch;

    /* pixels at the position "y-1" will be set to pixels at the "y" for the 1st iteration */

    back_pitch = 0;

    /* get pointers to the wavelet bands */

    b0_ptr = plane->bands[0].buf;

    b1_ptr = plane->bands[1].buf;

    b2_ptr = plane->bands[2].buf;

    b3_ptr = plane->bands[3].buf;

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

        if (y+2 >= plane->height)

            pitch= 0;

        /* load storage variables with values */

        if (num_bands > 0) {

            b0_1 = b0_ptr[0];

            b0_2 = b0_ptr[pitch];

        }

        if (num_bands > 1) {

            b1_1 = b1_ptr[back_pitch];

            b1_2 = b1_ptr[0];

            b1_3 = b1_1 - b1_2*6 + b1_ptr[pitch];

        }

        if (num_bands > 2) {

            b2_2 = b2_ptr[0];     // b2[x,  y  ]

            b2_3 = b2_2;          // b2[x+1,y  ] = b2[x,y]

            b2_5 = b2_ptr[pitch]; // b2[x  ,y+1]

            b2_6 = b2_5;          // b2[x+1,y+1] = b2[x,y+1]

        }

        if (num_bands > 3) {

            b3_2 = b3_ptr[back_pitch]; // b3[x  ,y-1]

            b3_3 = b3_2;               // b3[x+1,y-1] = b3[x  ,y-1]

            b3_5 = b3_ptr[0];          // b3[x  ,y  ]

            b3_6 = b3_5;               // b3[x+1,y  ] = b3[x  ,y  ]

            b3_8 = b3_2 - b3_5*6 + b3_ptr[pitch];

            b3_9 = b3_8;

        }

        for (x = 0, indx = 0; x < plane->width; x+=2, indx++) {

            /* some values calculated in the previous iterations can */

            /* be reused in the next ones, so do appropriate copying */

            b2_1 = b2_2; // b2[x-1,y  ] = b2[x,  y  ]

            b2_2 = b2_3; // b2[x  ,y  ] = b2[x+1,y  ]

            b2_4 = b2_5; // b2[x-1,y+1] = b2[x  ,y+1]

            b2_5 = b2_6; // b2[x  ,y+1] = b2[x+1,y+1]

            b3_1 = b3_2; // b3[x-1,y-1] = b3[x  ,y-1]

            b3_2 = b3_3; // b3[x  ,y-1] = b3[x+1,y-1]

            b3_4 = b3_5; // b3[x-1,y  ] = b3[x  ,y  ]

            b3_5 = b3_6; // b3[x  ,y  ] = b3[x+1,y  ]

            b3_7 = b3_8; // vert_HPF(x-1)

            b3_8 = b3_9; // vert_HPF(x  )

            p0 = p1 = p2 = p3 = 0;

            /* process the LL-band by applying LPF both vertically and horizontally */

            if (num_bands > 0) {

                tmp0 = b0_1;

                tmp2 = b0_2;

                b0_1 = b0_ptr[indx+1];

                b0_2 = b0_ptr[pitch+indx+1];

                tmp1 = tmp0 + b0_1;

                p0 =  tmp0 << 4;

                p1 =  tmp1 << 3;

                p2 = (tmp0 + tmp2) << 3;

                p3 = (tmp1 + tmp2 + b0_2) << 2;

            }

            /* process the HL-band by applying HPF vertically and LPF horizontally */

            if (num_bands > 1) {

                tmp0 = b1_2;

                tmp1 = b1_1;

                b1_2 = b1_ptr[indx+1];

                b1_1 = b1_ptr[back_pitch+indx+1];

                tmp2 = tmp1 - tmp0*6 + b1_3;

                b1_3 = b1_1 - b1_2*6 + b1_ptr[pitch+indx+1];

                p0 += (tmp0 + tmp1) << 3;

                p1 += (tmp0 + tmp1 + b1_1 + b1_2) << 2;

                p2 +=  tmp2 << 2;

                p3 += (tmp2 + b1_3) << 1;

            }

            /* process the LH-band by applying LPF vertically and HPF horizontally */

            if (num_bands > 2) {

                b2_3 = b2_ptr[indx+1];

                b2_6 = b2_ptr[pitch+indx+1];

                tmp0 = b2_1 + b2_2;

                tmp1 = b2_1 - b2_2*6 + b2_3;

                p0 += tmp0 << 3;

                p1 += tmp1 << 2;

                p2 += (tmp0 + b2_4 + b2_5) << 2;

                p3 += (tmp1 + b2_4 - b2_5*6 + b2_6) << 1;

            }

            /* process the HH-band by applying HPF both vertically and horizontally */

            if (num_bands > 3) {

                b3_6 = b3_ptr[indx+1];            // b3[x+1,y  ]

                b3_3 = b3_ptr[back_pitch+indx+1]; // b3[x+1,y-1]

                tmp0 = b3_1 + b3_4;

                tmp1 = b3_2 + b3_5;

                tmp2 = b3_3 + b3_6;

                b3_9 = b3_3 - b3_6*6 + b3_ptr[pitch+indx+1];

                p0 += (tmp0 + tmp1) << 2;

                p1 += (tmp0 - tmp1*6 + tmp2) << 1;

                p2 += (b3_7 + b3_8) << 1;

                p3 +=  b3_7 - b3_8*6 + b3_9;

            }

            /* output four pixels */

            dst[x]             = av_clip_uint8((p0 >> 6) + 128);

            dst[x+1]           = av_clip_uint8((p1 >> 6) + 128);

            dst[dst_pitch+x]   = av_clip_uint8((p2 >> 6) + 128);

            dst[dst_pitch+x+1] = av_clip_uint8((p3 >> 6) + 128);

        }// for x

        dst += dst_pitch << 1;

        back_pitch = -pitch;

        b0_ptr += pitch;

        b1_ptr += pitch;

        b2_ptr += pitch;

        b3_ptr += pitch;

    }

}


void select_soundhw(const char *optarg)

{

    struct soundhw *c;

    if (*optarg == '?') {

    show_valid_cards:

        printf("Valid sound card names (comma separated):\n");

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

            printf ("%-11s %s\n", c->name, c->descr);

        }

        printf("\n-soundhw all will enable all of the above\n");

        exit(*optarg != '?');

    }

    else {

        size_t l;

        const char *p;

        char *e;

        int bad_card = 0;

        if (!strcmp(optarg, "all")) {

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

                c->enabled = 1;

            }

            return;

        }

        p = optarg;

        while (*p) {

            e = strchr(p, ',');

            l = !e ? strlen(p) : (size_t) (e - p);

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

                if (!strncmp(c->name, p, l) && !c->name[l]) {

                    c->enabled = 1;

                    break;

                }

            }

            if (!c->name) {

                if (l > 80) {

                    fprintf(stderr,

                            "Unknown sound card name (too big to show)\n");

                }

                else {

                    fprintf(stderr, "Unknown sound card name `%.*s'\n",

                            (int) l, p);

                }

                bad_card = 1;

            }

            p += l + (e != NULL);

        }

        if (bad_card) {

            goto show_valid_cards;

        }

    }

}


int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){

    AVPacketList *pktl;

    int stream_count=0, noninterleaved_count=0;

    int64_t delta_dts_max = 0;

    int i;

    if(pkt){

        ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);

    }

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

        if (s->streams[i]->last_in_packet_buffer) {

            ++stream_count;

        } else if(s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {

            ++noninterleaved_count;

        }

    }

    if (s->nb_streams == stream_count) {

        flush = 1;

    } else if (!flush){

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

            if (s->streams[i]->last_in_packet_buffer) {

                int64_t delta_dts =

                    av_rescale_q(s->streams[i]->last_in_packet_buffer->pkt.dts,

                                s->streams[i]->time_base,

                                AV_TIME_BASE_Q) -

                    av_rescale_q(s->packet_buffer->pkt.dts,

                                s->streams[s->packet_buffer->pkt.stream_index]->time_base,

                                AV_TIME_BASE_Q);

                delta_dts_max= FFMAX(delta_dts_max, delta_dts);

            }

        }

        if(s->nb_streams == stream_count+noninterleaved_count &&

           delta_dts_max > 20*AV_TIME_BASE) {

            av_log(s, AV_LOG_DEBUG, "flushing with %d noninterleaved\n", noninterleaved_count);

            flush = 1;

        }

    }

    if(stream_count && flush){

        pktl= s->packet_buffer;

        *out= pktl->pkt;

        s->packet_buffer= pktl->next;

        if(!s->packet_buffer)

            s->packet_buffer_end= NULL;

        if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)

            s->streams[out->stream_index]->last_in_packet_buffer= NULL;

        av_freep(&pktl);

        return 1;

    }else{

        av_init_packet(out);

        return 0;

    }

}


static int read_header(AVFormatContext *s)

{

    WtvContext *wtv = s->priv_data;

    int root_sector, root_size;

    uint8_t root[WTV_SECTOR_SIZE];

    AVIOContext *pb;

    int64_t timeline_pos;

    int64_t ret;

    wtv->epoch          =

    wtv->pts            =

    wtv->last_valid_pts = AV_NOPTS_VALUE;

    /* read root directory sector */

    avio_skip(s->pb, 0x30);

    root_size = avio_rl32(s->pb);

    if (root_size > sizeof(root)) {

        av_log(s, AV_LOG_ERROR, "root directory size exceeds sector size\n");

        return AVERROR_INVALIDDATA;

    }

    avio_skip(s->pb, 4);

    root_sector = avio_rl32(s->pb);

    ret = seek_by_sector(s->pb, root_sector, 0);

    if (ret < 0)

        return ret;

    root_size = avio_read(s->pb, root, root_size);

    if (root_size < 0)

        return AVERROR_INVALIDDATA;

    /* parse chunks up until first data chunk */

    wtv->pb = wtvfile_open(s, root, root_size, ff_timeline_le16);

    if (!wtv->pb) {

        av_log(s, AV_LOG_ERROR, "timeline data missing\n");

        return AVERROR_INVALIDDATA;

    }

    ret = parse_chunks(s, SEEK_TO_DATA, 0, 0);

    if (ret < 0)

        return ret;

    avio_seek(wtv->pb, -32, SEEK_CUR);

    timeline_pos = avio_tell(s->pb); // save before opening another file

    /* read metadata */

    pb = wtvfile_open(s, root, root_size, ff_table_0_entries_legacy_attrib_le16);

    if (pb) {

        parse_legacy_attrib(s, pb);

        wtvfile_close(pb);

    }

    s->ctx_flags |= AVFMTCTX_NOHEADER; // Needed for noStreams.wtv

    /* read seek index */

    if (s->nb_streams) {

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

        pb = wtvfile_open(s, root, root_size, ff_table_0_entries_time_le16);

        if (pb) {

            while(1) {

                uint64_t timestamp = avio_rl64(pb);

                uint64_t frame_nb  = avio_rl64(pb);

                if (avio_feof(pb))

                    break;

                ff_add_index_entry(&wtv->index_entries, &wtv->nb_index_entries, &wtv->index_entries_allocated_size,

                                   0, timestamp, frame_nb, 0, AVINDEX_KEYFRAME);

            }

            wtvfile_close(pb);

            if (wtv->nb_index_entries) {

                pb = wtvfile_open(s, root, root_size, ff_timeline_table_0_entries_Events_le16);

                if (pb) {

                    AVIndexEntry *e = wtv->index_entries;

                    AVIndexEntry *e_end = wtv->index_entries + wtv->nb_index_entries - 1;

                    uint64_t last_position = 0;

                    while (1) {

                        uint64_t frame_nb = avio_rl64(pb);

                        uint64_t position = avio_rl64(pb);

                        while (frame_nb > e->size && e <= e_end) {

                            e->pos = last_position;

                            e++;

                        }

                        if (avio_feof(pb))

                            break;

                        last_position = position;

                    }

                    e_end->pos = last_position;

                    wtvfile_close(pb);

                    st->duration = e_end->timestamp;

                }

            }

        }

    }

    avio_seek(s->pb, timeline_pos, SEEK_SET);

    return 0;

}


SwsVector *sws_getGaussianVec(double variance, double quality)

{

    const int length = (int)(variance * quality + 0.5) | 1;

    int i;

    double middle  = (length - 1) * 0.5;

    SwsVector *vec = sws_allocVec(length);

    if (!vec)

        return NULL;

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

        double dist = i - middle;

        vec->coeff[i] = exp(-dist * dist / (2 * variance * variance)) /

                        sqrt(2 * variance * M_PI);

    }

    sws_normalizeVec(vec, 1.0);

    return vec;

}


static void h261_h_loop_filter_c(uint8_t *dest,uint8_t *src, int stride){

    int i,j,xy,yz;

    int res;

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

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

            xy = j * stride + i;

            yz = j * 8 + i;

            res = (int)src[yz-1] + ((int)(src[yz]) *2) + (int)src[yz+1];

            res+=2;

            res>>=2;

            dest[xy] = (uint8_t)res;

        }

    }

}


PcGuestInfo *pc_guest_info_init(ram_addr_t below_4g_mem_size,

                                ram_addr_t above_4g_mem_size)

{

    PcGuestInfoState *guest_info_state = g_malloc0(sizeof *guest_info_state);

    PcGuestInfo *guest_info = &guest_info_state->info;

    guest_info->pci_info.w32.end = IO_APIC_DEFAULT_ADDRESS;

    if (sizeof(hwaddr) == 4) {

        guest_info->pci_info.w64.begin = 0;

        guest_info->pci_info.w64.end = 0;

    } else {

        /*

         * BIOS does not set MTRR entries for the 64 bit window, so no need to

         * align address to power of two.  Align address at 1G, this makes sure

         * it can be exactly covered with a PAT entry even when using huge

         * pages.

         */

        guest_info->pci_info.w64.begin =

            ROUND_UP((0x1ULL << 32) + above_4g_mem_size, 0x1ULL << 30);

        guest_info->pci_info.w64.end = guest_info->pci_info.w64.begin +

            (0x1ULL << 62);

        assert(guest_info->pci_info.w64.begin <= guest_info->pci_info.w64.end);

    }

    guest_info_state->machine_done.notify = pc_guest_info_machine_done;

    qemu_add_machine_init_done_notifier(&guest_info_state->machine_done);

    return guest_info;

}


static void escaped_string(void)

{

    int i;

    struct {

        const char *encoded;

        const char *decoded;

        int skip;

    } test_cases[] = {

        { "\"\\b\"", "\b" },

        { "\"\\f\"", "\f" },

        { "\"\\n\"", "\n" },

        { "\"\\r\"", "\r" },

        { "\"\\t\"", "\t" },

        { "\"/\"", "/" },

        { "\"\\/\"", "/", .skip = 1 },

        { "\"\\\\\"", "\\" },

        { "\"\\\"\"", "\"" },

        { "\"hello world \\\"embedded string\\\"\"",

          "hello world \"embedded string\"" },

        { "\"hello world\\nwith new line\"", "hello world\nwith new line" },

        { "\"single byte utf-8 \\u0020\"", "single byte utf-8  ", .skip = 1 },

        { "\"double byte utf-8 \\u00A2\"", "double byte utf-8 \xc2\xa2" },

        { "\"triple byte utf-8 \\u20AC\"", "triple byte utf-8 \xe2\x82\xac" },

        { "'\\b'", "\b", .skip = 1 },

        { "'\\f'", "\f", .skip = 1 },

        { "'\\n'", "\n", .skip = 1 },

        { "'\\r'", "\r", .skip = 1 },

        { "'\\t'", "\t", .skip = 1 },

        { "'\\/'", "/", .skip = 1 },

        { "'\\\\'", "\\", .skip = 1 },

        {}

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QString *str;

        obj = qobject_from_json(test_cases[i].encoded, NULL);

        str = qobject_to_qstring(obj);

        g_assert(str);

        g_assert_cmpstr(qstring_get_str(str), ==, test_cases[i].decoded);

        if (test_cases[i].skip == 0) {

            str = qobject_to_json(obj);

            g_assert_cmpstr(qstring_get_str(str), ==, test_cases[i].encoded);

            qobject_decref(obj);

        }

        QDECREF(str);

    }

}


ogg_read_header (AVFormatContext * s, AVFormatParameters * ap)
{
    struct ogg *ogg = s->priv_data;
    ogg->curidx = -1;
    //linear headers seek from start
    if (ogg_get_headers (s) < 0){
        return -1;
    }
    //linear granulepos seek from end
    ogg_get_length (s);
    //fill the extradata in the per codec callbacks
    return 0;
}


static void print_net_client(Monitor *mon, VLANClientState *vc)

{

    monitor_printf(mon, "%s: type=%s,%s\n", vc->name,

                   net_client_types[vc->info->type].type, vc->info_str);

}


static int apng_read_close(AVFormatContext *s)

{

    APNGDemuxContext *ctx = s->priv_data;

    av_freep(&ctx->extra_data);

    ctx->extra_data_size = 0;

    return 0;

}


static void br(DisasContext *dc, uint32_t code, uint32_t flags)

{

    I_TYPE(instr, code);

    gen_goto_tb(dc, 0, dc->pc + 4 + (instr.imm16s & -4));

    dc->is_jmp = DISAS_TB_JUMP;

}


static int dnxhd_write_header(AVCodecContext *avctx, uint8_t *buf)
{
    DNXHDEncContext *ctx = avctx->priv_data;
    const uint8_t header_prefix[5] = { 0x00,0x00,0x02,0x80,0x01 };
    memcpy(buf, header_prefix, 5);
    buf[5] = ctx->interlaced ? ctx->cur_field+2 : 0x01;
    buf[6] = 0x80; // crc flag off
    buf[7] = 0xa0; // reserved
    AV_WB16(buf + 0x18, avctx->height); // ALPF
    AV_WB16(buf + 0x1a, avctx->width);  // SPL
    AV_WB16(buf + 0x1d, avctx->height); // NAL
    buf[0x21] = 0x38; // FIXME 8 bit per comp
    buf[0x22] = 0x88 + (ctx->frame.interlaced_frame<<2);
    AV_WB32(buf + 0x28, ctx->cid); // CID
    buf[0x2c] = ctx->interlaced ? 0 : 0x80;
    buf[0x5f] = 0x01; // UDL
    buf[0x167] = 0x02; // reserved
    AV_WB16(buf + 0x16a, ctx->m.mb_height * 4 + 4); // MSIPS
    buf[0x16d] = ctx->m.mb_height; // Ns
    buf[0x16f] = 0x10; // reserved
    ctx->msip = buf + 0x170;
    return 0;
}


static int slirp_smb(SlirpState* s, const char *exported_dir,

                     struct in_addr vserver_addr)

{

    static int instance;

    char smb_conf[128];

    char smb_cmdline[128];

    FILE *f;

    snprintf(s->smb_dir, sizeof(s->smb_dir), "/tmp/qemu-smb.%ld-%d",

             (long)getpid(), instance++);

    if (mkdir(s->smb_dir, 0700) < 0) {

        error_report("could not create samba server dir '%s'", s->smb_dir);

        return -1;

    }

    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", s->smb_dir, "smb.conf");

    f = fopen(smb_conf, "w");

    if (!f) {

        slirp_smb_cleanup(s);

        error_report("could not create samba server configuration file '%s'",

                     smb_conf);

        return -1;

    }

    fprintf(f,

            "[global]\n"

            "private dir=%s\n"

            "socket address=127.0.0.1\n"

            "pid directory=%s\n"

            "lock directory=%s\n"

            "state directory=%s\n"

            "log file=%s/log.smbd\n"

            "smb passwd file=%s/smbpasswd\n"

            "security = share\n"

            "[qemu]\n"

            "path=%s\n"

            "read only=no\n"

            "guest ok=yes\n",

            exported_dir

            );

    fclose(f);

    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",

             CONFIG_SMBD_COMMAND, smb_conf);

    if (slirp_add_exec(s->slirp, 0, smb_cmdline, &vserver_addr, 139) < 0) {

        slirp_smb_cleanup(s);

        error_report("conflicting/invalid smbserver address");

        return -1;

    }

    return 0;

}


static int write_memory(DumpState *s, RAMBlock *block, ram_addr_t start,

                        int64_t size)

{

    int64_t i;

    int ret;

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

        ret = write_data(s, block->host + start + i * TARGET_PAGE_SIZE,

                         TARGET_PAGE_SIZE);

        if (ret < 0) {

            return ret;

        }

    }

    if ((size % TARGET_PAGE_SIZE) != 0) {

        ret = write_data(s, block->host + start + i * TARGET_PAGE_SIZE,

                         size % TARGET_PAGE_SIZE);

        if (ret < 0) {

            return ret;

        }

    }

    return 0;

}


static int rtmp_handshake(URLContext *s, RTMPContext *rt)
{
    AVLFG rnd;
    uint8_t tosend    [RTMP_HANDSHAKE_PACKET_SIZE+1] = {
        3,                // unencrypted data
        0, 0, 0, 0,       // client uptime
        RTMP_CLIENT_VER1,
        RTMP_CLIENT_VER2,
        RTMP_CLIENT_VER3,
        RTMP_CLIENT_VER4,
    };
    uint8_t clientdata[RTMP_HANDSHAKE_PACKET_SIZE];
    uint8_t serverdata[RTMP_HANDSHAKE_PACKET_SIZE+1];
    int i;
    int server_pos, client_pos;
    uint8_t digest[32], signature[32];
    int ret, type = 0;
    av_log(s, AV_LOG_DEBUG, "Handshaking...\n");
    av_lfg_init(&rnd, 0xDEADC0DE);
    // generate handshake packet - 1536 bytes of pseudorandom data
    for (i = 9; i <= RTMP_HANDSHAKE_PACKET_SIZE; i++)
        tosend[i] = av_lfg_get(&rnd) >> 24;
    if (rt->encrypted && CONFIG_FFRTMPCRYPT_PROTOCOL) {
        /* When the client wants to use RTMPE, we have to change the command
         * byte to 0x06 which means to use encrypted data and we have to set
         * the flash version to at least 9.0.115.0. */
        tosend[0] = 6;
        tosend[5] = 128;
        tosend[6] = 0;
        tosend[7] = 3;
        tosend[8] = 2;
        /* Initialize the Diffie-Hellmann context and generate the public key
         * to send to the server. */
        if ((ret = ff_rtmpe_gen_pub_key(rt->stream, tosend + 1)) < 0)
    client_pos = rtmp_handshake_imprint_with_digest(tosend + 1, rt->encrypted);
    if (client_pos < 0)
        return client_pos;
    if ((ret = ffurl_write(rt->stream, tosend,
                           RTMP_HANDSHAKE_PACKET_SIZE + 1)) < 0) {
        av_log(s, AV_LOG_ERROR, "Cannot write RTMP handshake request\n");
    if ((ret = ffurl_read_complete(rt->stream, serverdata,
                                   RTMP_HANDSHAKE_PACKET_SIZE + 1)) < 0) {
        av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
    if ((ret = ffurl_read_complete(rt->stream, clientdata,
                                   RTMP_HANDSHAKE_PACKET_SIZE)) < 0) {
        av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
    av_log(s, AV_LOG_DEBUG, "Type answer %d\n", serverdata[0]);
    av_log(s, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n",
           serverdata[5], serverdata[6], serverdata[7], serverdata[8]);
    if (rt->is_input && serverdata[5] >= 3) {
        server_pos = rtmp_validate_digest(serverdata + 1, 772);
        if (server_pos < 0)
            return server_pos;
        if (!server_pos) {
            type = 1;
            server_pos = rtmp_validate_digest(serverdata + 1, 8);
            if (server_pos < 0)
                return server_pos;
            if (!server_pos) {
                av_log(s, AV_LOG_ERROR, "Server response validating failed\n");
                return AVERROR(EIO);
        ret = ff_rtmp_calc_digest(tosend + 1 + client_pos, 32, 0,
                                  rtmp_server_key, sizeof(rtmp_server_key),
                                  digest);
        if (ret < 0)
        ret = ff_rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE - 32,
                                  0, digest, 32, signature);
        if (ret < 0)
        if (rt->encrypted && CONFIG_FFRTMPCRYPT_PROTOCOL) {
            /* Compute the shared secret key sent by the server and initialize
             * the RC4 encryption. */
            if ((ret = ff_rtmpe_compute_secret_key(rt->stream, serverdata + 1,
                                                   tosend + 1, type)) < 0)
            /* Encrypt the signature received by the server. */
            ff_rtmpe_encrypt_sig(rt->stream, signature, digest, serverdata[0]);
        if (memcmp(signature, clientdata + RTMP_HANDSHAKE_PACKET_SIZE - 32, 32)) {
            av_log(s, AV_LOG_ERROR, "Signature mismatch\n");
            return AVERROR(EIO);
        for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++)
            tosend[i] = av_lfg_get(&rnd) >> 24;
        ret = ff_rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0,
                                  rtmp_player_key, sizeof(rtmp_player_key),
                                  digest);
        if (ret < 0)
        ret = ff_rtmp_calc_digest(tosend, RTMP_HANDSHAKE_PACKET_SIZE - 32, 0,
                                  digest, 32,
                                  tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
        if (ret < 0)
        if (rt->encrypted && CONFIG_FFRTMPCRYPT_PROTOCOL) {
            /* Encrypt the signature to be send to the server. */
            ff_rtmpe_encrypt_sig(rt->stream, tosend +
                                 RTMP_HANDSHAKE_PACKET_SIZE - 32, digest,
                                 serverdata[0]);
        // write reply back to the server
        if ((ret = ffurl_write(rt->stream, tosend,
                               RTMP_HANDSHAKE_PACKET_SIZE)) < 0)
        if (rt->encrypted && CONFIG_FFRTMPCRYPT_PROTOCOL) {
            /* Set RC4 keys for encryption and update the keystreams. */
            if ((ret = ff_rtmpe_update_keystream(rt->stream)) < 0)
    } else {
        if (rt->encrypted && CONFIG_FFRTMPCRYPT_PROTOCOL) {
            /* Compute the shared secret key sent by the server and initialize
             * the RC4 encryption. */
            if ((ret = ff_rtmpe_compute_secret_key(rt->stream, serverdata + 1,
                            tosend + 1, 1)) < 0)
            if (serverdata[0] == 9) {
                /* Encrypt the signature received by the server. */
                ff_rtmpe_encrypt_sig(rt->stream, signature, digest,
                                     serverdata[0]);
        if ((ret = ffurl_write(rt->stream, serverdata + 1,
                               RTMP_HANDSHAKE_PACKET_SIZE)) < 0)
        if (rt->encrypted && CONFIG_FFRTMPCRYPT_PROTOCOL) {
            /* Set RC4 keys for encryption and update the keystreams. */
            if ((ret = ff_rtmpe_update_keystream(rt->stream)) < 0)
    return 0;


static int qemu_rdma_reg_control(RDMAContext *rdma, int idx)

{

    rdma->wr_data[idx].control_mr = ibv_reg_mr(rdma->pd,

            rdma->wr_data[idx].control, RDMA_CONTROL_MAX_BUFFER,

            IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);

    if (rdma->wr_data[idx].control_mr) {

        rdma->total_registrations++;

        return 0;

    }

    fprintf(stderr, "qemu_rdma_reg_control failed!\n");

    return -1;

}


static hwaddr ppc_hash64_pteg_search(PowerPCCPU *cpu, hwaddr hash,

                                     ppc_slb_t *slb, bool secondary,

                                     target_ulong ptem, ppc_hash_pte64_t *pte)

{

    CPUPPCState *env = &cpu->env;

    int i;

    uint64_t token;

    target_ulong pte0, pte1;

    target_ulong pte_index;

    pte_index = (hash & env->htab_mask) * HPTES_PER_GROUP;

    token = ppc_hash64_start_access(cpu, pte_index);

    if (!token) {

        return -1;

    }

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

        pte0 = ppc_hash64_load_hpte0(cpu, token, i);

        pte1 = ppc_hash64_load_hpte1(cpu, token, i);

        if ((pte0 & HPTE64_V_VALID)

            && (secondary == !!(pte0 & HPTE64_V_SECONDARY))

            && HPTE64_V_COMPARE(pte0, ptem)) {

            unsigned pshift = hpte_page_shift(slb->sps, pte0, pte1);

            /*

             * If there is no match, ignore the PTE, it could simply

             * be for a different segment size encoding and the

             * architecture specifies we should not match. Linux will

             * potentially leave behind PTEs for the wrong base page

             * size when demoting segments.

             */

            if (pshift == 0) {

                continue;

            }

            /* We don't do anything with pshift yet as qemu TLB only deals

             * with 4K pages anyway

             */

            pte->pte0 = pte0;

            pte->pte1 = pte1;

            ppc_hash64_stop_access(cpu, token);

            return (pte_index + i) * HASH_PTE_SIZE_64;

        }

    }

    ppc_hash64_stop_access(cpu, token);

    /*

     * We didn't find a valid entry.

     */

    return -1;

}


static int vmdk_write_extent(VmdkExtent *extent, int64_t cluster_offset,

                            int64_t offset_in_cluster, const uint8_t *buf,

                            int nb_sectors, int64_t sector_num)

{

    int ret;

    VmdkGrainMarker *data = NULL;

    uLongf buf_len;

    const uint8_t *write_buf = buf;

    int write_len = nb_sectors * 512;

    if (extent->compressed) {

        if (!extent->has_marker) {

            ret = -EINVAL;

            goto out;

        }

        buf_len = (extent->cluster_sectors << 9) * 2;

        data = g_malloc(buf_len + sizeof(VmdkGrainMarker));

        if (compress(data->data, &buf_len, buf, nb_sectors << 9) != Z_OK ||

                buf_len == 0) {

            ret = -EINVAL;

            goto out;

        }

        data->lba = sector_num;

        data->size = buf_len;

        write_buf = (uint8_t *)data;

        write_len = buf_len + sizeof(VmdkGrainMarker);

    }

    ret = bdrv_pwrite(extent->file,

                        cluster_offset + offset_in_cluster,

                        write_buf,

                        write_len);

    if (ret != write_len) {

        ret = ret < 0 ? ret : -EIO;

        goto out;

    }

    ret = 0;

 out:

    g_free(data);

    return ret;

}


int ff_scale_eval_dimensions(void *log_ctx,

    const char *w_expr, const char *h_expr,

    AVFilterLink *inlink, AVFilterLink *outlink,

    int *ret_w, int *ret_h)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);

    const AVPixFmtDescriptor *out_desc = av_pix_fmt_desc_get(outlink->format);

    const char *expr;

    int w, h;

    int factor_w, factor_h;

    int eval_w, eval_h;

    int ret;

    const char scale2ref = outlink->src->nb_inputs == 2 && outlink->src->inputs[1] == inlink;

    double var_values[VARS_NB + VARS_S2R_NB], res;

    const AVPixFmtDescriptor *main_desc;

    const AVFilterLink *main_link;

    const char *const *names = scale2ref ? var_names_scale2ref : var_names;

    if (scale2ref) {

        main_link = outlink->src->inputs[0];

        main_desc = av_pix_fmt_desc_get(main_link->format);

    }

    var_values[VAR_PI]    = M_PI;

    var_values[VAR_PHI]   = M_PHI;

    var_values[VAR_E]     = M_E;

    var_values[VAR_IN_W]  = var_values[VAR_IW] = inlink->w;

    var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;

    var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;

    var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;

    var_values[VAR_A]     = (double) inlink->w / inlink->h;

    var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?

        (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;

    var_values[VAR_DAR]   = var_values[VAR_A] * var_values[VAR_SAR];

    var_values[VAR_HSUB]  = 1 << desc->log2_chroma_w;

    var_values[VAR_VSUB]  = 1 << desc->log2_chroma_h;

    var_values[VAR_OHSUB] = 1 << out_desc->log2_chroma_w;

    var_values[VAR_OVSUB] = 1 << out_desc->log2_chroma_h;

    if (scale2ref) {

        var_values[VARS_NB + VAR_S2R_MAIN_W] = main_link->w;

        var_values[VARS_NB + VAR_S2R_MAIN_H] = main_link->h;

        var_values[VARS_NB + VAR_S2R_MAIN_A] = (double) main_link->w / main_link->h;

        var_values[VARS_NB + VAR_S2R_MAIN_SAR] = main_link->sample_aspect_ratio.num ?

            (double) main_link->sample_aspect_ratio.num / main_link->sample_aspect_ratio.den : 1;

        var_values[VARS_NB + VAR_S2R_MAIN_DAR] = var_values[VARS_NB + VAR_S2R_MDAR] =

            var_values[VARS_NB + VAR_S2R_MAIN_A] * var_values[VARS_NB + VAR_S2R_MAIN_SAR];

        var_values[VARS_NB + VAR_S2R_MAIN_HSUB] = 1 << main_desc->log2_chroma_w;

        var_values[VARS_NB + VAR_S2R_MAIN_VSUB] = 1 << main_desc->log2_chroma_h;

    }

    /* evaluate width and height */

    av_expr_parse_and_eval(&res, (expr = w_expr),

                           names, var_values,

                           NULL, NULL, NULL, NULL, NULL, 0, log_ctx);

    eval_w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;

    if ((ret = av_expr_parse_and_eval(&res, (expr = h_expr),

                                      names, var_values,

                                      NULL, NULL, NULL, NULL, NULL, 0, log_ctx)) < 0)

        goto fail;

    eval_h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res;

    /* evaluate again the width, as it may depend on the output height */

    if ((ret = av_expr_parse_and_eval(&res, (expr = w_expr),

                                      names, var_values,

                                      NULL, NULL, NULL, NULL, NULL, 0, log_ctx)) < 0)

        goto fail;

    eval_w = res;

    w = eval_w;

    h = eval_h;

    /* Check if it is requested that the result has to be divisible by a some

     * factor (w or h = -n with n being the factor). */

    factor_w = 1;

    factor_h = 1;

    if (w < -1) {

        factor_w = -w;

    }

    if (h < -1) {

        factor_h = -h;

    }

    if (w < 0 && h < 0)

        eval_w = eval_h = 0;

    if (!(w = eval_w))

        w = inlink->w;

    if (!(h = eval_h))

        h = inlink->h;

    /* Make sure that the result is divisible by the factor we determined

     * earlier. If no factor was set, it is nothing will happen as the default

     * factor is 1 */

    if (w < 0)

        w = av_rescale(h, inlink->w, inlink->h * factor_w) * factor_w;

    if (h < 0)

        h = av_rescale(w, inlink->h, inlink->w * factor_h) * factor_h;

    *ret_w = w;

    *ret_h = h;

    return 0;

fail:

    av_log(log_ctx, AV_LOG_ERROR,

           "Error when evaluating the expression '%s'.\n"

           "Maybe the expression for out_w:'%s' or for out_h:'%s' is self-referencing.\n",

           expr, w_expr, h_expr);

    return ret;

}


static int adpcm_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            const uint8_t *buf, int buf_size)

{

    ADPCMContext *c = avctx->priv_data;

    ADPCMChannelStatus *cs;

    int n, m, channel, i;

    int block_predictor[2];

    short *samples;

    short *samples_end;

    const uint8_t *src;

    int st; /* stereo */

    /* DK3 ADPCM accounting variables */

    unsigned char last_byte = 0;

    unsigned char nibble;

    int decode_top_nibble_next = 0;

    int diff_channel;

    /* EA ADPCM state variables */

    uint32_t samples_in_chunk;

    int32_t previous_left_sample, previous_right_sample;

    int32_t current_left_sample, current_right_sample;

    int32_t next_left_sample, next_right_sample;

    int32_t coeff1l, coeff2l, coeff1r, coeff2r;

    uint8_t shift_left, shift_right;

    int count1, count2;

    int coeff[2][2], shift[2];//used in EA MAXIS ADPCM

    if (!buf_size)

        return 0;

    //should protect all 4bit ADPCM variants

    //8 is needed for CODEC_ID_ADPCM_IMA_WAV with 2 channels

    //

    if(*data_size/4 < buf_size + 8)

        return -1;

    samples = data;

    samples_end= samples + *data_size/2;

    *data_size= 0;

    src = buf;

    st = avctx->channels == 2 ? 1 : 0;

    switch(avctx->codec->id) {

    case CODEC_ID_ADPCM_IMA_QT:

        n = (buf_size - 2);/* >> 2*avctx->channels;*/

        channel = c->channel;

        cs = &(c->status[channel]);

        /* (pppppp) (piiiiiii) */

        /* Bits 15-7 are the _top_ 9 bits of the 16-bit initial predictor value */

        cs->predictor = (*src++) << 8;

        cs->predictor |= (*src & 0x80);

        cs->predictor &= 0xFF80;

        /* sign extension */

        if(cs->predictor & 0x8000)

            cs->predictor -= 0x10000;

        cs->predictor = av_clip_int16(cs->predictor);

        cs->step_index = (*src++) & 0x7F;

        if (cs->step_index > 88){

            av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);

            cs->step_index = 88;

        }

        cs->step = step_table[cs->step_index];

        if (st && channel)

            samples++;

        for(m=32; n>0 && m>0; n--, m--) { /* in QuickTime, IMA is encoded by chuncks of 34 bytes (=64 samples) */

            *samples = adpcm_ima_expand_nibble(cs, src[0] & 0x0F, 3);

            samples += avctx->channels;

            *samples = adpcm_ima_expand_nibble(cs, src[0] >> 4  , 3);

            samples += avctx->channels;

            src ++;

        }

        if(st) { /* handle stereo interlacing */

            c->channel = (channel + 1) % 2; /* we get one packet for left, then one for right data */

            if(!channel) { /* wait for the other packet before outputing anything */

                return src - buf;

            }

            samples--;

        }

        break;

    case CODEC_ID_ADPCM_IMA_WAV:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

//        samples_per_block= (block_align-4*chanels)*8 / (bits_per_sample * chanels) + 1;

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

            cs = &(c->status[i]);

            cs->predictor = *samples++ = (int16_t)(src[0] + (src[1]<<8));

            src+=2;

            cs->step_index = *src++;

            if (cs->step_index > 88){

                av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);

                cs->step_index = 88;

            }

            if (*src++) av_log(avctx, AV_LOG_ERROR, "unused byte should be null but is %d!!\n", src[-1]); /* unused */

        }

        while(src < buf + buf_size){

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

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

                    *samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] & 0x0F, 3);

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

                    *samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] >> 4  , 3);

                src++;

            }

            src += 4*st;

        }

        break;

    case CODEC_ID_ADPCM_4XM:

        cs = &(c->status[0]);

        c->status[0].predictor= (int16_t)(src[0] + (src[1]<<8)); src+=2;

        if(st){

            c->status[1].predictor= (int16_t)(src[0] + (src[1]<<8)); src+=2;

        }

        c->status[0].step_index= (int16_t)(src[0] + (src[1]<<8)); src+=2;

        if(st){

            c->status[1].step_index= (int16_t)(src[0] + (src[1]<<8)); src+=2;

        }

        if (cs->step_index < 0) cs->step_index = 0;

        if (cs->step_index > 88) cs->step_index = 88;

        m= (buf_size - (src - buf))>>st;

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

            *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] & 0x0F, 4);

            if (st)

                *samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] & 0x0F, 4);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] >> 4, 4);

            if (st)

                *samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] >> 4, 4);

        }

        src += m<<st;

        break;

    case CODEC_ID_ADPCM_MS:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        n = buf_size - 7 * avctx->channels;

        if (n < 0)

            return -1;

        block_predictor[0] = av_clip(*src++, 0, 7);

        block_predictor[1] = 0;

        if (st)

            block_predictor[1] = av_clip(*src++, 0, 7);

        c->status[0].idelta = (int16_t)((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        src+=2;

        if (st){

            c->status[1].idelta = (int16_t)((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

            src+=2;

        }

        c->status[0].coeff1 = AdaptCoeff1[block_predictor[0]];

        c->status[0].coeff2 = AdaptCoeff2[block_predictor[0]];

        c->status[1].coeff1 = AdaptCoeff1[block_predictor[1]];

        c->status[1].coeff2 = AdaptCoeff2[block_predictor[1]];

        c->status[0].sample1 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        src+=2;

        if (st) c->status[1].sample1 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        if (st) src+=2;

        c->status[0].sample2 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        src+=2;

        if (st) c->status[1].sample2 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        if (st) src+=2;

        *samples++ = c->status[0].sample1;

        if (st) *samples++ = c->status[1].sample1;

        *samples++ = c->status[0].sample2;

        if (st) *samples++ = c->status[1].sample2;

        for(;n>0;n--) {

            *samples++ = adpcm_ms_expand_nibble(&c->status[0 ], src[0] >> 4  );

            *samples++ = adpcm_ms_expand_nibble(&c->status[st], src[0] & 0x0F);

            src ++;

        }

        break;

    case CODEC_ID_ADPCM_IMA_DK4:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        c->status[0].predictor = (int16_t)(src[0] | (src[1] << 8));

        c->status[0].step_index = src[2];

        src += 4;

        *samples++ = c->status[0].predictor;

        if (st) {

            c->status[1].predictor = (int16_t)(src[0] | (src[1] << 8));

            c->status[1].step_index = src[2];

            src += 4;

            *samples++ = c->status[1].predictor;

        }

        while (src < buf + buf_size) {

            /* take care of the top nibble (always left or mono channel) */

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                src[0] >> 4, 3);

            /* take care of the bottom nibble, which is right sample for

             * stereo, or another mono sample */

            if (st)

                *samples++ = adpcm_ima_expand_nibble(&c->status[1],

                    src[0] & 0x0F, 3);

            else

                *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                    src[0] & 0x0F, 3);

            src++;

        }

        break;

    case CODEC_ID_ADPCM_IMA_DK3:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        if(buf_size + 16 > (samples_end - samples)*3/8)

            return -1;

        c->status[0].predictor = (int16_t)(src[10] | (src[11] << 8));

        c->status[1].predictor = (int16_t)(src[12] | (src[13] << 8));

        c->status[0].step_index = src[14];

        c->status[1].step_index = src[15];

        /* sign extend the predictors */

        src += 16;

        diff_channel = c->status[1].predictor;

        /* the DK3_GET_NEXT_NIBBLE macro issues the break statement when

         * the buffer is consumed */

        while (1) {

            /* for this algorithm, c->status[0] is the sum channel and

             * c->status[1] is the diff channel */

            /* process the first predictor of the sum channel */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[0], nibble, 3);

            /* process the diff channel predictor */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[1], nibble, 3);

            /* process the first pair of stereo PCM samples */

            diff_channel = (diff_channel + c->status[1].predictor) / 2;

            *samples++ = c->status[0].predictor + c->status[1].predictor;

            *samples++ = c->status[0].predictor - c->status[1].predictor;

            /* process the second predictor of the sum channel */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[0], nibble, 3);

            /* process the second pair of stereo PCM samples */

            diff_channel = (diff_channel + c->status[1].predictor) / 2;

            *samples++ = c->status[0].predictor + c->status[1].predictor;

            *samples++ = c->status[0].predictor - c->status[1].predictor;

        }

        break;

    case CODEC_ID_ADPCM_IMA_WS:

        /* no per-block initialization; just start decoding the data */

        while (src < buf + buf_size) {

            if (st) {

                *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                    src[0] >> 4  , 3);

                *samples++ = adpcm_ima_expand_nibble(&c->status[1],

                    src[0] & 0x0F, 3);

            } else {

                *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                    src[0] >> 4  , 3);

                *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                    src[0] & 0x0F, 3);

            }

            src++;

        }

        break;

    case CODEC_ID_ADPCM_XA:

        while (buf_size >= 128) {

            xa_decode(samples, src, &c->status[0], &c->status[1],

                avctx->channels);

            src += 128;

            samples += 28 * 8;

            buf_size -= 128;

        }

        break;

    case CODEC_ID_ADPCM_IMA_EA_EACS:

        samples_in_chunk = bytestream_get_le32(&src) >> (1-st);

        if (samples_in_chunk > buf_size-4-(8<<st)) {

            src += buf_size - 4;

            break;

        }

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

            c->status[i].step_index = bytestream_get_le32(&src);

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

            c->status[i].predictor  = bytestream_get_le32(&src);

        for (; samples_in_chunk; samples_in_chunk--, src++) {

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],  *src>>4,   3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[st], *src&0x0F, 3);

        }

        break;

    case CODEC_ID_ADPCM_IMA_EA_SEAD:

        for (; src < buf+buf_size; src++) {

            *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[0] >> 4, 6);

            *samples++ = adpcm_ima_expand_nibble(&c->status[st],src[0]&0x0F, 6);

        }

        break;

    case CODEC_ID_ADPCM_EA:

        samples_in_chunk = AV_RL32(src);

        if (samples_in_chunk >= ((buf_size - 12) * 2)) {

            src += buf_size;

            break;

        }

        src += 4;

        current_left_sample = (int16_t)AV_RL16(src);

        src += 2;

        previous_left_sample = (int16_t)AV_RL16(src);

        src += 2;

        current_right_sample = (int16_t)AV_RL16(src);

        src += 2;

        previous_right_sample = (int16_t)AV_RL16(src);

        src += 2;

        for (count1 = 0; count1 < samples_in_chunk/28;count1++) {

            coeff1l = ea_adpcm_table[ *src >> 4       ];

            coeff2l = ea_adpcm_table[(*src >> 4  ) + 4];

            coeff1r = ea_adpcm_table[*src & 0x0F];

            coeff2r = ea_adpcm_table[(*src & 0x0F) + 4];

            src++;

            shift_left  = (*src >> 4  ) + 8;

            shift_right = (*src & 0x0F) + 8;

            src++;

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

                next_left_sample  = (int32_t)((*src & 0xF0) << 24) >> shift_left;

                next_right_sample = (int32_t)((*src & 0x0F) << 28) >> shift_right;

                src++;

                next_left_sample = (next_left_sample +

                    (current_left_sample * coeff1l) +

                    (previous_left_sample * coeff2l) + 0x80) >> 8;

                next_right_sample = (next_right_sample +

                    (current_right_sample * coeff1r) +

                    (previous_right_sample * coeff2r) + 0x80) >> 8;

                previous_left_sample = current_left_sample;

                current_left_sample = av_clip_int16(next_left_sample);

                previous_right_sample = current_right_sample;

                current_right_sample = av_clip_int16(next_right_sample);

                *samples++ = (unsigned short)current_left_sample;

                *samples++ = (unsigned short)current_right_sample;

            }

        }

        break;

    case CODEC_ID_ADPCM_EA_MAXIS_XA:

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

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

                coeff[channel][i] = ea_adpcm_table[(*src >> 4) + 4*i];

            shift[channel] = (*src & 0x0F) + 8;

            src++;

        }

        for (count1 = 0; count1 < (buf_size - avctx->channels) / avctx->channels; count1++) {

            for(i = 4; i >= 0; i-=4) { /* Pairwise samples LL RR (st) or LL LL (mono) */

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

                    int32_t sample = (int32_t)(((*(src+channel) >> i) & 0x0F) << 0x1C) >> shift[channel];

                    sample = (sample +

                             c->status[channel].sample1 * coeff[channel][0] +

                             c->status[channel].sample2 * coeff[channel][1] + 0x80) >> 8;

                    c->status[channel].sample2 = c->status[channel].sample1;

                    c->status[channel].sample1 = av_clip_int16(sample);

                    *samples++ = c->status[channel].sample1;

                }

            }

            src+=avctx->channels;

        }

        break;

    case CODEC_ID_ADPCM_EA_R1:

    case CODEC_ID_ADPCM_EA_R2:

    case CODEC_ID_ADPCM_EA_R3: {

        /* channel numbering

           2chan: 0=fl, 1=fr

           4chan: 0=fl, 1=rl, 2=fr, 3=rr

           6chan: 0=fl, 1=c,  2=fr, 3=rl,  4=rr, 5=sub */

        const int big_endian = avctx->codec->id == CODEC_ID_ADPCM_EA_R3;

        int32_t previous_sample, current_sample, next_sample;

        int32_t coeff1, coeff2;

        uint8_t shift;

        unsigned int channel;

        uint16_t *samplesC;

        const uint8_t *srcC;

        samples_in_chunk = (big_endian ? bytestream_get_be32(&src)

                                       : bytestream_get_le32(&src)) / 28;

        if (samples_in_chunk > UINT32_MAX/(28*avctx->channels) ||

            28*samples_in_chunk*avctx->channels > samples_end-samples) {

            src += buf_size - 4;

            break;

        }

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

            srcC = src + (big_endian ? bytestream_get_be32(&src)

                                     : bytestream_get_le32(&src))

                       + (avctx->channels-channel-1) * 4;

            samplesC = samples + channel;

            if (avctx->codec->id == CODEC_ID_ADPCM_EA_R1) {

                current_sample  = (int16_t)bytestream_get_le16(&srcC);

                previous_sample = (int16_t)bytestream_get_le16(&srcC);

            } else {

                current_sample  = c->status[channel].predictor;

                previous_sample = c->status[channel].prev_sample;

            }

            for (count1=0; count1<samples_in_chunk; count1++) {

                if (*srcC == 0xEE) {  /* only seen in R2 and R3 */

                    srcC++;

                    current_sample  = (int16_t)bytestream_get_be16(&srcC);

                    previous_sample = (int16_t)bytestream_get_be16(&srcC);

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

                        *samplesC = (int16_t)bytestream_get_be16(&srcC);

                        samplesC += avctx->channels;

                    }

                } else {

                    coeff1 = ea_adpcm_table[ *srcC>>4     ];

                    coeff2 = ea_adpcm_table[(*srcC>>4) + 4];

                    shift = (*srcC++ & 0x0F) + 8;

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

                        if (count2 & 1)

                            next_sample = (int32_t)((*srcC++ & 0x0F) << 28) >> shift;

                        else

                            next_sample = (int32_t)((*srcC   & 0xF0) << 24) >> shift;

                        next_sample += (current_sample  * coeff1) +

                                       (previous_sample * coeff2);

                        next_sample = av_clip_int16(next_sample >> 8);

                        previous_sample = current_sample;

                        current_sample  = next_sample;

                        *samplesC = current_sample;

                        samplesC += avctx->channels;

                    }

                }

            }

            if (avctx->codec->id != CODEC_ID_ADPCM_EA_R1) {

                c->status[channel].predictor   = current_sample;

                c->status[channel].prev_sample = previous_sample;

            }

        }

        src = src + buf_size - (4 + 4*avctx->channels);

        samples += 28 * samples_in_chunk * avctx->channels;

        break;

    }

    case CODEC_ID_ADPCM_EA_XAS:

        if (samples_end-samples < 32*4*avctx->channels

            || buf_size < (4+15)*4*avctx->channels) {

            src += buf_size;

            break;

        }

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

            int coeff[2][4], shift[4];

            short *s2, *s = &samples[channel];

            for (n=0; n<4; n++, s+=32*avctx->channels) {

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

                    coeff[i][n] = ea_adpcm_table[(src[0]&0x0F)+4*i];

                shift[n] = (src[2]&0x0F) + 8;

                for (s2=s, i=0; i<2; i++, src+=2, s2+=avctx->channels)

                    s2[0] = (src[0]&0xF0) + (src[1]<<8);

            }

            for (m=2; m<32; m+=2) {

                s = &samples[m*avctx->channels + channel];

                for (n=0; n<4; n++, src++, s+=32*avctx->channels) {

                    for (s2=s, i=0; i<8; i+=4, s2+=avctx->channels) {

                        int level = (int32_t)((*src & (0xF0>>i)) << (24+i)) >> shift[n];

                        int pred  = s2[-1*avctx->channels] * coeff[0][n]

                                  + s2[-2*avctx->channels] * coeff[1][n];

                        s2[0] = av_clip_int16((level + pred + 0x80) >> 8);

                    }

                }

            }

        }

        samples += 32*4*avctx->channels;

        break;

    case CODEC_ID_ADPCM_IMA_AMV:

    case CODEC_ID_ADPCM_IMA_SMJPEG:

        c->status[0].predictor = (int16_t)bytestream_get_le16(&src);

        c->status[0].step_index = bytestream_get_le16(&src);

        if (avctx->codec->id == CODEC_ID_ADPCM_IMA_AMV)

            src+=4;

        while (src < buf + buf_size) {

            char hi, lo;

            lo = *src & 0x0F;

            hi = *src >> 4;

            if (avctx->codec->id == CODEC_ID_ADPCM_IMA_AMV)

                FFSWAP(char, hi, lo);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                lo, 3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                hi, 3);

            src++;

        }

        break;

    case CODEC_ID_ADPCM_CT:

        while (src < buf + buf_size) {

            if (st) {

                *samples++ = adpcm_ct_expand_nibble(&c->status[0],

                    src[0] >> 4);

                *samples++ = adpcm_ct_expand_nibble(&c->status[1],

                    src[0] & 0x0F);

            } else {

                *samples++ = adpcm_ct_expand_nibble(&c->status[0],

                    src[0] >> 4);

                *samples++ = adpcm_ct_expand_nibble(&c->status[0],

                    src[0] & 0x0F);

            }

            src++;

        }

        break;

    case CODEC_ID_ADPCM_SBPRO_4:

    case CODEC_ID_ADPCM_SBPRO_3:

    case CODEC_ID_ADPCM_SBPRO_2:

        if (!c->status[0].step_index) {

            /* the first byte is a raw sample */

            *samples++ = 128 * (*src++ - 0x80);

            if (st)

              *samples++ = 128 * (*src++ - 0x80);

            c->status[0].step_index = 1;

        }

        if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_4) {

            while (src < buf + buf_size) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    src[0] >> 4, 4, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    src[0] & 0x0F, 4, 0);

                src++;

            }

        } else if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_3) {

            while (src < buf + buf_size && samples + 2 < samples_end) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                     src[0] >> 5        , 3, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 2) & 0x07, 3, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    src[0] & 0x03, 2, 0);

                src++;

            }

        } else {

            while (src < buf + buf_size && samples + 3 < samples_end) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                     src[0] >> 6        , 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    (src[0] >> 4) & 0x03, 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 2) & 0x03, 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    src[0] & 0x03, 2, 2);

                src++;

            }

        }

        break;

    case CODEC_ID_ADPCM_SWF:

    {

        GetBitContext gb;

        const int *table;

        int k0, signmask, nb_bits, count;

        int size = buf_size*8;

        init_get_bits(&gb, buf, size);

        //read bits & initial values

        nb_bits = get_bits(&gb, 2)+2;

        //av_log(NULL,AV_LOG_INFO,"nb_bits: %d\n", nb_bits);

        table = swf_index_tables[nb_bits-2];

        k0 = 1 << (nb_bits-2);

        signmask = 1 << (nb_bits-1);

        while (get_bits_count(&gb) <= size - 22*avctx->channels) {

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

                *samples++ = c->status[i].predictor = get_sbits(&gb, 16);

                c->status[i].step_index = get_bits(&gb, 6);

            }

            for (count = 0; get_bits_count(&gb) <= size - nb_bits*avctx->channels && count < 4095; count++) {

                int i;

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

                    // similar to IMA adpcm

                    int delta = get_bits(&gb, nb_bits);

                    int step = step_table[c->status[i].step_index];

                    long vpdiff = 0; // vpdiff = (delta+0.5)*step/4

                    int k = k0;

                    do {

                        if (delta & k)

                            vpdiff += step;

                        step >>= 1;

                        k >>= 1;

                    } while(k);

                    vpdiff += step;

                    if (delta & signmask)

                        c->status[i].predictor -= vpdiff;

                    else

                        c->status[i].predictor += vpdiff;

                    c->status[i].step_index += table[delta & (~signmask)];

                    c->status[i].step_index = av_clip(c->status[i].step_index, 0, 88);

                    c->status[i].predictor = av_clip_int16(c->status[i].predictor);

                    *samples++ = c->status[i].predictor;

                    if (samples >= samples_end) {

                        av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");

                        return -1;

                    }

                }

            }

        }

        src += buf_size;

        break;

    }

    case CODEC_ID_ADPCM_YAMAHA:

        while (src < buf + buf_size) {

            if (st) {

                *samples++ = adpcm_yamaha_expand_nibble(&c->status[0],

                        src[0] & 0x0F);

                *samples++ = adpcm_yamaha_expand_nibble(&c->status[1],

                        src[0] >> 4  );

            } else {

                *samples++ = adpcm_yamaha_expand_nibble(&c->status[0],

                        src[0] & 0x0F);

                *samples++ = adpcm_yamaha_expand_nibble(&c->status[0],

                        src[0] >> 4  );

            }

            src++;

        }

        break;

    case CODEC_ID_ADPCM_THP:

    {

        int table[2][16];

        unsigned int samplecnt;

        int prev[2][2];

        int ch;

        if (buf_size < 80) {

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

            return -1;

        }

        src+=4;

        samplecnt = bytestream_get_be32(&src);

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

            table[0][i] = (int16_t)bytestream_get_be16(&src);

        /* Initialize the previous sample.  */

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

            prev[0][i] = (int16_t)bytestream_get_be16(&src);

        if (samplecnt >= (samples_end - samples) /  (st + 1)) {

            av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");

            return -1;

        }

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

            samples = (unsigned short *) data + ch;

            /* Read in every sample for this channel.  */

            for (i = 0; i < samplecnt / 14; i++) {

                int index = (*src >> 4) & 7;

                unsigned int exp = 28 - (*src++ & 15);

                int factor1 = table[ch][index * 2];

                int factor2 = table[ch][index * 2 + 1];

                /* Decode 14 samples.  */

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

                    int32_t sampledat;

                    if(n&1) sampledat=  *src++    <<28;

                    else    sampledat= (*src&0xF0)<<24;

                    sampledat = ((prev[ch][0]*factor1

                                + prev[ch][1]*factor2) >> 11) + (sampledat>>exp);

                    *samples = av_clip_int16(sampledat);

                    prev[ch][1] = prev[ch][0];

                    prev[ch][0] = *samples++;

                    /* In case of stereo, skip one sample, this sample

                       is for the other channel.  */

                    samples += st;

                }

            }

        }

        /* In the previous loop, in case stereo is used, samples is

           increased exactly one time too often.  */

        samples -= st;

        break;

    }

    default:

        return -1;

    }

    *data_size = (uint8_t *)samples - (uint8_t *)data;

    return src - buf;

}


int tap_win32_init(VLANState *vlan, const char *model,

                   const char *name, const char *ifname)

{

    TAPState *s;

    s = qemu_mallocz(sizeof(TAPState));

    if (!s)

        return -1;

    if (tap_win32_open(&s->handle, ifname) < 0) {

        printf("tap: Could not open '%s'\n", ifname);

        return -1;

    }

    s->vc = qemu_new_vlan_client(vlan, model, name, tap_receive, NULL, s);

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

             "tap: ifname=%s", ifname);

    qemu_add_wait_object(s->handle->tap_semaphore, tap_win32_send, s);

    return 0;

}


static int parse_netdev(DeviceState *dev, const char *str, void **ptr)
{
    NICPeers *peers_ptr = (NICPeers *)ptr;
    NICConf *conf = container_of(peers_ptr, NICConf, peers);
    NetClientState **ncs = peers_ptr->ncs;
    NetClientState *peers[MAX_QUEUE_NUM];
    int queues, i = 0;
    int ret;
    queues = qemu_find_net_clients_except(str, peers,
                                          NET_CLIENT_OPTIONS_KIND_NIC,
                                          MAX_QUEUE_NUM);
    if (queues == 0) {
        ret = -ENOENT;
    if (queues > MAX_QUEUE_NUM) {
        ret = -E2BIG;
    for (i = 0; i < queues; i++) {
        if (peers[i] == NULL) {
            ret = -ENOENT;
        if (peers[i]->peer) {
            ret = -EEXIST;
        ncs[i] = peers[i];
        ncs[i]->queue_index = i;
    conf->queues = queues;
    return 0;
err:
    return ret;


static void property_get_str(Object *obj, Visitor *v, void *opaque,

                             const char *name, Error **errp)

{

    StringProperty *prop = opaque;

    char *value;

    value = prop->get(obj, errp);

    if (value) {

        visit_type_str(v, &value, name, errp);

        g_free(value);

    }

}


static void setup_frame(int sig, struct target_sigaction *ka,

                        target_sigset_t *set, CPUCRISState *env)

{

	struct target_signal_frame *frame;

	abi_ulong frame_addr;

	int err = 0;

	int i;

	frame_addr = get_sigframe(env, sizeof *frame);

	if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0))

		goto badframe;

	/*

	 * The CRIS signal return trampoline. A real linux/CRIS kernel doesn't

	 * use this trampoline anymore but it sets it up for GDB.

	 * In QEMU, using the trampoline simplifies things a bit so we use it.

	 *

	 * This is movu.w __NR_sigreturn, r9; break 13;

	 */

    __put_user(0x9c5f, frame->retcode+0);

    __put_user(TARGET_NR_sigreturn,

               frame->retcode + 1);

    __put_user(0xe93d, frame->retcode + 2);

	/* Save the mask.  */

    __put_user(set->sig[0], &frame->sc.oldmask);

	if (err)

		goto badframe;

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

		if (__put_user(set->sig[i], &frame->extramask[i - 1]))

			goto badframe;

	}

	setup_sigcontext(&frame->sc, env);

	/* Move the stack and setup the arguments for the handler.  */

	env->regs[R_SP] = frame_addr;

	env->regs[10] = sig;

	env->pc = (unsigned long) ka->_sa_handler;

	/* Link SRP so the guest returns through the trampoline.  */

	env->pregs[PR_SRP] = frame_addr + offsetof(typeof(*frame), retcode);

	unlock_user_struct(frame, frame_addr, 1);

	return;

  badframe:

	unlock_user_struct(frame, frame_addr, 1);

	force_sig(TARGET_SIGSEGV);

}


static int filter_frame(AVFilterLink *link, AVFrame *in)

{

    AVFilterContext *ctx = link->dst;

    AVFilterLink *outlink = ctx->outputs[0];

    ColorSpaceContext *s = ctx->priv;

    // FIXME if yuv2yuv_passthrough, don't get a new buffer but use the

    // input one if it is writable *OR* the actual literal values of in_*

    // and out_* are identical (not just their respective properties)

    AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);

    int res;

    ptrdiff_t rgb_stride = FFALIGN(in->width * sizeof(int16_t), 32);

    unsigned rgb_sz = rgb_stride * in->height;

    struct ThreadData td;

    if (!out) {

        av_frame_free(&in);

        return AVERROR(ENOMEM);

    }

    av_frame_copy_props(out, in);

    out->color_primaries = s->user_prm == AVCOL_PRI_UNSPECIFIED ?

                           default_prm[FFMIN(s->user_all, CS_NB)] : s->user_prm;

    if (s->user_trc == AVCOL_TRC_UNSPECIFIED) {

        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(out->format);

        out->color_trc   = default_trc[FFMIN(s->user_all, CS_NB)];

        if (out->color_trc == AVCOL_TRC_BT2020_10 && desc && desc->comp[0].depth >= 12)

            out->color_trc = AVCOL_TRC_BT2020_12;

    } else {

        out->color_trc   = s->user_trc;

    }

    out->colorspace      = s->user_csp == AVCOL_SPC_UNSPECIFIED ?

                           default_csp[FFMIN(s->user_all, CS_NB)] : s->user_csp;

    out->color_range     = s->user_rng == AVCOL_RANGE_UNSPECIFIED ?

                           in->color_range : s->user_rng;

    if (rgb_sz != s->rgb_sz) {

        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(out->format);

        int uvw = in->width >> desc->log2_chroma_w;

        av_freep(&s->rgb[0]);

        av_freep(&s->rgb[1]);

        av_freep(&s->rgb[2]);

        s->rgb_sz = 0;

        av_freep(&s->dither_scratch_base[0][0]);

        av_freep(&s->dither_scratch_base[0][1]);

        av_freep(&s->dither_scratch_base[1][0]);

        av_freep(&s->dither_scratch_base[1][1]);

        av_freep(&s->dither_scratch_base[2][0]);

        av_freep(&s->dither_scratch_base[2][1]);

        s->rgb[0] = av_malloc(rgb_sz);

        s->rgb[1] = av_malloc(rgb_sz);

        s->rgb[2] = av_malloc(rgb_sz);

        s->dither_scratch_base[0][0] =

            av_malloc(sizeof(*s->dither_scratch_base[0][0]) * (in->width + 4));

        s->dither_scratch_base[0][1] =

            av_malloc(sizeof(*s->dither_scratch_base[0][1]) * (in->width + 4));

        s->dither_scratch_base[1][0] =

            av_malloc(sizeof(*s->dither_scratch_base[1][0]) * (uvw + 4));

        s->dither_scratch_base[1][1] =

            av_malloc(sizeof(*s->dither_scratch_base[1][1]) * (uvw + 4));

        s->dither_scratch_base[2][0] =

            av_malloc(sizeof(*s->dither_scratch_base[2][0]) * (uvw + 4));

        s->dither_scratch_base[2][1] =

            av_malloc(sizeof(*s->dither_scratch_base[2][1]) * (uvw + 4));

        s->dither_scratch[0][0] = &s->dither_scratch_base[0][0][1];

        s->dither_scratch[0][1] = &s->dither_scratch_base[0][1][1];

        s->dither_scratch[1][0] = &s->dither_scratch_base[1][0][1];

        s->dither_scratch[1][1] = &s->dither_scratch_base[1][1][1];

        s->dither_scratch[2][0] = &s->dither_scratch_base[2][0][1];

        s->dither_scratch[2][1] = &s->dither_scratch_base[2][1][1];

        if (!s->rgb[0] || !s->rgb[1] || !s->rgb[2] ||

            !s->dither_scratch_base[0][0] || !s->dither_scratch_base[0][1] ||

            !s->dither_scratch_base[1][0] || !s->dither_scratch_base[1][1] ||

            !s->dither_scratch_base[2][0] || !s->dither_scratch_base[2][1]) {

            uninit(ctx);

            return AVERROR(ENOMEM);

        }

        s->rgb_sz = rgb_sz;

    }

    res = create_filtergraph(ctx, in, out);

    if (res < 0)

        return res;

    s->rgb_stride = rgb_stride / sizeof(int16_t);

    td.in = in;

    td.out = out;

    td.in_linesize[0] = in->linesize[0];

    td.in_linesize[1] = in->linesize[1];

    td.in_linesize[2] = in->linesize[2];

    td.out_linesize[0] = out->linesize[0];

    td.out_linesize[1] = out->linesize[1];

    td.out_linesize[2] = out->linesize[2];

    td.in_ss_h = av_pix_fmt_desc_get(in->format)->log2_chroma_h;

    td.out_ss_h = av_pix_fmt_desc_get(out->format)->log2_chroma_h;

    if (s->yuv2yuv_passthrough) {

        av_frame_copy(out, in);

    } else {

        ctx->internal->execute(ctx, convert, &td, NULL,

                               FFMIN((in->height + 1) >> 1, ctx->graph->nb_threads));

    }

    av_frame_free(&in);

    return ff_filter_frame(outlink, out);

}


static struct glfs *qemu_gluster_glfs_init(BlockdevOptionsGluster *gconf,

                                           Error **errp)

{

    struct glfs *glfs;

    int ret;

    int old_errno;

    GlusterServerList *server;

    glfs = glfs_new(gconf->volume);

    if (!glfs) {

        goto out;

    }

    for (server = gconf->server; server; server = server->next) {

        if (server->value->type  == GLUSTER_TRANSPORT_UNIX) {

            ret = glfs_set_volfile_server(glfs,

                                   GlusterTransport_lookup[server->value->type],

                                   server->value->u.q_unix.path, 0);

        } else {

            ret = glfs_set_volfile_server(glfs,

                                   GlusterTransport_lookup[server->value->type],

                                   server->value->u.tcp.host,

                                   atoi(server->value->u.tcp.port));

        }

        if (ret < 0) {

            goto out;

        }

    }

    ret = glfs_set_logging(glfs, "-", gconf->debug_level);

    if (ret < 0) {

        goto out;

    }

    ret = glfs_init(glfs);

    if (ret) {

        error_setg(errp, "Gluster connection for volume %s, path %s failed"

                         " to connect", gconf->volume, gconf->path);

        for (server = gconf->server; server; server = server->next) {

            if (server->value->type  == GLUSTER_TRANSPORT_UNIX) {

                error_append_hint(errp, "hint: failed on socket %s ",

                                  server->value->u.q_unix.path);

            } else {

                error_append_hint(errp, "hint: failed on host %s and port %s ",

                                  server->value->u.tcp.host,

                                  server->value->u.tcp.port);

            }

        }

        error_append_hint(errp, "Please refer to gluster logs for more info\n");

        /* glfs_init sometimes doesn't set errno although docs suggest that */

        if (errno == 0) {

            errno = EINVAL;

        }

        goto out;

    }

    return glfs;

out:

    if (glfs) {

        old_errno = errno;

        glfs_fini(glfs);

        errno = old_errno;

    }

    return NULL;

}


void virtio_queue_set_notification(VirtQueue *vq, int enable)

{

    vq->notification = enable;

    if (vq->vdev->guest_features & (1 << VIRTIO_RING_F_EVENT_IDX)) {

        vring_avail_event(vq, vring_avail_idx(vq));

    } else if (enable) {

        vring_used_flags_unset_bit(vq, VRING_USED_F_NO_NOTIFY);

    } else {

        vring_used_flags_set_bit(vq, VRING_USED_F_NO_NOTIFY);


static void decode_vui(HEVCContext *s, HEVCSPS *sps)

{

    VUI *vui          = &sps->vui;

    GetBitContext *gb = &s->HEVClc->gb;

    int sar_present;

    av_log(s->avctx, AV_LOG_DEBUG, "Decoding VUI\n");

    sar_present = get_bits1(gb);

    if (sar_present) {

        uint8_t sar_idx = get_bits(gb, 8);

        if (sar_idx < FF_ARRAY_ELEMS(vui_sar))

            vui->sar = vui_sar[sar_idx];

        else if (sar_idx == 255) {

            vui->sar.num = get_bits(gb, 16);

            vui->sar.den = get_bits(gb, 16);

        } else

            av_log(s->avctx, AV_LOG_WARNING,

                   "Unknown SAR index: %u.\n", sar_idx);

    }

    vui->overscan_info_present_flag = get_bits1(gb);

    if (vui->overscan_info_present_flag)

        vui->overscan_appropriate_flag = get_bits1(gb);

    vui->video_signal_type_present_flag = get_bits1(gb);

    if (vui->video_signal_type_present_flag) {

        vui->video_format                    = get_bits(gb, 3);

        vui->video_full_range_flag           = get_bits1(gb);

        vui->colour_description_present_flag = get_bits1(gb);

        if (vui->video_full_range_flag && sps->pix_fmt == AV_PIX_FMT_YUV420P)

            sps->pix_fmt = AV_PIX_FMT_YUVJ420P;

        if (vui->colour_description_present_flag) {

            vui->colour_primaries        = get_bits(gb, 8);

            vui->transfer_characteristic = get_bits(gb, 8);

            vui->matrix_coeffs           = get_bits(gb, 8);

            // Set invalid values to "unspecified"

            if (vui->colour_primaries >= AVCOL_PRI_NB)

                vui->colour_primaries = AVCOL_PRI_UNSPECIFIED;

            if (vui->transfer_characteristic >= AVCOL_TRC_NB)

                vui->transfer_characteristic = AVCOL_TRC_UNSPECIFIED;

            if (vui->matrix_coeffs >= AVCOL_SPC_NB)

                vui->matrix_coeffs = AVCOL_SPC_UNSPECIFIED;

        }

    }

    vui->chroma_loc_info_present_flag = get_bits1(gb);

    if (vui->chroma_loc_info_present_flag) {

        vui->chroma_sample_loc_type_top_field    = get_ue_golomb_long(gb);

        vui->chroma_sample_loc_type_bottom_field = get_ue_golomb_long(gb);

    }

    vui->neutra_chroma_indication_flag = get_bits1(gb);

    vui->field_seq_flag                = get_bits1(gb);

    vui->frame_field_info_present_flag = get_bits1(gb);

    vui->default_display_window_flag = get_bits1(gb);

    if (vui->default_display_window_flag) {

        //TODO: * 2 is only valid for 420

        vui->def_disp_win.left_offset   = get_ue_golomb_long(gb) * 2;

        vui->def_disp_win.right_offset  = get_ue_golomb_long(gb) * 2;

        vui->def_disp_win.top_offset    = get_ue_golomb_long(gb) * 2;

        vui->def_disp_win.bottom_offset = get_ue_golomb_long(gb) * 2;

        if (s->apply_defdispwin &&

            s->avctx->flags2 & CODEC_FLAG2_IGNORE_CROP) {

            av_log(s->avctx, AV_LOG_DEBUG,

                   "discarding vui default display window, "

                   "original values are l:%u r:%u t:%u b:%u\n",

                   vui->def_disp_win.left_offset,

                   vui->def_disp_win.right_offset,

                   vui->def_disp_win.top_offset,

                   vui->def_disp_win.bottom_offset);

            vui->def_disp_win.left_offset   =

            vui->def_disp_win.right_offset  =

            vui->def_disp_win.top_offset    =

            vui->def_disp_win.bottom_offset = 0;

        }

    }

    vui->vui_timing_info_present_flag = get_bits1(gb);

    if (vui->vui_timing_info_present_flag) {

        vui->vui_num_units_in_tick               = get_bits(gb, 32);

        vui->vui_time_scale                      = get_bits(gb, 32);

        vui->vui_poc_proportional_to_timing_flag = get_bits1(gb);

        if (vui->vui_poc_proportional_to_timing_flag)

            vui->vui_num_ticks_poc_diff_one_minus1 = get_ue_golomb_long(gb);

        vui->vui_hrd_parameters_present_flag = get_bits1(gb);

        if (vui->vui_hrd_parameters_present_flag)

            decode_hrd(s, 1, sps->max_sub_layers);

    }

    vui->bitstream_restriction_flag = get_bits1(gb);

    if (vui->bitstream_restriction_flag) {

        vui->tiles_fixed_structure_flag              = get_bits1(gb);

        vui->motion_vectors_over_pic_boundaries_flag = get_bits1(gb);

        vui->restricted_ref_pic_lists_flag           = get_bits1(gb);

        vui->min_spatial_segmentation_idc            = get_ue_golomb_long(gb);

        vui->max_bytes_per_pic_denom                 = get_ue_golomb_long(gb);

        vui->max_bits_per_min_cu_denom               = get_ue_golomb_long(gb);

        vui->log2_max_mv_length_horizontal           = get_ue_golomb_long(gb);

        vui->log2_max_mv_length_vertical             = get_ue_golomb_long(gb);

    }

}


static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)

{

    EHCIPacket *p;

    uint32_t entry, devaddr;

    EHCIQueue *q;

    entry = ehci_get_fetch_addr(ehci, async);

    q = ehci_find_queue_by_qh(ehci, entry, async);

    if (NULL == q) {

        q = ehci_alloc_queue(ehci, entry, async);

    }

    p = QTAILQ_FIRST(&q->packets);

    q->seen++;

    if (q->seen > 1) {

        /* we are going in circles -- stop processing */

        ehci_set_state(ehci, async, EST_ACTIVE);

        q = NULL;

        goto out;

    }

    get_dwords(ehci, NLPTR_GET(q->qhaddr),

               (uint32_t *) &q->qh, sizeof(EHCIqh) >> 2);

    ehci_trace_qh(q, NLPTR_GET(q->qhaddr), &q->qh);

    devaddr = get_field(q->qh.epchar, QH_EPCHAR_DEVADDR);

    if (q->dev != NULL && q->dev->addr != devaddr) {

        if (!QTAILQ_EMPTY(&q->packets)) {

            /* should not happen (guest bug) */

            ehci_cancel_queue(q);

        }

        q->dev = NULL;

    }

    if (q->dev == NULL) {

        q->dev = ehci_find_device(q->ehci, devaddr);

    }

    if (p && p->async == EHCI_ASYNC_FINISHED) {

        /* I/O finished -- continue processing queue */

        trace_usb_ehci_packet_action(p->queue, p, "complete");

        ehci_set_state(ehci, async, EST_EXECUTING);

        goto out;

    }

    if (async && (q->qh.epchar & QH_EPCHAR_H)) {

        /*  EHCI spec version 1.0 Section 4.8.3 & 4.10.1 */

        if (ehci->usbsts & USBSTS_REC) {

            ehci_clear_usbsts(ehci, USBSTS_REC);

        } else {

            DPRINTF("FETCHQH:  QH 0x%08x. H-bit set, reclamation status reset"

                       " - done processing\n", q->qhaddr);

            ehci_set_state(ehci, async, EST_ACTIVE);

            q = NULL;

            goto out;

        }

    }

#if EHCI_DEBUG

    if (q->qhaddr != q->qh.next) {

    DPRINTF("FETCHQH:  QH 0x%08x (h %x halt %x active %x) next 0x%08x\n",

               q->qhaddr,

               q->qh.epchar & QH_EPCHAR_H,

               q->qh.token & QTD_TOKEN_HALT,

               q->qh.token & QTD_TOKEN_ACTIVE,

               q->qh.next);

    }

#endif

    if (q->qh.token & QTD_TOKEN_HALT) {

        ehci_set_state(ehci, async, EST_HORIZONTALQH);

    } else if ((q->qh.token & QTD_TOKEN_ACTIVE) &&

               (NLPTR_TBIT(q->qh.current_qtd) == 0)) {

        q->qtdaddr = q->qh.current_qtd;

        ehci_set_state(ehci, async, EST_FETCHQTD);

    } else {

        /*  EHCI spec version 1.0 Section 4.10.2 */

        ehci_set_state(ehci, async, EST_ADVANCEQUEUE);

    }

out:

    return q;

}


static av_cold int aacPlus_encode_init(AVCodecContext *avctx)

{

    aacPlusAudioContext *s = avctx->priv_data;

    aacplusEncConfiguration *aacplus_cfg;

    /* number of channels */

    if (avctx->channels < 1 || avctx->channels > 2) {

        av_log(avctx, AV_LOG_ERROR, "encoding %d channel(s) is not allowed\n", avctx->channels);

        return AVERROR(EINVAL);

    if (avctx->profile != FF_PROFILE_AAC_LOW && avctx->profile != FF_PROFILE_UNKNOWN) {

        av_log(avctx, AV_LOG_ERROR, "invalid AAC profile: %d, only LC supported\n", avctx->profile);

        return AVERROR(EINVAL);

    s->aacplus_handle = aacplusEncOpen(avctx->sample_rate, avctx->channels,

                                       &s->samples_input, &s->max_output_bytes);

    if (!s->aacplus_handle) {

        av_log(avctx, AV_LOG_ERROR, "can't open encoder\n");

        return AVERROR(EINVAL);

    /* check aacplus version */

    aacplus_cfg = aacplusEncGetCurrentConfiguration(s->aacplus_handle);

    aacplus_cfg->bitRate = avctx->bit_rate;

    aacplus_cfg->bandWidth = avctx->cutoff;

    aacplus_cfg->outputFormat = !(avctx->flags & CODEC_FLAG_GLOBAL_HEADER);

    aacplus_cfg->inputFormat = avctx->sample_fmt == AV_SAMPLE_FMT_FLT ? AACPLUS_INPUT_FLOAT : AACPLUS_INPUT_16BIT;

    if (!aacplusEncSetConfiguration(s->aacplus_handle, aacplus_cfg)) {

        av_log(avctx, AV_LOG_ERROR, "libaacplus doesn't support this output format!\n");

        return AVERROR(EINVAL);

    avctx->frame_size = s->samples_input / avctx->channels;

    /* Set decoder specific info */

    avctx->extradata_size = 0;

    if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {

        unsigned char *buffer = NULL;

        unsigned long decoder_specific_info_size;

        if (aacplusEncGetDecoderSpecificInfo(s->aacplus_handle, &buffer,

                                           &decoder_specific_info_size) == 1) {

            avctx->extradata = av_malloc(decoder_specific_info_size + FF_INPUT_BUFFER_PADDING_SIZE);

            avctx->extradata_size = decoder_specific_info_size;

            memcpy(avctx->extradata, buffer, avctx->extradata_size);

    return 0;


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    VirtIOS390DeviceClass *k = VIRTIO_S390_DEVICE_CLASS(klass);

    k->init = s390_virtio_blk_init;

    dc->props = s390_virtio_blk_properties;

}