static int fill_filter_caches(H264Context *h, H264SliceContext *sl, int mb_type) { const int mb_xy = h->mb_xy; int top_xy, left_xy[LEFT_MBS]; int top_type, left_type[LEFT_MBS]; uint8_t *nnz; uint8_t *nnz_cache; top_xy = mb_xy - (h->mb_stride << MB_FIELD(h)); /* Wow, what a mess, why didn't they simplify the interlacing & intra * stuff, I can't imagine that these complex rules are worth it. */ left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1; if (FRAME_MBAFF(h)) { const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]); const int curr_mb_field_flag = IS_INTERLACED(mb_type); if (h->mb_y & 1) { if (left_mb_field_flag != curr_mb_field_flag) left_xy[LTOP] -= h->mb_stride; } else { if (curr_mb_field_flag) top_xy += h->mb_stride & (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1); if (left_mb_field_flag != curr_mb_field_flag) left_xy[LBOT] += h->mb_stride; } } sl->top_mb_xy = top_xy; sl->left_mb_xy[LTOP] = left_xy[LTOP]; sl->left_mb_xy[LBOT] = left_xy[LBOT]; { /* For sufficiently low qp, filtering wouldn't do anything. * This is a conservative estimate: could also check beta_offset * and more accurate chroma_qp. */ int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice int qp = h->cur_pic.qscale_table[mb_xy]; if (qp <= qp_thresh && (left_xy[LTOP] < 0 || ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) && (top_xy < 0 || ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) { if (!FRAME_MBAFF(h)) return 1; if ((left_xy[LTOP] < 0 || ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) && (top_xy < h->mb_stride || ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh)) return 1; } } top_type = h->cur_pic.mb_type[top_xy]; left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]]; left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]]; if (h->deblocking_filter == 2) { if (h->slice_table[top_xy] != sl->slice_num) top_type = 0; if (h->slice_table[left_xy[LBOT]] != sl->slice_num) left_type[LTOP] = left_type[LBOT] = 0; } else { if (h->slice_table[top_xy] == 0xFFFF) top_type = 0; if (h->slice_table[left_xy[LBOT]] == 0xFFFF) left_type[LTOP] = left_type[LBOT] = 0; } sl->top_type = top_type; sl->left_type[LTOP] = left_type[LTOP]; sl->left_type[LBOT] = left_type[LBOT]; if (IS_INTRA(mb_type)) return 0; fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy, top_type, left_type, mb_xy, 0); if (sl->list_count == 2) fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy, top_type, left_type, mb_xy, 1); nnz = h->non_zero_count[mb_xy]; nnz_cache = sl->non_zero_count_cache; AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]); AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]); AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]); AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]); sl->cbp = h->cbp_table[mb_xy]; if (top_type) { nnz = h->non_zero_count[top_xy]; AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]); } if (left_type[LTOP]) { nnz = h->non_zero_count[left_xy[LTOP]]; nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4]; nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4]; nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4]; nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4]; } /* CAVLC 8x8dct requires NNZ values for residual decoding that differ * from what the loop filter needs */ if (!CABAC(h) && h->pps.transform_8x8_mode) { if (IS_8x8DCT(top_type)) { nnz_cache[4 + 8 * 0] = nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12; nnz_cache[6 + 8 * 0] = nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12; } if (IS_8x8DCT(left_type[LTOP])) { nnz_cache[3 + 8 * 1] = nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF } if (IS_8x8DCT(left_type[LBOT])) { nnz_cache[3 + 8 * 3] = nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF } if (IS_8x8DCT(mb_type)) { nnz_cache[scan8[0]] = nnz_cache[scan8[1]] = nnz_cache[scan8[2]] = nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12; nnz_cache[scan8[0 + 4]] = nnz_cache[scan8[1 + 4]] = nnz_cache[scan8[2 + 4]] = nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12; nnz_cache[scan8[0 + 8]] = nnz_cache[scan8[1 + 8]] = nnz_cache[scan8[2 + 8]] = nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12; nnz_cache[scan8[0 + 12]] = nnz_cache[scan8[1 + 12]] = nnz_cache[scan8[2 + 12]] = nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12; } } return 0; }


av_cold void ff_init_lls_x86(LLSModel *m) { int cpu_flags = av_get_cpu_flags(); if (EXTERNAL_SSE2(cpu_flags)) { m->update_lls = ff_update_lls_sse2; if (m->indep_count >= 4) m->evaluate_lls = ff_evaluate_lls_sse2; } if (EXTERNAL_AVX(cpu_flags)) { m->update_lls = ff_update_lls_avx; } }


static inline void RENAME(yuv2yuvX)(SwsContext *c, int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize, int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize, uint8_t *dest, uint8_t *uDest, uint8_t *vDest, long dstW, long chrDstW) { #ifdef HAVE_MMX if (c->flags & SWS_ACCURATE_RND){ if (uDest){ YSCALEYUV2YV12X_ACCURATE( 0, CHR_MMX_FILTER_OFFSET, uDest, chrDstW) YSCALEYUV2YV12X_ACCURATE(4096, CHR_MMX_FILTER_OFFSET, vDest, chrDstW) } YSCALEYUV2YV12X_ACCURATE(0, LUM_MMX_FILTER_OFFSET, dest, dstW) }else{ if (uDest){ YSCALEYUV2YV12X( 0, CHR_MMX_FILTER_OFFSET, uDest, chrDstW) YSCALEYUV2YV12X(4096, CHR_MMX_FILTER_OFFSET, vDest, chrDstW) } YSCALEYUV2YV12X(0, LUM_MMX_FILTER_OFFSET, dest, dstW) } #else #ifdef HAVE_ALTIVEC yuv2yuvX_altivec_real(lumFilter, lumSrc, lumFilterSize, chrFilter, chrSrc, chrFilterSize, dest, uDest, vDest, dstW, chrDstW); #else //HAVE_ALTIVEC yuv2yuvXinC(lumFilter, lumSrc, lumFilterSize, chrFilter, chrSrc, chrFilterSize, dest, uDest, vDest, dstW, chrDstW); #endif //!HAVE_ALTIVEC #endif /* HAVE_MMX */ }


static void vmxnet3_update_rx_mode(VMXNET3State *s) { s->rx_mode = VMXNET3_READ_DRV_SHARED32(s->drv_shmem, devRead.rxFilterConf.rxMode); VMW_CFPRN("RX mode: 0x%08X", s->rx_mode); }


static int qemu_peek_byte(QEMUFile *f) { if (f->is_write) { abort(); } if (f->buf_index >= f->buf_size) { qemu_fill_buffer(f); if (f->buf_index >= f->buf_size) { return 0; } } return f->buf[f->buf_index]; }


static int virtio_ccw_set_vqs(SubchDev *sch, uint64_t addr, uint32_t align, uint16_t index, uint16_t num) { VirtIODevice *vdev = virtio_ccw_get_vdev(sch); if (index > VIRTIO_PCI_QUEUE_MAX) { return -EINVAL; } /* Current code in virtio.c relies on 4K alignment. */ if (addr && (align != 4096)) { return -EINVAL; } if (!vdev) { return -EINVAL; } virtio_queue_set_addr(vdev, index, addr); if (!addr) { virtio_queue_set_vector(vdev, index, 0); } else { /* Fail if we don't have a big enough queue. */ /* TODO: Add interface to handle vring.num changing */ if (virtio_queue_get_num(vdev, index) > num) { return -EINVAL; } virtio_queue_set_vector(vdev, index, index); } /* tell notify handler in case of config change */ vdev->config_vector = VIRTIO_PCI_QUEUE_MAX; return 0; }


static bool cuda_cmd_set_time(CUDAState *s, const uint8_t *in_data, int in_len, uint8_t *out_data, int *out_len) { uint32_t ti; if (in_len != 4) { return false; } ti = (((uint32_t)in_data[1]) << 24) + (((uint32_t)in_data[2]) << 16) + (((uint32_t)in_data[3]) << 8) + in_data[4]; s->tick_offset = ti - (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / NANOSECONDS_PER_SECOND); return true; }


static void vscsi_send_request_sense(VSCSIState *s, vscsi_req *req) { SCSIDevice *sdev = req->sdev; uint8_t *cdb = req->iu.srp.cmd.cdb; int n; cdb[0] = 3; cdb[1] = 0; cdb[2] = 0; cdb[3] = 0; cdb[4] = 96; cdb[5] = 0; req->sensing = 1; n = sdev->info->send_command(sdev, req->qtag, cdb, req->lun); dprintf("VSCSI: Queued request sense tag 0x%x\n", req->qtag); if (n < 0) { fprintf(stderr, "VSCSI: REQUEST_SENSE wants write data !?!?!?\n"); sdev->info->cancel_io(sdev, req->qtag); vscsi_makeup_sense(s, req, HARDWARE_ERROR, 0, 0); vscsi_send_rsp(s, req, CHECK_CONDITION, 0, 0); vscsi_put_req(s, req); return; } else if (n == 0) { return; } sdev->info->read_data(sdev, req->qtag); }


static inline void RENAME(yv12touyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst, long width, long height, long lumStride, long chromStride, long dstStride) { //FIXME interpolate chroma RENAME(yuvPlanartouyvy)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 2); }


static uint64_t pmsav5_data_ap_read(CPUARMState *env, const ARMCPRegInfo *ri) { return simple_mpu_ap_bits(env->cp15.c5_data); }


static void flat(WaveformContext *s, AVFrame *in, AVFrame *out, int component, int intensity, int offset, int column) { const int plane = s->desc->comp[component].plane; const int mirror = s->mirror; const int c0_linesize = in->linesize[ plane + 0 ]; const int c1_linesize = in->linesize[(plane + 1) % s->ncomp]; const int c2_linesize = in->linesize[(plane + 2) % s->ncomp]; const int d0_linesize = out->linesize[ plane + 0 ]; const int d1_linesize = out->linesize[(plane + 1) % s->ncomp]; const int max = 255 - intensity; const int src_h = in->height; const int src_w = in->width; int x, y; if (column) { const int d0_signed_linesize = d0_linesize * (mirror == 1 ? -1 : 1); const int d1_signed_linesize = d1_linesize * (mirror == 1 ? -1 : 1); for (x = 0; x < src_w; x++) { const uint8_t *c0_data = in->data[plane + 0]; const uint8_t *c1_data = in->data[(plane + 1) % s->ncomp]; const uint8_t *c2_data = in->data[(plane + 2) % s->ncomp]; uint8_t *d0_data = out->data[plane] + offset * d0_linesize; uint8_t *d1_data = out->data[(plane + 1) % s->ncomp] + offset * d1_linesize; uint8_t * const d0_bottom_line = d0_data + d0_linesize * (s->size - 1); uint8_t * const d0 = (mirror ? d0_bottom_line : d0_data); uint8_t * const d1_bottom_line = d1_data + d1_linesize * (s->size - 1); uint8_t * const d1 = (mirror ? d1_bottom_line : d1_data); for (y = 0; y < src_h; y++) { const int c0 = c0_data[x] + 256; const int c1 = FFABS(c1_data[x] - 128) + FFABS(c2_data[x] - 128); uint8_t *target; int p; target = d0 + x + d0_signed_linesize * c0; update(target, max, intensity); for (p = c0 - c1; p < c0 + c1; p++) { target = d1 + x + d1_signed_linesize * p; update(target, max, 1); } c0_data += c0_linesize; c1_data += c1_linesize; c2_data += c2_linesize; d0_data += d0_linesize; d1_data += d1_linesize; } } } else { const uint8_t *c0_data = in->data[plane]; const uint8_t *c1_data = in->data[(plane + 1) % s->ncomp]; const uint8_t *c2_data = in->data[(plane + 2) % s->ncomp]; uint8_t *d0_data = out->data[plane] + offset; uint8_t *d1_data = out->data[(plane + 1) % s->ncomp] + offset; if (mirror) { d0_data += s->size - 1; d1_data += s->size - 1; } for (y = 0; y < src_h; y++) { for (x = 0; x < src_w; x++) { int c0 = c0_data[x] + 256; const int c1 = FFABS(c1_data[x] - 128) + FFABS(c2_data[x] - 128); uint8_t *target; int p; if (mirror) target = d0_data - c0; else target = d0_data + c0; update(target, max, intensity); for (p = c0 - c1; p < c0 + c1; p++) { if (mirror) target = d1_data - p; else target = d1_data + p; update(target, max, 1); } } c0_data += c0_linesize; c1_data += c1_linesize; c2_data += c2_linesize; d0_data += d0_linesize; d1_data += d1_linesize; } } envelope(s, out, plane, plane); envelope(s, out, plane, (plane + 1) % s->ncomp); }


av_cold int ff_mpv_common_init(MpegEncContext *s) { int i; int nb_slices = (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_SLICE) ? s->avctx->thread_count : 1; if (s->encoding && s->avctx->slices) nb_slices = s->avctx->slices; if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && !s->progressive_sequence) s->mb_height = (s->height + 31) / 32 * 2; else s->mb_height = (s->height + 15) / 16; if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "decoding to AV_PIX_FMT_NONE is not supported.\n"); return -1; } if (nb_slices > MAX_THREADS || (nb_slices > s->mb_height && s->mb_height)) { int max_slices; if (s->mb_height) max_slices = FFMIN(MAX_THREADS, s->mb_height); else max_slices = MAX_THREADS; av_log(s->avctx, AV_LOG_WARNING, "too many threads/slices (%d)," " reducing to %d\n", nb_slices, max_slices); nb_slices = max_slices; } if ((s->width || s->height) && av_image_check_size(s->width, s->height, 0, s->avctx)) return -1; dct_init(s); /* set chroma shifts */ avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift); FF_ALLOCZ_OR_GOTO(s->avctx, s->picture, MAX_PICTURE_COUNT * sizeof(Picture), fail); for (i = 0; i < MAX_PICTURE_COUNT; i++) { s->picture[i].f = av_frame_alloc(); if (!s->picture[i].f) goto fail; } memset(&s->next_picture, 0, sizeof(s->next_picture)); memset(&s->last_picture, 0, sizeof(s->last_picture)); memset(&s->current_picture, 0, sizeof(s->current_picture)); memset(&s->new_picture, 0, sizeof(s->new_picture)); s->next_picture.f = av_frame_alloc(); if (!s->next_picture.f) goto fail; s->last_picture.f = av_frame_alloc(); if (!s->last_picture.f) goto fail; s->current_picture.f = av_frame_alloc(); if (!s->current_picture.f) goto fail; s->new_picture.f = av_frame_alloc(); if (!s->new_picture.f) goto fail; if (init_context_frame(s)) goto fail; s->parse_context.state = -1; s->context_initialized = 1; s->thread_context[0] = s; // if (s->width && s->height) { if (nb_slices > 1) { for (i = 1; i < nb_slices; i++) { s->thread_context[i] = av_malloc(sizeof(MpegEncContext)); memcpy(s->thread_context[i], s, sizeof(MpegEncContext)); } for (i = 0; i < nb_slices; i++) { if (init_duplicate_context(s->thread_context[i]) < 0) goto fail; s->thread_context[i]->start_mb_y = (s->mb_height * (i) + nb_slices / 2) / nb_slices; s->thread_context[i]->end_mb_y = (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices; } } else { if (init_duplicate_context(s) < 0) goto fail; s->start_mb_y = 0; s->end_mb_y = s->mb_height; } s->slice_context_count = nb_slices; // } return 0; fail: ff_mpv_common_end(s); return -1; }


static int read_audio_mux_element(struct LATMContext *latmctx, GetBitContext *gb) { int err; uint8_t use_same_mux = get_bits(gb, 1); if (!use_same_mux) { if ((err = read_stream_mux_config(latmctx, gb)) < 0) return err; } else if (!latmctx->aac_ctx.avctx->extradata) { av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG, "no decoder config found\n"); return AVERROR(EAGAIN); } if (latmctx->audio_mux_version_A == 0) { int mux_slot_length_bytes = read_payload_length_info(latmctx, gb); if (mux_slot_length_bytes * 8 > get_bits_left(gb)) { av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n"); return AVERROR_INVALIDDATA; } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) { av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "frame length mismatch %d << %d\n", mux_slot_length_bytes * 8, get_bits_left(gb)); return AVERROR_INVALIDDATA; } } return 0; }


static int vpc_has_zero_init(BlockDriverState *bs) { BDRVVPCState *s = bs->opaque; VHDFooter *footer = (VHDFooter *) s->footer_buf; if (cpu_to_be32(footer->type) == VHD_FIXED) { return bdrv_has_zero_init(bs->file); } else { return 1; } }


static int mpeg_decode_postinit(AVCodecContext *avctx) { Mpeg1Context *s1 = avctx->priv_data; MpegEncContext *s = &s1->mpeg_enc_ctx; uint8_t old_permutation[64]; int ret; if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO) { // MPEG-1 aspect avctx->sample_aspect_ratio = av_d2q(1.0 / ff_mpeg1_aspect[s->aspect_ratio_info], 255); } else { // MPEG-2 // MPEG-2 aspect if (s->aspect_ratio_info > 1) { AVRational dar = av_mul_q(av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info], (AVRational) { s1->pan_scan.width, s1->pan_scan.height }), (AVRational) { s->width, s->height }); /* We ignore the spec here and guess a bit as reality does not * match the spec, see for example res_change_ffmpeg_aspect.ts * and sequence-display-aspect.mpg. * issue1613, 621, 562 */ if ((s1->pan_scan.width == 0) || (s1->pan_scan.height == 0) || (av_cmp_q(dar, (AVRational) { 4, 3 }) && av_cmp_q(dar, (AVRational) { 16, 9 }))) { s->avctx->sample_aspect_ratio = av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info], (AVRational) { s->width, s->height }); } else { s->avctx->sample_aspect_ratio = av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info], (AVRational) { s1->pan_scan.width, s1->pan_scan.height }); // issue1613 4/3 16/9 -> 16/9 // res_change_ffmpeg_aspect.ts 4/3 225/44 ->4/3 // widescreen-issue562.mpg 4/3 16/9 -> 16/9 // s->avctx->sample_aspect_ratio = av_mul_q(s->avctx->sample_aspect_ratio, (AVRational) {s->width, s->height}); ff_dlog(avctx, "aspect A %d/%d\n", ff_mpeg2_aspect[s->aspect_ratio_info].num, ff_mpeg2_aspect[s->aspect_ratio_info].den); ff_dlog(avctx, "aspect B %d/%d\n", s->avctx->sample_aspect_ratio.num, s->avctx->sample_aspect_ratio.den); } } else { s->avctx->sample_aspect_ratio = ff_mpeg2_aspect[s->aspect_ratio_info]; } } // MPEG-2 if (av_image_check_sar(s->width, s->height, avctx->sample_aspect_ratio) < 0) { av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n", avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den); avctx->sample_aspect_ratio = (AVRational){ 0, 1 }; } if ((s1->mpeg_enc_ctx_allocated == 0) || avctx->coded_width != s->width || avctx->coded_height != s->height || s1->save_width != s->width || s1->save_height != s->height || av_cmp_q(s1->save_aspect, s->avctx->sample_aspect_ratio) || (s1->save_progressive_seq != s->progressive_sequence && FFALIGN(s->height, 16) != FFALIGN(s->height, 32)) || 0) { if (s1->mpeg_enc_ctx_allocated) { ParseContext pc = s->parse_context; s->parse_context.buffer = 0; ff_mpv_common_end(s); s->parse_context = pc; s1->mpeg_enc_ctx_allocated = 0; } ret = ff_set_dimensions(avctx, s->width, s->height); if (ret < 0) return ret; if (avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO && s->bit_rate) { avctx->rc_max_rate = s->bit_rate; } else if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO && s->bit_rate && (s->bit_rate != 0x3FFFF*400 || s->vbv_delay != 0xFFFF)) { avctx->bit_rate = s->bit_rate; } s1->save_aspect = s->avctx->sample_aspect_ratio; s1->save_width = s->width; s1->save_height = s->height; s1->save_progressive_seq = s->progressive_sequence; /* low_delay may be forced, in this case we will have B-frames * that behave like P-frames. */ avctx->has_b_frames = !s->low_delay; if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO) { // MPEG-1 fps avctx->framerate = ff_mpeg12_frame_rate_tab[s->frame_rate_index]; avctx->ticks_per_frame = 1; avctx->chroma_sample_location = AVCHROMA_LOC_CENTER; } else { // MPEG-2 // MPEG-2 fps av_reduce(&s->avctx->framerate.num, &s->avctx->framerate.den, ff_mpeg12_frame_rate_tab[s->frame_rate_index].num * s1->frame_rate_ext.num, ff_mpeg12_frame_rate_tab[s->frame_rate_index].den * s1->frame_rate_ext.den, 1 << 30); avctx->ticks_per_frame = 2; switch (s->chroma_format) { case 1: avctx->chroma_sample_location = AVCHROMA_LOC_LEFT; break; case 2: case 3: avctx->chroma_sample_location = AVCHROMA_LOC_TOPLEFT; break; default: av_assert0(0); } } // MPEG-2 avctx->pix_fmt = mpeg_get_pixelformat(avctx); setup_hwaccel_for_pixfmt(avctx); /* Quantization matrices may need reordering * if DCT permutation is changed. */ memcpy(old_permutation, s->idsp.idct_permutation, 64 * sizeof(uint8_t)); ff_mpv_idct_init(s); if ((ret = ff_mpv_common_init(s)) < 0) return ret; quant_matrix_rebuild(s->intra_matrix, old_permutation, s->idsp.idct_permutation); quant_matrix_rebuild(s->inter_matrix, old_permutation, s->idsp.idct_permutation); quant_matrix_rebuild(s->chroma_intra_matrix, old_permutation, s->idsp.idct_permutation); quant_matrix_rebuild(s->chroma_inter_matrix, old_permutation, s->idsp.idct_permutation); s1->mpeg_enc_ctx_allocated = 1; } return 0; }


static void mxf_write_index_table_segment(AVFormatContext *s) { MXFContext *mxf = s->priv_data; AVIOContext *pb = s->pb; int i, j, temporal_reordering = 0; int key_index = mxf->last_key_index; av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count); if (!mxf->edit_units_count && !mxf->edit_unit_byte_count) return; avio_write(pb, index_table_segment_key, 16); if (mxf->edit_unit_byte_count) { klv_encode_ber_length(pb, 80); } else { klv_encode_ber_length(pb, 85 + 12+(s->nb_streams+1)*6 + 12+mxf->edit_units_count*(11+mxf->slice_count*4)); } // instance id mxf_write_local_tag(pb, 16, 0x3C0A); mxf_write_uuid(pb, IndexTableSegment, 0); // index edit rate mxf_write_local_tag(pb, 8, 0x3F0B); avio_wb32(pb, mxf->time_base.den); avio_wb32(pb, mxf->time_base.num); // index start position mxf_write_local_tag(pb, 8, 0x3F0C); avio_wb64(pb, mxf->last_indexed_edit_unit); // index duration mxf_write_local_tag(pb, 8, 0x3F0D); if (mxf->edit_unit_byte_count) avio_wb64(pb, 0); // index table covers whole container else avio_wb64(pb, mxf->edit_units_count); // edit unit byte count mxf_write_local_tag(pb, 4, 0x3F05); avio_wb32(pb, mxf->edit_unit_byte_count); // index sid mxf_write_local_tag(pb, 4, 0x3F06); avio_wb32(pb, 2); // body sid mxf_write_local_tag(pb, 4, 0x3F07); avio_wb32(pb, 1); if (!mxf->edit_unit_byte_count) { // real slice count - 1 mxf_write_local_tag(pb, 1, 0x3F08); avio_w8(pb, mxf->slice_count); // delta entry array mxf_write_local_tag(pb, 8 + (s->nb_streams+1)*6, 0x3F09); avio_wb32(pb, s->nb_streams+1); // num of entries avio_wb32(pb, 6); // size of one entry // write system item delta entry avio_w8(pb, 0); avio_w8(pb, 0); // slice entry avio_wb32(pb, 0); // element delta for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MXFStreamContext *sc = st->priv_data; avio_w8(pb, sc->temporal_reordering); if (sc->temporal_reordering) temporal_reordering = 1; if (i == 0) { // video track avio_w8(pb, 0); // slice number avio_wb32(pb, KAG_SIZE); // system item size including klv fill } else { // audio track unsigned audio_frame_size = sc->aic.samples[0]*sc->aic.sample_size; audio_frame_size += klv_fill_size(audio_frame_size); avio_w8(pb, 1); avio_wb32(pb, (i-1)*audio_frame_size); // element delta } } mxf_write_local_tag(pb, 8 + mxf->edit_units_count*(11+mxf->slice_count*4), 0x3F0A); avio_wb32(pb, mxf->edit_units_count); // num of entries avio_wb32(pb, 11+mxf->slice_count*4); // size of one entry for (i = 0; i < mxf->edit_units_count; i++) { int temporal_offset = 0; if (!(mxf->index_entries[i].flags & 0x33)) { // I frame mxf->last_key_index = key_index; key_index = i; } if (temporal_reordering) { int pic_num_in_gop = i - key_index; if (pic_num_in_gop != mxf->index_entries[i].temporal_ref) { for (j = key_index; j < mxf->edit_units_count; j++) { if (pic_num_in_gop == mxf->index_entries[j].temporal_ref) break; } if (j == mxf->edit_units_count) av_log(s, AV_LOG_WARNING, "missing frames\n"); temporal_offset = j - key_index - pic_num_in_gop; } } avio_w8(pb, temporal_offset); if ((mxf->index_entries[i].flags & 0x30) == 0x30) { // back and forward prediction avio_w8(pb, mxf->last_key_index - i); } else { avio_w8(pb, key_index - i); // key frame offset if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward mxf->last_key_index = key_index; } if (!(mxf->index_entries[i].flags & 0x33) && // I frame mxf->index_entries[i].flags & 0x40 && !temporal_offset) mxf->index_entries[i].flags |= 0x80; // random access avio_w8(pb, mxf->index_entries[i].flags); // stream offset avio_wb64(pb, mxf->index_entries[i].offset); if (s->nb_streams > 1) avio_wb32(pb, mxf->index_entries[i].slice_offset); } mxf->last_key_index = key_index - mxf->edit_units_count; mxf->last_indexed_edit_unit += mxf->edit_units_count; mxf->edit_units_count = 0; } }


static int vaapi_h264_decode_slice(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size) { H264Context * const h = avctx->priv_data; H264SliceContext *sl = &h->slice_ctx[0]; VASliceParameterBufferH264 *slice_param; ff_dlog(avctx, "vaapi_h264_decode_slice(): buffer %p, size %d\n", buffer, size); /* Fill in VASliceParameterBufferH264. */ slice_param = (VASliceParameterBufferH264 *)ff_vaapi_alloc_slice(avctx->hwaccel_context, buffer, size); if (!slice_param) return -1; slice_param->slice_data_bit_offset = get_bits_count(&sl->gb); slice_param->first_mb_in_slice = (sl->mb_y >> FIELD_OR_MBAFF_PICTURE(h)) * h->mb_width + sl->mb_x; slice_param->slice_type = ff_h264_get_slice_type(sl); slice_param->direct_spatial_mv_pred_flag = sl->slice_type == AV_PICTURE_TYPE_B ? sl->direct_spatial_mv_pred : 0; slice_param->num_ref_idx_l0_active_minus1 = sl->list_count > 0 ? sl->ref_count[0] - 1 : 0; slice_param->num_ref_idx_l1_active_minus1 = sl->list_count > 1 ? sl->ref_count[1] - 1 : 0; slice_param->cabac_init_idc = sl->cabac_init_idc; slice_param->slice_qp_delta = sl->qscale - h->pps.init_qp; slice_param->disable_deblocking_filter_idc = sl->deblocking_filter < 2 ? !sl->deblocking_filter : sl->deblocking_filter; slice_param->slice_alpha_c0_offset_div2 = sl->slice_alpha_c0_offset / 2; slice_param->slice_beta_offset_div2 = sl->slice_beta_offset / 2; slice_param->luma_log2_weight_denom = sl->pwt.luma_log2_weight_denom; slice_param->chroma_log2_weight_denom = sl->pwt.chroma_log2_weight_denom; fill_vaapi_RefPicList(slice_param->RefPicList0, sl->ref_list[0], sl->list_count > 0 ? sl->ref_count[0] : 0); fill_vaapi_RefPicList(slice_param->RefPicList1, sl->ref_list[1], sl->list_count > 1 ? sl->ref_count[1] : 0); fill_vaapi_plain_pred_weight_table(h, 0, &slice_param->luma_weight_l0_flag, slice_param->luma_weight_l0, slice_param->luma_offset_l0, &slice_param->chroma_weight_l0_flag, slice_param->chroma_weight_l0, slice_param->chroma_offset_l0); fill_vaapi_plain_pred_weight_table(h, 1, &slice_param->luma_weight_l1_flag, slice_param->luma_weight_l1, slice_param->luma_offset_l1, &slice_param->chroma_weight_l1_flag, slice_param->chroma_weight_l1, slice_param->chroma_offset_l1); return 0; }


static void adaptive_quantization(MpegEncContext *s, double q){ int i; const float lumi_masking= s->avctx->lumi_masking / (128.0*128.0); const float dark_masking= s->avctx->dark_masking / (128.0*128.0); const float temp_cplx_masking= s->avctx->temporal_cplx_masking; const float spatial_cplx_masking = s->avctx->spatial_cplx_masking; const float p_masking = s->avctx->p_masking; float bits_sum= 0.0; float cplx_sum= 0.0; float cplx_tab[s->mb_num]; float bits_tab[s->mb_num]; const int qmin= 2; //s->avctx->mb_qmin; const int qmax= 31; //s->avctx->mb_qmax; Picture * const pic= &s->current_picture; for(i=0; i<s->mb_num; i++){ float temp_cplx= sqrt(pic->mc_mb_var[i]); float spat_cplx= sqrt(pic->mb_var[i]); const int lumi= pic->mb_mean[i]; float bits, cplx, factor; if(spat_cplx < q/3) spat_cplx= q/3; //FIXME finetune if(temp_cplx < q/3) temp_cplx= q/3; //FIXME finetune if((s->mb_type[i]&MB_TYPE_INTRA)){//FIXME hq mode cplx= spat_cplx; factor= 1.0 + p_masking; }else{ cplx= temp_cplx; factor= pow(temp_cplx, - temp_cplx_masking); } factor*=pow(spat_cplx, - spatial_cplx_masking); if(lumi>127) factor*= (1.0 - (lumi-128)*(lumi-128)*lumi_masking); else factor*= (1.0 - (lumi-128)*(lumi-128)*dark_masking); if(factor<0.00001) factor= 0.00001; bits= cplx*factor; cplx_sum+= cplx; bits_sum+= bits; cplx_tab[i]= cplx; bits_tab[i]= bits; } /* handle qmin/qmax cliping */ if(s->flags&CODEC_FLAG_NORMALIZE_AQP){ for(i=0; i<s->mb_num; i++){ float newq= q*cplx_tab[i]/bits_tab[i]; newq*= bits_sum/cplx_sum; if (newq > qmax){ bits_sum -= bits_tab[i]; cplx_sum -= cplx_tab[i]*q/qmax; } else if(newq < qmin){ bits_sum -= bits_tab[i]; cplx_sum -= cplx_tab[i]*q/qmin; } } } for(i=0; i<s->mb_num; i++){ float newq= q*cplx_tab[i]/bits_tab[i]; int intq; if(s->flags&CODEC_FLAG_NORMALIZE_AQP){ newq*= bits_sum/cplx_sum; } if(i && ABS(pic->qscale_table[i-1] - newq)<0.75) intq= pic->qscale_table[i-1]; else intq= (int)(newq + 0.5); if (intq > qmax) intq= qmax; else if(intq < qmin) intq= qmin; //if(i%s->mb_width==0) printf("\n"); //printf("%2d%3d ", intq, ff_sqrt(s->mc_mb_var[i])); pic->qscale_table[i]= intq; } }


static int flashsv2_prime(FlashSVContext *s, uint8_t *src, int size, int unp_size) { z_stream zs; int zret; // Zlib return code zs.zalloc = NULL; zs.zfree = NULL; zs.opaque = NULL; s->zstream.next_in = src; s->zstream.avail_in = size; s->zstream.next_out = s->tmpblock; s->zstream.avail_out = s->block_size * 3; inflate(&s->zstream, Z_SYNC_FLUSH); deflateInit(&zs, 0); zs.next_in = s->tmpblock; zs.avail_in = s->block_size * 3 - s->zstream.avail_out; zs.next_out = s->deflate_block; zs.avail_out = s->deflate_block_size; deflate(&zs, Z_SYNC_FLUSH); deflateEnd(&zs); if ((zret = inflateReset(&s->zstream)) != Z_OK) { av_log(s->avctx, AV_LOG_ERROR, "Inflate reset error: %d\n", zret); return AVERROR_UNKNOWN; } s->zstream.next_in = s->deflate_block; s->zstream.avail_in = s->deflate_block_size - zs.avail_out; s->zstream.next_out = s->tmpblock; s->zstream.avail_out = s->block_size * 3; inflate(&s->zstream, Z_SYNC_FLUSH); return 0; }


int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num_bits = av_log2(s->mb_num - 1) + 1; int header_extension = 0, mb_num, len; /* is there enough space left for a video packet + header */ if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20) return -1; for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; if (len != ff_mpeg4_get_video_packet_prefix_length(s)) { av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n"); return -1; } if (ctx->shape != RECT_SHAPE) { header_extension = get_bits1(&s->gb); // FIXME more stuff here } mb_num = get_bits(&s->gb, mb_num_bits); if (mb_num >= s->mb_num) { av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num); return -1; } s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) { int qscale = get_bits(&s->gb, s->quant_precision); if (qscale) s->chroma_qscale = s->qscale = qscale; } if (ctx->shape == RECT_SHAPE) header_extension = get_bits1(&s->gb); if (header_extension) { int time_incr = 0; while (get_bits1(&s->gb) != 0) time_incr++; check_marker(s->avctx, &s->gb, "before time_increment in video packed header"); skip_bits(&s->gb, ctx->time_increment_bits); /* time_increment */ check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header"); skip_bits(&s->gb, 2); /* vop coding type */ // FIXME not rect stuff here if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits(&s->gb, 3); /* intra dc vlc threshold */ // FIXME don't just ignore everything if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0) return AVERROR_INVALIDDATA; av_log(s->avctx, AV_LOG_ERROR, "untested\n"); } // FIXME reduced res stuff here if (s->pict_type != AV_PICTURE_TYPE_I) { int f_code = get_bits(&s->gb, 3); /* fcode_for */ if (f_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n"); } if (s->pict_type == AV_PICTURE_TYPE_B) { int b_code = get_bits(&s->gb, 3); if (b_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n"); } } } if (ctx->new_pred) decode_new_pred(ctx, &s->gb); return 0; }


static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q, uint8_t *properties) { int compno; if (s->buf_end - s->buf < 1) return AVERROR(EINVAL); compno = bytestream_get_byte(&s->buf); properties[compno] |= HAD_QCC; return get_qcx(s, n - 1, q + compno); }


static int mkv_write_tracks(AVFormatContext *s) { MatroskaMuxContext *mkv = s->priv_data; AVIOContext *dyn_cp, *pb = s->pb; ebml_master tracks; int i, ret, default_stream_exists = 0; ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb)); if (ret < 0) return ret; ret = start_ebml_master_crc32(pb, &dyn_cp, &tracks, MATROSKA_ID_TRACKS, 0); if (ret < 0) return ret; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT; } for (i = 0; i < s->nb_streams; i++) { ret = mkv_write_track(s, mkv, i, dyn_cp, default_stream_exists); if (ret < 0) return ret; } end_ebml_master_crc32(pb, &dyn_cp, mkv, tracks); return 0; }


static void v9fs_stat(void *opaque) { int32_t fid; V9fsStat v9stat; ssize_t err = 0; size_t offset = 7; struct stat stbuf; V9fsFidState *fidp; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; pdu_unmarshal(pdu, offset, "d", &fid); fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -ENOENT; goto out_nofid; } err = v9fs_co_lstat(pdu, &fidp->path, &stbuf); if (err < 0) { goto out; } err = stat_to_v9stat(pdu, &fidp->path, &stbuf, &v9stat); if (err < 0) { goto out; } offset += pdu_marshal(pdu, offset, "wS", 0, &v9stat); err = offset; v9fs_stat_free(&v9stat); out: put_fid(pdu, fidp); out_nofid: trace_v9fs_stat_return(pdu->tag, pdu->id, v9stat.mode, v9stat.atime, v9stat.mtime, v9stat.length); complete_pdu(s, pdu, err); }


static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, int Al){ int i, mb_x, mb_y; uint8_t* data[MAX_COMPONENTS]; int linesize[MAX_COMPONENTS]; for(i=0; i < nb_components; i++) { int c = s->comp_index[i]; data[c] = s->picture.data[c]; linesize[c]=s->linesize[c]; s->coefs_finished[c] |= 1; if(s->flipped) { //picture should be flipped upside-down for this codec assert(!(s->avctx->flags & CODEC_FLAG_EMU_EDGE)); data[c] += (linesize[c] * (s->v_scount[i] * (8 * s->mb_height -((s->height/s->v_max)&7)) - 1 )); linesize[c] *= -1; } } for(mb_y = 0; mb_y < s->mb_height; mb_y++) { for(mb_x = 0; mb_x < s->mb_width; mb_x++) { if (s->restart_interval && !s->restart_count) s->restart_count = s->restart_interval; for(i=0;i<nb_components;i++) { uint8_t *ptr; int n, h, v, x, y, c, j; n = s->nb_blocks[i]; c = s->comp_index[i]; h = s->h_scount[i]; v = s->v_scount[i]; x = 0; y = 0; for(j=0;j<n;j++) { ptr = data[c] + (((linesize[c] * (v * mb_y + y) * 8) + (h * mb_x + x) * 8) >> s->avctx->lowres); if(s->interlaced && s->bottom_field) ptr += linesize[c] >> 1; if(!s->progressive) { s->dsp.clear_block(s->block); if(decode_block(s, s->block, i, s->dc_index[i], s->ac_index[i], s->quant_matrixes[ s->quant_index[c] ]) < 0) { av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x); return -1; } s->dsp.idct_put(ptr, linesize[c], s->block); } else { int block_idx = s->block_stride[c] * (v * mb_y + y) + (h * mb_x + x); DCTELEM *block = s->blocks[c][block_idx]; if(Ah) block[0] += get_bits1(&s->gb) * s->quant_matrixes[ s->quant_index[c] ][0] << Al; else if(decode_dc_progressive(s, block, i, s->dc_index[i], s->quant_matrixes[ s->quant_index[c] ], Al) < 0) { av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x); return -1; } } // av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n", mb_y, mb_x); //av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d \n", mb_x, mb_y, x, y, c, s->bottom_field, (v * mb_y + y) * 8, (h * mb_x + x) * 8); if (++x == h) { x = 0; y++; } } } if (s->restart_interval && !--s->restart_count) { align_get_bits(&s->gb); skip_bits(&s->gb, 16); /* skip RSTn */ for (i=0; i<nb_components; i++) /* reset dc */ s->last_dc[i] = 1024; } } } return 0; }


static double eval_expr(Parser *p, AVExpr *e) { switch (e->type) { case e_value: return e->value; case e_const: return e->value * p->const_values[e->a.const_index]; case e_func0: return e->value * e->a.func0(eval_expr(p, e->param[0])); case e_func1: return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0])); case e_func2: return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1])); case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0]))); case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); } case e_ld: return e->value * p->var[av_clip(eval_expr(p, e->param[0]), 0, VARS-1)]; case e_isnan: return e->value * !!isnan(eval_expr(p, e->param[0])); case e_floor: return e->value * floor(eval_expr(p, e->param[0])); case e_ceil : return e->value * ceil (eval_expr(p, e->param[0])); case e_trunc: return e->value * trunc(eval_expr(p, e->param[0])); case e_sqrt: return e->value * sqrt (eval_expr(p, e->param[0])); case e_not: return e->value * (eval_expr(p, e->param[0]) == 0); case e_if: return e->value * ( eval_expr(p, e->param[0]) ? eval_expr(p, e->param[1]) : 0); case e_ifnot: return e->value * (!eval_expr(p, e->param[0]) ? eval_expr(p, e->param[1]) : 0); case e_random:{ int idx= av_clip(eval_expr(p, e->param[0]), 0, VARS-1); uint64_t r= isnan(p->var[idx]) ? 0 : p->var[idx]; r= r*1664525+1013904223; p->var[idx]= r; return e->value * (r * (1.0/UINT64_MAX)); } case e_while: { double d = NAN; while (eval_expr(p, e->param[0])) d=eval_expr(p, e->param[1]); return d; } case e_taylor: { double t = 1, d = 0, v; double x = eval_expr(p, e->param[1]); int id = e->param[2] ? av_clip(eval_expr(p, e->param[2]), 0, VARS-1) : 0; int i; double var0 = p->var[id]; for(i=0; i<1000; i++) { double ld = d; p->var[id] = i; v = eval_expr(p, e->param[0]); d += t*v; if(ld==d && v) break; t *= x / (i+1); } p->var[id] = var0; return d; } case e_root: { int i; double low = -1, high = -1, v, low_v = -DBL_MAX, high_v = DBL_MAX; double var0 = p->var[0]; double x_max = eval_expr(p, e->param[1]); for(i=-1; i<1024; i++) { if(i<255) { p->var[0] = av_reverse[i&255]*x_max/255; } else { p->var[0] = x_max*pow(0.9, i-255); if (i&1) p->var[0] *= -1; if (i&2) p->var[0] += low; else p->var[0] += high; } v = eval_expr(p, e->param[0]); if (v<=0 && v>low_v) { low = p->var[0]; low_v = v; } if (v>=0 && v<high_v) { high = p->var[0]; high_v = v; } if (low>=0 && high>=0){ while (1) { p->var[0] = (low+high)*0.5; if (low == p->var[0] || high == p->var[0]) break; v = eval_expr(p, e->param[0]); if (v<=0) low = p->var[0]; if (v>=0) high= p->var[0]; if (isnan(v)) { low = high = v; break; } } break; } } p->var[0] = var0; return -low_v<high_v ? low : high; } default: { double d = eval_expr(p, e->param[0]); double d2 = eval_expr(p, e->param[1]); switch (e->type) { case e_mod: return e->value * (d - floor(d/d2)*d2); case e_gcd: return e->value * av_gcd(d,d2); case e_max: return e->value * (d > d2 ? d : d2); case e_min: return e->value * (d < d2 ? d : d2); case e_eq: return e->value * (d == d2 ? 1.0 : 0.0); case e_gt: return e->value * (d > d2 ? 1.0 : 0.0); case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0); case e_pow: return e->value * pow(d, d2); case e_mul: return e->value * (d * d2); case e_div: return e->value * (d / d2); case e_add: return e->value * (d + d2); case e_last:return e->value * d2; case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2); case e_hypot:return e->value * (sqrt(d*d + d2*d2)); } } } return NAN; }


static int deband_16_coupling_c(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) { DebandContext *s = ctx->priv; ThreadData *td = arg; AVFrame *in = td->in; AVFrame *out = td->out; const int start = (s->planeheight[0] * jobnr ) / nb_jobs; const int end = (s->planeheight[0] * (jobnr+1)) / nb_jobs; int x, y, p, z; for (y = start; y < end; y++) { const int pos = y * s->planewidth[0]; for (x = 0; x < s->planewidth[p]; x++) { const int x_pos = s->x_pos[pos + x]; const int y_pos = s->y_pos[pos + x]; int avg[4], cmp[4] = { 0 }, src[4]; for (p = 0; p < s->nb_components; p++) { const uint16_t *src_ptr = (const uint16_t *)in->data[p]; const int src_linesize = in->linesize[p] / 2; const int thr = s->thr[p]; const int w = s->planewidth[p] - 1; const int h = s->planeheight[p] - 1; const int ref0 = src_ptr[av_clip(y + y_pos, 0, h) * src_linesize + av_clip(x + x_pos, 0, w)]; const int ref1 = src_ptr[av_clip(y + -y_pos, 0, h) * src_linesize + av_clip(x + x_pos, 0, w)]; const int ref2 = src_ptr[av_clip(y + -y_pos, 0, h) * src_linesize + av_clip(x + -x_pos, 0, w)]; const int ref3 = src_ptr[av_clip(y + y_pos, 0, h) * src_linesize + av_clip(x + -x_pos, 0, w)]; const int src0 = src_ptr[y * src_linesize + x]; src[p] = src0; avg[p] = get_avg(ref0, ref1, ref2, ref3); if (s->blur) { cmp[p] = FFABS(src0 - avg[p]) < thr; } else { cmp[p] = (FFABS(src0 - ref0) < thr) && (FFABS(src0 - ref1) < thr) && (FFABS(src0 - ref2) < thr) && (FFABS(src0 - ref3) < thr); } } for (z = 0; z < s->nb_components; z++) if (!cmp[z]) break; if (z == s->nb_components) { for (p = 0; p < s->nb_components; p++) { const int dst_linesize = out->linesize[p] / 2; uint16_t *dst = (uint16_t *)out->data[p] + y * dst_linesize + x; dst[0] = avg[p]; } } else { for (p = 0; p < s->nb_components; p++) { const int dst_linesize = out->linesize[p] / 2; uint16_t *dst = (uint16_t *)out->data[p] + y * dst_linesize + x; dst[0] = src[p]; } } } } return 0; }


static int tiff_decode_tag(TiffContext *s) { unsigned tag, type, count, off, value = 0; int i, j, k, pos, start; int ret; uint32_t *pal; double *dp; tag = tget_short(&s->gb, s->le); type = tget_short(&s->gb, s->le); count = tget_long(&s->gb, s->le); off = tget_long(&s->gb, s->le); start = bytestream2_tell(&s->gb); if (type == 0 || type >= FF_ARRAY_ELEMS(type_sizes)) { av_log(s->avctx, AV_LOG_DEBUG, "Unknown tiff type (%u) encountered\n", type); return 0; } if (count == 1) { switch (type) { case TIFF_BYTE: case TIFF_SHORT: bytestream2_seek(&s->gb, -4, SEEK_CUR); value = tget(&s->gb, type, s->le); break; case TIFF_LONG: value = off; break; case TIFF_STRING: if (count <= 4) { bytestream2_seek(&s->gb, -4, SEEK_CUR); break; } default: value = UINT_MAX; bytestream2_seek(&s->gb, off, SEEK_SET); } } else { if (count <= 4 && type_sizes[type] * count <= 4) { bytestream2_seek(&s->gb, -4, SEEK_CUR); } else { bytestream2_seek(&s->gb, off, SEEK_SET); } } switch (tag) { case TIFF_WIDTH: s->width = value; break; case TIFF_HEIGHT: s->height = value; break; case TIFF_BPP: s->bppcount = count; if (count > 4) { av_log(s->avctx, AV_LOG_ERROR, "This format is not supported (bpp=%d, %d components)\n", s->bpp, count); return AVERROR_INVALIDDATA; } if (count == 1) s->bpp = value; else { switch (type) { case TIFF_BYTE: s->bpp = (off & 0xFF) + ((off >> 8) & 0xFF) + ((off >> 16) & 0xFF) + ((off >> 24) & 0xFF); break; case TIFF_SHORT: case TIFF_LONG: s->bpp = 0; if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count) return AVERROR_INVALIDDATA; for (i = 0; i < count; i++) s->bpp += tget(&s->gb, type, s->le); break; default: s->bpp = -1; } } break; case TIFF_SAMPLES_PER_PIXEL: if (count != 1) { av_log(s->avctx, AV_LOG_ERROR, "Samples per pixel requires a single value, many provided\n"); return AVERROR_INVALIDDATA; } if (value > 4U) { av_log(s->avctx, AV_LOG_ERROR, "Samples per pixel %d is too large\n", value); return AVERROR_INVALIDDATA; } if (s->bppcount == 1) s->bpp *= value; s->bppcount = value; break; case TIFF_COMPR: s->compr = value; s->predictor = 0; switch (s->compr) { case TIFF_RAW: case TIFF_PACKBITS: case TIFF_LZW: case TIFF_CCITT_RLE: break; case TIFF_G3: case TIFF_G4: s->fax_opts = 0; break; case TIFF_DEFLATE: case TIFF_ADOBE_DEFLATE: #if CONFIG_ZLIB break; #else av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n"); return AVERROR(ENOSYS); #endif case TIFF_JPEG: case TIFF_NEWJPEG: av_log(s->avctx, AV_LOG_ERROR, "JPEG compression is not supported\n"); return AVERROR_PATCHWELCOME; default: av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n", s->compr); return AVERROR_INVALIDDATA; } break; case TIFF_ROWSPERSTRIP: if (type == TIFF_LONG && value == UINT_MAX) value = s->height; if (value < 1) { av_log(s->avctx, AV_LOG_ERROR, "Incorrect value of rows per strip\n"); return AVERROR_INVALIDDATA; } s->rps = value; break; case TIFF_STRIP_OFFS: if (count == 1) { s->strippos = 0; s->stripoff = value; } else s->strippos = off; s->strips = count; if (s->strips == 1) s->rps = s->height; s->sot = type; if (s->strippos > bytestream2_size(&s->gb)) { av_log(s->avctx, AV_LOG_ERROR, "Tag referencing position outside the image\n"); return AVERROR_INVALIDDATA; } break; case TIFF_STRIP_SIZE: if (count == 1) { s->stripsizesoff = 0; s->stripsize = value; s->strips = 1; } else { s->stripsizesoff = off; } s->strips = count; s->sstype = type; if (s->stripsizesoff > bytestream2_size(&s->gb)) { av_log(s->avctx, AV_LOG_ERROR, "Tag referencing position outside the image\n"); return AVERROR_INVALIDDATA; } break; case TIFF_TILE_BYTE_COUNTS: case TIFF_TILE_LENGTH: case TIFF_TILE_OFFSETS: case TIFF_TILE_WIDTH: av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n"); return AVERROR_PATCHWELCOME; break; case TIFF_PREDICTOR: s->predictor = value; break; case TIFF_INVERT: switch (value) { case 0: s->invert = 1; break; case 1: s->invert = 0; break; case 2: case 3: break; default: av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n", value); return AVERROR_INVALIDDATA; } break; case TIFF_FILL_ORDER: if (value < 1 || value > 2) { av_log(s->avctx, AV_LOG_ERROR, "Unknown FillOrder value %d, trying default one\n", value); value = 1; } s->fill_order = value - 1; break; case TIFF_PAL: pal = (uint32_t *) s->palette; off = type_sizes[type]; if (count / 3 > 256 || bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3) return AVERROR_INVALIDDATA; off = (type_sizes[type] - 1) << 3; for (k = 2; k >= 0; k--) { for (i = 0; i < count / 3; i++) { if (k == 2) pal[i] = 0xFFU << 24; j = (tget(&s->gb, type, s->le) >> off) << (k * 8); pal[i] |= j; } } s->palette_is_set = 1; break; case TIFF_PLANAR: if (value == 2) { av_log(s->avctx, AV_LOG_ERROR, "Planar format is not supported\n"); return AVERROR_PATCHWELCOME; } break; case TIFF_T4OPTIONS: if (s->compr == TIFF_G3) s->fax_opts = value; break; case TIFF_T6OPTIONS: if (s->compr == TIFF_G4) s->fax_opts = value; break; #define ADD_METADATA(count, name, sep)\ if ((ret = add_metadata(count, type, name, sep, s)) < 0) {\ av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\ return ret;\ } case TIFF_MODEL_PIXEL_SCALE: ADD_METADATA(count, "ModelPixelScaleTag", NULL); break; case TIFF_MODEL_TRANSFORMATION: ADD_METADATA(count, "ModelTransformationTag", NULL); break; case TIFF_MODEL_TIEPOINT: ADD_METADATA(count, "ModelTiepointTag", NULL); break; case TIFF_GEO_KEY_DIRECTORY: ADD_METADATA(1, "GeoTIFF_Version", NULL); ADD_METADATA(2, "GeoTIFF_Key_Revision", "."); s->geotag_count = tget_short(&s->gb, s->le); if (s->geotag_count > count / 4 - 1) { s->geotag_count = count / 4 - 1; av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n"); } if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4) { s->geotag_count = 0; return -1; } s->geotags = av_mallocz(sizeof(TiffGeoTag) * s->geotag_count); if (!s->geotags) { av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n"); s->geotag_count = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->geotag_count; i++) { s->geotags[i].key = tget_short(&s->gb, s->le); s->geotags[i].type = tget_short(&s->gb, s->le); s->geotags[i].count = tget_short(&s->gb, s->le); if (!s->geotags[i].type) s->geotags[i].val = get_geokey_val(s->geotags[i].key, tget_short(&s->gb, s->le)); else s->geotags[i].offset = tget_short(&s->gb, s->le); } break; case TIFF_GEO_DOUBLE_PARAMS: if (count >= INT_MAX / sizeof(int64_t)) return AVERROR_INVALIDDATA; if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t)) return AVERROR_INVALIDDATA; dp = av_malloc(count * sizeof(double)); if (!dp) { av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n"); return AVERROR(ENOMEM); } for (i = 0; i < count; i++) dp[i] = tget_double(&s->gb, s->le); for (i = 0; i < s->geotag_count; i++) { if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) { if (s->geotags[i].count == 0 || s->geotags[i].offset + s->geotags[i].count > count) { av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key); } else { char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", "); if (!ap) { av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n"); av_freep(&dp); return AVERROR(ENOMEM); } s->geotags[i].val = ap; } } } av_freep(&dp); break; case TIFF_GEO_ASCII_PARAMS: pos = bytestream2_tell(&s->gb); for (i = 0; i < s->geotag_count; i++) { if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) { if (s->geotags[i].count == 0 || s->geotags[i].offset + s->geotags[i].count > count) { av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key); } else { char *ap; bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET); if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count) return AVERROR_INVALIDDATA; ap = av_malloc(s->geotags[i].count); if (!ap) { av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n"); return AVERROR(ENOMEM); } bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count); ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte s->geotags[i].val = ap; } } } break; case TIFF_ARTIST: ADD_METADATA(count, "artist", NULL); break; case TIFF_COPYRIGHT: ADD_METADATA(count, "copyright", NULL); break; case TIFF_DATE: ADD_METADATA(count, "date", NULL); break; case TIFF_DOCUMENT_NAME: ADD_METADATA(count, "document_name", NULL); break; case TIFF_HOST_COMPUTER: ADD_METADATA(count, "computer", NULL); break; case TIFF_IMAGE_DESCRIPTION: ADD_METADATA(count, "description", NULL); break; case TIFF_MAKE: ADD_METADATA(count, "make", NULL); break; case TIFF_MODEL: ADD_METADATA(count, "model", NULL); break; case TIFF_PAGE_NAME: ADD_METADATA(count, "page_name", NULL); break; case TIFF_PAGE_NUMBER: ADD_METADATA(count, "page_number", " / "); break; case TIFF_SOFTWARE_NAME: ADD_METADATA(count, "software", NULL); break; default: av_log(s->avctx, AV_LOG_DEBUG, "Unknown or unsupported tag %d/0X%0X\n", tag, tag); } bytestream2_seek(&s->gb, start, SEEK_SET); return 0; }


static void FUNC(put_hevc_epel_bi_w_v)(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride, int16_t *src2, int height, int denom, int wx0, int wx1, int ox0, int ox1, intptr_t mx, intptr_t my, int width) { int x, y; pixel *src = (pixel *)_src; ptrdiff_t srcstride = _srcstride / sizeof(pixel); const int8_t *filter = ff_hevc_epel_filters[my - 1]; pixel *dst = (pixel *)_dst; ptrdiff_t dststride = _dststride / sizeof(pixel); int shift = 14 + 1 - BIT_DEPTH; int log2Wd = denom + shift - 1; ox0 = ox0 * (1 << (BIT_DEPTH - 8)); ox1 = ox1 * (1 << (BIT_DEPTH - 8)); for (y = 0; y < height; y++) { for (x = 0; x < width; x++) dst[x] = av_clip_pixel(((EPEL_FILTER(src, srcstride) >> (BIT_DEPTH - 8)) * wx1 + src2[x] * wx0 + ((ox0 + ox1 + 1) << log2Wd)) >> (log2Wd + 1)); src += srcstride; dst += dststride; src2 += MAX_PB_SIZE; } }


DriveInfo *drive_init(QemuOpts *opts, int default_to_scsi) { const char *buf; const char *file = NULL; char devname[128]; const char *serial; const char *mediastr = ""; BlockInterfaceType type; enum { MEDIA_DISK, MEDIA_CDROM } media; int bus_id, unit_id; int cyls, heads, secs, translation; BlockDriver *drv = NULL; int max_devs; int index; int ro = 0; int bdrv_flags = 0; int on_read_error, on_write_error; const char *devaddr; DriveInfo *dinfo; BlockIOLimit io_limits; int snapshot = 0; bool copy_on_read; int ret; translation = BIOS_ATA_TRANSLATION_AUTO; media = MEDIA_DISK; /* extract parameters */ bus_id = qemu_opt_get_number(opts, "bus", 0); unit_id = qemu_opt_get_number(opts, "unit", -1); index = qemu_opt_get_number(opts, "index", -1); cyls = qemu_opt_get_number(opts, "cyls", 0); heads = qemu_opt_get_number(opts, "heads", 0); secs = qemu_opt_get_number(opts, "secs", 0); snapshot = qemu_opt_get_bool(opts, "snapshot", 0); ro = qemu_opt_get_bool(opts, "readonly", 0); copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false); file = qemu_opt_get(opts, "file"); serial = qemu_opt_get(opts, "serial"); if ((buf = qemu_opt_get(opts, "if")) != NULL) { pstrcpy(devname, sizeof(devname), buf); for (type = 0; type < IF_COUNT && strcmp(buf, if_name[type]); type++) ; if (type == IF_COUNT) { error_report("unsupported bus type '%s'", buf); return NULL; } } else { type = default_to_scsi ? IF_SCSI : IF_IDE; pstrcpy(devname, sizeof(devname), if_name[type]); } max_devs = if_max_devs[type]; if (cyls || heads || secs) { if (cyls < 1 || (type == IF_IDE && cyls > 16383)) { error_report("invalid physical cyls number"); return NULL; } if (heads < 1 || (type == IF_IDE && heads > 16)) { error_report("invalid physical heads number"); return NULL; } if (secs < 1 || (type == IF_IDE && secs > 63)) { error_report("invalid physical secs number"); return NULL; } } if ((buf = qemu_opt_get(opts, "trans")) != NULL) { if (!cyls) { error_report("'%s' trans must be used with cyls, heads and secs", buf); return NULL; } if (!strcmp(buf, "none")) translation = BIOS_ATA_TRANSLATION_NONE; else if (!strcmp(buf, "lba")) translation = BIOS_ATA_TRANSLATION_LBA; else if (!strcmp(buf, "auto")) translation = BIOS_ATA_TRANSLATION_AUTO; else { error_report("'%s' invalid translation type", buf); return NULL; } } if ((buf = qemu_opt_get(opts, "media")) != NULL) { if (!strcmp(buf, "disk")) { media = MEDIA_DISK; } else if (!strcmp(buf, "cdrom")) { if (cyls || secs || heads) { error_report("CHS can't be set with media=%s", buf); return NULL; } media = MEDIA_CDROM; } else { error_report("'%s' invalid media", buf); return NULL; } } if ((buf = qemu_opt_get(opts, "cache")) != NULL) { if (bdrv_parse_cache_flags(buf, &bdrv_flags) != 0) { error_report("invalid cache option"); return NULL; } } #ifdef CONFIG_LINUX_AIO if ((buf = qemu_opt_get(opts, "aio")) != NULL) { if (!strcmp(buf, "native")) { bdrv_flags |= BDRV_O_NATIVE_AIO; } else if (!strcmp(buf, "threads")) { /* this is the default */ } else { error_report("invalid aio option"); return NULL; } } #endif if ((buf = qemu_opt_get(opts, "format")) != NULL) { if (strcmp(buf, "?") == 0) { error_printf("Supported formats:"); bdrv_iterate_format(bdrv_format_print, NULL); error_printf("\n"); return NULL; } drv = bdrv_find_whitelisted_format(buf); if (!drv) { error_report("'%s' invalid format", buf); return NULL; } } /* disk I/O throttling */ io_limits.bps[BLOCK_IO_LIMIT_TOTAL] = qemu_opt_get_number(opts, "bps", 0); io_limits.bps[BLOCK_IO_LIMIT_READ] = qemu_opt_get_number(opts, "bps_rd", 0); io_limits.bps[BLOCK_IO_LIMIT_WRITE] = qemu_opt_get_number(opts, "bps_wr", 0); io_limits.iops[BLOCK_IO_LIMIT_TOTAL] = qemu_opt_get_number(opts, "iops", 0); io_limits.iops[BLOCK_IO_LIMIT_READ] = qemu_opt_get_number(opts, "iops_rd", 0); io_limits.iops[BLOCK_IO_LIMIT_WRITE] = qemu_opt_get_number(opts, "iops_wr", 0); if (!do_check_io_limits(&io_limits)) { error_report("bps(iops) and bps_rd/bps_wr(iops_rd/iops_wr) " "cannot be used at the same time"); return NULL; } on_write_error = BLOCK_ERR_STOP_ENOSPC; if ((buf = qemu_opt_get(opts, "werror")) != NULL) { if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) { error_report("werror is not supported by this bus type"); return NULL; } on_write_error = parse_block_error_action(buf, 0); if (on_write_error < 0) { return NULL; } } on_read_error = BLOCK_ERR_REPORT; if ((buf = qemu_opt_get(opts, "rerror")) != NULL) { if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI && type != IF_NONE) { error_report("rerror is not supported by this bus type"); return NULL; } on_read_error = parse_block_error_action(buf, 1); if (on_read_error < 0) { return NULL; } } if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) { if (type != IF_VIRTIO) { error_report("addr is not supported by this bus type"); return NULL; } } /* compute bus and unit according index */ if (index != -1) { if (bus_id != 0 || unit_id != -1) { error_report("index cannot be used with bus and unit"); return NULL; } bus_id = drive_index_to_bus_id(type, index); unit_id = drive_index_to_unit_id(type, index); } /* if user doesn't specify a unit_id, * try to find the first free */ if (unit_id == -1) { unit_id = 0; while (drive_get(type, bus_id, unit_id) != NULL) { unit_id++; if (max_devs && unit_id >= max_devs) { unit_id -= max_devs; bus_id++; } } } /* check unit id */ if (max_devs && unit_id >= max_devs) { error_report("unit %d too big (max is %d)", unit_id, max_devs - 1); return NULL; } /* * catch multiple definitions */ if (drive_get(type, bus_id, unit_id) != NULL) { error_report("drive with bus=%d, unit=%d (index=%d) exists", bus_id, unit_id, index); return NULL; } /* init */ dinfo = g_malloc0(sizeof(*dinfo)); if ((buf = qemu_opts_id(opts)) != NULL) { dinfo->id = g_strdup(buf); } else { /* no id supplied -> create one */ dinfo->id = g_malloc0(32); if (type == IF_IDE || type == IF_SCSI) mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd"; if (max_devs) snprintf(dinfo->id, 32, "%s%i%s%i", devname, bus_id, mediastr, unit_id); else snprintf(dinfo->id, 32, "%s%s%i", devname, mediastr, unit_id); } dinfo->bdrv = bdrv_new(dinfo->id); dinfo->devaddr = devaddr; dinfo->type = type; dinfo->bus = bus_id; dinfo->unit = unit_id; dinfo->opts = opts; dinfo->refcount = 1; if (serial) { pstrcpy(dinfo->serial, sizeof(dinfo->serial), serial); } QTAILQ_INSERT_TAIL(&drives, dinfo, next); bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error); /* disk I/O throttling */ bdrv_set_io_limits(dinfo->bdrv, &io_limits); switch(type) { case IF_IDE: case IF_SCSI: case IF_XEN: case IF_NONE: switch(media) { case MEDIA_DISK: if (cyls != 0) { bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs); bdrv_set_translation_hint(dinfo->bdrv, translation); } break; case MEDIA_CDROM: dinfo->media_cd = 1; break; } break; case IF_SD: case IF_FLOPPY: case IF_PFLASH: case IF_MTD: break; case IF_VIRTIO: /* add virtio block device */ opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0); if (arch_type == QEMU_ARCH_S390X) { qemu_opt_set(opts, "driver", "virtio-blk-s390"); } else { qemu_opt_set(opts, "driver", "virtio-blk-pci"); } qemu_opt_set(opts, "drive", dinfo->id); if (devaddr) qemu_opt_set(opts, "addr", devaddr); break; default: abort(); } if (!file || !*file) { return dinfo; } if (snapshot) { /* always use cache=unsafe with snapshot */ bdrv_flags &= ~BDRV_O_CACHE_MASK; bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH); } if (copy_on_read) { bdrv_flags |= BDRV_O_COPY_ON_READ; } if (runstate_check(RUN_STATE_INMIGRATE)) { bdrv_flags |= BDRV_O_INCOMING; } if (media == MEDIA_CDROM) { /* CDROM is fine for any interface, don't check. */ ro = 1; } else if (ro == 1) { if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY && type != IF_NONE && type != IF_PFLASH) { error_report("readonly not supported by this bus type"); goto err; } } bdrv_flags |= ro ? 0 : BDRV_O_RDWR; ret = bdrv_open(dinfo->bdrv, file, bdrv_flags, drv); if (ret < 0) { error_report("could not open disk image %s: %s", file, strerror(-ret)); goto err; } if (bdrv_key_required(dinfo->bdrv)) autostart = 0; return dinfo; err: bdrv_delete(dinfo->bdrv); g_free(dinfo->id); QTAILQ_REMOVE(&drives, dinfo, next); g_free(dinfo); return NULL; }


bool vhost_net_query(VHostNetState *net, VirtIODevice *dev) { return false; }


static int init_input(AVFormatContext *s, const char *filename) { int ret; AVProbeData pd = {filename, NULL, 0}; if (s->pb) { s->flags |= AVFMT_FLAG_CUSTOM_IO; if (!s->iformat) return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0); else if (s->iformat->flags & AVFMT_NOFILE) av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and " "will be ignored with AVFMT_NOFILE format.\n"); } if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) || (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0)))) if ((ret = avio_open(&s->pb, filename, AVIO_FLAG_READ)) < 0) return ret; if (s->iformat) return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0); }


void *etraxfs_eth_init(NICInfo *nd, CPUState *env, qemu_irq *irq, target_phys_addr_t base, int phyaddr) { struct etraxfs_dma_client *dma = NULL; struct fs_eth *eth = NULL; qemu_check_nic_model(nd, "fseth"); dma = qemu_mallocz(sizeof *dma * 2); eth = qemu_mallocz(sizeof *eth); dma[0].client.push = eth_tx_push; dma[0].client.opaque = eth; dma[1].client.opaque = eth; dma[1].client.pull = NULL; eth->env = env; eth->irq = irq; eth->dma_out = dma; eth->dma_in = dma + 1; /* Connect the phy. */ eth->phyaddr = phyaddr & 0x1f; tdk_init(&eth->phy); mdio_attach(&eth->mdio_bus, &eth->phy, eth->phyaddr); eth->ethregs = cpu_register_io_memory(0, eth_read, eth_write, eth); cpu_register_physical_memory (base, 0x5c, eth->ethregs); eth->vc = qemu_new_vlan_client(nd->vlan, nd->model, nd->name, eth_receive, eth_can_receive, eth); eth->vc->opaque = eth; eth->vc->link_status_changed = eth_set_link; return dma; }


static int gif_read_extension(GifState *s) { ByteIOContext *f = s->f; int ext_code, ext_len, i, gce_flags, gce_transparent_index; /* extension */ ext_code = get_byte(f); ext_len = get_byte(f); #ifdef DEBUG printf("gif: ext_code=0x%x len=%d\n", ext_code, ext_len); #endif switch(ext_code) { case 0xf9: if (ext_len != 4) goto discard_ext; s->transparent_color_index = -1; gce_flags = get_byte(f); s->gce_delay = get_le16(f); gce_transparent_index = get_byte(f); if (gce_flags & 0x01) s->transparent_color_index = gce_transparent_index; else s->transparent_color_index = -1; s->gce_disposal = (gce_flags >> 2) & 0x7; #ifdef DEBUG printf("gif: gce_flags=%x delay=%d tcolor=%d disposal=%d\n", gce_flags, s->gce_delay, s->transparent_color_index, s->gce_disposal); #endif ext_len = get_byte(f); break; } /* NOTE: many extension blocks can come after */ discard_ext: while (ext_len != 0) { for (i = 0; i < ext_len; i++) get_byte(f); ext_len = get_byte(f); #ifdef DEBUG printf("gif: ext_len1=%d\n", ext_len); #endif } return 0; }


altivec_packIntArrayToCharArray(int *val, uint8_t* dest, int dstW) { register int i; vector unsigned int altivec_vectorShiftInt19 = vec_add(vec_splat_u32(10),vec_splat_u32(9)); if ((unsigned long)dest % 16) { /* badly aligned store, we force store alignement */ /* and will handle load misalignement on val w/ vec_perm */ vector unsigned char perm1; vector signed int v1; for (i = 0 ; (i < dstW) && (((unsigned long)dest + i) % 16) ; i++) { int t = val[i] >> 19; dest[i] = (t < 0) ? 0 : ((t > 255) ? 255 : t); } perm1 = vec_lvsl(i << 2, val); v1 = vec_ld(i << 2, val); for ( ; i < (dstW - 15); i+=16) { int offset = i << 2; vector signed int v2 = vec_ld(offset + 16, val); vector signed int v3 = vec_ld(offset + 32, val); vector signed int v4 = vec_ld(offset + 48, val); vector signed int v5 = vec_ld(offset + 64, val); vector signed int v12 = vec_perm(v1,v2,perm1); vector signed int v23 = vec_perm(v2,v3,perm1); vector signed int v34 = vec_perm(v3,v4,perm1); vector signed int v45 = vec_perm(v4,v5,perm1); vector signed int vA = vec_sra(v12, altivec_vectorShiftInt19); vector signed int vB = vec_sra(v23, altivec_vectorShiftInt19); vector signed int vC = vec_sra(v34, altivec_vectorShiftInt19); vector signed int vD = vec_sra(v45, altivec_vectorShiftInt19); vector unsigned short vs1 = vec_packsu(vA, vB); vector unsigned short vs2 = vec_packsu(vC, vD); vector unsigned char vf = vec_packsu(vs1, vs2); vec_st(vf, i, dest); v1 = v5; } } else { // dest is properly aligned, great for (i = 0; i < (dstW - 15); i+=16) { int offset = i << 2; vector signed int v1 = vec_ld(offset, val); vector signed int v2 = vec_ld(offset + 16, val); vector signed int v3 = vec_ld(offset + 32, val); vector signed int v4 = vec_ld(offset + 48, val); vector signed int v5 = vec_sra(v1, altivec_vectorShiftInt19); vector signed int v6 = vec_sra(v2, altivec_vectorShiftInt19); vector signed int v7 = vec_sra(v3, altivec_vectorShiftInt19); vector signed int v8 = vec_sra(v4, altivec_vectorShiftInt19); vector unsigned short vs1 = vec_packsu(v5, v6); vector unsigned short vs2 = vec_packsu(v7, v8); vector unsigned char vf = vec_packsu(vs1, vs2); vec_st(vf, i, dest); } } for ( ; i < dstW ; i++) { int t = val[i] >> 19; dest[i] = (t < 0) ? 0 : ((t > 255) ? 255 : t); } }


static void virtio_pci_realize(PCIDevice *pci_dev, Error **errp) { VirtIOPCIProxy *proxy = VIRTIO_PCI(pci_dev); VirtioPCIClass *k = VIRTIO_PCI_GET_CLASS(pci_dev); /* * virtio pci bar layout used by default. * subclasses can re-arrange things if needed. * * region 0 -- virtio legacy io bar * region 1 -- msi-x bar * region 4+5 -- virtio modern memory (64bit) bar * */ proxy->legacy_io_bar = 0; proxy->msix_bar = 1; proxy->modern_io_bar = 2; proxy->modern_mem_bar = 4; proxy->common.offset = 0x0; proxy->common.size = 0x1000; proxy->common.type = VIRTIO_PCI_CAP_COMMON_CFG; proxy->isr.offset = 0x1000; proxy->isr.size = 0x1000; proxy->isr.type = VIRTIO_PCI_CAP_ISR_CFG; proxy->device.offset = 0x2000; proxy->device.size = 0x1000; proxy->device.type = VIRTIO_PCI_CAP_DEVICE_CFG; proxy->notify.offset = 0x3000; proxy->notify.size = QEMU_VIRTIO_PCI_QUEUE_MEM_MULT * VIRTIO_QUEUE_MAX; proxy->notify.type = VIRTIO_PCI_CAP_NOTIFY_CFG; proxy->notify_pio.offset = 0x0; proxy->notify_pio.size = 0x4; proxy->notify_pio.type = VIRTIO_PCI_CAP_NOTIFY_CFG; /* subclasses can enforce modern, so do this unconditionally */ memory_region_init(&proxy->modern_bar, OBJECT(proxy), "virtio-pci", 2 * QEMU_VIRTIO_PCI_QUEUE_MEM_MULT * VIRTIO_QUEUE_MAX); memory_region_init_alias(&proxy->modern_cfg, OBJECT(proxy), "virtio-pci-cfg", &proxy->modern_bar, 0, memory_region_size(&proxy->modern_bar)); address_space_init(&proxy->modern_as, &proxy->modern_cfg, "virtio-pci-cfg-as"); if (!(proxy->flags & VIRTIO_PCI_FLAG_DISABLE_PCIE) && !(proxy->flags & VIRTIO_PCI_FLAG_DISABLE_MODERN) && pci_bus_is_express(pci_dev->bus) && !pci_bus_is_root(pci_dev->bus)) { int pos; pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS; pos = pcie_endpoint_cap_init(pci_dev, 0); assert(pos > 0); pos = pci_add_capability(pci_dev, PCI_CAP_ID_PM, 0, PCI_PM_SIZEOF); assert(pos > 0); /* * Indicates that this function complies with revision 1.2 of the * PCI Power Management Interface Specification. */ pci_set_word(pci_dev->config + pos + PCI_PM_PMC, 0x3); } virtio_pci_bus_new(&proxy->bus, sizeof(proxy->bus), proxy); if (k->realize) { k->realize(proxy, errp); } }


static HTTPContext *find_rtp_session_with_url(const char *url, const char *session_id) { HTTPContext *rtp_c; char path1[1024]; const char *path; char buf[1024]; int s; rtp_c = find_rtp_session(session_id); if (!rtp_c) return NULL; /* find which url is asked */ url_split(NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url); path = path1; if (*path == '/') path++; if(!strcmp(path, rtp_c->stream->filename)) return rtp_c; for(s=0; s<rtp_c->stream->nb_streams; ++s) { snprintf(buf, sizeof(buf), "%s/streamid=%d", rtp_c->stream->filename, s); if(!strncmp(path, buf, sizeof(buf))) { // XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE if nb_streams>1? return rtp_c; } } return NULL; }


static void write_header(FFV1Context *f) { uint8_t state[CONTEXT_SIZE]; int i, j; RangeCoder *const c = &f->slice_context[0]->c; memset(state, 128, sizeof(state)); if (f->version < 2) { put_symbol(c, state, f->version, 0); put_symbol(c, state, f->ac, 0); if (f->ac > 1) { for (i = 1; i < 256; i++) put_symbol(c, state, f->state_transition[i] - c->one_state[i], 1); } put_symbol(c, state, f->colorspace, 0); // YUV cs type if (f->version > 0) put_symbol(c, state, f->bits_per_raw_sample, 0); put_rac(c, state, f->chroma_planes); put_symbol(c, state, f->chroma_h_shift, 0); put_symbol(c, state, f->chroma_v_shift, 0); put_rac(c, state, f->transparency); write_quant_tables(c, f->quant_table); } else if (f->version < 3) { put_symbol(c, state, f->slice_count, 0); for (i = 0; i < f->slice_count; i++) { FFV1Context *fs = f->slice_context[i]; put_symbol(c, state, (fs->slice_x + 1) * f->num_h_slices / f->width, 0); put_symbol(c, state, (fs->slice_y + 1) * f->num_v_slices / f->height, 0); put_symbol(c, state, (fs->slice_width + 1) * f->num_h_slices / f->width - 1, 0); put_symbol(c, state, (fs->slice_height + 1) * f->num_v_slices / f->height - 1, 0); for (j = 0; j < f->plane_count; j++) { put_symbol(c, state, f->plane[j].quant_table_index, 0); av_assert0(f->plane[j].quant_table_index == f->avctx->context_model); } } } }


static void __attribute__((constructor)) init_main_loop(void) { init_clocks(); init_timer_alarm(); qemu_clock_enable(vm_clock, false); }


static unsigned tget_long(const uint8_t **p, int le) { unsigned v = le ? AV_RL32(*p) : AV_RB32(*p); *p += 4; return v; }


tcp_input(struct mbuf *m, int iphlen, struct socket *inso) { struct ip save_ip, *ip; register struct tcpiphdr *ti; caddr_t optp = NULL; int optlen = 0; int len, tlen, off; register struct tcpcb *tp = NULL; register int tiflags; struct socket *so = NULL; int todrop, acked, ourfinisacked, needoutput = 0; int iss = 0; u_long tiwin; int ret; struct ex_list *ex_ptr; Slirp *slirp; DEBUG_CALL("tcp_input"); DEBUG_ARGS((dfd, " m = %8lx iphlen = %2d inso = %lx\n", (long )m, iphlen, (long )inso )); /* * If called with m == 0, then we're continuing the connect */ if (m == NULL) { so = inso; slirp = so->slirp; /* Re-set a few variables */ tp = sototcpcb(so); m = so->so_m; so->so_m = NULL; ti = so->so_ti; tiwin = ti->ti_win; tiflags = ti->ti_flags; goto cont_conn; } slirp = m->slirp; /* * Get IP and TCP header together in first mbuf. * Note: IP leaves IP header in first mbuf. */ ti = mtod(m, struct tcpiphdr *); if (iphlen > sizeof(struct ip )) { ip_stripoptions(m, (struct mbuf *)0); iphlen=sizeof(struct ip ); } /* XXX Check if too short */ /* * Save a copy of the IP header in case we want restore it * for sending an ICMP error message in response. */ ip=mtod(m, struct ip *); save_ip = *ip; save_ip.ip_len+= iphlen; /* * Checksum extended TCP header and data. */ tlen = ((struct ip *)ti)->ip_len; tcpiphdr2qlink(ti)->next = tcpiphdr2qlink(ti)->prev = NULL; memset(&ti->ti_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr)); ti->ti_x1 = 0; ti->ti_len = htons((uint16_t)tlen); len = sizeof(struct ip ) + tlen; if(cksum(m, len)) { goto drop; } /* * Check that TCP offset makes sense, * pull out TCP options and adjust length. XXX */ off = ti->ti_off << 2; if (off < sizeof (struct tcphdr) || off > tlen) { goto drop; } tlen -= off; ti->ti_len = tlen; if (off > sizeof (struct tcphdr)) { optlen = off - sizeof (struct tcphdr); optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr); } tiflags = ti->ti_flags; /* * Convert TCP protocol specific fields to host format. */ NTOHL(ti->ti_seq); NTOHL(ti->ti_ack); NTOHS(ti->ti_win); NTOHS(ti->ti_urp); /* * Drop TCP, IP headers and TCP options. */ m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr); m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr); if (slirp->restricted) { for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) { if (ex_ptr->ex_fport == ti->ti_dport && ti->ti_dst.s_addr == ex_ptr->ex_addr.s_addr) { break; } } if (!ex_ptr) goto drop; } /* * Locate pcb for segment. */ findso: so = slirp->tcp_last_so; if (so->so_fport != ti->ti_dport || so->so_lport != ti->ti_sport || so->so_laddr.s_addr != ti->ti_src.s_addr || so->so_faddr.s_addr != ti->ti_dst.s_addr) { so = solookup(&slirp->tcb, ti->ti_src, ti->ti_sport, ti->ti_dst, ti->ti_dport); if (so) slirp->tcp_last_so = so; } /* * If the state is CLOSED (i.e., TCB does not exist) then * all data in the incoming segment is discarded. * If the TCB exists but is in CLOSED state, it is embryonic, * but should either do a listen or a connect soon. * * state == CLOSED means we've done socreate() but haven't * attached it to a protocol yet... * * XXX If a TCB does not exist, and the TH_SYN flag is * the only flag set, then create a session, mark it * as if it was LISTENING, and continue... */ if (so == NULL) { if ((tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) != TH_SYN) goto dropwithreset; if ((so = socreate(slirp)) == NULL) goto dropwithreset; if (tcp_attach(so) < 0) { free(so); /* Not sofree (if it failed, it's not insqued) */ goto dropwithreset; } sbreserve(&so->so_snd, TCP_SNDSPACE); sbreserve(&so->so_rcv, TCP_RCVSPACE); so->so_laddr = ti->ti_src; so->so_lport = ti->ti_sport; so->so_faddr = ti->ti_dst; so->so_fport = ti->ti_dport; if ((so->so_iptos = tcp_tos(so)) == 0) so->so_iptos = ((struct ip *)ti)->ip_tos; tp = sototcpcb(so); tp->t_state = TCPS_LISTEN; } /* * If this is a still-connecting socket, this probably * a retransmit of the SYN. Whether it's a retransmit SYN * or something else, we nuke it. */ if (so->so_state & SS_ISFCONNECTING) goto drop; tp = sototcpcb(so); /* XXX Should never fail */ if (tp == NULL) goto dropwithreset; if (tp->t_state == TCPS_CLOSED) goto drop; tiwin = ti->ti_win; /* * Segment received on connection. * Reset idle time and keep-alive timer. */ tp->t_idle = 0; if (SO_OPTIONS) tp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL; else tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE; /* * Process options if not in LISTEN state, * else do it below (after getting remote address). */ if (optp && tp->t_state != TCPS_LISTEN) tcp_dooptions(tp, (u_char *)optp, optlen, ti); /* * Header prediction: check for the two common cases * of a uni-directional data xfer. If the packet has * no control flags, is in-sequence, the window didn't * change and we're not retransmitting, it's a * candidate. If the length is zero and the ack moved * forward, we're the sender side of the xfer. Just * free the data acked & wake any higher level process * that was blocked waiting for space. If the length * is non-zero and the ack didn't move, we're the * receiver side. If we're getting packets in-order * (the reassembly queue is empty), add the data to * the socket buffer and note that we need a delayed ack. * * XXX Some of these tests are not needed * eg: the tiwin == tp->snd_wnd prevents many more * predictions.. with no *real* advantage.. */ if (tp->t_state == TCPS_ESTABLISHED && (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK && ti->ti_seq == tp->rcv_nxt && tiwin && tiwin == tp->snd_wnd && tp->snd_nxt == tp->snd_max) { if (ti->ti_len == 0) { if (SEQ_GT(ti->ti_ack, tp->snd_una) && SEQ_LEQ(ti->ti_ack, tp->snd_max) && tp->snd_cwnd >= tp->snd_wnd) { /* * this is a pure ack for outstanding data. */ if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq)) tcp_xmit_timer(tp, tp->t_rtt); acked = ti->ti_ack - tp->snd_una; sbdrop(&so->so_snd, acked); tp->snd_una = ti->ti_ack; m_free(m); /* * If all outstanding data are acked, stop * retransmit timer, otherwise restart timer * using current (possibly backed-off) value. * If process is waiting for space, * wakeup/selwakeup/signal. If data * are ready to send, let tcp_output * decide between more output or persist. */ if (tp->snd_una == tp->snd_max) tp->t_timer[TCPT_REXMT] = 0; else if (tp->t_timer[TCPT_PERSIST] == 0) tp->t_timer[TCPT_REXMT] = tp->t_rxtcur; /* * This is called because sowwakeup might have * put data into so_snd. Since we don't so sowwakeup, * we don't need this.. XXX??? */ if (so->so_snd.sb_cc) (void) tcp_output(tp); return; } } else if (ti->ti_ack == tp->snd_una && tcpfrag_list_empty(tp) && ti->ti_len <= sbspace(&so->so_rcv)) { /* * this is a pure, in-sequence data packet * with nothing on the reassembly queue and * we have enough buffer space to take it. */ tp->rcv_nxt += ti->ti_len; /* * Add data to socket buffer. */ if (so->so_emu) { if (tcp_emu(so,m)) sbappend(so, m); } else sbappend(so, m); /* * If this is a short packet, then ACK now - with Nagel * congestion avoidance sender won't send more until * he gets an ACK. * * It is better to not delay acks at all to maximize * TCP throughput. See RFC 2581. */ tp->t_flags |= TF_ACKNOW; tcp_output(tp); return; } } /* header prediction */ /* * Calculate amount of space in receive window, * and then do TCP input processing. * Receive window is amount of space in rcv queue, * but not less than advertised window. */ { int win; win = sbspace(&so->so_rcv); if (win < 0) win = 0; tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt)); } switch (tp->t_state) { /* * If the state is LISTEN then ignore segment if it contains an RST. * If the segment contains an ACK then it is bad and send a RST. * If it does not contain a SYN then it is not interesting; drop it. * Don't bother responding if the destination was a broadcast. * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial * tp->iss, and send a segment: * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK> * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss. * Fill in remote peer address fields if not previously specified. * Enter SYN_RECEIVED state, and process any other fields of this * segment in this state. */ case TCPS_LISTEN: { if (tiflags & TH_RST) goto drop; if (tiflags & TH_ACK) goto dropwithreset; if ((tiflags & TH_SYN) == 0) goto drop; /* * This has way too many gotos... * But a bit of spaghetti code never hurt anybody :) */ /* * If this is destined for the control address, then flag to * tcp_ctl once connected, otherwise connect */ if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) == slirp->vnetwork_addr.s_addr) { if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr && so->so_faddr.s_addr != slirp->vnameserver_addr.s_addr) { /* May be an add exec */ for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) { if(ex_ptr->ex_fport == so->so_fport && so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) { so->so_state |= SS_CTL; break; } } if (so->so_state & SS_CTL) { goto cont_input; } } /* CTL_ALIAS: Do nothing, tcp_fconnect will be called on it */ } if (so->so_emu & EMU_NOCONNECT) { so->so_emu &= ~EMU_NOCONNECT; goto cont_input; } if((tcp_fconnect(so) == -1) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK)) { u_char code=ICMP_UNREACH_NET; DEBUG_MISC((dfd, " tcp fconnect errno = %d-%s\n", errno,strerror(errno))); if(errno == ECONNREFUSED) { /* ACK the SYN, send RST to refuse the connection */ tcp_respond(tp, ti, m, ti->ti_seq+1, (tcp_seq)0, TH_RST|TH_ACK); } else { if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST; HTONL(ti->ti_seq); /* restore tcp header */ HTONL(ti->ti_ack); HTONS(ti->ti_win); HTONS(ti->ti_urp); m->m_data -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr); m->m_len += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr); *ip=save_ip; icmp_error(m, ICMP_UNREACH,code, 0,strerror(errno)); } tcp_close(tp); m_free(m); } else { /* * Haven't connected yet, save the current mbuf * and ti, and return * XXX Some OS's don't tell us whether the connect() * succeeded or not. So we must time it out. */ so->so_m = m; so->so_ti = ti; tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT; tp->t_state = TCPS_SYN_RECEIVED; tcp_template(tp); } return; cont_conn: /* m==NULL * Check if the connect succeeded */ if (so->so_state & SS_NOFDREF) { tp = tcp_close(tp); goto dropwithreset; } cont_input: tcp_template(tp); if (optp) tcp_dooptions(tp, (u_char *)optp, optlen, ti); if (iss) tp->iss = iss; else tp->iss = slirp->tcp_iss; slirp->tcp_iss += TCP_ISSINCR/2; tp->irs = ti->ti_seq; tcp_sendseqinit(tp); tcp_rcvseqinit(tp); tp->t_flags |= TF_ACKNOW; tp->t_state = TCPS_SYN_RECEIVED; tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT; goto trimthenstep6; } /* case TCPS_LISTEN */ /* * If the state is SYN_SENT: * if seg contains an ACK, but not for our SYN, drop the input. * if seg contains a RST, then drop the connection. * if seg does not contain SYN, then drop it. * Otherwise this is an acceptable SYN segment * initialize tp->rcv_nxt and tp->irs * if seg contains ack then advance tp->snd_una * if SYN has been acked change to ESTABLISHED else SYN_RCVD state * arrange for segment to be acked (eventually) * continue processing rest of data/controls, beginning with URG */ case TCPS_SYN_SENT: if ((tiflags & TH_ACK) && (SEQ_LEQ(ti->ti_ack, tp->iss) || SEQ_GT(ti->ti_ack, tp->snd_max))) goto dropwithreset; if (tiflags & TH_RST) { if (tiflags & TH_ACK) { tcp_drop(tp, 0); /* XXX Check t_softerror! */ } goto drop; } if ((tiflags & TH_SYN) == 0) goto drop; if (tiflags & TH_ACK) { tp->snd_una = ti->ti_ack; if (SEQ_LT(tp->snd_nxt, tp->snd_una)) tp->snd_nxt = tp->snd_una; } tp->t_timer[TCPT_REXMT] = 0; tp->irs = ti->ti_seq; tcp_rcvseqinit(tp); tp->t_flags |= TF_ACKNOW; if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) { soisfconnected(so); tp->t_state = TCPS_ESTABLISHED; (void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0); /* * if we didn't have to retransmit the SYN, * use its rtt as our initial srtt & rtt var. */ if (tp->t_rtt) tcp_xmit_timer(tp, tp->t_rtt); } else tp->t_state = TCPS_SYN_RECEIVED; trimthenstep6: /* * Advance ti->ti_seq to correspond to first data byte. * If data, trim to stay within window, * dropping FIN if necessary. */ ti->ti_seq++; if (ti->ti_len > tp->rcv_wnd) { todrop = ti->ti_len - tp->rcv_wnd; m_adj(m, -todrop); ti->ti_len = tp->rcv_wnd; tiflags &= ~TH_FIN; } tp->snd_wl1 = ti->ti_seq - 1; tp->rcv_up = ti->ti_seq; goto step6; } /* switch tp->t_state */ /* * States other than LISTEN or SYN_SENT. * Check that at least some bytes of segment are within * receive window. If segment begins before rcv_nxt, * drop leading data (and SYN); if nothing left, just ack. */ todrop = tp->rcv_nxt - ti->ti_seq; if (todrop > 0) { if (tiflags & TH_SYN) { tiflags &= ~TH_SYN; ti->ti_seq++; if (ti->ti_urp > 1) ti->ti_urp--; else tiflags &= ~TH_URG; todrop--; } /* * Following if statement from Stevens, vol. 2, p. 960. */ if (todrop > ti->ti_len || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) { /* * Any valid FIN must be to the left of the window. * At this point the FIN must be a duplicate or out * of sequence; drop it. */ tiflags &= ~TH_FIN; /* * Send an ACK to resynchronize and drop any data. * But keep on processing for RST or ACK. */ tp->t_flags |= TF_ACKNOW; todrop = ti->ti_len; } m_adj(m, todrop); ti->ti_seq += todrop; ti->ti_len -= todrop; if (ti->ti_urp > todrop) ti->ti_urp -= todrop; else { tiflags &= ~TH_URG; ti->ti_urp = 0; } } /* * If new data are received on a connection after the * user processes are gone, then RST the other end. */ if ((so->so_state & SS_NOFDREF) && tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) { tp = tcp_close(tp); goto dropwithreset; } /* * If segment ends after window, drop trailing data * (and PUSH and FIN); if nothing left, just ACK. */ todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd); if (todrop > 0) { if (todrop >= ti->ti_len) { /* * If a new connection request is received * while in TIME_WAIT, drop the old connection * and start over if the sequence numbers * are above the previous ones. */ if (tiflags & TH_SYN && tp->t_state == TCPS_TIME_WAIT && SEQ_GT(ti->ti_seq, tp->rcv_nxt)) { iss = tp->rcv_nxt + TCP_ISSINCR; tp = tcp_close(tp); goto findso; } /* * If window is closed can only take segments at * window edge, and have to drop data and PUSH from * incoming segments. Continue processing, but * remember to ack. Otherwise, drop segment * and ack. */ if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) { tp->t_flags |= TF_ACKNOW; } else { goto dropafterack; } } m_adj(m, -todrop); ti->ti_len -= todrop; tiflags &= ~(TH_PUSH|TH_FIN); } /* * If the RST bit is set examine the state: * SYN_RECEIVED STATE: * If passive open, return to LISTEN state. * If active open, inform user that connection was refused. * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES: * Inform user that connection was reset, and close tcb. * CLOSING, LAST_ACK, TIME_WAIT STATES * Close the tcb. */ if (tiflags&TH_RST) switch (tp->t_state) { case TCPS_SYN_RECEIVED: case TCPS_ESTABLISHED: case TCPS_FIN_WAIT_1: case TCPS_FIN_WAIT_2: case TCPS_CLOSE_WAIT: tp->t_state = TCPS_CLOSED; tcp_close(tp); goto drop; case TCPS_CLOSING: case TCPS_LAST_ACK: case TCPS_TIME_WAIT: tcp_close(tp); goto drop; } /* * If a SYN is in the window, then this is an * error and we send an RST and drop the connection. */ if (tiflags & TH_SYN) { tp = tcp_drop(tp,0); goto dropwithreset; } /* * If the ACK bit is off we drop the segment and return. */ if ((tiflags & TH_ACK) == 0) goto drop; /* * Ack processing. */ switch (tp->t_state) { /* * In SYN_RECEIVED state if the ack ACKs our SYN then enter * ESTABLISHED state and continue processing, otherwise * send an RST. una<=ack<=max */ case TCPS_SYN_RECEIVED: if (SEQ_GT(tp->snd_una, ti->ti_ack) || SEQ_GT(ti->ti_ack, tp->snd_max)) goto dropwithreset; tp->t_state = TCPS_ESTABLISHED; /* * The sent SYN is ack'ed with our sequence number +1 * The first data byte already in the buffer will get * lost if no correction is made. This is only needed for * SS_CTL since the buffer is empty otherwise. * tp->snd_una++; or: */ tp->snd_una=ti->ti_ack; if (so->so_state & SS_CTL) { /* So tcp_ctl reports the right state */ ret = tcp_ctl(so); if (ret == 1) { soisfconnected(so); so->so_state &= ~SS_CTL; /* success XXX */ } else if (ret == 2) { so->so_state &= SS_PERSISTENT_MASK; so->so_state |= SS_NOFDREF; /* CTL_CMD */ } else { needoutput = 1; tp->t_state = TCPS_FIN_WAIT_1; } } else { soisfconnected(so); } (void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0); tp->snd_wl1 = ti->ti_seq - 1; /* Avoid ack processing; snd_una==ti_ack => dup ack */ goto synrx_to_est; /* fall into ... */ /* * In ESTABLISHED state: drop duplicate ACKs; ACK out of range * ACKs. If the ack is in the range * tp->snd_una < ti->ti_ack <= tp->snd_max * then advance tp->snd_una to ti->ti_ack and drop * data from the retransmission queue. If this ACK reflects * more up to date window information we update our window information. */ case TCPS_ESTABLISHED: case TCPS_FIN_WAIT_1: case TCPS_FIN_WAIT_2: case TCPS_CLOSE_WAIT: case TCPS_CLOSING: case TCPS_LAST_ACK: case TCPS_TIME_WAIT: if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) { if (ti->ti_len == 0 && tiwin == tp->snd_wnd) { DEBUG_MISC((dfd, " dup ack m = %lx so = %lx\n", (long )m, (long )so)); /* * If we have outstanding data (other than * a window probe), this is a completely * duplicate ack (ie, window info didn't * change), the ack is the biggest we've * seen and we've seen exactly our rexmt * threshold of them, assume a packet * has been dropped and retransmit it. * Kludge snd_nxt & the congestion * window so we send only this one * packet. * * We know we're losing at the current * window size so do congestion avoidance * (set ssthresh to half the current window * and pull our congestion window back to * the new ssthresh). * * Dup acks mean that packets have left the * network (they're now cached at the receiver) * so bump cwnd by the amount in the receiver * to keep a constant cwnd packets in the * network. */ if (tp->t_timer[TCPT_REXMT] == 0 || ti->ti_ack != tp->snd_una) tp->t_dupacks = 0; else if (++tp->t_dupacks == TCPREXMTTHRESH) { tcp_seq onxt = tp->snd_nxt; u_int win = min(tp->snd_wnd, tp->snd_cwnd) / 2 / tp->t_maxseg; if (win < 2) win = 2; tp->snd_ssthresh = win * tp->t_maxseg; tp->t_timer[TCPT_REXMT] = 0; tp->t_rtt = 0; tp->snd_nxt = ti->ti_ack; tp->snd_cwnd = tp->t_maxseg; (void) tcp_output(tp); tp->snd_cwnd = tp->snd_ssthresh + tp->t_maxseg * tp->t_dupacks; if (SEQ_GT(onxt, tp->snd_nxt)) tp->snd_nxt = onxt; goto drop; } else if (tp->t_dupacks > TCPREXMTTHRESH) { tp->snd_cwnd += tp->t_maxseg; (void) tcp_output(tp); goto drop; } } else tp->t_dupacks = 0; break; } synrx_to_est: /* * If the congestion window was inflated to account * for the other side's cached packets, retract it. */ if (tp->t_dupacks > TCPREXMTTHRESH && tp->snd_cwnd > tp->snd_ssthresh) tp->snd_cwnd = tp->snd_ssthresh; tp->t_dupacks = 0; if (SEQ_GT(ti->ti_ack, tp->snd_max)) { goto dropafterack; } acked = ti->ti_ack - tp->snd_una; /* * If transmit timer is running and timed sequence * number was acked, update smoothed round trip time. * Since we now have an rtt measurement, cancel the * timer backoff (cf., Phil Karn's retransmit alg.). * Recompute the initial retransmit timer. */ if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq)) tcp_xmit_timer(tp,tp->t_rtt); /* * If all outstanding data is acked, stop retransmit * timer and remember to restart (more output or persist). * If there is more data to be acked, restart retransmit * timer, using current (possibly backed-off) value. */ if (ti->ti_ack == tp->snd_max) { tp->t_timer[TCPT_REXMT] = 0; needoutput = 1; } else if (tp->t_timer[TCPT_PERSIST] == 0) tp->t_timer[TCPT_REXMT] = tp->t_rxtcur; /* * When new data is acked, open the congestion window. * If the window gives us less than ssthresh packets * in flight, open exponentially (maxseg per packet). * Otherwise open linearly: maxseg per window * (maxseg^2 / cwnd per packet). */ { register u_int cw = tp->snd_cwnd; register u_int incr = tp->t_maxseg; if (cw > tp->snd_ssthresh) incr = incr * incr / cw; tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale); } if (acked > so->so_snd.sb_cc) { tp->snd_wnd -= so->so_snd.sb_cc; sbdrop(&so->so_snd, (int )so->so_snd.sb_cc); ourfinisacked = 1; } else { sbdrop(&so->so_snd, acked); tp->snd_wnd -= acked; ourfinisacked = 0; } tp->snd_una = ti->ti_ack; if (SEQ_LT(tp->snd_nxt, tp->snd_una)) tp->snd_nxt = tp->snd_una; switch (tp->t_state) { /* * In FIN_WAIT_1 STATE in addition to the processing * for the ESTABLISHED state if our FIN is now acknowledged * then enter FIN_WAIT_2. */ case TCPS_FIN_WAIT_1: if (ourfinisacked) { /* * If we can't receive any more * data, then closing user can proceed. * Starting the timer is contrary to the * specification, but if we don't get a FIN * we'll hang forever. */ if (so->so_state & SS_FCANTRCVMORE) { tp->t_timer[TCPT_2MSL] = TCP_MAXIDLE; } tp->t_state = TCPS_FIN_WAIT_2; } break; /* * In CLOSING STATE in addition to the processing for * the ESTABLISHED state if the ACK acknowledges our FIN * then enter the TIME-WAIT state, otherwise ignore * the segment. */ case TCPS_CLOSING: if (ourfinisacked) { tp->t_state = TCPS_TIME_WAIT; tcp_canceltimers(tp); tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL; } break; /* * In LAST_ACK, we may still be waiting for data to drain * and/or to be acked, as well as for the ack of our FIN. * If our FIN is now acknowledged, delete the TCB, * enter the closed state and return. */ case TCPS_LAST_ACK: if (ourfinisacked) { tcp_close(tp); goto drop; } break; /* * In TIME_WAIT state the only thing that should arrive * is a retransmission of the remote FIN. Acknowledge * it and restart the finack timer. */ case TCPS_TIME_WAIT: tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL; goto dropafterack; } } /* switch(tp->t_state) */ step6: /* * Update window information. * Don't look at window if no ACK: TAC's send garbage on first SYN. */ if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, ti->ti_seq) || (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) || (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) { tp->snd_wnd = tiwin; tp->snd_wl1 = ti->ti_seq; tp->snd_wl2 = ti->ti_ack; if (tp->snd_wnd > tp->max_sndwnd) tp->max_sndwnd = tp->snd_wnd; needoutput = 1; } /* * Process segments with URG. */ if ((tiflags & TH_URG) && ti->ti_urp && TCPS_HAVERCVDFIN(tp->t_state) == 0) { /* * This is a kludge, but if we receive and accept * random urgent pointers, we'll crash in * soreceive. It's hard to imagine someone * actually wanting to send this much urgent data. */ if (ti->ti_urp + so->so_rcv.sb_cc > so->so_rcv.sb_datalen) { ti->ti_urp = 0; tiflags &= ~TH_URG; goto dodata; } /* * If this segment advances the known urgent pointer, * then mark the data stream. This should not happen * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since * a FIN has been received from the remote side. * In these states we ignore the URG. * * According to RFC961 (Assigned Protocols), * the urgent pointer points to the last octet * of urgent data. We continue, however, * to consider it to indicate the first octet * of data past the urgent section as the original * spec states (in one of two places). */ if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) { tp->rcv_up = ti->ti_seq + ti->ti_urp; so->so_urgc = so->so_rcv.sb_cc + (tp->rcv_up - tp->rcv_nxt); /* -1; */ tp->rcv_up = ti->ti_seq + ti->ti_urp; } } else /* * If no out of band data is expected, * pull receive urgent pointer along * with the receive window. */ if (SEQ_GT(tp->rcv_nxt, tp->rcv_up)) tp->rcv_up = tp->rcv_nxt; dodata: /* * If this is a small packet, then ACK now - with Nagel * congestion avoidance sender won't send more until * he gets an ACK. */ if (ti->ti_len && (unsigned)ti->ti_len <= 5 && ((struct tcpiphdr_2 *)ti)->first_char == (char)27) { tp->t_flags |= TF_ACKNOW; } /* * Process the segment text, merging it into the TCP sequencing queue, * and arranging for acknowledgment of receipt if necessary. * This process logically involves adjusting tp->rcv_wnd as data * is presented to the user (this happens in tcp_usrreq.c, * case PRU_RCVD). If a FIN has already been received on this * connection then we just ignore the text. */ if ((ti->ti_len || (tiflags&TH_FIN)) && TCPS_HAVERCVDFIN(tp->t_state) == 0) { TCP_REASS(tp, ti, m, so, tiflags); } else { m_free(m); tiflags &= ~TH_FIN; } /* * If FIN is received ACK the FIN and let the user know * that the connection is closing. */ if (tiflags & TH_FIN) { if (TCPS_HAVERCVDFIN(tp->t_state) == 0) { /* * If we receive a FIN we can't send more data, * set it SS_FDRAIN * Shutdown the socket if there is no rx data in the * buffer. * soread() is called on completion of shutdown() and * will got to TCPS_LAST_ACK, and use tcp_output() * to send the FIN. */ sofwdrain(so); tp->t_flags |= TF_ACKNOW; tp->rcv_nxt++; } switch (tp->t_state) { /* * In SYN_RECEIVED and ESTABLISHED STATES * enter the CLOSE_WAIT state. */ case TCPS_SYN_RECEIVED: case TCPS_ESTABLISHED: if(so->so_emu == EMU_CTL) /* no shutdown on socket */ tp->t_state = TCPS_LAST_ACK; else tp->t_state = TCPS_CLOSE_WAIT; break; /* * If still in FIN_WAIT_1 STATE FIN has not been acked so * enter the CLOSING state. */ case TCPS_FIN_WAIT_1: tp->t_state = TCPS_CLOSING; break; /* * In FIN_WAIT_2 state enter the TIME_WAIT state, * starting the time-wait timer, turning off the other * standard timers. */ case TCPS_FIN_WAIT_2: tp->t_state = TCPS_TIME_WAIT; tcp_canceltimers(tp); tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL; break; /* * In TIME_WAIT state restart the 2 MSL time_wait timer. */ case TCPS_TIME_WAIT: tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL; break; } } /* * Return any desired output. */ if (needoutput || (tp->t_flags & TF_ACKNOW)) { (void) tcp_output(tp); } return; dropafterack: /* * Generate an ACK dropping incoming segment if it occupies * sequence space, where the ACK reflects our state. */ if (tiflags & TH_RST) goto drop; m_free(m); tp->t_flags |= TF_ACKNOW; (void) tcp_output(tp); return; dropwithreset: /* reuses m if m!=NULL, m_free() unnecessary */ if (tiflags & TH_ACK) tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST); else { if (tiflags & TH_SYN) ti->ti_len++; tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0, TH_RST|TH_ACK); } return; drop: /* * Drop space held by incoming segment and return. */ m_free(m); }


static bool cmd_identify(IDEState *s, uint8_t cmd) { if (s->bs && s->drive_kind != IDE_CD) { if (s->drive_kind != IDE_CFATA) { ide_identify(s); } else { ide_cfata_identify(s); } s->status = READY_STAT | SEEK_STAT; ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop); ide_set_irq(s->bus); return false; } else { if (s->drive_kind == IDE_CD) { ide_set_signature(s); } ide_abort_command(s); } return true; }


static coroutine_fn int dmg_co_read(BlockDriverState *bs, int64_t sector_num, uint8_t *buf, int nb_sectors) { int ret; BDRVDMGState *s = bs->opaque; qemu_co_mutex_lock(&s->lock); ret = dmg_read(bs, sector_num, buf, nb_sectors); qemu_co_mutex_unlock(&s->lock); return ret; }


static void cmd_read_cdvd_capacity(IDEState *s, uint8_t* buf) { uint64_t total_sectors = s->nb_sectors >> 2; if (total_sectors == 0) { ide_atapi_cmd_error(s, SENSE_NOT_READY, ASC_MEDIUM_NOT_PRESENT); return; } /* NOTE: it is really the number of sectors minus 1 */ cpu_to_ube32(buf, total_sectors - 1); cpu_to_ube32(buf + 4, 2048); ide_atapi_cmd_reply(s, 8, 8); }


int64 float32_to_int64_round_to_zero( float32 a STATUS_PARAM ) { flag aSign; int16 aExp, shiftCount; bits32 aSig; bits64 aSig64; int64 z; aSig = extractFloat32Frac( a ); aExp = extractFloat32Exp( a ); aSign = extractFloat32Sign( a ); shiftCount = aExp - 0xBE; if ( 0 <= shiftCount ) { if ( a != 0xDF000000 ) { float_raise( float_flag_invalid STATUS_VAR); if ( ! aSign || ( ( aExp == 0xFF ) && aSig ) ) { return LIT64( 0x7FFFFFFFFFFFFFFF ); } } return (sbits64) LIT64( 0x8000000000000000 ); } else if ( aExp <= 0x7E ) { if ( aExp | aSig ) STATUS(float_exception_flags) |= float_flag_inexact; return 0; } aSig64 = aSig | 0x00800000; aSig64 <<= 40; z = aSig64>>( - shiftCount ); if ( (bits64) ( aSig64<<( shiftCount & 63 ) ) ) { STATUS(float_exception_flags) |= float_flag_inexact; } if ( aSign ) z = - z; return z; }


putsum(uint8_t *data, uint32_t n, uint32_t sloc, uint32_t css, uint32_t cse) { if (cse && cse < n) n = cse + 1; if (sloc < n-1) cpu_to_be16wu((uint16_t *)(data + sloc), do_cksum(data + css, data + n)); }


uint32_t HELPER(lcxbr)(CPUS390XState *env, uint32_t f1, uint32_t f2) { CPU_QuadU x1, x2; x2.ll.upper = env->fregs[f2].ll; x2.ll.lower = env->fregs[f2 + 2].ll; x1.q = float128_chs(x2.q); env->fregs[f1].ll = x1.ll.upper; env->fregs[f1 + 2].ll = x1.ll.lower; return set_cc_nz_f128(x1.q); }


static void pc_machine_set_nvdimm(Object *obj, bool value, Error **errp) { PCMachineState *pcms = PC_MACHINE(obj); pcms->nvdimm = value; }