int ff_img_read_header(AVFormatContext *s1) { VideoDemuxData *s = s1->priv_data; int first_index = 1, last_index = 1; AVStream *st; enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE; s1->ctx_flags |= AVFMTCTX_NOHEADER; st = avformat_new_stream(s1, NULL); if (!st) { return AVERROR(ENOMEM); } if (s->pixel_format && (pix_fmt = av_get_pix_fmt(s->pixel_format)) == AV_PIX_FMT_NONE) { av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n", s->pixel_format); return AVERROR(EINVAL); } av_strlcpy(s->path, s1->filename, sizeof(s->path)); s->img_number = 0; s->img_count = 0; /* find format */ if (s1->iformat->flags & AVFMT_NOFILE) s->is_pipe = 0; else { s->is_pipe = 1; st->need_parsing = AVSTREAM_PARSE_FULL; } if (s->ts_from_file == 2) { #if !HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC av_log(s1, AV_LOG_ERROR, "POSIX.1-2008 not supported, nanosecond file timestamps unavailable\n"); return AVERROR(ENOSYS); #endif avpriv_set_pts_info(st, 64, 1, 1000000000); } else if (s->ts_from_file) avpriv_set_pts_info(st, 64, 1, 1); else avpriv_set_pts_info(st, 64, s->framerate.den, s->framerate.num); if (s->width && s->height) { st->codec->width = s->width; st->codec->height = s->height; } if (!s->is_pipe) { if (s->pattern_type == PT_GLOB_SEQUENCE) { s->use_glob = is_glob(s->path); if (s->use_glob) { #if HAVE_GLOB char *p = s->path, *q, *dup; int gerr; #endif av_log(s1, AV_LOG_WARNING, "Pattern type 'glob_sequence' is deprecated: " "use pattern_type 'glob' instead\n"); #if HAVE_GLOB dup = q = av_strdup(p); while (*q) { /* Do we have room for the next char and a \ insertion? */ if ((p - s->path) >= (sizeof(s->path) - 2)) break; if (*q == '%' && strspn(q + 1, "%*?[]{}")) ++q; else if (strspn(q, "\\*?[]{}")) *p++ = '\\'; *p++ = *q++; } *p = 0; av_free(dup); gerr = glob(s->path, GLOB_NOCHECK|GLOB_BRACE|GLOB_NOMAGIC, NULL, &s->globstate); if (gerr != 0) { return AVERROR(ENOENT); } first_index = 0; last_index = s->globstate.gl_pathc - 1; #endif } } if ((s->pattern_type == PT_GLOB_SEQUENCE && !s->use_glob) || s->pattern_type == PT_SEQUENCE) { if (find_image_range(&first_index, &last_index, s->path, s->start_number, s->start_number_range) < 0) { av_log(s1, AV_LOG_ERROR, "Could find no file with path '%s' and index in the range %d-%d\n", s->path, s->start_number, s->start_number + s->start_number_range - 1); return AVERROR(ENOENT); } } else if (s->pattern_type == PT_GLOB) { #if HAVE_GLOB int gerr; gerr = glob(s->path, GLOB_NOCHECK|GLOB_BRACE|GLOB_NOMAGIC, NULL, &s->globstate); if (gerr != 0) { return AVERROR(ENOENT); } first_index = 0; last_index = s->globstate.gl_pathc - 1; s->use_glob = 1; #else av_log(s1, AV_LOG_ERROR, "Pattern type 'glob' was selected but globbing " "is not supported by this libavformat build\n"); return AVERROR(ENOSYS); #endif } else if (s->pattern_type != PT_GLOB_SEQUENCE && s->pattern_type != PT_NONE) { av_log(s1, AV_LOG_ERROR, "Unknown value '%d' for pattern_type option\n", s->pattern_type); return AVERROR(EINVAL); } s->img_first = first_index; s->img_last = last_index; s->img_number = first_index; /* compute duration */ if (!s->ts_from_file) { st->start_time = 0; st->duration = last_index - first_index + 1; } } if (s1->video_codec_id) { st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = s1->video_codec_id; } else if (s1->audio_codec_id) { st->codec->codec_type = AVMEDIA_TYPE_AUDIO; st->codec->codec_id = s1->audio_codec_id; } else if (s1->iformat->raw_codec_id) { st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = s1->iformat->raw_codec_id; } else { const char *str = strrchr(s->path, '.'); s->split_planes = str && !av_strcasecmp(str + 1, "y"); st->codec->codec_type = AVMEDIA_TYPE_VIDEO; if (s1->pb) { int probe_buffer_size = 2048; uint8_t *probe_buffer = av_realloc(NULL, probe_buffer_size + AVPROBE_PADDING_SIZE); AVInputFormat *fmt = NULL; AVProbeData pd = { 0 }; if (!probe_buffer) return AVERROR(ENOMEM); probe_buffer_size = avio_read(s1->pb, probe_buffer, probe_buffer_size); if (probe_buffer_size < 0) { av_free(probe_buffer); return probe_buffer_size; } memset(probe_buffer + probe_buffer_size, 0, AVPROBE_PADDING_SIZE); pd.buf = probe_buffer; pd.buf_size = probe_buffer_size; pd.filename = s1->filename; while ((fmt = av_iformat_next(fmt))) { if (fmt->read_header != ff_img_read_header || !fmt->read_probe || (fmt->flags & AVFMT_NOFILE) || !fmt->raw_codec_id) continue; if (fmt->read_probe(&pd) > 0) { st->codec->codec_id = fmt->raw_codec_id; break; } } if (s1->flags & AVFMT_FLAG_CUSTOM_IO) { avio_seek(s1->pb, 0, SEEK_SET); } else ffio_rewind_with_probe_data(s1->pb, &probe_buffer, probe_buffer_size); } if (st->codec->codec_id == AV_CODEC_ID_NONE) st->codec->codec_id = ff_guess_image2_codec(s->path); if (st->codec->codec_id == AV_CODEC_ID_LJPEG) st->codec->codec_id = AV_CODEC_ID_MJPEG; if (st->codec->codec_id == AV_CODEC_ID_ALIAS_PIX) // we cannot distingiush this from BRENDER_PIX st->codec->codec_id = AV_CODEC_ID_NONE; } if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && pix_fmt != AV_PIX_FMT_NONE) st->codec->pix_fmt = pix_fmt; return 0; }


static av_always_inline void decode_bgr_1(HYuvContext *s, int count, int decorrelate, int alpha) { int i; OPEN_READER(re, &s->gb); for (i = 0; i < count; i++) { unsigned int index; int code, n; UPDATE_CACHE(re, &s->gb); index = SHOW_UBITS(re, &s->gb, VLC_BITS); code = s->vlc[4].table[index][0]; n = s->vlc[4].table[index][1]; if (code != -1) { *(uint32_t*)&s->temp[0][4 * i] = s->pix_bgr_map[code]; LAST_SKIP_BITS(re, &s->gb, n); } else { int nb_bits; if(decorrelate) { VLC_INTERN(s->temp[0][4 * i + G], s->vlc[1].table, &s->gb, re, VLC_BITS, 3); UPDATE_CACHE(re, &s->gb); index = SHOW_UBITS(re, &s->gb, VLC_BITS); VLC_INTERN(code, s->vlc[0].table, &s->gb, re, VLC_BITS, 3); s->temp[0][4 * i + B] = code + s->temp[0][4 * i + G]; UPDATE_CACHE(re, &s->gb); index = SHOW_UBITS(re, &s->gb, VLC_BITS); VLC_INTERN(code, s->vlc[2].table, &s->gb, re, VLC_BITS, 3); s->temp[0][4 * i + R] = code + s->temp[0][4 * i + G]; } else { VLC_INTERN(s->temp[0][4 * i + B], s->vlc[0].table, &s->gb, re, VLC_BITS, 3); UPDATE_CACHE(re, &s->gb); index = SHOW_UBITS(re, &s->gb, VLC_BITS); VLC_INTERN(s->temp[0][4 * i + G], s->vlc[1].table, &s->gb, re, VLC_BITS, 3); UPDATE_CACHE(re, &s->gb); index = SHOW_UBITS(re, &s->gb, VLC_BITS); VLC_INTERN(s->temp[0][4 * i + R], s->vlc[2].table, &s->gb, re, VLC_BITS, 3); } if (alpha) { UPDATE_CACHE(re, &s->gb); index = SHOW_UBITS(re, &s->gb, VLC_BITS); VLC_INTERN(s->temp[0][4 * i + A], s->vlc[2].table, &s->gb, re, VLC_BITS, 3); } } } CLOSE_READER(re, &s->gb); }


static int dnxhd_init_rc(DNXHDEncContext *ctx) { CHECKED_ALLOCZ(ctx->mb_rc, 8160*ctx->m.avctx->qmax*sizeof(RCEntry)); if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD) CHECKED_ALLOCZ(ctx->mb_cmp, ctx->m.mb_num*sizeof(RCCMPEntry)); ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4) * 8; ctx->qscale = 1; ctx->lambda = 2<<LAMBDA_FRAC_BITS; // qscale 2 return 0; fail: return -1; }


static int mpeg1_decode_picture(AVCodecContext *avctx, UINT8 *buf, int buf_size) { Mpeg1Context *s1 = avctx->priv_data; MpegEncContext *s = &s1->mpeg_enc_ctx; int ref, f_code; init_get_bits(&s->gb, buf, buf_size); ref = get_bits(&s->gb, 10); /* temporal ref */ s->pict_type = get_bits(&s->gb, 3); dprintf("pict_type=%d number=%d\n", s->pict_type, s->picture_number); skip_bits(&s->gb, 16); if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) { s->full_pel[0] = get_bits1(&s->gb); f_code = get_bits(&s->gb, 3); if (f_code == 0) return -1; s->mpeg_f_code[0][0] = f_code; s->mpeg_f_code[0][1] = f_code; } if (s->pict_type == B_TYPE) { s->full_pel[1] = get_bits1(&s->gb); f_code = get_bits(&s->gb, 3); if (f_code == 0) return -1; s->mpeg_f_code[1][0] = f_code; s->mpeg_f_code[1][1] = f_code; } s->current_picture.pict_type= s->pict_type; s->current_picture.key_frame= s->pict_type == I_TYPE; s->y_dc_scale = 8; s->c_dc_scale = 8; s->first_slice = 1; return 0; }


static int mpeg1_find_frame_end(MpegEncContext *s, uint8_t *buf, int buf_size){ ParseContext *pc= &s->parse_context; int i; uint32_t state; state= pc->state; i=0; if(!pc->frame_start_found){ for(i=0; i<buf_size; i++){ state= (state<<8) | buf[i]; if(state >= SLICE_MIN_START_CODE && state <= SLICE_MAX_START_CODE){ i++; pc->frame_start_found=1; break; } } } if(pc->frame_start_found){ for(; i<buf_size; i++){ state= (state<<8) | buf[i]; if((state&0xFFFFFF00) == 0x100){ if(state < SLICE_MIN_START_CODE || state > SLICE_MAX_START_CODE){ pc->frame_start_found=0; pc->state=-1; return i-3; } } } } pc->state= state; return -1; }


static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int i; int64_t creation_time; int version = avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ if (version == 1) { creation_time = avio_rb64(pb); avio_rb64(pb); } else { creation_time = avio_rb32(pb); avio_rb32(pb); /* modification time */ } mov_metadata_creation_time(&c->fc->metadata, creation_time); c->time_scale = avio_rb32(pb); /* time scale */ if (c->time_scale <= 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d\n", c->time_scale); return AVERROR_INVALIDDATA; } av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale); c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */ // set the AVCodecContext duration because the duration of individual tracks // may be inaccurate if (c->time_scale > 0 && !c->trex_data) c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale); avio_rb32(pb); /* preferred scale */ avio_rb16(pb); /* preferred volume */ avio_skip(pb, 10); /* reserved */ /* movie display matrix, store it in main context and use it later on */ for (i = 0; i < 3; i++) { c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point } avio_rb32(pb); /* preview time */ avio_rb32(pb); /* preview duration */ avio_rb32(pb); /* poster time */ avio_rb32(pb); /* selection time */ avio_rb32(pb); /* selection duration */ avio_rb32(pb); /* current time */ avio_rb32(pb); /* next track ID */ return 0; }


static int decode_packet(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000ResLevel *rlevel, int precno, int layno, uint8_t *expn, int numgbits) { int bandno, cblkny, cblknx, cblkno, ret; if (!(ret = get_bits(s, 1))){ j2k_flush(s); return 0; } else if (ret < 0) return ret; for (bandno = 0; bandno < rlevel->nbands; bandno++){ Jpeg2000Band *band = rlevel->band + bandno; Jpeg2000Prec *prec = band->prec + precno; int pos = 0; if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; for (cblkny = prec->yi0; cblkny < prec->yi1; cblkny++) for(cblknx = prec->xi0, cblkno = cblkny * band->cblknx + cblknx; cblknx < prec->xi1; cblknx++, cblkno++, pos++){ Jpeg2000Cblk *cblk = band->cblk + cblkno; int incl, newpasses, llen; if (cblk->npasses) incl = get_bits(s, 1); else incl = tag_tree_decode(s, prec->cblkincl + pos, layno+1) == layno; if (!incl) continue; else if (incl < 0) return incl; if (!cblk->npasses) cblk->nonzerobits = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + pos, 100); if ((newpasses = getnpasses(s)) < 0) return newpasses; if ((llen = getlblockinc(s)) < 0) return llen; cblk->lblock += llen; if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0) return ret; cblk->lengthinc = ret; cblk->npasses += newpasses; } } j2k_flush(s); if (codsty->csty & JPEG2000_CSTY_EPH) { if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH) { bytestream2_skip(&s->g, 2); } else { av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n"); } } for (bandno = 0; bandno < rlevel->nbands; bandno++){ Jpeg2000Band *band = rlevel->band + bandno; int yi, cblknw = band->prec[precno].xi1 - band->prec[precno].xi0; for (yi = band->prec[precno].yi0; yi < band->prec[precno].yi1; yi++){ int xi; for (xi = band->prec[precno].xi0; xi < band->prec[precno].xi1; xi++){ Jpeg2000Cblk *cblk = band->cblk + yi * cblknw + xi; if (bytestream2_get_bytes_left(&s->g) < cblk->lengthinc) return AVERROR(EINVAL); bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc); cblk->length += cblk->lengthinc; cblk->lengthinc = 0; } } } return 0; }


static void avc_luma_vt_and_aver_dst_8x8_msa(const uint8_t *src, int32_t src_stride, uint8_t *dst, int32_t dst_stride) { int32_t loop_cnt; int16_t filt_const0 = 0xfb01; int16_t filt_const1 = 0x1414; int16_t filt_const2 = 0x1fb; v16u8 dst0, dst1, dst2, dst3; v16i8 src0, src1, src2, src3, src4, src7, src8, src9, src10; v16i8 src10_r, src32_r, src76_r, src98_r; v16i8 src21_r, src43_r, src87_r, src109_r; v8i16 out0, out1, out2, out3; v16i8 filt0, filt1, filt2; filt0 = (v16i8) __msa_fill_h(filt_const0); filt1 = (v16i8) __msa_fill_h(filt_const1); filt2 = (v16i8) __msa_fill_h(filt_const2); LD_SB5(src, src_stride, src0, src1, src2, src3, src4); src += (5 * src_stride); XORI_B5_128_SB(src0, src1, src2, src3, src4); ILVR_B4_SB(src1, src0, src2, src1, src3, src2, src4, src3, src10_r, src21_r, src32_r, src43_r); for (loop_cnt = 2; loop_cnt--;) { LD_SB4(src, src_stride, src7, src8, src9, src10); src += (4 * src_stride); XORI_B4_128_SB(src7, src8, src9, src10); ILVR_B4_SB(src7, src4, src8, src7, src9, src8, src10, src9, src76_r, src87_r, src98_r, src109_r); out0 = DPADD_SH3_SH(src10_r, src32_r, src76_r, filt0, filt1, filt2); out1 = DPADD_SH3_SH(src21_r, src43_r, src87_r, filt0, filt1, filt2); out2 = DPADD_SH3_SH(src32_r, src76_r, src98_r, filt0, filt1, filt2); out3 = DPADD_SH3_SH(src43_r, src87_r, src109_r, filt0, filt1, filt2); SRARI_H4_SH(out0, out1, out2, out3, 5); SAT_SH4_SH(out0, out1, out2, out3, 7); LD_UB4(dst, dst_stride, dst0, dst1, dst2, dst3); ILVR_D2_UB(dst1, dst0, dst3, dst2, dst0, dst1); CONVERT_UB_AVG_ST8x4_UB(out0, out1, out2, out3, dst0, dst1, dst, dst_stride); dst += (4 * dst_stride); src10_r = src76_r; src32_r = src98_r; src21_r = src87_r; src43_r = src109_r; src4 = src10; } }


int main (int argc, char **argv) { int ret = 0, got_frame; if (argc != 4 && argc != 5) { fprintf(stderr, "usage: %s [-refcount=<old|new_norefcount|new_refcount>] " "input_file video_output_file audio_output_file\n" "API example program to show how to read frames from an input file.\n" "This program reads frames from a file, decodes them, and writes decoded\n" "video frames to a rawvideo file named video_output_file, and decoded\n" "audio frames to a rawaudio file named audio_output_file.\n\n" "If the -refcount option is specified, the program use the\n" "reference counting frame system which allows keeping a copy of\n" "the data for longer than one decode call. If unset, it's using\n" "the classic old method.\n" "\n", argv[0]); exit(1); } if (argc == 5) { const char *mode = argv[1] + strlen("-refcount="); if (!strcmp(mode, "old")) api_mode = API_MODE_OLD; else if (!strcmp(mode, "new_norefcount")) api_mode = API_MODE_NEW_API_NO_REF_COUNT; else if (!strcmp(mode, "new_refcount")) api_mode = API_MODE_NEW_API_REF_COUNT; else { fprintf(stderr, "unknow mode '%s'\n", mode); exit(1); } argv++; } src_filename = argv[1]; video_dst_filename = argv[2]; audio_dst_filename = argv[3]; /* register all formats and codecs */ av_register_all(); /* open input file, and allocate format context */ if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) { fprintf(stderr, "Could not open source file %s\n", src_filename); exit(1); } /* retrieve stream information */ if (avformat_find_stream_info(fmt_ctx, NULL) < 0) { fprintf(stderr, "Could not find stream information\n"); exit(1); } if (open_codec_context(&video_stream_idx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) { video_stream = fmt_ctx->streams[video_stream_idx]; video_dec_ctx = video_stream->codec; video_dst_file = fopen(video_dst_filename, "wb"); if (!video_dst_file) { fprintf(stderr, "Could not open destination file %s\n", video_dst_filename); ret = 1; goto end; } /* allocate image where the decoded image will be put */ ret = av_image_alloc(video_dst_data, video_dst_linesize, video_dec_ctx->width, video_dec_ctx->height, video_dec_ctx->pix_fmt, 1); if (ret < 0) { fprintf(stderr, "Could not allocate raw video buffer\n"); goto end; } video_dst_bufsize = ret; } if (open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) { audio_stream = fmt_ctx->streams[audio_stream_idx]; audio_dec_ctx = audio_stream->codec; audio_dst_file = fopen(audio_dst_filename, "wb"); if (!audio_dst_file) { fprintf(stderr, "Could not open destination file %s\n", video_dst_filename); ret = 1; goto end; } } /* dump input information to stderr */ av_dump_format(fmt_ctx, 0, src_filename, 0); if (!audio_stream && !video_stream) { fprintf(stderr, "Could not find audio or video stream in the input, aborting\n"); ret = 1; goto end; } /* When using the new API, you need to use the libavutil/frame.h API, while * the classic frame management is available in libavcodec */ if (api_mode == API_MODE_OLD) frame = avcodec_alloc_frame(); else frame = av_frame_alloc(); if (!frame) { fprintf(stderr, "Could not allocate frame\n"); ret = AVERROR(ENOMEM); goto end; } /* initialize packet, set data to NULL, let the demuxer fill it */ av_init_packet(&pkt); pkt.data = NULL; pkt.size = 0; if (video_stream) printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename); if (audio_stream) printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename); /* read frames from the file */ while (av_read_frame(fmt_ctx, &pkt) >= 0) { AVPacket orig_pkt = pkt; do { ret = decode_packet(&got_frame, 0); if (ret < 0) break; pkt.data += ret; pkt.size -= ret; } while (pkt.size > 0); av_free_packet(&orig_pkt); } /* flush cached frames */ pkt.data = NULL; pkt.size = 0; do { decode_packet(&got_frame, 1); } while (got_frame); printf("Demuxing succeeded.\n"); if (video_stream) { printf("Play the output video file with the command:\n" "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n", av_get_pix_fmt_name(video_dec_ctx->pix_fmt), video_dec_ctx->width, video_dec_ctx->height, video_dst_filename); } if (audio_stream) { enum AVSampleFormat sfmt = audio_dec_ctx->sample_fmt; int n_channels = audio_dec_ctx->channels; const char *fmt; if (av_sample_fmt_is_planar(sfmt)) { const char *packed = av_get_sample_fmt_name(sfmt); printf("Warning: the sample format the decoder produced is planar " "(%s). This example will output the first channel only.\n", packed ? packed : "?"); sfmt = av_get_packed_sample_fmt(sfmt); n_channels = 1; } if ((ret = get_format_from_sample_fmt(&fmt, sfmt)) < 0) goto end; printf("Play the output audio file with the command:\n" "ffplay -f %s -ac %d -ar %d %s\n", fmt, n_channels, audio_dec_ctx->sample_rate, audio_dst_filename); } end: if (video_dec_ctx) avcodec_close(video_dec_ctx); if (audio_dec_ctx) avcodec_close(audio_dec_ctx); avformat_close_input(&fmt_ctx); if (video_dst_file) fclose(video_dst_file); if (audio_dst_file) fclose(audio_dst_file); if (api_mode == API_MODE_OLD) avcodec_free_frame(&frame); else av_frame_free(&frame); av_free(video_dst_data[0]); return ret < 0; }


void ff_celp_lp_synthesis_filterf(float *out, const float* filter_coeffs, const float* in, int buffer_length, int filter_length) { int i,n; // Avoids a +1 in the inner loop. filter_length++; for (n = 0; n < buffer_length; n++) { out[n] = in[n]; for (i = 1; i < filter_length; i++) out[n] -= filter_coeffs[i-1] * out[n-i]; } }


static int read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { BinkDemuxContext *bink = s->priv_data; AVStream *vst = s->streams[0]; if (!s->pb->seekable) return -1; /* seek to the first frame */ if (avio_seek(s->pb, vst->index_entries[0].pos, SEEK_SET) < 0) return -1; bink->video_pts = 0; memset(bink->audio_pts, 0, sizeof(bink->audio_pts)); bink->current_track = -1; return 0; }


static int dvvideo_decode_frame(AVCodecContext *avctx, void *data, int *data_size, UINT8 *buf, int buf_size) { DVVideoDecodeContext *s = avctx->priv_data; int sct, dsf, apt, ds, nb_dif_segs, vs, width, height, i, packet_size; unsigned size; UINT8 *buf_ptr; const UINT16 *mb_pos_ptr; AVPicture *picture; /* parse id */ init_get_bits(&s->gb, buf, buf_size); sct = get_bits(&s->gb, 3); if (sct != 0) return -1; skip_bits(&s->gb, 5); get_bits(&s->gb, 4); /* dsn (sequence number */ get_bits(&s->gb, 1); /* fsc (channel number) */ skip_bits(&s->gb, 3); get_bits(&s->gb, 8); /* dbn (diff block number 0-134) */ dsf = get_bits(&s->gb, 1); /* 0 = NTSC 1 = PAL */ if (get_bits(&s->gb, 1) != 0) return -1; skip_bits(&s->gb, 11); apt = get_bits(&s->gb, 3); /* apt */ get_bits(&s->gb, 1); /* tf1 */ skip_bits(&s->gb, 4); get_bits(&s->gb, 3); /* ap1 */ get_bits(&s->gb, 1); /* tf2 */ skip_bits(&s->gb, 4); get_bits(&s->gb, 3); /* ap2 */ get_bits(&s->gb, 1); /* tf3 */ skip_bits(&s->gb, 4); get_bits(&s->gb, 3); /* ap3 */ /* init size */ width = 720; if (dsf) { avctx->frame_rate = 25 * FRAME_RATE_BASE; packet_size = PAL_FRAME_SIZE; height = 576; nb_dif_segs = 12; } else { avctx->frame_rate = 30 * FRAME_RATE_BASE; packet_size = NTSC_FRAME_SIZE; height = 480; nb_dif_segs = 10; } /* NOTE: we only accept several full frames */ if (buf_size < packet_size) return -1; /* XXX: is it correct to assume that 420 is always used in PAL mode ? */ s->sampling_411 = !dsf; if (s->sampling_411) { mb_pos_ptr = dv_place_411; avctx->pix_fmt = PIX_FMT_YUV411P; } else { mb_pos_ptr = dv_place_420; avctx->pix_fmt = PIX_FMT_YUV420P; } avctx->width = width; avctx->height = height; if (avctx->flags & CODEC_FLAG_DR1 && avctx->get_buffer_callback) { s->width = -1; avctx->dr_buffer[0] = avctx->dr_buffer[1] = avctx->dr_buffer[2] = 0; if(avctx->get_buffer_callback(avctx, width, height, I_TYPE) < 0){ fprintf(stderr, "get_buffer() failed\n"); return -1; } } /* (re)alloc picture if needed */ if (s->width != width || s->height != height) { if (!(avctx->flags & CODEC_FLAG_DR1)) for(i=0;i<3;i++) { if (avctx->dr_buffer[i] != s->current_picture[i]) av_freep(&s->current_picture[i]); avctx->dr_buffer[i] = 0; } for(i=0;i<3;i++) { if (avctx->dr_buffer[i]) { s->current_picture[i] = avctx->dr_buffer[i]; s->linesize[i] = (i == 0) ? avctx->dr_stride : avctx->dr_uvstride; } else { size = width * height; s->linesize[i] = width; if (i >= 1) { size >>= 2; s->linesize[i] >>= s->sampling_411 ? 2 : 1; } s->current_picture[i] = av_malloc(size); } if (!s->current_picture[i]) return -1; } s->width = width; s->height = height; } /* for each DIF segment */ buf_ptr = buf; for (ds = 0; ds < nb_dif_segs; ds++) { buf_ptr += 6 * 80; /* skip DIF segment header */ for(vs = 0; vs < 27; vs++) { if ((vs % 3) == 0) { /* skip audio block */ buf_ptr += 80; } dv_decode_video_segment(s, buf_ptr, mb_pos_ptr); buf_ptr += 5 * 80; mb_pos_ptr += 5; } } emms_c(); /* return image */ *data_size = sizeof(AVPicture); picture = data; for(i=0;i<3;i++) { picture->data[i] = s->current_picture[i]; picture->linesize[i] = s->linesize[i]; } return packet_size; }


static int audio_read_header(AVFormatContext *s1, AVFormatParameters *ap) { AudioData *s = s1->priv_data; AVStream *st; int ret; if (!ap || ap->sample_rate <= 0 || ap->channels <= 0) return -1; st = av_new_stream(s1, 0); if (!st) { return -ENOMEM; } s->sample_rate = ap->sample_rate; s->channels = ap->channels; ret = audio_open(s, 0, ap->device); if (ret < 0) { av_free(st); return AVERROR_IO; } /* take real parameters */ st->codec->codec_type = CODEC_TYPE_AUDIO; st->codec->codec_id = s->codec_id; st->codec->sample_rate = s->sample_rate; st->codec->channels = s->channels; av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */ return 0; }


char *ff_get_ref_perms_string(char *buf, size_t buf_size, int perms) { snprintf(buf, buf_size, "%s%s%s%s%s", perms & AV_PERM_READ ? "r" : "", perms & AV_PERM_WRITE ? "w" : "", perms & AV_PERM_PRESERVE ? "p" : "", perms & AV_PERM_REUSE ? "u" : "", perms & AV_PERM_REUSE2 ? "U" : ""); return buf; }


static void gif_copy_img_rect(const uint32_t *src, uint32_t *dst, int linesize, int l, int t, int w, int h) { const int y_start = t * linesize; const uint32_t *src_px, *src_pr, *src_py = src + y_start, *dst_py = dst + y_start; const uint32_t *src_pb = src_py + t * linesize; uint32_t *dst_px; for (; src_py < src_pb; src_py += linesize, dst_py += linesize) { src_px = src_py + l; dst_px = (uint32_t *)dst_py + l; src_pr = src_px + w; for (; src_px < src_pr; src_px++, dst_px++) *dst_px = *src_px; } }


static int alac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr) { AlacEncodeContext *s = avctx->priv_data; int out_bytes, max_frame_size, ret; s->frame_size = frame->nb_samples; if (frame->nb_samples < DEFAULT_FRAME_SIZE) max_frame_size = get_max_frame_size(s->frame_size, avctx->channels, avctx->bits_per_raw_sample); else max_frame_size = s->max_coded_frame_size; if ((ret = ff_alloc_packet2(avctx, avpkt, 2 * max_frame_size))) return ret; /* use verbatim mode for compression_level 0 */ if (s->compression_level) { s->verbatim = 0; s->extra_bits = avctx->bits_per_raw_sample - 16; } else { s->verbatim = 1; s->extra_bits = 0; } out_bytes = write_frame(s, avpkt, frame->extended_data); if (out_bytes > max_frame_size) { /* frame too large. use verbatim mode */ s->verbatim = 1; s->extra_bits = 0; out_bytes = write_frame(s, avpkt, frame->extended_data); } avpkt->size = out_bytes; *got_packet_ptr = 1; return 0; }


static int bmdma_rw_buf(IDEDMA *dma, int is_write) { BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma); IDEState *s = bmdma_active_if(bm); struct { uint32_t addr; uint32_t size; } prd; int l, len; for(;;) { l = s->io_buffer_size - s->io_buffer_index; if (l <= 0) break; if (bm->cur_prd_len == 0) { /* end of table (with a fail safe of one page) */ if (bm->cur_prd_last || (bm->cur_addr - bm->addr) >= BMDMA_PAGE_SIZE) return 0; cpu_physical_memory_read(bm->cur_addr, (uint8_t *)&prd, 8); bm->cur_addr += 8; prd.addr = le32_to_cpu(prd.addr); prd.size = le32_to_cpu(prd.size); len = prd.size & 0xfffe; if (len == 0) len = 0x10000; bm->cur_prd_len = len; bm->cur_prd_addr = prd.addr; bm->cur_prd_last = (prd.size & 0x80000000); } if (l > bm->cur_prd_len) l = bm->cur_prd_len; if (l > 0) { if (is_write) { cpu_physical_memory_write(bm->cur_prd_addr, s->io_buffer + s->io_buffer_index, l); } else { cpu_physical_memory_read(bm->cur_prd_addr, s->io_buffer + s->io_buffer_index, l); } bm->cur_prd_addr += l; bm->cur_prd_len -= l; s->io_buffer_index += l; } } return 1; }


static void gen_dmfc0 (DisasContext *ctx, int reg, int sel) { const char *rn = "invalid"; switch (reg) { case 0: switch (sel) { case 0: gen_op_mfc0_index(); rn = "Index"; break; case 1: // gen_op_dmfc0_mvpcontrol(); /* MT ASE */ rn = "MVPControl"; // break; case 2: // gen_op_dmfc0_mvpconf0(); /* MT ASE */ rn = "MVPConf0"; // break; case 3: // gen_op_dmfc0_mvpconf1(); /* MT ASE */ rn = "MVPConf1"; // break; default: goto die; } break; case 1: switch (sel) { case 0: gen_op_mfc0_random(); rn = "Random"; break; case 1: // gen_op_dmfc0_vpecontrol(); /* MT ASE */ rn = "VPEControl"; // break; case 2: // gen_op_dmfc0_vpeconf0(); /* MT ASE */ rn = "VPEConf0"; // break; case 3: // gen_op_dmfc0_vpeconf1(); /* MT ASE */ rn = "VPEConf1"; // break; case 4: // gen_op_dmfc0_YQMask(); /* MT ASE */ rn = "YQMask"; // break; case 5: // gen_op_dmfc0_vpeschedule(); /* MT ASE */ rn = "VPESchedule"; // break; case 6: // gen_op_dmfc0_vpeschefback(); /* MT ASE */ rn = "VPEScheFBack"; // break; case 7: // gen_op_dmfc0_vpeopt(); /* MT ASE */ rn = "VPEOpt"; // break; default: goto die; } break; case 2: switch (sel) { case 0: gen_op_dmfc0_entrylo0(); rn = "EntryLo0"; break; case 1: // gen_op_dmfc0_tcstatus(); /* MT ASE */ rn = "TCStatus"; // break; case 2: // gen_op_dmfc0_tcbind(); /* MT ASE */ rn = "TCBind"; // break; case 3: // gen_op_dmfc0_tcrestart(); /* MT ASE */ rn = "TCRestart"; // break; case 4: // gen_op_dmfc0_tchalt(); /* MT ASE */ rn = "TCHalt"; // break; case 5: // gen_op_dmfc0_tccontext(); /* MT ASE */ rn = "TCContext"; // break; case 6: // gen_op_dmfc0_tcschedule(); /* MT ASE */ rn = "TCSchedule"; // break; case 7: // gen_op_dmfc0_tcschefback(); /* MT ASE */ rn = "TCScheFBack"; // break; default: goto die; } break; case 3: switch (sel) { case 0: gen_op_dmfc0_entrylo1(); rn = "EntryLo1"; break; default: goto die; } break; case 4: switch (sel) { case 0: gen_op_dmfc0_context(); rn = "Context"; break; case 1: // gen_op_dmfc0_contextconfig(); /* SmartMIPS ASE */ rn = "ContextConfig"; // break; default: goto die; } break; case 5: switch (sel) { case 0: gen_op_mfc0_pagemask(); rn = "PageMask"; break; case 1: gen_op_mfc0_pagegrain(); rn = "PageGrain"; break; default: goto die; } break; case 6: switch (sel) { case 0: gen_op_mfc0_wired(); rn = "Wired"; break; case 1: // gen_op_dmfc0_srsconf0(); /* shadow registers */ rn = "SRSConf0"; // break; case 2: // gen_op_dmfc0_srsconf1(); /* shadow registers */ rn = "SRSConf1"; // break; case 3: // gen_op_dmfc0_srsconf2(); /* shadow registers */ rn = "SRSConf2"; // break; case 4: // gen_op_dmfc0_srsconf3(); /* shadow registers */ rn = "SRSConf3"; // break; case 5: // gen_op_dmfc0_srsconf4(); /* shadow registers */ rn = "SRSConf4"; // break; default: goto die; } break; case 7: switch (sel) { case 0: gen_op_mfc0_hwrena(); rn = "HWREna"; break; default: goto die; } break; case 8: switch (sel) { case 0: gen_op_dmfc0_badvaddr(); rn = "BadVaddr"; break; default: goto die; } break; case 9: switch (sel) { case 0: gen_op_mfc0_count(); rn = "Count"; break; /* 6,7 are implementation dependent */ default: goto die; } break; case 10: switch (sel) { case 0: gen_op_dmfc0_entryhi(); rn = "EntryHi"; break; default: goto die; } break; case 11: switch (sel) { case 0: gen_op_mfc0_compare(); rn = "Compare"; break; /* 6,7 are implementation dependent */ default: goto die; } break; case 12: switch (sel) { case 0: gen_op_mfc0_status(); rn = "Status"; break; case 1: gen_op_mfc0_intctl(); rn = "IntCtl"; break; case 2: gen_op_mfc0_srsctl(); rn = "SRSCtl"; break; case 3: gen_op_mfc0_srsmap(); /* shadow registers */ rn = "SRSMap"; break; default: goto die; } break; case 13: switch (sel) { case 0: gen_op_mfc0_cause(); rn = "Cause"; break; default: goto die; } break; case 14: switch (sel) { case 0: gen_op_dmfc0_epc(); rn = "EPC"; break; default: goto die; } break; case 15: switch (sel) { case 0: gen_op_mfc0_prid(); rn = "PRid"; break; case 1: gen_op_dmfc0_ebase(); rn = "EBase"; break; default: goto die; } break; case 16: switch (sel) { case 0: gen_op_mfc0_config0(); rn = "Config"; break; case 1: gen_op_mfc0_config1(); rn = "Config1"; break; case 2: gen_op_mfc0_config2(); rn = "Config2"; break; case 3: gen_op_mfc0_config3(); rn = "Config3"; break; /* 6,7 are implementation dependent */ default: goto die; } break; case 17: switch (sel) { case 0: gen_op_dmfc0_lladdr(); rn = "LLAddr"; break; default: goto die; } break; case 18: switch (sel) { case 0: gen_op_dmfc0_watchlo0(); rn = "WatchLo"; break; case 1: // gen_op_dmfc0_watchlo1(); rn = "WatchLo1"; // break; case 2: // gen_op_dmfc0_watchlo2(); rn = "WatchLo2"; // break; case 3: // gen_op_dmfc0_watchlo3(); rn = "WatchLo3"; // break; case 4: // gen_op_dmfc0_watchlo4(); rn = "WatchLo4"; // break; case 5: // gen_op_dmfc0_watchlo5(); rn = "WatchLo5"; // break; case 6: // gen_op_dmfc0_watchlo6(); rn = "WatchLo6"; // break; case 7: // gen_op_dmfc0_watchlo7(); rn = "WatchLo7"; // break; default: goto die; } break; case 19: switch (sel) { case 0: gen_op_mfc0_watchhi0(); rn = "WatchHi"; break; case 1: // gen_op_mfc0_watchhi1(); rn = "WatchHi1"; // break; case 2: // gen_op_mfc0_watchhi2(); rn = "WatchHi2"; // break; case 3: // gen_op_mfc0_watchhi3(); rn = "WatchHi3"; // break; case 4: // gen_op_mfc0_watchhi4(); rn = "WatchHi4"; // break; case 5: // gen_op_mfc0_watchhi5(); rn = "WatchHi5"; // break; case 6: // gen_op_mfc0_watchhi6(); rn = "WatchHi6"; // break; case 7: // gen_op_mfc0_watchhi7(); rn = "WatchHi7"; // break; default: goto die; } break; case 20: switch (sel) { case 0: /* 64 bit MMU only */ gen_op_dmfc0_xcontext(); rn = "XContext"; break; default: goto die; } break; case 21: /* Officially reserved, but sel 0 is used for R1x000 framemask */ switch (sel) { case 0: gen_op_mfc0_framemask(); rn = "Framemask"; break; default: goto die; } break; case 22: /* ignored */ rn = "'Diagnostic"; /* implementation dependent */ break; case 23: switch (sel) { case 0: gen_op_mfc0_debug(); /* EJTAG support */ rn = "Debug"; break; case 1: // gen_op_dmfc0_tracecontrol(); /* PDtrace support */ rn = "TraceControl"; // break; case 2: // gen_op_dmfc0_tracecontrol2(); /* PDtrace support */ rn = "TraceControl2"; // break; case 3: // gen_op_dmfc0_usertracedata(); /* PDtrace support */ rn = "UserTraceData"; // break; case 4: // gen_op_dmfc0_debug(); /* PDtrace support */ rn = "TraceBPC"; // break; default: goto die; } break; case 24: switch (sel) { case 0: gen_op_dmfc0_depc(); /* EJTAG support */ rn = "DEPC"; break; default: goto die; } break; case 25: switch (sel) { case 0: gen_op_mfc0_performance0(); rn = "Performance0"; break; case 1: // gen_op_dmfc0_performance1(); rn = "Performance1"; // break; case 2: // gen_op_dmfc0_performance2(); rn = "Performance2"; // break; case 3: // gen_op_dmfc0_performance3(); rn = "Performance3"; // break; case 4: // gen_op_dmfc0_performance4(); rn = "Performance4"; // break; case 5: // gen_op_dmfc0_performance5(); rn = "Performance5"; // break; case 6: // gen_op_dmfc0_performance6(); rn = "Performance6"; // break; case 7: // gen_op_dmfc0_performance7(); rn = "Performance7"; // break; default: goto die; } break; case 26: rn = "ECC"; break; case 27: switch (sel) { /* ignored */ case 0 ... 3: rn = "CacheErr"; break; default: goto die; } break; case 28: switch (sel) { case 0: case 2: case 4: case 6: gen_op_mfc0_taglo(); rn = "TagLo"; break; case 1: case 3: case 5: case 7: gen_op_mfc0_datalo(); rn = "DataLo"; break; default: goto die; } break; case 29: switch (sel) { case 0: case 2: case 4: case 6: gen_op_mfc0_taghi(); rn = "TagHi"; break; case 1: case 3: case 5: case 7: gen_op_mfc0_datahi(); rn = "DataHi"; break; default: goto die; } break; case 30: switch (sel) { case 0: gen_op_dmfc0_errorepc(); rn = "ErrorEPC"; break; default: goto die; } break; case 31: switch (sel) { case 0: gen_op_mfc0_desave(); /* EJTAG support */ rn = "DESAVE"; break; default: goto die; } break; default: goto die; } #if defined MIPS_DEBUG_DISAS if (loglevel & CPU_LOG_TB_IN_ASM) { fprintf(logfile, "dmfc0 %s (reg %d sel %d)\n", rn, reg, sel); } #endif return; die: #if defined MIPS_DEBUG_DISAS if (loglevel & CPU_LOG_TB_IN_ASM) { fprintf(logfile, "dmfc0 %s (reg %d sel %d)\n", rn, reg, sel); } #endif generate_exception(ctx, EXCP_RI); }


static void create_cpu(const char *cpu_model, qemu_irq *cbus_irq, qemu_irq *i8259_irq) { CPUMIPSState *env; MIPSCPU *cpu; int i; if (cpu_model == NULL) { #ifdef TARGET_MIPS64 cpu_model = "20Kc"; #else cpu_model = "24Kf"; #endif } for (i = 0; i < smp_cpus; i++) { cpu = cpu_mips_init(cpu_model); if (cpu == NULL) { fprintf(stderr, "Unable to find CPU definition\n"); exit(1); } env = &cpu->env; /* Init internal devices */ cpu_mips_irq_init_cpu(env); cpu_mips_clock_init(env); qemu_register_reset(main_cpu_reset, cpu); } cpu = MIPS_CPU(first_cpu); env = &cpu->env; *i8259_irq = env->irq[2]; *cbus_irq = env->irq[4]; }


void qed_release(BDRVQEDState *s) { aio_context_release(bdrv_get_aio_context(s->bs)); }


int v9fs_co_readlink(V9fsPDU *pdu, V9fsPath *path, V9fsString *buf) { int err; ssize_t len; V9fsState *s = pdu->s; if (v9fs_request_cancelled(pdu)) { return -EINTR; } buf->data = g_malloc(PATH_MAX); v9fs_path_read_lock(s); v9fs_co_run_in_worker( { len = s->ops->readlink(&s->ctx, path, buf->data, PATH_MAX - 1); if (len > -1) { buf->size = len; buf->data[len] = 0; err = 0; } else { err = -errno; } }); v9fs_path_unlock(s); if (err) { g_free(buf->data); buf->data = NULL; buf->size = 0; } return err; }


int nbd_receive_negotiate(QIOChannel *ioc, const char *name, uint16_t *flags, QCryptoTLSCreds *tlscreds, const char *hostname, QIOChannel **outioc, off_t *size, Error **errp) { char buf[256]; uint64_t magic, s; int rc; bool zeroes = true; TRACE("Receiving negotiation tlscreds=%p hostname=%s.", tlscreds, hostname ? hostname : "<null>"); rc = -EINVAL; if (outioc) { *outioc = NULL; } if (tlscreds && !outioc) { error_setg(errp, "Output I/O channel required for TLS"); goto fail; } if (read_sync(ioc, buf, 8, errp) < 0) { error_prepend(errp, "Failed to read data"); goto fail; } buf[8] = '\0'; if (strlen(buf) == 0) { error_setg(errp, "Server connection closed unexpectedly"); goto fail; } TRACE("Magic is %c%c%c%c%c%c%c%c", qemu_isprint(buf[0]) ? buf[0] : '.', qemu_isprint(buf[1]) ? buf[1] : '.', qemu_isprint(buf[2]) ? buf[2] : '.', qemu_isprint(buf[3]) ? buf[3] : '.', qemu_isprint(buf[4]) ? buf[4] : '.', qemu_isprint(buf[5]) ? buf[5] : '.', qemu_isprint(buf[6]) ? buf[6] : '.', qemu_isprint(buf[7]) ? buf[7] : '.'); if (memcmp(buf, "NBDMAGIC", 8) != 0) { error_setg(errp, "Invalid magic received"); goto fail; } if (read_sync(ioc, &magic, sizeof(magic), errp) < 0) { error_prepend(errp, "Failed to read magic"); goto fail; } magic = be64_to_cpu(magic); TRACE("Magic is 0x%" PRIx64, magic); if (magic == NBD_OPTS_MAGIC) { uint32_t clientflags = 0; uint16_t globalflags; bool fixedNewStyle = false; if (read_sync(ioc, &globalflags, sizeof(globalflags), errp) < 0) { error_prepend(errp, "Failed to read server flags"); goto fail; } globalflags = be16_to_cpu(globalflags); TRACE("Global flags are %" PRIx32, globalflags); if (globalflags & NBD_FLAG_FIXED_NEWSTYLE) { fixedNewStyle = true; TRACE("Server supports fixed new style"); clientflags |= NBD_FLAG_C_FIXED_NEWSTYLE; } if (globalflags & NBD_FLAG_NO_ZEROES) { zeroes = false; TRACE("Server supports no zeroes"); clientflags |= NBD_FLAG_C_NO_ZEROES; } /* client requested flags */ clientflags = cpu_to_be32(clientflags); if (write_sync(ioc, &clientflags, sizeof(clientflags), errp) < 0) { error_prepend(errp, "Failed to send clientflags field"); goto fail; } if (tlscreds) { if (fixedNewStyle) { *outioc = nbd_receive_starttls(ioc, tlscreds, hostname, errp); if (!*outioc) { goto fail; } ioc = *outioc; } else { error_setg(errp, "Server does not support STARTTLS"); goto fail; } } if (!name) { TRACE("Using default NBD export name \"\""); name = ""; } if (fixedNewStyle) { /* Check our desired export is present in the * server export list. Since NBD_OPT_EXPORT_NAME * cannot return an error message, running this * query gives us good error reporting if the * server required TLS */ if (nbd_receive_query_exports(ioc, name, errp) < 0) { goto fail; } } /* write the export name request */ if (nbd_send_option_request(ioc, NBD_OPT_EXPORT_NAME, -1, name, errp) < 0) { goto fail; } /* Read the response */ if (read_sync(ioc, &s, sizeof(s), errp) < 0) { error_prepend(errp, "Failed to read export length"); goto fail; } *size = be64_to_cpu(s); if (read_sync(ioc, flags, sizeof(*flags), errp) < 0) { error_prepend(errp, "Failed to read export flags"); goto fail; } be16_to_cpus(flags); } else if (magic == NBD_CLIENT_MAGIC) { uint32_t oldflags; if (name) { error_setg(errp, "Server does not support export names"); goto fail; } if (tlscreds) { error_setg(errp, "Server does not support STARTTLS"); goto fail; } if (read_sync(ioc, &s, sizeof(s), errp) < 0) { error_prepend(errp, "Failed to read export length"); goto fail; } *size = be64_to_cpu(s); TRACE("Size is %" PRIu64, *size); if (read_sync(ioc, &oldflags, sizeof(oldflags), errp) < 0) { error_prepend(errp, "Failed to read export flags"); goto fail; } be32_to_cpus(&oldflags); if (oldflags & ~0xffff) { error_setg(errp, "Unexpected export flags %0x" PRIx32, oldflags); goto fail; } *flags = oldflags; } else { error_setg(errp, "Bad magic received"); goto fail; } TRACE("Size is %" PRIu64 ", export flags %" PRIx16, *size, *flags); if (zeroes && drop_sync(ioc, 124, errp) < 0) { error_prepend(errp, "Failed to read reserved block"); goto fail; } rc = 0; fail: return rc; }


void spapr_events_fdt_skel(void *fdt, uint32_t epow_irq) { uint32_t epow_irq_ranges[] = {cpu_to_be32(epow_irq), cpu_to_be32(1)}; uint32_t epow_interrupts[] = {cpu_to_be32(epow_irq), 0}; _FDT((fdt_begin_node(fdt, "event-sources"))); _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0))); _FDT((fdt_property_cell(fdt, "#interrupt-cells", 2))); _FDT((fdt_property(fdt, "interrupt-ranges", epow_irq_ranges, sizeof(epow_irq_ranges)))); _FDT((fdt_begin_node(fdt, "epow-events"))); _FDT((fdt_property(fdt, "interrupts", epow_interrupts, sizeof(epow_interrupts)))); _FDT((fdt_end_node(fdt))); _FDT((fdt_end_node(fdt))); }


static void vfio_put_device(VFIOPCIDevice *vdev) { QLIST_REMOVE(vdev, next); vdev->vbasedev.group = NULL; trace_vfio_put_device(vdev->vbasedev.fd); close(vdev->vbasedev.fd); g_free(vdev->vbasedev.name); if (vdev->msix) { g_free(vdev->msix); vdev->msix = NULL; } }


static int open_self_cmdline(void *cpu_env, int fd) { int fd_orig = -1; bool word_skipped = false; fd_orig = open("/proc/self/cmdline", O_RDONLY); if (fd_orig < 0) { return fd_orig; } while (true) { ssize_t nb_read; char buf[128]; char *cp_buf = buf; nb_read = read(fd_orig, buf, sizeof(buf)); if (nb_read < 0) { int e = errno; fd_orig = close(fd_orig); errno = e; return -1; } else if (nb_read == 0) { break; } if (!word_skipped) { /* Skip the first string, which is the path to qemu-*-static instead of the actual command. */ cp_buf = memchr(buf, 0, sizeof(buf)); if (cp_buf) { /* Null byte found, skip one string */ cp_buf++; nb_read -= cp_buf - buf; word_skipped = true; } } if (word_skipped) { if (write(fd, cp_buf, nb_read) != nb_read) { int e = errno; close(fd_orig); errno = e; return -1; } } } return close(fd_orig); }


static int xan_decode_frame_type1(AVCodecContext *avctx) { XanContext *s = avctx->priv_data; uint8_t *ybuf, *src = s->scratch_buffer; int cur, last; int i, j; int ret; if ((ret = xan_decode_chroma(avctx, bytestream2_get_le32(&s->gb))) != 0) return ret; bytestream2_seek(&s->gb, 16, SEEK_SET); ret = xan_unpack_luma(s, src, s->buffer_size >> 1); if (ret) { av_log(avctx, AV_LOG_ERROR, "Luma decoding failed\n"); return ret; } ybuf = s->y_buffer; for (i = 0; i < avctx->height; i++) { last = (ybuf[0] + (*src++ << 1)) & 0x3F; ybuf[0] = last; for (j = 1; j < avctx->width - 1; j += 2) { cur = (ybuf[j + 1] + (*src++ << 1)) & 0x3F; ybuf[j] = (last + cur) >> 1; ybuf[j+1] = cur; last = cur; } ybuf[j] = last; ybuf += avctx->width; } src = s->y_buffer; ybuf = s->pic.data[0]; for (j = 0; j < avctx->height; j++) { for (i = 0; i < avctx->width; i++) ybuf[i] = (src[i] << 2) | (src[i] >> 3); src += avctx->width; ybuf += s->pic.linesize[0]; } return 0; }


static void vtd_context_device_invalidate(IntelIOMMUState *s, uint16_t source_id, uint16_t func_mask) { uint16_t mask; VTDAddressSpace **pvtd_as; VTDAddressSpace *vtd_as; uint16_t devfn; uint16_t devfn_it; switch (func_mask & 3) { case 0: mask = 0; /* No bits in the SID field masked */ break; case 1: mask = 4; /* Mask bit 2 in the SID field */ break; case 2: mask = 6; /* Mask bit 2:1 in the SID field */ break; case 3: mask = 7; /* Mask bit 2:0 in the SID field */ break; } VTD_DPRINTF(INV, "device-selective invalidation source 0x%"PRIx16 " mask %"PRIu16, source_id, mask); pvtd_as = s->address_spaces[VTD_SID_TO_BUS(source_id)]; if (pvtd_as) { devfn = VTD_SID_TO_DEVFN(source_id); for (devfn_it = 0; devfn_it < VTD_PCI_DEVFN_MAX; ++devfn_it) { vtd_as = pvtd_as[devfn_it]; if (vtd_as && ((devfn_it & mask) == (devfn & mask))) { VTD_DPRINTF(INV, "invalidate context-cahce of devfn 0x%"PRIx16, devfn_it); vtd_as->context_cache_entry.context_cache_gen = 0; } } } }


static int raw_open(BlockDriverState *bs, QDict *options, int flags, Error **errp) { BDRVRawState *s = bs->opaque; int access_flags; DWORD overlapped; QemuOpts *opts; Error *local_err = NULL; const char *filename; int ret; s->type = FTYPE_FILE; opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort); qemu_opts_absorb_qdict(opts, options, &local_err); if (local_err) { error_propagate(errp, local_err); ret = -EINVAL; goto fail; } filename = qemu_opt_get(opts, "filename"); raw_parse_flags(flags, &access_flags, &overlapped); if (filename[0] && filename[1] == ':') { snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", filename[0]); } else if (filename[0] == '\\' && filename[1] == '\\') { s->drive_path[0] = 0; } else { /* Relative path. */ char buf[MAX_PATH]; GetCurrentDirectory(MAX_PATH, buf); snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", buf[0]); } s->hfile = CreateFile(filename, access_flags, FILE_SHARE_READ, NULL, OPEN_EXISTING, overlapped, NULL); if (s->hfile == INVALID_HANDLE_VALUE) { int err = GetLastError(); if (err == ERROR_ACCESS_DENIED) { ret = -EACCES; } else { ret = -EINVAL; } goto fail; } if (flags & BDRV_O_NATIVE_AIO) { s->aio = win32_aio_init(); if (s->aio == NULL) { CloseHandle(s->hfile); error_setg(errp, "Could not initialize AIO"); ret = -EINVAL; goto fail; } ret = win32_aio_attach(s->aio, s->hfile); if (ret < 0) { win32_aio_cleanup(s->aio); CloseHandle(s->hfile); error_setg_errno(errp, -ret, "Could not enable AIO"); goto fail; } win32_aio_attach_aio_context(s->aio, bdrv_get_aio_context(bs)); } raw_probe_alignment(bs); ret = 0; fail: qemu_opts_del(opts); return ret; }


static struct omap_watchdog_timer_s *omap_wd_timer_init(MemoryRegion *memory, target_phys_addr_t base, qemu_irq irq, omap_clk clk) { struct omap_watchdog_timer_s *s = (struct omap_watchdog_timer_s *) g_malloc0(sizeof(struct omap_watchdog_timer_s)); s->timer.irq = irq; s->timer.clk = clk; s->timer.timer = qemu_new_timer_ns(vm_clock, omap_timer_tick, &s->timer); omap_wd_timer_reset(s); omap_timer_clk_setup(&s->timer); memory_region_init_io(&s->iomem, &omap_wd_timer_ops, s, "omap-wd-timer", 0x100); memory_region_add_subregion(memory, base, &s->iomem); return s; }


void qmp_block_job_cancel(const char *device, bool has_force, bool force, Error **errp) { BlockJob *job = find_block_job(device); if (!has_force) { force = false; } if (!job) { error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device); return; } if (job->paused && !force) { error_setg(errp, "The block job for device '%s' is currently paused", device); return; } trace_qmp_block_job_cancel(job); block_job_cancel(job); }


static void gen_flt3_ldst (DisasContext *ctx, uint32_t opc, int fd, int fs, int base, int index) { const char *opn = "extended float load/store"; int store = 0; TCGv t0 = tcg_temp_new(); if (base == 0) { gen_load_gpr(t0, index); } else if (index == 0) { gen_load_gpr(t0, base); } else { gen_load_gpr(t0, index); gen_op_addr_add(ctx, t0, cpu_gpr[base]); } /* Don't do NOP if destination is zero: we must perform the actual memory access. */ save_cpu_state(ctx, 0); switch (opc) { case OPC_LWXC1: check_cop1x(ctx); { TCGv_i32 fp0 = tcg_temp_new_i32(); tcg_gen_qemu_ld32s(t0, t0, ctx->mem_idx); tcg_gen_trunc_tl_i32(fp0, t0); gen_store_fpr32(fp0, fd); tcg_temp_free_i32(fp0); } opn = "lwxc1"; break; case OPC_LDXC1: check_cop1x(ctx); check_cp1_registers(ctx, fd); { TCGv_i64 fp0 = tcg_temp_new_i64(); tcg_gen_qemu_ld64(fp0, t0, ctx->mem_idx); gen_store_fpr64(ctx, fp0, fd); tcg_temp_free_i64(fp0); } opn = "ldxc1"; break; case OPC_LUXC1: check_cp1_64bitmode(ctx); tcg_gen_andi_tl(t0, t0, ~0x7); { TCGv_i64 fp0 = tcg_temp_new_i64(); tcg_gen_qemu_ld64(fp0, t0, ctx->mem_idx); gen_store_fpr64(ctx, fp0, fd); tcg_temp_free_i64(fp0); } opn = "luxc1"; break; case OPC_SWXC1: check_cop1x(ctx); { TCGv_i32 fp0 = tcg_temp_new_i32(); TCGv t1 = tcg_temp_new(); gen_load_fpr32(fp0, fs); tcg_gen_extu_i32_tl(t1, fp0); tcg_gen_qemu_st32(t1, t0, ctx->mem_idx); tcg_temp_free_i32(fp0); tcg_temp_free_i32(t1); } opn = "swxc1"; store = 1; break; case OPC_SDXC1: check_cop1x(ctx); check_cp1_registers(ctx, fs); { TCGv_i64 fp0 = tcg_temp_new_i64(); gen_load_fpr64(ctx, fp0, fs); tcg_gen_qemu_st64(fp0, t0, ctx->mem_idx); tcg_temp_free_i64(fp0); } opn = "sdxc1"; store = 1; break; case OPC_SUXC1: check_cp1_64bitmode(ctx); tcg_gen_andi_tl(t0, t0, ~0x7); { TCGv_i64 fp0 = tcg_temp_new_i64(); gen_load_fpr64(ctx, fp0, fs); tcg_gen_qemu_st64(fp0, t0, ctx->mem_idx); tcg_temp_free_i64(fp0); } opn = "suxc1"; store = 1; break; } tcg_temp_free(t0); MIPS_DEBUG("%s %s, %s(%s)", opn, fregnames[store ? fs : fd], regnames[index], regnames[base]); }


static ioreq_t *cpu_get_ioreq(XenIOState *state) { int i; evtchn_port_t port; port = xc_evtchn_pending(state->xce_handle); if (port == state->bufioreq_local_port) { timer_mod(state->buffered_io_timer, BUFFER_IO_MAX_DELAY + qemu_clock_get_ms(QEMU_CLOCK_REALTIME)); return NULL; } if (port != -1) { for (i = 0; i < max_cpus; i++) { if (state->ioreq_local_port[i] == port) { break; } } if (i == max_cpus) { hw_error("Fatal error while trying to get io event!\n"); } /* unmask the wanted port again */ xc_evtchn_unmask(state->xce_handle, port); /* get the io packet from shared memory */ state->send_vcpu = i; return cpu_get_ioreq_from_shared_memory(state, i); } /* read error or read nothing */ return NULL; }


BlockDriverAIOCB *bdrv_aio_read(BlockDriverState *bs, int64_t sector_num, uint8_t *buf, int nb_sectors, BlockDriverCompletionFunc *cb, void *opaque) { BlockDriver *drv = bs->drv; BlockDriverAIOCB *ret; if (!drv) return NULL; /* XXX: we assume that nb_sectors == 0 is suppored by the async read */ if (sector_num == 0 && bs->boot_sector_enabled && nb_sectors > 0) { memcpy(buf, bs->boot_sector_data, 512); sector_num++; nb_sectors--; buf += 512; } ret = drv->bdrv_aio_read(bs, sector_num, buf, nb_sectors, cb, opaque); if (ret) { /* Update stats even though technically transfer has not happened. */ bs->rd_bytes += (unsigned) nb_sectors * SECTOR_SIZE; bs->rd_ops ++; } return ret; }


static void tcp_chr_tls_init(Chardev *chr) { SocketChardev *s = SOCKET_CHARDEV(chr); QIOChannelTLS *tioc; Error *err = NULL; gchar *name; if (s->is_listen) { tioc = qio_channel_tls_new_server( s->ioc, s->tls_creds, NULL, /* XXX Use an ACL */ &err); } else { tioc = qio_channel_tls_new_client( s->ioc, s->tls_creds, s->addr->u.inet.data->host, &err); } if (tioc == NULL) { error_free(err); tcp_chr_disconnect(chr); return; } name = g_strdup_printf("chardev-tls-%s-%s", s->is_listen ? "server" : "client", chr->label); qio_channel_set_name(QIO_CHANNEL(tioc), name); g_free(name); object_unref(OBJECT(s->ioc)); s->ioc = QIO_CHANNEL(tioc); qio_channel_tls_handshake(tioc, tcp_chr_tls_handshake, chr, NULL); }


static int aac_sync(uint64_t state, AACAC3ParseContext *hdr_info, int *need_next_header, int *new_frame_start) { GetBitContext bits; int size, rdb, ch, sr; union { uint64_t u64; uint8_t u8[8]; } tmp; tmp.u64 = be2me_64(state); init_get_bits(&bits, tmp.u8+8-AAC_HEADER_SIZE, AAC_HEADER_SIZE * 8); if(get_bits(&bits, 12) != 0xfff) return 0; skip_bits1(&bits); /* id */ skip_bits(&bits, 2); /* layer */ skip_bits1(&bits); /* protection_absent */ skip_bits(&bits, 2); /* profile_objecttype */ sr = get_bits(&bits, 4); /* sample_frequency_index */ if(!ff_mpeg4audio_sample_rates[sr]) return 0; skip_bits1(&bits); /* private_bit */ ch = get_bits(&bits, 3); /* channel_configuration */ if(!ff_mpeg4audio_channels[ch]) return 0; skip_bits1(&bits); /* original/copy */ skip_bits1(&bits); /* home */ /* adts_variable_header */ skip_bits1(&bits); /* copyright_identification_bit */ skip_bits1(&bits); /* copyright_identification_start */ size = get_bits(&bits, 13); /* aac_frame_length */ if(size < AAC_HEADER_SIZE) return 0; skip_bits(&bits, 11); /* adts_buffer_fullness */ rdb = get_bits(&bits, 2); /* number_of_raw_data_blocks_in_frame */ hdr_info->channels = ff_mpeg4audio_channels[ch]; hdr_info->sample_rate = ff_mpeg4audio_sample_rates[sr]; hdr_info->samples = (rdb + 1) * 1024; hdr_info->bit_rate = size * 8 * hdr_info->sample_rate / hdr_info->samples; *need_next_header = 0; *new_frame_start = 1; return size; }


static int local_post_create_passthrough(FsContext *fs_ctx, const char *path, FsCred *credp) { char buffer[PATH_MAX]; if (chmod(rpath(fs_ctx, path, buffer), credp->fc_mode & 07777) < 0) { return -1; } if (lchown(rpath(fs_ctx, path, buffer), credp->fc_uid, credp->fc_gid) < 0) { /* * If we fail to change ownership and if we are * using security model none. Ignore the error */ if ((fs_ctx->export_flags & V9FS_SEC_MASK) != V9FS_SM_NONE) { return -1; } } return 0; }


void vga_reset(void *opaque) { VGAState *s = (VGAState *) opaque; s->lfb_addr = 0; s->lfb_end = 0; s->map_addr = 0; s->map_end = 0; s->lfb_vram_mapped = 0; s->bios_offset = 0; s->bios_size = 0; s->sr_index = 0; memset(s->sr, '\0', sizeof(s->sr)); s->gr_index = 0; memset(s->gr, '\0', sizeof(s->gr)); s->ar_index = 0; memset(s->ar, '\0', sizeof(s->ar)); s->ar_flip_flop = 0; s->cr_index = 0; memset(s->cr, '\0', sizeof(s->cr)); s->msr = 0; s->fcr = 0; s->st00 = 0; s->st01 = 0; s->dac_state = 0; s->dac_sub_index = 0; s->dac_read_index = 0; s->dac_write_index = 0; memset(s->dac_cache, '\0', sizeof(s->dac_cache)); s->dac_8bit = 0; memset(s->palette, '\0', sizeof(s->palette)); s->bank_offset = 0; #ifdef CONFIG_BOCHS_VBE s->vbe_index = 0; memset(s->vbe_regs, '\0', sizeof(s->vbe_regs)); s->vbe_regs[VBE_DISPI_INDEX_ID] = VBE_DISPI_ID0; s->vbe_start_addr = 0; s->vbe_line_offset = 0; s->vbe_bank_mask = (s->vram_size >> 16) - 1; #endif memset(s->font_offsets, '\0', sizeof(s->font_offsets)); s->graphic_mode = -1; /* force full update */ s->shift_control = 0; s->double_scan = 0; s->line_offset = 0; s->line_compare = 0; s->start_addr = 0; s->plane_updated = 0; s->last_cw = 0; s->last_ch = 0; s->last_width = 0; s->last_height = 0; s->last_scr_width = 0; s->last_scr_height = 0; s->cursor_start = 0; s->cursor_end = 0; s->cursor_offset = 0; memset(s->invalidated_y_table, '\0', sizeof(s->invalidated_y_table)); memset(s->last_palette, '\0', sizeof(s->last_palette)); memset(s->last_ch_attr, '\0', sizeof(s->last_ch_attr)); switch (vga_retrace_method) { case VGA_RETRACE_DUMB: break; case VGA_RETRACE_PRECISE: memset(&s->retrace_info, 0, sizeof (s->retrace_info)); break; } }


void decode_mb_mode(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y, uint8_t *segment, uint8_t *ref, int layout, int is_vp7) { VP56RangeCoder *c = &s->c; static const char *vp7_feature_name[] = { "q-index", "lf-delta", "partial-golden-update", "blit-pitch" }; if (is_vp7) { int i; *segment = 0; for (i = 0; i < 4; i++) { if (s->feature_enabled[i]) { if (vp56_rac_get_prob_branchy(c, s->feature_present_prob[i])) { int index = vp8_rac_get_tree(c, vp7_feature_index_tree, s->feature_index_prob[i]); av_log(s->avctx, AV_LOG_WARNING, "Feature %s present in macroblock (value 0x%x)\n", vp7_feature_name[i], s->feature_value[i][index]); } } } } else if (s->segmentation.update_map) { int bit = vp56_rac_get_prob(c, s->prob->segmentid[0]); *segment = vp56_rac_get_prob(c, s->prob->segmentid[1+bit]) + 2*bit; } else if (s->segmentation.enabled) *segment = ref ? *ref : *segment; mb->segment = *segment; mb->skip = s->mbskip_enabled ? vp56_rac_get_prob(c, s->prob->mbskip) : 0; if (s->keyframe) { mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_intra, vp8_pred16x16_prob_intra); if (mb->mode == MODE_I4x4) { decode_intra4x4_modes(s, c, mb, mb_x, 1, layout); } else { const uint32_t modes = (is_vp7 ? vp7_pred4x4_mode : vp8_pred4x4_mode)[mb->mode] * 0x01010101u; if (s->mb_layout) AV_WN32A(mb->intra4x4_pred_mode_top, modes); else AV_WN32A(s->intra4x4_pred_mode_top + 4 * mb_x, modes); AV_WN32A(s->intra4x4_pred_mode_left, modes); } mb->chroma_pred_mode = vp8_rac_get_tree(c, vp8_pred8x8c_tree, vp8_pred8x8c_prob_intra); mb->ref_frame = VP56_FRAME_CURRENT; } else if (vp56_rac_get_prob_branchy(c, s->prob->intra)) { // inter MB, 16.2 if (vp56_rac_get_prob_branchy(c, s->prob->last)) mb->ref_frame = (!is_vp7 && vp56_rac_get_prob(c, s->prob->golden)) ? VP56_FRAME_GOLDEN2 /* altref */ : VP56_FRAME_GOLDEN; else mb->ref_frame = VP56_FRAME_PREVIOUS; s->ref_count[mb->ref_frame - 1]++; // motion vectors, 16.3 if (is_vp7) vp7_decode_mvs(s, mb, mb_x, mb_y, layout); else vp8_decode_mvs(s, mb, mb_x, mb_y, layout); } else { // intra MB, 16.1 mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_inter, s->prob->pred16x16); if (mb->mode == MODE_I4x4) decode_intra4x4_modes(s, c, mb, mb_x, 0, layout); mb->chroma_pred_mode = vp8_rac_get_tree(c, vp8_pred8x8c_tree, s->prob->pred8x8c); mb->ref_frame = VP56_FRAME_CURRENT; mb->partitioning = VP8_SPLITMVMODE_NONE; AV_ZERO32(&mb->bmv[0]); } }


static void asfrtp_close_context(PayloadContext *asf) { ffio_free_dyn_buf(&asf->pktbuf); av_freep(&asf->buf); av_free(asf); }


static av_cold int dilate_init(AVFilterContext *ctx, const char *args) { OCVContext *ocv = ctx->priv; DilateContext *dilate = ocv->priv; char default_kernel_str[] = "3x3+0x0/rect"; char *kernel_str; const char *buf = args; int ret; dilate->nb_iterations = 1; if (args) kernel_str = av_get_token(&buf, "|"); if ((ret = parse_iplconvkernel(&dilate->kernel, *kernel_str ? kernel_str : default_kernel_str, ctx)) < 0) return ret; av_free(kernel_str); sscanf(buf, "|%d", &dilate->nb_iterations); av_log(ctx, AV_LOG_VERBOSE, "iterations_nb:%d\n", dilate->nb_iterations); if (dilate->nb_iterations <= 0) { av_log(ctx, AV_LOG_ERROR, "Invalid non-positive value '%d' for nb_iterations\n", dilate->nb_iterations); return AVERROR(EINVAL); } return 0; }


BlockDriverState *bdrv_new(void) { BlockDriverState *bs; int i; bs = g_new0(BlockDriverState, 1); QLIST_INIT(&bs->dirty_bitmaps); for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { QLIST_INIT(&bs->op_blockers[i]); } notifier_with_return_list_init(&bs->before_write_notifiers); bs->refcnt = 1; bs->aio_context = qemu_get_aio_context(); QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list); return bs; }


static inline void RENAME(bgr32ToUV)(uint8_t *dstU, uint8_t *dstV, uint8_t *src1, uint8_t *src2, int width) { int i; assert(src1 == src2); for(i=0; i<width; i++) { const int a= ((uint32_t*)src1)[2*i+0]; const int e= ((uint32_t*)src1)[2*i+1]; const int l= (a&0xFF00FF) + (e&0xFF00FF); const int h= (a&0x00FF00) + (e&0x00FF00); const int b= l&0x3FF; const int g= h>>8; const int r= l>>16; dstU[i]= ((RU*r + GU*g + BU*b)>>(RGB2YUV_SHIFT+1)) + 128; dstV[i]= ((RV*r + GV*g + BV*b)>>(RGB2YUV_SHIFT+1)) + 128; } }


static int qemu_rdma_init_ram_blocks(RDMAContext *rdma) { RDMALocalBlocks *local = &rdma->local_ram_blocks; assert(rdma->blockmap == NULL); rdma->blockmap = g_hash_table_new(g_direct_hash, g_direct_equal); memset(local, 0, sizeof *local); qemu_ram_foreach_block(qemu_rdma_init_one_block, rdma); DPRINTF("Allocated %d local ram block structures\n", local->nb_blocks); rdma->block = (RDMARemoteBlock *) g_malloc0(sizeof(RDMARemoteBlock) * rdma->local_ram_blocks.nb_blocks); local->init = true; return 0; }


static always_inline void gen_op_subfeo (void) { gen_op_move_T2_T0(); gen_op_subfe(); gen_op_check_subfo(); }


void commit_start(BlockDriverState *bs, BlockDriverState *base, BlockDriverState *top, int64_t speed, BlockdevOnError on_error, BlockDriverCompletionFunc *cb, void *opaque, Error **errp) { CommitBlockJob *s; BlockReopenQueue *reopen_queue = NULL; int orig_overlay_flags; int orig_base_flags; BlockDriverState *overlay_bs; Error *local_err = NULL; if ((on_error == BLOCKDEV_ON_ERROR_STOP || on_error == BLOCKDEV_ON_ERROR_ENOSPC) && !bdrv_iostatus_is_enabled(bs)) { error_set(errp, QERR_INVALID_PARAMETER_COMBINATION); return; } /* Once we support top == active layer, remove this check */ if (top == bs) { error_setg(errp, "Top image as the active layer is currently unsupported"); return; } if (top == base) { error_setg(errp, "Invalid files for merge: top and base are the same"); return; } /* top and base may be valid, but let's make sure that base is reachable * from top */ if (bdrv_find_backing_image(top, base->filename) != base) { error_setg(errp, "Base (%s) is not reachable from top (%s)", base->filename, top->filename); return; } overlay_bs = bdrv_find_overlay(bs, top); if (overlay_bs == NULL) { error_setg(errp, "Could not find overlay image for %s:", top->filename); return; } orig_base_flags = bdrv_get_flags(base); orig_overlay_flags = bdrv_get_flags(overlay_bs); /* convert base & overlay_bs to r/w, if necessary */ if (!(orig_base_flags & BDRV_O_RDWR)) { reopen_queue = bdrv_reopen_queue(reopen_queue, base, orig_base_flags | BDRV_O_RDWR); } if (!(orig_overlay_flags & BDRV_O_RDWR)) { reopen_queue = bdrv_reopen_queue(reopen_queue, overlay_bs, orig_overlay_flags | BDRV_O_RDWR); } if (reopen_queue) { bdrv_reopen_multiple(reopen_queue, &local_err); if (local_err != NULL) { error_propagate(errp, local_err); return; } } s = block_job_create(&commit_job_type, bs, speed, cb, opaque, errp); if (!s) { return; } s->base = base; s->top = top; s->active = bs; s->base_flags = orig_base_flags; s->orig_overlay_flags = orig_overlay_flags; s->on_error = on_error; s->common.co = qemu_coroutine_create(commit_run); trace_commit_start(bs, base, top, s, s->common.co, opaque); qemu_coroutine_enter(s->common.co, s); }


static void check_guest_output(const testdef_t *test, int fd) { bool output_ok = false; int i, nbr, pos = 0; char ch; /* Poll serial output... Wait at most 60 seconds */ for (i = 0; i < 6000; ++i) { while ((nbr = read(fd, &ch, 1)) == 1) { if (ch == test->expect[pos]) { pos += 1; if (test->expect[pos] == '\0') { /* We've reached the end of the expected string! */ output_ok = true; goto done; } } else { pos = 0; } } g_assert(nbr >= 0); g_usleep(10000); } done: g_assert(output_ok); }


static void do_subtitle_out(AVFormatContext *s, AVOutputStream *ost, AVInputStream *ist, AVSubtitle *sub, int64_t pts) { static uint8_t *subtitle_out = NULL; int subtitle_out_max_size = 65536; int subtitle_out_size, nb, i; AVCodecContext *enc; AVPacket pkt; if (pts == AV_NOPTS_VALUE) { fprintf(stderr, "Subtitle packets must have a pts\n"); if (exit_on_error) return; enc = ost->st->codec; if (!subtitle_out) { subtitle_out = av_malloc(subtitle_out_max_size); /* Note: DVB subtitle need one packet to draw them and one other packet to clear them */ /* XXX: signal it in the codec context ? */ if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) nb = 2; else nb = 1; for(i = 0; i < nb; i++) { sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q); subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out, subtitle_out_max_size, sub); av_init_packet(&pkt); pkt.stream_index = ost->index; pkt.data = subtitle_out; pkt.size = subtitle_out_size; pkt.pts = av_rescale_q(pts, ist->st->time_base, ost->st->time_base); if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) { /* XXX: the pts correction is handled here. Maybe handling it in the codec would be better */ if (i == 0) pkt.pts += 90 * sub->start_display_time; else pkt.pts += 90 * sub->end_display_time; write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);


static int handle_sw_breakpoint(S390CPU *cpu, struct kvm_run *run) { CPUS390XState *env = &cpu->env; unsigned long pc; cpu_synchronize_state(CPU(cpu)); pc = env->psw.addr - 4; if (kvm_find_sw_breakpoint(CPU(cpu), pc)) { env->psw.addr = pc; return EXCP_DEBUG; } return -ENOENT; }


static void vhost_dev_sync_region(struct vhost_dev *dev, MemoryRegionSection *section, uint64_t mfirst, uint64_t mlast, uint64_t rfirst, uint64_t rlast) { uint64_t start = MAX(mfirst, rfirst); uint64_t end = MIN(mlast, rlast); vhost_log_chunk_t *from = dev->log + start / VHOST_LOG_CHUNK; vhost_log_chunk_t *to = dev->log + end / VHOST_LOG_CHUNK + 1; uint64_t addr = (start / VHOST_LOG_CHUNK) * VHOST_LOG_CHUNK; if (end < start) { return; } assert(end / VHOST_LOG_CHUNK < dev->log_size); assert(start / VHOST_LOG_CHUNK < dev->log_size); for (;from < to; ++from) { vhost_log_chunk_t log; int bit; /* We first check with non-atomic: much cheaper, * and we expect non-dirty to be the common case. */ if (!*from) { addr += VHOST_LOG_CHUNK; continue; } /* Data must be read atomically. We don't really * need the barrier semantics of __sync * builtins, but it's easier to use them than * roll our own. */ log = __sync_fetch_and_and(from, 0); while ((bit = sizeof(log) > sizeof(int) ? ffsll(log) : ffs(log))) { ram_addr_t ram_addr; bit -= 1; ram_addr = section->offset_within_region + bit * VHOST_LOG_PAGE; memory_region_set_dirty(section->mr, ram_addr, VHOST_LOG_PAGE); log &= ~(0x1ull << bit); } addr += VHOST_LOG_CHUNK; } }


int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset, int count) { NBDClientSession *client = nbd_get_client_session(bs); NBDRequest request = { .type = NBD_CMD_TRIM, .from = offset, .len = count, }; NBDReply reply; ssize_t ret; if (!(client->nbdflags & NBD_FLAG_SEND_TRIM)) { return 0; } nbd_coroutine_start(client, &request); ret = nbd_co_send_request(bs, &request, NULL); if (ret < 0) { reply.error = -ret; } else { nbd_co_receive_reply(client, &request, &reply, NULL); } nbd_coroutine_end(bs, &request); return -reply.error; }


int qcow2_check_refcounts(BlockDriverState *bs) { BDRVQcowState *s = bs->opaque; int64_t size; int nb_clusters, refcount1, refcount2, i; QCowSnapshot *sn; uint16_t *refcount_table; int ret, errors = 0; size = bdrv_getlength(bs->file); nb_clusters = size_to_clusters(s, size); refcount_table = qemu_mallocz(nb_clusters * sizeof(uint16_t)); /* header */ errors += inc_refcounts(bs, refcount_table, nb_clusters, 0, s->cluster_size); /* current L1 table */ ret = check_refcounts_l1(bs, refcount_table, nb_clusters, s->l1_table_offset, s->l1_size, 1); if (ret < 0) { return ret; } errors += ret; /* snapshots */ for(i = 0; i < s->nb_snapshots; i++) { sn = s->snapshots + i; check_refcounts_l1(bs, refcount_table, nb_clusters, sn->l1_table_offset, sn->l1_size, 0); } errors += inc_refcounts(bs, refcount_table, nb_clusters, s->snapshots_offset, s->snapshots_size); /* refcount data */ errors += inc_refcounts(bs, refcount_table, nb_clusters, s->refcount_table_offset, s->refcount_table_size * sizeof(uint64_t)); for(i = 0; i < s->refcount_table_size; i++) { int64_t offset; offset = s->refcount_table[i]; /* Refcount blocks are cluster aligned */ if (offset & (s->cluster_size - 1)) { fprintf(stderr, "ERROR refcount block %d is not " "cluster aligned; refcount table entry corrupted\n", i); errors++; } if (offset != 0) { errors += inc_refcounts(bs, refcount_table, nb_clusters, offset, s->cluster_size); if (refcount_table[offset / s->cluster_size] != 1) { fprintf(stderr, "ERROR refcount block %d refcount=%d\n", i, refcount_table[offset / s->cluster_size]); } } } /* compare ref counts */ for(i = 0; i < nb_clusters; i++) { refcount1 = get_refcount(bs, i); if (refcount1 < 0) { fprintf(stderr, "Can't get refcount for cluster %d: %s\n", i, strerror(-refcount1)); } refcount2 = refcount_table[i]; if (refcount1 != refcount2) { fprintf(stderr, "ERROR cluster %d refcount=%d reference=%d\n", i, refcount1, refcount2); errors++; } } qemu_free(refcount_table); return errors; }


static int caf_write_trailer(AVFormatContext *s) { AVIOContext *pb = s->pb; AVCodecContext *enc = s->streams[0]->codec; if (pb->seekable) { CAFContext *caf = s->priv_data; int64_t file_size = avio_tell(pb); avio_seek(pb, caf->data, SEEK_SET); avio_wb64(pb, file_size - caf->data - 8); avio_seek(pb, file_size, SEEK_SET); if (!enc->block_align) { ffio_wfourcc(pb, "pakt"); avio_wb64(pb, caf->size_entries_used + 24); avio_wb64(pb, caf->packets); ///< mNumberPackets avio_wb64(pb, caf->packets * samples_per_packet(enc->codec_id, enc->channels)); ///< mNumberValidFrames avio_wb32(pb, 0); ///< mPrimingFrames avio_wb32(pb, 0); ///< mRemainderFrames avio_write(pb, caf->pkt_sizes, caf->size_entries_used); av_freep(&caf->pkt_sizes); caf->size_buffer_size = 0; } avio_flush(pb); } return 0; }


static void init_proc_970GX (CPUPPCState *env) { gen_spr_ne_601(env); gen_spr_7xx(env); /* Time base */ gen_tbl(env); /* Hardware implementation registers */ /* XXX : not implemented */ spr_register(env, SPR_HID0, "HID0", SPR_NOACCESS, SPR_NOACCESS, &spr_read_generic, &spr_write_clear, 0x60000000); /* XXX : not implemented */ spr_register(env, SPR_HID1, "HID1", SPR_NOACCESS, SPR_NOACCESS, &spr_read_generic, &spr_write_generic, 0x00000000); /* XXX : not implemented */ spr_register(env, SPR_750_HID2, "HID2", SPR_NOACCESS, SPR_NOACCESS, &spr_read_generic, &spr_write_generic, 0x00000000); /* XXX : not implemented */ spr_register(env, SPR_970_HID5, "HID5", SPR_NOACCESS, SPR_NOACCESS, &spr_read_generic, &spr_write_generic, #if defined(CONFIG_USER_ONLY) 0x00000080 #else 0x00000000 #endif ); /* Memory management */ /* XXX: not correct */ gen_low_BATs(env); #if 0 // TODO env->slb_nr = 32; #endif init_excp_970(env); env->dcache_line_size = 128; env->icache_line_size = 128; /* Allocate hardware IRQ controller */ ppc970_irq_init(env); }


static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end) { const uint8_t *buf_ptr; unsigned int v, v2; int val; int skipped = 0; buf_ptr = *pbuf_ptr; while (buf_ptr < buf_end) { v = *buf_ptr++; v2 = *buf_ptr; if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) { val = *buf_ptr++; goto found; } skipped++; } val = -1; found: av_dlog(NULL, "find_marker skipped %d bytes\n", skipped); *pbuf_ptr = buf_ptr; return val; }


static int cavs_decode_frame(AVCodecContext * avctx,void *data, int *data_size, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; AVSContext *h = avctx->priv_data; MpegEncContext *s = &h->s; int input_size; const uint8_t *buf_end; const uint8_t *buf_ptr; AVFrame *picture = data; uint32_t stc = -1; s->avctx = avctx; if (buf_size == 0) { if (!s->low_delay && h->DPB[0].f.data[0]) { *data_size = sizeof(AVPicture); *picture = *(AVFrame *) &h->DPB[0]; } return 0; } buf_ptr = buf; buf_end = buf + buf_size; for(;;) { buf_ptr = ff_find_start_code(buf_ptr,buf_end, &stc); if(stc & 0xFFFFFE00) return FFMAX(0, buf_ptr - buf - s->parse_context.last_index); input_size = (buf_end - buf_ptr)*8; switch(stc) { case CAVS_START_CODE: init_get_bits(&s->gb, buf_ptr, input_size); decode_seq_header(h); break; case PIC_I_START_CODE: if(!h->got_keyframe) { if(h->DPB[0].f.data[0]) avctx->release_buffer(avctx, (AVFrame *)&h->DPB[0]); if(h->DPB[1].f.data[0]) avctx->release_buffer(avctx, (AVFrame *)&h->DPB[1]); h->got_keyframe = 1; } case PIC_PB_START_CODE: *data_size = 0; if(!h->got_keyframe) break; init_get_bits(&s->gb, buf_ptr, input_size); h->stc = stc; if(decode_pic(h)) break; *data_size = sizeof(AVPicture); if(h->pic_type != AV_PICTURE_TYPE_B) { if(h->DPB[1].f.data[0]) { *picture = *(AVFrame *) &h->DPB[1]; } else { *data_size = 0; } } else *picture = *(AVFrame *) &h->picture; break; case EXT_START_CODE: //mpeg_decode_extension(avctx,buf_ptr, input_size); break; case USER_START_CODE: //mpeg_decode_user_data(avctx,buf_ptr, input_size); break; default: if (stc <= SLICE_MAX_START_CODE) { init_get_bits(&s->gb, buf_ptr, input_size); decode_slice_header(h, &s->gb); } break; } } }


static int get_pci_config_device(QEMUFile *f, void *pv, size_t size) { PCIDevice *s = container_of(pv, PCIDevice, config); uint8_t config[size]; int i; qemu_get_buffer(f, config, size); for (i = 0; i < size; ++i) if ((config[i] ^ s->config[i]) & s->cmask[i] & ~s->wmask[i]) return -EINVAL; memcpy(s->config, config, size); pci_update_mappings(s); return 0; }


static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples) { #if HAVE_BIGENDIAN int i; for (i = 0; i < s->frame.blocksize * s->channels; i++) { int16_t smp = av_le2ne16(samples[i]); av_md5_update(s->md5ctx, (uint8_t *)&smp, 2); } #else av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2); #endif }


static int cuvid_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { CuvidContext *ctx = avctx->priv_data; AVHWDeviceContext *device_ctx = (AVHWDeviceContext*)ctx->hwdevice->data; AVCUDADeviceContext *device_hwctx = device_ctx->hwctx; CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx; AVFrame *frame = data; CUVIDSOURCEDATAPACKET cupkt; AVPacket filter_packet = { 0 }; AVPacket filtered_packet = { 0 }; CUdeviceptr mapped_frame = 0; int ret = 0, eret = 0; if (ctx->bsf && avpkt->size) { if ((ret = av_packet_ref(&filter_packet, avpkt)) < 0) { av_log(avctx, AV_LOG_ERROR, "av_packet_ref failed\n"); return ret; } if ((ret = av_bsf_send_packet(ctx->bsf, &filter_packet)) < 0) { av_log(avctx, AV_LOG_ERROR, "av_bsf_send_packet failed\n"); av_packet_unref(&filter_packet); return ret; } if ((ret = av_bsf_receive_packet(ctx->bsf, &filtered_packet)) < 0) { av_log(avctx, AV_LOG_ERROR, "av_bsf_receive_packet failed\n"); return ret; } avpkt = &filtered_packet; } ret = CHECK_CU(cuCtxPushCurrent(cuda_ctx)); if (ret < 0) { av_packet_unref(&filtered_packet); return ret; } memset(&cupkt, 0, sizeof(cupkt)); if (avpkt->size) { cupkt.payload_size = avpkt->size; cupkt.payload = avpkt->data; if (avpkt->pts != AV_NOPTS_VALUE) { cupkt.flags = CUVID_PKT_TIMESTAMP; cupkt.timestamp = av_rescale_q(avpkt->pts, avctx->pkt_timebase, (AVRational){1, 10000000}); } } else { cupkt.flags = CUVID_PKT_ENDOFSTREAM; } ret = CHECK_CU(cuvidParseVideoData(ctx->cuparser, &cupkt)); av_packet_unref(&filtered_packet); if (ret < 0) { if (ctx->internal_error) ret = ctx->internal_error; goto error; } if (av_fifo_size(ctx->frame_queue)) { CUVIDPARSERDISPINFO dispinfo; CUVIDPROCPARAMS params; unsigned int pitch = 0; int offset = 0; int i; av_fifo_generic_read(ctx->frame_queue, &dispinfo, sizeof(CUVIDPARSERDISPINFO), NULL); memset(&params, 0, sizeof(params)); params.progressive_frame = dispinfo.progressive_frame; params.second_field = 0; params.top_field_first = dispinfo.top_field_first; ret = CHECK_CU(cuvidMapVideoFrame(ctx->cudecoder, dispinfo.picture_index, &mapped_frame, &pitch, &params)); if (ret < 0) goto error; if (avctx->pix_fmt == AV_PIX_FMT_CUDA) { ret = av_hwframe_get_buffer(ctx->hwframe, frame, 0); if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "av_hwframe_get_buffer failed\n"); goto error; } ret = ff_decode_frame_props(avctx, frame); if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "ff_decode_frame_props failed\n"); goto error; } for (i = 0; i < 2; i++) { CUDA_MEMCPY2D cpy = { .srcMemoryType = CU_MEMORYTYPE_DEVICE, .dstMemoryType = CU_MEMORYTYPE_DEVICE, .srcDevice = mapped_frame, .dstDevice = (CUdeviceptr)frame->data[i], .srcPitch = pitch, .dstPitch = frame->linesize[i], .srcY = offset, .WidthInBytes = FFMIN(pitch, frame->linesize[i]), .Height = avctx->coded_height >> (i ? 1 : 0), }; ret = CHECK_CU(cuMemcpy2D(&cpy)); if (ret < 0) goto error; offset += avctx->coded_height; } } else if (avctx->pix_fmt == AV_PIX_FMT_NV12) { AVFrame *tmp_frame = av_frame_alloc(); if (!tmp_frame) { av_log(avctx, AV_LOG_ERROR, "av_frame_alloc failed\n"); ret = AVERROR(ENOMEM); goto error; } tmp_frame->format = AV_PIX_FMT_CUDA; tmp_frame->hw_frames_ctx = av_buffer_ref(ctx->hwframe); tmp_frame->data[0] = (uint8_t*)mapped_frame; tmp_frame->linesize[0] = pitch; tmp_frame->data[1] = (uint8_t*)(mapped_frame + avctx->coded_height * pitch); tmp_frame->linesize[1] = pitch; tmp_frame->width = avctx->width; tmp_frame->height = avctx->height; ret = ff_get_buffer(avctx, frame, 0); if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "ff_get_buffer failed\n"); av_frame_free(&tmp_frame); goto error; } ret = av_hwframe_transfer_data(frame, tmp_frame, 0); if (ret) { av_log(avctx, AV_LOG_ERROR, "av_hwframe_transfer_data failed\n"); av_frame_free(&tmp_frame); goto error; } av_frame_free(&tmp_frame); } else { ret = AVERROR_BUG; goto error; } frame->width = avctx->width; frame->height = avctx->height; frame->pts = av_rescale_q(dispinfo.timestamp, (AVRational){1, 10000000}, avctx->pkt_timebase); /* CUVIDs opaque reordering breaks the internal pkt logic. * So set pkt_pts and clear all the other pkt_ fields. */ frame->pkt_pts = frame->pts; av_frame_set_pkt_pos(frame, -1); av_frame_set_pkt_duration(frame, 0); av_frame_set_pkt_size(frame, -1); frame->interlaced_frame = !dispinfo.progressive_frame; if (!dispinfo.progressive_frame) frame->top_field_first = dispinfo.top_field_first; *got_frame = 1; } else { *got_frame = 0; } error: if (mapped_frame) eret = CHECK_CU(cuvidUnmapVideoFrame(ctx->cudecoder, mapped_frame)); eret = CHECK_CU(cuCtxPopCurrent(&dummy)); if (eret < 0) return eret; else return ret; }


static void intra_predict_mad_cow_dc_0lt_8x8_msa(uint8_t *src, int32_t stride) { uint8_t lp_cnt; uint32_t src0, src1, src2 = 0, src3; uint32_t out0, out1, out2, out3; v16u8 src_top; v8u16 add; v4u32 sum; src_top = LD_UB(src - stride); add = __msa_hadd_u_h(src_top, src_top); sum = __msa_hadd_u_w(add, add); src0 = __msa_copy_u_w((v4i32) sum, 0); src1 = __msa_copy_u_w((v4i32) sum, 1); for (lp_cnt = 0; lp_cnt < 4; lp_cnt++) { src2 += src[(4 + lp_cnt) * stride - 1]; } src0 = (src0 + 2) >> 2; src3 = (src1 + src2 + 4) >> 3; src1 = (src1 + 2) >> 2; src2 = (src2 + 2) >> 2; out0 = src0 * 0x01010101; out1 = src1 * 0x01010101; out2 = src2 * 0x01010101; out3 = src3 * 0x01010101; for (lp_cnt = 4; lp_cnt--;) { SW(out0, src); SW(out1, src + 4); SW(out2, src + stride * 4); SW(out3, src + stride * 4 + 4); src += stride; } }


static int img_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { VideoDemuxData *s1 = s->priv_data; if (timestamp < 0 || timestamp > s1->img_last - s1->img_first) return -1; s1->img_number = timestamp + s1->img_first; return 0; }


static int read_filter_params(MLPDecodeContext *m, GetBitContext *gbp, unsigned int channel, unsigned int filter) { FilterParams *fp = &m->channel_params[channel].filter_params[filter]; const int max_order = filter ? MAX_IIR_ORDER : MAX_FIR_ORDER; const char fchar = filter ? 'I' : 'F'; int i, order; // Filter is 0 for FIR, 1 for IIR. assert(filter < 2); m->filter_changed[channel][filter]++; order = get_bits(gbp, 4); if (order > max_order) { av_log(m->avctx, AV_LOG_ERROR, "%cIR filter order %d is greater than maximum %d.\n", fchar, order, max_order); return -1; } fp->order = order; if (order > 0) { int coeff_bits, coeff_shift; fp->shift = get_bits(gbp, 4); coeff_bits = get_bits(gbp, 5); coeff_shift = get_bits(gbp, 3); if (coeff_bits < 1 || coeff_bits > 16) { av_log(m->avctx, AV_LOG_ERROR, "%cIR filter coeff_bits must be between 1 and 16.\n", fchar); return -1; } if (coeff_bits + coeff_shift > 16) { av_log(m->avctx, AV_LOG_ERROR, "Sum of coeff_bits and coeff_shift for %cIR filter must be 16 or less.\n", fchar); return -1; } for (i = 0; i < order; i++) fp->coeff[i] = get_sbits(gbp, coeff_bits) << coeff_shift; if (get_bits1(gbp)) { int state_bits, state_shift; if (filter == FIR) { av_log(m->avctx, AV_LOG_ERROR, "FIR filter has state data specified.\n"); return -1; } state_bits = get_bits(gbp, 4); state_shift = get_bits(gbp, 4); /* TODO: Check validity of state data. */ for (i = 0; i < order; i++) fp->state[i] = get_sbits(gbp, state_bits) << state_shift; } } return 0; }


static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int size; int32_t yaw, pitch, roll; size_t l = 0, t = 0, r = 0, b = 0; size_t padding = 0; uint32_t tag; enum AVSphericalProjection projection; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; if (atom.size < 8) { av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n"); return AVERROR_INVALIDDATA; } size = avio_rb32(pb); if (size <= 12 || size > atom.size) return AVERROR_INVALIDDATA; tag = avio_rl32(pb); if (tag != MKTAG('s','v','h','d')) { av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n"); return 0; } avio_skip(pb, 4); /* version + flags */ avio_skip(pb, size - 12); /* metadata_source */ size = avio_rb32(pb); if (size > atom.size) return AVERROR_INVALIDDATA; tag = avio_rl32(pb); if (tag != MKTAG('p','r','o','j')) { av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n"); return 0; } size = avio_rb32(pb); if (size > atom.size) return AVERROR_INVALIDDATA; tag = avio_rl32(pb); if (tag != MKTAG('p','r','h','d')) { av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n"); return 0; } avio_skip(pb, 4); /* version + flags */ /* 16.16 fixed point */ yaw = avio_rb32(pb); pitch = avio_rb32(pb); roll = avio_rb32(pb); size = avio_rb32(pb); if (size > atom.size) return AVERROR_INVALIDDATA; tag = avio_rl32(pb); avio_skip(pb, 4); /* version + flags */ switch (tag) { case MKTAG('c','b','m','p'): projection = AV_SPHERICAL_CUBEMAP; padding = avio_rb32(pb); break; case MKTAG('e','q','u','i'): t = avio_rb32(pb); b = avio_rb32(pb); l = avio_rb32(pb); r = avio_rb32(pb); if (b >= UINT_MAX - t || r >= UINT_MAX - l) { av_log(c->fc, AV_LOG_ERROR, "Invalid bounding rectangle coordinates %"SIZE_SPECIFIER"," "%"SIZE_SPECIFIER",%"SIZE_SPECIFIER",%"SIZE_SPECIFIER"\n", l, t, r, b); return AVERROR_INVALIDDATA; } if (l || t || r || b) projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE; else projection = AV_SPHERICAL_EQUIRECTANGULAR; break; default: av_log(c->fc, AV_LOG_ERROR, "Unknown projection type\n"); return 0; } sc->spherical = av_spherical_alloc(&sc->spherical_size); if (!sc->spherical) return AVERROR(ENOMEM); sc->spherical->projection = projection; sc->spherical->yaw = yaw; sc->spherical->pitch = pitch; sc->spherical->roll = roll; sc->spherical->padding = padding; sc->spherical->bound_left = l; sc->spherical->bound_top = t; sc->spherical->bound_right = r; sc->spherical->bound_bottom = b; return 0; }


struct tm *brktimegm(time_t secs, struct tm *tm) { int days, y, ny, m; int md[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; days = secs / 86400; secs %= 86400; tm->tm_hour = secs / 3600; tm->tm_min = (secs % 3600) / 60; tm->tm_sec = secs % 60; /* oh well, may be someone some day will invent a formula for this stuff */ y = 1970; /* start "guessing" */ while (days >= (ISLEAP(y)?366:365)) { ny = (y + days/366); days -= (ny - y) * 365 + LEAPS_COUNT(ny - 1) - LEAPS_COUNT(y - 1); y = ny; } md[1] = ISLEAP(y)?29:28; for (m=0; days >= md[m]; m++) days -= md[m]; tm->tm_year = y; /* unlike gmtime_r we store complete year here */ tm->tm_mon = m+1; /* unlike gmtime_r tm_mon is from 1 to 12 */ tm->tm_mday = days+1; return tm; }


static int dnxhd_decode_macroblock(const DNXHDContext *ctx, RowContext *row, AVFrame *frame, int x, int y) { int shift1 = ctx->bit_depth >= 10; int dct_linesize_luma = frame->linesize[0]; int dct_linesize_chroma = frame->linesize[1]; uint8_t *dest_y, *dest_u, *dest_v; int dct_y_offset, dct_x_offset; int qscale, i, act; int interlaced_mb = 0; if (ctx->mbaff) { interlaced_mb = get_bits1(&row->gb); qscale = get_bits(&row->gb, 10); } else { qscale = get_bits(&row->gb, 11); } act = get_bits1(&row->gb); if (act) { static int warned = 0; if (!warned) { warned = 1; av_log(ctx->avctx, AV_LOG_ERROR, "Unsupported adaptive color transform, patch welcome.\n"); } } if (qscale != row->last_qscale) { for (i = 0; i < 64; i++) { row->luma_scale[i] = qscale * ctx->cid_table->luma_weight[i]; row->chroma_scale[i] = qscale * ctx->cid_table->chroma_weight[i]; } row->last_qscale = qscale; } for (i = 0; i < 8 + 4 * ctx->is_444; i++) { if (ctx->decode_dct_block(ctx, row, i) < 0) return AVERROR_INVALIDDATA; } if (frame->interlaced_frame) { dct_linesize_luma <<= 1; dct_linesize_chroma <<= 1; } dest_y = frame->data[0] + ((y * dct_linesize_luma) << 4) + (x << (4 + shift1)); dest_u = frame->data[1] + ((y * dct_linesize_chroma) << 4) + (x << (3 + shift1 + ctx->is_444)); dest_v = frame->data[2] + ((y * dct_linesize_chroma) << 4) + (x << (3 + shift1 + ctx->is_444)); if (frame->interlaced_frame && ctx->cur_field) { dest_y += frame->linesize[0]; dest_u += frame->linesize[1]; dest_v += frame->linesize[2]; } if (interlaced_mb) { dct_linesize_luma <<= 1; dct_linesize_chroma <<= 1; } dct_y_offset = interlaced_mb ? frame->linesize[0] : (dct_linesize_luma << 3); dct_x_offset = 8 << shift1; if (!ctx->is_444) { ctx->idsp.idct_put(dest_y, dct_linesize_luma, row->blocks[0]); ctx->idsp.idct_put(dest_y + dct_x_offset, dct_linesize_luma, row->blocks[1]); ctx->idsp.idct_put(dest_y + dct_y_offset, dct_linesize_luma, row->blocks[4]); ctx->idsp.idct_put(dest_y + dct_y_offset + dct_x_offset, dct_linesize_luma, row->blocks[5]); if (!(ctx->avctx->flags & AV_CODEC_FLAG_GRAY)) { dct_y_offset = interlaced_mb ? frame->linesize[1] : (dct_linesize_chroma << 3); ctx->idsp.idct_put(dest_u, dct_linesize_chroma, row->blocks[2]); ctx->idsp.idct_put(dest_v, dct_linesize_chroma, row->blocks[3]); ctx->idsp.idct_put(dest_u + dct_y_offset, dct_linesize_chroma, row->blocks[6]); ctx->idsp.idct_put(dest_v + dct_y_offset, dct_linesize_chroma, row->blocks[7]); } } else { ctx->idsp.idct_put(dest_y, dct_linesize_luma, row->blocks[0]); ctx->idsp.idct_put(dest_y + dct_x_offset, dct_linesize_luma, row->blocks[1]); ctx->idsp.idct_put(dest_y + dct_y_offset, dct_linesize_luma, row->blocks[6]); ctx->idsp.idct_put(dest_y + dct_y_offset + dct_x_offset, dct_linesize_luma, row->blocks[7]); if (!(ctx->avctx->flags & AV_CODEC_FLAG_GRAY)) { dct_y_offset = interlaced_mb ? frame->linesize[1] : (dct_linesize_chroma << 3); ctx->idsp.idct_put(dest_u, dct_linesize_chroma, row->blocks[2]); ctx->idsp.idct_put(dest_u + dct_x_offset, dct_linesize_chroma, row->blocks[3]); ctx->idsp.idct_put(dest_u + dct_y_offset, dct_linesize_chroma, row->blocks[8]); ctx->idsp.idct_put(dest_u + dct_y_offset + dct_x_offset, dct_linesize_chroma, row->blocks[9]); ctx->idsp.idct_put(dest_v, dct_linesize_chroma, row->blocks[4]); ctx->idsp.idct_put(dest_v + dct_x_offset, dct_linesize_chroma, row->blocks[5]); ctx->idsp.idct_put(dest_v + dct_y_offset, dct_linesize_chroma, row->blocks[10]); ctx->idsp.idct_put(dest_v + dct_y_offset + dct_x_offset, dct_linesize_chroma, row->blocks[11]); } } return 0; }


static int get_audio_flags(AVCodecContext *enc){ int flags = (enc->bits_per_coded_sample == 16) ? FLV_SAMPLESSIZE_16BIT : FLV_SAMPLESSIZE_8BIT; if (enc->codec_id == CODEC_ID_AAC) // specs force these parameters return FLV_CODECID_AAC | FLV_SAMPLERATE_44100HZ | FLV_SAMPLESSIZE_16BIT | FLV_STEREO; else if (enc->codec_id == CODEC_ID_SPEEX) { if (enc->sample_rate != 16000) { av_log(enc, AV_LOG_ERROR, "flv only supports wideband (16kHz) Speex audio\n"); return -1; } if (enc->channels != 1) { av_log(enc, AV_LOG_ERROR, "flv only supports mono Speex audio\n"); return -1; } if (enc->frame_size / 320 > 8) { av_log(enc, AV_LOG_WARNING, "Warning: Speex stream has more than " "8 frames per packet. Adobe Flash " "Player cannot handle this!\n"); } return FLV_CODECID_SPEEX | FLV_SAMPLERATE_11025HZ | FLV_SAMPLESSIZE_16BIT; } else { switch (enc->sample_rate) { case 44100: flags |= FLV_SAMPLERATE_44100HZ; break; case 22050: flags |= FLV_SAMPLERATE_22050HZ; break; case 11025: flags |= FLV_SAMPLERATE_11025HZ; break; case 8000: //nellymoser only case 5512: //not mp3 if(enc->codec_id != CODEC_ID_MP3){ flags |= FLV_SAMPLERATE_SPECIAL; break; } default: av_log(enc, AV_LOG_ERROR, "flv does not support that sample rate, choose from (44100, 22050, 11025).\n"); return -1; } } if (enc->channels > 1) { flags |= FLV_STEREO; } switch(enc->codec_id){ case CODEC_ID_MP3: flags |= FLV_CODECID_MP3 | FLV_SAMPLESSIZE_16BIT; break; case CODEC_ID_PCM_U8: flags |= FLV_CODECID_PCM | FLV_SAMPLESSIZE_8BIT; break; case CODEC_ID_PCM_S16BE: flags |= FLV_CODECID_PCM | FLV_SAMPLESSIZE_16BIT; break; case CODEC_ID_PCM_S16LE: flags |= FLV_CODECID_PCM_LE | FLV_SAMPLESSIZE_16BIT; break; case CODEC_ID_ADPCM_SWF: flags |= FLV_CODECID_ADPCM | FLV_SAMPLESSIZE_16BIT; break; case CODEC_ID_NELLYMOSER: if (enc->sample_rate == 8000) { flags |= FLV_CODECID_NELLYMOSER_8KHZ_MONO | FLV_SAMPLESSIZE_16BIT; } else { flags |= FLV_CODECID_NELLYMOSER | FLV_SAMPLESSIZE_16BIT; } break; case 0: flags |= enc->codec_tag<<4; break; default: av_log(enc, AV_LOG_ERROR, "codec not compatible with flv\n"); return -1; } return flags; }


static int init_output_stream_encode(OutputStream *ost) { InputStream *ist = get_input_stream(ost); AVCodecContext *enc_ctx = ost->enc_ctx; AVCodecContext *dec_ctx = NULL; AVFormatContext *oc = output_files[ost->file_index]->ctx; int j, ret; set_encoder_id(output_files[ost->file_index], ost); if (ist) { ost->st->disposition = ist->st->disposition; dec_ctx = ist->dec_ctx; enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location; } else { for (j = 0; j < oc->nb_streams; j++) { AVStream *st = oc->streams[j]; if (st != ost->st && st->codecpar->codec_type == ost->st->codecpar->codec_type) break; } if (j == oc->nb_streams) if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) ost->st->disposition = AV_DISPOSITION_DEFAULT; } if ((enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO || enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO) && filtergraph_is_simple(ost->filter->graph)) { FilterGraph *fg = ost->filter->graph; if (configure_filtergraph(fg)) { av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n"); exit_program(1); } } if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) { if (!ost->frame_rate.num) ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter); if (ist && !ost->frame_rate.num) ost->frame_rate = ist->framerate; if (ist && !ost->frame_rate.num) ost->frame_rate = ist->st->r_frame_rate; if (ist && !ost->frame_rate.num) { ost->frame_rate = (AVRational){25, 1}; av_log(NULL, AV_LOG_WARNING, "No information " "about the input framerate is available. Falling " "back to a default value of 25fps for output stream #%d:%d. Use the -r option " "if you want a different framerate.\n", ost->file_index, ost->index); } // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1}; if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) { int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates); ost->frame_rate = ost->enc->supported_framerates[idx]; } // reduce frame rate for mpeg4 to be within the spec limits if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) { av_reduce(&ost->frame_rate.num, &ost->frame_rate.den, ost->frame_rate.num, ost->frame_rate.den, 65535); } } switch (enc_ctx->codec_type) { case AVMEDIA_TYPE_AUDIO: enc_ctx->sample_fmt = av_buffersink_get_format(ost->filter->filter); if (dec_ctx) enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample, av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3); enc_ctx->sample_rate = av_buffersink_get_sample_rate(ost->filter->filter); enc_ctx->channel_layout = av_buffersink_get_channel_layout(ost->filter->filter); enc_ctx->channels = av_buffersink_get_channels(ost->filter->filter); enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate }; break; case AVMEDIA_TYPE_VIDEO: enc_ctx->time_base = av_inv_q(ost->frame_rate); if (!(enc_ctx->time_base.num && enc_ctx->time_base.den)) enc_ctx->time_base = av_buffersink_get_time_base(ost->filter->filter); if ( av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){ av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n" "Please consider specifying a lower framerate, a different muxer or -vsync 2\n"); } for (j = 0; j < ost->forced_kf_count; j++) ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j], AV_TIME_BASE_Q, enc_ctx->time_base); enc_ctx->width = av_buffersink_get_w(ost->filter->filter); enc_ctx->height = av_buffersink_get_h(ost->filter->filter); enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio = ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) : av_buffersink_get_sample_aspect_ratio(ost->filter->filter); if (!strncmp(ost->enc->name, "libx264", 7) && enc_ctx->pix_fmt == AV_PIX_FMT_NONE && av_buffersink_get_format(ost->filter->filter) != AV_PIX_FMT_YUV420P) av_log(NULL, AV_LOG_WARNING, "No pixel format specified, %s for H.264 encoding chosen.\n" "Use -pix_fmt yuv420p for compatibility with outdated media players.\n", av_get_pix_fmt_name(av_buffersink_get_format(ost->filter->filter))); if (!strncmp(ost->enc->name, "mpeg2video", 10) && enc_ctx->pix_fmt == AV_PIX_FMT_NONE && av_buffersink_get_format(ost->filter->filter) != AV_PIX_FMT_YUV420P) av_log(NULL, AV_LOG_WARNING, "No pixel format specified, %s for MPEG-2 encoding chosen.\n" "Use -pix_fmt yuv420p for compatibility with outdated media players.\n", av_get_pix_fmt_name(av_buffersink_get_format(ost->filter->filter))); enc_ctx->pix_fmt = av_buffersink_get_format(ost->filter->filter); if (dec_ctx) enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample, av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth); ost->st->avg_frame_rate = ost->frame_rate; if (!dec_ctx || enc_ctx->width != dec_ctx->width || enc_ctx->height != dec_ctx->height || enc_ctx->pix_fmt != dec_ctx->pix_fmt) { enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample; } if (ost->forced_keyframes) { if (!strncmp(ost->forced_keyframes, "expr:", 5)) { ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5, forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5); return ret; } ost->forced_keyframes_expr_const_values[FKF_N] = 0; ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0; ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN; ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN; // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes', // parse it only for static kf timings } else if(strncmp(ost->forced_keyframes, "source", 6)) { parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx); } } break; case AVMEDIA_TYPE_SUBTITLE: enc_ctx->time_base = (AVRational){1, 1000}; if (!enc_ctx->width) { enc_ctx->width = input_streams[ost->source_index]->st->codecpar->width; enc_ctx->height = input_streams[ost->source_index]->st->codecpar->height; } break; case AVMEDIA_TYPE_DATA: break; default: abort(); break; } return 0; }


int avio_put_str16le(AVIOContext *s, const char *str) { const uint8_t *q = str; int ret = 0; while (*q) { uint32_t ch; uint16_t tmp; GET_UTF8(ch, *q++, break;) PUT_UTF16(ch, tmp, avio_wl16(s, tmp); ret += 2;) } avio_wl16(s, 0); ret += 2; return ret; }


void init_get_bits(GetBitContext *s, UINT8 *buffer, int buffer_size) { s->buffer= buffer; s->size= buffer_size; s->buffer_end= buffer + buffer_size; #ifdef ALT_BITSTREAM_READER s->index=0; #elif defined LIBMPEG2_BITSTREAM_READER s->buffer_ptr = buffer; s->bit_count = 16; s->cache = 0; #elif defined A32_BITSTREAM_READER s->buffer_ptr = (uint32_t*)buffer; s->bit_count = 32; s->cache0 = 0; s->cache1 = 0; #endif { OPEN_READER(re, s) UPDATE_CACHE(re, s) // UPDATE_CACHE(re, s) CLOSE_READER(re, s) } #ifdef A32_BITSTREAM_READER s->cache1 = 0; #endif }


static int sdp_parse_rtpmap(AVCodecContext *codec, RTSPStream *rtsp_st, int payload_type, const char *p) { char buf[256]; int i; AVCodec *c; const char *c_name; /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and see if we can handle this kind of payload */ get_word_sep(buf, sizeof(buf), "/", &p); if (payload_type >= RTP_PT_PRIVATE) { RTPDynamicProtocolHandler *handler= RTPFirstDynamicPayloadHandler; while(handler) { if (!strcasecmp(buf, handler->enc_name) && (codec->codec_type == handler->codec_type)) { codec->codec_id = handler->codec_id; rtsp_st->dynamic_handler= handler; if(handler->open) { rtsp_st->dynamic_protocol_context= handler->open(); } break; } handler= handler->next; } } else { /* We are in a standard case ( from http://www.iana.org/assignments/rtp-parameters) */ /* search into AVRtpPayloadTypes[] */ codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type); } c = avcodec_find_decoder(codec->codec_id); if (c && c->name) c_name = c->name; else c_name = (char *)NULL; if (c_name) { get_word_sep(buf, sizeof(buf), "/", &p); i = atoi(buf); switch (codec->codec_type) { case CODEC_TYPE_AUDIO: av_log(codec, AV_LOG_DEBUG, " audio codec set to : %s\n", c_name); codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE; codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS; if (i > 0) { codec->sample_rate = i; get_word_sep(buf, sizeof(buf), "/", &p); i = atoi(buf); if (i > 0) codec->channels = i; // TODO: there is a bug here; if it is a mono stream, and less than 22000Hz, faad upconverts to stereo and twice the // frequency. No problem, but the sample rate is being set here by the sdp line. Upcoming patch forthcoming. (rdm) } av_log(codec, AV_LOG_DEBUG, " audio samplerate set to : %i\n", codec->sample_rate); av_log(codec, AV_LOG_DEBUG, " audio channels set to : %i\n", codec->channels); break; case CODEC_TYPE_VIDEO: av_log(codec, AV_LOG_DEBUG, " video codec set to : %s\n", c_name); break; default: break; } return 0; } return -1; }


static void virtio_net_device_realize(DeviceState *dev, Error **errp) { VirtIODevice *vdev = VIRTIO_DEVICE(dev); VirtIONet *n = VIRTIO_NET(dev); NetClientState *nc; int i; virtio_init(vdev, "virtio-net", VIRTIO_ID_NET, n->config_size); n->max_queues = MAX(n->nic_conf.peers.queues, 1); n->vqs = g_malloc0(sizeof(VirtIONetQueue) * n->max_queues); n->vqs[0].rx_vq = virtio_add_queue(vdev, 256, virtio_net_handle_rx); n->curr_queues = 1; n->vqs[0].n = n; n->tx_timeout = n->net_conf.txtimer; if (n->net_conf.tx && strcmp(n->net_conf.tx, "timer") && strcmp(n->net_conf.tx, "bh")) { error_report("virtio-net: " "Unknown option tx=%s, valid options: \"timer\" \"bh\"", n->net_conf.tx); error_report("Defaulting to \"bh\""); if (n->net_conf.tx && !strcmp(n->net_conf.tx, "timer")) { n->vqs[0].tx_vq = virtio_add_queue(vdev, 256, virtio_net_handle_tx_timer); n->vqs[0].tx_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, virtio_net_tx_timer, &n->vqs[0]); } else { n->vqs[0].tx_vq = virtio_add_queue(vdev, 256, virtio_net_handle_tx_bh); n->vqs[0].tx_bh = qemu_bh_new(virtio_net_tx_bh, &n->vqs[0]); n->ctrl_vq = virtio_add_queue(vdev, 64, virtio_net_handle_ctrl); qemu_macaddr_default_if_unset(&n->nic_conf.macaddr); memcpy(&n->mac[0], &n->nic_conf.macaddr, sizeof(n->mac)); n->status = VIRTIO_NET_S_LINK_UP; n->announce_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, virtio_net_announce_timer, n); if (n->netclient_type) { /* * Happen when virtio_net_set_netclient_name has been called. */ n->nic = qemu_new_nic(&net_virtio_info, &n->nic_conf, n->netclient_type, n->netclient_name, n); } else { n->nic = qemu_new_nic(&net_virtio_info, &n->nic_conf, object_get_typename(OBJECT(dev)), dev->id, n); peer_test_vnet_hdr(n); if (peer_has_vnet_hdr(n)) { for (i = 0; i < n->max_queues; i++) { qemu_using_vnet_hdr(qemu_get_subqueue(n->nic, i)->peer, true); n->host_hdr_len = sizeof(struct virtio_net_hdr); } else { n->host_hdr_len = 0; qemu_format_nic_info_str(qemu_get_queue(n->nic), n->nic_conf.macaddr.a); n->vqs[0].tx_waiting = 0; n->tx_burst = n->net_conf.txburst; virtio_net_set_mrg_rx_bufs(n, 0); n->promisc = 1; /* for compatibility */ n->mac_table.macs = g_malloc0(MAC_TABLE_ENTRIES * ETH_ALEN); n->vlans = g_malloc0(MAX_VLAN >> 3); nc = qemu_get_queue(n->nic); nc->rxfilter_notify_enabled = 1; n->qdev = dev; register_savevm(dev, "virtio-net", -1, VIRTIO_NET_VM_VERSION, virtio_net_save, virtio_net_load, n);