diff --git a/Changelog b/Changelog index 90964f0ae9..441be22abe 100644 --- a/Changelog +++ b/Changelog @@ -1,7 +1,919 @@ Entries are sorted chronologically from oldest to youngest within each release, releases are sorted from youngest to oldest. -version : +version 3.0.12 +- avutil/integer: Fix integer overflow in av_mul_i() +- avcodec/msrle: Check that the input is large enough to contain a end of picture code +- avcodec/jpeg2000dec: Fix off by 1 error in JPEG2000_PGOD_CPRL handling +- avcodec/mpeg4videodec: Fix typo in sprite delta check +- avcodec/h264_cavlc: Check mb_skip_run +- avcodec/ra144: Fix integer overflow in add_wav() +- avformat/utils: Never store negative values in last_IP_duration +- avformat/utils: Fix integer overflow in discontinuity check +- avcodec/unary: Improve get_unary() docs +- avcodec/dvdsubdec: Sanity check len in decode_rle() +- avcodec/mpeg4videodec: Fix undefined shift in get_amv() +- avcodec/zmbv: Check that the decompressed data size is correct +- avcodec/zmbv: Update decomp_len in raw frames +- avcodec/shorten: Fix bitstream end check in read_header() +- avcodec/dvdsubdec: Avoid branch in decode_run_8bit() +- avcodec/h264_refs: Document last if() in ff_h264_execute_ref_pic_marking() +- avcodec/ra144: Fix undefined integer overflow in add_wav() +- avcodec/hq_hqa: Check remaining input bits in hqa_decode_mb() +- avcodec/vb: Check for end of bytestream before reading blocktype +- avcodec/snowdec: Fix integer overflow with motion vector residual +- avformat/nsvdec: Do not parse multiple NSVf +- avformat/mlvdec: read_string() received unsigned size, make the argument unsigned +- avformat/rmdec: Fix EOF check in the stream loop in ivr_read_header() +- avcodec/shorten: Fix integer overflow in residual/LPC combination +- avcodec/shorten: Check verbatim length +- avcodec/mpegaudio_parser: Initialize poutbuf* +- avcodec/aacpsdsp_template: Fix integer overflow in ps_stereo_interpolate_c() +- avcodec/qtrle: Check remaining bytestream in qtrle_decode_XYbpp() +- avcodec/diracdec: Check bytes count in else branch in decode_lowdelay() too +- avcodec/diracdec: Change frame_number to 64bit as its a 32bit from the bitstream and we also have a -1 special case +- avcodec/dirac_dwt_template: Fix several integer overflows in horizontal_compose_daub97i() +- avcodec/diracdec: Prevent integer overflow in intermediate in global_mv() +- swresample/swresample: Fix input channel count in resample_first computation +- avutil/pixfmt: Document chroma plane size for odd resolutions +- avcodec/dvdsub_parser: Allocate input padding +- avcodec/dvdsub_parser: Init output buf/size +- avcodec/imgconvert: fix possible null pointer dereference +- avcodec/dirac_dwt_template: Fix signedness regression in interleave() +- swresample/arm: rename labels to fix xcode build error +- avformat/utils: fix mixed declarations and code +- libwebpenc_animencoder: add missing braces to struct initialization +- avformat/movenc: Check input sample count +- avcodec/mjpegdec: Check for odd progressive RGB +- avformat/movenc: Check that frame_types other than EAC3_FRAME_TYPE_INDEPENDENT have a supported substream id +- avformat/mms: Add missing chunksize check +- avformat/pva: Check for EOF before retrying in read_part_of_packet() +- avformat/rmdec: Do not pass mime type in rm_read_multi() to ff_rm_read_mdpr_codecdata() +- avcodec/indeo4: Check for end of bitstream in decode_mb_info() +- avcodec/shorten: Fix undefined addition in shorten_decode_frame() +- avcodec/jpeg2000dec: Fixes invalid shifts in jpeg2000_decode_packets_po_iteration() +- avcodec/jpeg2000dec: Check that there are enough bytes for all tiles +- avcodec/escape124: Fix spelling errors in comment +- avcodec/ra144: Fix integer overflow in ff_eval_refl() +- avcodec/cscd: Check output buffer size for lzo. +- avcodec/escape124: Check buf_size against num_superblocks +- avcodec/mjpegdec: Check for end of bitstream in ljpeg_decode_rgb_scan() +- avcodec/aacdec_fixed: Fix undefined integer overflow in apply_independent_coupling_fixed() +- avcodec/dirac_dwt_template: Fix undefined behavior in interleave() +- avutil/common: Fix undefined behavior in av_clip_uintp2_c() +- fftools/ffmpeg: Fallback to duration if sample rate is unavailable +- avformat/mov: Only set pkt->duration to non negative values +- avcodec/h264_mc_template: Only prefetch motion if the list is used. +- avcodec/xwddec: Use ff_set_dimensions() +- avcodec/wavpack: Fix overflow in adding tail +- avcodec/shorten: Fix multiple integer overflows +- avcodec/shorten: Sanity check nmeans +- avcodec/mjpegdec: Fix integer overflow in ljpeg_decode_rgb_scan() +- avcodec/truemotion2: Fix overflow in tm2_apply_deltas() +- avcodec/opus_silk: Change silk_lsf2lpc() slightly toward silk/NLSF2A.c +- avcodec/amrwbdec: Fix division by 0 in find_hb_gain() +- avformat/mov: replace a value error by clipping into valid range in mov_read_stsc() +- avformat/mov: Break out early if chunk_count is 0 in mov_build_index() +- avcodec/fic: Avoid some magic numbers related to cursors +- avcodec/g2meet: ask for sample with overflowing RGB +- avcodec/aacdec_fixed: use 64bit to avoid overflow in rounding in apply_dependent_coupling_fixed() +- oavcodec/aacpsdsp_template: Use unsigned for hs0X to prevent undefined behavior +- avcodec/g723_1dec: Clip bits2 in both directions +- avcodec/mpeg4videoenc: Use 64 bit for times in mpeg4_encode_gop_header() +- avcodec/mlpdec: Only change noise_type if the related fields are valid +- indeo4: Decode all or nothing of a band header. +- avformat/mov: Only fail for STCO/STSC contradictions if both exist +- avcodec/dirac_dwt: Fix integer overflow in COMPOSE_DD97iH0 / COMPOSE_DD137iL0 +- avcodec/fic: Check available input space for cursor +- avcodec/g2meet: Check RGB upper limit +- avcodec/jpeg2000dec: Fix undefined shift in the jpeg2000_decode_packets_po_iteration() CPRL case +- avcodec/jpeg2000dec: Skip init for component in CPRL if nothing is to be done +- avcodec/g2meet: Change order of operations to avoid undefined behavior +- avcodec/flac_parser: Fix infinite loop +- avcodec/wavpack: Fix integer overflow in DEC_MED() / INC_MED() +- avcodec/error_resilience: Fix integer overflow in filter181() +- avcodec/h263dec: Check slice_ret in mspeg4 slice loop +- avcodec/elsdec: Fix memleaks +- avcodec/vc1_block: simplify ac_val computation +- avcodec/ffv1enc: Check that the crc + version combination is supported +- lavf/http.c: Free allocated client URLContext in case of error. +- avcodec/dsicinvideo: Fail if there is only a small fraction of the data available that comprises a full frame +- avcodec/dsicinvideo: Propagate errors from cin_decode_rle() +- avcodec/dfa: Check dimension against maximum +- avcodec/cinepak: Skip empty frames +- avcodec/cinepak: move some checks prior to frame allocation +- swresample/arm: remove unintentional relocation. +- doc/APIchanges: Fix typos in hashes +- avformat/utils: Check cur_dts in update_initial_timestamps() more +- avcodec/utils: Enforce minimum width also for VP5/6 +- avcodec/truemotion2: Propagate out of bounds error from GET_TOK() +- avcodec/mjpegdec: Check input buffer size. +- lavc/libopusdec: Allow avcodec_open2 to call .close +- avcodec/movtextdec: Check style_start/end +- avcodec/aacsbr_fixed: Fix integer overflow in sbr_hf_assemble() +- libavcodec/rv34: error out earlier on missing references +- swresample/swresample: Fix for seg fault in swr_convert_internal() -> sum2_float during dithering. +- avcodec/aacdec_fixed: Fix integer overflow in apply_independent_coupling_fixed() +- avcodec/cscd: Error out when LZ* decompression fails +- avcodec/imgconvert: Fix loss mask bug in avcodec_find_best_pix_fmt_of_list() +- avcodec/wmalosslessdec: Fix null pointer dereference in decode_frame() +- avcodec/tableprint_vlc: Fix build failure with --enable-hardcoded-tables +- avcodec/get_bits: Make sure the input bitstream with padding can be addressed +- avformat/mov: Check STSC and remove invalid entries +- avcodec/nuv: rtjpeg with dimensions less than 16 would result in no decoded pixels thus reject it +- avcodec/nuv: Check for minimum input size for uncomprssed and rtjpeg +- avcodec/wmalosslessdec: Reset num_saved_bits on error path +- avformat/mov: Fix integer overflows related to sample_duration +- avformat/oggparsedaala: Do not adjust AV_NOPTS_VALUE +- avformat/oggparseogm: Check lb against psize +- avformat/oggparseogm: Fix undefined shift in ogm_packet() +- avformat/avidec: Fix integer overflow in cum_len check +- avformat/oggparsetheora: Do not adjust AV_NOPTS_VALUE +- avformat/utils: Fix integer overflow of fps_first/last_dts +- libavformat/oggparsevorbis: Fix memleak on multiple headers +- avdevice/iec61883: free the private context at the end +- avdevice/iec61883: return reference counted packets +- avdevice/iec61883: free packet on buffer allocation error + + +version 3.0.11 +- avcodec/bintext: sanity check dimensions +- avcodec/utvideodec: Check subsample factors +- avcodec/smc: Check input packet size +- avcodec/cavsdec: Check alpha/beta offset +- avcodec/diracdec: Fix integer overflow in mv computation +- avcodec/aacdec_templat: Fix integer overflow in apply_ltp() +- avcodec/jpeg2000dwt: Fix integer overflows in sr_1d53() +- avcodec/diracdec: Use int64 in global mv to prevent overflow +- avcodec/dxtory: Remove code that corrupts dimensions +- avformat/hvcc: zero initialize the nal buffers past the last written byte +- swresample/rematrix: fix update of channel matrix if input or output layout is undefined +- avcodec/dirac_dwt_template: Fix Integer overflow in horizontal_compose_dd137i() +- avcodec/vp8: Check for bitstream end before vp7_fade_frame() +- avcodec/exr: Check remaining bits in last get code loop +- avutil/common: Fix integer overflow in av_clip_uint8_c() and av_clip_uint16_c() +- avcodec/h264_cabac: Tighten allowed coeff_abs range +- avcodec/h264_cavlc: Set valid qscale value in ff_h264_decode_mb_cavlc() +- avcodec/vp3: Error out on invalid num_coeffs in unpack_vlcs() +- avcodec/mpeg4videodec: Ignore multiple VOL headers +- avcodec/vp3: Check eob_run +- avcodec/huffyuvdec: Check input buffer size +- avcodec/wavpack: Fix integer overflow in FFABS +- avcodec/aacsbr_fixed: Fix overflows in rounding in sbr_hf_assemble() +- avcodec/dirac_dwt: Fix several integer overflows +- avcodec/indeo5: Do not leave frame_type set to an invalid value +- avcodec/hevc_ps: Check log2_sao_offset_scale_* +- avcodec/hevc_ps: extract one SPS fields required for hvcC construction +- avcodec/mpeg4videodec: Avoid possibly aliasing violating casts +- avcodec/get_bits: Document the return code of get_vlc2() +- avcodec/mpeg4videodec: Check mb_num also against 0 +- avfilter/vf_transpose: Fix used plane count. +- avcodec/hevc_cabac: Check prefix so as to avoid invalid shifts in coeff_abs_level_remaining_decode() +- avcodec/mjpegdec: Fix integer overflow in DC dequantization +- avcodec/dxtory: Fix bits left checks +- avcodec/hevc_cabac: Move prefix check in coeff_abs_level_remaining_decode() down +- avcodec/truemotion2: Fix integer overflow in TM2_RECALC_BLOCK() +- avcodec/snowdec: Fix integer overflow before htaps check +- avcodec/ulti: Check number of blocks at init +- avcodec/ac3dec_fixed: Fix integer overflow in scale_coefs() +- avformat/lrcdec: Fix memory leak in lrc_read_header() +- avformat/matroskadec: Fix float-cast-overflow undefined behavior in matroska_parse_tracks() +- configure: bump year +- avcodec/utils: Avoid hardcoding duplicated types in sizeof() +- avcodec/arm/sbrdsp_neon: Use a free register instead of putting 2 things in one +- avcodec/h264addpx_template: Fixes integer overflows +- avcodec/dirac_dwt: Fix overflows in COMPOSE_HAARiH0/COMPOSE_HAARiL0 +- avcodec/diracdec: Fix integer overflow with quant +- avcodec/opus_parser: Check payload_len in parse_opus_ts_header() +- avcodec/jpeg2000dsp: Fix integer overflows in ict_int() +- avcodec/h264_slice: Do not attempt to render into frames already output +- avcodec/dnxhddec: Check dc vlc +- avcodec/exr: Check buf_size more completely +- avcodec/flacdec: Fix overflow in multiplication in decode_subframe_fixed() +- avcodec/hevcdsp_template: Fix Invalid shifts in put_hevc_qpel_bi_w_h() and put_hevc_qpel_bi_w_w() +- avcodec/flacdec: avoid undefined shift +- avcodec/hevcdsp_template.c: Fix undefined shift in FUNC(dequant) +- avcodec/dirac_dwt: Fix integer overflow in COMPOSE_DD97iH0() and COMPOSE_DD137iL0() +- avcodec/hevc_cabac: Fix integer overflow in ff_hevc_cu_qp_delta_abs() +- avcodec/hevc_sei: Fix integer overflows in decode_nal_sei_message() +- avcodec/hevcdsp_template: Fix undefined shift in put_hevc_qpel_bi_w_hv() +- libavfilter/af_dcshift.c: Fixed repeated spelling error +- avfilter/formats: fix wrong function name in error message +- avcodec/amrwbdec: Fix division by 0 in voice_factor() +- avcodec/diracdsp: Fix integer overflow in PUT_SIGNED_RECT_CLAMPED() +- avcodec/dirac_dwt: Fix integer overflows in COMPOSE_DAUB97* +- avformat/libssh: check the user provided a password before trying to use it + +version 3.0.10 +- avcodec/vorbis: Fix another 1 << 31 > int32_t::max() with 1u. +- Don't manipulate duration when it's AV_NOPTS_VALUE. +- avcodec/vorbis: 1 << 31 > int32_t::max(), so use 1u << 31 instead. +- avformat/utils: Prevent undefined shift with wrap_bits > 64. +- avcodec/j2kenc: Fix out of array access in encode_cblk() +- avcodec/hevcdsp_template: Fix undefined shift in put_hevc_epel_bi_w_h() +- avcodec/mlpdsp: Fix signed integer overflow, 2nd try +- avcodec/kgv1dec: Check that there is enough input for maximum RLE compression +- avcodec/dirac_dwt: Fix integer overflow in COMPOSE_FIDELITYi* +- avcodec/mpeg4videodec: Check also for negative versions in the validity check +- Close ogg stream upon error when using AV_EF_EXPLODE. +- Fix undefined shift on assumed 8-bit input. +- Use ff_thread_once for fixed, float table init. +- avformat/mov: Propagate errors in mov_switch_root. +- avcodec/hevcdsp_template: Fix invalid shift in put_hevc_epel_bi_w_v() +- avcodec/mlpdsp: Fix undefined shift ff_mlp_pack_output() +- avcodec/zmbv: Check that the buffer is large enough for mvec +- avcodec/dirac_dwt: Fix integer overflow in COMPOSE_DD137iL0() +- avcodec/wmv2dec: Check end of bitstream in parse_mb_skip() and ff_wmv2_decode_mb() +- avcodec/snowdec: Check for remaining bitstream in decode_blocks() +- avcodec/snowdec: Check intra block dc differences. +- avformat/mov: Check size of STSC allocation +- avcodec/vc2enc: Clear coef_buf on allocation +- avcodec/h264dec: Fix potential array overread +- avcodec/x86/mpegvideodsp: Fix signedness bug in need_emu +- avcodec/aacpsdsp_template: Fix integer overflows in ps_decorrelate_c() +- avcodec/aacdec_fixed: Fix undefined shift +- avcodec/mdct_*: Fix integer overflow in addition in RESCALE() +- avcodec/snowdec: Fix integer overflow in header parsing +- avcodec/cngdec: Fix integer clipping +- avcodec/sbrdsp_fixed: Fix integer overflow in shift in sbr_hf_g_filt_c() +- avutil/softfloat: Add FLOAT_MIN +- avcodec/aacsbr_fixed: Fix division by zero in sbr_gain_calc() +- avcodec/h264idct_template: Fix integer overflows in ff_h264_idct8_add() +- avcodec/xan: Check for bitstream end in xan_huffman_decode() +- avformat: Free the internal codec context at the end +- avcodec/xan: Improve overlapping check +- avcodec/aacdec_fixed: Fix integer overflow in apply_dependent_coupling_fixed() +- avcodec/aacdec_fixed: Fix integer overflow in predict() +- avcodec/jpeglsdec: Check for end of bitstream in ls_decode_line() +- avcodec/jpeglsdec: Check ilv for being a supported value +- avcodec/snowdec: Check mv_scale +- avcodec/pafvideo: Check for bitstream end in decode_0() +- avcodec/ffv1dec: Fix out of array read in slice counting +- avcodec/dirac_dwt: Fix integer overflow in COMPOSE_53iL0() +- avcodec/mpeg_er: Clear mcsel in mpeg_er_decode_mb() +- avcodec/mpeg4videodec: Use 64 bit intermediates for sprite delta +- avcodec/x86/lossless_videoencdsp: Fix handling of small widths +- avcodec/truemotion2: Fix integer overflows in tm2_high_chroma() +- avcodec/aacdec_template: Clear tns present flag on error +- avcodec/proresdec2: SKIP_BITS() does not work with len=32 +- avcodec/hevcdsp_template: Fix undefined shift +- avcodec/jpeg2000: Check that codsty->log2_prec_widths/heights has been initialized +- avcodec/takdec: Fix integer overflow in decode_lpc() +- avcodec/proresdec2: Check bits in DECODE_CODEWORD(), fixes invalid shift +- avcodec/takdec: Fix integer overflows in decode_subframe() +- avcodec/dirac_dwt: Fix integer overflow in COMPOSE_FIDELITYi*() +- avcodec/ffv1dec: Fix integer overflow in read_quant_table() +- avcodec/svq3: Fix overflow in svq3_add_idct_c() +- avcodec/pngdec: Clean up on av_frame_ref() failure +- avcodec/hevc_ps: Fix c?_qp_offset_list size +- avcodec/jpeg2000dsp: Fix multiple integer overflows in ict_int() +- avcodec/hevcdsp_template: Fix undefined shift in put_hevc_pel_bi_w_pixels +- avcodec/diracdec: Fix overflow in DC computation +- avformat/asfdec: Fix DoS in asf_build_simple_index() +- avformat/mov: Fix DoS in read_tfra() +- avcodec/dirac_dwt: Fix multiple overflows in 9/7 lifting +- avcodec/diracdec: Fix integer overflow in INTRA_DC_PRED() +- avformat/mxfdec: Fix Sign error in mxf_read_primer_pack() +- avformat/mxfdec: Fix DoS issues in mxf_read_index_entry_array() +- avformat/nsvdec: Fix DoS due to lack of eof check in nsvs_file_offset loop. +- avcodec/snowdec: Fix integer overflow in decode_subband_slice_buffered() +- avcodec/hevc_ps: Fix undefined shift in pcm code +- avcodec/sbrdsp_fixed: Fix undefined overflows in autocorrelate() +- avformat/mvdec: Fix DoS due to lack of eof check +- avformat/rl2: Fix DoS due to lack of eof check +- avformat/rmdec: Fix DoS due to lack of eof check +- avformat/cinedec: Fix DoS due to lack of eof check +- avformat/asfdec: Fix DoS due to lack of eof check +- avformat/hls: Fix DoS due to infinite loop +- ffprobe: Fix NULL pointer handling in color parameter printing +- ffprobe: Fix null pointer dereference with color primaries +- avcodec/hevc_ps: Check delta_pocs in ff_hevc_decode_short_term_rps() +- avformat/aviobuf: Fix signed integer overflow in avio_seek() +- avformat/mov: Fix signed integer overflows with total_size +- avcodec/utils: Fix signed integer overflow in rc_initial_buffer_occupancy initialization +- avcodec/aacdec_template: Fix running cleanup in decode_ics_info() +- avcodec/me_cmp: Fix crashes on ARM due to misalignment +- avcodec/dirac_dwt_template: Fix integer overflow in vertical_compose53iL0() +- avcodec/fic: Fixes signed integer overflow +- avcodec/snowdec: Fix off by 1 error +- avcodec/diracdec: Check perspective_exp and zrs_exp. +- avcodec/mpeg4videodec: Clear mcsel before decoding an image +- avcodec/dirac_dwt: Fixes integer overflows in COMPOSE_DAUB97* +- avcodec/aacdec_fixed: fix invalid shift in predict() +- avcodec/h264_slice: Fix overflow in slice offset +- avformat/utils: fix memory leak in avformat_free_context +- avcodec/dirac_dwt: Fix multiple integer overflows in COMPOSE_DD97iH0() +- avcodec/diracdec: Fix integer overflow in divide3() +- avcodec/takdec: Fix integer overflow in decode_subframe() +- avformat/rtmppkt: Convert ff_amf_get_field_value() to bytestream2 +- avformat/rtmppkt: Convert ff_amf_tag_size() to bytestream2 +- avcodec/diracdec: Fix integer overflow in signed multiplication in UNPACK_ARITH() +- avcodec/dnxhddec: Move mb height check out of non hr branch +- avcodec/hevc_ps: fix integer overflow in log2_parallel_merge_level_minus2 +- avformat/oggparsecelt: Do not re-allocate os->private +- avcodec/aacps: Fix multiple integer overflow in map_val_34_to_20() +- avcodec/aacdec_fixed: fix: left shift of negative value -1 +- doc/filters: typo in frei0r +- avcodec/cfhd: Fix decoding regression due to height chec + +version 3.0.9 +- avcodec/aacdec_template: Fix undefined integer overflow in apply_tns() +- avcodec/mjpegdec: Clip DC also on the negative side. +- avcodec/aacps (fixed point): Fix multiple signed integer overflows +- avcodec/sbrdsp_fixed: Fix integer overflow in sbr_hf_apply_noise() +- avcodec/wavpack: Fix invalid shift +- avcodec/hevc_ps: Fix integer overflow with beta/tc offsets +- avcodec/cfhd: Fix invalid left shift of negative value +- avcodec/vb: Check vertical GMC component before multiply +- avcodec/jpeg2000dwt: Fix integer overflow in dwt_decode97_int() +- avcodec/apedec: Fix integer overflow +- avcodec/wavpack: Fix integer overflow in wv_unpack_stereo() +- avcodec/mpeg4videodec: Fix GMC with videos of dimension 1 +- avcodec/wavpack: Fix integer overflow +- avcodec/takdec: Fix integer overflow +- avcodec/tiff: Update pointer only when the result is used +- avcodec/cfhd: Check bpc before setting bpc in context +- avcodec/cfhd: Fix undefined shift +- avcodec/hevc_filter: Fix invalid shift +- avcodec/mpeg4videodec: Fix overflow in virtual_ref computation +- avcodec/lpc: signed integer overflow in compute_lpc_coefs() (aacdec_fixed) +- avcodec/wavpack: Fix undefined integer negation +- avcodec/aacdec_fixed: Check s for being too small +- avcodec/htmlsubtitles: Replace very slow redundant sscanf() calls by cleaner and faster code +- avcodec/h264: Fix mix of lossless and lossy MBs decoding +- avcodec/h264_mb: Fix 8x8dct in lossless for new versions of x264 +- avcodec/h264_cabac: Fix CABAC+8x8dct in 4:4:4 +- avcodec/takdec: Fixes: integer overflow in AV_SAMPLE_FMT_U8P output +- avcodec/jpeg2000dsp: Reorder operations in ict_int() to avoid 2 integer overflows +- avcodec/hevcpred_template: Fix left shift of negative value +- avcodec/hevcdec: Fix signed integer overflow in decode_lt_rps() +- avcodec/jpeg2000dec: Check nonzerobits more completely +- avcodec/shorten: Sanity check maxnlpc +- avcodec/truemotion2: Move skip computation after checks +- avcodec/jpeg2000: Fixes integer overflow in ff_jpeg2000_ceildivpow2() +- avcodec/hevcdec: Check nb_sps +- avcodec/hevc_refs: Check nb_refs in add_candidate_ref() +- avcodec/mpeg4videodec: Check sprite delta upshift against overflowing. +- avcodec/mpeg4videodec: Fix integer overflow in num_sprite_warping_points=2 case +- avcodec/aacsbr_fixed: Check shift in sbr_hf_assemble() +- avcodec/sbrdsp_fixed: Return an error from sbr_hf_apply_noise() if operations are impossible +- avcodec/jpeg2000dwt: Fix runtime error: left shift of negative value -123 +- avcodec/wavpack: Fix runtime error: signed integer overflow: 1886191616 + 277872640 cannot be represented in type 'int' +- avcodec/snowdec: Fix runtime error: left shift of negative value -1 +- avcodec/aacdec_fixed: Fix runtime error: left shift of negative value -1297616 +- avcodec/tiff: Fix leak of geotags[].val +- avcodec/ra144: Fix runtime error: signed integer overflow: -2200 * 1033073 cannot be represented in type 'int' +- avcodec/flicvideo: Fix runtime error: signed integer overflow: 4864 * 459296 cannot be represented in type 'int' +- avcodec/cfhd: Check band parameters before storing them +- avcodec/indeo4: Check remaining data in Pic hdr extension parsing code +- avcodec/ac3dec_fixed: Fix multiple runtime error: signed integer overflow: -39271008 * 59 cannot be represented in type 'int' +- avcodec/mpeg4videodec: Fix runtime error: signed integer overflow: 53098 * 40448 cannot be represented in type 'int' +- avcodec/pafvideo: Fix assertion failure +- avcodec/takdec: Fix multiple runtime error: signed integer overflow: 637072 * 4096 cannot be represented in type 'int' +- avcodec/mjpegdec: Check that reference frame matches the current frame +- avcodec/tiff: Avoid loosing allocated geotag values +- avcodec/cavs: Fix runtime error: signed integer overflow: -12648062 * 256 cannot be represented in type 'int' +- avformat/hls: Check local file extensions +- avcodec/qdrw: Fix null pointer dereference +- avutil/softfloat: Fix sign error in and improve documentation of av_int2sf() +- avcodec/hevc_ps: Fix runtime error: index 32 out of bounds for type 'uint8_t [32]' +- avcodec/dxv: Check remaining bytes in dxv_decompress_raw() +- avcodec/pafvideo: Check packet size and frame code before ff_reget_buffer() +- avcodec/ac3dec_fixed: Fix runtime error: left shift of 419 by 23 places cannot be represented in type 'int' +- avformat/options: log filename on open +- avcodec/aacps: Fix runtime error: left shift of 1073741824 by 1 places cannot be represented in type 'INTFLOAT' (aka 'int') +- avcodec/wavpack: Fix runtime error: shift exponent 32 is too large for 32-bit type 'int' +- avcodec/wavpack: Fix runtime error: signed integer overflow: 2013265955 - -134217694 cannot be represented in type 'int' +- avcodec/cinepak: Check input packet size before frame reallocation +- avcodec/hevc_ps: Fix runtime error: signed integer overflow: 2147483628 + 256 cannot be represented in type 'int' +- avcodec/ra144: Fixes runtime error: signed integer overflow: 7160 * 327138 cannot be represented in type 'int' +- avcodec/pnm: Use ff_set_dimensions() +- avcodec/cavsdec: Fix runtime error: signed integer overflow: 59 + 2147483600 cannot be represented in type 'int' +- avformat/avidec: Limit formats in gab2 to srt and ass/ssa +- avcodec/acelp_pitch_delay: Fix runtime error: value 4.83233e+39 is outside the range of representable values of type 'float' +- avcodec/wavpack: Check float_shift +- avcodec/wavpack: Fix runtime error: signed integer overflow: 24 * -2147483648 cannot be represented in type 'int' +- avcodec/ansi: Fix frame memleak +- avcodec/jpeg2000dec: Use ff_set_dimensions() +- avcodec/truemotion2: Fix passing null pointer to memset() +- avcodec/truemotion2: Fix runtime error: left shift of 1 by 31 places cannot be represented in type 'int' +- avcodec/ra144: Fix runtime error: signed integer overflow: -2449 * 1398101 cannot be represented in type 'int' +- avcodec/ra144: Fix runtime error: signed integer overflow: 11184810 * 404 cannot be represented in type 'int' +- avcodec/aac_defines: Add missing () to AAC_HALF_SUM() macro +- avcodec/webp: Fixes null pointer dereference +- avcodec/aacdec_fixed: Fix runtime error: left shift of 1 by 31 places cannot be represented in type 'int' +- avcodec/snow: Fix runtime error: signed integer overflow: 1086573993 + 1086573994 cannot be represented in type 'int' +- avcodec/jpeg2000: Fix runtime error: signed integer overflow: 4185 + 2147483394 cannot be represented in type 'int' +- avcodec/jpeg2000dec: Check tile offsets more completely +- avcodec/aacdec_fixed: Fix multiple runtime error: shift exponent 127 is too large for 32-bit type 'int' +- avcodec/wnv1: More strict buffer size check +- avcodec/libfdk-aacdec: Correct buffer_size parameter +- avcodec/sbrdsp_template: Fix: runtime error: signed integer overflow: 849815297 + 1315389781 cannot be represented in type 'int' +- avcodec/ivi_dsp: Fix runtime error: left shift of negative value -2 +- doc/filters: Clarify scale2ref example +- avcodec/mlpdec: Do not leave invalid values in matrix_out_ch[] on error +- avcodec/ra144dec: Fix runtime error: left shift of negative value -17 +- avformat/mux: Fix copy an paste typo +- avutil/internal: Do not enable CHECKED with DEBUG +- avcodec/aacdec_fixed: Fix runtime error: signed integer overflow: -2147483648 * -1 cannot be represented in type 'int' +- avcodec/smc: Check remaining input +- avcodec/jpeg2000dec: Fix copy and paste error +- avcodec/jpeg2000dec: Check tile offsets +- avcodec/sanm: Fix uninitialized reference frames +- avcodec/jpeglsdec: Check get_bits_left() before decoding a picture +- avcodec/ivi_dsp: Fix multiple runtime error: left shift of negative value -71 +- avcodec/mjpegdec: Fix runtime error: signed integer overflow: -32767 * 130560 cannot be represented in type 'int' +- avcodec/aacdec_fixed: Fix runtime error: shift exponent 34 is too large for 32-bit type 'int' +- avcodec/mpeg4videodec: Check for multiple VOL headers +- avcodec/vmnc: Check location before use +- avcodec/takdec: Fix runtime error: signed integer overflow: 8192 * 524308 cannot be represented in type 'int' +- avcodec/aac_defines: Fix: runtime error: left shift of negative value -2 +- avcodec/takdec: Fix runtime error: left shift of negative value -63 +- avcodec/mlpdsp: Fix runtime error: signed integer overflow: -24419392 * 128 cannot be represented in type 'int' +- avcodec/sbrdsp_fixed: fix runtime error: left shift of 1 by 31 places cannot be represented in type 'int' +- avcodec/aacsbr_fixed: Fix multiple runtime error: shift exponent 170 is too large for 32-bit type 'int' +- avcodec/mlpdec: Do not leave a invalid num_primitive_matrices in the context +- avcodec/aacsbr_fixed: Fix multiple runtime error: shift exponent 150 is too large for 32-bit type 'int' +- avcodec/mimic: Use ff_set_dimensions() to set the dimensions +- avcodec/fic: Fix multiple runtime error: signed integer overflow: 5793 * 419752 cannot be represented in type 'int' + + +version 3.0.8 +- avcodec/aacdec: Fix runtime error: signed integer overflow: 2147483520 + 255 cannot be represented in type 'int' +- avcodec/aacdec_template: Fix fixed point scale in decode_cce() +- avcodec/flicvideo: Check frame_size before decrementing +- avcodec/mlpdec: Fix runtime error: left shift of negative value -1 +- avcodec/takdec: Fix runtime error: left shift of negative value -42 +- avcodec/hq_hqa: Fix: runtime error: signed integer overflow: -255 * 10180917 cannot be represented in type 'int' +- avcodec/truemotion1: Fix multiple runtime error: signed integer overflow: 1246906962 * 2 cannot be represented in type 'int' +- avcodec/svq3: Fix runtime error: left shift of negative value -6 +- avcodec/tiff: reset sampling[] if its invalid +- avcodec/aacps: Fix undefined behavior +- avcodec/opus_silk: Fix integer overflow and out of array read +- avcodec/flacdec: Return error code instead of 0 for failures +- avcodec/snowdec: Check width +- avcodec/webp: Update canvas size in vp8_lossy_decode_frame() as in vp8_lossless_decode_frame() +- avcodec/webp: Factor update_canvas_size() out +- avcodec/cllc: Check prefix +- avcodec/rscc: Check pixel_size for overflow +- avcodec/dds: Fix runtime error: left shift of 210 by 24 places cannot be represented in type 'int' +- avcodec/mpeg4videodec: Clear sprite wraping on unsupported cases in VOP decode +- avcodec/ac3dec: Fix: runtime error: index -1 out of bounds for type 'INTFLOAT [2]' +- avcodec/hqxdsp: Fix runtime error: signed integer overflow: -196264 * 11585 cannot be represented in type 'int' +- avcodec/g723_1dec: Fix LCG type +- libswscale/tests/swscale: Fix uninitialized variables +- avcodec/ffv1dec: Fix runtime error: signed integer overflow: 1550964438 + 1550964438 cannot be represented in type 'int' +- avcodec/webp: Fix signedness in prefix_code check +- avcodec/svq3: Fix runtime error: signed integer overflow: 169 * 12717677 cannot be represented in type 'int' +- avcodec/mlpdec: Check that there is enough data for headers +- avcodec/ac3dec: Keep track of band structure +- avcodec/webp: Add missing input padding +- avcodec/aacdec_fixed: Fix runtime error: left shift of negative value -1 +- avcodec/aacsbr_template: Do not change bs_num_env before its checked +- avcodec/mlp: Fix multiple runtime error: left shift of negative value -1 +- avcodec/vp8dsp: vp7_luma_dc_wht_c: Fix multiple runtime error: signed integer overflow: -1366381240 + -1262413604 cannot be represented in type 'int' +- avcodec/avcodec: Limit the number of side data elements per packet +- avcodec/texturedsp: Fix runtime error: left shift of 255 by 24 places cannot be represented in type 'int' +- avcodec/g723_1dec: Fix runtime error: left shift of negative value -1 +- avcodec/wmv2dsp: Fix runtime error: signed integer overflow: 181 * -17047030 cannot be represented in type 'int' +- avcodec/diracdec: Fix Assertion frame->buf[0] failed at libavcodec/decode.c:610 +- avcodec/msmpeg4dec: Check for cbpy VLC errors +- avcodec/cllc: Check num_bits +- avcodec/cllc: Factor VLC_BITS/DEPTH out, do not use repeated literal numbers +- avcodec/dvbsubdec: Check entry_id +- avcodec/aacdec_fixed: Fix multiple shift exponent 33 is too large for 32-bit type 'int' +- avcodec/mpeg12dec: Fixes runtime error: division by zero +- avcodec/webp: Always set pix_fmt +- avfilter/vf_uspp: Fix currently unused input frame dimensions +- avcodec/truemotion1: Fix multiple runtime error: left shift of negative value -1 +- avcodec/eatqi: Fix runtime error: signed integer overflow: 4466147 * 1075 cannot be represented in type 'int' +- avcodec/dss_sp: Fix runtime error: signed integer overflow: 2147481189 + 4096 cannot be represented in type 'int' +- avformat/wavdec: Check chunk_size +- avcodec/cavs: Check updated MV +- avcodec/y41pdec: Fix width in input buffer size check +- avcodec/svq3: Fix multiple runtime error: signed integer overflow: -237341 * 24552 cannot be represented in type 'int' +- avcodec/texturedsp: Fix runtime error: left shift of 218 by 24 places cannot be represented in type 'int' +- avcodec/lagarith: Check scale_factor +- avcodec/lagarith: Fix runtime error: left shift of negative value -1 +- avcodec/takdec: Fix multiple runtime error: left shift of negative value -1 +- avcodec/indeo2: Check for invalid VLCs +- avcodec/g723_1dec: Fix several integer related cases of undefined behaviour +- avcodec/htmlsubtitles: Check for string truncation and return error +- avcodec/bmvvideo: Fix runtime error: left shift of 137 by 24 places cannot be represented in type 'int' +- avcodec/dss_sp: Fix multiple runtime error: signed integer overflow: -15699 * -164039 cannot be represented in type 'int' +- avcodec/dvbsubdec: check region dimensions +- avcodec/vp8dsp: Fixes: runtime error: signed integer overflow: 1330143360 - -1023040530 cannot be represented in type 'int' +- avcodec/hqxdsp: Fix multiple runtime error: signed integer overflow: 248220 * 21407 cannot be represented in type 'int' in idct_col() +- avcodec/cavsdec: Check sym_factor +- avcodec/cdxl: Check format for BGR24 +- avcodec/ffv1dec: Fix copying planes of paletted formats +- avcodec/wmv2dsp: Fix runtime error: signed integer overflow: 181 * -12156865 cannot be represented in type 'int' +- avcodec/xwddec: Check bpp more completely +- avcodec/s302m: Fix left shift of 8 by 28 places cannot be represented in type 'int' +- avcodec/eamad: Fix runtime error: signed integer overflow: 49674 * 49858 cannot be represented in type 'int' +- avcodec/g726: Fix runtime error: left shift of negative value -2 +- avcodec/ra144: Fix runtime error: left shift of negative value -798 +- avcodec/mss34dsp: Fix multiple signed integer overflow +- avcodec/targa_y216dec: Fix width type +- avcodec/texturedsp: Fix multiple runtime error: left shift of 255 by 24 places cannot be represented in type 'int' +- avcodec/ivi_dsp: Fix multiple left shift of negative value -2 +- avcodec/svq3: Fix multiple runtime error: signed integer overflow: 44161 * 61694 cannot be represented in type 'int' +- avcodec/msmpeg4dec: Correct table depth +- avcodec/dds: Fix runtime error: left shift of 1 by 31 places cannot be represented in type 'int' +- avcodec/cdxl: Check format parameter +- avutil/softfloat: Fix overflow in av_div_sf() +- avcodec/hq_hqa: Fix runtime error: left shift of negative value -207 +- avcodec/mss3: Change types in rac_get_model_sym() to match the types they are initialized from +- avcodec/shorten: Check k in get_uint() +- avcodec/webp: Fix null pointer dereference +- avcodec/dfa: Fix signed integer overflow: -2147483648 - 1 cannot be represented in type 'int' +- avcodec/g723_1: Fix multiple runtime error: left shift of negative value +- avcodec/mimic: Fix runtime error: left shift of negative value -1 +- avcodec/fic: Fix multiple left shift of negative value -15 +- avcodec/mlpdec: Fix runtime error: left shift of negative value -22 +- avcodec/snowdec: Check qbias +- avutil/softfloat: Fix multiple runtime error: left shift of negative value -8 +- avcodec/aacsbr_template: Do not leave bs_num_env invalid +- avcodec/mdec: Fix signed integer overflow: 28835400 * 83 cannot be represented in type 'int' +- avcodec/dfa: Fix off by 1 error +- avcodec/nellymoser: Fix multiple left shift of negative value -8591 +- avcodec/cdxl: Fix signed integer overflow: 14243456 * 164 cannot be represented in type 'int' +- avcodec/g722: Fix multiple runtime error: left shift of negative value -1 +- avcodec/dss_sp: Fix multiple left shift of negative value -466 +- avcodec/wnv1: Fix runtime error: left shift of negative value -1 +- avcodec/tiertexseqv: set the fixed dimenasions, do not depend on the demuxer doing so +- avcodec/mjpegdec: Fix runtime error: signed integer overflow: -24543 * 2031616 cannot be represented in type 'int' +- avcodec/cavsdec: Fix undefined behavior from integer overflow +- avcodec/dvdsubdec: Fix runtime error: left shift of 242 by 24 places cannot be represented in type 'int' +- libavcodec/mpeg4videodec: Convert sprite_offset to 64bit +- avcodec/pngdec: Use ff_set_dimensions() +- avcodec/msvideo1: Check buffer size before re-getting the frame +- avcodec/h264_cavlc: Fix undefined behavior on qscale overflow +- avcodec/dcadsp: Fix runtime error: signed integer overflow +- avcodec/svq3: Increase offsets to prevent integer overflows +- avcodec/indeo2: Check remaining bits in ir2_decode_plane() +- avcodec/vp3: Check remaining bits in unpack_dct_coeffs() +- doc/developer: Add terse documentation of assumed C implementation defined behavior +- avcodec/mdec: Fix runtime error: left shift of negative value -127 +- avcodec/x86/vc1dsp_init: Fix build failure with --disable-optimizations and clang +- libavcodec/exr : fix float to uint16 conversion for negative float value +- avformat/webmdashenc: Validate the 'streams' adaptation sets parameter +- avformat/webmdashenc: Require the 'adaptation_sets' option to be set +- avcodec/dvdsubdec: Fixes 2 runtime error: left shift of 170 by 24 places cannot be represented in type 'int' +- avformat/oggparsedaala: Do not leave an invalid value in gpshift +- avformat/oggparsedaala: Check duration for AV_NOPTS_VALUE +- avfilter/af_sofalizer: Fix bad shift +- avfilter/avfiltergraph: Add assert to write down in machine readable form what is assumed about sample rates in swap_samplerates_on_filter() +- avcodec/tiff: Perform multiply in tiff_unpack_lzma() as 64bit +- avcodec/vdpau_hevc: Fix potential out-of-bounds write +- avcodec/tiff: Check geotag count for being non zero +- avcodec/vp56: Check avctx->error_concealment before enabling EC +- avcodec/tiff: Check stripsize strippos for overflow +- avcodec/mpegaudiodec_template: Make l3_unscale() work with e=0 +- avcodec/tiff: Check for multiple geo key directories +- avcodec/wavpack: Fix runtime error: shift exponent 32 is too large for 32-bit type 'int' +- avcodec/rv34: Fix runtime error: signed integer overflow: 36880 * 66288 cannot be represented in type 'int' +- avcodec/amrwbdec: Fix runtime error: left shift of negative value -1 +- avcodec/mpeg4videodec: Fix runtime error: signed integer overflow: -135088512 * 16 cannot be represented in type 'int' +- avcodec/h264_mvpred: Fix runtime error: left shift of negative value -1 +- avcodec/mjpegdec: Fix runtime error: left shift of negative value -127 +- avcodec/wavpack: Fix runtime error: left shift of negative value -5 +- avcodec/wavpack: Fix runtime error: left shift of negative value -2 +- avcodec/mpeg4videodec: Fix runtime error: signed integer overflow: 134527392 * 16 cannot be represented in type 'int' +- avcodec/mpeg12dec: Fix runtime error: left shift of negative value -13 +- avcodec/h264_mvpred: Fix multiple runtime error: left shift of negative value +- avcodec/adxdec: Fix runtime error: left shift of negative value -1 +- avcodec/mpeg4videodec: Improve the overflow checks in mpeg4_decode_sprite_trajectory() +- avcodec/mjpegdec: Fix runtime error: left shift of negative value -511 +- avcodec/h264_direct: Fix runtime error: left shift of negative value -14 +- avcodec/pictordec: Check plane value before doing value/mask computations +- avcodec/mpeg4videodec: Fix runtime error: left shift of negative value -2650 +- avcodec/eac3dec: Fix runtime error: left shift of negative value -3 +- avcodec/mpeg12dec: Fix runtime error: left shift of negative value -2 +- avcodec/mpeg4videodec: Check the other 3 sprite points for intermediate overflows +- avcodec/mpeg4videodec: Check sprite_offset in addition to shifts +- avcodec/mpeg4video: Fix runtime error: left shift of negative value +- avcodec/ituh263dec: Fix runtime error: left shift of negative value -22 +- avcodec/rv40: Fix runtime error: left shift of negative value +- avcodec/h264_cabac: runtime error: signed integer overflow: 2147483647 + 14 cannot be represented in type 'int' +- avcodec/mpeg4videodec: Fix runtime error: shift exponent -2 is negative +- avcodec/mjpegdec: Fix runtime error: left shift of negative value -507 +- avcodec/eac3dec: Fix runtime error: left shift of negative value +- avcodec/htmlsubtitles: Fix reading one byte beyond the array +- avcodec/vp6: clear dimensions on failed resolution change in vp6_parse_header() +- avcodec/vp56: Reset have_undamaged_frame on resolution changes +- avcodec/vp8: Fix hang with slice threads +- avcodec/vp8: Check for the bitstream end per MB in decode_mb_row_no_filter() +- avcodec/vp568: Check that there is enough data for ff_vp56_init_range_decoder() +- avcodec/vp8: remove redundant check +- avcodec/vp56: Require a correctly decoded frame before using vp56_conceal_mb() +- avcodec/vp3: Do not return random positive values but the buf size +- avcodec/vp8: Check for bitsteam end in decode_mb_row_no_filter() +- avcodec/vp56: Factorize vp56_render_mb() out +- avcodec/vp3dsp: Fix multiple signed integer overflow: 46341 * 47523 cannot be represented in type 'int' +- Add CHECK/SUINT code +- avcodec/mpeg12dec: Fix runtime error: left shift of negative value -1 +- avcodec/vp56: Clear dimensions in case of failure in the middle of a resolution change +- avcodec/vp56: Implement very basic error concealment +- avcodec/amrwbdec: Fix 2 runtime errors: left shift of negative value -1 +- avcodec/pngdec: Fix runtime error: left shift of 152 by 24 places cannot be represented in type 'int' +- avcodec/vp56: Fix sign typo +- avcodec/mpegaudiodec_template: Correct return code on id3 tag discarding +- avcodec/rv34: Simplify and factor get_slice_offset() code +- avcodec/pictordec: Do not read more than nb_planes +- avcodec/srtdec: Fix signed integer overflow: 1811992524 * 384 cannot be represented in type 'int' +- avcodec/pngdec: Check bit depth for validity +- avcodec/mpeg12dec: Fix runtime error: left shift of negative value +- avcodec/wavpacl: Fix runtime error: left shift of negative value -1 +- avformat/http: Check for truncated buffers in http_connect() +- avformat/apng: fix setting frame delay when max_fps is set to no limit +- swresample/resample: free existing ResampleContext on reinit +- swresample/resample: move resample_free() higher in the file +- lavf/mpeg: Initialize a stack variable used by memcmp(). +- lavc/avpacket: Initialize a variable in error path. + +version 3.0.7 +- avcodec/h264_slice: Clear ref_counts on redundant slices +- lavf/mov.c: Avoid heap allocation wrap in mov_read_uuid +- lavf/mov.c: Avoid heap allocation wrap in mov_read_hdlr +- avcodec/pictordec: Fix logic error +- avcodec/movtextdec: Fix decode_styl() cleanup +- lavf/matroskadec: fix is_keyframe for early Blocks + +version 3.0.6: +- avcodec/pngdec: Check trns more completely +- avcodec/interplayvideo: Move parameter change check up +- avcodec/mjpegdec: Check for for the bitstream end in mjpeg_decode_scan_progressive_ac() +- avformat/flacdec: Check avio_read result when reading flac block header. +- avcodec/utils: correct align value for interplay +- avcodec/vp56: Check for the bitstream end, pass error codes on +- avcodec/mjpegdec: Check remaining bitstream in ljpeg_decode_yuv_scan() +- avcodec/pngdec: Fix off by 1 size in decode_zbuf() +- avformat/avidec: skip odml master index chunks in avi_sync +- avcodec/mjpegdec: Check for rgb before flipping +- avutil/random_seed: Reduce the time needed on systems with very low precision clock() +- avutil/random_seed: Improve get_generic_seed() with higher precision clock() +- avformat/utils: Print verbose error message if stream count exceeds max_streams +- avformat/options_table: Set the default maximum number of streams to 1000 +- pgssubdec: reset rle_data_len/rle_remaining_len on allocation error +- avutil: Add av_image_check_size2() +- avformat: Add max_streams option +- avcodec/ffv1enc: Allocate smaller packet if the worst case size cannot be allocated +- avcodec/mpeg4videodec: Fix undefined shifts in mpeg4_decode_sprite_trajectory() +- avformat/oggdec: Skip streams in duration correction that did not had their duration set. +- avcodec/ffv1enc: Fix size of first slice + + +version 3.0.5: +- configure: check for strtoull on msvc +- http: move chunk handling from http_read_stream() to http_buf_read(). +- http: make length/offset-related variables unsigned. +- ffserver: Check chunk size +- Avoid using the term "file" and prefer "url" in some docs and comments +- avformat/rtmppkt: Check for packet size mismatches +- zmqsend: Initialize ret to 0 +- avcodec/rawdec: check for side data before checking its size +- avcodec/flacdec: Fix undefined shift in decode_subframe() +- avcodec/get_bits: Fix get_sbits_long(0) +- avformat/ffmdec: Check media type for chunks +- avcodec/flacdec: Fix signed integer overflow in decode_subframe_fixed() +- avcodec/flacdsp_template: Fix undefined shift in flac_decorrelate_indep_c +- avformat/oggparsespeex: Check frames_per_packet and packet_size +- avformat/utils: Check start/end before computing duration in update_stream_timings() +- avcodec/flac_parser: Update nb_headers_buffered +- avformat/idroqdec: Check chunk_size for being too large +- avformat/mpeg: Adjust vid probe threshold to correct mis-detection +- avcodec/rv40: Test remaining space in loop of get_dimension() +- avcodec/ituh263dec: Avoid spending a long time in slice sync +- avcodec/movtextdec: Add error message for tsmb_size check +- avcodec/movtextdec: Fix tsmb_size check==0 check +- avcodec/movtextdec: Fix potential integer overflow +- avcodec/sunrast: Fix input buffer pointer check +- avcodec/tscc: Check side data size before use +- avcodec/rawdec: Check side data size before use +- avcodec/msvideo1: Check side data size before use +- avcodec/qpeg: Check side data size before use +- avcodec/qtrle: Check side data size before use +- avcodec/msrle: Check side data size before use +- avcodec/kmvc: Check side data size before use +- avcodec/idcinvideo: Check side data size before use +- avcodec/cinepak: Check side data size before use +- avcodec/8bps: Check side data size before use +- avcodec/dvdsubdec: Fix off by 1 error +- avcodec/dvdsubdec: Fix buf_size check +- vp9: change order of operations in adapt_prob(). +- avcodec/interplayvideo: Check side data size before use +- avformat/mxfdec: Check size to avoid integer overflow in mxf_read_utf16_string() +- avcodec/mpegvideo_enc: Clear mmx state in ff_mpv_reallocate_putbitbuffer() +- avcodec/utils: Clear MMX state before returning from avcodec_default_execute*() +- avformat/icodec: Fix crash probing fuzzed file +- dcstr: fix division by zero +- rsd: limit number of channels +- mss2: only use error correction for matching block counts +- softfloat: decrease MIN_EXP to cover full float range +- libopusdec: default to stereo for invalid number of channels +- pgssubdec: only set w/h/linesize when allocating data +- sbgdec: prevent NULL pointer access +- smacker: limit recursion depth of smacker_decode_bigtree +- mxfdec: fix NULL pointer dereference in mxf_read_packet_old +- libschroedingerdec: fix leaking of framewithpts +- libschroedingerdec: don't produce empty frames +- softfloat: handle -INT_MAX correctly +- filmstripdec: correctly check image dimensions +- pnmdec: make sure v is capped by maxval +- smvjpegdec: make sure cur_frame is not negative +- icodec: correctly check avio_read return value +- dvbsubdec: fix division by zero in compute_default_clut +- proresdec_lgpl: explicitly check coff[3] against slice_data_size +- escape124: reject codebook size 0 +- icodec: add ico_read_close to fix leaking ico->images +- icodec: fix leaking pkt on error +- mpegts: prevent division by zero +- matroskadec: fix NULL pointer dereference in webm_dash_manifest_read_header +- mpegaudio_parser: don't return AVERROR_PATCHWELCOME +- mxfdec: fix NULL pointer dereference +- lzf: update pointer p after realloc +- diracdec: check return code of get_buffer_with_edge +- ppc: pixblockdsp: do unaligned block accesses correctly again +- interplayacm: increase bitstream buffer size by AV_INPUT_BUFFER_PADDING_SIZE +- interplayacm: validate number of channels +- interplayacm: check for too large b +- mpeg12dec: unref discarded picture from extradata +- cavsdec: unref frame before referencing again +- avformat: prevent triggering request_probe assert in ff_read_packet +- avcodec/avpacket: fix leak on realloc in av_packet_add_side_data() + + +version 3.0.4: +- libopenjpegenc: fix out-of-bounds reads when filling the edges +- libopenjpegenc: stop reusing image data buffer for openjpeg 2 +- configure: fix detection of libopenjpeg +- cmdutils: fix typos +- lavfi: fix typos +- lavc: fix typos +- tools: fix grammar error +- ffmpeg: remove unused and errorneous AVFrame timestamp check +- Support for MIPS cpu P6600 +- avutil/mips/generic_macros_msa: rename macro variable which causes segfault for mips r +- avformat/avidec: Check nb_streams in read_gab2_sub() +- avformat/avidec: Remove ancient assert +- avformat/avidec: Fix memleak with dv in avi +- lavc/movtextdec.c: Avoid infinite loop on invalid data. +- avcodec/ansi: Check dimensions +- avcodec/cavsdsp: use av_clip_uint8() for idct +- avformat/movenc: Check packet in mov_write_single_packet() too +- avformat/movenc: Factor check_pkt() out +- avformat/utils: fix timebase error in avformat_seek_file() +- avcodec/g726: Add missing ADDB output mask +- avcodec/avpacket: clear side_data_elems +- avformat/movenc: Check first DTS similar to dts difference +- avcodec/ccaption_dec: Use simple array instead of AVBuffer +- avformat/mov: Fix potential integer overflow in mov_read_keys +- swscale/swscale_unscaled: Try to fix Rgb16ToPlanarRgb16Wrapper() with slices +- swscale/swscale_unscaled: Fix packed_16bpc_bswap() with slices +- lavf/utils: Avoid an overflow for huge negative durations. + +version 3.0.3: +- avformat/avidec: Fix infinite loop in avi_read_nikon() +- avcodec/aacenc: Tighter input checks +- avformat/wtvdec: Check pointer before use +- libavcodec/wmalosslessdec: Check the remaining bits +- avcodec/diracdec: Check numx/y +- avcodec/cfhd: Increase minimum band dimension to 3 +- avcodec/indeo2: check ctab +- avformat/swfdec: Fix inflate() error code check +- avcodec/rawdec: Fix bits_per_coded_sample checks +- lavc/mjpegdec: Do not skip reading quantization tables. +- cmdutils: fix implicit declaration of SetDllDirectory function +- cmdutils: check for SetDllDirectory() availability +- avcodec/h264: Put context_count check back +- cmdutils: remove the current working directory from the DLL search path on win32 +- avcodec/raw: Fix decoding of ilacetest.mov +- avcodec/ffv1enc: Fix assertion failure with non zero bits per sample +- avformat/oggdec: Fix integer overflow with invalid pts +- ffplay: Fix invalid array index +- avcodec/vp9_parser: Check the input frame sizes for being consistent +- libavformat/rtpdec_asf: zero initialize the AVIOContext struct +- libavutil/opt: Small bugfix in example. +- libx264: Increase x264 opts character limit to 4096 +- avformat/mov: Check sample size +- avformat/format: Fix registering a format more than once and related races +- avformat/flacdec: Fix seeking close to EOF +- avcodec/flac_parser: Raise threshold for detecting invalid data +- avformat/flvdec: Accept last size if its off by 1 +- tests/api/api-codec-param-test: Do not directly access caps_internal +- avcodec: Add avpriv_codec_get_cap_skip_frame_fill_param() +- avfilter/vf_telecine: Make frame writable before writing into it +- avformat/mpegts: adjust probe score for low check_count +- avcodec/mpc8: Correct end truncation +- avformat/mp3dec: Increase probe score slightly when the whole data from begin to end is mp3 +- avcodec/cfhd: Set dimensions unconditionally +- avcodec/mpegvideo: Do not clear the parse context during init +- avcodec/h264: Fix off by 1 context count +- avcodec/alsdec: Check r to prevent out of array read +- avcodec/alsdec: fix max bits in ltp prefix code +- avcodec/utils: check skip_samples signedness +- avformat/mpegts: Do not trust BSSD descriptor, it is sometimes not an S302M stream +- avcodec/bmp_parser: Check fsize +- avcodec/bmp_parser: reset state +- avcodec/bmp_parser: Fix remaining size +- avcodec/bmp_parser: Fix frame_start_found in cross frame cases +- avfilter/af_amix: do not fail if there are no samples in output_frame() +- avformat/allformats: Making av_register_all() thread-safe. +- librtmp: Avoid an infiniloop setting connection arguments +- avformat/oggparsevp8: fix pts calculation on pages ending with an invisible frame +- Revert "configure: Enable GCC vectorization on ≥4.9 on x86" +- avcodec/libopenjpegenc: Set numresolutions by default to a value that is not too large +- ffplay: Fix usage of private lavfi API +- tests/checkasm/checkasm: Disable checkasm_check_pixblockdsp for ppc64be +- avcodec/mpegvideo: Deallocate last/next picture earlier +- avcodec/bmp_parser: Fix state +- avformat/oggparseopus: Fix Undefined behavior in oggparseopus.c and libavformat/utils.c +- avformat/utils: avoid overflow in compute_chapters_end() with huge durations +- avformat/utils: avoid overflow in update_stream_timings() with huge durations +- doc/developer.texi: Add a code of conduct +- ffserver: fixed deallocation bug in build_feed_streams +- avcodec/diracdec: Fix potential integer overflow +- avformat/avidec: Detect index with too short entries +- avformat/utils: Check negative bps before shifting in ff_get_pcm_codec_id() +- avformat/utils: Do not compute the bitrate from duration == 0 +- ffmpeg: Check that r_frame_rate is set before attempting to use it +- swresample/resample: Fix division by 0 with tap_count=1 +- swresample/rematrix: Use clipping s16 rematrixing if overflows are possible +- swresample/rematrix: Use error diffusion to avoid error in the DC component of the matrix +- hevc: Fix memory leak related to a53_caption data +- libavformat/oggdec: Free stream private when header parsing fails. +- avformat/utils: Check bps before using it in a shift in ff_get_pcm_codec_id() +- avformat/oggparseopus: Check that granule pos is within the supported range +- avcodec/mjpegdec: Do not try to detect last scan but apply idct after all scans for progressive jpeg +- avformat/options_table: Add missing identifier for very strict compliance +- avformat/ffmdec: Check pix_fmt +- doc/general: update supported DCA extensions +- avcodec/rscc: check input buffer size for deflate mode +- avcodec/dca: fix sync word search error condition +- lavf/mpegts: Return small probe score for very short transport streams. + + +version 3.0.2: +- avcodec/ttaenc: Reallocate packet if its too small +- configure: build fix for P5600 with mips code restructuring +- mips: add support for R6 +- pgssubdec: fix subpicture output colorspace and range +- avcodec/ac3dec: Reset SPX when switching from EAC3 to AC3 +- avfilter/vf_drawtext: Check return code of load_glyph() +- avformat/mux: Check that deinit is set before calling it +- avcodec/takdec: add code that got somehow lost in process of REing +- avcodec/apedec: fix decoding of stereo files with one channel full of silence +- avcodec/avpacket: Fix off by 5 error +- avcodec/h264: Fix for H.264 configuration parsing +- avcodec/bmp_parser: Ensure remaining_size is not too small in startcode packet crossing corner case +- avcodec/pngdec: Fix alpha detection with skip_frame +- Changelog: Make formating consistent +- avfilter/src_movie: fix how we check for overflows with seek_point +- avcodec/j2kenc: Add attribution to OpenJPEG project: + + +version 3.0.1: +- avcodec/libutvideodec: copy frame so it has reference counters when refcounted_frames is set +- avformat/rtpdec_jpeg: fix low contrast image on low quality setting +- avformat/mpegtsenc: Fix used service +- avformat/mpegtsenc: Keep track of the program for each service +- avformat/file: Add crypto to default whitelist +- avcodec/mjpegenc_common: Store approximate aspect if exact cannot be stored +- lavc/hevc: Allow arbitrary garbage in bytestream as long as at least one NAL unit is found. +- avcodec/resample: Remove disabled and faulty code +- indeo2: Fix banding artefacts +- indeo2data: K&R formatting cosmetics +- avformat/hlsenc: Fix passing options, regression since bc9a5965c815cf7fd998d8ce14a18b8e861dd9ce +- avutil/random_seed: Add the runtime in cycles of the main loop to the entropy pool +- avutil/channel_layout: AV_CH_LAYOUT_6POINT1_BACK not reachable in parsing +- avformat/concatdec: set safe mode to enabled instead of auto +- avformat/utils: fix dts from pts code in compute_pkt_fields() during ascending delay +- avformat/rtpenc: Fix integer overflow in NTP_TO_RTP_FORMAT +- avcodec/dca: clear X96 channels if nothing was decoded +- fate/aac: Increase fuzz from of fate-aac-pns-encode from 72 to 74 for Loongson +- avformat/cache: Fix memleak of tree entries +- lavf/mov: downgrade sidx errors to non-fatal warnings; fixes trac #5216 +- lavf/mov: fix sidx with edit lists +- avcodec/mjpegdec: Fix decoding slightly odd progressive jpeg +- swscale/utils: Fix chrSrcHSubSample for GBRAP16 +- swscale/input: Fix GBRAP16 input +- avutil/pixdesc: Make get_color_type() aware of CIE XYZ formats +- avcodec/h264: Execute error concealment before marking the frame as done. +- swscale/x86/output: Fix yuv2planeX_16* with unaligned destination +- swscale/x86/output: Move code into yuv2planeX_mainloop +- MAINTAINERS: add myself as an OS/2 maintainer +- libwebpenc_animencoder: print library messages in verbose log levels +- libwebpenc_animencoder: zero initialize the WebPAnimEncoderOptions struct +- configure: check for SEC_I_CONTEXT_EXPIRED before enabling SChannel +- lavf/http: Add httpproxy to the default protocol whitelist. +- doc/utils: fix typo for min() description +- ffserver&ffm: Fixed issues preventing ffserver write_index and files_size from being set correctly which was breaking ffserver streaming. +- postproc: fix unaligned access +- vc2enc: fix use of uninitialized variables in the rate control system, correctly zero out coefficient array padding +- aacenc: optimize encoding speed +- avcodec/diracdec: check bitstream size related fields for overflows +- avcodec/h264_slice: Check PPS more extensively when its not copied version 3.0: @@ -70,6 +982,8 @@ version 3.0: - streamselect video and astreamselect audio filter - swaprect filter - metadata video and ametadata audio filter +- SMPTE VC-2 HQ profile support for the Dirac decoder +- SMPTE VC-2 native encoder supporting the HQ profile version 2.8: diff --git a/MAINTAINERS b/MAINTAINERS index e57150da90..15203e29cb 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -56,7 +56,7 @@ Communication website Deby Barbara Lepage fate.ffmpeg.org Timothy Gu Trac bug tracker Alexander Strasser, Michael Niedermayer, Carl Eugen Hoyos, Lou Logan -mailing lists Michael Niedermayer, Baptiste Coudurier, Lou Logan +mailing lists Baptiste Coudurier, Lou Logan Google+ Paul B Mahol, Michael Niedermayer, Alexander Strasser Twitter Lou Logan, Reynaldo H. Verdejo Pinochet Launchpad Timothy Gu @@ -168,7 +168,7 @@ Codecs: dirac* Rostislav Pehlivanov dnxhd* Baptiste Coudurier dpcm.c Mike Melanson - dss_sp.c Oleksij Rempel, Michael Niedermayer + dss_sp.c Oleksij Rempel dv.c Roman Shaposhnik dvbsubdec.c Anshul Maheshwari dxa.c Kostya Shishkov @@ -422,7 +422,7 @@ Muxers/Demuxers: cdxl.c Paul B Mahol crc.c Michael Niedermayer daud.c Reimar Doeffinger - dss.c Oleksij Rempel, Michael Niedermayer + dss.c Oleksij Rempel dtshddec.c Paul B Mahol dv.c Roman Shaposhnik dxa.c Kostya Shishkov @@ -458,7 +458,7 @@ Muxers/Demuxers: mgsts.c Paul B Mahol microdvd* Aurelien Jacobs mm.c Peter Ross - mov.c Michael Niedermayer, Baptiste Coudurier + mov.c Baptiste Coudurier movenc.c Baptiste Coudurier, Matthieu Bouron movenccenc.c Eran Kornblau mpc.c Kostya Shishkov @@ -563,7 +563,7 @@ Windows MSVC Matthew Oliver, Hendrik Leppkes Windows ICL Matthew Oliver ADI/Blackfin DSP Marc Hoffman Sparc Roman Shaposhnik -x86 Michael Niedermayer +OS/2 KO Myung-Hun Releases diff --git a/RELEASE b/RELEASE index 847967f1eb..f93fc9f42e 100644 --- a/RELEASE +++ b/RELEASE @@ -1 +1 @@ -2.8.git +3.0.12 diff --git a/RELEASE_NOTES b/RELEASE_NOTES new file mode 100644 index 0000000000..861dc04a13 --- /dev/null +++ b/RELEASE_NOTES @@ -0,0 +1,15 @@ + + ┌─────────────────────────────────────────┐ + │ RELEASE NOTES for FFmpeg 3.0 "Einstein" │ + └─────────────────────────────────────────┘ + + The FFmpeg Project proudly presents FFmpeg 3.0 "Einstein", about 5 + months after the release of FFmpeg 2.8. + + A complete Changelog is available at the root of the project, and the + complete Git history on http://source.ffmpeg.org. + + We hope you will like this release as much as we enjoyed working on it, and + as usual, if you have any questions about it, or any FFmpeg related topic, + feel free to join us on the #ffmpeg IRC channel (on irc.freenode.net) or ask + on the mailing-lists. diff --git a/cmdutils.c b/cmdutils.c index 03a4836207..476c85894c 100644 --- a/cmdutils.c +++ b/cmdutils.c @@ -61,6 +61,9 @@ #include #include #endif +#if HAVE_SETDLLDIRECTORY +#include +#endif static int init_report(const char *env); @@ -107,6 +110,15 @@ static void log_callback_report(void *ptr, int level, const char *fmt, va_list v } } +void init_dynload(void) +{ +#if HAVE_SETDLLDIRECTORY + /* Calling SetDllDirectory with the empty string (but not NULL) removes the + * current working directory from the DLL search path as a security pre-caution. */ + SetDllDirectory(""); +#endif +} + static void (*program_exit)(int ret); void register_exit(void (*cb)(int ret)) @@ -2099,7 +2111,7 @@ static int print_device_sources(AVInputFormat *fmt, AVDictionary *opts) if (!fmt || !fmt->priv_class || !AV_IS_INPUT_DEVICE(fmt->priv_class->category)) return AVERROR(EINVAL); - printf("Audo-detected sources for %s:\n", fmt->name); + printf("Auto-detected sources for %s:\n", fmt->name); if (!fmt->get_device_list) { ret = AVERROR(ENOSYS); printf("Cannot list sources. Not implemented.\n"); @@ -2129,7 +2141,7 @@ static int print_device_sinks(AVOutputFormat *fmt, AVDictionary *opts) if (!fmt || !fmt->priv_class || !AV_IS_OUTPUT_DEVICE(fmt->priv_class->category)) return AVERROR(EINVAL); - printf("Audo-detected sinks for %s:\n", fmt->name); + printf("Auto-detected sinks for %s:\n", fmt->name); if (!fmt->get_device_list) { ret = AVERROR(ENOSYS); printf("Cannot list sinks. Not implemented.\n"); diff --git a/cmdutils.h b/cmdutils.h index 83ea4ad39e..1b96aa48d1 100644 --- a/cmdutils.h +++ b/cmdutils.h @@ -61,6 +61,11 @@ void register_exit(void (*cb)(int ret)); */ void exit_program(int ret) av_noreturn; +/** + * Initialize dynamic library loading + */ +void init_dynload(void); + /** * Initialize the cmdutils option system, in particular * allocate the *_opts contexts. @@ -445,13 +450,13 @@ int show_devices(void *optctx, const char *opt, const char *arg); #if CONFIG_AVDEVICE /** - * Print a listing containing audodetected sinks of the output device. + * Print a listing containing autodetected sinks of the output device. * Device name with options may be passed as an argument to limit results. */ int show_sinks(void *optctx, const char *opt, const char *arg); /** - * Print a listing containing audodetected sources of the input device. + * Print a listing containing autodetected sources of the input device. * Device name with options may be passed as an argument to limit results. */ int show_sources(void *optctx, const char *opt, const char *arg); diff --git a/configure b/configure index 2148f11044..ee88da5d38 100755 --- a/configure +++ b/configure @@ -913,6 +913,25 @@ void foo(void){ __asm__ volatile($code); } EOF } +check_inline_asm_flags(){ + log check_inline_asm_flags "$@" + name="$1" + code="$2" + flags='' + shift 2 + while [ "$1" != "" ]; do + append flags $1 + shift + done; + disable $name + cat > $TMPC < /dev/null 2>&1 && enable makeinfo || disable makeinfo enabled makeinfo \ @@ -5935,11 +5930,7 @@ elif enabled ccc; then add_cflags -msg_disable nonstandcast add_cflags -msg_disable unsupieee elif enabled gcc; then - case $gcc_basever in - 4.9*) enabled x86 || check_optflags -fno-tree-vectorize ;; - 4.*) check_optflags -fno-tree-vectorize ;; - *) enabled x86 || check_optflags -fno-tree-vectorize ;; - esac + check_optflags -fno-tree-vectorize check_cflags -Werror=format-security check_cflags -Werror=implicit-function-declaration check_cflags -Werror=missing-prototypes @@ -6004,6 +5995,7 @@ __declspec($_restrict) void* foo(int); EOF fi check_func strtoll || add_cflags -Dstrtoll=_strtoi64 + check_func strtoull || add_cflags -Dstrtoull=_strtoui64 fi for pfx in "" host_; do @@ -6420,7 +6412,7 @@ cat > $TMPH <coded_picture_number, - av_ts2timestr(frame->pts, &video_dec_ctx->time_base)); + video_frame_count++, frame->coded_picture_number); /* copy decoded frame to destination buffer: * this is required since rawvideo expects non aligned data */ diff --git a/doc/ffmpeg.texi b/doc/ffmpeg.texi index e02807cb47..2ee81c283e 100644 --- a/doc/ffmpeg.texi +++ b/doc/ffmpeg.texi @@ -12,7 +12,7 @@ @chapter Synopsis -ffmpeg [@var{global_options}] @{[@var{input_file_options}] -i @file{input_file}@} ... @{[@var{output_file_options}] @file{output_file}@} ... +ffmpeg [@var{global_options}] @{[@var{input_file_options}] -i @file{input_url}@} ... @{[@var{output_file_options}] @file{output_url}@} ... @chapter Description @c man begin DESCRIPTION @@ -24,10 +24,10 @@ rates and resize video on the fly with a high quality polyphase filter. @command{ffmpeg} reads from an arbitrary number of input "files" (which can be regular files, pipes, network streams, grabbing devices, etc.), specified by the @code{-i} option, and writes to an arbitrary number of output "files", which are -specified by a plain output filename. Anything found on the command line which -cannot be interpreted as an option is considered to be an output filename. +specified by a plain output url. Anything found on the command line which +cannot be interpreted as an option is considered to be an output url. -Each input or output file can, in principle, contain any number of streams of +Each input or output url can, in principle, contain any number of streams of different types (video/audio/subtitle/attachment/data). The allowed number and/or types of streams may be limited by the container format. Selecting which streams from which inputs will go into which output is either done automatically @@ -243,8 +243,8 @@ Force input or output file format. The format is normally auto detected for inpu files and guessed from the file extension for output files, so this option is not needed in most cases. -@item -i @var{filename} (@emph{input}) -input file name +@item -i @var{url} (@emph{input}) +input file url @item -y (@emph{global}) Overwrite output files without asking. @@ -281,7 +281,7 @@ libx264, and the 138th audio, which will be encoded with libvorbis. When used as an input option (before @code{-i}), limit the @var{duration} of data read from the input file. -When used as an output option (before an output filename), stop writing the +When used as an output option (before an output url), stop writing the output after its duration reaches @var{duration}. @var{duration} must be a time duration specification, @@ -310,7 +310,7 @@ extra segment between the seek point and @var{position} will be decoded and discarded. When doing stream copy or when @option{-noaccurate_seek} is used, it will be preserved. -When used as an output option (before an output filename), decodes but discards +When used as an output option (before an output url), decodes but discards input until the timestamps reach @var{position}. @var{position} must be a time duration specification, @@ -1129,7 +1129,7 @@ may be reassigned to a different value. For example, to set the stream 0 PID to 33 and the stream 1 PID to 36 for an output mpegts file: @example -ffmpeg -i infile -streamid 0:33 -streamid 1:36 out.ts +ffmpeg -i inurl -streamid 0:33 -streamid 1:36 out.ts @end example @item -bsf[:@var{stream_specifier}] @var{bitstream_filters} (@emph{output,per-stream}) diff --git a/doc/ffplay.texi b/doc/ffplay.texi index 4bc3ced39a..073b457256 100644 --- a/doc/ffplay.texi +++ b/doc/ffplay.texi @@ -12,7 +12,7 @@ @chapter Synopsis -ffplay [@var{options}] [@file{input_file}] +ffplay [@var{options}] [@file{input_url}] @chapter Description @c man begin DESCRIPTION @@ -106,8 +106,8 @@ the input audio. Use the option "-filters" to show all the available filters (including sources and sinks). -@item -i @var{input_file} -Read @var{input_file}. +@item -i @var{input_url} +Read @var{input_url}. @end table @section Advanced options diff --git a/doc/ffprobe.texi b/doc/ffprobe.texi index 2024eed4e5..26530a9962 100644 --- a/doc/ffprobe.texi +++ b/doc/ffprobe.texi @@ -12,7 +12,7 @@ @chapter Synopsis -ffprobe [@var{options}] [@file{input_file}] +ffprobe [@var{options}] [@file{input_url}] @chapter Description @c man begin DESCRIPTION @@ -24,8 +24,8 @@ For example it can be used to check the format of the container used by a multimedia stream and the format and type of each media stream contained in it. -If a filename is specified in input, ffprobe will try to open and -probe the file content. If the file cannot be opened or recognized as +If a url is specified in input, ffprobe will try to open and +probe the url content. If the url cannot be opened or recognized as a multimedia file, a positive exit code is returned. ffprobe may be employed both as a standalone application or in @@ -332,8 +332,8 @@ with name "PIXEL_FORMAT". Force bitexact output, useful to produce output which is not dependent on the specific build. -@item -i @var{input_file} -Read @var{input_file}. +@item -i @var{input_url} +Read @var{input_url}. @end table @c man end diff --git a/doc/filters.texi b/doc/filters.texi index 68f54f19b0..e46b7822c4 100644 --- a/doc/filters.texi +++ b/doc/filters.texi @@ -7276,7 +7276,7 @@ It accepts the following parameters: @item filter_name The name of the frei0r effect to load. If the environment variable @env{FREI0R_PATH} is defined, the frei0r effect is searched for in each of the -directories specified by the colon-separated list in @env{FREIOR_PATH}. +directories specified by the colon-separated list in @env{FREI0R_PATH}. Otherwise, the standard frei0r paths are searched, in this order: @file{HOME/.frei0r-1/lib/}, @file{/usr/local/lib/frei0r-1/}, @file{/usr/lib/frei0r-1/}. @@ -10598,7 +10598,7 @@ uses the reference video instead of the main input as basis. @itemize @item -Scale a subtitle stream to match the main video in size before overlaying +Scale a subtitle stream (b) to match the main video (a) in size before overlaying @example 'scale2ref[b][a];[a][b]overlay' @end example diff --git a/doc/formats.texi b/doc/formats.texi index 617cda54a9..b62ca43dd7 100644 --- a/doc/formats.texi +++ b/doc/formats.texi @@ -205,6 +205,10 @@ For example to separate the fields with newlines and indention: ffprobe -dump_separator " " -i ~/videos/matrixbench_mpeg2.mpg @end example + +@item max_streams @var{integer} (@emph{input}) +Specifies the maximum number of streams. This can be used to reject files that +would require too many resources due to a large number of streams. @end table @c man end FORMAT OPTIONS diff --git a/doc/general.texi b/doc/general.texi index 59ea4f44d9..df16c3e97f 100644 --- a/doc/general.texi +++ b/doc/general.texi @@ -950,7 +950,7 @@ following image formats are supported: @item COOK @tab @tab X @tab All versions except 5.1 are supported. @item DCA (DTS Coherent Acoustics) @tab X @tab X - @tab supported extensions: XCh, XLL (partially) + @tab supported extensions: XCh, XXCH, X96, XBR, XLL @item DPCM id RoQ @tab X @tab X @tab Used in Quake III, Jedi Knight 2 and other computer games. @item DPCM Interplay @tab @tab X diff --git a/doc/utils.texi b/doc/utils.texi index 756c609072..7aea460609 100644 --- a/doc/utils.texi +++ b/doc/utils.texi @@ -869,7 +869,7 @@ Return 1 if @var{x} is lesser than or equal to @var{y}, 0 otherwise. Return the maximum between @var{x} and @var{y}. @item min(x, y) -Return the maximum between @var{x} and @var{y}. +Return the minimum between @var{x} and @var{y}. @item mod(x, y) Compute the remainder of division of @var{x} by @var{y}. diff --git a/ffmpeg.c b/ffmpeg.c index a5ec3c3833..11d4c1703d 100644 --- a/ffmpeg.c +++ b/ffmpeg.c @@ -2014,12 +2014,7 @@ static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output) } } - /* if the decoder provides a pts, use it instead of the last packet pts. - the decoder could be delaying output by a packet or more. */ - if (decoded_frame->pts != AV_NOPTS_VALUE) { - ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q); - decoded_frame_tb = avctx->time_base; - } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) { + if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) { decoded_frame->pts = decoded_frame->pkt_pts; decoded_frame_tb = ist->st->time_base; } else if (pkt->pts != AV_NOPTS_VALUE) { @@ -2387,8 +2382,12 @@ static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eo ist->dts = ist->next_dts; switch (ist->dec_ctx->codec_type) { case AVMEDIA_TYPE_AUDIO: - ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) / - ist->dec_ctx->sample_rate; + if (ist->dec_ctx->sample_rate) { + ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) / + ist->dec_ctx->sample_rate; + } else { + ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q); + } break; case AVMEDIA_TYPE_VIDEO: if (ist->framerate.num) { @@ -2893,7 +2892,8 @@ static int transcode_init(void) * overhead */ if(!strcmp(oc->oformat->name, "avi")) { - if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate) + if ( copy_tb<0 && ist->st->r_frame_rate.num + && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate) && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base) && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(dec_ctx->time_base) && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500 @@ -4267,6 +4267,8 @@ int main(int argc, char **argv) int ret; int64_t ti; + init_dynload(); + register_exit(ffmpeg_cleanup); setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */ diff --git a/ffmpeg_opt.c b/ffmpeg_opt.c index bc8355e2bf..304a4d4d66 100644 --- a/ffmpeg_opt.c +++ b/ffmpeg_opt.c @@ -2989,8 +2989,8 @@ enum OptGroup { }; static const OptionGroupDef groups[] = { - [GROUP_OUTFILE] = { "output file", NULL, OPT_OUTPUT }, - [GROUP_INFILE] = { "input file", "i", OPT_INPUT }, + [GROUP_OUTFILE] = { "output url", NULL, OPT_OUTPUT }, + [GROUP_INFILE] = { "input url", "i", OPT_INPUT }, }; static int open_files(OptionGroupList *l, const char *inout, diff --git a/ffplay.c b/ffplay.c index 2cfdf26ee9..22c530bb87 100644 --- a/ffplay.c +++ b/ffplay.c @@ -2730,7 +2730,7 @@ static int stream_component_open(VideoState *is, int stream_index) goto fail; link = is->out_audio_filter->inputs[0]; sample_rate = link->sample_rate; - nb_channels = link->channels; + nb_channels = avfilter_link_get_channels(link); channel_layout = link->channel_layout; } #else @@ -2931,7 +2931,7 @@ static int read_thread(void *arg) AVStream *st = ic->streams[i]; enum AVMediaType type = st->codec->codec_type; st->discard = AVDISCARD_ALL; - if (wanted_stream_spec[type] && st_index[type] == -1) + if (type >= 0 && wanted_stream_spec[type] && st_index[type] == -1) if (avformat_match_stream_specifier(ic, st, wanted_stream_spec[type]) > 0) st_index[type] = i; } @@ -3771,6 +3771,8 @@ int main(int argc, char **argv) VideoState *is; char dummy_videodriver[] = "SDL_VIDEODRIVER=dummy"; + init_dynload(); + av_log_set_flags(AV_LOG_SKIP_REPEATED); parse_loglevel(argc, argv, options); diff --git a/ffprobe.c b/ffprobe.c index f7b51adda2..6a0e9aebc6 100644 --- a/ffprobe.c +++ b/ffprobe.c @@ -1746,6 +1746,57 @@ static inline int show_tags(WriterContext *w, AVDictionary *tags, int section_id return ret; } + +static void print_color_range(WriterContext *w, enum AVColorRange color_range, const char *fallback) +{ + const char *val = av_color_range_name(color_range); + if (!val || color_range == AVCOL_RANGE_UNSPECIFIED) { + print_str_opt("color_range", fallback); + } else { + print_str("color_range", val); + } +} + +static void print_color_space(WriterContext *w, enum AVColorSpace color_space) +{ + const char *val = av_color_space_name(color_space); + if (!val || color_space == AVCOL_SPC_UNSPECIFIED) { + print_str_opt("color_space", "unknown"); + } else { + print_str("color_space", val); + } +} + +static void print_primaries(WriterContext *w, enum AVColorPrimaries color_primaries) +{ + const char *val = av_color_primaries_name(color_primaries); + if (!val || color_primaries == AVCOL_PRI_UNSPECIFIED) { + print_str_opt("color_primaries", "unknown"); + } else { + print_str("color_primaries", val); + } +} + +static void print_color_trc(WriterContext *w, enum AVColorTransferCharacteristic color_trc) +{ + const char *val = av_color_transfer_name(color_trc); + if (!val || color_trc == AVCOL_TRC_UNSPECIFIED) { + print_str_opt("color_transfer", "unknown"); + } else { + print_str("color_transfer", val); + } +} + +static void print_chroma_location(WriterContext *w, enum AVChromaLocation chroma_location) +{ + const char *val = av_chroma_location_name(chroma_location); + if (!val || chroma_location == AVCHROMA_LOC_UNSPECIFIED) { + print_str_opt("chroma_location", "unspecified"); + } else { + print_str("chroma_location", val); + } +} + static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx) { char val_str[128]; @@ -2208,28 +2259,12 @@ static int show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_id if (s) print_str ("pix_fmt", s); else print_str_opt("pix_fmt", "unknown"); print_int("level", dec_ctx->level); - if (dec_ctx->color_range != AVCOL_RANGE_UNSPECIFIED) - print_str ("color_range", av_color_range_name(dec_ctx->color_range)); - else - print_str_opt("color_range", "N/A"); - s = av_get_colorspace_name(dec_ctx->colorspace); - if (s) print_str ("color_space", s); - else print_str_opt("color_space", "unknown"); - if (dec_ctx->color_trc != AVCOL_TRC_UNSPECIFIED) - print_str("color_transfer", av_color_transfer_name(dec_ctx->color_trc)); - else - print_str_opt("color_transfer", av_color_transfer_name(dec_ctx->color_trc)); - - if (dec_ctx->color_primaries != AVCOL_PRI_UNSPECIFIED) - print_str("color_primaries", av_color_primaries_name(dec_ctx->color_primaries)); - else - print_str_opt("color_primaries", av_color_primaries_name(dec_ctx->color_primaries)); - - if (dec_ctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) - print_str("chroma_location", av_chroma_location_name(dec_ctx->chroma_sample_location)); - else - print_str_opt("chroma_location", av_chroma_location_name(dec_ctx->chroma_sample_location)); + print_color_range(w, dec_ctx->color_range, "N/A"); + print_color_space(w, dec_ctx->colorspace); + print_color_trc(w, dec_ctx->color_trc); + print_primaries(w, dec_ctx->color_primaries); + print_chroma_location(w, dec_ctx->chroma_sample_location); #if FF_API_PRIVATE_OPT if (dec_ctx->timecode_frame_start >= 0) { @@ -3178,6 +3213,8 @@ int main(int argc, char **argv) char *w_name = NULL, *w_args = NULL; int ret, i; + init_dynload(); + av_log_set_flags(AV_LOG_SKIP_REPEATED); register_exit(ffprobe_cleanup); diff --git a/ffserver.c b/ffserver.c index bc7dbee760..5ce439a0df 100644 --- a/ffserver.c +++ b/ffserver.c @@ -373,8 +373,8 @@ static void ffm_set_write_index(AVFormatContext *s, int64_t pos, int64_t file_size) { av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN); - av_opt_set_int(s, "write_index", pos, AV_OPT_SEARCH_CHILDREN); - av_opt_set_int(s, "file_size", file_size, AV_OPT_SEARCH_CHILDREN); + av_opt_set_int(s, "ffm_write_index", pos, AV_OPT_SEARCH_CHILDREN); + av_opt_set_int(s, "ffm_file_size", file_size, AV_OPT_SEARCH_CHILDREN); } static char *ctime1(char *buf2, size_t buf_size) @@ -2701,8 +2701,10 @@ static int http_receive_data(HTTPContext *c) } else if (c->buffer_ptr - c->buffer >= 2 && !memcmp(c->buffer_ptr - 1, "\r\n", 2)) { c->chunk_size = strtol(c->buffer, 0, 16); - if (c->chunk_size == 0) // end of stream + if (c->chunk_size <= 0) { // end of stream or invalid chunk size + c->chunk_size = 0; goto fail; + } c->buffer_ptr = c->buffer; break; } else if (++loop_run > 10) @@ -2724,6 +2726,7 @@ static int http_receive_data(HTTPContext *c) /* end of connection : close it */ goto fail; else { + av_assert0(len <= c->chunk_size); c->chunk_size -= len; c->buffer_ptr += len; c->data_count += len; @@ -3858,6 +3861,8 @@ drop: if (avformat_write_header(s, NULL) < 0) { http_log("Container doesn't support the required parameters\n"); avio_closep(&s->pb); + s->streams = NULL; + s->nb_streams = 0; avformat_free_context(s); goto bail; } @@ -3973,6 +3978,7 @@ int main(int argc, char **argv) int cfg_parsed; int ret = EXIT_FAILURE; + init_dynload(); config.filename = av_strdup("/etc/ffserver.conf"); diff --git a/libavcodec/8bps.c b/libavcodec/8bps.c index 2e4464dbb4..14f7bd5bf6 100644 --- a/libavcodec/8bps.c +++ b/libavcodec/8bps.c @@ -120,12 +120,15 @@ static int decode_frame(AVCodecContext *avctx, void *data, } if (avctx->bits_per_coded_sample <= 8) { + int size; const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, - NULL); - if (pal) { + &size); + if (pal && size == AVPALETTE_SIZE) { frame->palette_has_changed = 1; memcpy(c->pal, pal, AVPALETTE_SIZE); + } else if (pal) { + av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", size); } memcpy (frame->data[1], c->pal, AVPALETTE_SIZE); diff --git a/libavcodec/aac_defines.h b/libavcodec/aac_defines.h index eff63b347c..8a54a666f9 100644 --- a/libavcodec/aac_defines.h +++ b/libavcodec/aac_defines.h @@ -35,6 +35,7 @@ #define AAC_RENAME(x) x ## _fixed #define AAC_RENAME_32(x) x ## _fixed_32 typedef int INTFLOAT; +typedef unsigned UINTFLOAT; ///< Equivalent to INTFLOAT, Used as temporal cast to avoid undefined sign overflow operations. typedef int64_t INT64FLOAT; typedef int16_t SHORTFLOAT; typedef SoftFloat AAC_FLOAT; @@ -45,7 +46,7 @@ typedef int AAC_SIGNE; #define Q30(x) (int)((x)*1073741824.0 + 0.5) #define Q31(x) (int)((x)*2147483648.0 + 0.5) #define RANGE15(x) x -#define GET_GAIN(x, y) (-(y) << (x)) + 1024 +#define GET_GAIN(x, y) (-(y) * (1 << (x))) + 1024 #define AAC_MUL16(x, y) (int)(((int64_t)(x) * (y) + 0x8000) >> 16) #define AAC_MUL26(x, y) (int)(((int64_t)(x) * (y) + 0x2000000) >> 26) #define AAC_MUL30(x, y) (int)(((int64_t)(x) * (y) + 0x20000000) >> 30) @@ -72,7 +73,7 @@ typedef int AAC_SIGNE; #define AAC_MSUB31_V3(x, y, z) (int)((((int64_t)(x) * (z)) - \ ((int64_t)(y) * (z)) + \ 0x40000000) >> 31) -#define AAC_HALF_SUM(x, y) (x) >> 1 + (y) >> 1 +#define AAC_HALF_SUM(x, y) (((x) >> 1) + ((y) >> 1)) #define AAC_SRA_R(x, y) (int)(((x) + (1 << ((y) - 1))) >> (y)) #else @@ -83,6 +84,7 @@ typedef int AAC_SIGNE; #define AAC_RENAME(x) x #define AAC_RENAME_32(x) x typedef float INTFLOAT; +typedef float UINTFLOAT; typedef float INT64FLOAT; typedef float SHORTFLOAT; typedef float AAC_FLOAT; diff --git a/libavcodec/aacdec.c b/libavcodec/aacdec.c index 26bdea1ecc..708779312c 100644 --- a/libavcodec/aacdec.c +++ b/libavcodec/aacdec.c @@ -424,6 +424,8 @@ static int read_payload_length_info(struct LATMContext *ctx, GetBitContext *gb) if (ctx->frame_length_type == 0) { int mux_slot_length = 0; do { + if (get_bits_left(gb) < 8) + return AVERROR_INVALIDDATA; tmp = get_bits(gb, 8); mux_slot_length += tmp; } while (tmp == 255); @@ -453,7 +455,7 @@ static int read_audio_mux_element(struct LATMContext *latmctx, } if (latmctx->audio_mux_version_A == 0) { int mux_slot_length_bytes = read_payload_length_info(latmctx, gb); - if (mux_slot_length_bytes * 8 > get_bits_left(gb)) { + if (mux_slot_length_bytes < 0 || mux_slot_length_bytes * 8LL > get_bits_left(gb)) { av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n"); return AVERROR_INVALIDDATA; } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) { diff --git a/libavcodec/aacdec_fixed.c b/libavcodec/aacdec_fixed.c index 396a874d95..795397febe 100644 --- a/libavcodec/aacdec_fixed.c +++ b/libavcodec/aacdec_fixed.c @@ -125,7 +125,7 @@ static inline int *DEC_SQUAD(int *dst, unsigned idx) static inline int *DEC_UPAIR(int *dst, unsigned idx, unsigned sign) { dst[0] = (idx & 15) * (1 - (sign & 0xFFFFFFFE)); - dst[1] = (idx >> 4 & 15) * (1 - ((sign & 1) << 1)); + dst[1] = (idx >> 4 & 15) * (1 - ((sign & 1) * 2)); return dst + 2; } @@ -134,16 +134,16 @@ static inline int *DEC_UQUAD(int *dst, unsigned idx, unsigned sign) { unsigned nz = idx >> 12; - dst[0] = (idx & 3) * (1 + (((int)sign >> 31) << 1)); + dst[0] = (idx & 3) * (1 + (((int)sign >> 31) * 2)); sign <<= nz & 1; nz >>= 1; - dst[1] = (idx >> 2 & 3) * (1 + (((int)sign >> 31) << 1)); + dst[1] = (idx >> 2 & 3) * (1 + (((int)sign >> 31) * 2)); sign <<= nz & 1; nz >>= 1; - dst[2] = (idx >> 4 & 3) * (1 + (((int)sign >> 31) << 1)); + dst[2] = (idx >> 4 & 3) * (1 + (((int)sign >> 31) * 2)); sign <<= nz & 1; nz >>= 1; - dst[3] = (idx >> 6 & 3) * (1 + (((int)sign >> 31) << 1)); + dst[3] = (idx >> 6 & 3) * (1 + (((int)sign >> 31) * 2)); return dst + 4; } @@ -171,20 +171,25 @@ static void subband_scale(int *dst, int *src, int scale, int offset, int len) s = offset - (s >> 2); - if (s > 0) { + if (s > 31) { + for (i=0; i 0) { round = 1 << (s-1); for (i=0; i> 32); dst[i] = ((int)(out+round) >> s) * ssign; } - } - else { + } else if (s > -32) { s = s + 32; round = 1 << (s-1); for (i=0; i> s); - dst[i] = out * ssign; + dst[i] = out * (unsigned)ssign; } + } else { + av_log(NULL, AV_LOG_ERROR, "Overflow in subband_scale()\n"); } } @@ -203,8 +208,12 @@ static void noise_scale(int *coefs, int scale, int band_energy, int len) c /= band_energy; s = 21 + nlz - (s >> 2); - if (s > 0) { - round = 1 << (s-1); + if (s > 31) { + for (i=0; i= 0) { + round = s ? 1 << (s-1) : 0; for (i=0; i> 32); coefs[i] = ((int)(out+round) >> s) * ssign; @@ -296,8 +305,12 @@ static av_always_inline void predict(PredictorState *ps, int *coef, if (output_enable) { int shift = 28 - pv.exp; - if (shift < 31) - *coef += (pv.mant + (1 << (shift - 1))) >> shift; + if (shift < 31) { + if (shift > 0) { + *coef += (unsigned)((pv.mant + (1 << (shift - 1))) >> shift); + } else + *coef += (unsigned)pv.mant << -shift; + } } e0 = av_int2sf(*coef, 2); @@ -362,7 +375,9 @@ static void apply_dependent_coupling_fixed(AACContext *ac, shift = (gain-1024) >> 3; } - if (shift < 0) { + if (shift < -31) { + // Nothing to do + } else if (shift < 0) { shift = -shift; round = 1 << (shift - 1); @@ -370,7 +385,7 @@ static void apply_dependent_coupling_fixed(AACContext *ac, for (k = offsets[i]; k < offsets[i + 1]; k++) { tmp = (int)(((int64_t)src[group * 128 + k] * c + \ (int64_t)0x1000000000) >> 37); - dest[group * 128 + k] += (tmp + round) >> shift; + dest[group * 128 + k] += (tmp + (int64_t)round) >> shift; } } } @@ -379,7 +394,7 @@ static void apply_dependent_coupling_fixed(AACContext *ac, for (k = offsets[i]; k < offsets[i + 1]; k++) { tmp = (int)(((int64_t)src[group * 128 + k] * c + \ (int64_t)0x1000000000) >> 37); - dest[group * 128 + k] += tmp << shift; + dest[group * 128 + k] += tmp * (1U << shift); } } } @@ -402,7 +417,7 @@ static void apply_independent_coupling_fixed(AACContext *ac, int i, c, shift, round, tmp; const int gain = cce->coup.gain[index][0]; const int *src = cce->ch[0].ret; - int *dest = target->ret; + unsigned int *dest = target->ret; const int len = 1024 << (ac->oc[1].m4ac.sbr == 1); c = cce_scale_fixed[gain & 7]; @@ -419,7 +434,7 @@ static void apply_independent_coupling_fixed(AACContext *ac, else { for (i = 0; i < len; i++) { tmp = (int)(((int64_t)src[i] * c + (int64_t)0x1000000000) >> 37); - dest[i] += tmp << shift; + dest[i] += tmp * (1U << shift); } } } diff --git a/libavcodec/aacdec_template.c b/libavcodec/aacdec_template.c index 6bc94c879a..f21d215c9e 100644 --- a/libavcodec/aacdec_template.c +++ b/libavcodec/aacdec_template.c @@ -1255,6 +1255,8 @@ static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics, const MPEG4AudioConfig *const m4ac = &ac->oc[1].m4ac; const int aot = m4ac->object_type; const int sampling_index = m4ac->sampling_index; + int ret_fail = AVERROR_INVALIDDATA; + if (aot != AOT_ER_AAC_ELD) { if (get_bits1(gb)) { av_log(ac->avctx, AV_LOG_ERROR, "Reserved bit set.\n"); @@ -1305,8 +1307,10 @@ static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics, ics->num_swb = ff_aac_num_swb_512[sampling_index]; ics->tns_max_bands = ff_tns_max_bands_512[sampling_index]; } - if (!ics->num_swb || !ics->swb_offset) - return AVERROR_BUG; + if (!ics->num_swb || !ics->swb_offset) { + ret_fail = AVERROR_BUG; + goto fail; + } } else { ics->swb_offset = ff_swb_offset_1024[sampling_index]; ics->num_swb = ff_aac_num_swb_1024[sampling_index]; @@ -1330,7 +1334,8 @@ static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics, if (aot == AOT_ER_AAC_LD) { av_log(ac->avctx, AV_LOG_ERROR, "LTP in ER AAC LD not yet implemented.\n"); - return AVERROR_PATCHWELCOME; + ret_fail = AVERROR_PATCHWELCOME; + goto fail; } if ((ics->ltp.present = get_bits(gb, 1))) decode_ltp(&ics->ltp, gb, ics->max_sfb); @@ -1349,7 +1354,7 @@ static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics, return 0; fail: ics->max_sfb = 0; - return AVERROR_INVALIDDATA; + return ret_fail; } /** @@ -1936,16 +1941,17 @@ static int decode_ics(AACContext *ac, SingleChannelElement *sce, global_gain = get_bits(gb, 8); if (!common_window && !scale_flag) { - if (decode_ics_info(ac, ics, gb) < 0) - return AVERROR_INVALIDDATA; + ret = decode_ics_info(ac, ics, gb); + if (ret < 0) + goto fail; } if ((ret = decode_band_types(ac, sce->band_type, sce->band_type_run_end, gb, ics)) < 0) - return ret; + goto fail; if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics, sce->band_type, sce->band_type_run_end)) < 0) - return ret; + goto fail; pulse_present = 0; if (!scale_flag) { @@ -1953,37 +1959,48 @@ static int decode_ics(AACContext *ac, SingleChannelElement *sce, if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) { av_log(ac->avctx, AV_LOG_ERROR, "Pulse tool not allowed in eight short sequence.\n"); - return AVERROR_INVALIDDATA; + ret = AVERROR_INVALIDDATA; + goto fail; } if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) { av_log(ac->avctx, AV_LOG_ERROR, "Pulse data corrupt or invalid.\n"); - return AVERROR_INVALIDDATA; + ret = AVERROR_INVALIDDATA; + goto fail; } } tns->present = get_bits1(gb); - if (tns->present && !er_syntax) - if (decode_tns(ac, tns, gb, ics) < 0) - return AVERROR_INVALIDDATA; + if (tns->present && !er_syntax) { + ret = decode_tns(ac, tns, gb, ics); + if (ret < 0) + goto fail; + } if (!eld_syntax && get_bits1(gb)) { avpriv_request_sample(ac->avctx, "SSR"); - return AVERROR_PATCHWELCOME; + ret = AVERROR_PATCHWELCOME; + goto fail; } // I see no textual basis in the spec for this occurring after SSR gain // control, but this is what both reference and real implmentations do - if (tns->present && er_syntax) - if (decode_tns(ac, tns, gb, ics) < 0) - return AVERROR_INVALIDDATA; + if (tns->present && er_syntax) { + ret = decode_tns(ac, tns, gb, ics); + if (ret < 0) + goto fail; + } } - if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, - &pulse, ics, sce->band_type) < 0) - return AVERROR_INVALIDDATA; + ret = decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present, + &pulse, ics, sce->band_type); + if (ret < 0) + goto fail; if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window) apply_prediction(ac, sce); return 0; +fail: + tns->present = 0; + return ret; } /** @@ -2155,7 +2172,11 @@ static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che) coup->coupling_point += get_bits1(gb) || (coup->coupling_point >> 1); sign = get_bits(gb, 1); - scale = AAC_RENAME(cce_scale)[get_bits(gb, 2)]; +#if USE_FIXED + scale = get_bits(gb, 2); +#else + scale = cce_scale[get_bits(gb, 2)]; +#endif if ((ret = decode_ics(ac, sce, gb, 0, 0))) return ret; @@ -2169,6 +2190,10 @@ static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che) cge = coup->coupling_point == AFTER_IMDCT ? 1 : get_bits1(gb); gain = cge ? get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60: 0; gain_cache = GET_GAIN(scale, gain); +#if USE_FIXED + if ((abs(gain_cache)-1024) >> 3 > 30) + return AVERROR(ERANGE); +#endif } if (coup->coupling_point == AFTER_IMDCT) { coup->gain[c][0] = gain_cache; @@ -2186,6 +2211,10 @@ static int decode_cce(AACContext *ac, GetBitContext *gb, ChannelElement *che) t >>= 1; } gain_cache = GET_GAIN(scale, t) * s; +#if USE_FIXED + if ((abs(gain_cache)-1024) >> 3 > 30) + return AVERROR(ERANGE); +#endif } } coup->gain[c][idx] = gain_cache; @@ -2359,7 +2388,7 @@ static int decode_extension_payload(AACContext *ac, GetBitContext *gb, int cnt, * @param decode 1 if tool is used normally, 0 if tool is used in LTP. * @param coef spectral coefficients */ -static void apply_tns(INTFLOAT coef[1024], TemporalNoiseShaping *tns, +static void apply_tns(INTFLOAT coef_param[1024], TemporalNoiseShaping *tns, IndividualChannelStream *ics, int decode) { const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb); @@ -2367,6 +2396,7 @@ static void apply_tns(INTFLOAT coef[1024], TemporalNoiseShaping *tns, int bottom, top, order, start, end, size, inc; INTFLOAT lpc[TNS_MAX_ORDER]; INTFLOAT tmp[TNS_MAX_ORDER+1]; + UINTFLOAT *coef = coef_param; for (w = 0; w < ics->num_windows; w++) { bottom = ics->num_swb; @@ -2396,7 +2426,7 @@ static void apply_tns(INTFLOAT coef[1024], TemporalNoiseShaping *tns, // ar filter for (m = 0; m < size; m++, start += inc) for (i = 1; i <= FFMIN(m, order); i++) - coef[start] -= AAC_MUL26(coef[start - i * inc], lpc[i - 1]); + coef[start] -= AAC_MUL26((INTFLOAT)coef[start - i * inc], lpc[i - 1]); } else { // ma filter for (m = 0; m < size; m++, start += inc) { @@ -2466,7 +2496,7 @@ static void apply_ltp(AACContext *ac, SingleChannelElement *sce) for (sfb = 0; sfb < FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB); sfb++) if (ltp->used[sfb]) for (i = offsets[sfb]; i < offsets[sfb + 1]; i++) - sce->coeffs[i] += predFreq[i]; + sce->coeffs[i] += (UINTFLOAT)predFreq[i]; } } diff --git a/libavcodec/aacenc.c b/libavcodec/aacenc.c index 5a70da1764..51b90e98b5 100644 --- a/libavcodec/aacenc.c +++ b/libavcodec/aacenc.c @@ -609,8 +609,8 @@ static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, } for (k = 0; k < 1024; k++) { - if (!isfinite(cpe->ch[ch].coeffs[k])) { - av_log(avctx, AV_LOG_ERROR, "Input contains NaN/+-Inf\n"); + if (!(fabs(cpe->ch[ch].coeffs[k]) < 1E16)) { // Ensure headroom for energy calculation + av_log(avctx, AV_LOG_ERROR, "Input contains (near) NaN/+-Inf\n"); return AVERROR(EINVAL); } } diff --git a/libavcodec/aacenc_utils.h b/libavcodec/aacenc_utils.h index cb5bc8da12..07f733746b 100644 --- a/libavcodec/aacenc_utils.h +++ b/libavcodec/aacenc_utils.h @@ -28,6 +28,7 @@ #ifndef AVCODEC_AACENC_UTILS_H #define AVCODEC_AACENC_UTILS_H +#include "libavutil/internal.h" #include "aac.h" #include "aacenctab.h" #include "aactab.h" @@ -66,13 +67,13 @@ static inline void quantize_bands(int *out, const float *in, const float *scaled const float rounding) { int i; - double qc; for (i = 0; i < size; i++) { - qc = scaled[i] * Q34; - out[i] = (int)FFMIN(qc + rounding, (double)maxval); + float qc = scaled[i] * Q34; + int tmp = (int)FFMIN(qc + rounding, (float)maxval); if (is_signed && in[i] < 0.0f) { - out[i] = -out[i]; + tmp = -tmp; } + out[i] = tmp; } } @@ -90,8 +91,7 @@ static inline float find_max_val(int group_len, int swb_size, const float *scale static inline int find_min_book(float maxval, int sf) { - float Q = ff_aac_pow2sf_tab[POW_SF2_ZERO - sf + SCALE_ONE_POS - SCALE_DIV_512]; - float Q34 = sqrtf(Q * sqrtf(Q)); + float Q34 = ff_aac_pow34sf_tab[POW_SF2_ZERO - sf + SCALE_ONE_POS - SCALE_DIV_512]; int qmaxval, cb; qmaxval = maxval * Q34 + C_QUANT; if (qmaxval >= (FF_ARRAY_ELEMS(aac_maxval_cb))) @@ -123,7 +123,10 @@ static inline float find_form_factor(int group_len, int swb_size, float thresh, if (s >= ethresh) { nzl += 1.0f; } else { - nzl += powf(s / ethresh, nzslope); + if (nzslope == 2.f) + nzl += (s / ethresh) * (s / ethresh); + else + nzl += ff_fast_powf(s / ethresh, nzslope); } } if (e2 > thresh) { diff --git a/libavcodec/aacps.c b/libavcodec/aacps.c index ccc79ffc1d..aa0220b147 100644 --- a/libavcodec/aacps.c +++ b/libavcodec/aacps.c @@ -499,13 +499,13 @@ static void map_idx_34_to_20(int8_t *par_mapped, const int8_t *par, int full) static void map_val_34_to_20(INTFLOAT par[PS_MAX_NR_IIDICC]) { #if USE_FIXED - par[ 0] = (int)(((int64_t)(par[ 0] + (par[ 1]>>1)) * 1431655765 + \ + par[ 0] = (int)(((int64_t)(par[ 0] + (unsigned)(par[ 1]>>1)) * 1431655765 + \ 0x40000000) >> 31); - par[ 1] = (int)(((int64_t)((par[ 1]>>1) + par[ 2]) * 1431655765 + \ + par[ 1] = (int)(((int64_t)((par[ 1]>>1) + (unsigned)par[ 2]) * 1431655765 + \ 0x40000000) >> 31); - par[ 2] = (int)(((int64_t)(par[ 3] + (par[ 4]>>1)) * 1431655765 + \ + par[ 2] = (int)(((int64_t)(par[ 3] + (unsigned)(par[ 4]>>1)) * 1431655765 + \ 0x40000000) >> 31); - par[ 3] = (int)(((int64_t)((par[ 4]>>1) + par[ 5]) * 1431655765 + \ + par[ 3] = (int)(((int64_t)((par[ 4]>>1) + (unsigned)par[ 5]) * 1431655765 + \ 0x40000000) >> 31); #else par[ 0] = (2*par[ 0] + par[ 1]) * 0.33333333f; @@ -692,26 +692,17 @@ static void decorrelation(PSContext *ps, INTFLOAT (*out)[32][2], const INTFLOAT for (i = 0; i < NR_PAR_BANDS[is34]; i++) { for (n = n0; n < nL; n++) { int decayed_peak; - int denom; - decayed_peak = (int)(((int64_t)peak_decay_factor * \ peak_decay_nrg[i] + 0x40000000) >> 31); peak_decay_nrg[i] = FFMAX(decayed_peak, power[i][n]); - power_smooth[i] += (power[i][n] - power_smooth[i] + 2) >> 2; - peak_decay_diff_smooth[i] += (peak_decay_nrg[i] - power[i][n] - \ - peak_decay_diff_smooth[i] + 2) >> 2; - denom = peak_decay_diff_smooth[i] + (peak_decay_diff_smooth[i] >> 1); - if (denom > power_smooth[i]) { - int p = power_smooth[i]; - while (denom < 0x40000000) { - denom <<= 1; - p <<= 1; - } - transient_gain[i][n] = p / (denom >> 16); - } - else { - transient_gain[i][n] = 1 << 16; - } + power_smooth[i] += (power[i][n] + 2LL - power_smooth[i]) >> 2; + peak_decay_diff_smooth[i] += (peak_decay_nrg[i] + 2LL - power[i][n] - \ + peak_decay_diff_smooth[i]) >> 2; + + if (peak_decay_diff_smooth[i]) { + transient_gain[i][n] = FFMIN(power_smooth[i]*43691LL / peak_decay_diff_smooth[i], 1<<16); + } else + transient_gain[i][n] = 1 << 16; } } #else @@ -942,7 +933,7 @@ static void stereo_processing(PSContext *ps, INTFLOAT (*l)[32][2], INTFLOAT (*r) int stop = ps->border_position[e+1]; INTFLOAT width = Q30(1.f) / ((stop - start) ? (stop - start) : 1); #if USE_FIXED - width <<= 1; + width = FFMIN(2U*width, INT_MAX); #endif b = k_to_i[k]; h[0][0] = H11[0][e][b]; @@ -975,7 +966,7 @@ static void stereo_processing(PSContext *ps, INTFLOAT (*l)[32][2], INTFLOAT (*r) h_step[1][3] = AAC_MSUB31_V3(H22[1][e+1][b], h[1][3], width); } ps->dsp.stereo_interpolate[!PS_BASELINE && ps->enable_ipdopd]( - l[k] + start + 1, r[k] + start + 1, + l[k] + 1 + start, r[k] + 1 + start, h, h_step, stop - start); } } diff --git a/libavcodec/aacpsdsp_template.c b/libavcodec/aacpsdsp_template.c index 3049ce8b79..b924148e0f 100644 --- a/libavcodec/aacpsdsp_template.c +++ b/libavcodec/aacpsdsp_template.c @@ -129,12 +129,12 @@ static void ps_decorrelate_c(INTFLOAT (*out)[2], INTFLOAT (*delay)[2], INTFLOAT apd_im = in_im; in_re = AAC_MSUB30(link_delay_re, fractional_delay_re, link_delay_im, fractional_delay_im); - in_re -= a_re; + in_re -= (UINTFLOAT)a_re; in_im = AAC_MADD30(link_delay_re, fractional_delay_im, link_delay_im, fractional_delay_re); - in_im -= a_im; - ap_delay[m][n+5][0] = apd_re + AAC_MUL31(ag[m], in_re); - ap_delay[m][n+5][1] = apd_im + AAC_MUL31(ag[m], in_im); + in_im -= (UINTFLOAT)a_im; + ap_delay[m][n+5][0] = apd_re + (UINTFLOAT)AAC_MUL31(ag[m], in_re); + ap_delay[m][n+5][1] = apd_im + (UINTFLOAT)AAC_MUL31(ag[m], in_im); } out[n][0] = AAC_MUL16(transient_gain[n], in_re); out[n][1] = AAC_MUL16(transient_gain[n], in_im); @@ -149,10 +149,10 @@ static void ps_stereo_interpolate_c(INTFLOAT (*l)[2], INTFLOAT (*r)[2], INTFLOAT h1 = h[0][1]; INTFLOAT h2 = h[0][2]; INTFLOAT h3 = h[0][3]; - INTFLOAT hs0 = h_step[0][0]; - INTFLOAT hs1 = h_step[0][1]; - INTFLOAT hs2 = h_step[0][2]; - INTFLOAT hs3 = h_step[0][3]; + UINTFLOAT hs0 = h_step[0][0]; + UINTFLOAT hs1 = h_step[0][1]; + UINTFLOAT hs2 = h_step[0][2]; + UINTFLOAT hs3 = h_step[0][3]; int n; for (n = 0; n < len; n++) { @@ -180,10 +180,10 @@ static void ps_stereo_interpolate_ipdopd_c(INTFLOAT (*l)[2], INTFLOAT (*r)[2], INTFLOAT h01 = h[0][1], h11 = h[1][1]; INTFLOAT h02 = h[0][2], h12 = h[1][2]; INTFLOAT h03 = h[0][3], h13 = h[1][3]; - INTFLOAT hs00 = h_step[0][0], hs10 = h_step[1][0]; - INTFLOAT hs01 = h_step[0][1], hs11 = h_step[1][1]; - INTFLOAT hs02 = h_step[0][2], hs12 = h_step[1][2]; - INTFLOAT hs03 = h_step[0][3], hs13 = h_step[1][3]; + UINTFLOAT hs00 = h_step[0][0], hs10 = h_step[1][0]; + UINTFLOAT hs01 = h_step[0][1], hs11 = h_step[1][1]; + UINTFLOAT hs02 = h_step[0][2], hs12 = h_step[1][2]; + UINTFLOAT hs03 = h_step[0][3], hs13 = h_step[1][3]; int n; for (n = 0; n < len; n++) { diff --git a/libavcodec/aacsbr_fixed.c b/libavcodec/aacsbr_fixed.c index b26314a7eb..a25605800f 100644 --- a/libavcodec/aacsbr_fixed.c +++ b/libavcodec/aacsbr_fixed.c @@ -288,6 +288,8 @@ static void sbr_hf_inverse_filter(SBRDSPContext *dsp, shift = a00.exp; if (shift >= 3) alpha0[k][0] = 0x7fffffff; + else if (shift <= -30) + alpha0[k][0] = 0; else { a00.mant <<= 1; shift = 2-shift; @@ -302,6 +304,8 @@ static void sbr_hf_inverse_filter(SBRDSPContext *dsp, shift = a01.exp; if (shift >= 3) alpha0[k][1] = 0x7fffffff; + else if (shift <= -30) + alpha0[k][1] = 0; else { a01.mant <<= 1; shift = 2-shift; @@ -315,6 +319,8 @@ static void sbr_hf_inverse_filter(SBRDSPContext *dsp, shift = a10.exp; if (shift >= 3) alpha1[k][0] = 0x7fffffff; + else if (shift <= -30) + alpha1[k][0] = 0; else { a10.mant <<= 1; shift = 2-shift; @@ -329,6 +335,8 @@ static void sbr_hf_inverse_filter(SBRDSPContext *dsp, shift = a11.exp; if (shift >= 3) alpha1[k][1] = 0x7fffffff; + else if (shift <= -30) + alpha1[k][1] = 0; else { a11.mant <<= 1; shift = 2-shift; @@ -429,6 +437,7 @@ static void sbr_gain_calc(AACContext *ac, SpectralBandReplication *sbr, av_add_sf(FLOAT_1, sbr->e_curr[e][m]), av_add_sf(FLOAT_1, sbr->q_mapped[e][m])))); } + sbr->gain[e][m] = av_add_sf(sbr->gain[e][m], FLOAT_MIN); } for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) { sum[0] = av_add_sf(sum[0], sbr->e_origmapped[e][m]); @@ -562,25 +571,39 @@ static void sbr_hf_assemble(int Y1[38][64][2], int idx = indexsine&1; int A = (1-((indexsine+(kx & 1))&2)); int B = (A^(-idx)) + idx; - int *out = &Y1[i][kx][idx]; - int shift, round; + unsigned *out = &Y1[i][kx][idx]; + int shift; + unsigned round; SoftFloat *in = sbr->s_m[e]; for (m = 0; m+1 < m_max; m+=2) { - shift = 22 - in[m ].exp; - round = 1 << (shift-1); - out[2*m ] += (in[m ].mant * A + round) >> shift; + int shift2; + shift = 22 - in[m ].exp; + shift2= 22 - in[m+1].exp; + if (shift < 1 || shift2 < 1) { + av_log(NULL, AV_LOG_ERROR, "Overflow in sbr_hf_assemble, shift=%d,%d\n", shift, shift2); + return; + } + if (shift < 32) { + round = 1 << (shift-1); + out[2*m ] += (int)(in[m ].mant * A + round) >> shift; + } - shift = 22 - in[m+1].exp; - round = 1 << (shift-1); - out[2*m+2] += (in[m+1].mant * B + round) >> shift; + if (shift2 < 32) { + round = 1 << (shift2-1); + out[2*m+2] += (int)(in[m+1].mant * B + round) >> shift2; + } } if(m_max&1) { - shift = 22 - in[m ].exp; - round = 1 << (shift-1); - - out[2*m ] += (in[m ].mant * A + round) >> shift; + shift = 22 - in[m ].exp; + if (shift < 1) { + av_log(NULL, AV_LOG_ERROR, "Overflow in sbr_hf_assemble, shift=%d\n", shift); + return; + } else if (shift < 32) { + round = 1 << (shift-1); + out[2*m ] += (int)(in[m ].mant * A + round) >> shift; + } } } indexnoise = (indexnoise + m_max) & 0x1ff; diff --git a/libavcodec/aacsbr_template.c b/libavcodec/aacsbr_template.c index 733e619b78..3dcdcd898d 100644 --- a/libavcodec/aacsbr_template.c +++ b/libavcodec/aacsbr_template.c @@ -623,24 +623,26 @@ static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr, int abs_bord_trail = 16; int num_rel_lead, num_rel_trail; unsigned bs_num_env_old = ch_data->bs_num_env; + int bs_frame_class, bs_num_env; ch_data->bs_freq_res[0] = ch_data->bs_freq_res[ch_data->bs_num_env]; ch_data->bs_amp_res = sbr->bs_amp_res_header; ch_data->t_env_num_env_old = ch_data->t_env[bs_num_env_old]; - switch (ch_data->bs_frame_class = get_bits(gb, 2)) { + switch (bs_frame_class = get_bits(gb, 2)) { case FIXFIX: - ch_data->bs_num_env = 1 << get_bits(gb, 2); + bs_num_env = 1 << get_bits(gb, 2); + if (bs_num_env > 4) { + av_log(ac->avctx, AV_LOG_ERROR, + "Invalid bitstream, too many SBR envelopes in FIXFIX type SBR frame: %d\n", + bs_num_env); + return -1; + } + ch_data->bs_num_env = bs_num_env; num_rel_lead = ch_data->bs_num_env - 1; if (ch_data->bs_num_env == 1) ch_data->bs_amp_res = 0; - if (ch_data->bs_num_env > 4) { - av_log(ac->avctx, AV_LOG_ERROR, - "Invalid bitstream, too many SBR envelopes in FIXFIX type SBR frame: %d\n", - ch_data->bs_num_env); - return -1; - } ch_data->t_env[0] = 0; ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail; @@ -688,14 +690,15 @@ static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr, abs_bord_trail += get_bits(gb, 2); num_rel_lead = get_bits(gb, 2); num_rel_trail = get_bits(gb, 2); - ch_data->bs_num_env = num_rel_lead + num_rel_trail + 1; + bs_num_env = num_rel_lead + num_rel_trail + 1; - if (ch_data->bs_num_env > 5) { + if (bs_num_env > 5) { av_log(ac->avctx, AV_LOG_ERROR, "Invalid bitstream, too many SBR envelopes in VARVAR type SBR frame: %d\n", - ch_data->bs_num_env); + bs_num_env); return -1; } + ch_data->bs_num_env = bs_num_env; ch_data->t_env[ch_data->bs_num_env] = abs_bord_trail; @@ -710,6 +713,7 @@ static int read_sbr_grid(AACContext *ac, SpectralBandReplication *sbr, get_bits1_vector(gb, ch_data->bs_freq_res + 1, ch_data->bs_num_env); break; } + ch_data->bs_frame_class = bs_frame_class; av_assert0(bs_pointer >= 0); if (bs_pointer > ch_data->bs_num_env + 1) { diff --git a/libavcodec/ac3dec.c b/libavcodec/ac3dec.c index 5d5330c4aa..4971abe9f4 100644 --- a/libavcodec/ac3dec.c +++ b/libavcodec/ac3dec.c @@ -744,30 +744,31 @@ static void ac3_upmix_delay(AC3DecodeContext *s) * @param[in] default_band_struct default band structure table * @param[out] num_bands number of bands (optionally NULL) * @param[out] band_sizes array containing the number of bins in each band (optionally NULL) + * @param[in,out] band_struct current band structure */ static void decode_band_structure(GetBitContext *gbc, int blk, int eac3, int ecpl, int start_subband, int end_subband, const uint8_t *default_band_struct, - int *num_bands, uint8_t *band_sizes) + int *num_bands, uint8_t *band_sizes, + uint8_t *band_struct, int band_struct_size) { int subbnd, bnd, n_subbands, n_bands=0; uint8_t bnd_sz[22]; - uint8_t coded_band_struct[22]; - const uint8_t *band_struct; n_subbands = end_subband - start_subband; + if (!blk) + memcpy(band_struct, default_band_struct, band_struct_size); + + av_assert0(band_struct_size >= start_subband + n_subbands); + + band_struct += start_subband + 1; + /* decode band structure from bitstream or use default */ if (!eac3 || get_bits1(gbc)) { for (subbnd = 0; subbnd < n_subbands - 1; subbnd++) { - coded_band_struct[subbnd] = get_bits1(gbc); + band_struct[subbnd] = get_bits1(gbc); } - band_struct = coded_band_struct; - } else if (!blk) { - band_struct = &default_band_struct[start_subband+1]; - } else { - /* no change in band structure */ - return; } /* calculate number of bands and band sizes based on band structure. @@ -894,12 +895,15 @@ static int decode_audio_block(AC3DecodeContext *s, int blk) start_subband, end_subband, ff_eac3_default_spx_band_struct, &s->num_spx_bands, - s->spx_band_sizes); - } else { - for (ch = 1; ch <= fbw_channels; ch++) { - s->channel_uses_spx[ch] = 0; - s->first_spx_coords[ch] = 1; - } + s->spx_band_sizes, + s->spx_band_struct, sizeof(s->spx_band_struct)); + } + } + if (!s->eac3 || !s->spx_in_use) { + s->spx_in_use = 0; + for (ch = 1; ch <= fbw_channels; ch++) { + s->channel_uses_spx[ch] = 0; + s->first_spx_coords[ch] = 1; } } @@ -1026,7 +1030,8 @@ static int decode_audio_block(AC3DecodeContext *s, int blk) decode_band_structure(gbc, blk, s->eac3, 0, cpl_start_subband, cpl_end_subband, ff_eac3_default_cpl_band_struct, - &s->num_cpl_bands, s->cpl_band_sizes); + &s->num_cpl_bands, s->cpl_band_sizes, + s->cpl_band_struct, sizeof(s->cpl_band_struct)); } else { /* coupling not in use */ for (ch = 1; ch <= fbw_channels; ch++) { @@ -1326,7 +1331,7 @@ static int decode_audio_block(AC3DecodeContext *s, int blk) for (ch = 1; ch <= s->channels; ch++) { int audio_channel = 0; INTFLOAT gain; - if (s->channel_mode == AC3_CHMODE_DUALMONO) + if (s->channel_mode == AC3_CHMODE_DUALMONO && ch <= 2) audio_channel = 2-ch; if (s->heavy_compression && s->compression_exists[audio_channel]) gain = s->heavy_dynamic_range[audio_channel]; diff --git a/libavcodec/ac3dec.h b/libavcodec/ac3dec.h index b3498fec96..fe3cf86c43 100644 --- a/libavcodec/ac3dec.h +++ b/libavcodec/ac3dec.h @@ -126,6 +126,7 @@ typedef struct AC3DecodeContext { int phase_flags_in_use; ///< phase flags in use (phsflginu) int phase_flags[AC3_MAX_CPL_BANDS]; ///< phase flags (phsflg) int num_cpl_bands; ///< number of coupling bands (ncplbnd) + uint8_t cpl_band_struct[AC3_MAX_CPL_BANDS]; uint8_t cpl_band_sizes[AC3_MAX_CPL_BANDS]; ///< number of coeffs in each coupling band int firstchincpl; ///< first channel in coupling int first_cpl_coords[AC3_MAX_CHANNELS]; ///< first coupling coordinates states (firstcplcos) @@ -142,6 +143,7 @@ typedef struct AC3DecodeContext { int spx_dst_start_freq; ///< spx starting frequency bin for copying (copystartmant) ///< the copy region ends at the start of the spx region. int num_spx_bands; ///< number of spx bands (nspxbnds) + uint8_t spx_band_struct[SPX_MAX_BANDS]; uint8_t spx_band_sizes[SPX_MAX_BANDS]; ///< number of bins in each spx band uint8_t first_spx_coords[AC3_MAX_CHANNELS]; ///< first spx coordinates states (firstspxcos) INTFLOAT spx_noise_blend[AC3_MAX_CHANNELS][SPX_MAX_BANDS]; ///< spx noise blending factor (nblendfact) diff --git a/libavcodec/ac3dec_fixed.c b/libavcodec/ac3dec_fixed.c index 6416da436e..ef5fa5501a 100644 --- a/libavcodec/ac3dec_fixed.c +++ b/libavcodec/ac3dec_fixed.c @@ -64,12 +64,12 @@ static void scale_coefs ( int dynrng, int len) { - int i, shift, round; - int16_t mul; + int i, shift; + unsigned mul, round; int temp, temp1, temp2, temp3, temp4, temp5, temp6, temp7; mul = (dynrng & 0x1f) + 0x20; - shift = 4 - ((dynrng << 23) >> 28); + shift = 4 - (sign_extend(dynrng, 9) >> 5); if (shift > 0 ) { round = 1 << (shift-1); for (i=0; is2; for (i = 0; i < BLOCK_SAMPLES; i++) { d = get_sbits(&gb, 4); - s0 = ((d << COEFF_BITS) * scale + c->coeff[0] * s1 + c->coeff[1] * s2) >> COEFF_BITS; + s0 = ((d * (1 << COEFF_BITS)) * scale + c->coeff[0] * s1 + c->coeff[1] * s2) >> COEFF_BITS; s2 = s1; s1 = av_clip_int16(s0); *out++ = s1; diff --git a/libavcodec/alsdec.c b/libavcodec/alsdec.c index ebd364e085..d2c3485ee6 100644 --- a/libavcodec/alsdec.c +++ b/libavcodec/alsdec.c @@ -765,8 +765,13 @@ static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd) bd->ltp_gain[0] = decode_rice(gb, 1) << 3; bd->ltp_gain[1] = decode_rice(gb, 2) << 3; - r = get_unary(gb, 0, 3); + r = get_unary(gb, 0, 4); c = get_bits(gb, 2); + if (r >= 4) { + av_log(avctx, AV_LOG_ERROR, "r overflow\n"); + return AVERROR_INVALIDDATA; + } + bd->ltp_gain[2] = ltp_gain_values[r][c]; bd->ltp_gain[3] = decode_rice(gb, 2) << 3; diff --git a/libavcodec/amrwbdec.c b/libavcodec/amrwbdec.c index a99dbd110e..3314e47838 100644 --- a/libavcodec/amrwbdec.c +++ b/libavcodec/amrwbdec.c @@ -265,7 +265,7 @@ static void decode_pitch_lag_high(int *lag_int, int *lag_frac, int pitch_index, *lag_frac = pitch_index - (*lag_int << 2) + 136; } else if (pitch_index < 440) { *lag_int = (pitch_index + 257 - 376) >> 1; - *lag_frac = (pitch_index - (*lag_int << 1) + 256 - 376) << 1; + *lag_frac = (pitch_index - (*lag_int << 1) + 256 - 376) * 2; /* the actual resolution is 1/2 but expressed as 1/4 */ } else { *lag_int = pitch_index - 280; @@ -295,7 +295,7 @@ static void decode_pitch_lag_low(int *lag_int, int *lag_frac, int pitch_index, if (subframe == 0 || (subframe == 2 && mode != MODE_6k60)) { if (pitch_index < 116) { *lag_int = (pitch_index + 69) >> 1; - *lag_frac = (pitch_index - (*lag_int << 1) + 68) << 1; + *lag_frac = (pitch_index - (*lag_int << 1) + 68) * 2; } else { *lag_int = pitch_index - 24; *lag_frac = 0; @@ -305,7 +305,7 @@ static void decode_pitch_lag_low(int *lag_int, int *lag_frac, int pitch_index, AMRWB_P_DELAY_MIN, AMRWB_P_DELAY_MAX - 15); } else { *lag_int = (pitch_index + 1) >> 1; - *lag_frac = (pitch_index - (*lag_int << 1)) << 1; + *lag_frac = (pitch_index - (*lag_int << 1)) * 2; *lag_int += *base_lag_int; } } @@ -614,7 +614,7 @@ static float voice_factor(float *p_vector, float p_gain, AMRWB_SFR_SIZE) * f_gain * f_gain; - return (p_ener - f_ener) / (p_ener + f_ener); + return (p_ener - f_ener) / (p_ener + f_ener + 0.01); } /** @@ -865,15 +865,20 @@ static float find_hb_gain(AMRWBContext *ctx, const float *synth, { int wsp = (vad > 0); float tilt; + float tmp; if (ctx->fr_cur_mode == MODE_23k85) return qua_hb_gain[hb_idx] * (1.0f / (1 << 14)); - tilt = ctx->celpm_ctx.dot_productf(synth, synth + 1, AMRWB_SFR_SIZE - 1) / - ctx->celpm_ctx.dot_productf(synth, synth, AMRWB_SFR_SIZE); + tmp = ctx->celpm_ctx.dot_productf(synth, synth + 1, AMRWB_SFR_SIZE - 1); + + if (tmp > 0) { + tilt = tmp / ctx->celpm_ctx.dot_productf(synth, synth, AMRWB_SFR_SIZE); + } else + tilt = 0; /* return gain bounded by [0.1, 1.0] */ - return av_clipf((1.0 - FFMAX(0.0, tilt)) * (1.25 - 0.25 * wsp), 0.1, 1.0); + return av_clipf((1.0 - tilt) * (1.25 - 0.25 * wsp), 0.1, 1.0); } /** diff --git a/libavcodec/ansi.c b/libavcodec/ansi.c index 21d5ae1db2..31405b4a99 100644 --- a/libavcodec/ansi.c +++ b/libavcodec/ansi.c @@ -80,10 +80,6 @@ static av_cold int decode_init(AVCodecContext *avctx) AnsiContext *s = avctx->priv_data; avctx->pix_fmt = AV_PIX_FMT_PAL8; - s->frame = av_frame_alloc(); - if (!s->frame) - return AVERROR(ENOMEM); - /* defaults */ s->font = avpriv_vga16_font; s->font_height = 16; @@ -94,7 +90,15 @@ static av_cold int decode_init(AVCodecContext *avctx) int ret = ff_set_dimensions(avctx, 80 << 3, 25 << 4); if (ret < 0) return ret; + } else if (avctx->width % FONT_WIDTH || avctx->height % s->font_height) { + av_log(avctx, AV_LOG_ERROR, "Invalid dimensions %d %d\n", avctx->width, avctx->height); + return AVERROR(EINVAL); } + + s->frame = av_frame_alloc(); + if (!s->frame) + return AVERROR(ENOMEM); + return 0; } diff --git a/libavcodec/apedec.c b/libavcodec/apedec.c index bed9a96984..a0ad7dc395 100644 --- a/libavcodec/apedec.c +++ b/libavcodec/apedec.c @@ -1372,7 +1372,7 @@ static void ape_unpack_stereo(APEContext *ctx, int count) int32_t *decoded0 = ctx->decoded[0]; int32_t *decoded1 = ctx->decoded[1]; - if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) { + if ((ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) == APE_FRAMECODE_STEREO_SILENCE) { /* We are pure silence, so we're done. */ av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n"); return; @@ -1404,6 +1404,7 @@ static int ape_decode_frame(AVCodecContext *avctx, void *data, int32_t *sample24; int i, ch, ret; int blockstodecode; + uint64_t decoded_buffer_size; /* this should never be negative, but bad things will happen if it is, so check it just to make sure. */ @@ -1459,7 +1460,7 @@ static int ape_decode_frame(AVCodecContext *avctx, void *data, skip_bits_long(&s->gb, offset); } - if (!nblocks || nblocks > INT_MAX) { + if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) { av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n", nblocks); return AVERROR_INVALIDDATA; @@ -1485,8 +1486,9 @@ static int ape_decode_frame(AVCodecContext *avctx, void *data, blockstodecode = s->samples; /* reallocate decoded sample buffer if needed */ - av_fast_malloc(&s->decoded_buffer, &s->decoded_size, - 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer)); + decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer); + av_assert0(decoded_buffer_size <= INT_MAX); + av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size); if (!s->decoded_buffer) return AVERROR(ENOMEM); memset(s->decoded_buffer, 0, s->decoded_size); diff --git a/libavcodec/arm/sbrdsp_neon.S b/libavcodec/arm/sbrdsp_neon.S index e66abd682a..003b04ea05 100644 --- a/libavcodec/arm/sbrdsp_neon.S +++ b/libavcodec/arm/sbrdsp_neon.S @@ -336,11 +336,11 @@ function ff_sbr_hf_apply_noise_0_neon, export=1 vld1.32 {d0}, [r0,:64] vld1.32 {d6}, [lr,:64] vld1.32 {d2[]}, [r1,:32]! - vld1.32 {d3[]}, [r2,:32]! + vld1.32 {d18[]}, [r2,:32]! vceq.f32 d4, d2, #0 veor d2, d2, d3 vmov d1, d0 - vmla.f32 d0, d6, d3 + vmla.f32 d0, d6, d18 vadd.f32 s2, s2, s4 vbif d0, d1, d4 vst1.32 {d0}, [r0,:64]! diff --git a/libavcodec/asvenc.c b/libavcodec/asvenc.c index ec98a0ce35..c4eca2a13d 100644 --- a/libavcodec/asvenc.c +++ b/libavcodec/asvenc.c @@ -61,7 +61,7 @@ static inline void asv2_put_level(ASV1Context *a, PutBitContext *pb, int level) } else { put_bits(pb, ff_asv2_level_tab[31][1], ff_asv2_level_tab[31][0]); if (level < -128 || level > 127) { - av_log(a->avctx, AV_LOG_WARNING, "Cliping level %d, increase qscale\n", level); + av_log(a->avctx, AV_LOG_WARNING, "Clipping level %d, increase qscale\n", level); level = av_clip_int8(level); } asv2_put_bits(pb, 8, level & 0xFF); diff --git a/libavcodec/avcodec.h b/libavcodec/avcodec.h index d8497655b0..54c7e49c59 100644 --- a/libavcodec/avcodec.h +++ b/libavcodec/avcodec.h @@ -1403,6 +1403,16 @@ enum AVPacketSideDataType { * side data includes updated metadata which appeared in the stream. */ AV_PKT_DATA_METADATA_UPDATE, + + /** + * The number of side data elements (in fact a bit more than it). + * This is not part of the public API/ABI in the sense that it may + * change when new side data types are added. + * This must stay the last enum value. + * If its value becomes huge, some code using it + * needs to be updated as it assumes it to be smaller than other limits. + */ + AV_PKT_DATA_NB }; #define AV_PKT_DATA_QUALITY_FACTOR AV_PKT_DATA_QUALITY_STATS //DEPRECATED diff --git a/libavcodec/avpacket.c b/libavcodec/avpacket.c index 4901d361b1..5e2e969659 100644 --- a/libavcodec/avpacket.c +++ b/libavcodec/avpacket.c @@ -184,6 +184,7 @@ static int copy_packet_data(AVPacket *pkt, const AVPacket *src, int dup) { pkt->data = NULL; pkt->side_data = NULL; + pkt->side_data_elems = 0; if (pkt->buf) { AVBufferRef *ref = av_buffer_ref(src->buf); if (!ref) @@ -193,9 +194,11 @@ static int copy_packet_data(AVPacket *pkt, const AVPacket *src, int dup) } else { DUP_DATA(pkt->data, src->data, pkt->size, 1, ALLOC_BUF); } - if (pkt->side_data_elems && dup) + if (src->side_data_elems && dup) { pkt->side_data = src->side_data; - if (pkt->side_data_elems && !dup) { + pkt->side_data_elems = src->side_data_elems; + } + if (src->side_data_elems && !dup) { return av_copy_packet_side_data(pkt, src); } return 0; @@ -277,16 +280,17 @@ FF_ENABLE_DEPRECATION_WARNINGS int av_packet_add_side_data(AVPacket *pkt, enum AVPacketSideDataType type, uint8_t *data, size_t size) { + AVPacketSideData *tmp; int elems = pkt->side_data_elems; - if ((unsigned)elems + 1 > INT_MAX / sizeof(*pkt->side_data)) + if ((unsigned)elems + 1 > AV_PKT_DATA_NB) return AVERROR(ERANGE); - pkt->side_data = av_realloc(pkt->side_data, - (elems + 1) * sizeof(*pkt->side_data)); - if (!pkt->side_data) + tmp = av_realloc(pkt->side_data, (elems + 1) * sizeof(*tmp)); + if (!tmp) return AVERROR(ENOMEM); + pkt->side_data = tmp; pkt->side_data[elems].data = data; pkt->side_data[elems].size = size; pkt->side_data[elems].type = type; @@ -329,6 +333,8 @@ uint8_t *av_packet_get_side_data(AVPacket *pkt, enum AVPacketSideDataType type, return pkt->side_data[i].data; } } + if (size) + *size = 0; return NULL; } @@ -401,13 +407,18 @@ int av_packet_split_side_data(AVPacket *pkt){ p = pkt->data + pkt->size - 8 - 5; for (i=1; ; i++){ size = AV_RB32(p); - if (size>INT_MAX || p - pkt->data < size) + if (size>INT_MAX - 5 || p - pkt->data < size) return 0; if (p[4]&128) break; + if (p - pkt->data < size + 5) + return 0; p-= size+5; } + if (i > AV_PKT_DATA_NB) + return AVERROR(ERANGE); + pkt->side_data = av_malloc_array(i, sizeof(*pkt->side_data)); if (!pkt->side_data) return AVERROR(ENOMEM); @@ -415,7 +426,7 @@ int av_packet_split_side_data(AVPacket *pkt){ p= pkt->data + pkt->size - 8 - 5; for (i=0; ; i++){ size= AV_RB32(p); - av_assert0(size<=INT_MAX && p - pkt->data >= size); + av_assert0(size<=INT_MAX - 5 && p - pkt->data >= size); pkt->side_data[i].data = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE); pkt->side_data[i].size = size; pkt->side_data[i].type = p[4]&127; diff --git a/libavcodec/bintext.c b/libavcodec/bintext.c index 90bbe67b59..d967317671 100644 --- a/libavcodec/bintext.c +++ b/libavcodec/bintext.c @@ -35,6 +35,8 @@ #include "bintext.h" #include "internal.h" +#define FONT_WIDTH 8 + typedef struct XbinContext { AVFrame *frame; int palette[16]; @@ -91,6 +93,9 @@ static av_cold int decode_init(AVCodecContext *avctx) break; } } + if (avctx->width < FONT_WIDTH || avctx->height < s->font_height) + return AVERROR_INVALIDDATA; + s->frame = av_frame_alloc(); if (!s->frame) @@ -113,8 +118,6 @@ av_unused static void hscroll(AVCodecContext *avctx) } } -#define FONT_WIDTH 8 - /** * Draw character to screen */ diff --git a/libavcodec/bmp_parser.c b/libavcodec/bmp_parser.c index c9493dc32d..cd65f02a2e 100644 --- a/libavcodec/bmp_parser.c +++ b/libavcodec/bmp_parser.c @@ -53,7 +53,8 @@ restart: if (bpc->pc.frame_start_found == 0) { if ((state >> 48) == (('B' << 8) | 'M')) { bpc->fsize = av_bswap32(state >> 16); - bpc->pc.frame_start_found = 1; + if (bpc->fsize > 17) + bpc->pc.frame_start_found = 1; } } else if (bpc->pc.frame_start_found == 2+4+4) { // unsigned hsize = av_bswap32(state>>32); @@ -67,8 +68,12 @@ restart: if (bpc->pc.index + i > 17) { next = i - 17; - } else + state = 0; + break; + } else { + bpc->pc.state64 = 0; goto restart; + } } else if (bpc->pc.frame_start_found) bpc->pc.frame_start_found++; } @@ -89,7 +94,10 @@ flush: if (ff_combine_frame(&bpc->pc, next, &buf, &buf_size) < 0) return buf_size; - bpc->pc.frame_start_found = 0; + if (next != END_NOT_FOUND && next < 0) + bpc->pc.frame_start_found = FFMAX(bpc->pc.frame_start_found - i - 1, 0); + else + bpc->pc.frame_start_found = 0; *poutbuf = buf; *poutbuf_size = buf_size; diff --git a/libavcodec/bmvvideo.c b/libavcodec/bmvvideo.c index 97f850dbae..cf7f0a0501 100644 --- a/libavcodec/bmvvideo.c +++ b/libavcodec/bmvvideo.c @@ -107,7 +107,7 @@ static int decode_bmv_frame(const uint8_t *source, int src_len, uint8_t *frame, if (src < source || src >= source_end) return AVERROR_INVALIDDATA; shift += 2; - val |= *src << shift; + val |= (unsigned)*src << shift; if (*src & 0xC) break; } diff --git a/libavcodec/cavs.c b/libavcodec/cavs.c index 10a25d8749..9a4a03ef30 100644 --- a/libavcodec/cavs.c +++ b/libavcodec/cavs.c @@ -538,8 +538,7 @@ void ff_cavs_inter(AVSContext *h, enum cavs_mb mb_type) static inline void scale_mv(AVSContext *h, int *d_x, int *d_y, cavs_vector *src, int distp) { - int den = h->scale_den[FFMAX(src->ref, 0)]; - + int64_t den = h->scale_den[FFMAX(src->ref, 0)]; *d_x = (src->x * distp * den + 256 + FF_SIGNBIT(src->x)) >> 9; *d_y = (src->y * distp * den + 256 + FF_SIGNBIT(src->y)) >> 9; } @@ -614,8 +613,15 @@ void ff_cavs_mv(AVSContext *h, enum cavs_mv_loc nP, enum cavs_mv_loc nC, mv_pred_median(h, mvP, mvA, mvB, mvC); if (mode < MV_PRED_PSKIP) { - mvP->x += get_se_golomb(&h->gb); - mvP->y += get_se_golomb(&h->gb); + int mx = get_se_golomb(&h->gb) + (unsigned)mvP->x; + int my = get_se_golomb(&h->gb) + (unsigned)mvP->y; + + if (mx != (int16_t)mx || my != (int16_t)my) { + av_log(h->avctx, AV_LOG_ERROR, "MV %d %d out of supported range\n", mx, my); + } else { + mvP->x = mx; + mvP->y = my; + } } set_mvs(mvP, size); } diff --git a/libavcodec/cavsdec.c b/libavcodec/cavsdec.c index 70ac6f8a42..b7aeb45603 100644 --- a/libavcodec/cavsdec.c +++ b/libavcodec/cavsdec.c @@ -465,7 +465,7 @@ static inline void mv_pred_direct(AVSContext *h, cavs_vector *pmv_fw, cavs_vector *col_mv) { cavs_vector *pmv_bw = pmv_fw + MV_BWD_OFFS; - int den = h->direct_den[col_mv->ref]; + unsigned den = h->direct_den[col_mv->ref]; int m = FF_SIGNBIT(col_mv->x); pmv_fw->dist = h->dist[1]; @@ -615,7 +615,7 @@ static inline int decode_residual_inter(AVSContext *h) /* get quantizer */ if (h->cbp && !h->qp_fixed) - h->qp = (h->qp + get_se_golomb(&h->gb)) & 63; + h->qp = (h->qp + (unsigned)get_se_golomb(&h->gb)) & 63; for (block = 0; block < 4; block++) if (h->cbp & (1 << block)) decode_residual_block(h, &h->gb, inter_dec, 0, h->qp, @@ -1031,6 +1031,10 @@ static int decode_pic(AVSContext *h) h->scale_den[1] = h->dist[1] ? 512/h->dist[1] : 0; if (h->cur.f->pict_type == AV_PICTURE_TYPE_B) { h->sym_factor = h->dist[0] * h->scale_den[1]; + if (FFABS(h->sym_factor) > 32768) { + av_log(h->avctx, AV_LOG_ERROR, "sym_factor %d too large\n", h->sym_factor); + return AVERROR_INVALIDDATA; + } } else { h->direct_den[0] = h->dist[0] ? 16384 / h->dist[0] : 0; h->direct_den[1] = h->dist[1] ? 16384 / h->dist[1] : 0; @@ -1063,6 +1067,11 @@ static int decode_pic(AVSContext *h) if (!h->loop_filter_disable && get_bits1(&h->gb)) { h->alpha_offset = get_se_golomb(&h->gb); h->beta_offset = get_se_golomb(&h->gb); + if ( h->alpha_offset < -64 || h->alpha_offset > 64 + || h-> beta_offset < -64 || h-> beta_offset > 64) { + h->alpha_offset = h->beta_offset = 0; + return AVERROR_INVALIDDATA; + } } else { h->alpha_offset = h->beta_offset = 0; } @@ -1217,6 +1226,8 @@ static int cavs_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, h->got_keyframe = 1; } case PIC_PB_START_CODE: + if (*got_frame) + av_frame_unref(data); *got_frame = 0; if (!h->got_keyframe) break; diff --git a/libavcodec/cavsdsp.c b/libavcodec/cavsdsp.c index 91f6d7350b..df9490ad8f 100644 --- a/libavcodec/cavsdsp.c +++ b/libavcodec/cavsdsp.c @@ -188,7 +188,6 @@ static void cavs_filter_ch_c(uint8_t *d, int stride, int alpha, int beta, int tc static void cavs_idct8_add_c(uint8_t *dst, int16_t *block, int stride) { int i; int16_t (*src)[8] = (int16_t(*)[8])block; - const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP; src[0][0] += 8; @@ -243,14 +242,14 @@ static void cavs_idct8_add_c(uint8_t *dst, int16_t *block, int stride) { const int b2 = a5 - a7; const int b3 = a4 - a6; - dst[i + 0*stride] = cm[ dst[i + 0*stride] + ((b0 + b4) >> 7)]; - dst[i + 1*stride] = cm[ dst[i + 1*stride] + ((b1 + b5) >> 7)]; - dst[i + 2*stride] = cm[ dst[i + 2*stride] + ((b2 + b6) >> 7)]; - dst[i + 3*stride] = cm[ dst[i + 3*stride] + ((b3 + b7) >> 7)]; - dst[i + 4*stride] = cm[ dst[i + 4*stride] + ((b3 - b7) >> 7)]; - dst[i + 5*stride] = cm[ dst[i + 5*stride] + ((b2 - b6) >> 7)]; - dst[i + 6*stride] = cm[ dst[i + 6*stride] + ((b1 - b5) >> 7)]; - dst[i + 7*stride] = cm[ dst[i + 7*stride] + ((b0 - b4) >> 7)]; + dst[i + 0*stride] = av_clip_uint8( dst[i + 0*stride] + ((b0 + b4) >> 7)); + dst[i + 1*stride] = av_clip_uint8( dst[i + 1*stride] + ((b1 + b5) >> 7)); + dst[i + 2*stride] = av_clip_uint8( dst[i + 2*stride] + ((b2 + b6) >> 7)); + dst[i + 3*stride] = av_clip_uint8( dst[i + 3*stride] + ((b3 + b7) >> 7)); + dst[i + 4*stride] = av_clip_uint8( dst[i + 4*stride] + ((b3 - b7) >> 7)); + dst[i + 5*stride] = av_clip_uint8( dst[i + 5*stride] + ((b2 - b6) >> 7)); + dst[i + 6*stride] = av_clip_uint8( dst[i + 6*stride] + ((b1 - b5) >> 7)); + dst[i + 7*stride] = av_clip_uint8( dst[i + 7*stride] + ((b0 - b4) >> 7)); } } diff --git a/libavcodec/ccaption_dec.c b/libavcodec/ccaption_dec.c index 790f0718fd..4b42dbc5db 100644 --- a/libavcodec/ccaption_dec.c +++ b/libavcodec/ccaption_dec.c @@ -135,7 +135,8 @@ typedef struct CCaptionSubContext { int64_t last_real_time; char prev_cmd[2]; /* buffer to store pkt data */ - AVBufferRef *pktbuf; + uint8_t *pktbuf; + int pktbuf_size; } CCaptionSubContext; @@ -160,11 +161,7 @@ static av_cold int init_decoder(AVCodecContext *avctx) if (ret < 0) { return ret; } - /* allocate pkt buffer */ - ctx->pktbuf = av_buffer_alloc(128); - if (!ctx->pktbuf) { - ret = AVERROR(ENOMEM); - } + return ret; } @@ -172,7 +169,8 @@ static av_cold int close_decoder(AVCodecContext *avctx) { CCaptionSubContext *ctx = avctx->priv_data; av_bprint_finalize(&ctx->buffer, NULL); - av_buffer_unref(&ctx->pktbuf); + av_freep(&ctx->pktbuf); + ctx->pktbuf_size = 0; return 0; } @@ -578,16 +576,13 @@ static int decode(AVCodecContext *avctx, void *data, int *got_sub, AVPacket *avp int ret = 0; int i; - if (ctx->pktbuf->size < len) { - ret = av_buffer_realloc(&ctx->pktbuf, len); - if (ret < 0) { - av_log(ctx, AV_LOG_WARNING, "Insufficient Memory of %d truncated to %d\n", len, ctx->pktbuf->size); - len = ctx->pktbuf->size; - ret = 0; - } + av_fast_padded_malloc(&ctx->pktbuf, &ctx->pktbuf_size, len); + if (!ctx->pktbuf) { + av_log(ctx, AV_LOG_WARNING, "Insufficient Memory of %d truncated to %d\n", len, ctx->pktbuf_size); + return AVERROR(ENOMEM); } - memcpy(ctx->pktbuf->data, avpkt->data, len); - bptr = ctx->pktbuf->data; + memcpy(ctx->pktbuf, avpkt->data, len); + bptr = ctx->pktbuf; for (i = 0; i < len; i += 3) { uint8_t cc_type = *(bptr + i) & 3; diff --git a/libavcodec/cdxl.c b/libavcodec/cdxl.c index 50d514b25d..3eaf194d2f 100644 --- a/libavcodec/cdxl.c +++ b/libavcodec/cdxl.c @@ -252,11 +252,11 @@ static int cdxl_decode_frame(AVCodecContext *avctx, void *data, aligned_width = FFALIGN(c->avctx->width, 16); c->padded_bits = aligned_width - c->avctx->width; - if (c->video_size < aligned_width * avctx->height * c->bpp / 8) + if (c->video_size < aligned_width * avctx->height * (int64_t)c->bpp / 8) return AVERROR_INVALIDDATA; - if (!encoding && c->palette_size && c->bpp <= 8) { + if (!encoding && c->palette_size && c->bpp <= 8 && c->format != CHUNKY) { avctx->pix_fmt = AV_PIX_FMT_PAL8; - } else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8)) { + } else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8) && c->format != CHUNKY) { if (c->palette_size != (1 << (c->bpp - 1))) return AVERROR_INVALIDDATA; avctx->pix_fmt = AV_PIX_FMT_BGR24; diff --git a/libavcodec/cfhd.c b/libavcodec/cfhd.c index 5c15d9bb04..685090eb61 100644 --- a/libavcodec/cfhd.c +++ b/libavcodec/cfhd.c @@ -250,6 +250,11 @@ static int cfhd_decode(AVCodecContext *avctx, void *data, int *got_frame, s->coded_height = data; } else if (tag == 101) { av_log(avctx, AV_LOG_DEBUG, "Bits per component: %"PRIu16"\n", data); + if (data < 1 || data > 31) { + av_log(avctx, AV_LOG_ERROR, "Bits per component %d is invalid\n", data); + ret = AVERROR(EINVAL); + break; + } s->bpc = data; } else if (tag == 12) { av_log(avctx, AV_LOG_DEBUG, "Channel Count: %"PRIu16"\n", data); @@ -309,22 +314,22 @@ static int cfhd_decode(AVCodecContext *avctx, void *data, int *got_frame, s->prescale_shift[2] = (data >> 6) & 0x7; av_log(avctx, AV_LOG_DEBUG, "Prescale shift (VC-5): %x\n", data); } else if (tag == 27) { - s->plane[s->channel_num].band[0][0].width = data; - s->plane[s->channel_num].band[0][0].stride = data; av_log(avctx, AV_LOG_DEBUG, "Lowpass width %"PRIu16"\n", data); - if (data < 2 || data > s->plane[s->channel_num].band[0][0].a_width) { + if (data < 3 || data > s->plane[s->channel_num].band[0][0].a_width) { av_log(avctx, AV_LOG_ERROR, "Invalid lowpass width\n"); ret = AVERROR(EINVAL); break; } + s->plane[s->channel_num].band[0][0].width = data; + s->plane[s->channel_num].band[0][0].stride = data; } else if (tag == 28) { - s->plane[s->channel_num].band[0][0].height = data; av_log(avctx, AV_LOG_DEBUG, "Lowpass height %"PRIu16"\n", data); - if (data < 2 || data > s->plane[s->channel_num].band[0][0].height) { + if (data < 3 || data > s->plane[s->channel_num].band[0][0].a_height) { av_log(avctx, AV_LOG_ERROR, "Invalid lowpass height\n"); ret = AVERROR(EINVAL); break; } + s->plane[s->channel_num].band[0][0].height = data; } else if (tag == 1) av_log(avctx, AV_LOG_DEBUG, "Sample type? %"PRIu16"\n", data); else if (tag == 10) { @@ -355,39 +360,39 @@ static int cfhd_decode(AVCodecContext *avctx, void *data, int *got_frame, av_log(avctx, AV_LOG_DEBUG, "Tag/Value = %x %x\n", tag2, val2); } } else if (tag == 41) { - s->plane[s->channel_num].band[s->level][s->subband_num].width = data; - s->plane[s->channel_num].band[s->level][s->subband_num].stride = FFALIGN(data, 8); av_log(avctx, AV_LOG_DEBUG, "Highpass width %i channel %i level %i subband %i\n", data, s->channel_num, s->level, s->subband_num); - if (data < 2) { + if (data < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid highpass width\n"); ret = AVERROR(EINVAL); break; } + s->plane[s->channel_num].band[s->level][s->subband_num].width = data; + s->plane[s->channel_num].band[s->level][s->subband_num].stride = FFALIGN(data, 8); } else if (tag == 42) { - s->plane[s->channel_num].band[s->level][s->subband_num].height = data; av_log(avctx, AV_LOG_DEBUG, "Highpass height %i\n", data); - if (data < 2) { + if (data < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid highpass height\n"); ret = AVERROR(EINVAL); break; } + s->plane[s->channel_num].band[s->level][s->subband_num].height = data; } else if (tag == 49) { - s->plane[s->channel_num].band[s->level][s->subband_num].width = data; - s->plane[s->channel_num].band[s->level][s->subband_num].stride = FFALIGN(data, 8); av_log(avctx, AV_LOG_DEBUG, "Highpass width2 %i\n", data); - if (data < 2) { + if (data < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid highpass width2\n"); ret = AVERROR(EINVAL); break; } + s->plane[s->channel_num].band[s->level][s->subband_num].width = data; + s->plane[s->channel_num].band[s->level][s->subband_num].stride = FFALIGN(data, 8); } else if (tag == 50) { - s->plane[s->channel_num].band[s->level][s->subband_num].height = data; av_log(avctx, AV_LOG_DEBUG, "Highpass height2 %i\n", data); - if (data < 2) { + if (data < 3) { av_log(avctx, AV_LOG_ERROR, "Invalid highpass height2\n"); ret = AVERROR(EINVAL); break; } + s->plane[s->channel_num].band[s->level][s->subband_num].height = data; } else if (tag == 71) { s->codebook = data; av_log(avctx, AV_LOG_DEBUG, "Codebook %i\n", s->codebook); @@ -396,12 +401,12 @@ static int cfhd_decode(AVCodecContext *avctx, void *data, int *got_frame, av_log(avctx, AV_LOG_DEBUG, "Other codebook? %i\n", s->codebook); } else if (tag == 70) { av_log(avctx, AV_LOG_DEBUG, "Subsampling or bit-depth flag? %i\n", data); - s->bpc = data; - if (!(s->bpc == 10 || s->bpc == 12)) { + if (!(data == 10 || data == 12)) { av_log(avctx, AV_LOG_ERROR, "Invalid bits per channel\n"); ret = AVERROR(EINVAL); break; } + s->bpc = data; } else if (tag == 84) { av_log(avctx, AV_LOG_DEBUG, "Sample format? %i\n", data); if (data == 1) @@ -425,6 +430,11 @@ static int cfhd_decode(AVCodecContext *avctx, void *data, int *got_frame, return ret; } } + ret = ff_set_dimensions(avctx, s->coded_width, s->coded_height); + if (ret < 0) + return ret; + frame.f->width = + frame.f->height = 0; if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) return ret; @@ -621,7 +631,7 @@ static int cfhd_decode(AVCodecContext *avctx, void *data, int *got_frame, output = s->plane[plane].subband[0]; for (i = 0; i < lowpass_height * 2; i++) { for (j = 0; j < lowpass_width * 2; j++) - output[j] <<= 2; + output[j] *= 4; output += lowpass_width * 2; } @@ -674,7 +684,7 @@ static int cfhd_decode(AVCodecContext *avctx, void *data, int *got_frame, output = s->plane[plane].subband[0]; for (i = 0; i < lowpass_height * 2; i++) { for (j = 0; j < lowpass_width * 2; j++) - output[j] <<= 2; + output[j] *= 4; output += lowpass_width * 2; } @@ -756,6 +766,6 @@ AVCodec ff_cfhd_decoder = { .init = cfhd_decode_init, .close = cfhd_close_decoder, .decode = cfhd_decode, - .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS, + .capabilities = AV_CODEC_CAP_DR1, .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP, }; diff --git a/libavcodec/cinepak.c b/libavcodec/cinepak.c index f1a4656303..9060e31fb1 100644 --- a/libavcodec/cinepak.c +++ b/libavcodec/cinepak.c @@ -315,17 +315,11 @@ static int cinepak_decode_strip (CinepakContext *s, return AVERROR_INVALIDDATA; } -static int cinepak_decode (CinepakContext *s) +static int cinepak_predecode_check (CinepakContext *s) { - const uint8_t *eod = (s->data + s->size); - int i, result, strip_size, frame_flags, num_strips; - int y0 = 0; + int num_strips; int encoded_buf_size; - if (s->size < 10) - return AVERROR_INVALIDDATA; - - frame_flags = s->data[0]; num_strips = AV_RB16 (&s->data[8]); encoded_buf_size = AV_RB24(&s->data[1]); @@ -356,6 +350,21 @@ static int cinepak_decode (CinepakContext *s) s->sega_film_skip_bytes = 0; } + if (s->size < 10 + s->sega_film_skip_bytes + num_strips * 12) + return AVERROR_INVALIDDATA; + + return 0; +} + +static int cinepak_decode (CinepakContext *s) +{ + const uint8_t *eod = (s->data + s->size); + int i, result, strip_size, frame_flags, num_strips; + int y0 = 0; + + frame_flags = s->data[0]; + num_strips = AV_RB16 (&s->data[8]); + s->data += 10 + s->sega_film_skip_bytes; num_strips = FFMIN(num_strips, MAX_STRIPS); @@ -435,18 +444,36 @@ static int cinepak_decode_frame(AVCodecContext *avctx, const uint8_t *buf = avpkt->data; int ret = 0, buf_size = avpkt->size; CinepakContext *s = avctx->priv_data; + int num_strips; s->data = buf; s->size = buf_size; + if (s->size < 10) + return AVERROR_INVALIDDATA; + + num_strips = AV_RB16 (&s->data[8]); + + //Empty frame, do not waste time + if (!num_strips && (!s->palette_video || !av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL))) + return buf_size; + + if ((ret = cinepak_predecode_check(s)) < 0) { + av_log(avctx, AV_LOG_ERROR, "cinepak_predecode_check failed\n"); + return ret; + } + if ((ret = ff_reget_buffer(avctx, s->frame)) < 0) return ret; if (s->palette_video) { - const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL); - if (pal) { + int size; + const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, &size); + if (pal && size == AVPALETTE_SIZE) { s->frame->palette_has_changed = 1; memcpy(s->pal, pal, AVPALETTE_SIZE); + } else if (pal) { + av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", size); } } diff --git a/libavcodec/cllc.c b/libavcodec/cllc.c index 1c6902afd4..97d3ae40ea 100644 --- a/libavcodec/cllc.c +++ b/libavcodec/cllc.c @@ -29,6 +29,10 @@ #include "avcodec.h" #include "internal.h" +#define VLC_BITS 7 +#define VLC_DEPTH 2 + + typedef struct CLLCContext { AVCodecContext *avctx; BswapDSPContext bdsp; @@ -51,6 +55,13 @@ static int read_code_table(CLLCContext *ctx, GetBitContext *gb, VLC *vlc) num_lens = get_bits(gb, 5); + if (num_lens > VLC_BITS * VLC_DEPTH) { + vlc->table = NULL; + + av_log(ctx->avctx, AV_LOG_ERROR, "To long VLCs %d\n", num_lens); + return AVERROR_INVALIDDATA; + } + for (i = 0; i < num_lens; i++) { num_codes = get_bits(gb, 9); num_codes_sum += num_codes; @@ -70,11 +81,15 @@ static int read_code_table(CLLCContext *ctx, GetBitContext *gb, VLC *vlc) count++; } + if (prefix > (65535 - 256)/2) { + vlc->table = NULL; + return AVERROR_INVALIDDATA; + } prefix <<= 1; } - return ff_init_vlc_sparse(vlc, 7, count, bits, 1, 1, + return ff_init_vlc_sparse(vlc, VLC_BITS, count, bits, 1, 1, codes, 2, 2, symbols, 1, 1, 0); } @@ -101,7 +116,7 @@ static int read_argb_line(CLLCContext *ctx, GetBitContext *gb, int *top_left, for (i = 0; i < ctx->avctx->width; i++) { /* Always get the alpha component */ UPDATE_CACHE(bits, gb); - GET_VLC(code, bits, gb, vlc[0].table, 7, 2); + GET_VLC(code, bits, gb, vlc[0].table, VLC_BITS, VLC_DEPTH); pred[0] += code; dst[0] = pred[0]; @@ -110,21 +125,21 @@ static int read_argb_line(CLLCContext *ctx, GetBitContext *gb, int *top_left, if (dst[0]) { /* Red */ UPDATE_CACHE(bits, gb); - GET_VLC(code, bits, gb, vlc[1].table, 7, 2); + GET_VLC(code, bits, gb, vlc[1].table, VLC_BITS, VLC_DEPTH); pred[1] += code; dst[1] = pred[1]; /* Green */ UPDATE_CACHE(bits, gb); - GET_VLC(code, bits, gb, vlc[2].table, 7, 2); + GET_VLC(code, bits, gb, vlc[2].table, VLC_BITS, VLC_DEPTH); pred[2] += code; dst[2] = pred[2]; /* Blue */ UPDATE_CACHE(bits, gb); - GET_VLC(code, bits, gb, vlc[3].table, 7, 2); + GET_VLC(code, bits, gb, vlc[3].table, VLC_BITS, VLC_DEPTH); pred[3] += code; dst[3] = pred[3]; @@ -166,7 +181,7 @@ static int read_rgb24_component_line(CLLCContext *ctx, GetBitContext *gb, /* Simultaneously read and restore the line */ for (i = 0; i < ctx->avctx->width; i++) { UPDATE_CACHE(bits, gb); - GET_VLC(code, bits, gb, vlc->table, 7, 2); + GET_VLC(code, bits, gb, vlc->table, VLC_BITS, VLC_DEPTH); pred += code; dst[0] = pred; @@ -195,7 +210,7 @@ static int read_yuv_component_line(CLLCContext *ctx, GetBitContext *gb, /* Simultaneously read and restore the line */ for (i = 0; i < ctx->avctx->width >> is_chroma; i++) { UPDATE_CACHE(bits, gb); - GET_VLC(code, bits, gb, vlc->table, 7, 2); + GET_VLC(code, bits, gb, vlc->table, VLC_BITS, VLC_DEPTH); pred += code; outbuf[i] = pred; diff --git a/libavcodec/cngdec.c b/libavcodec/cngdec.c index 0251086042..a3fabf90e3 100644 --- a/libavcodec/cngdec.c +++ b/libavcodec/cngdec.c @@ -147,7 +147,7 @@ static int cng_decode_frame(AVCodecContext *avctx, void *data, return ret; buf_out = (int16_t *)frame->data[0]; for (i = 0; i < avctx->frame_size; i++) - buf_out[i] = p->filter_out[i + p->order]; + buf_out[i] = av_clip_int16(p->filter_out[i + p->order]); memcpy(p->filter_out, p->filter_out + avctx->frame_size, p->order * sizeof(*p->filter_out)); diff --git a/libavcodec/cscd.c b/libavcodec/cscd.c index 9e1dec9d96..5eb511a565 100644 --- a/libavcodec/cscd.c +++ b/libavcodec/cscd.c @@ -81,15 +81,19 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, switch ((buf[0] >> 1) & 7) { case 0: { // lzo compression int outlen = c->decomp_size, inlen = buf_size - 2; - if (av_lzo1x_decode(c->decomp_buf, &outlen, &buf[2], &inlen)) + if (av_lzo1x_decode(c->decomp_buf, &outlen, &buf[2], &inlen) || outlen) { av_log(avctx, AV_LOG_ERROR, "error during lzo decompression\n"); + return AVERROR_INVALIDDATA; + } break; } case 1: { // zlib compression #if CONFIG_ZLIB unsigned long dlen = c->decomp_size; - if (uncompress(c->decomp_buf, &dlen, &buf[2], buf_size - 2) != Z_OK) + if (uncompress(c->decomp_buf, &dlen, &buf[2], buf_size - 2) != Z_OK) { av_log(avctx, AV_LOG_ERROR, "error during zlib decompression\n"); + return AVERROR_INVALIDDATA; + } break; #else av_log(avctx, AV_LOG_ERROR, "compiled without zlib support\n"); diff --git a/libavcodec/dca_core.c b/libavcodec/dca_core.c index 48a8f618f7..19496e944b 100644 --- a/libavcodec/dca_core.c +++ b/libavcodec/dca_core.c @@ -1760,6 +1760,7 @@ static int parse_x96_frame_exss(DCACoreDecoder *s) return ret; // Channel set data + s->x96_nchannels = 0; for (i = 0, x96_base_ch = 0; i < x96_nchsets; i++) { header_pos = get_bits_count(&s->gb); @@ -1899,9 +1900,10 @@ static int parse_optional_info(DCACoreDecoder *s) } } - if (s->avctx->err_recognition & AV_EF_EXPLODE) { + if (!s->xch_pos) { av_log(s->avctx, AV_LOG_ERROR, "XCH sync word not found\n"); - return AVERROR_INVALIDDATA; + if (s->avctx->err_recognition & AV_EF_EXPLODE) + return AVERROR_INVALIDDATA; } break; @@ -1921,9 +1923,10 @@ static int parse_optional_info(DCACoreDecoder *s) } } - if (s->avctx->err_recognition & AV_EF_EXPLODE) { + if (!s->x96_pos) { av_log(s->avctx, AV_LOG_ERROR, "X96 sync word not found\n"); - return AVERROR_INVALIDDATA; + if (s->avctx->err_recognition & AV_EF_EXPLODE) + return AVERROR_INVALIDDATA; } break; @@ -1946,9 +1949,10 @@ static int parse_optional_info(DCACoreDecoder *s) } } - if (s->avctx->err_recognition & AV_EF_EXPLODE) { + if (!s->xxch_pos) { av_log(s->avctx, AV_LOG_ERROR, "XXCH sync word not found\n"); - return AVERROR_INVALIDDATA; + if (s->avctx->err_recognition & AV_EF_EXPLODE) + return AVERROR_INVALIDDATA; } break; } diff --git a/libavcodec/dcadsp.c b/libavcodec/dcadsp.c index 09faee51fb..4316a2eb98 100644 --- a/libavcodec/dcadsp.c +++ b/libavcodec/dcadsp.c @@ -320,7 +320,7 @@ static void dmix_sub_c(int32_t *dst, const int32_t *src, int coeff, ptrdiff_t le int i; for (i = 0; i < len; i++) - dst[i] -= mul15(src[i], coeff); + dst[i] -= (unsigned)mul15(src[i], coeff); } static void dmix_add_c(int32_t *dst, const int32_t *src, int coeff, ptrdiff_t len) diff --git a/libavcodec/dds.c b/libavcodec/dds.c index 9577b67f0f..7cb89dade7 100644 --- a/libavcodec/dds.c +++ b/libavcodec/dds.c @@ -39,7 +39,7 @@ #define DDPF_FOURCC (1 << 2) #define DDPF_PALETTE (1 << 5) -#define DDPF_NORMALMAP (1 << 31) +#define DDPF_NORMALMAP (1U << 31) enum DDSPostProc { DDS_NONE = 0, @@ -676,7 +676,7 @@ static int dds_decode(AVCodecContext *avctx, void *data, (frame->data[1][2+i*4]<<0)+ (frame->data[1][1+i*4]<<8)+ (frame->data[1][0+i*4]<<16)+ - (frame->data[1][3+i*4]<<24) + ((unsigned)frame->data[1][3+i*4]<<24) ); frame->palette_has_changed = 1; diff --git a/libavcodec/dfa.c b/libavcodec/dfa.c index f45d019a79..b8500a4995 100644 --- a/libavcodec/dfa.c +++ b/libavcodec/dfa.c @@ -41,7 +41,7 @@ static av_cold int dfa_decode_init(AVCodecContext *avctx) avctx->pix_fmt = AV_PIX_FMT_PAL8; - if (!avctx->width || !avctx->height) + if (!avctx->width || !avctx->height || FFMAX(avctx->width, avctx->height) >= (1<<16)) return AVERROR_INVALIDDATA; av_assert0(av_image_check_size(avctx->width, avctx->height, 0, avctx) >= 0); @@ -67,7 +67,8 @@ static int decode_tsw1(GetByteContext *gb, uint8_t *frame, int width, int height const uint8_t *frame_start = frame; const uint8_t *frame_end = frame + width * height; int mask = 0x10000, bitbuf = 0; - int v, count, segments; + int v, count; + unsigned segments; unsigned offset; segments = bytestream2_get_le32(gb); @@ -175,7 +176,7 @@ static int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height return AVERROR_INVALIDDATA; frame += v; } else { - if (frame_end - frame < width + 3) + if (frame_end - frame < width + 4) return AVERROR_INVALIDDATA; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); @@ -249,7 +250,7 @@ static int decode_wdlt(GetByteContext *gb, uint8_t *frame, int width, int height segments = bytestream2_get_le16u(gb); while ((segments & 0xC000) == 0xC000) { unsigned skip_lines = -(int16_t)segments; - unsigned delta = -((int16_t)segments * width); + int64_t delta = -((int16_t)segments * (int64_t)width); if (frame_end - frame <= delta || y + lines + skip_lines > height) return AVERROR_INVALIDDATA; frame += delta; diff --git a/libavcodec/dirac_dwt.h b/libavcodec/dirac_dwt.h index 4d338651fa..994dc21d70 100644 --- a/libavcodec/dirac_dwt.h +++ b/libavcodec/dirac_dwt.h @@ -93,40 +93,40 @@ void ff_spatial_idwt_slice2(DWTContext *d, int y); // shared stuff for simd optimizations #define COMPOSE_53iL0(b0, b1, b2)\ - (b1 - ((b0 + b2 + 2) >> 2)) + (b1 - (unsigned)((int)(b0 + (unsigned)(b2) + 2) >> 2)) #define COMPOSE_DIRAC53iH0(b0, b1, b2)\ - (b1 + ((b0 + b2 + 1) >> 1)) + (b1 + (unsigned)((int)(b0 + (unsigned)(b2) + 1) >> 1)) #define COMPOSE_DD97iH0(b0, b1, b2, b3, b4)\ - (b2 + ((-b0 + 9*b1 + 9*b3 - b4 + 8) >> 4)) + (int)(((unsigned)(b2) + ((int)(9U*b1 + 9U*b3 - b4 - b0 + 8) >> 4))) #define COMPOSE_DD137iL0(b0, b1, b2, b3, b4)\ - (b2 - ((-b0 + 9*b1 + 9*b3 - b4 + 16) >> 5)) + (int)(((unsigned)(b2) - ((int)(9U*b1 + 9U*b3 - b4 - b0 + 16) >> 5))) #define COMPOSE_HAARiL0(b0, b1)\ - (b0 - ((b1 + 1) >> 1)) + ((int)(b0 - (unsigned)((int)(b1 + 1U) >> 1))) #define COMPOSE_HAARiH0(b0, b1)\ - (b0 + b1) + ((int)(b0 + (unsigned)(b1))) #define COMPOSE_FIDELITYiL0(b0, b1, b2, b3, b4, b5, b6, b7, b8)\ - (b4 - ((-8*(b0+b8) + 21*(b1+b7) - 46*(b2+b6) + 161*(b3+b5) + 128) >> 8)) + ((unsigned)b4 - ((int)(-8*(b0+(unsigned)b8) + 21*(b1+(unsigned)b7) - 46*(b2+(unsigned)b6) + 161*(b3+(unsigned)b5) + 128) >> 8)) #define COMPOSE_FIDELITYiH0(b0, b1, b2, b3, b4, b5, b6, b7, b8)\ - (b4 + ((-2*(b0+b8) + 10*(b1+b7) - 25*(b2+b6) + 81*(b3+b5) + 128) >> 8)) + ((unsigned)b4 + ((int)(-2*(b0+(unsigned)b8) + 10*(b1+(unsigned)b7) - 25*(b2+(unsigned)b6) + 81*(b3+(unsigned)b5) + 128) >> 8)) #define COMPOSE_DAUB97iL1(b0, b1, b2)\ - (b1 - ((1817*(b0 + b2) + 2048) >> 12)) + ((unsigned)(b1) - ((int)(1817*(b0 + (unsigned)b2) + 2048) >> 12)) #define COMPOSE_DAUB97iH1(b0, b1, b2)\ - (b1 - (( 113*(b0 + b2) + 64) >> 7)) + ((unsigned)(b1) - ((int)( 113*(b0 + (unsigned)b2) + 64) >> 7)) #define COMPOSE_DAUB97iL0(b0, b1, b2)\ - (b1 + (( 217*(b0 + b2) + 2048) >> 12)) + ((unsigned)(b1) + ((int)( 217*(b0 + (unsigned)b2) + 2048) >> 12)) #define COMPOSE_DAUB97iH0(b0, b1, b2)\ - (b1 + ((6497*(b0 + b2) + 2048) >> 12)) + ((unsigned)(b1) + ((int)(6497*(b0 + (unsigned)b2) + 2048) >> 12)) #endif /* AVCODEC_DWT_H */ diff --git a/libavcodec/dirac_dwt_template.c b/libavcodec/dirac_dwt_template.c index 972c711cff..5d55d932a1 100644 --- a/libavcodec/dirac_dwt_template.c +++ b/libavcodec/dirac_dwt_template.c @@ -49,7 +49,7 @@ static void RENAME(vertical_compose53iL0)(uint8_t *_b0, uint8_t *_b1, uint8_t *_ TYPE *b1 = (TYPE *)_b1; TYPE *b2 = (TYPE *)_b2; for (i = 0; i < width; i++) - b1[i] -= (b0[i] + b2[i] + 2) >> 2; + b1[i] -= (unsigned)((int)(b0[i] + (unsigned)b2[i] + 2) >> 2); } static av_always_inline void RENAME(interleave)(TYPE *dst, TYPE *src0, TYPE *src1, int w2, @@ -57,8 +57,8 @@ static av_always_inline void RENAME(interleave)(TYPE *dst, TYPE *src0, TYPE *src { int i; for (i = 0; i < w2; i++) { - dst[2*i ] = (src0[i] + add) >> shift; - dst[2*i+1] = (src1[i] + add) >> shift; + dst[2*i ] = ((int)(src0[i] + (unsigned)add)) >> shift; + dst[2*i+1] = ((int)(src1[i] + (unsigned)add)) >> shift; } } @@ -95,8 +95,8 @@ static void RENAME(horizontal_compose_dd97i)(uint8_t *_b, uint8_t *_tmp, int w) tmp[w2+1] = tmp[w2] = tmp[w2-1]; for (x = 0; x < w2; x++) { - b[2*x ] = (tmp[x] + 1)>>1; - b[2*x+1] = (COMPOSE_DD97iH0(tmp[x-1], tmp[x], b[x+w2], tmp[x+1], tmp[x+2]) + 1)>>1; + b[2*x ] = ((int)(tmp[x] + 1U))>>1; + b[2*x+1] = ((int)(COMPOSE_DD97iH0(tmp[x-1], tmp[x], b[x+w2], tmp[x+1], tmp[x+2]) + 1U))>>1; } } @@ -118,8 +118,8 @@ static void RENAME(horizontal_compose_dd137i)(uint8_t *_b, uint8_t *_tmp, int w) tmp[w2+1] = tmp[w2] = tmp[w2-1]; for (x = 0; x < w2; x++) { - b[2*x ] = (tmp[x] + 1)>>1; - b[2*x+1] = (COMPOSE_DD97iH0(tmp[x-1], tmp[x], b[x+w2], tmp[x+1], tmp[x+2]) + 1)>>1; + b[2*x ] = ((int)(tmp[x] + 1U))>>1; + b[2*x+1] = ((int)(COMPOSE_DD97iH0(tmp[x-1], tmp[x], b[x+w2], tmp[x+1], tmp[x+2]) + 1U))>>1; } } @@ -190,15 +190,15 @@ static void RENAME(horizontal_compose_daub97i)(uint8_t *_b, uint8_t *_temp, int // second stage combined with interleave and shift b0 = b2 = COMPOSE_DAUB97iL0(temp[w2], temp[0], temp[w2]); - b[0] = (b0 + 1) >> 1; + b[0] = ~((~b0) >> 1); for (x = 1; x < w2; x++) { b2 = COMPOSE_DAUB97iL0(temp[x+w2-1], temp[x ], temp[x+w2]); b1 = COMPOSE_DAUB97iH0( b0, temp[x+w2-1], b2 ); - b[2*x-1] = (b1 + 1) >> 1; - b[2*x ] = (b2 + 1) >> 1; + b[2*x-1] = ~((~b1) >> 1); + b[2*x ] = ~((~b2) >> 1); b0 = b2; } - b[w-1] = (COMPOSE_DAUB97iH0(b2, temp[w-1], b2) + 1) >> 1; + b[w-1] = ~((~COMPOSE_DAUB97iH0(b2, temp[w-1], b2)) >> 1); } static void RENAME(vertical_compose_dirac53iH0)(uint8_t *_b0, uint8_t *_b1, uint8_t *_b2, diff --git a/libavcodec/diracdec.c b/libavcodec/diracdec.c index e530a05de3..272f2b4011 100644 --- a/libavcodec/diracdec.c +++ b/libavcodec/diracdec.c @@ -129,7 +129,7 @@ typedef struct DiracContext { GetBitContext gb; AVDiracSeqHeader seq; int seen_sequence_header; - int frame_number; /* number of the next frame to display */ + int64_t frame_number; /* number of the next frame to display */ Plane plane[3]; int chroma_x_shift; int chroma_y_shift; @@ -173,7 +173,7 @@ typedef struct DiracContext { struct { unsigned prefix_bytes; - unsigned size_scaler; + uint64_t size_scaler; } highquality; struct { @@ -231,7 +231,7 @@ enum dirac_subband { /* magic number division by 3 from schroedinger */ static inline int divide3(int x) { - return ((x+1)*21845 + 10922) >> 16; + return (int)((x+1U)*21845 + 10922) >> 16; } static DiracFrame *remove_frame(DiracFrame *framelist[], int picnum) @@ -462,7 +462,8 @@ static inline int coeff_unpack_golomb(GetBitContext *gb, int qfactor, int qoffse static inline void coeff_unpack_arith_##n(DiracArith *c, int qfactor, int qoffset, \ SubBand *b, type *buf, int x, int y) \ { \ - int coeff, sign, sign_pred = 0, pred_ctx = CTX_ZPZN_F1; \ + int sign, sign_pred = 0, pred_ctx = CTX_ZPZN_F1; \ + unsigned coeff; \ const int mstride = -(b->stride >> (1+b->pshift)); \ if (b->parent) { \ const type *pbuf = (type *)b->parent->ibuf; \ @@ -515,16 +516,16 @@ static inline void codeblock(DiracContext *s, SubBand *b, } if (s->codeblock_mode && !(s->old_delta_quant && blockcnt_one)) { - int quant = b->quant; + int quant; if (is_arith) - quant += dirac_get_arith_int(c, CTX_DELTA_Q_F, CTX_DELTA_Q_DATA); + quant = dirac_get_arith_int(c, CTX_DELTA_Q_F, CTX_DELTA_Q_DATA); else - quant += dirac_get_se_golomb(gb); - if (quant < 0) { + quant = dirac_get_se_golomb(gb); + if (quant > INT_MAX - b->quant || b->quant + quant < 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid quant\n"); return; } - b->quant = quant; + b->quant += quant; } if (b->quant > 115) { @@ -593,7 +594,7 @@ static inline void codeblock(DiracContext *s, SubBand *b, } \ INTRA_DC_PRED(8, int16_t) -INTRA_DC_PRED(10, int32_t) +INTRA_DC_PRED(10, uint32_t) /** * Dirac Specification -> @@ -826,9 +827,15 @@ static int decode_hq_slice(AVCodecContext *avctx, void *arg) /* Luma + 2 Chroma planes */ for (i = 0; i < 3; i++) { - int length = s->highquality.size_scaler * get_bits(gb, 8); - int bits_left = 8 * length; - int bits_end = get_bits_count(gb) + bits_left; + int64_t length = s->highquality.size_scaler * get_bits(gb, 8); + int64_t bits_left = 8 * length; + int64_t bits_end = get_bits_count(gb) + bits_left; + + if (bits_end >= INT_MAX) { + av_log(s->avctx, AV_LOG_ERROR, "end too far away\n"); + return AVERROR_INVALIDDATA; + } + for (level = 0; level < s->wavelet_depth; level++) { for (orientation = !!level; orientation < 4; orientation++) { decode_subband(s, gb, quants[level][orientation], slice->slice_x, slice->slice_y, bits_end, @@ -848,7 +855,8 @@ static int decode_hq_slice(AVCodecContext *avctx, void *arg) static int decode_lowdelay(DiracContext *s) { AVCodecContext *avctx = s->avctx; - int slice_x, slice_y, bytes = 0, bufsize; + int slice_x, slice_y, bufsize; + int64_t bytes = 0; const uint8_t *buf; DiracSlice *slices; int slice_num = 0; @@ -872,6 +880,11 @@ static int decode_lowdelay(DiracContext *s) if (bytes <= bufsize/8) bytes += buf[bytes] * s->highquality.size_scaler + 1; } + if (bytes >= INT_MAX) { + av_log(s->avctx, AV_LOG_ERROR, "too many bytes\n"); + av_free(slices); + return AVERROR_INVALIDDATA; + } slices[slice_num].bytes = bytes; slices[slice_num].slice_x = slice_x; @@ -891,8 +904,12 @@ static int decode_lowdelay(DiracContext *s) } else { for (slice_y = 0; bufsize > 0 && slice_y < s->num_y; slice_y++) { for (slice_x = 0; bufsize > 0 && slice_x < s->num_x; slice_x++) { - bytes = (slice_num+1) * s->lowdelay.bytes.num / s->lowdelay.bytes.den - - slice_num * s->lowdelay.bytes.num / s->lowdelay.bytes.den; + bytes = (slice_num+1) * (int64_t)s->lowdelay.bytes.num / s->lowdelay.bytes.den + - slice_num * (int64_t)s->lowdelay.bytes.num / s->lowdelay.bytes.den; + if (bytes >= INT_MAX || bytes*8 > bufsize) { + av_log(s->avctx, AV_LOG_ERROR, "too many bytes\n"); + return AVERROR_INVALIDDATA; + } slices[slice_num].bytes = bytes; slices[slice_num].slice_x = slice_x; slices[slice_num].slice_y = slice_y; @@ -1069,6 +1086,10 @@ static int dirac_unpack_prediction_parameters(DiracContext *s) s->globalmc[ref].perspective[0] = dirac_get_se_golomb(gb); s->globalmc[ref].perspective[1] = dirac_get_se_golomb(gb); } + if (s->globalmc[ref].perspective_exp + (uint64_t)s->globalmc[ref].zrs_exp > 30) { + return AVERROR_INVALIDDATA; + } + } } @@ -1141,6 +1162,11 @@ static int dirac_unpack_idwt_params(DiracContext *s) else { s->num_x = svq3_get_ue_golomb(gb); s->num_y = svq3_get_ue_golomb(gb); + if (s->num_x * s->num_y == 0 || s->num_x * (uint64_t)s->num_y > INT_MAX) { + av_log(s->avctx,AV_LOG_ERROR,"Invalid numx/y\n"); + s->num_x = s->num_y = 0; + return AVERROR_INVALIDDATA; + } if (s->ld_picture) { s->lowdelay.bytes.num = svq3_get_ue_golomb(gb); s->lowdelay.bytes.den = svq3_get_ue_golomb(gb); @@ -1151,6 +1177,10 @@ static int dirac_unpack_idwt_params(DiracContext *s) } else if (s->hq_picture) { s->highquality.prefix_bytes = svq3_get_ue_golomb(gb); s->highquality.size_scaler = svq3_get_ue_golomb(gb); + if (s->highquality.prefix_bytes >= INT_MAX / 8) { + av_log(s->avctx,AV_LOG_ERROR,"too many prefix bytes\n"); + return AVERROR_INVALIDDATA; + } } /* [DIRAC_STD] 11.3.5 Quantisation matrices (low-delay syntax). quant_matrix() */ @@ -1289,8 +1319,8 @@ static void global_mv(DiracContext *s, DiracBlock *block, int x, int y, int ref) int *c = s->globalmc[ref].perspective; int m = (1<u.mv[ref][0] = (mx + (1<<(ez+ep))) >> (ez+ep); block->u.mv[ref][1] = (my + (1<<(ez+ep))) >> (ez+ep); @@ -1312,7 +1342,7 @@ static void decode_block_params(DiracContext *s, DiracArith arith[8], DiracBlock if (!block->ref) { pred_block_dc(block, stride, x, y); for (i = 0; i < 3; i++) - block->u.dc[i] += dirac_get_arith_int(arith+1+i, CTX_DC_F1, CTX_DC_DATA); + block->u.dc[i] += (unsigned)dirac_get_arith_int(arith+1+i, CTX_DC_F1, CTX_DC_DATA); return; } @@ -1327,8 +1357,8 @@ static void decode_block_params(DiracContext *s, DiracArith arith[8], DiracBlock global_mv(s, block, x, y, i); } else { pred_mv(block, stride, x, y, i); - block->u.mv[i][0] += dirac_get_arith_int(arith + 4 + 2 * i, CTX_MV_F1, CTX_MV_DATA); - block->u.mv[i][1] += dirac_get_arith_int(arith + 5 + 2 * i, CTX_MV_F1, CTX_MV_DATA); + block->u.mv[i][0] += (unsigned)dirac_get_arith_int(arith + 4 + 2 * i, CTX_MV_F1, CTX_MV_DATA); + block->u.mv[i][1] += (unsigned)dirac_get_arith_int(arith + 5 + 2 * i, CTX_MV_F1, CTX_MV_DATA); } } } @@ -1879,7 +1909,9 @@ static int dirac_decode_picture_header(DiracContext *s) for (j = 0; j < MAX_FRAMES; j++) if (!s->all_frames[j].avframe->data[0]) { s->ref_pics[i] = &s->all_frames[j]; - get_buffer_with_edge(s->avctx, s->ref_pics[i]->avframe, AV_GET_BUFFER_FLAG_REF); + ret = get_buffer_with_edge(s->avctx, s->ref_pics[i]->avframe, AV_GET_BUFFER_FLAG_REF); + if (ret < 0) + return ret; break; } @@ -1943,9 +1975,9 @@ static int get_delayed_pic(DiracContext *s, AVFrame *picture, int *got_frame) if (out) { out->reference ^= DELAYED_PIC_REF; - *got_frame = 1; if((ret = av_frame_ref(picture, out->avframe)) < 0) return ret; + *got_frame = 1; } return 0; @@ -2186,7 +2218,7 @@ static int dirac_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, } if (*got_frame) - s->frame_number = picture->display_picture_number + 1; + s->frame_number = picture->display_picture_number + 1LL; return buf_idx; } diff --git a/libavcodec/diracdsp.c b/libavcodec/diracdsp.c index ab8d1497f7..33c8a6cb1e 100644 --- a/libavcodec/diracdsp.c +++ b/libavcodec/diracdsp.c @@ -159,10 +159,10 @@ static void put_signed_rect_clamped_ ## PX ## bit_c(uint8_t *_dst, int dst_strid int32_t *src = (int32_t *)_src; \ for (y = 0; y < height; y++) { \ for (x = 0; x < width; x+=4) { \ - dst[x ] = av_clip_uintp2(src[x ] + (1 << (PX - 1)), PX); \ - dst[x+1] = av_clip_uintp2(src[x+1] + (1 << (PX - 1)), PX); \ - dst[x+2] = av_clip_uintp2(src[x+2] + (1 << (PX - 1)), PX); \ - dst[x+3] = av_clip_uintp2(src[x+3] + (1 << (PX - 1)), PX); \ + dst[x ] = av_clip_uintp2(src[x ] + (1U << (PX - 1)), PX); \ + dst[x+1] = av_clip_uintp2(src[x+1] + (1U << (PX - 1)), PX); \ + dst[x+2] = av_clip_uintp2(src[x+2] + (1U << (PX - 1)), PX); \ + dst[x+3] = av_clip_uintp2(src[x+3] + (1U << (PX - 1)), PX); \ } \ dst += dst_stride >> 1; \ src += src_stride >> 2; \ diff --git a/libavcodec/dnxhddec.c b/libavcodec/dnxhddec.c index 18080803fa..5f772b99a9 100644 --- a/libavcodec/dnxhddec.c +++ b/libavcodec/dnxhddec.c @@ -278,14 +278,18 @@ static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame, if (header_prefix == DNXHD_HEADER_HR2) { ctx->data_offset = 0x170 + (ctx->mb_height << 2); } else { - if (ctx->mb_height > 68 || - (ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) { + if (ctx->mb_height > 68) { av_log(ctx->avctx, AV_LOG_ERROR, "mb height too big: %d\n", ctx->mb_height); return AVERROR_INVALIDDATA; } ctx->data_offset = 0x280; } + if ((ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) { + av_log(ctx->avctx, AV_LOG_ERROR, + "mb height too big: %d\n", ctx->mb_height); + return AVERROR_INVALIDDATA; + } if (buf_size < ctx->data_offset) { av_log(ctx->avctx, AV_LOG_ERROR, @@ -352,6 +356,10 @@ static av_always_inline int dnxhd_decode_dct_block(const DNXHDContext *ctx, UPDATE_CACHE(bs, &row->gb); GET_VLC(len, bs, &row->gb, ctx->dc_vlc.table, DNXHD_DC_VLC_BITS, 1); + if (len < 0) { + ret = len; + goto error; + } if (len) { level = GET_CACHE(bs, &row->gb); LAST_SKIP_BITS(bs, &row->gb, len); @@ -405,7 +413,7 @@ static av_always_inline int dnxhd_decode_dct_block(const DNXHDContext *ctx, GET_VLC(index1, bs, &row->gb, ctx->ac_vlc.table, DNXHD_VLC_BITS, 2); } - +error: CLOSE_READER(bs, &row->gb); return ret; } diff --git a/libavcodec/dsicinvideo.c b/libavcodec/dsicinvideo.c index f95cbc74a0..aa080417d2 100644 --- a/libavcodec/dsicinvideo.c +++ b/libavcodec/dsicinvideo.c @@ -158,6 +158,9 @@ static int cin_decode_lzss(const unsigned char *src, int src_size, } } + if (dst_end - dst > dst_size - dst_size/10) + return AVERROR_INVALIDDATA; + return 0; } @@ -184,6 +187,10 @@ static int cin_decode_rle(const unsigned char *src, int src_size, } dst += len; } + + if (dst_end - dst > dst_size - dst_size/10) + return AVERROR_INVALIDDATA; + return 0; } @@ -226,27 +233,35 @@ static int cinvideo_decode_frame(AVCodecContext *avctx, * surface.width = surface.pitch */ switch (bitmap_frame_type) { case 9: - cin_decode_rle(buf, bitmap_frame_size, + res = cin_decode_rle(buf, bitmap_frame_size, cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size); + if (res < 0) + return res; break; case 34: - cin_decode_rle(buf, bitmap_frame_size, + res = cin_decode_rle(buf, bitmap_frame_size, cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size); + if (res < 0) + return res; cin_apply_delta_data(cin->bitmap_table[CIN_PRE_BMP], cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size); break; case 35: bitmap_frame_size = cin_decode_huffman(buf, bitmap_frame_size, cin->bitmap_table[CIN_INT_BMP], cin->bitmap_size); - cin_decode_rle(cin->bitmap_table[CIN_INT_BMP], bitmap_frame_size, + res = cin_decode_rle(cin->bitmap_table[CIN_INT_BMP], bitmap_frame_size, cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size); + if (res < 0) + return res; break; case 36: bitmap_frame_size = cin_decode_huffman(buf, bitmap_frame_size, cin->bitmap_table[CIN_INT_BMP], cin->bitmap_size); - cin_decode_rle(cin->bitmap_table[CIN_INT_BMP], bitmap_frame_size, + res = cin_decode_rle(cin->bitmap_table[CIN_INT_BMP], bitmap_frame_size, cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size); + if (res < 0) + return res; cin_apply_delta_data(cin->bitmap_table[CIN_PRE_BMP], cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size); break; diff --git a/libavcodec/dss_sp.c b/libavcodec/dss_sp.c index 7cf84899fc..f5dfda3642 100644 --- a/libavcodec/dss_sp.c +++ b/libavcodec/dss_sp.c @@ -33,7 +33,7 @@ #define DSS_SP_FRAME_SIZE 42 #define DSS_SP_SAMPLE_COUNT (66 * SUBFRAMES) -#define DSS_SP_FORMULA(a, b, c) (((((a) << 15) + (b) * (c)) + 0x4000) >> 15) +#define DSS_SP_FORMULA(a, b, c) ((int)((((a) * (1 << 15)) + (b) * (unsigned)(c)) + 0x4000) >> 15) typedef struct DssSpSubframe { int16_t gain; @@ -499,7 +499,7 @@ static void dss_sp_scale_vector(int32_t *vec, int bits, int size) vec[i] = vec[i] >> -bits; else for (i = 0; i < size; i++) - vec[i] = vec[i] << bits; + vec[i] = vec[i] * (1 << bits); } static void dss_sp_update_buf(int32_t *hist, int32_t *vector) @@ -524,12 +524,12 @@ static void dss_sp_shift_sq_sub(const int32_t *filter_buf, tmp = dst[a] * filter_buf[0]; for (i = 14; i > 0; i--) - tmp -= error_buf[i] * filter_buf[i]; + tmp -= error_buf[i] * (unsigned)filter_buf[i]; for (i = 14; i > 0; i--) error_buf[i] = error_buf[i - 1]; - tmp = (tmp + 4096) >> 13; + tmp = (int)(tmp + 4096U) >> 13; error_buf[1] = tmp; diff --git a/libavcodec/dvbsubdec.c b/libavcodec/dvbsubdec.c index a4663d997f..7c9ae999c2 100644 --- a/libavcodec/dvbsubdec.c +++ b/libavcodec/dvbsubdec.c @@ -24,6 +24,7 @@ #include "bytestream.h" #include "internal.h" #include "libavutil/colorspace.h" +#include "libavutil/imgutils.h" #include "libavutil/opt.h" #define DVBSUB_PAGE_SEGMENT 0x10 @@ -810,7 +811,7 @@ static void compute_default_clut(AVSubtitleRect *rect, int w, int h) list_inv[ i ] = bestv; } - count = i - 1; + count = FFMAX(i - 1, 1); for (i--; i>=0; i--) { int v = i*255/count; AV_WN32(rect->data[1] + 4*list_inv[i], RGBA(v/2,v,v/2,v)); @@ -1214,9 +1215,9 @@ static int dvbsub_parse_clut_segment(AVCodecContext *avctx, return AVERROR_INVALIDDATA; } - if (depth & 0x80) + if (depth & 0x80 && entry_id < 4) clut->clut4[entry_id] = RGBA(r,g,b,255 - alpha); - else if (depth & 0x40) + else if (depth & 0x40 && entry_id < 16) clut->clut16[entry_id] = RGBA(r,g,b,255 - alpha); else if (depth & 0x20) clut->clut256[entry_id] = RGBA(r,g,b,255 - alpha); @@ -1239,6 +1240,7 @@ static int dvbsub_parse_region_segment(AVCodecContext *avctx, DVBSubObject *object; DVBSubObjectDisplay *display; int fill; + int ret; if (buf_size < 10) return AVERROR_INVALIDDATA; @@ -1267,6 +1269,12 @@ static int dvbsub_parse_region_segment(AVCodecContext *avctx, region->height = AV_RB16(buf); buf += 2; + ret = av_image_check_size(region->width, region->height, 0, avctx); + if (ret < 0) { + region->width= region->height= 0; + return ret; + } + if (region->width * region->height != region->buf_size) { av_free(region->pbuf); diff --git a/libavcodec/dvdsub_parser.c b/libavcodec/dvdsub_parser.c index 32a945ed65..698ccb6987 100644 --- a/libavcodec/dvdsub_parser.c +++ b/libavcodec/dvdsub_parser.c @@ -44,6 +44,9 @@ static int dvdsub_parse(AVCodecParserContext *s, { DVDSubParseContext *pc = s->priv_data; + *poutbuf = buf; + *poutbuf_size = buf_size; + if (pc->packet_index == 0) { if (buf_size < 2 || AV_RB16(buf) && buf_size < 6) { if (buf_size) @@ -54,7 +57,11 @@ static int dvdsub_parse(AVCodecParserContext *s, if (pc->packet_len == 0) /* HD-DVD subpicture packet */ pc->packet_len = AV_RB32(buf+2); av_freep(&pc->packet); - pc->packet = av_malloc(pc->packet_len); + if ((unsigned)pc->packet_len > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) { + av_log(avctx, AV_LOG_ERROR, "packet length %d is invalid\n", pc->packet_len); + return buf_size; + } + pc->packet = av_malloc(pc->packet_len + AV_INPUT_BUFFER_PADDING_SIZE); } if (pc->packet) { if (pc->packet_index + buf_size <= pc->packet_len) { diff --git a/libavcodec/dvdsubdec.c b/libavcodec/dvdsubdec.c index 19f25f0e60..c564a889e3 100644 --- a/libavcodec/dvdsubdec.c +++ b/libavcodec/dvdsubdec.c @@ -60,7 +60,7 @@ static void yuv_a_to_rgba(const uint8_t *ycbcr, const uint8_t *alpha, uint32_t * cb = *ycbcr++; YUV_TO_RGB1_CCIR(cb, cr); YUV_TO_RGB2_CCIR(r, g, b, y); - *rgba++ = (*alpha++ << 24) | (r << 16) | (g << 8) | b; + *rgba++ = ((unsigned)*alpha++ << 24) | (r << 16) | (g << 8) | b; } } @@ -82,10 +82,7 @@ static int decode_run_8bit(GetBitContext *gb, int *color) { int len; int has_run = get_bits1(gb); - if (get_bits1(gb)) - *color = get_bits(gb, 8); - else - *color = get_bits(gb, 2); + *color = get_bits(gb, 2 + 6*get_bits1(gb)); if (has_run) { if (get_bits1(gb)) { len = get_bits(gb, 7); @@ -127,6 +124,8 @@ static int decode_rle(uint8_t *bitmap, int linesize, int w, int h, len = decode_run_8bit(&gb, &color); else len = decode_run_2bit(&gb, &color); + if (len != INT_MAX && len > w - x) + return AVERROR_INVALIDDATA; len = FFMIN(len, w - x); memset(d + x, color, len); x += len; @@ -185,16 +184,16 @@ static void guess_palette(DVDSubContext* ctx, for(i = 0; i < 4; i++) { if (alpha[i] != 0) { if (!color_used[colormap[i]]) { - level = level_map[nb_opaque_colors][j]; + level = level_map[nb_opaque_colors - 1][j]; r = (((subtitle_color >> 16) & 0xff) * level) >> 8; g = (((subtitle_color >> 8) & 0xff) * level) >> 8; b = (((subtitle_color >> 0) & 0xff) * level) >> 8; - rgba_palette[i] = b | (g << 8) | (r << 16) | ((alpha[i] * 17) << 24); + rgba_palette[i] = b | (g << 8) | (r << 16) | ((alpha[i] * 17U) << 24); color_used[colormap[i]] = (i + 1); j++; } else { rgba_palette[i] = (rgba_palette[color_used[colormap[i]] - 1] & 0x00ffffff) | - ((alpha[i] * 17) << 24); + ((alpha[i] * 17U) << 24); } } } @@ -548,7 +547,8 @@ static int append_to_cached_buf(AVCodecContext *avctx, { DVDSubContext *ctx = avctx->priv_data; - if (ctx->buf_size >= sizeof(ctx->buf) - buf_size) { + av_assert0(buf_size >= 0 && ctx->buf_size <= sizeof(ctx->buf)); + if (buf_size >= sizeof(ctx->buf) - ctx->buf_size) { av_log(avctx, AV_LOG_WARNING, "Attempt to reconstruct " "too large SPU packets aborted.\n"); ctx->buf_size = 0; diff --git a/libavcodec/dxtory.c b/libavcodec/dxtory.c index fc1936985d..2ac40dd2d1 100644 --- a/libavcodec/dxtory.c +++ b/libavcodec/dxtory.c @@ -304,11 +304,7 @@ static int dxtory_decode_v2(AVCodecContext *avctx, AVFrame *pic, } if (avctx->height - line) { - av_log(avctx, AV_LOG_VERBOSE, - "Not enough slice data available, " - "cropping the frame by %d pixels\n", - avctx->height - line); - avctx->height = line; + avpriv_request_sample(avctx, "Not enough slice data available"); } return 0; @@ -325,7 +321,7 @@ static int dx2_decode_slice_5x5(GetBitContext *gb, AVFrame *frame, int stride = frame->linesize[0]; uint8_t *dst = frame->data[0] + stride * line; - for (y = 0; y < left && get_bits_left(gb) > 16; y++) { + for (y = 0; y < left && get_bits_left(gb) > 6 * width; y++) { for (x = 0; x < width; x++) { b = decode_sym_565(gb, lru[0], 5); g = decode_sym_565(gb, lru[1], is_565 ? 6 : 5); @@ -391,7 +387,7 @@ static int dx2_decode_slice_rgb(GetBitContext *gb, AVFrame *frame, int stride = frame->linesize[0]; uint8_t *dst = frame->data[0] + stride * line; - for (y = 0; y < left && get_bits_left(gb) > 16; y++) { + for (y = 0; y < left && get_bits_left(gb) > 6 * width; y++) { for (x = 0; x < width; x++) { dst[x * 3 + 0] = decode_sym(gb, lru[0]); dst[x * 3 + 1] = decode_sym(gb, lru[1]); @@ -436,7 +432,7 @@ static int dx2_decode_slice_410(GetBitContext *gb, AVFrame *frame, uint8_t *U = frame->data[1] + (ustride >> 2) * line; uint8_t *V = frame->data[2] + (vstride >> 2) * line; - for (y = 0; y < left - 3 && get_bits_left(gb) > 16; y += 4) { + for (y = 0; y < left - 3 && get_bits_left(gb) > 9 * width; y += 4) { for (x = 0; x < width; x += 4) { for (j = 0; j < 4; j++) for (i = 0; i < 4; i++) @@ -480,7 +476,7 @@ static int dx2_decode_slice_420(GetBitContext *gb, AVFrame *frame, uint8_t *V = frame->data[2] + (vstride >> 1) * line; - for (y = 0; y < left - 1 && get_bits_left(gb) > 16; y += 2) { + for (y = 0; y < left - 1 && get_bits_left(gb) > 6 * width; y += 2) { for (x = 0; x < width; x += 2) { Y[x + 0 + 0 * ystride] = decode_sym(gb, lru[0]); Y[x + 1 + 0 * ystride] = decode_sym(gb, lru[0]); @@ -523,7 +519,7 @@ static int dx2_decode_slice_444(GetBitContext *gb, AVFrame *frame, uint8_t *U = frame->data[1] + ustride * line; uint8_t *V = frame->data[2] + vstride * line; - for (y = 0; y < left && get_bits_left(gb) > 16; y++) { + for (y = 0; y < left && get_bits_left(gb) > 6 * width; y++) { for (x = 0; x < width; x++) { Y[x] = decode_sym(gb, lru[0]); U[x] = decode_sym(gb, lru[1]) ^ 0x80; diff --git a/libavcodec/dxv.c b/libavcodec/dxv.c index 05a9aadd24..f194b134b5 100644 --- a/libavcodec/dxv.c +++ b/libavcodec/dxv.c @@ -331,6 +331,9 @@ static int dxv_decompress_raw(AVCodecContext *avctx) DXVContext *ctx = avctx->priv_data; GetByteContext *gbc = &ctx->gbc; + if (bytestream2_get_bytes_left(gbc) < ctx->tex_size) + return AVERROR_INVALIDDATA; + bytestream2_get_buffer(gbc, ctx->tex_data, ctx->tex_size); return 0; } diff --git a/libavcodec/eac3dec.c b/libavcodec/eac3dec.c index ef815afb55..001a404389 100644 --- a/libavcodec/eac3dec.c +++ b/libavcodec/eac3dec.c @@ -252,7 +252,7 @@ static void ff_eac3_decode_transform_coeffs_aht_ch(AC3DecodeContext *s, int ch) /* Vector Quantization */ int v = get_bits(gbc, bits); for (blk = 0; blk < 6; blk++) { - s->pre_mantissa[ch][bin][blk] = ff_eac3_mantissa_vq[hebap][v][blk] << 8; + s->pre_mantissa[ch][bin][blk] = ff_eac3_mantissa_vq[hebap][v][blk] * (1 << 8); } } else { /* Gain Adaptive Quantization */ @@ -271,16 +271,16 @@ static void ff_eac3_decode_transform_coeffs_aht_ch(AC3DecodeContext *s, int ch) int b; int mbits = bits - (2 - log_gain); mant = get_sbits(gbc, mbits); - mant <<= (23 - (mbits - 1)); + mant = ((unsigned)mant) << (23 - (mbits - 1)); /* remap mantissa value to correct for asymmetric quantization */ if (mant >= 0) b = 1 << (23 - log_gain); else - b = ff_eac3_gaq_remap_2_4_b[hebap-8][log_gain-1] << 8; + b = ff_eac3_gaq_remap_2_4_b[hebap-8][log_gain-1] * (1 << 8); mant += ((ff_eac3_gaq_remap_2_4_a[hebap-8][log_gain-1] * (int64_t)mant) >> 15) + b; } else { /* small mantissa, no GAQ, or Gk=1 */ - mant <<= 24 - bits; + mant *= (1 << 24 - bits); if (!log_gain) { /* remap mantissa value for no GAQ or Gk=1 */ mant += (ff_eac3_gaq_remap_1[hebap-8] * (int64_t)mant) >> 15; diff --git a/libavcodec/eamad.c b/libavcodec/eamad.c index 4e202f98a3..0525394838 100644 --- a/libavcodec/eamad.c +++ b/libavcodec/eamad.c @@ -284,7 +284,7 @@ static int decode_frame(AVCodecContext *avctx, if (avctx->width != width || avctx->height != height) { av_frame_unref(s->last_frame); - if((width * height)/2048*7 > bytestream2_get_bytes_left(&gb)) + if((width * (int64_t)height)/2048*7 > bytestream2_get_bytes_left(&gb)) return AVERROR_INVALIDDATA; if ((ret = ff_set_dimensions(avctx, width, height)) < 0) return ret; diff --git a/libavcodec/eatqi.c b/libavcodec/eatqi.c index 2423e21a41..75f914cd2f 100644 --- a/libavcodec/eatqi.c +++ b/libavcodec/eatqi.c @@ -93,7 +93,7 @@ static inline void tqi_idct_put(TqiContext *t, AVFrame *frame, int16_t (*block)[ static void tqi_calculate_qtable(MpegEncContext *s, int quant) { - const int qscale = (215 - 2*quant)*5; + const int64_t qscale = (215 - 2*quant)*5; int i; s->intra_matrix[0] = (ff_inv_aanscales[0]*ff_mpeg1_default_intra_matrix[0])>>11; for(i=1; i<64; i++) diff --git a/libavcodec/elsdec.c b/libavcodec/elsdec.c index 4797965457..cb0e9c6534 100644 --- a/libavcodec/elsdec.c +++ b/libavcodec/elsdec.c @@ -271,7 +271,7 @@ void ff_els_decoder_init(ElsDecCtx *ctx, const uint8_t *in, size_t data_size) void ff_els_decoder_uninit(ElsUnsignedRung *rung) { - av_free(rung->rem_rung_list); + av_freep(&rung->rem_rung_list); } static int els_import_byte(ElsDecCtx *ctx) @@ -391,12 +391,10 @@ unsigned ff_els_decode_unsigned(ElsDecCtx *ctx, ElsUnsignedRung *ur) if (ur->rung_list_size <= (ur->avail_index + 2) * sizeof(ElsRungNode)) { // remember rung_node position ptrdiff_t pos = rung_node - ur->rem_rung_list; - ur->rem_rung_list = av_realloc(ur->rem_rung_list, + ctx->err = av_reallocp(&ur->rem_rung_list, ur->rung_list_size + RUNG_SPACE); - if (!ur->rem_rung_list) { - av_free(ur->rem_rung_list); - ctx->err = AVERROR(ENOMEM); + if (ctx->err < 0) { return 0; } memset((uint8_t *) ur->rem_rung_list + ur->rung_list_size, 0, diff --git a/libavcodec/error_resilience.c b/libavcodec/error_resilience.c index 5a75faddf5..6bea0bf6ea 100644 --- a/libavcodec/error_resilience.c +++ b/libavcodec/error_resilience.c @@ -108,7 +108,7 @@ static void filter181(int16_t *data, int width, int height, int stride) dc = -prev_dc + data[x + y * stride] * 8 - data[x + 1 + y * stride]; - dc = (dc * 10923 + 32768) >> 16; + dc = (av_clip(dc, INT_MIN/10923, INT_MAX/10923 - 32768) * 10923 + 32768) >> 16; prev_dc = data[x + y * stride]; data[x + y * stride] = dc; } @@ -124,7 +124,7 @@ static void filter181(int16_t *data, int width, int height, int stride) dc = -prev_dc + data[x + y * stride] * 8 - data[x + (y + 1) * stride]; - dc = (dc * 10923 + 32768) >> 16; + dc = (av_clip(dc, INT_MIN/10923, INT_MAX/10923 - 32768) * 10923 + 32768) >> 16; prev_dc = data[x + y * stride]; data[x + y * stride] = dc; } diff --git a/libavcodec/escape124.c b/libavcodec/escape124.c index 50a86c8355..0965fdc3a7 100644 --- a/libavcodec/escape124.c +++ b/libavcodec/escape124.c @@ -222,7 +222,11 @@ static int escape124_decode_frame(AVCodecContext *avctx, // This call also guards the potential depth reads for the // codebook unpacking. - if (get_bits_left(&gb) < 64) + // Check if the amount we will read minimally is available on input. + // The 64 represent the immediately next 2 frame_* elements read, the 23/4320 + // represent a lower bound of the space needed for skipped superblocks. Non + // skipped SBs need more space. + if (get_bits_left(&gb) < 64 + s->num_superblocks * 23LL / 4320) return -1; frame_flags = get_bits_long(&gb, 32); @@ -250,6 +254,10 @@ static int escape124_decode_frame(AVCodecContext *avctx, // This codebook can be cut off at places other than // powers of 2, leaving some of the entries undefined. cb_size = get_bits_long(&gb, 20); + if (!cb_size) { + av_log(avctx, AV_LOG_ERROR, "Invalid codebook size 0.\n"); + return AVERROR_INVALIDDATA; + } cb_depth = av_log2(cb_size - 1) + 1; } else { cb_depth = get_bits(&gb, 4); diff --git a/libavcodec/exr.c b/libavcodec/exr.c index 9ec99d65a0..ac00f85150 100644 --- a/libavcodec/exr.c +++ b/libavcodec/exr.c @@ -186,9 +186,9 @@ static union av_intfloat32 exr_half2float(uint16_t hf) * * @return normalized 16-bit unsigned int */ -static inline uint16_t exr_flt2uint(uint32_t v) +static inline uint16_t exr_flt2uint(int32_t v) { - unsigned int exp = v >> 23; + int32_t exp = v >> 23; // "HACK": negative values result in exp< 0, so clipping them to 0 // is also handled by this condition, avoids explicit check for sign bit. if (exp <= 127 + 7 - 24) // we would shift out all bits anyway @@ -539,7 +539,7 @@ static int huf_decode(const uint64_t *hcode, const HufDec *hdecod, while (lc > 0) { const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK]; - if (pl.len) { + if (pl.len && lc >= pl.len) { lc -= pl.len; get_code(pl.lit, rlc, c, lc, gb, out, oe, outb); } else { @@ -849,7 +849,7 @@ static int decode_block(AVCodecContext *avctx, void *tdata, line_offset = AV_RL64(s->gb.buffer + jobnr * 8); // Check if the buffer has the required bytes needed from the offset - if (line_offset > buf_size - 8) + if (buf_size < 8 || line_offset > buf_size - 8) return AVERROR_INVALIDDATA; src = buf + line_offset + 8; @@ -858,7 +858,7 @@ static int decode_block(AVCodecContext *avctx, void *tdata, return AVERROR_INVALIDDATA; data_size = AV_RL32(src - 4); - if (data_size <= 0 || data_size > buf_size) + if (data_size <= 0 || data_size > buf_size - line_offset - 8) return AVERROR_INVALIDDATA; s->ysize = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); diff --git a/libavcodec/ffv1dec.c b/libavcodec/ffv1dec.c index d2bf3a89fd..bf1b1b7302 100644 --- a/libavcodec/ffv1dec.c +++ b/libavcodec/ffv1dec.c @@ -45,7 +45,8 @@ static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state, if (get_rac(c, state + 0)) return 0; else { - int i, e, a; + int i, e; + unsigned a; e = 0; while (get_rac(c, state + 1 + FFMIN(e, 9))) { // 1..10 e++; @@ -482,7 +483,7 @@ static int read_quant_table(RangeCoder *c, int16_t *quant_table, int scale) memset(state, 128, sizeof(state)); for (v = 0; i < 128; v++) { - unsigned len = get_symbol(c, state, 0) + 1; + unsigned len = get_symbol(c, state, 0) + 1U; if (len > 128 - i || !len) return AVERROR_INVALIDDATA; @@ -802,7 +803,7 @@ static int read_header(FFV1Context *f) } else { const uint8_t *p = c->bytestream_end; for (f->slice_count = 0; - f->slice_count < MAX_SLICES && 3 < p - c->bytestream_start; + f->slice_count < MAX_SLICES && 3 + 5*!!f->ec < p - c->bytestream_start; f->slice_count++) { int trailer = 3 + 5*!!f->ec; int size = AV_RB24(p-trailer); @@ -1002,7 +1003,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPac const uint8_t *src[4]; uint8_t *dst[4]; ff_thread_await_progress(&f->last_picture, INT_MAX, 0); - for (j = 0; j < 4; j++) { + for (j = 0; j < desc->nb_components; j++) { int pixshift = desc->comp[j].depth > 8; int sh = (j == 1 || j == 2) ? f->chroma_h_shift : 0; int sv = (j == 1 || j == 2) ? f->chroma_v_shift : 0; @@ -1010,6 +1011,12 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPac (fs->slice_y >> sv) + ((fs->slice_x >> sh) << pixshift); src[j] = f->last_picture.f->data[j] + f->last_picture.f->linesize[j] * (fs->slice_y >> sv) + ((fs->slice_x >> sh) << pixshift); + + } + if (desc->flags & AV_PIX_FMT_FLAG_PAL || + desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL) { + dst[1] = p->data[1]; + src[1] = f->last_picture.f->data[1]; } av_image_copy(dst, p->linesize, src, f->last_picture.f->linesize, diff --git a/libavcodec/ffv1enc.c b/libavcodec/ffv1enc.c index 9ee992144b..6d12a06e97 100644 --- a/libavcodec/ffv1enc.c +++ b/libavcodec/ffv1enc.c @@ -699,6 +699,10 @@ static av_cold int encode_init(AVCodecContext *avctx) s->ec = (s->version >= 3); } + // CRC requires version 3+ + if (s->ec) + s->version = FFMAX(s->version, 3); + if ((s->version == 2 || s->version>3) && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { av_log(avctx, AV_LOG_ERROR, "Version 2 needed for requested features but version 2 is experimental and not enabled\n"); return AVERROR_INVALIDDATA; @@ -780,14 +784,12 @@ FF_ENABLE_DEPRECATION_WARNINGS s->colorspace = 1; s->transparency = 1; s->chroma_planes = 1; - if (!avctx->bits_per_raw_sample) - s->bits_per_raw_sample = 8; + s->bits_per_raw_sample = 8; break; case AV_PIX_FMT_0RGB32: s->colorspace = 1; s->chroma_planes = 1; - if (!avctx->bits_per_raw_sample) - s->bits_per_raw_sample = 8; + s->bits_per_raw_sample = 8; break; case AV_PIX_FMT_GBRP9: if (!avctx->bits_per_raw_sample) @@ -1224,7 +1226,6 @@ static int encode_frame(AVCodecContext *avctx, AVPacket *pkt, FFV1Context *f = avctx->priv_data; RangeCoder *const c = &f->slice_context[0]->c; AVFrame *const p = f->picture.f; - int used_count = 0; uint8_t keystate = 128; uint8_t *buf_p; int i, ret; @@ -1280,6 +1281,11 @@ static int encode_frame(AVCodecContext *avctx, AVPacket *pkt, if (f->version > 3) maxsize = AV_INPUT_BUFFER_MIN_SIZE + avctx->width*avctx->height*3LL*4; + if (maxsize > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE - 32) { + av_log(avctx, AV_LOG_WARNING, "Cannot allocate worst case packet size, the encoding could fail\n"); + maxsize = INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE - 32; + } + if ((ret = ff_alloc_packet2(avctx, pkt, maxsize, 0)) < 0) return ret; @@ -1309,11 +1315,17 @@ static int encode_frame(AVCodecContext *avctx, AVPacket *pkt, } } - for (i = 1; i < f->slice_count; i++) { + for (i = 0; i < f->slice_count; i++) { FFV1Context *fs = f->slice_context[i]; - uint8_t *start = pkt->data + (pkt->size - used_count) * (int64_t)i / f->slice_count; + uint8_t *start = pkt->data + pkt->size * (int64_t)i / f->slice_count; int len = pkt->size / f->slice_count; - ff_init_range_encoder(&fs->c, start, len); + if (i) { + ff_init_range_encoder(&fs->c, start, len); + } else { + av_assert0(fs->c.bytestream_end >= fs->c.bytestream_start + len); + av_assert0(fs->c.bytestream < fs->c.bytestream_start + len); + fs->c.bytestream_end = fs->c.bytestream_start + len; + } } avctx->execute(avctx, encode_slice, &f->slice_context[0], NULL, f->slice_count, sizeof(void *)); diff --git a/libavcodec/fic.c b/libavcodec/fic.c index 7d698f08d9..621d352547 100644 --- a/libavcodec/fic.c +++ b/libavcodec/fic.c @@ -81,29 +81,30 @@ static const uint8_t fic_qmat_lq[64] = { static const uint8_t fic_header[7] = { 0, 0, 1, 'F', 'I', 'C', 'V' }; #define FIC_HEADER_SIZE 27 +#define CURSOR_OFFSET 59 static av_always_inline void fic_idct(int16_t *blk, int step, int shift, int rnd) { - const int t0 = 27246 * blk[3 * step] + 18405 * blk[5 * step]; - const int t1 = 27246 * blk[5 * step] - 18405 * blk[3 * step]; - const int t2 = 6393 * blk[7 * step] + 32139 * blk[1 * step]; - const int t3 = 6393 * blk[1 * step] - 32139 * blk[7 * step]; - const int t4 = 5793 * (t2 + t0 + 0x800 >> 12); - const int t5 = 5793 * (t3 + t1 + 0x800 >> 12); - const int t6 = t2 - t0; - const int t7 = t3 - t1; - const int t8 = 17734 * blk[2 * step] - 42813 * blk[6 * step]; - const int t9 = 17734 * blk[6 * step] + 42814 * blk[2 * step]; - const int tA = (blk[0 * step] - blk[4 * step] << 15) + rnd; - const int tB = (blk[0 * step] + blk[4 * step] << 15) + rnd; - blk[0 * step] = ( t4 + t9 + tB) >> shift; - blk[1 * step] = ( t6 + t7 + t8 + tA) >> shift; - blk[2 * step] = ( t6 - t7 - t8 + tA) >> shift; - blk[3 * step] = ( t5 - t9 + tB) >> shift; - blk[4 * step] = ( -t5 - t9 + tB) >> shift; - blk[5 * step] = (-(t6 - t7) - t8 + tA) >> shift; - blk[6 * step] = (-(t6 + t7) + t8 + tA) >> shift; - blk[7 * step] = ( -t4 + t9 + tB) >> shift; + const unsigned t0 = 27246 * blk[3 * step] + 18405 * blk[5 * step]; + const unsigned t1 = 27246 * blk[5 * step] - 18405 * blk[3 * step]; + const unsigned t2 = 6393 * blk[7 * step] + 32139 * blk[1 * step]; + const unsigned t3 = 6393 * blk[1 * step] - 32139 * blk[7 * step]; + const unsigned t4 = 5793U * ((int)(t2 + t0 + 0x800) >> 12); + const unsigned t5 = 5793U * ((int)(t3 + t1 + 0x800) >> 12); + const unsigned t6 = t2 - t0; + const unsigned t7 = t3 - t1; + const unsigned t8 = 17734 * blk[2 * step] - 42813 * blk[6 * step]; + const unsigned t9 = 17734 * blk[6 * step] + 42814 * blk[2 * step]; + const unsigned tA = (blk[0 * step] - blk[4 * step]) * 32768 + rnd; + const unsigned tB = (blk[0 * step] + blk[4 * step]) * 32768 + rnd; + blk[0 * step] = (int)( t4 + t9 + tB) >> shift; + blk[1 * step] = (int)( t6 + t7 + t8 + tA) >> shift; + blk[2 * step] = (int)( t6 - t7 - t8 + tA) >> shift; + blk[3 * step] = (int)( t5 - t9 + tB) >> shift; + blk[4 * step] = (int)( -t5 - t9 + tB) >> shift; + blk[5 * step] = (int)(-(t6 - t7) - t8 + tA) >> shift; + blk[6 * step] = (int)(-(t6 + t7) + t8 + tA) >> shift; + blk[7 * step] = (int)( -t4 + t9 + tB) >> shift; } static void fic_idct_put(uint8_t *dst, int stride, int16_t *block) @@ -334,6 +335,10 @@ static int fic_decode_frame(AVCodecContext *avctx, void *data, skip_cursor = 1; } + if (!skip_cursor && avpkt->size < CURSOR_OFFSET + sizeof(ctx->cursor_buf)) { + skip_cursor = 1; + } + /* Slice height for all but the last slice. */ ctx->slice_h = 16 * (ctx->aligned_height >> 4) / nslices; if (ctx->slice_h % 16) @@ -413,7 +418,7 @@ static int fic_decode_frame(AVCodecContext *avctx, void *data, /* Draw cursor. */ if (!skip_cursor) { - memcpy(ctx->cursor_buf, src + 59, 32 * 32 * 4); + memcpy(ctx->cursor_buf, src + CURSOR_OFFSET, sizeof(ctx->cursor_buf)); fic_draw_cursor(avctx, cur_x, cur_y); } diff --git a/libavcodec/flac_parser.c b/libavcodec/flac_parser.c index 3723716441..00181f279a 100644 --- a/libavcodec/flac_parser.c +++ b/libavcodec/flac_parser.c @@ -586,10 +586,12 @@ static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx, temp = curr->next; av_freep(&curr->link_penalty); av_free(curr); + fpc->nb_headers_buffered--; } fpc->headers = fpc->best_header->next; av_freep(&fpc->best_header->link_penalty); av_freep(&fpc->best_header); + fpc->nb_headers_buffered--; } /* Find and score new headers. */ @@ -617,8 +619,8 @@ static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx, if (!av_fifo_space(fpc->fifo_buf) && av_fifo_size(fpc->fifo_buf) / FLAC_AVG_FRAME_SIZE > - fpc->nb_headers_buffered * 10) { - /* There is less than one valid flac header buffered for 10 headers + fpc->nb_headers_buffered * 20) { + /* There is less than one valid flac header buffered for 20 headers * buffered. Therefore the fifo is most likely filled with invalid * data and the input is not a flac file. */ goto handle_error; @@ -684,12 +686,17 @@ static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx, } for (curr = fpc->headers; curr; curr = curr->next) { - if (curr->max_score > 0 && - (!fpc->best_header || curr->max_score > fpc->best_header->max_score)) { + if (!fpc->best_header || curr->max_score > fpc->best_header->max_score) { fpc->best_header = curr; } } + if (fpc->best_header && fpc->best_header->max_score <= 0) { + // Only accept a bad header if there is no other option to continue + if (!buf_size || !buf || read_end != buf || fpc->nb_headers_buffered < FLAC_MIN_HEADERS) + fpc->best_header = NULL; + } + if (fpc->best_header) { fpc->best_header_valid = 1; if (fpc->best_header->offset > 0) { diff --git a/libavcodec/flacdec.c b/libavcodec/flacdec.c index b7237e18f0..f95f795f5e 100644 --- a/libavcodec/flacdec.c +++ b/libavcodec/flacdec.c @@ -201,12 +201,12 @@ static int get_metadata_size(const uint8_t *buf, int buf_size) buf += 4; do { if (buf_end - buf < 4) - return 0; + return AVERROR_INVALIDDATA; flac_parse_block_header(buf, &metadata_last, NULL, &metadata_size); buf += 4; if (buf_end - buf < metadata_size) { /* need more data in order to read the complete header */ - return 0; + return AVERROR_INVALIDDATA; } buf += metadata_size; } while (!metadata_last); @@ -268,7 +268,8 @@ static int decode_subframe_fixed(FLACContext *s, int32_t *decoded, int pred_order, int bps) { const int blocksize = s->blocksize; - int av_uninit(a), av_uninit(b), av_uninit(c), av_uninit(d), i; + unsigned av_uninit(a), av_uninit(b), av_uninit(c), av_uninit(d); + int i; int ret; /* warm up samples */ @@ -286,7 +287,7 @@ static int decode_subframe_fixed(FLACContext *s, int32_t *decoded, if (pred_order > 2) c = b - decoded[pred_order-2] + decoded[pred_order-3]; if (pred_order > 3) - d = c - decoded[pred_order-2] + 2*decoded[pred_order-3] - decoded[pred_order-4]; + d = c - decoded[pred_order-2] + 2U*decoded[pred_order-3] - decoded[pred_order-4]; switch (pred_order) { case 0: @@ -444,10 +445,10 @@ static inline int decode_subframe(FLACContext *s, int channel) return AVERROR_INVALIDDATA; } - if (wasted) { + if (wasted && wasted < 32) { int i; for (i = 0; i < s->blocksize; i++) - decoded[i] <<= wasted; + decoded[i] = (unsigned)decoded[i] << wasted; } return 0; diff --git a/libavcodec/flacdsp_template.c b/libavcodec/flacdsp_template.c index 62c0a15ff6..776c78da71 100644 --- a/libavcodec/flacdsp_template.c +++ b/libavcodec/flacdsp_template.c @@ -56,7 +56,7 @@ static void FUNC(flac_decorrelate_indep_c)(uint8_t **out, int32_t **in, for (j = 0; j < len; j++) for (i = 0; i < channels; i++) - S(samples, i, j) = in[i][j] << shift; + S(samples, i, j) = (int)((unsigned)in[i][j] << shift); } static void FUNC(flac_decorrelate_ls_c)(uint8_t **out, int32_t **in, diff --git a/libavcodec/flicvideo.c b/libavcodec/flicvideo.c index 3e0573af93..0ef7797a85 100644 --- a/libavcodec/flicvideo.c +++ b/libavcodec/flicvideo.c @@ -202,6 +202,9 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx, num_chunks = bytestream2_get_le16(&g2); bytestream2_skip(&g2, 8); /* skip padding */ + if (frame_size < 16) + return AVERROR_INVALIDDATA; + frame_size -= 16; /* iterate through the chunks */ @@ -272,10 +275,14 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx, while (compressed_lines > 0) { if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk) break; + if (y_ptr > pixel_limit) + return AVERROR_INVALIDDATA; line_packets = bytestream2_get_le16(&g2); if ((line_packets & 0xC000) == 0xC000) { // line skip opcode line_packets = -line_packets; + if (line_packets > s->avctx->height) + return AVERROR_INVALIDDATA; y_ptr += line_packets * s->frame->linesize[0]; } else if ((line_packets & 0xC000) == 0x4000) { av_log(avctx, AV_LOG_ERROR, "Undefined opcode (%x) in DELTA_FLI\n", line_packets); @@ -324,6 +331,8 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx, case FLI_LC: /* line compressed */ starting_line = bytestream2_get_le16(&g2); + if (starting_line >= s->avctx->height) + return AVERROR_INVALIDDATA; y_ptr = 0; y_ptr += starting_line * s->frame->linesize[0]; @@ -520,6 +529,8 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx, if (frame_size > buf_size) frame_size = buf_size; + if (frame_size < 16) + return AVERROR_INVALIDDATA; frame_size -= 16; /* iterate through the chunks */ @@ -556,9 +567,13 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx, while (compressed_lines > 0) { if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk) break; + if (y_ptr > pixel_limit) + return AVERROR_INVALIDDATA; line_packets = bytestream2_get_le16(&g2); if (line_packets < 0) { line_packets = -line_packets; + if (line_packets > s->avctx->height) + return AVERROR_INVALIDDATA; y_ptr += line_packets * s->frame->linesize[0]; } else { compressed_lines--; diff --git a/libavcodec/g2meet.c b/libavcodec/g2meet.c index 51e8bbcd7b..58bf070e42 100644 --- a/libavcodec/g2meet.c +++ b/libavcodec/g2meet.c @@ -555,8 +555,8 @@ static uint32_t epic_decode_pixel_pred(ePICContext *dc, int x, int y, B = ((pred >> B_shift) & 0xFF) - TOSIGNED(delta); } - if (R<0 || G<0 || B<0) { - av_log(NULL, AV_LOG_ERROR, "RGB %d %d %d is out of range\n", R, G, B); + if (R<0 || G<0 || B<0 || R > 255 || G > 255 || B > 255) { + avpriv_request_sample(NULL, "RGB %d %d %d is out of range\n", R, G, B); return 0; } @@ -926,6 +926,7 @@ static int epic_jb_decode_tile(G2MContext *c, int tile_x, int tile_y, if (c->ec.els_ctx.err != 0) { av_log(avctx, AV_LOG_ERROR, "ePIC: couldn't decode transparency pixel!\n"); + ff_els_decoder_uninit(&c->ec.unsigned_rung); return AVERROR_INVALIDDATA; } @@ -1354,14 +1355,16 @@ static void g2m_paint_cursor(G2MContext *c, uint8_t *dst, int stride) } else { dst += x * 3; } - if (y < 0) { + + if (y < 0) h += y; + if (w < 0 || h < 0) + return; + if (y < 0) { cursor += -y * c->cursor_stride; } else { dst += y * stride; } - if (w < 0 || h < 0) - return; for (j = 0; j < h; j++) { for (i = 0; i < w; i++) { diff --git a/libavcodec/g722.c b/libavcodec/g722.c index ee3b85f845..ef7ca6d446 100644 --- a/libavcodec/g722.c +++ b/libavcodec/g722.c @@ -88,14 +88,14 @@ static inline void s_zero(int cur_diff, struct G722Band *band) ACCUM(3, band->diff_mem[2], 1); ACCUM(2, band->diff_mem[1], 1); ACCUM(1, band->diff_mem[0], 1); - ACCUM(0, cur_diff << 1, 1); + ACCUM(0, cur_diff * 2, 1); } else { ACCUM(5, band->diff_mem[4], 0); ACCUM(4, band->diff_mem[3], 0); ACCUM(3, band->diff_mem[2], 0); ACCUM(2, band->diff_mem[1], 0); ACCUM(1, band->diff_mem[0], 0); - ACCUM(0, cur_diff << 1, 0); + ACCUM(0, cur_diff * 2, 0); } #undef ACCUM band->s_zero = s_zero; @@ -119,14 +119,14 @@ static void do_adaptive_prediction(struct G722Band *band, const int cur_diff) band->part_reconst_mem[0] = cur_part_reconst; band->pole_mem[1] = av_clip((sg[0] * av_clip(band->pole_mem[0], -8191, 8191) >> 5) + - (sg[1] << 7) + (band->pole_mem[1] * 127 >> 7), -12288, 12288); + (sg[1] * 128) + (band->pole_mem[1] * 127 >> 7), -12288, 12288); limit = 15360 - band->pole_mem[1]; band->pole_mem[0] = av_clip(-192 * sg[0] + (band->pole_mem[0] * 255 >> 8), -limit, limit); s_zero(cur_diff, band); - cur_qtzd_reconst = av_clip_int16((band->s_predictor + cur_diff) << 1); + cur_qtzd_reconst = av_clip_int16((band->s_predictor + cur_diff) * 2); band->s_predictor = av_clip_int16(band->s_zero + (band->pole_mem[0] * cur_qtzd_reconst >> 15) + (band->pole_mem[1] * band->prev_qtzd_reconst >> 15)); diff --git a/libavcodec/g723_1.c b/libavcodec/g723_1.c index a11fec8a9e..78ce922266 100644 --- a/libavcodec/g723_1.c +++ b/libavcodec/g723_1.c @@ -41,7 +41,7 @@ int ff_g723_1_scale_vector(int16_t *dst, const int16_t *vector, int length) bits= FFMAX(bits, 0); for (i = 0; i < length; i++) - dst[i] = vector[i] << bits >> 3; + dst[i] = (vector[i] * (1 << bits)) >> 3; return bits - 3; } @@ -125,9 +125,9 @@ static void lsp2lpc(int16_t *lpc) for (j = 0; j < LPC_ORDER; j++) { int index = (lpc[j] >> 7) & 0x1FF; int offset = lpc[j] & 0x7f; - int temp1 = cos_tab[index] << 16; + int temp1 = cos_tab[index] * (1 << 16); int temp2 = (cos_tab[index + 1] - cos_tab[index]) * - ((offset << 8) + 0x80) << 1; + (((offset << 8) + 0x80) << 1); lpc[j] = -(av_sat_dadd32(1 << 15, temp1 + temp2) >> 16); } @@ -138,11 +138,11 @@ static void lsp2lpc(int16_t *lpc) */ /* Initialize with values in Q28 */ f1[0] = 1 << 28; - f1[1] = (lpc[0] << 14) + (lpc[2] << 14); + f1[1] = (lpc[0] + lpc[2]) * (1 << 14); f1[2] = lpc[0] * lpc[2] + (2 << 28); f2[0] = 1 << 28; - f2[1] = (lpc[1] << 14) + (lpc[3] << 14); + f2[1] = (lpc[1] + lpc[3]) * (1 << 14); f2[2] = lpc[1] * lpc[3] + (2 << 28); /* @@ -162,8 +162,8 @@ static void lsp2lpc(int16_t *lpc) f1[0] >>= 1; f2[0] >>= 1; - f1[1] = ((lpc[2 * i] << 16 >> i) + f1[1]) >> 1; - f2[1] = ((lpc[2 * i + 1] << 16 >> i) + f2[1]) >> 1; + f1[1] = ((lpc[2 * i] * 65536 >> i) + f1[1]) >> 1; + f2[1] = ((lpc[2 * i + 1] * 65536 >> i) + f2[1]) >> 1; } /* Convert polynomial coefficients to LPC coefficients */ @@ -171,8 +171,8 @@ static void lsp2lpc(int16_t *lpc) int64_t ff1 = f1[i + 1] + f1[i]; int64_t ff2 = f2[i + 1] - f2[i]; - lpc[i] = av_clipl_int32(((ff1 + ff2) << 3) + (1 << 15)) >> 16; - lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) << 3) + + lpc[i] = av_clipl_int32(((ff1 + ff2) * 8) + (1 << 15)) >> 16; + lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) * 8) + (1 << 15)) >> 16; } } diff --git a/libavcodec/g723_1.h b/libavcodec/g723_1.h index 40d6e700b1..f833af01c6 100644 --- a/libavcodec/g723_1.h +++ b/libavcodec/g723_1.h @@ -55,7 +55,7 @@ * @param b 16 bit multiplier */ #define MULL2(a, b) \ - ((((a) >> 16) * (b) << 1) + (((a) & 0xffff) * (b) >> 15)) + ((((a) >> 16) * (b) * 2) + (((a) & 0xffff) * (b) >> 15)) /** * G723.1 frame types diff --git a/libavcodec/g723_1dec.c b/libavcodec/g723_1dec.c index 3e8c4897d2..d205d0428c 100644 --- a/libavcodec/g723_1dec.c +++ b/libavcodec/g723_1dec.c @@ -487,7 +487,7 @@ static void residual_interp(int16_t *buf, int16_t *out, int lag, (FRAME_LEN - lag) * sizeof(*out)); } else { /* Unvoiced */ for (i = 0; i < FRAME_LEN; i++) { - *rseed = *rseed * 521 + 259; + *rseed = (int16_t)(*rseed * 521 + 259); out[i] = gain * *rseed >> 15; } memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(*buf)); @@ -516,7 +516,7 @@ static void residual_interp(int16_t *buf, int16_t *out, int lag, (iir_coef)[n - 1] * ((dest)[m - n] >> in_shift);\ }\ \ - (dest)[m] = av_clipl_int32(((src)[m] << 16) + (filter << 3) +\ + (dest)[m] = av_clipl_int32(((src)[m] * 65536) + (filter * 8) +\ (1 << 15)) >> res_shift;\ }\ } @@ -548,7 +548,7 @@ static void gain_scale(G723_1_Context *p, int16_t * buf, int energy) denom <<= bits2; bits2 = 5 + bits1 - bits2; - bits2 = FFMAX(0, bits2); + bits2 = av_clip_uintp2(bits2, 5); gain = (num >> 1) / (denom >> 16); gain = square_root(gain << 16 >> bits2); @@ -663,7 +663,7 @@ static int estimate_sid_gain(G723_1_Context *p) t = p->sid_gain << shift; else t = p->sid_gain >> -shift; - x = t * cng_filt[0] >> 16; + x = av_clipl_int32(t * (int64_t)cng_filt[0] >> 16); if (x >= cng_bseg[2]) return 0x3F; @@ -694,13 +694,13 @@ static int estimate_sid_gain(G723_1_Context *p) if (y <= 0) { t = seg * 32 + (val + 1 << seg2); t = t * t - x; - val = (seg2 - 1 << 4) + val; + val = (seg2 - 1) * 16 + val; if (t >= y) val++; } else { t = seg * 32 + (val - 1 << seg2); t = t * t - x; - val = (seg2 - 1 << 4) + val; + val = (seg2 - 1) * 16 + val; if (t >= y) val--; } @@ -732,7 +732,7 @@ static void generate_noise(G723_1_Context *p) off[i * 2 + 1] = ((t >> 1) & 1) + SUBFRAME_LEN; t >>= 2; for (j = 0; j < 11; j++) { - signs[i * 11 + j] = (t & 1) * 2 - 1 << 14; + signs[i * 11 + j] = ((t & 1) * 2 - 1) * (1 << 14); t >>= 1; } } @@ -776,7 +776,7 @@ static void generate_noise(G723_1_Context *p) sum = 0; if (shift < 0) { for (j = 0; j < SUBFRAME_LEN * 2; j++) { - t = vector_ptr[j] << -shift; + t = vector_ptr[j] * (1 << -shift); sum += t * t; tmp[j] = t; } @@ -814,7 +814,7 @@ static void generate_noise(G723_1_Context *p) if (shift < 0) x >>= -shift; else - x <<= shift; + x *= 1 << shift; x = av_clip(x, -10000, 10000); for (j = 0; j < 11; j++) { @@ -903,7 +903,7 @@ static int g723_1_decode_frame(AVCodecContext *avctx, void *data, &p->subframe[i], p->cur_rate); /* Get the total excitation */ for (j = 0; j < SUBFRAME_LEN; j++) { - int v = av_clip_int16(vector_ptr[j] << 1); + int v = av_clip_int16(vector_ptr[j] * 2); vector_ptr[j] = av_clip_int16(v + acb_vector[j]); } vector_ptr += SUBFRAME_LEN; diff --git a/libavcodec/g726.c b/libavcodec/g726.c index c3d018fda6..4be44b23d0 100644 --- a/libavcodec/g726.c +++ b/libavcodec/g726.c @@ -206,7 +206,7 @@ static int16_t g726_decode(G726Context* c, int I) if (I_sig) /* get the sign */ dq = -dq; - re_signal = c->se + dq; + re_signal = (int16_t)(c->se + dq); /* Update second order predictor coefficient A2 and A1 */ pk0 = (c->sez + dq) ? sgn(c->sez + dq) : 0; @@ -269,7 +269,7 @@ static int16_t g726_decode(G726Context* c, int I) c->se += mult(i2f(c->a[i] >> 2, &f), &c->sr[i]); c->se >>= 1; - return av_clip(re_signal << 2, -0xffff, 0xffff); + return av_clip(re_signal * 4, -0xffff, 0xffff); } static av_cold int g726_reset(G726Context *c) diff --git a/libavcodec/get_bits.h b/libavcodec/get_bits.h index 4cf61d6f1b..3ae0dbce63 100644 --- a/libavcodec/get_bits.h +++ b/libavcodec/get_bits.h @@ -32,6 +32,7 @@ #include "libavutil/intreadwrite.h" #include "libavutil/log.h" #include "libavutil/avassert.h" +#include "avcodec.h" #include "mathops.h" /* @@ -382,6 +383,10 @@ static inline uint64_t get_bits64(GetBitContext *s, int n) */ static inline int get_sbits_long(GetBitContext *s, int n) { + // sign_extend(x, 0) is undefined + if (!n) + return 0; + return sign_extend(get_bits_long(s, n), n); } @@ -421,7 +426,7 @@ static inline int init_get_bits(GetBitContext *s, const uint8_t *buffer, int buffer_size; int ret = 0; - if (bit_size >= INT_MAX - 7 || bit_size < 0 || !buffer) { + if (bit_size >= INT_MAX - FFMAX(7, AV_INPUT_BUFFER_PADDING_SIZE*8) || bit_size < 0 || !buffer) { bit_size = 0; buffer = NULL; ret = AVERROR_INVALIDDATA; @@ -570,6 +575,7 @@ void ff_free_vlc(VLC *vlc); * @param max_depth is the number of times bits bits must be read to completely * read the longest vlc code * = (max_vlc_length + bits - 1) / bits + * @returns the code parsed or -1 if no vlc matches */ static av_always_inline int get_vlc2(GetBitContext *s, VLC_TYPE (*table)[2], int bits, int max_depth) diff --git a/libavcodec/h263dec.c b/libavcodec/h263dec.c index 628546bb86..8670f53bb9 100644 --- a/libavcodec/h263dec.c +++ b/libavcodec/h263dec.c @@ -637,7 +637,7 @@ retry: slice_ret = decode_slice(s); while (s->mb_y < s->mb_height) { if (s->msmpeg4_version) { - if (s->slice_height == 0 || s->mb_x != 0 || + if (s->slice_height == 0 || s->mb_x != 0 || slice_ret < 0 || (s->mb_y % s->slice_height) != 0 || get_bits_left(&s->gb) < 0) break; } else { diff --git a/libavcodec/h264.c b/libavcodec/h264.c index fe8d44e3bd..550a7fc15e 100644 --- a/libavcodec/h264.c +++ b/libavcodec/h264.c @@ -1591,7 +1591,9 @@ again: #endif } else context_count++; - } + } else + sl->ref_count[0] = sl->ref_count[1] = 0; + break; break; case NAL_DPA: case NAL_DPB: @@ -1656,8 +1658,8 @@ again: av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n"); sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0; } else if (err == SLICE_SINGLETHREAD) { - if (context_count > 1) { - ret = ff_h264_execute_decode_slices(h, context_count - 1); + if (context_count > 0) { + ret = ff_h264_execute_decode_slices(h, context_count); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) goto end; context_count = 0; @@ -1678,6 +1680,47 @@ again: ret = 0; end: + +#if CONFIG_ERROR_RESILIENCE + sl = h->slice_ctx; + /* + * FIXME: Error handling code does not seem to support interlaced + * when slices span multiple rows + * The ff_er_add_slice calls don't work right for bottom + * fields; they cause massive erroneous error concealing + * Error marking covers both fields (top and bottom). + * This causes a mismatched s->error_count + * and a bad error table. Further, the error count goes to + * INT_MAX when called for bottom field, because mb_y is + * past end by one (callers fault) and resync_mb_y != 0 + * causes problems for the first MB line, too. + */ + if (!FIELD_PICTURE(h) && h->current_slice && !h->sps.new && h->enable_er) { + int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0]; + + ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr); + + if (use_last_pic) { + ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec); + sl->ref_list[0][0].parent = &h->last_pic_for_ec; + memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data)); + memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize)); + sl->ref_list[0][0].reference = h->last_pic_for_ec.reference; + } else if (sl->ref_count[0]) { + ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent); + } else + ff_h264_set_erpic(&sl->er.last_pic, NULL); + + if (sl->ref_count[1]) + ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent); + + sl->er.ref_count = sl->ref_count[0]; + + ff_er_frame_end(&sl->er); + if (use_last_pic) + memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0])); + } +#endif /* CONFIG_ERROR_RESILIENCE */ /* clean up */ if (h->cur_pic_ptr && !h->droppable) { ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, @@ -1740,7 +1783,7 @@ static int is_extra(const uint8_t *buf, int buf_size) const uint8_t *p= buf+6; while(cnt--){ int nalsize= AV_RB16(p) + 2; - if(nalsize > buf_size - (p-buf) || p[2]!=0x67) + if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 7) return 0; p += nalsize; } @@ -1749,7 +1792,7 @@ static int is_extra(const uint8_t *buf, int buf_size) return 0; while(cnt--){ int nalsize= AV_RB16(p) + 2; - if(nalsize > buf_size - (p-buf) || p[2]!=0x68) + if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 8) return 0; p += nalsize; } diff --git a/libavcodec/h264.h b/libavcodec/h264.h index a5fc3a053f..cfd14aa646 100644 --- a/libavcodec/h264.h +++ b/libavcodec/h264.h @@ -605,6 +605,7 @@ typedef struct H264Context { uint8_t (*mvd_table[2])[2]; uint8_t *direct_table; + uint8_t scan_padding[16]; uint8_t zigzag_scan[16]; uint8_t zigzag_scan8x8[64]; uint8_t zigzag_scan8x8_cavlc[64]; diff --git a/libavcodec/h264_cabac.c b/libavcodec/h264_cabac.c index deab35a3d9..a450b4ec39 100644 --- a/libavcodec/h264_cabac.c +++ b/libavcodec/h264_cabac.c @@ -1736,7 +1736,7 @@ decode_cabac_residual_internal(const H264Context *h, H264SliceContext *sl, \ if( coeff_abs >= 15 ) { \ int j = 0; \ - while (get_cabac_bypass(CC) && j < 30) { \ + while (get_cabac_bypass(CC) && j < 16+7) { \ j++; \ } \ \ @@ -1744,7 +1744,7 @@ decode_cabac_residual_internal(const H264Context *h, H264SliceContext *sl, while( j-- ) { \ coeff_abs += coeff_abs + get_cabac_bypass( CC ); \ } \ - coeff_abs+= 14; \ + coeff_abs+= 14U; \ } \ \ if( is_dc ) { \ @@ -2343,21 +2343,40 @@ decode_intra_mb: if (CHROMA444(h) && IS_8x8DCT(mb_type)){ int i; uint8_t *nnz_cache = sl->non_zero_count_cache; - for (i = 0; i < 2; i++){ - if (sl->left_type[LEFT(i)] && !IS_8x8DCT(sl->left_type[LEFT(i)])) { - nnz_cache[3+8* 1 + 2*8*i]= - nnz_cache[3+8* 2 + 2*8*i]= - nnz_cache[3+8* 6 + 2*8*i]= - nnz_cache[3+8* 7 + 2*8*i]= - nnz_cache[3+8*11 + 2*8*i]= - nnz_cache[3+8*12 + 2*8*i]= IS_INTRA(mb_type) ? 64 : 0; + if (h->x264_build < 151U) { + for (i = 0; i < 2; i++){ + if (sl->left_type[LEFT(i)] && !IS_8x8DCT(sl->left_type[LEFT(i)])) { + nnz_cache[3+8* 1 + 2*8*i]= + nnz_cache[3+8* 2 + 2*8*i]= + nnz_cache[3+8* 6 + 2*8*i]= + nnz_cache[3+8* 7 + 2*8*i]= + nnz_cache[3+8*11 + 2*8*i]= + nnz_cache[3+8*12 + 2*8*i]= IS_INTRA(mb_type) ? 64 : 0; + } + } + if (sl->top_type && !IS_8x8DCT(sl->top_type)){ + uint32_t top_empty = !IS_INTRA(mb_type) ? 0 : 0x40404040; + AV_WN32A(&nnz_cache[4+8* 0], top_empty); + AV_WN32A(&nnz_cache[4+8* 5], top_empty); + AV_WN32A(&nnz_cache[4+8*10], top_empty); + } + } else { + for (i = 0; i < 2; i++){ + if (sl->left_type[LEFT(i)] && !IS_8x8DCT(sl->left_type[LEFT(i)])) { + nnz_cache[3+8* 1 + 2*8*i]= + nnz_cache[3+8* 2 + 2*8*i]= + nnz_cache[3+8* 6 + 2*8*i]= + nnz_cache[3+8* 7 + 2*8*i]= + nnz_cache[3+8*11 + 2*8*i]= + nnz_cache[3+8*12 + 2*8*i]= !IS_INTRA_PCM(sl->left_type[LEFT(i)]) ? 0 : 64; + } + } + if (sl->top_type && !IS_8x8DCT(sl->top_type)){ + uint32_t top_empty = !IS_INTRA_PCM(sl->top_type) ? 0 : 0x40404040; + AV_WN32A(&nnz_cache[4+8* 0], top_empty); + AV_WN32A(&nnz_cache[4+8* 5], top_empty); + AV_WN32A(&nnz_cache[4+8*10], top_empty); } - } - if (sl->top_type && !IS_8x8DCT(sl->top_type)){ - uint32_t top_empty = CABAC(h) && !IS_INTRA(mb_type) ? 0 : 0x40404040; - AV_WN32A(&nnz_cache[4+8* 0], top_empty); - AV_WN32A(&nnz_cache[4+8* 5], top_empty); - AV_WN32A(&nnz_cache[4+8*10], top_empty); } } h->cur_pic.mb_type[mb_xy] = mb_type; @@ -2366,14 +2385,6 @@ decode_intra_mb: const uint8_t *scan, *scan8x8; const uint32_t *qmul; - if(IS_INTERLACED(mb_type)){ - scan8x8 = sl->qscale ? h->field_scan8x8 : h->field_scan8x8_q0; - scan = sl->qscale ? h->field_scan : h->field_scan_q0; - }else{ - scan8x8 = sl->qscale ? h->zigzag_scan8x8 : h->zigzag_scan8x8_q0; - scan = sl->qscale ? h->zigzag_scan : h->zigzag_scan_q0; - } - // decode_cabac_mb_dqp if(get_cabac_noinline( &sl->cabac, &sl->cabac_state[60 + (sl->last_qscale_diff != 0)])){ int val = 1; @@ -2404,6 +2415,14 @@ decode_intra_mb: }else sl->last_qscale_diff=0; + if(IS_INTERLACED(mb_type)){ + scan8x8 = sl->qscale ? h->field_scan8x8 : h->field_scan8x8_q0; + scan = sl->qscale ? h->field_scan : h->field_scan_q0; + }else{ + scan8x8 = sl->qscale ? h->zigzag_scan8x8 : h->zigzag_scan8x8_q0; + scan = sl->qscale ? h->zigzag_scan : h->zigzag_scan_q0; + } + decode_cabac_luma_residual(h, sl, scan, scan8x8, pixel_shift, mb_type, cbp, 0); if (CHROMA444(h)) { decode_cabac_luma_residual(h, sl, scan, scan8x8, pixel_shift, mb_type, cbp, 1); diff --git a/libavcodec/h264_cavlc.c b/libavcodec/h264_cavlc.c index b0251f405c..250e93bc8e 100644 --- a/libavcodec/h264_cavlc.c +++ b/libavcodec/h264_cavlc.c @@ -721,8 +721,14 @@ int ff_h264_decode_mb_cavlc(const H264Context *h, H264SliceContext *sl) cbp = 0; /* avoid warning. FIXME: find a solution without slowing down the code */ if (sl->slice_type_nos != AV_PICTURE_TYPE_I) { - if (sl->mb_skip_run == -1) - sl->mb_skip_run = get_ue_golomb_long(&sl->gb); + if (sl->mb_skip_run == -1) { + unsigned mb_skip_run = get_ue_golomb_long(&sl->gb); + if (mb_skip_run > h->mb_num) { + av_log(h->avctx, AV_LOG_ERROR, "mb_skip_run %d is invalid\n", mb_skip_run); + return AVERROR_INVALIDDATA; + } + sl->mb_skip_run = mb_skip_run; + } if (sl->mb_skip_run--) { if (FRAME_MBAFF(h) && (sl->mb_y & 1) == 0) { @@ -1104,6 +1110,23 @@ decode_intra_mb: const uint8_t *scan, *scan8x8; const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8); + dquant= get_se_golomb(&sl->gb); + + sl->qscale += (unsigned)dquant; + + if (((unsigned)sl->qscale) > max_qp){ + if (sl->qscale < 0) sl->qscale += max_qp + 1; + else sl->qscale -= max_qp+1; + if (((unsigned)sl->qscale) > max_qp){ + av_log(h->avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, sl->mb_x, sl->mb_y); + sl->qscale = max_qp; + return -1; + } + } + + sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale); + sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale); + if(IS_INTERLACED(mb_type)){ scan8x8 = sl->qscale ? h->field_scan8x8_cavlc : h->field_scan8x8_cavlc_q0; scan = sl->qscale ? h->field_scan : h->field_scan_q0; @@ -1112,22 +1135,6 @@ decode_intra_mb: scan = sl->qscale ? h->zigzag_scan : h->zigzag_scan_q0; } - dquant= get_se_golomb(&sl->gb); - - sl->qscale += dquant; - - if (((unsigned)sl->qscale) > max_qp){ - if (sl->qscale < 0) sl->qscale += max_qp + 1; - else sl->qscale -= max_qp+1; - if (((unsigned)sl->qscale) > max_qp){ - av_log(h->avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, sl->mb_x, sl->mb_y); - return -1; - } - } - - sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale); - sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale); - if ((ret = decode_luma_residual(h, sl, gb, scan, scan8x8, pixel_shift, mb_type, cbp, 0)) < 0 ) { return -1; } diff --git a/libavcodec/h264_direct.c b/libavcodec/h264_direct.c index 5f66a67d89..2660cb80d3 100644 --- a/libavcodec/h264_direct.c +++ b/libavcodec/h264_direct.c @@ -613,7 +613,7 @@ single_col: { const int16_t *mv_col = l1mv[x8 * 3 + y8 * b4_stride]; - int my_col = (mv_col[1] << y_shift) / 2; + int my_col = (mv_col[1] * (1 << y_shift)) / 2; int mx = (scale * mv_col[0] + 128) >> 8; int my = (scale * my_col + 128) >> 8; fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, diff --git a/libavcodec/h264_mb.c b/libavcodec/h264_mb.c index 8302de040e..f9b8287c2e 100644 --- a/libavcodec/h264_mb.c +++ b/libavcodec/h264_mb.c @@ -638,7 +638,7 @@ static av_always_inline void hl_decode_mb_predict_luma(const H264Context *h, uint8_t *const ptr = dest_y + block_offset[i]; const int dir = sl->intra4x4_pred_mode_cache[scan8[i]]; if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) { - if (h->x264_build != -1) { + if (h->x264_build < 151U) { h->hpc.pred8x8l_add[dir](ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize); } else h->hpc.pred8x8l_filter_add[dir](ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), diff --git a/libavcodec/h264_mc_template.c b/libavcodec/h264_mc_template.c index e4333a733c..acdf4d126c 100644 --- a/libavcodec/h264_mc_template.c +++ b/libavcodec/h264_mc_template.c @@ -78,7 +78,8 @@ static void MCFUNC(hl_motion)(const H264Context *h, H264SliceContext *sl, if (HAVE_THREADS && (h->avctx->active_thread_type & FF_THREAD_FRAME)) await_references(h, sl); - prefetch_motion(h, sl, 0, PIXEL_SHIFT, CHROMA_IDC); + if (USES_LIST(mb_type, 0)) + prefetch_motion(h, sl, 0, PIXEL_SHIFT, CHROMA_IDC); if (IS_16X16(mb_type)) { mc_part(h, sl, 0, 1, 16, 0, dest_y, dest_cb, dest_cr, 0, 0, diff --git a/libavcodec/h264_mvpred.h b/libavcodec/h264_mvpred.h index 763746cc26..18de4b0bbc 100644 --- a/libavcodec/h264_mvpred.h +++ b/libavcodec/h264_mvpred.h @@ -68,7 +68,7 @@ static av_always_inline int fetch_diagonal_mv(const H264Context *h, H264SliceCon } if (MB_FIELD(sl) && !IS_INTERLACED(sl->left_type[0])) { // left shift will turn LIST_NOT_USED into PART_NOT_AVAILABLE, but that's OK. - SET_DIAG_MV(/ 2, << 1, sl->left_mb_xy[i >= 36], ((i >> 2)) & 3); + SET_DIAG_MV(/ 2, *2, sl->left_mb_xy[i >= 36], ((i >> 2)) & 3); } } #undef SET_DIAG_MV @@ -248,7 +248,7 @@ static av_always_inline void pred_8x16_motion(const H264Context *const h, if (IS_INTERLACED(type)) { \ refn >>= 1; \ AV_COPY32(mvbuf[idx], mvn); \ - mvbuf[idx][1] <<= 1; \ + mvbuf[idx][1] *= 2; \ mvn = mvbuf[idx]; \ } \ } \ diff --git a/libavcodec/h264_picture.c b/libavcodec/h264_picture.c index 731d780e67..c4b17c03c9 100644 --- a/libavcodec/h264_picture.c +++ b/libavcodec/h264_picture.c @@ -186,47 +186,6 @@ int ff_h264_field_end(H264Context *h, H264SliceContext *sl, int in_setup) ff_vdpau_h264_picture_complete(h); #endif -#if CONFIG_ERROR_RESILIENCE - av_assert0(sl == h->slice_ctx); - /* - * FIXME: Error handling code does not seem to support interlaced - * when slices span multiple rows - * The ff_er_add_slice calls don't work right for bottom - * fields; they cause massive erroneous error concealing - * Error marking covers both fields (top and bottom). - * This causes a mismatched s->error_count - * and a bad error table. Further, the error count goes to - * INT_MAX when called for bottom field, because mb_y is - * past end by one (callers fault) and resync_mb_y != 0 - * causes problems for the first MB line, too. - */ - if (!FIELD_PICTURE(h) && h->current_slice && !h->sps.new && h->enable_er) { - int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0]; - - ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr); - - if (use_last_pic) { - ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec); - sl->ref_list[0][0].parent = &h->last_pic_for_ec; - memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data)); - memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize)); - sl->ref_list[0][0].reference = h->last_pic_for_ec.reference; - } else if (sl->ref_count[0]) { - ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent); - } else - ff_h264_set_erpic(&sl->er.last_pic, NULL); - - if (sl->ref_count[1]) - ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent); - - sl->er.ref_count = sl->ref_count[0]; - - ff_er_frame_end(&sl->er); - if (use_last_pic) - memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0])); - } -#endif /* CONFIG_ERROR_RESILIENCE */ - if (!in_setup && !h->droppable) ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, h->picture_structure == PICT_BOTTOM_FIELD); diff --git a/libavcodec/h264_refs.c b/libavcodec/h264_refs.c index d46d940dae..9900cd5805 100644 --- a/libavcodec/h264_refs.c +++ b/libavcodec/h264_refs.c @@ -814,6 +814,7 @@ int ff_h264_execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count) pps_ref_count[1] = FFMAX(pps_ref_count[1], h->pps.ref_count[1]); } + // Detect unmarked random access points if ( err >= 0 && h->long_ref_count==0 && ( h->short_ref_count<=2 diff --git a/libavcodec/h264_slice.c b/libavcodec/h264_slice.c index 2131338a7b..0afd49bac5 100644 --- a/libavcodec/h264_slice.c +++ b/libavcodec/h264_slice.c @@ -1282,9 +1282,13 @@ int ff_h264_decode_slice_header(H264Context *h, H264SliceContext *sl) if (first_slice) { h->pps = *h->pps_buffers[pps_id]; - } else if (h->setup_finished && h->dequant_coeff_pps != pps_id) { - av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n"); - return AVERROR_INVALIDDATA; + } else { + if (h->pps.sps_id != pps->sps_id || + h->pps.transform_8x8_mode != pps->transform_8x8_mode || + (h->setup_finished && h->dequant_coeff_pps != pps_id)) { + av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n"); + return AVERROR_INVALIDDATA; + } } if (pps->sps_id != h->sps.sps_id || @@ -1629,6 +1633,12 @@ int ff_h264_decode_slice_header(H264Context *h, H264SliceContext *sl) h->missing_fields ++; h->cur_pic_ptr = NULL; h->first_field = FIELD_PICTURE(h); + } else if (h->cur_pic_ptr->reference & DELAYED_PIC_REF) { + /* This frame was already output, we cannot draw into it + * anymore. + */ + h->first_field = 1; + h->cur_pic_ptr = NULL; } else { h->missing_fields = 0; if (h->cur_pic_ptr->frame_num != h->frame_num) { @@ -1818,17 +1828,19 @@ int ff_h264_decode_slice_header(H264Context *h, H264SliceContext *sl) sl->deblocking_filter ^= 1; // 1<->0 if (sl->deblocking_filter) { - sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2; - sl->slice_beta_offset = get_se_golomb(&sl->gb) * 2; - if (sl->slice_alpha_c0_offset > 12 || - sl->slice_alpha_c0_offset < -12 || - sl->slice_beta_offset > 12 || - sl->slice_beta_offset < -12) { + int slice_alpha_c0_offset_div2 = get_se_golomb(&sl->gb); + int slice_beta_offset_div2 = get_se_golomb(&sl->gb); + if (slice_alpha_c0_offset_div2 > 6 || + slice_alpha_c0_offset_div2 < -6 || + slice_beta_offset_div2 > 6 || + slice_beta_offset_div2 < -6) { av_log(h->avctx, AV_LOG_ERROR, "deblocking filter parameters %d %d out of range\n", - sl->slice_alpha_c0_offset, sl->slice_beta_offset); + slice_alpha_c0_offset_div2, slice_beta_offset_div2); return AVERROR_INVALIDDATA; } + sl->slice_alpha_c0_offset = slice_alpha_c0_offset_div2 * 2; + sl->slice_beta_offset = slice_beta_offset_div2 * 2; } } diff --git a/libavcodec/h264addpx_template.c b/libavcodec/h264addpx_template.c index 046b6c2e19..a99030c589 100644 --- a/libavcodec/h264addpx_template.c +++ b/libavcodec/h264addpx_template.c @@ -35,10 +35,10 @@ static void FUNCC(ff_h264_add_pixels4)(uint8_t *_dst, int16_t *_src, int stride) stride /= sizeof(pixel); for (i = 0; i < 4; i++) { - dst[0] += src[0]; - dst[1] += src[1]; - dst[2] += src[2]; - dst[3] += src[3]; + dst[0] += (unsigned)src[0]; + dst[1] += (unsigned)src[1]; + dst[2] += (unsigned)src[2]; + dst[3] += (unsigned)src[3]; dst += stride; src += 4; @@ -55,14 +55,14 @@ static void FUNCC(ff_h264_add_pixels8)(uint8_t *_dst, int16_t *_src, int stride) stride /= sizeof(pixel); for (i = 0; i < 8; i++) { - dst[0] += src[0]; - dst[1] += src[1]; - dst[2] += src[2]; - dst[3] += src[3]; - dst[4] += src[4]; - dst[5] += src[5]; - dst[6] += src[6]; - dst[7] += src[7]; + dst[0] += (unsigned)src[0]; + dst[1] += (unsigned)src[1]; + dst[2] += (unsigned)src[2]; + dst[3] += (unsigned)src[3]; + dst[4] += (unsigned)src[4]; + dst[5] += (unsigned)src[5]; + dst[6] += (unsigned)src[6]; + dst[7] += (unsigned)src[7]; dst += stride; src += 8; diff --git a/libavcodec/h264idct_template.c b/libavcodec/h264idct_template.c index abf888ed96..e402c9636b 100644 --- a/libavcodec/h264idct_template.c +++ b/libavcodec/h264idct_template.c @@ -91,10 +91,10 @@ void FUNCC(ff_h264_idct8_add)(uint8_t *_dst, int16_t *_block, int stride){ const int a5 = -block[i+1*8] + block[i+7*8] + block[i+5*8] + (block[i+5*8]>>1); const int a7 = block[i+3*8] + block[i+5*8] + block[i+1*8] + (block[i+1*8]>>1); - const int b1 = (a7>>2) + a1; - const int b3 = a3 + (a5>>2); - const int b5 = (a3>>2) - a5; - const int b7 = a7 - (a1>>2); + const int b1 = (a7>>2) + (unsigned)a1; + const int b3 = (unsigned)a3 + (a5>>2); + const int b5 = (a3>>2) - (unsigned)a5; + const int b7 = (unsigned)a7 - (a1>>2); block[i+0*8] = b0 + b7; block[i+7*8] = b0 - b7; diff --git a/libavcodec/hevc.c b/libavcodec/hevc.c index 203f90ab2e..7ece31f8aa 100644 --- a/libavcodec/hevc.c +++ b/libavcodec/hevc.c @@ -246,6 +246,8 @@ static int decode_lt_rps(HEVCContext *s, LongTermRPS *rps, GetBitContext *gb) nb_sps = get_ue_golomb_long(gb); nb_sh = get_ue_golomb_long(gb); + if (nb_sps > sps->num_long_term_ref_pics_sps) + return AVERROR_INVALIDDATA; if (nb_sh + (uint64_t)nb_sps > FF_ARRAY_ELEMS(rps->poc)) return AVERROR_INVALIDDATA; @@ -269,12 +271,16 @@ static int decode_lt_rps(HEVCContext *s, LongTermRPS *rps, GetBitContext *gb) delta_poc_msb_present = get_bits1(gb); if (delta_poc_msb_present) { - int delta = get_ue_golomb_long(gb); + int64_t delta = get_ue_golomb_long(gb); + int64_t poc; if (i && i != nb_sps) delta += prev_delta_msb; - rps->poc[i] += s->poc - delta * max_poc_lsb - s->sh.pic_order_cnt_lsb; + poc = rps->poc[i] + s->poc - delta * max_poc_lsb - s->sh.pic_order_cnt_lsb; + if (poc != (int32_t)poc) + return AVERROR_INVALIDDATA; + rps->poc[i] = poc; prev_delta_msb = delta; } } @@ -2775,6 +2781,10 @@ static int decode_nal_unit(HEVCContext *s, const HEVCNAL *nal) } if (s->sh.first_slice_in_pic_flag) { + if (s->ref) { + av_log(s->avctx, AV_LOG_ERROR, "Two slices reporting being the first in the same frame.\n"); + goto fail; + } ret = hevc_frame_start(s); if (ret < 0) return ret; @@ -3149,6 +3159,8 @@ static av_cold int hevc_init_context(AVCodecContext *avctx) s->context_initialized = 1; s->eos = 0; + ff_hevc_reset_sei(s); + return 0; fail: diff --git a/libavcodec/hevc.h b/libavcodec/hevc.h index c91f815857..0d410bdd86 100644 --- a/libavcodec/hevc.h +++ b/libavcodec/hevc.h @@ -407,6 +407,7 @@ typedef struct HEVCSPS { HEVCWindow pic_conf_win; int bit_depth; + int bit_depth_chroma; int pixel_shift; enum AVPixelFormat pix_fmt; @@ -538,8 +539,8 @@ typedef struct HEVCPPS { uint8_t chroma_qp_offset_list_enabled_flag; uint8_t diff_cu_chroma_qp_offset_depth; uint8_t chroma_qp_offset_list_len_minus1; - int8_t cb_qp_offset_list[5]; - int8_t cr_qp_offset_list[5]; + int8_t cb_qp_offset_list[6]; + int8_t cr_qp_offset_list[6]; uint8_t log2_sao_offset_scale_luma; uint8_t log2_sao_offset_scale_chroma; @@ -1092,6 +1093,15 @@ int ff_hevc_split_packet(HEVCContext *s, HEVCPacket *pkt, const uint8_t *buf, in int ff_hevc_encode_nal_vps(HEVCVPS *vps, unsigned int id, uint8_t *buf, int buf_size); +/** + * Reset SEI values that are stored on the Context. + * e.g. Caption data that was extracted during NAL + * parsing. + * + * @param s HEVCContext. + */ +void ff_hevc_reset_sei(HEVCContext *s); + extern const uint8_t ff_hevc_qpel_extra_before[4]; extern const uint8_t ff_hevc_qpel_extra_after[4]; extern const uint8_t ff_hevc_qpel_extra[4]; diff --git a/libavcodec/hevc_cabac.c b/libavcodec/hevc_cabac.c index d1bef8320f..0e4c522bb1 100644 --- a/libavcodec/hevc_cabac.c +++ b/libavcodec/hevc_cabac.c @@ -633,8 +633,10 @@ int ff_hevc_cu_qp_delta_abs(HEVCContext *s) suffix_val += 1 << k; k++; } - if (k == CABAC_MAX_BIN) + if (k == CABAC_MAX_BIN) { av_log(s->avctx, AV_LOG_ERROR, "CABAC_MAX_BIN : %d\n", k); + return AVERROR_INVALIDDATA; + } while (k--) suffix_val += get_cabac_bypass(&s->HEVClc->cc) << k; @@ -975,16 +977,19 @@ static av_always_inline int coeff_abs_level_remaining_decode(HEVCContext *s, int while (prefix < CABAC_MAX_BIN && get_cabac_bypass(&s->HEVClc->cc)) prefix++; - if (prefix == CABAC_MAX_BIN) { - av_log(s->avctx, AV_LOG_ERROR, "CABAC_MAX_BIN : %d\n", prefix); - return 0; - } + if (prefix < 3) { for (i = 0; i < rc_rice_param; i++) suffix = (suffix << 1) | get_cabac_bypass(&s->HEVClc->cc); last_coeff_abs_level_remaining = (prefix << rc_rice_param) + suffix; } else { int prefix_minus3 = prefix - 3; + + if (prefix == CABAC_MAX_BIN || prefix_minus3 + rc_rice_param >= 31) { + av_log(s->avctx, AV_LOG_ERROR, "CABAC_MAX_BIN : %d\n", prefix); + return 0; + } + for (i = 0; i < prefix_minus3 + rc_rice_param; i++) suffix = (suffix << 1) | get_cabac_bypass(&s->HEVClc->cc); last_coeff_abs_level_remaining = (((1 << prefix_minus3) + 3 - 1) diff --git a/libavcodec/hevc_filter.c b/libavcodec/hevc_filter.c index 1f33b0cdfe..9fbcd1d8b8 100644 --- a/libavcodec/hevc_filter.c +++ b/libavcodec/hevc_filter.c @@ -471,7 +471,7 @@ static int get_pcm(HEVCContext *s, int x, int y) #define TC_CALC(qp, bs) \ tctable[av_clip((qp) + DEFAULT_INTRA_TC_OFFSET * ((bs) - 1) + \ - (tc_offset >> 1 << 1), \ + (tc_offset & -2), \ 0, MAX_QP + DEFAULT_INTRA_TC_OFFSET)] static void deblocking_filter_CTB(HEVCContext *s, int x0, int y0) diff --git a/libavcodec/hevc_parse.c b/libavcodec/hevc_parse.c index 63ed84a8de..d557cc7f04 100644 --- a/libavcodec/hevc_parse.c +++ b/libavcodec/hevc_parse.c @@ -232,8 +232,14 @@ int ff_hevc_split_packet(HEVCContext *s, HEVCPacket *pkt, const uint8_t *buf, in ++buf; --length; if (length < 4) { - av_log(avctx, AV_LOG_ERROR, "No start code is found.\n"); - return AVERROR_INVALIDDATA; + if (pkt->nb_nals > 0) { + // No more start codes: we discarded some irrelevant + // bytes at the end of the packet. + return 0; + } else { + av_log(avctx, AV_LOG_ERROR, "No start code is found.\n"); + return AVERROR_INVALIDDATA; + } } } diff --git a/libavcodec/hevc_parser.c b/libavcodec/hevc_parser.c index 4625e6149a..d635716fb9 100644 --- a/libavcodec/hevc_parser.c +++ b/libavcodec/hevc_parser.c @@ -209,6 +209,8 @@ static inline int parse_nal_units(AVCodecParserContext *s, const uint8_t *buf, h->avctx = avctx; + ff_hevc_reset_sei(h); + if (!buf_size) return 0; diff --git a/libavcodec/hevc_ps.c b/libavcodec/hevc_ps.c index 64d6e2f064..f76333d273 100644 --- a/libavcodec/hevc_ps.c +++ b/libavcodec/hevc_ps.c @@ -169,6 +169,12 @@ int ff_hevc_decode_short_term_rps(GetBitContext *gb, AVCodecContext *avctx, } } + if (k >= FF_ARRAY_ELEMS(rps->used)) { + av_log(avctx, AV_LOG_ERROR, + "Invalid num_delta_pocs: %d\n", k); + return AVERROR_INVALIDDATA; + } + rps->num_delta_pocs = k; rps->num_negative_pics = k0; // sort in increasing order (smallest first) @@ -218,6 +224,12 @@ int ff_hevc_decode_short_term_rps(GetBitContext *gb, AVCodecContext *avctx, prev = 0; for (i = 0; i < rps->num_negative_pics; i++) { delta_poc = get_ue_golomb_long(gb) + 1; + if (delta_poc < 1 || delta_poc > 32768) { + av_log(avctx, AV_LOG_ERROR, + "Invalid value of delta_poc: %d\n", + delta_poc); + return AVERROR_INVALIDDATA; + } prev -= delta_poc; rps->delta_poc[i] = prev; rps->used[i] = get_bits1(gb); @@ -225,6 +237,12 @@ int ff_hevc_decode_short_term_rps(GetBitContext *gb, AVCodecContext *avctx, prev = 0; for (i = 0; i < nb_positive_pics; i++) { delta_poc = get_ue_golomb_long(gb) + 1; + if (delta_poc < 1 || delta_poc > 32768) { + av_log(avctx, AV_LOG_ERROR, + "Invalid value of delta_poc: %d\n", + delta_poc); + return AVERROR_INVALIDDATA; + } prev += delta_poc; rps->delta_poc[rps->num_negative_pics + i] = prev; rps->used[rps->num_negative_pics + i] = get_bits1(gb); @@ -724,7 +742,7 @@ static int scaling_list_data(GetBitContext *gb, AVCodecContext *avctx, ScalingLi ff_hevc_diag_scan8x8_x[i]; scaling_list_delta_coef = get_se_golomb(gb); - next_coef = (next_coef + scaling_list_delta_coef + 256) % 256; + next_coef = (next_coef + 256U + scaling_list_delta_coef) % 256; sl->sl[size_id][matrix_id][pos] = next_coef; } } @@ -888,6 +906,7 @@ int ff_hevc_parse_sps(HEVCSPS *sps, GetBitContext *gb, unsigned int *sps_id, sps->bit_depth, bit_depth_chroma); return AVERROR_INVALIDDATA; } + sps->bit_depth_chroma = bit_depth_chroma; ret = map_pixel_format(avctx, sps); if (ret < 0) @@ -981,10 +1000,10 @@ int ff_hevc_parse_sps(HEVCSPS *sps, GetBitContext *gb, unsigned int *sps_id, sps->pcm.log2_min_pcm_cb_size = get_ue_golomb_long(gb) + 3; sps->pcm.log2_max_pcm_cb_size = sps->pcm.log2_min_pcm_cb_size + get_ue_golomb_long(gb); - if (sps->pcm.bit_depth > sps->bit_depth) { + if (FFMAX(sps->pcm.bit_depth, sps->pcm.bit_depth_chroma) > sps->bit_depth) { av_log(avctx, AV_LOG_ERROR, - "PCM bit depth (%d) is greater than normal bit depth (%d)\n", - sps->pcm.bit_depth, sps->bit_depth); + "PCM bit depth (%d, %d) is greater than normal bit depth (%d)\n", + sps->pcm.bit_depth, sps->pcm.bit_depth_chroma, sps->bit_depth); return AVERROR_INVALIDDATA; } @@ -1251,6 +1270,11 @@ static int pps_range_extensions(GetBitContext *gb, AVCodecContext *avctx, pps->log2_sao_offset_scale_luma = get_ue_golomb_long(gb); pps->log2_sao_offset_scale_chroma = get_ue_golomb_long(gb); + if ( pps->log2_sao_offset_scale_luma > FFMAX(sps->bit_depth - 10, 0) + || pps->log2_sao_offset_scale_chroma > FFMAX(sps->bit_depth_chroma - 10, 0) + ) + return AVERROR_INVALIDDATA; + return(0); } @@ -1392,6 +1416,7 @@ int ff_hevc_decode_nal_pps(GetBitContext *gb, AVCodecContext *avctx, HEVCSPS *sps = NULL; int i, ret = 0; unsigned int pps_id = 0; + unsigned log2_parallel_merge_level_minus2; AVBufferRef *pps_buf; HEVCPPS *pps = av_mallocz(sizeof(*pps)); @@ -1551,20 +1576,22 @@ int ff_hevc_decode_nal_pps(GetBitContext *gb, AVCodecContext *avctx, pps->deblocking_filter_override_enabled_flag = get_bits1(gb); pps->disable_dbf = get_bits1(gb); if (!pps->disable_dbf) { - pps->beta_offset = get_se_golomb(gb) * 2; - pps->tc_offset = get_se_golomb(gb) * 2; - if (pps->beta_offset/2 < -6 || pps->beta_offset/2 > 6) { + int beta_offset_div2 = get_se_golomb(gb); + int tc_offset_div2 = get_se_golomb(gb) ; + if (beta_offset_div2 < -6 || beta_offset_div2 > 6) { av_log(avctx, AV_LOG_ERROR, "pps_beta_offset_div2 out of range: %d\n", - pps->beta_offset/2); + beta_offset_div2); ret = AVERROR_INVALIDDATA; goto err; } - if (pps->tc_offset/2 < -6 || pps->tc_offset/2 > 6) { + if (tc_offset_div2 < -6 || tc_offset_div2 > 6) { av_log(avctx, AV_LOG_ERROR, "pps_tc_offset_div2 out of range: %d\n", - pps->tc_offset/2); + tc_offset_div2); ret = AVERROR_INVALIDDATA; goto err; } + pps->beta_offset = 2 * beta_offset_div2; + pps->tc_offset = 2 * tc_offset_div2; } } @@ -1576,13 +1603,14 @@ int ff_hevc_decode_nal_pps(GetBitContext *gb, AVCodecContext *avctx, goto err; } pps->lists_modification_present_flag = get_bits1(gb); - pps->log2_parallel_merge_level = get_ue_golomb_long(gb) + 2; - if (pps->log2_parallel_merge_level > sps->log2_ctb_size) { + log2_parallel_merge_level_minus2 = get_ue_golomb_long(gb); + if (log2_parallel_merge_level_minus2 > sps->log2_ctb_size) { av_log(avctx, AV_LOG_ERROR, "log2_parallel_merge_level_minus2 out of range: %d\n", - pps->log2_parallel_merge_level - 2); + log2_parallel_merge_level_minus2); ret = AVERROR_INVALIDDATA; goto err; } + pps->log2_parallel_merge_level = log2_parallel_merge_level_minus2 + 2; pps->slice_header_extension_present_flag = get_bits1(gb); diff --git a/libavcodec/hevc_refs.c b/libavcodec/hevc_refs.c index 611ad458de..df52e401ad 100644 --- a/libavcodec/hevc_refs.c +++ b/libavcodec/hevc_refs.c @@ -438,7 +438,7 @@ static int add_candidate_ref(HEVCContext *s, RefPicList *list, { HEVCFrame *ref = find_ref_idx(s, poc); - if (ref == s->ref) + if (ref == s->ref || list->nb_refs >= MAX_REFS) return AVERROR_INVALIDDATA; if (!ref) { diff --git a/libavcodec/hevc_sei.c b/libavcodec/hevc_sei.c index 40685fe5d8..190c18740e 100644 --- a/libavcodec/hevc_sei.c +++ b/libavcodec/hevc_sei.c @@ -145,7 +145,7 @@ static int decode_nal_sei_display_orientation(HEVCContext *s) return 0; } -static int decode_pic_timing(HEVCContext *s) +static int decode_pic_timing(HEVCContext *s, int size) { GetBitContext *gb = &s->HEVClc->gb; HEVCSPS *sps; @@ -166,8 +166,12 @@ static int decode_pic_timing(HEVCContext *s) } get_bits(gb, 2); // source_scan_type get_bits(gb, 1); // duplicate_flag + skip_bits1(gb); + size--; } - return 1; + skip_bits_long(gb, 8 * size); + + return 0; } static int decode_registered_user_data_closed_caption(HEVCContext *s, int size) @@ -297,9 +301,8 @@ static int decode_nal_sei_prefix(HEVCContext *s, int type, int size) return decode_nal_sei_display_orientation(s); case SEI_TYPE_PICTURE_TIMING: { - int ret = decode_pic_timing(s); + int ret = decode_pic_timing(s, size); av_log(s->avctx, AV_LOG_DEBUG, "Skipped PREFIX SEI %d\n", type); - skip_bits(gb, 8 * size); return ret; } case SEI_TYPE_MASTERING_DISPLAY_INFO: @@ -341,11 +344,15 @@ static int decode_nal_sei_message(HEVCContext *s) av_log(s->avctx, AV_LOG_DEBUG, "Decoding SEI\n"); while (byte == 0xFF) { + if (get_bits_left(gb) < 16 || payload_type > INT_MAX - 255) + return AVERROR_INVALIDDATA; byte = get_bits(gb, 8); payload_type += byte; } byte = 0xFF; while (byte == 0xFF) { + if (get_bits_left(gb) < 8 + 8LL*payload_size) + return AVERROR_INVALIDDATA; byte = get_bits(gb, 8); payload_size += byte; } @@ -373,3 +380,9 @@ int ff_hevc_decode_nal_sei(HEVCContext *s) } while (more_rbsp_data(&s->HEVClc->gb)); return 1; } + +void ff_hevc_reset_sei(HEVCContext *s) +{ + s->a53_caption_size = 0; + av_freep(&s->a53_caption); +} diff --git a/libavcodec/hevcdsp_template.c b/libavcodec/hevcdsp_template.c index b840d179c3..65dd179d0d 100644 --- a/libavcodec/hevcdsp_template.c +++ b/libavcodec/hevcdsp_template.c @@ -125,7 +125,7 @@ static void FUNC(transform_skip)(int16_t *_coeffs, int16_t log2_size) } else { for (y = 0; y < size; y++) { for (x = 0; x < size; x++) { - *coeffs = *coeffs << -shift; + *coeffs = *(uint16_t*)coeffs << -shift; coeffs++; } } @@ -599,7 +599,7 @@ static void FUNC(put_hevc_pel_bi_w_pixels)(uint8_t *_dst, ptrdiff_t _dststride, ox1 = ox1 * (1 << (BIT_DEPTH - 8)); for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { - dst[x] = av_clip_pixel(( (src[x] << (14 - BIT_DEPTH)) * wx1 + src2[x] * wx0 + ((ox0 + ox1 + 1) << log2Wd)) >> (log2Wd + 1)); + dst[x] = av_clip_pixel(( (src[x] << (14 - BIT_DEPTH)) * wx1 + src2[x] * wx0 + (ox0 + ox1 + 1) * (1 << log2Wd)) >> (log2Wd + 1)); } src += srcstride; dst += dststride; @@ -921,7 +921,7 @@ static void FUNC(put_hevc_qpel_bi_w_h)(uint8_t *_dst, ptrdiff_t _dststride, uint for (y = 0; y < height; y++) { for (x = 0; x < width; x++) dst[x] = av_clip_pixel(((QPEL_FILTER(src, 1) >> (BIT_DEPTH - 8)) * wx1 + src2[x] * wx0 + - ((ox0 + ox1 + 1) << log2Wd)) >> (log2Wd + 1)); + ((ox0 + ox1 + 1) * (1 << log2Wd))) >> (log2Wd + 1)); src += srcstride; dst += dststride; src2 += MAX_PB_SIZE; @@ -976,7 +976,7 @@ static void FUNC(put_hevc_qpel_bi_w_v)(uint8_t *_dst, ptrdiff_t _dststride, uint for (y = 0; y < height; y++) { for (x = 0; x < width; x++) dst[x] = av_clip_pixel(((QPEL_FILTER(src, srcstride) >> (BIT_DEPTH - 8)) * wx1 + src2[x] * wx0 + - ((ox0 + ox1 + 1) << log2Wd)) >> (log2Wd + 1)); + ((ox0 + ox1 + 1) * (1 << log2Wd))) >> (log2Wd + 1)); src += srcstride; dst += dststride; src2 += MAX_PB_SIZE; @@ -1057,7 +1057,7 @@ static void FUNC(put_hevc_qpel_bi_w_hv)(uint8_t *_dst, ptrdiff_t _dststride, uin for (y = 0; y < height; y++) { for (x = 0; x < width; x++) dst[x] = av_clip_pixel(((QPEL_FILTER(tmp, MAX_PB_SIZE) >> 6) * wx1 + src2[x] * wx0 + - ((ox0 + ox1 + 1) << log2Wd)) >> (log2Wd + 1)); + ((ox0 + ox1 + 1) * (1 << log2Wd))) >> (log2Wd + 1)); tmp += MAX_PB_SIZE; dst += dststride; src2 += MAX_PB_SIZE; @@ -1361,7 +1361,7 @@ static void FUNC(put_hevc_epel_bi_w_h)(uint8_t *_dst, ptrdiff_t _dststride, uint for (y = 0; y < height; y++) { for (x = 0; x < width; x++) dst[x] = av_clip_pixel(((EPEL_FILTER(src, 1) >> (BIT_DEPTH - 8)) * wx1 + src2[x] * wx0 + - ((ox0 + ox1 + 1) << log2Wd)) >> (log2Wd + 1)); + ((ox0 + ox1 + 1) * (1 << log2Wd))) >> (log2Wd + 1)); src += srcstride; dst += dststride; src2 += MAX_PB_SIZE; @@ -1413,7 +1413,7 @@ static void FUNC(put_hevc_epel_bi_w_v)(uint8_t *_dst, ptrdiff_t _dststride, uint for (y = 0; y < height; y++) { for (x = 0; x < width; x++) dst[x] = av_clip_pixel(((EPEL_FILTER(src, srcstride) >> (BIT_DEPTH - 8)) * wx1 + src2[x] * wx0 + - ((ox0 + ox1 + 1) << log2Wd)) >> (log2Wd + 1)); + ((ox0 + ox1 + 1) * (1 << log2Wd))) >> (log2Wd + 1)); src += srcstride; dst += dststride; src2 += MAX_PB_SIZE; @@ -1492,7 +1492,7 @@ static void FUNC(put_hevc_epel_bi_w_hv)(uint8_t *_dst, ptrdiff_t _dststride, uin for (y = 0; y < height; y++) { for (x = 0; x < width; x++) dst[x] = av_clip_pixel(((EPEL_FILTER(tmp, MAX_PB_SIZE) >> 6) * wx1 + src2[x] * wx0 + - ((ox0 + ox1 + 1) << log2Wd)) >> (log2Wd + 1)); + ((ox0 + ox1 + 1) * (1 << log2Wd))) >> (log2Wd + 1)); tmp += MAX_PB_SIZE; dst += dststride; src2 += MAX_PB_SIZE; diff --git a/libavcodec/hevcpred_template.c b/libavcodec/hevcpred_template.c index 6ae87cca13..6fe33546b1 100644 --- a/libavcodec/hevcpred_template.c +++ b/libavcodec/hevcpred_template.c @@ -35,7 +35,7 @@ static av_always_inline void FUNC(intra_pred)(HEVCContext *s, int x0, int y0, #define MVF(x, y) \ (s->ref->tab_mvf[(x) + (y) * min_pu_width]) #define MVF_PU(x, y) \ - MVF(PU(x0 + ((x) << hshift)), PU(y0 + ((y) << vshift))) + MVF(PU(x0 + ((x) * (1 << hshift))), PU(y0 + ((y) * (1 << vshift)))) #define IS_INTRA(x, y) \ (MVF_PU(x, y).pred_flag == PF_INTRA) #define MIN_TB_ADDR_ZS(x, y) \ diff --git a/libavcodec/hq_hqa.c b/libavcodec/hq_hqa.c index 3ef83d4eb4..7ae58e0985 100644 --- a/libavcodec/hq_hqa.c +++ b/libavcodec/hq_hqa.c @@ -67,11 +67,11 @@ static int hq_decode_block(HQContext *c, GetBitContext *gb, int16_t block[64], memset(block, 0, 64 * sizeof(*block)); if (!is_hqa) { - block[0] = get_sbits(gb, 9) << 6; + block[0] = get_sbits(gb, 9) * 64; q = ff_hq_quants[qsel][is_chroma][get_bits(gb, 2)]; } else { q = ff_hq_quants[qsel][is_chroma][get_bits(gb, 2)]; - block[0] = get_sbits(gb, 9) << 6; + block[0] = get_sbits(gb, 9) * 64; } for (;;) { @@ -82,7 +82,7 @@ static int hq_decode_block(HQContext *c, GetBitContext *gb, int16_t block[64], pos += ff_hq_ac_skips[val]; if (pos >= 64) break; - block[ff_zigzag_direct[pos]] = (ff_hq_ac_syms[val] * q[pos]) >> 12; + block[ff_zigzag_direct[pos]] = (int)(ff_hq_ac_syms[val] * (unsigned)q[pos]) >> 12; pos++; } @@ -180,6 +180,9 @@ static int hqa_decode_mb(HQContext *c, AVFrame *pic, int qgroup, int flag = 0; int i, ret, cbp; + if (get_bits_left(gb) < 1) + return AVERROR_INVALIDDATA; + cbp = get_vlc2(gb, c->hqa_cbp_vlc.table, 5, 1); for (i = 0; i < 12; i++) diff --git a/libavcodec/hqxdsp.c b/libavcodec/hqxdsp.c index feff9c0b68..7f8044e463 100644 --- a/libavcodec/hqxdsp.c +++ b/libavcodec/hqxdsp.c @@ -39,18 +39,18 @@ static inline void idct_col(int16_t *blk, const uint8_t *quant) s6 = (int) blk[6 * 8] * quant[6 * 8]; s7 = (int) blk[7 * 8] * quant[7 * 8]; - t0 = (s3 * 19266 + s5 * 12873) >> 15; - t1 = (s5 * 19266 - s3 * 12873) >> 15; - t2 = ((s7 * 4520 + s1 * 22725) >> 15) - t0; - t3 = ((s1 * 4520 - s7 * 22725) >> 15) - t1; + t0 = (int)(s3 * 19266U + s5 * 12873U) >> 15; + t1 = (int)(s5 * 19266U - s3 * 12873U) >> 15; + t2 = ((int)(s7 * 4520U + s1 * 22725U) >> 15) - t0; + t3 = ((int)(s1 * 4520U - s7 * 22725U) >> 15) - t1; t4 = t0 * 2 + t2; t5 = t1 * 2 + t3; t6 = t2 - t3; t7 = t3 * 2 + t6; - t8 = (t6 * 11585) >> 14; - t9 = (t7 * 11585) >> 14; - tA = (s2 * 8867 - s6 * 21407) >> 14; - tB = (s6 * 8867 + s2 * 21407) >> 14; + t8 = (int)(t6 * 11585U) >> 14; + t9 = (int)(t7 * 11585U) >> 14; + tA = (int)(s2 * 8867U - s6 * 21407U) >> 14; + tB = (int)(s6 * 8867U + s2 * 21407U) >> 14; tC = (s0 >> 1) - (s4 >> 1); tD = (s4 >> 1) * 2 + tC; tE = tC - (tA >> 1); diff --git a/libavcodec/htmlsubtitles.c b/libavcodec/htmlsubtitles.c index a2cd40fad3..70311c66d5 100644 --- a/libavcodec/htmlsubtitles.c +++ b/libavcodec/htmlsubtitles.c @@ -46,15 +46,17 @@ typedef struct SrtStack { static void rstrip_spaces_buf(AVBPrint *buf) { - while (buf->len > 0 && buf->str[buf->len - 1] == ' ') - buf->str[--buf->len] = 0; + if (av_bprint_is_complete(buf)) + while (buf->len > 0 && buf->str[buf->len - 1] == ' ') + buf->str[--buf->len] = 0; } -void ff_htmlmarkup_to_ass(void *log_ctx, AVBPrint *dst, const char *in) +int ff_htmlmarkup_to_ass(void *log_ctx, AVBPrint *dst, const char *in) { char *param, buffer[128], tmp[128]; int len, tag_close, sptr = 1, line_start = 1, an = 0, end = 0; SrtStack stack[16]; + int closing_brace_missing = 0; stack[0].tag[0] = 0; strcpy(stack[0].param[PARAM_SIZE], "{\\fs}"); @@ -82,11 +84,20 @@ void ff_htmlmarkup_to_ass(void *log_ctx, AVBPrint *dst, const char *in) and all microdvd like styles such as {Y:xxx} */ len = 0; an += sscanf(in, "{\\an%*1u}%n", &len) >= 0 && len > 0; - if ((an != 1 && (len = 0, sscanf(in, "{\\%*[^}]}%n", &len) >= 0 && len > 0)) || - (len = 0, sscanf(in, "{%*1[CcFfoPSsYy]:%*[^}]}%n", &len) >= 0 && len > 0)) { - in += len - 1; - } else - av_bprint_chars(dst, *in, 1); + + if (!closing_brace_missing) { + if ( (an != 1 && in[1] == '\\') + || (in[1] && strchr("CcFfoPSsYy", in[1]) && in[2] == ':')) { + char *bracep = strchr(in+2, '}'); + if (bracep) { + in = bracep; + break; + } else + closing_brace_missing = 1; + } + } + + av_bprint_chars(dst, *in, 1); break; case '<': tag_close = in[1] == '/'; @@ -146,7 +157,7 @@ void ff_htmlmarkup_to_ass(void *log_ctx, AVBPrint *dst, const char *in) if (stack[sptr].param[i][0]) av_bprintf(dst, "%s", stack[sptr].param[i]); } - } else if (!tagname[1] && strspn(tagname, "bisu") == 1) { + } else if (tagname[0] && !tagname[1] && strspn(tagname, "bisu") == 1) { av_bprintf(dst, "{\\%c%d}", tagname[0], !tag_close); } else { unknown = 1; @@ -171,8 +182,13 @@ void ff_htmlmarkup_to_ass(void *log_ctx, AVBPrint *dst, const char *in) line_start = 0; } + if (!av_bprint_is_complete(dst)) + return AVERROR(ENOMEM); + while (dst->len >= 2 && !strncmp(&dst->str[dst->len - 2], "\\N", 2)) dst->len -= 2; dst->str[dst->len] = 0; rstrip_spaces_buf(dst); + + return 0; } diff --git a/libavcodec/htmlsubtitles.h b/libavcodec/htmlsubtitles.h index e10cdda241..f3a8ef5d8b 100644 --- a/libavcodec/htmlsubtitles.h +++ b/libavcodec/htmlsubtitles.h @@ -23,6 +23,6 @@ #include "libavutil/bprint.h" -void ff_htmlmarkup_to_ass(void *log_ctx, AVBPrint *dst, const char *in); +int ff_htmlmarkup_to_ass(void *log_ctx, AVBPrint *dst, const char *in); #endif /* AVCODEC_HTMLSUBTITLES_H */ diff --git a/libavcodec/huffyuvdec.c b/libavcodec/huffyuvdec.c index 7314519fca..47bca00010 100644 --- a/libavcodec/huffyuvdec.c +++ b/libavcodec/huffyuvdec.c @@ -915,6 +915,9 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVFrame *const p = data; int table_size = 0, ret; + if (buf_size < (width * height + 7)/8) + return AVERROR_INVALIDDATA; + av_fast_padded_malloc(&s->bitstream_buffer, &s->bitstream_buffer_size, buf_size); diff --git a/libavcodec/idcinvideo.c b/libavcodec/idcinvideo.c index 4a0a6fb6c0..014a3c3ed5 100644 --- a/libavcodec/idcinvideo.c +++ b/libavcodec/idcinvideo.c @@ -214,7 +214,8 @@ static int idcin_decode_frame(AVCodecContext *avctx, const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; IdcinContext *s = avctx->priv_data; - const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL); + int pal_size; + const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, &pal_size); AVFrame *frame = data; int ret; @@ -227,9 +228,11 @@ static int idcin_decode_frame(AVCodecContext *avctx, if (idcin_decode_vlcs(s, frame)) return AVERROR_INVALIDDATA; - if (pal) { + if (pal && pal_size == AVPALETTE_SIZE) { frame->palette_has_changed = 1; memcpy(s->pal, pal, AVPALETTE_SIZE); + } else if (pal) { + av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", pal_size); } /* make the palette available on the way out */ memcpy(frame->data[1], s->pal, AVPALETTE_SIZE); diff --git a/libavcodec/imgconvert.c b/libavcodec/imgconvert.c index 0035dc6e1c..3ec1403a1e 100644 --- a/libavcodec/imgconvert.c +++ b/libavcodec/imgconvert.c @@ -77,10 +77,15 @@ enum AVPixelFormat avcodec_find_best_pix_fmt_of_list(const enum AVPixelFormat *p int i; enum AVPixelFormat best = AV_PIX_FMT_NONE; + int loss; - for(i=0; pix_fmt_list[i] != AV_PIX_FMT_NONE; i++) - best = avcodec_find_best_pix_fmt_of_2(best, pix_fmt_list[i], src_pix_fmt, has_alpha, loss_ptr); + for (i=0; pix_fmt_list[i] != AV_PIX_FMT_NONE; i++) { + loss = loss_ptr ? *loss_ptr : 0; + best = avcodec_find_best_pix_fmt_of_2(best, pix_fmt_list[i], src_pix_fmt, has_alpha, &loss); + } + if (loss_ptr) + *loss_ptr = loss; return best; } diff --git a/libavcodec/indeo2.c b/libavcodec/indeo2.c index 3424e00b38..d99ad18f0e 100644 --- a/libavcodec/indeo2.c +++ b/libavcodec/indeo2.c @@ -68,6 +68,8 @@ static int ir2_decode_plane(Ir2Context *ctx, int width, int height, uint8_t *dst for (i = 0; i < c * 2; i++) dst[out++] = 0x80; } else { /* copy two values from table */ + if (c <= 0) + return AVERROR_INVALIDDATA; dst[out++] = table[c * 2]; dst[out++] = table[(c * 2) + 1]; } @@ -76,6 +78,8 @@ static int ir2_decode_plane(Ir2Context *ctx, int width, int height, uint8_t *dst for (j = 1; j < height; j++) { out = 0; + if (get_bits_left(&ctx->gb) <= 0) + return AVERROR_INVALIDDATA; while (out < width) { int c = ir2_get_code(&ctx->gb); if (c >= 0x80) { /* we have a skip */ @@ -87,7 +91,10 @@ static int ir2_decode_plane(Ir2Context *ctx, int width, int height, uint8_t *dst out++; } } else { /* add two deltas from table */ - int t = dst[out - pitch] + (table[c * 2] - 128); + int t; + if (c <= 0) + return AVERROR_INVALIDDATA; + t = dst[out - pitch] + (table[c * 2] - 128); t = av_clip_uint8(t); dst[out] = t; out++; @@ -115,12 +122,16 @@ static int ir2_decode_plane_inter(Ir2Context *ctx, int width, int height, uint8_ for (j = 0; j < height; j++) { out = 0; + if (get_bits_left(&ctx->gb) <= 0) + return AVERROR_INVALIDDATA; while (out < width) { c = ir2_get_code(&ctx->gb); if (c >= 0x80) { /* we have a skip */ c -= 0x7F; out += c * 2; } else { /* add two deltas from table */ + if (c <= 0) + return AVERROR_INVALIDDATA; t = dst[out] + (((table[c * 2] - 128)*3) >> 2); t = av_clip_uint8(t); dst[out] = t; @@ -146,6 +157,7 @@ static int ir2_decode_frame(AVCodecContext *avctx, AVFrame *picture = data; AVFrame * const p = s->picture; int start, ret; + int ltab, ctab; if ((ret = ff_reget_buffer(avctx, p)) < 0) return ret; @@ -168,34 +180,42 @@ static int ir2_decode_frame(AVCodecContext *avctx, if ((ret = init_get_bits8(&s->gb, buf + start, buf_size - start)) < 0) return ret; + ltab = buf[0x22] & 3; + ctab = buf[0x22] >> 2; + + if (ctab > 3) { + av_log(avctx, AV_LOG_ERROR, "ctab %d is invalid\n", ctab); + return AVERROR_INVALIDDATA; + } + if (s->decode_delta) { /* intraframe */ if ((ret = ir2_decode_plane(s, avctx->width, avctx->height, p->data[0], p->linesize[0], - ir2_luma_table)) < 0) + ir2_delta_table[ltab])) < 0) return ret; /* swapped U and V */ if ((ret = ir2_decode_plane(s, avctx->width >> 2, avctx->height >> 2, p->data[2], p->linesize[2], - ir2_luma_table)) < 0) + ir2_delta_table[ctab])) < 0) return ret; if ((ret = ir2_decode_plane(s, avctx->width >> 2, avctx->height >> 2, p->data[1], p->linesize[1], - ir2_luma_table)) < 0) + ir2_delta_table[ctab])) < 0) return ret; } else { /* interframe */ if ((ret = ir2_decode_plane_inter(s, avctx->width, avctx->height, p->data[0], p->linesize[0], - ir2_luma_table)) < 0) + ir2_delta_table[ltab])) < 0) return ret; /* swapped U and V */ if ((ret = ir2_decode_plane_inter(s, avctx->width >> 2, avctx->height >> 2, p->data[2], p->linesize[2], - ir2_luma_table)) < 0) + ir2_delta_table[ctab])) < 0) return ret; if ((ret = ir2_decode_plane_inter(s, avctx->width >> 2, avctx->height >> 2, p->data[1], p->linesize[1], - ir2_luma_table)) < 0) + ir2_delta_table[ctab])) < 0) return ret; } diff --git a/libavcodec/indeo2data.h b/libavcodec/indeo2data.h index 0d6d82f22c..e05c91ff58 100644 --- a/libavcodec/indeo2data.h +++ b/libavcodec/indeo2data.h @@ -27,115 +27,211 @@ #define IR2_CODES 143 static const uint16_t ir2_codes[IR2_CODES][2] = { #ifdef BITSTREAM_READER_LE -{0x0000, 3}, {0x0004, 3}, {0x0006, 3}, {0x0001, 5}, -{0x0009, 5}, {0x0019, 5}, {0x000D, 5}, {0x001D, 5}, -{0x0023, 6}, {0x0013, 6}, {0x0033, 6}, {0x000B, 6}, -{0x002B, 6}, {0x001B, 6}, {0x0007, 8}, {0x0087, 8}, -{0x0027, 8}, {0x00A7, 8}, {0x0067, 8}, {0x00E7, 8}, -{0x0097, 8}, {0x0057, 8}, {0x0037, 8}, {0x00B7, 8}, -{0x00F7, 8}, {0x000F, 9}, {0x008F, 9}, {0x018F, 9}, -{0x014F, 9}, {0x00CF, 9}, {0x002F, 9}, {0x012F, 9}, -{0x01AF, 9}, {0x006F, 9}, {0x00EF, 9}, {0x01EF, 9}, -{0x001F, 10}, {0x021F, 10}, {0x011F, 10}, {0x031F, 10}, -{0x009F, 10}, {0x029F, 10}, {0x019F, 10}, {0x039F, 10}, -{0x005F, 10}, {0x025F, 10}, {0x015F, 10}, {0x035F, 10}, -{0x00DF, 10}, {0x02DF, 10}, {0x01DF, 10}, {0x03DF, 10}, -{0x003F, 13}, {0x103F, 13}, {0x083F, 13}, {0x183F, 13}, -{0x043F, 13}, {0x143F, 13}, {0x0C3F, 13}, {0x1C3F, 13}, -{0x023F, 13}, {0x123F, 13}, {0x0A3F, 13}, {0x1A3F, 13}, -{0x063F, 13}, {0x163F, 13}, {0x0E3F, 13}, {0x1E3F, 13}, -{0x013F, 13}, {0x113F, 13}, {0x093F, 13}, {0x193F, 13}, -{0x053F, 13}, {0x153F, 13}, {0x0D3F, 13}, {0x1D3F, 13}, -{0x033F, 13}, {0x133F, 13}, {0x0B3F, 13}, {0x1B3F, 13}, -{0x073F, 13}, {0x173F, 13}, {0x0F3F, 13}, {0x1F3F, 13}, -{0x00BF, 13}, {0x10BF, 13}, {0x08BF, 13}, {0x18BF, 13}, -{0x04BF, 13}, {0x14BF, 13}, {0x0CBF, 13}, {0x1CBF, 13}, -{0x02BF, 13}, {0x12BF, 13}, {0x0ABF, 13}, {0x1ABF, 13}, -{0x06BF, 13}, {0x16BF, 13}, {0x0EBF, 13}, {0x1EBF, 13}, -{0x01BF, 13}, {0x11BF, 13}, {0x09BF, 13}, {0x19BF, 13}, -{0x05BF, 13}, {0x15BF, 13}, {0x0DBF, 13}, {0x1DBF, 13}, -{0x03BF, 13}, {0x13BF, 13}, {0x0BBF, 13}, {0x1BBF, 13}, -{0x07BF, 13}, {0x17BF, 13}, {0x0FBF, 13}, {0x1FBF, 13}, -{0x007F, 14}, {0x207F, 14}, {0x107F, 14}, {0x307F, 14}, -{0x087F, 14}, {0x287F, 14}, {0x187F, 14}, {0x387F, 14}, -{0x047F, 14}, {0x247F, 14}, {0x147F, 14}, {0x0002, 3}, -{0x0011, 5}, {0x0005, 5}, {0x0015, 5}, {0x0003, 6}, -{0x003B, 6}, {0x0047, 8}, {0x00C7, 8}, {0x0017, 8}, -{0x00D7, 8}, {0x0077, 8}, {0x010F, 9}, {0x004F, 9}, -{0x01CF, 9}, {0x00AF, 9}, {0x016F, 9}, + { 0x0000, 3 }, { 0x0004, 3 }, { 0x0006, 3 }, { 0x0001, 5 }, + { 0x0009, 5 }, { 0x0019, 5 }, { 0x000D, 5 }, { 0x001D, 5 }, + { 0x0023, 6 }, { 0x0013, 6 }, { 0x0033, 6 }, { 0x000B, 6 }, + { 0x002B, 6 }, { 0x001B, 6 }, { 0x0007, 8 }, { 0x0087, 8 }, + { 0x0027, 8 }, { 0x00A7, 8 }, { 0x0067, 8 }, { 0x00E7, 8 }, + { 0x0097, 8 }, { 0x0057, 8 }, { 0x0037, 8 }, { 0x00B7, 8 }, + { 0x00F7, 8 }, { 0x000F, 9 }, { 0x008F, 9 }, { 0x018F, 9 }, + { 0x014F, 9 }, { 0x00CF, 9 }, { 0x002F, 9 }, { 0x012F, 9 }, + { 0x01AF, 9 }, { 0x006F, 9 }, { 0x00EF, 9 }, { 0x01EF, 9 }, + { 0x001F, 10 }, { 0x021F, 10 }, { 0x011F, 10 }, { 0x031F, 10 }, + { 0x009F, 10 }, { 0x029F, 10 }, { 0x019F, 10 }, { 0x039F, 10 }, + { 0x005F, 10 }, { 0x025F, 10 }, { 0x015F, 10 }, { 0x035F, 10 }, + { 0x00DF, 10 }, { 0x02DF, 10 }, { 0x01DF, 10 }, { 0x03DF, 10 }, + { 0x003F, 13 }, { 0x103F, 13 }, { 0x083F, 13 }, { 0x183F, 13 }, + { 0x043F, 13 }, { 0x143F, 13 }, { 0x0C3F, 13 }, { 0x1C3F, 13 }, + { 0x023F, 13 }, { 0x123F, 13 }, { 0x0A3F, 13 }, { 0x1A3F, 13 }, + { 0x063F, 13 }, { 0x163F, 13 }, { 0x0E3F, 13 }, { 0x1E3F, 13 }, + { 0x013F, 13 }, { 0x113F, 13 }, { 0x093F, 13 }, { 0x193F, 13 }, + { 0x053F, 13 }, { 0x153F, 13 }, { 0x0D3F, 13 }, { 0x1D3F, 13 }, + { 0x033F, 13 }, { 0x133F, 13 }, { 0x0B3F, 13 }, { 0x1B3F, 13 }, + { 0x073F, 13 }, { 0x173F, 13 }, { 0x0F3F, 13 }, { 0x1F3F, 13 }, + { 0x00BF, 13 }, { 0x10BF, 13 }, { 0x08BF, 13 }, { 0x18BF, 13 }, + { 0x04BF, 13 }, { 0x14BF, 13 }, { 0x0CBF, 13 }, { 0x1CBF, 13 }, + { 0x02BF, 13 }, { 0x12BF, 13 }, { 0x0ABF, 13 }, { 0x1ABF, 13 }, + { 0x06BF, 13 }, { 0x16BF, 13 }, { 0x0EBF, 13 }, { 0x1EBF, 13 }, + { 0x01BF, 13 }, { 0x11BF, 13 }, { 0x09BF, 13 }, { 0x19BF, 13 }, + { 0x05BF, 13 }, { 0x15BF, 13 }, { 0x0DBF, 13 }, { 0x1DBF, 13 }, + { 0x03BF, 13 }, { 0x13BF, 13 }, { 0x0BBF, 13 }, { 0x1BBF, 13 }, + { 0x07BF, 13 }, { 0x17BF, 13 }, { 0x0FBF, 13 }, { 0x1FBF, 13 }, + { 0x007F, 14 }, { 0x207F, 14 }, { 0x107F, 14 }, { 0x307F, 14 }, + { 0x087F, 14 }, { 0x287F, 14 }, { 0x187F, 14 }, { 0x387F, 14 }, + { 0x047F, 14 }, { 0x247F, 14 }, { 0x147F, 14 }, { 0x0002, 3 }, + { 0x0011, 5 }, { 0x0005, 5 }, { 0x0015, 5 }, { 0x0003, 6 }, + { 0x003B, 6 }, { 0x0047, 8 }, { 0x00C7, 8 }, { 0x0017, 8 }, + { 0x00D7, 8 }, { 0x0077, 8 }, { 0x010F, 9 }, { 0x004F, 9 }, + { 0x01CF, 9 }, { 0x00AF, 9 }, { 0x016F, 9 }, #else - {0x0000, 3}, {0x0001, 3}, {0x0003, 3}, {0x0010, 5}, - {0x0012, 5}, {0x0013, 5}, {0x0016, 5}, {0x0017, 5}, - {0x0031, 6}, {0x0032, 6}, {0x0033, 6}, {0x0034, 6}, - {0x0035, 6}, {0x0036, 6}, {0x00E0, 8}, {0x00E1, 8}, - {0x00E4, 8}, {0x00E5, 8}, {0x00E6, 8}, {0x00E7, 8}, - {0x00E9, 8}, {0x00EA, 8}, {0x00EC, 8}, {0x00ED, 8}, - {0x00EF, 8}, {0x01E0, 9}, {0x01E2, 9}, {0x01E3, 9}, - {0x01E5, 9}, {0x01E6, 9}, {0x01E8, 9}, {0x01E9, 9}, - {0x01EB, 9}, {0x01EC, 9}, {0x01EE, 9}, {0x01EF, 9}, - {0x03E0, 10}, {0x03E1, 10}, {0x03E2, 10}, {0x03E3, 10}, - {0x03E4, 10}, {0x03E5, 10}, {0x03E6, 10}, {0x03E7, 10}, - {0x03E8, 10}, {0x03E9, 10}, {0x03EA, 10}, {0x03EB, 10}, - {0x03EC, 10}, {0x03ED, 10}, {0x03EE, 10}, {0x03EF, 10}, - {0x1F80, 13}, {0x1F81, 13}, {0x1F82, 13}, {0x1F83, 13}, - {0x1F84, 13}, {0x1F85, 13}, {0x1F86, 13}, {0x1F87, 13}, - {0x1F88, 13}, {0x1F89, 13}, {0x1F8A, 13}, {0x1F8B, 13}, - {0x1F8C, 13}, {0x1F8D, 13}, {0x1F8E, 13}, {0x1F8F, 13}, - {0x1F90, 13}, {0x1F91, 13}, {0x1F92, 13}, {0x1F93, 13}, - {0x1F94, 13}, {0x1F95, 13}, {0x1F96, 13}, {0x1F97, 13}, - {0x1F98, 13}, {0x1F99, 13}, {0x1F9A, 13}, {0x1F9B, 13}, - {0x1F9C, 13}, {0x1F9D, 13}, {0x1F9E, 13}, {0x1F9F, 13}, - {0x1FA0, 13}, {0x1FA1, 13}, {0x1FA2, 13}, {0x1FA3, 13}, - {0x1FA4, 13}, {0x1FA5, 13}, {0x1FA6, 13}, {0x1FA7, 13}, - {0x1FA8, 13}, {0x1FA9, 13}, {0x1FAA, 13}, {0x1FAB, 13}, - {0x1FAC, 13}, {0x1FAD, 13}, {0x1FAE, 13}, {0x1FAF, 13}, - {0x1FB0, 13}, {0x1FB1, 13}, {0x1FB2, 13}, {0x1FB3, 13}, - {0x1FB4, 13}, {0x1FB5, 13}, {0x1FB6, 13}, {0x1FB7, 13}, - {0x1FB8, 13}, {0x1FB9, 13}, {0x1FBA, 13}, {0x1FBB, 13}, - {0x1FBC, 13}, {0x1FBD, 13}, {0x1FBE, 13}, {0x1FBF, 13}, - {0x3F80, 14}, {0x3F81, 14}, {0x3F82, 14}, {0x3F83, 14}, - {0x3F84, 14}, {0x3F85, 14}, {0x3F86, 14}, {0x3F87, 14}, - {0x3F88, 14}, {0x3F89, 14}, {0x3F8A, 14}, {0x0002, 3}, - {0x0011, 5}, {0x0014, 5}, {0x0015, 5}, {0x0030, 6}, - {0x0037, 6}, {0x00E2, 8}, {0x00E3, 8}, {0x00E8, 8}, - {0x00EB, 8}, {0x00EE, 8}, {0x01E1, 9}, {0x01E4, 9}, - {0x01E7, 9}, {0x01EA, 9}, {0x01ED, 9} + { 0x0000, 3 }, { 0x0001, 3 }, { 0x0003, 3 }, { 0x0010, 5 }, + { 0x0012, 5 }, { 0x0013, 5 }, { 0x0016, 5 }, { 0x0017, 5 }, + { 0x0031, 6 }, { 0x0032, 6 }, { 0x0033, 6 }, { 0x0034, 6 }, + { 0x0035, 6 }, { 0x0036, 6 }, { 0x00E0, 8 }, { 0x00E1, 8 }, + { 0x00E4, 8 }, { 0x00E5, 8 }, { 0x00E6, 8 }, { 0x00E7, 8 }, + { 0x00E9, 8 }, { 0x00EA, 8 }, { 0x00EC, 8 }, { 0x00ED, 8 }, + { 0x00EF, 8 }, { 0x01E0, 9 }, { 0x01E2, 9 }, { 0x01E3, 9 }, + { 0x01E5, 9 }, { 0x01E6, 9 }, { 0x01E8, 9 }, { 0x01E9, 9 }, + { 0x01EB, 9 }, { 0x01EC, 9 }, { 0x01EE, 9 }, { 0x01EF, 9 }, + { 0x03E0, 10 }, { 0x03E1, 10 }, { 0x03E2, 10 }, { 0x03E3, 10 }, + { 0x03E4, 10 }, { 0x03E5, 10 }, { 0x03E6, 10 }, { 0x03E7, 10 }, + { 0x03E8, 10 }, { 0x03E9, 10 }, { 0x03EA, 10 }, { 0x03EB, 10 }, + { 0x03EC, 10 }, { 0x03ED, 10 }, { 0x03EE, 10 }, { 0x03EF, 10 }, + { 0x1F80, 13 }, { 0x1F81, 13 }, { 0x1F82, 13 }, { 0x1F83, 13 }, + { 0x1F84, 13 }, { 0x1F85, 13 }, { 0x1F86, 13 }, { 0x1F87, 13 }, + { 0x1F88, 13 }, { 0x1F89, 13 }, { 0x1F8A, 13 }, { 0x1F8B, 13 }, + { 0x1F8C, 13 }, { 0x1F8D, 13 }, { 0x1F8E, 13 }, { 0x1F8F, 13 }, + { 0x1F90, 13 }, { 0x1F91, 13 }, { 0x1F92, 13 }, { 0x1F93, 13 }, + { 0x1F94, 13 }, { 0x1F95, 13 }, { 0x1F96, 13 }, { 0x1F97, 13 }, + { 0x1F98, 13 }, { 0x1F99, 13 }, { 0x1F9A, 13 }, { 0x1F9B, 13 }, + { 0x1F9C, 13 }, { 0x1F9D, 13 }, { 0x1F9E, 13 }, { 0x1F9F, 13 }, + { 0x1FA0, 13 }, { 0x1FA1, 13 }, { 0x1FA2, 13 }, { 0x1FA3, 13 }, + { 0x1FA4, 13 }, { 0x1FA5, 13 }, { 0x1FA6, 13 }, { 0x1FA7, 13 }, + { 0x1FA8, 13 }, { 0x1FA9, 13 }, { 0x1FAA, 13 }, { 0x1FAB, 13 }, + { 0x1FAC, 13 }, { 0x1FAD, 13 }, { 0x1FAE, 13 }, { 0x1FAF, 13 }, + { 0x1FB0, 13 }, { 0x1FB1, 13 }, { 0x1FB2, 13 }, { 0x1FB3, 13 }, + { 0x1FB4, 13 }, { 0x1FB5, 13 }, { 0x1FB6, 13 }, { 0x1FB7, 13 }, + { 0x1FB8, 13 }, { 0x1FB9, 13 }, { 0x1FBA, 13 }, { 0x1FBB, 13 }, + { 0x1FBC, 13 }, { 0x1FBD, 13 }, { 0x1FBE, 13 }, { 0x1FBF, 13 }, + { 0x3F80, 14 }, { 0x3F81, 14 }, { 0x3F82, 14 }, { 0x3F83, 14 }, + { 0x3F84, 14 }, { 0x3F85, 14 }, { 0x3F86, 14 }, { 0x3F87, 14 }, + { 0x3F88, 14 }, { 0x3F89, 14 }, { 0x3F8A, 14 }, { 0x0002, 3 }, + { 0x0011, 5 }, { 0x0014, 5 }, { 0x0015, 5 }, { 0x0030, 6 }, + { 0x0037, 6 }, { 0x00E2, 8 }, { 0x00E3, 8 }, { 0x00E8, 8 }, + { 0x00EB, 8 }, { 0x00EE, 8 }, { 0x01E1, 9 }, { 0x01E4, 9 }, + { 0x01E7, 9 }, { 0x01EA, 9 }, { 0x01ED, 9 }, #endif }; -static const uint8_t ir2_luma_table[256] = { - 0x80, 0x80, 0x84, 0x84, 0x7C, 0x7C, 0x7F, 0x85, - 0x81, 0x7B, 0x85, 0x7F, 0x7B, 0x81, 0x8C, 0x8C, - 0x74, 0x74, 0x83, 0x8D, 0x7D, 0x73, 0x8D, 0x83, - 0x73, 0x7D, 0x77, 0x89, 0x89, 0x77, 0x89, 0x77, - 0x77, 0x89, 0x8C, 0x95, 0x74, 0x6B, 0x95, 0x8C, - 0x6B, 0x74, 0x7C, 0x90, 0x84, 0x70, 0x90, 0x7C, - 0x70, 0x84, 0x96, 0x96, 0x6A, 0x6A, 0x82, 0x98, - 0x7E, 0x68, 0x98, 0x82, 0x68, 0x7E, 0x97, 0xA2, - 0x69, 0x5E, 0xA2, 0x97, 0x5E, 0x69, 0xA2, 0xA2, - 0x5E, 0x5E, 0x8B, 0xA3, 0x75, 0x5D, 0xA3, 0x8B, - 0x5D, 0x75, 0x71, 0x95, 0x8F, 0x6B, 0x95, 0x71, - 0x6B, 0x8F, 0x78, 0x9D, 0x88, 0x63, 0x9D, 0x78, - 0x63, 0x88, 0x7F, 0xA7, 0x81, 0x59, 0xA7, 0x7F, - 0x59, 0x81, 0xA4, 0xB1, 0x5C, 0x4F, 0xB1, 0xA4, - 0x4F, 0x5C, 0x96, 0xB1, 0x6A, 0x4F, 0xB1, 0x96, - 0x4F, 0x6A, 0xB2, 0xB2, 0x4E, 0x4E, 0x65, 0x9B, - 0x9B, 0x65, 0x9B, 0x65, 0x65, 0x9B, 0x89, 0xB4, - 0x77, 0x4C, 0xB4, 0x89, 0x4C, 0x77, 0x6A, 0xA3, - 0x96, 0x5D, 0xA3, 0x6A, 0x5D, 0x96, 0x73, 0xAC, - 0x8D, 0x54, 0xAC, 0x73, 0x54, 0x8D, 0xB4, 0xC3, - 0x4C, 0x3D, 0xC3, 0xB4, 0x3D, 0x4C, 0xA4, 0xC3, - 0x5C, 0x3D, 0xC3, 0xA4, 0x3D, 0x5C, 0xC4, 0xC4, - 0x3C, 0x3C, 0x96, 0xC6, 0x6A, 0x3A, 0xC6, 0x96, - 0x3A, 0x6A, 0x7C, 0xBA, 0x84, 0x46, 0xBA, 0x7C, - 0x46, 0x84, 0x5B, 0xAB, 0xA5, 0x55, 0xAB, 0x5B, - 0x55, 0xA5, 0x63, 0xB4, 0x9D, 0x4C, 0xB4, 0x63, - 0x4C, 0x9D, 0x86, 0xCA, 0x7A, 0x36, 0xCA, 0x86, - 0x36, 0x7A, 0xB6, 0xD7, 0x4A, 0x29, 0xD7, 0xB6, - 0x29, 0x4A, 0xC8, 0xD7, 0x38, 0x29, 0xD7, 0xC8, - 0x29, 0x38, 0xA4, 0xD8, 0x5C, 0x28, 0xD8, 0xA4, - 0x28, 0x5C, 0x6C, 0xC1, 0x94, 0x3F, 0xC1, 0x6C, - 0x3F, 0x94, 0xD9, 0xD9, 0x27, 0x27, 0x80, 0x80 +static const uint8_t ir2_delta_table[4][256] = { + { 0x80, 0x80, 0x84, 0x84, 0x7C, 0x7C, 0x7F, 0x85, + 0x81, 0x7B, 0x85, 0x7F, 0x7B, 0x81, 0x8C, 0x8C, + 0x74, 0x74, 0x83, 0x8D, 0x7D, 0x73, 0x8D, 0x83, + 0x73, 0x7D, 0x77, 0x89, 0x89, 0x77, 0x89, 0x77, + 0x77, 0x89, 0x8C, 0x95, 0x74, 0x6B, 0x95, 0x8C, + 0x6B, 0x74, 0x7C, 0x90, 0x84, 0x70, 0x90, 0x7C, + 0x70, 0x84, 0x96, 0x96, 0x6A, 0x6A, 0x82, 0x98, + 0x7E, 0x68, 0x98, 0x82, 0x68, 0x7E, 0x97, 0xA2, + 0x69, 0x5E, 0xA2, 0x97, 0x5E, 0x69, 0xA2, 0xA2, + 0x5E, 0x5E, 0x8B, 0xA3, 0x75, 0x5D, 0xA3, 0x8B, + 0x5D, 0x75, 0x71, 0x95, 0x8F, 0x6B, 0x95, 0x71, + 0x6B, 0x8F, 0x78, 0x9D, 0x88, 0x63, 0x9D, 0x78, + 0x63, 0x88, 0x7F, 0xA7, 0x81, 0x59, 0xA7, 0x7F, + 0x59, 0x81, 0xA4, 0xB1, 0x5C, 0x4F, 0xB1, 0xA4, + 0x4F, 0x5C, 0x96, 0xB1, 0x6A, 0x4F, 0xB1, 0x96, + 0x4F, 0x6A, 0xB2, 0xB2, 0x4E, 0x4E, 0x65, 0x9B, + 0x9B, 0x65, 0x9B, 0x65, 0x65, 0x9B, 0x89, 0xB4, + 0x77, 0x4C, 0xB4, 0x89, 0x4C, 0x77, 0x6A, 0xA3, + 0x96, 0x5D, 0xA3, 0x6A, 0x5D, 0x96, 0x73, 0xAC, + 0x8D, 0x54, 0xAC, 0x73, 0x54, 0x8D, 0xB4, 0xC3, + 0x4C, 0x3D, 0xC3, 0xB4, 0x3D, 0x4C, 0xA4, 0xC3, + 0x5C, 0x3D, 0xC3, 0xA4, 0x3D, 0x5C, 0xC4, 0xC4, + 0x3C, 0x3C, 0x96, 0xC6, 0x6A, 0x3A, 0xC6, 0x96, + 0x3A, 0x6A, 0x7C, 0xBA, 0x84, 0x46, 0xBA, 0x7C, + 0x46, 0x84, 0x5B, 0xAB, 0xA5, 0x55, 0xAB, 0x5B, + 0x55, 0xA5, 0x63, 0xB4, 0x9D, 0x4C, 0xB4, 0x63, + 0x4C, 0x9D, 0x86, 0xCA, 0x7A, 0x36, 0xCA, 0x86, + 0x36, 0x7A, 0xB6, 0xD7, 0x4A, 0x29, 0xD7, 0xB6, + 0x29, 0x4A, 0xC8, 0xD7, 0x38, 0x29, 0xD7, 0xC8, + 0x29, 0x38, 0xA4, 0xD8, 0x5C, 0x28, 0xD8, 0xA4, + 0x28, 0x5C, 0x6C, 0xC1, 0x94, 0x3F, 0xC1, 0x6C, + 0x3F, 0x94, 0xD9, 0xD9, 0x27, 0x27, 0x80, 0x80, }, + { 0x80, 0x80, 0x85, 0x85, 0x7B, 0x7B, 0x7E, 0x87, + 0x82, 0x79, 0x87, 0x7E, 0x79, 0x82, 0x8F, 0x8F, + 0x71, 0x71, 0x84, 0x8F, 0x7C, 0x71, 0x8F, 0x84, + 0x71, 0x7C, 0x75, 0x8B, 0x8B, 0x75, 0x8B, 0x75, + 0x75, 0x8B, 0x8E, 0x9A, 0x72, 0x66, 0x9A, 0x8E, + 0x66, 0x72, 0x7B, 0x93, 0x85, 0x6D, 0x93, 0x7B, + 0x6D, 0x85, 0x9B, 0x9B, 0x65, 0x65, 0x82, 0x9D, + 0x7E, 0x63, 0x9D, 0x82, 0x63, 0x7E, 0x9B, 0xA8, + 0x65, 0x58, 0xA8, 0x9B, 0x58, 0x65, 0xA9, 0xA9, + 0x57, 0x57, 0x8D, 0xAA, 0x73, 0x56, 0xAA, 0x8D, + 0x56, 0x73, 0x6E, 0x99, 0x92, 0x67, 0x99, 0x6E, + 0x67, 0x92, 0x76, 0xA2, 0x8A, 0x5E, 0xA2, 0x76, + 0x5E, 0x8A, 0x7F, 0xAF, 0x81, 0x51, 0xAF, 0x7F, + 0x51, 0x81, 0xAB, 0xBA, 0x55, 0x46, 0xBA, 0xAB, + 0x46, 0x55, 0x9A, 0xBB, 0x66, 0x45, 0xBB, 0x9A, + 0x45, 0x66, 0xBB, 0xBB, 0x45, 0x45, 0x60, 0xA0, + 0xA0, 0x60, 0xA0, 0x60, 0x60, 0xA0, 0x8B, 0xBE, + 0x75, 0x42, 0xBE, 0x8B, 0x42, 0x75, 0x66, 0xAA, + 0x9A, 0x56, 0xAA, 0x66, 0x56, 0x9A, 0x70, 0xB5, + 0x90, 0x4B, 0xB5, 0x70, 0x4B, 0x90, 0xBE, 0xCF, + 0x42, 0x31, 0xCF, 0xBE, 0x31, 0x42, 0xAB, 0xD0, + 0x55, 0x30, 0xD0, 0xAB, 0x30, 0x55, 0xD1, 0xD1, + 0x2F, 0x2F, 0x9A, 0xD3, 0x66, 0x2D, 0xD3, 0x9A, + 0x2D, 0x66, 0x7B, 0xC5, 0x85, 0x3B, 0xC5, 0x7B, + 0x3B, 0x85, 0x54, 0xB4, 0xAC, 0x4C, 0xB4, 0x54, + 0x4C, 0xAC, 0x5E, 0xBE, 0xA2, 0x42, 0xBE, 0x5E, + 0x42, 0xA2, 0x87, 0xD8, 0x79, 0x28, 0xD8, 0x87, + 0x28, 0x79, 0xC0, 0xE8, 0x40, 0x18, 0xE8, 0xC0, + 0x18, 0x40, 0xD5, 0xE8, 0x2B, 0x18, 0xE8, 0xD5, + 0x18, 0x2B, 0xAB, 0xE9, 0x55, 0x17, 0xE9, 0xAB, + 0x17, 0x55, 0x68, 0xCD, 0x98, 0x33, 0xCD, 0x68, + 0x33, 0x98, 0xEA, 0xEA, 0x16, 0x16, 0x80, 0x80, }, + { 0x80, 0x80, 0x86, 0x86, 0x7A, 0x7A, 0x7E, 0x88, + 0x82, 0x78, 0x88, 0x7E, 0x78, 0x82, 0x92, 0x92, + 0x6E, 0x6E, 0x85, 0x92, 0x7B, 0x6E, 0x92, 0x85, + 0x6E, 0x7B, 0x73, 0x8D, 0x8D, 0x73, 0x8D, 0x73, + 0x73, 0x8D, 0x91, 0x9E, 0x6F, 0x62, 0x9E, 0x91, + 0x62, 0x6F, 0x79, 0x97, 0x87, 0x69, 0x97, 0x79, + 0x69, 0x87, 0xA0, 0xA0, 0x60, 0x60, 0x83, 0xA2, + 0x7D, 0x5E, 0xA2, 0x83, 0x5E, 0x7D, 0xA0, 0xB0, + 0x60, 0x50, 0xB0, 0xA0, 0x50, 0x60, 0xB1, 0xB1, + 0x4F, 0x4F, 0x8F, 0xB2, 0x71, 0x4E, 0xB2, 0x8F, + 0x4E, 0x71, 0x6B, 0x9E, 0x95, 0x62, 0x9E, 0x6B, + 0x62, 0x95, 0x74, 0xA9, 0x8C, 0x57, 0xA9, 0x74, + 0x57, 0x8C, 0x7F, 0xB8, 0x81, 0x48, 0xB8, 0x7F, + 0x48, 0x81, 0xB4, 0xC5, 0x4C, 0x3B, 0xC5, 0xB4, + 0x3B, 0x4C, 0x9F, 0xC6, 0x61, 0x3A, 0xC6, 0x9F, + 0x3A, 0x61, 0xC6, 0xC6, 0x3A, 0x3A, 0x59, 0xA7, + 0xA7, 0x59, 0xA7, 0x59, 0x59, 0xA7, 0x8D, 0xCA, + 0x73, 0x36, 0xCA, 0x8D, 0x36, 0x73, 0x61, 0xB2, + 0x9F, 0x4E, 0xB2, 0x61, 0x4E, 0x9F, 0x6D, 0xBF, + 0x93, 0x41, 0xBF, 0x6D, 0x41, 0x93, 0xCA, 0xDF, + 0x36, 0x21, 0xDF, 0xCA, 0x21, 0x36, 0xB3, 0xDF, + 0x4D, 0x21, 0xDF, 0xB3, 0x21, 0x4D, 0xE1, 0xE1, + 0x1F, 0x1F, 0x9F, 0xE3, 0x61, 0x1D, 0xE3, 0x9F, + 0x1D, 0x61, 0x7A, 0xD3, 0x86, 0x2D, 0xD3, 0x7A, + 0x2D, 0x86, 0x4C, 0xBE, 0xB4, 0x42, 0xBE, 0x4C, + 0x42, 0xB4, 0x57, 0xCA, 0xA9, 0x36, 0xCA, 0x57, + 0x36, 0xA9, 0x88, 0xE9, 0x78, 0x17, 0xE9, 0x88, + 0x17, 0x78, 0xCC, 0xFB, 0x34, 0x05, 0xFB, 0xCC, + 0x05, 0x34, 0xE6, 0xFB, 0x1A, 0x05, 0xFB, 0xE6, + 0x05, 0x1A, 0xB4, 0xFD, 0x4C, 0x03, 0xFD, 0xB4, + 0x03, 0x4C, 0x63, 0xDC, 0x9D, 0x24, 0xDC, 0x63, + 0x24, 0x9D, 0xFE, 0xFE, 0x02, 0x02, 0x80, 0x80, }, + { 0x80, 0x80, 0x87, 0x87, 0x79, 0x79, 0x7E, 0x89, + 0x82, 0x77, 0x89, 0x7E, 0x77, 0x82, 0x95, 0x95, + 0x6B, 0x6B, 0x86, 0x96, 0x7A, 0x6A, 0x96, 0x86, + 0x6A, 0x7A, 0x70, 0x90, 0x90, 0x70, 0x90, 0x70, + 0x70, 0x90, 0x94, 0xA4, 0x6C, 0x5C, 0xA4, 0x94, + 0x5C, 0x6C, 0x78, 0x9B, 0x88, 0x65, 0x9B, 0x78, + 0x65, 0x88, 0xA6, 0xA6, 0x5A, 0x5A, 0x83, 0xA9, + 0x7D, 0x57, 0xA9, 0x83, 0x57, 0x7D, 0xA6, 0xB9, + 0x5A, 0x47, 0xB9, 0xA6, 0x47, 0x5A, 0xBA, 0xBA, + 0x46, 0x46, 0x92, 0xBC, 0x6E, 0x44, 0xBC, 0x92, + 0x44, 0x6E, 0x67, 0xA3, 0x99, 0x5D, 0xA3, 0x67, + 0x5D, 0x99, 0x72, 0xB0, 0x8E, 0x50, 0xB0, 0x72, + 0x50, 0x8E, 0x7F, 0xC3, 0x81, 0x3D, 0xC3, 0x7F, + 0x3D, 0x81, 0xBE, 0xD2, 0x42, 0x2E, 0xD2, 0xBE, + 0x2E, 0x42, 0xA5, 0xD4, 0x5B, 0x2C, 0xD4, 0xA5, + 0x2C, 0x5B, 0xD4, 0xD4, 0x2C, 0x2C, 0x52, 0xAE, + 0xAE, 0x52, 0xAE, 0x52, 0x52, 0xAE, 0x8F, 0xD8, + 0x71, 0x28, 0xD8, 0x8F, 0x28, 0x71, 0x5B, 0xBB, + 0xA5, 0x45, 0xBB, 0x5B, 0x45, 0xA5, 0x69, 0xCB, + 0x97, 0x35, 0xCB, 0x69, 0x35, 0x97, 0xD8, 0xF0, + 0x28, 0x10, 0xF0, 0xD8, 0x10, 0x28, 0xBD, 0xF1, + 0x43, 0x0F, 0xF1, 0xBD, 0x0F, 0x43, 0xF3, 0xF3, + 0x0D, 0x0D, 0xA5, 0xF6, 0x5B, 0x0A, 0xF6, 0xA5, + 0x0A, 0x5B, 0x78, 0xE2, 0x88, 0x1E, 0xE2, 0x78, + 0x1E, 0x88, 0x42, 0xC9, 0xBE, 0x37, 0xC9, 0x42, + 0x37, 0xBE, 0x4F, 0xD8, 0xB1, 0x28, 0xD8, 0x4F, + 0x28, 0xB1, 0x8A, 0xFD, 0x76, 0x03, 0xFD, 0x8A, + 0x03, 0x76, 0xDB, 0xFF, 0x25, 0x01, 0xFF, 0xDB, + 0x01, 0x25, 0xF9, 0xFF, 0x07, 0x01, 0xFF, 0xF9, + 0x01, 0x07, 0xBE, 0xFF, 0x42, 0x01, 0xFF, 0xBE, + 0x01, 0x42, 0x5E, 0xED, 0xA2, 0x13, 0xED, 0x5E, + 0x13, 0xA2, 0xFF, 0xFF, 0x01, 0x01, 0x80, 0x80, }, }; #endif /* AVCODEC_INDEO2DATA_H */ diff --git a/libavcodec/indeo4.c b/libavcodec/indeo4.c index 0065b52c75..b2d3cd5f4b 100644 --- a/libavcodec/indeo4.c +++ b/libavcodec/indeo4.c @@ -246,6 +246,8 @@ static int decode_pic_hdr(IVI45DecContext *ctx, AVCodecContext *avctx) /* skip picture header extension if any */ while (get_bits1(&ctx->gb)) { ff_dlog(avctx, "Pic hdr extension encountered!\n"); + if (get_bits_left(&ctx->gb) < 10) + return AVERROR_INVALIDDATA; skip_bits(&ctx->gb, 8); } @@ -267,12 +269,14 @@ static int decode_pic_hdr(IVI45DecContext *ctx, AVCodecContext *avctx) * @param[in] avctx pointer to the AVCodecContext * @return result code: 0 = OK, negative number = error */ -static int decode_band_hdr(IVI45DecContext *ctx, IVIBandDesc *band, +static int decode_band_hdr(IVI45DecContext *ctx, IVIBandDesc *arg_band, AVCodecContext *avctx) { int plane, band_num, indx, transform_id, scan_indx; int i; int quant_mat; + IVIBandDesc temp_band, *band = &temp_band; + memcpy(&temp_band, arg_band, sizeof(temp_band)); plane = get_bits(&ctx->gb, 2); band_num = get_bits(&ctx->gb, 4); @@ -406,10 +410,10 @@ static int decode_band_hdr(IVI45DecContext *ctx, IVIBandDesc *band, /* decode block huffman codebook */ if (!get_bits1(&ctx->gb)) - band->blk_vlc.tab = ctx->blk_vlc.tab; + arg_band->blk_vlc.tab = ctx->blk_vlc.tab; else if (ff_ivi_dec_huff_desc(&ctx->gb, 1, IVI_BLK_HUFF, - &band->blk_vlc, avctx)) + &arg_band->blk_vlc, avctx)) return AVERROR_INVALIDDATA; /* select appropriate rvmap table for this band */ @@ -450,6 +454,9 @@ static int decode_band_hdr(IVI45DecContext *ctx, IVIBandDesc *band, return AVERROR_INVALIDDATA; } + band->blk_vlc = arg_band->blk_vlc; + memcpy(arg_band, band, sizeof(*arg_band)); + return 0; } @@ -498,6 +505,11 @@ static int decode_mb_info(IVI45DecContext *ctx, IVIBandDesc *band, mb->b_mv_x = mb->b_mv_y = 0; + if (get_bits_left(&ctx->gb) < 1) { + av_log(avctx, AV_LOG_ERROR, "Insufficient input for mb info\n"); + return AVERROR_INVALIDDATA; + } + if (get_bits1(&ctx->gb)) { if (ctx->frame_type == IVI4_FRAMETYPE_INTRA) { av_log(avctx, AV_LOG_ERROR, "Empty macroblock in an INTRA picture!\n"); diff --git a/libavcodec/indeo5.c b/libavcodec/indeo5.c index 5f931c8b98..5028def4bc 100644 --- a/libavcodec/indeo5.c +++ b/libavcodec/indeo5.c @@ -324,6 +324,7 @@ static int decode_pic_hdr(IVI45DecContext *ctx, AVCodecContext *avctx) ctx->frame_type = get_bits(&ctx->gb, 3); if (ctx->frame_type >= 5) { av_log(avctx, AV_LOG_ERROR, "Invalid frame type: %d \n", ctx->frame_type); + ctx->frame_type = FRAMETYPE_INTRA; return AVERROR_INVALIDDATA; } diff --git a/libavcodec/internal.h b/libavcodec/internal.h index 24d320c186..6c0efec8b1 100644 --- a/libavcodec/internal.h +++ b/libavcodec/internal.h @@ -293,6 +293,8 @@ const uint8_t *avpriv_find_start_code(const uint8_t *p, const uint8_t *end, uint32_t *state); +int avpriv_codec_get_cap_skip_frame_fill_param(const AVCodec *codec); + /** * Check that the provided frame dimensions are valid and set them on the codec * context. diff --git a/libavcodec/interplayacm.c b/libavcodec/interplayacm.c index a676bcb931..8b340093df 100644 --- a/libavcodec/interplayacm.c +++ b/libavcodec/interplayacm.c @@ -61,6 +61,11 @@ static av_cold int decode_init(AVCodecContext *avctx) if (avctx->extradata_size < 14) return AVERROR_INVALIDDATA; + if (avctx->channels <= 0) { + av_log(avctx, AV_LOG_ERROR, "Invalid number of channels: %d\n", avctx->channels); + return AVERROR_INVALIDDATA; + } + s->level = AV_RL16(avctx->extradata + 12) & 0xf; s->rows = AV_RL16(avctx->extradata + 12) >> 4; s->cols = 1 << s->level; @@ -71,7 +76,7 @@ static av_cold int decode_init(AVCodecContext *avctx) s->block = av_calloc(s->block_len, sizeof(int)); s->wrapbuf = av_calloc(s->wrapbuf_len, sizeof(int)); s->ampbuf = av_calloc(0x10000, sizeof(int)); - s->bitstream = av_calloc(s->max_framesize, sizeof(*s->bitstream)); + s->bitstream = av_calloc(s->max_framesize + AV_INPUT_BUFFER_PADDING_SIZE / sizeof(*s->bitstream) + 1, sizeof(*s->bitstream)); if (!s->block || !s->wrapbuf || !s->ampbuf || !s->bitstream) return AVERROR(ENOMEM); @@ -325,6 +330,10 @@ static int t15(InterplayACMContext *s, unsigned ind, unsigned col) for (i = 0; i < s->rows; i++) { /* b = (x1) + (x2 * 3) + (x3 * 9) */ b = get_bits(gb, 5); + if (b > 26) { + av_log(NULL, AV_LOG_ERROR, "Too large b = %d > 26\n", b); + return AVERROR_INVALIDDATA; + } n1 = (mul_3x3[b] & 0x0F) - 1; n2 = ((mul_3x3[b] >> 4) & 0x0F) - 1; @@ -350,6 +359,10 @@ static int t27(InterplayACMContext *s, unsigned ind, unsigned col) for (i = 0; i < s->rows; i++) { /* b = (x1) + (x2 * 5) + (x3 * 25) */ b = get_bits(gb, 7); + if (b > 124) { + av_log(NULL, AV_LOG_ERROR, "Too large b = %d > 124\n", b); + return AVERROR_INVALIDDATA; + } n1 = (mul_3x5[b] & 0x0F) - 2; n2 = ((mul_3x5[b] >> 4) & 0x0F) - 2; @@ -374,6 +387,10 @@ static int t37(InterplayACMContext *s, unsigned ind, unsigned col) for (i = 0; i < s->rows; i++) { /* b = (x1) + (x2 * 11) */ b = get_bits(gb, 7); + if (b > 120) { + av_log(NULL, AV_LOG_ERROR, "Too large b = %d > 120\n", b); + return AVERROR_INVALIDDATA; + } n1 = (mul_2x11[b] & 0x0F) - 5; n2 = ((mul_2x11[b] >> 4) & 0x0F) - 5; diff --git a/libavcodec/interplayvideo.c b/libavcodec/interplayvideo.c index 1460741a53..48dc3783b4 100644 --- a/libavcodec/interplayvideo.c +++ b/libavcodec/interplayvideo.c @@ -988,6 +988,11 @@ static int ipvideo_decode_frame(AVCodecContext *avctx, AVFrame *frame = data; int ret; + if (av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, NULL)) { + av_frame_unref(s->last_frame); + av_frame_unref(s->second_last_frame); + } + if (buf_size < 2) return AVERROR_INVALIDDATA; @@ -999,10 +1004,6 @@ static int ipvideo_decode_frame(AVCodecContext *avctx, if (buf_size < s->decoding_map_size + 2) return buf_size; - if (av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, NULL)) { - av_frame_unref(s->last_frame); - av_frame_unref(s->second_last_frame); - } s->decoding_map = buf + 2; bytestream2_init(&s->stream_ptr, buf + 2 + s->decoding_map_size, @@ -1012,10 +1013,13 @@ static int ipvideo_decode_frame(AVCodecContext *avctx, return ret; if (!s->is_16bpp) { - const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL); - if (pal) { + int size; + const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, &size); + if (pal && size == AVPALETTE_SIZE) { frame->palette_has_changed = 1; memcpy(s->pal, pal, AVPALETTE_SIZE); + } else if (pal) { + av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", size); } } diff --git a/libavcodec/ituh263dec.c b/libavcodec/ituh263dec.c index 2e449f8eeb..2d83bf3d30 100644 --- a/libavcodec/ituh263dec.c +++ b/libavcodec/ituh263dec.c @@ -167,6 +167,7 @@ static int h263_decode_gob_header(MpegEncContext *s) /* We have a GBSC probably with GSTUFF */ skip_bits(&s->gb, 16); /* Drop the zeros */ left= get_bits_left(&s->gb); + left = FFMIN(left, 32); //MN: we must check the bits left or we might end in a infinite loop (or segfault) for(;left>13; left--){ if(get_bits1(&s->gb)) break; /* Seek the '1' bit */ @@ -523,7 +524,7 @@ retry: }else{ level = SHOW_UBITS(re, &s->gb, 5); SKIP_CACHE(re, &s->gb, 5); - level |= SHOW_SBITS(re, &s->gb, 6)<<5; + level |= SHOW_SBITS(re, &s->gb, 6) * (1<<5); SKIP_COUNTER(re, &s->gb, 5 + 6); } } diff --git a/libavcodec/ivi_dsp.c b/libavcodec/ivi_dsp.c index 4b973992e0..2286c58033 100644 --- a/libavcodec/ivi_dsp.c +++ b/libavcodec/ivi_dsp.c @@ -116,10 +116,10 @@ void ff_ivi_recompose53(const IVIPlaneDesc *plane, uint8_t *dst, b0_2 = b0_ptr[pitch+indx+1]; tmp1 = tmp0 + b0_1; - p0 = tmp0 << 4; - p1 = tmp1 << 3; - p2 = (tmp0 + tmp2) << 3; - p3 = (tmp1 + tmp2 + b0_2) << 2; + p0 = tmp0 * 16; + p1 = tmp1 * 8; + p2 = (tmp0 + tmp2) * 8; + p3 = (tmp1 + tmp2 + b0_2) * 4; } /* process the HL-band by applying HPF vertically and LPF horizontally */ @@ -132,10 +132,10 @@ void ff_ivi_recompose53(const IVIPlaneDesc *plane, uint8_t *dst, tmp2 = tmp1 - tmp0*6 + b1_3; b1_3 = b1_1 - b1_2*6 + b1_ptr[pitch+indx+1]; - p0 += (tmp0 + tmp1) << 3; - p1 += (tmp0 + tmp1 + b1_1 + b1_2) << 2; - p2 += tmp2 << 2; - p3 += (tmp2 + b1_3) << 1; + p0 += (tmp0 + tmp1) * 8; + p1 += (tmp0 + tmp1 + b1_1 + b1_2) * 4; + p2 += tmp2 * 4; + p3 += (tmp2 + b1_3) * 2; } /* process the LH-band by applying LPF vertically and HPF horizontally */ @@ -146,10 +146,10 @@ void ff_ivi_recompose53(const IVIPlaneDesc *plane, uint8_t *dst, tmp0 = b2_1 + b2_2; tmp1 = b2_1 - b2_2*6 + b2_3; - p0 += tmp0 << 3; - p1 += tmp1 << 2; - p2 += (tmp0 + b2_4 + b2_5) << 2; - p3 += (tmp1 + b2_4 - b2_5*6 + b2_6) << 1; + p0 += tmp0 * 8; + p1 += tmp1 * 4; + p2 += (tmp0 + b2_4 + b2_5) * 4; + p3 += (tmp1 + b2_4 - b2_5*6 + b2_6) * 2; } /* process the HH-band by applying HPF both vertically and horizontally */ @@ -163,9 +163,9 @@ void ff_ivi_recompose53(const IVIPlaneDesc *plane, uint8_t *dst, b3_9 = b3_3 - b3_6*6 + b3_ptr[pitch+indx+1]; - p0 += (tmp0 + tmp1) << 2; - p1 += (tmp0 - tmp1*6 + tmp2) << 1; - p2 += (b3_7 + b3_8) << 1; + p0 += (tmp0 + tmp1) * 4; + p1 += (tmp0 - tmp1*6 + tmp2) * 2; + p2 += (b3_7 + b3_8) * 2; p3 += b3_7 - b3_8*6 + b3_9; } @@ -243,7 +243,7 @@ void ff_ivi_recompose_haar(const IVIPlaneDesc *plane, uint8_t *dst, #define INV_HAAR8(s1, s5, s3, s7, s2, s4, s6, s8,\ d1, d2, d3, d4, d5, d6, d7, d8,\ t0, t1, t2, t3, t4, t5, t6, t7, t8) {\ - t1 = (s1) << 1; t5 = (s5) << 1;\ + t1 = (s1) * 2; t5 = (s5) * 2;\ IVI_HAAR_BFLY(t1, t5, t1, t5, t0); IVI_HAAR_BFLY(t1, s3, t1, t3, t0);\ IVI_HAAR_BFLY(t5, s7, t5, t7, t0); IVI_HAAR_BFLY(t1, s2, t1, t2, t0);\ IVI_HAAR_BFLY(t3, s4, t3, t4, t0); IVI_HAAR_BFLY(t5, s6, t5, t6, t0);\ @@ -284,10 +284,10 @@ void ff_ivi_inverse_haar_8x8(const int32_t *in, int16_t *out, uint32_t pitch, if (flags[i]) { /* pre-scaling */ shift = !(i & 4); - sp1 = src[ 0] << shift; - sp2 = src[ 8] << shift; - sp3 = src[16] << shift; - sp4 = src[24] << shift; + sp1 = src[ 0] * (1 << shift); + sp2 = src[ 8] * (1 << shift); + sp3 = src[16] * (1 << shift); + sp4 = src[24] * (1 << shift); INV_HAAR8( sp1, sp2, sp3, sp4, src[32], src[40], src[48], src[56], dst[ 0], dst[ 8], dst[16], dst[24], @@ -393,8 +393,8 @@ void ff_ivi_inverse_haar_4x4(const int32_t *in, int16_t *out, uint32_t pitch, if (flags[i]) { /* pre-scaling */ shift = !(i & 2); - sp1 = src[0] << shift; - sp2 = src[4] << shift; + sp1 = src[0] * (1 << shift); + sp2 = src[4] * (1 << shift); INV_HAAR4( sp1, sp2, src[8], src[12], dst[0], dst[4], dst[8], dst[12], t0, t1, t2, t3, t4); diff --git a/libavcodec/j2kenc.c b/libavcodec/j2kenc.c index 2cd837d8be..baaf47422c 100644 --- a/libavcodec/j2kenc.c +++ b/libavcodec/j2kenc.c @@ -17,8 +17,46 @@ * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * ********************************************************************************************************************** + * + * + * + * This source code incorporates work covered by the following copyright and + * permission notice: + * + * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium + * Copyright (c) 2002-2007, Professor Benoit Macq + * Copyright (c) 2001-2003, David Janssens + * Copyright (c) 2002-2003, Yannick Verschueren + * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe + * Copyright (c) 2005, Herve Drolon, FreeImage Team + * Copyright (c) 2007, Callum Lerwick + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ + /** * JPEG2000 image encoder * @file @@ -650,7 +688,8 @@ static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg20 cblk->npasses = passno; cblk->ninclpasses = passno; - cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len); + if (passno) + cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len); } /* tier-2 routines: */ diff --git a/libavcodec/jpeg2000.c b/libavcodec/jpeg2000.c index b5b2dbf220..1d6ae373fc 100644 --- a/libavcodec/jpeg2000.c +++ b/libavcodec/jpeg2000.c @@ -506,6 +506,9 @@ int ff_jpeg2000_init_component(Jpeg2000Component *comp, // update precincts size: 2^n value reslevel->log2_prec_width = codsty->log2_prec_widths[reslevelno]; reslevel->log2_prec_height = codsty->log2_prec_heights[reslevelno]; + if (!reslevel->log2_prec_width || !reslevel->log2_prec_height) { + return AVERROR_INVALIDDATA; + } /* Number of bands for each resolution level */ if (reslevelno == 0) diff --git a/libavcodec/jpeg2000.h b/libavcodec/jpeg2000.h index ed3b421ad8..8a022ad918 100644 --- a/libavcodec/jpeg2000.h +++ b/libavcodec/jpeg2000.h @@ -215,12 +215,12 @@ typedef struct Jpeg2000Component { /* misc tools */ static inline int ff_jpeg2000_ceildivpow2(int a, int b) { - return -(((int64_t)(-a)) >> b); + return -((-(int64_t)a) >> b); } static inline int ff_jpeg2000_ceildiv(int a, int b) { - return (a + b - 1) / b; + return (a + (int64_t)b - 1) / b; } /* TIER-1 routines */ diff --git a/libavcodec/jpeg2000dec.c b/libavcodec/jpeg2000dec.c index c13670e6d6..64355589ee 100644 --- a/libavcodec/jpeg2000dec.c +++ b/libavcodec/jpeg2000dec.c @@ -260,6 +260,7 @@ static int get_siz(Jpeg2000DecoderContext *s) uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; + int ret; if (bytestream2_get_bytes_left(&s->g) < 36) { av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for SIZ\n"); @@ -298,6 +299,16 @@ static int get_siz(Jpeg2000DecoderContext *s) return AVERROR_PATCHWELCOME; } + if (s->tile_offset_x < 0 || s->tile_offset_y < 0 || + s->image_offset_x < s->tile_offset_x || + s->image_offset_y < s->tile_offset_y || + s->tile_width + (int64_t)s->tile_offset_x <= s->image_offset_x || + s->tile_height + (int64_t)s->tile_offset_y <= s->image_offset_y + ) { + av_log(s->avctx, AV_LOG_ERROR, "Tile offsets are invalid\n"); + return AVERROR_INVALIDDATA; + } + s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { @@ -329,7 +340,10 @@ static int get_siz(Jpeg2000DecoderContext *s) s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); - if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { + // There must be at least a SOT and SOD per tile, their minimum size is 14 + if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile) || + s->numXtiles * s->numYtiles * 14LL > bytestream2_size(&s->g) + ) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } @@ -349,10 +363,13 @@ static int get_siz(Jpeg2000DecoderContext *s) } /* compute image size with reduction factor */ - s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, - s->reduction_factor); - s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, - s->reduction_factor); + ret = ff_set_dimensions(s->avctx, + ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, + s->reduction_factor), + ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, + s->reduction_factor)); + if (ret < 0) + return ret; if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { @@ -946,9 +963,9 @@ static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, if (!cblk->npasses) { int v = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + cblkno, 100); - if (v < 0) { + if (v < 0 || v > 30) { av_log(s->avctx, AV_LOG_ERROR, - "nonzerobits %d invalid\n", v); + "nonzerobits %d invalid or unsupported\n", v); return AVERROR_INVALIDDATA; } cblk->nonzerobits = v; @@ -1111,6 +1128,9 @@ static int jpeg2000_decode_packets_po_iteration(Jpeg2000DecoderContext *s, Jpeg2 step_x = 32; step_y = 32; + if (RSpoc >= FFMIN(codsty->nreslevels, REpoc)) + continue; + for (reslevelno = RSpoc; reslevelno < FFMIN(codsty->nreslevels, REpoc); reslevelno++) { uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; @@ -1130,10 +1150,10 @@ static int jpeg2000_decode_packets_po_iteration(Jpeg2000DecoderContext *s, Jpeg2 int xc = x / s->cdx[compno]; int yc = y / s->cdy[compno]; - if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check + if (yc % (1LL << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check continue; - if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check + if (xc % (1LL << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check continue; // check if a precinct exists @@ -1200,10 +1220,10 @@ static int jpeg2000_decode_packets_po_iteration(Jpeg2000DecoderContext *s, Jpeg2 if (reslevelno >= codsty->nreslevels) continue; - if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check + if (yc % (1LL << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check continue; - if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check + if (xc % (1LL << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check continue; // check if a precinct exists @@ -1271,10 +1291,10 @@ static int jpeg2000_decode_packets_po_iteration(Jpeg2000DecoderContext *s, Jpeg2 uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; - if (yc % (1 << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check + if (yc % (1LL << (rlevel->log2_prec_height + reducedresno)) && y != tile->coord[1][0]) //FIXME this is a subset of the check continue; - if (xc % (1 << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check + if (xc % (1LL << (rlevel->log2_prec_width + reducedresno)) && x != tile->coord[0][0]) //FIXME this is a subset of the check continue; // check if a precinct exists diff --git a/libavcodec/jpeg2000dsp.c b/libavcodec/jpeg2000dsp.c index d183cbb87d..90e73b1e20 100644 --- a/libavcodec/jpeg2000dsp.c +++ b/libavcodec/jpeg2000dsp.c @@ -64,10 +64,10 @@ static void ict_int(void *_src0, void *_src1, void *_src2, int csize) int i; for (i = 0; i < csize; i++) { - i0 = *src0 + (((i_ict_params[0] * *src2) + (1 << 15)) >> 16); - i1 = *src0 - (((i_ict_params[1] * *src1) + (1 << 15)) >> 16) - - (((i_ict_params[2] * *src2) + (1 << 15)) >> 16); - i2 = *src0 + (((i_ict_params[3] * *src1) + (1 << 15)) >> 16); + i0 = *src0 + *src2 + ((int)((26345U * *src2) + (1 << 15)) >> 16); + i1 = *src0 - ((int)(((unsigned)i_ict_params[1] * *src1) + (1 << 15)) >> 16) + - ((int)(((unsigned)i_ict_params[2] * *src2) + (1 << 15)) >> 16); + i2 = *src0 + (2 * *src1) + ((int)((-14942U * *src1) + (1 << 15)) >> 16); *src0++ = i0; *src1++ = i1; *src2++ = i2; diff --git a/libavcodec/jpeg2000dwt.c b/libavcodec/jpeg2000dwt.c index a46c93a9b2..5a72335d91 100644 --- a/libavcodec/jpeg2000dwt.c +++ b/libavcodec/jpeg2000dwt.c @@ -305,22 +305,22 @@ static void dwt_encode97_int(DWTContext *s, int *t) t[i] = (t[i] + ((1<>1)) >> I_PRESHIFT; } -static void sr_1d53(int *p, int i0, int i1) +static void sr_1d53(unsigned *p, int i0, int i1) { int i; if (i1 <= i0 + 1) { if (i0 == 1) - p[1] >>= 1; + p[1] = (int)p[1] >> 1; return; } extend53(p, i0, i1); for (i = (i0 >> 1); i < (i1 >> 1) + 1; i++) - p[2 * i] -= (p[2 * i - 1] + p[2 * i + 1] + 2) >> 2; + p[2 * i] -= (int)(p[2 * i - 1] + p[2 * i + 1] + 2) >> 2; for (i = (i0 >> 1); i < (i1 >> 1); i++) - p[2 * i + 1] += (p[2 * i] + p[2 * i + 2]) >> 1; + p[2 * i + 1] += (int)(p[2 * i] + p[2 * i + 2]) >> 1; } static void dwt_decode53(DWTContext *s, int *t) @@ -488,7 +488,7 @@ static void dwt_decode97_int(DWTContext *s, int32_t *t) line += 5; for (i = 0; i < w * h; i++) - data[i] <<= I_PRESHIFT; + data[i] *= 1LL << I_PRESHIFT; for (lev = 0; lev < s->ndeclevels; lev++) { int lh = s->linelen[lev][0], diff --git a/libavcodec/jpeglsdec.c b/libavcodec/jpeglsdec.c index 68151cbbd8..5e0a3d2978 100644 --- a/libavcodec/jpeglsdec.c +++ b/libavcodec/jpeglsdec.c @@ -233,6 +233,9 @@ static inline void ls_decode_line(JLSState *state, MJpegDecodeContext *s, while (x < w) { int err, pred; + if (get_bits_left(&s->gb) <= 0) + return; + /* compute gradients */ Ra = x ? R(dst, x - stride) : R(last, x); Rb = R(last, x); @@ -385,6 +388,10 @@ int ff_jpegls_decode_picture(MJpegDecodeContext *s, int near, av_log(s->avctx, AV_LOG_DEBUG, "JPEG params: ILV=%i Pt=%i BPP=%i, scan = %i\n", ilv, point_transform, s->bits, s->cur_scan); } + if (get_bits_left(&s->gb) < s->height) { + ret = AVERROR_INVALIDDATA; + goto end; + } if (ilv == 0) { /* separate planes */ if (s->cur_scan > s->nb_components) { ret = AVERROR_INVALIDDATA; @@ -434,6 +441,10 @@ int ff_jpegls_decode_picture(MJpegDecodeContext *s, int near, avpriv_report_missing_feature(s->avctx, "Sample interleaved images"); ret = AVERROR_PATCHWELCOME; goto end; + } else { /* unknown interleaving */ + avpriv_report_missing_feature(s->avctx, "Unknown interleaved images"); + ret = AVERROR_PATCHWELCOME; + goto end; } if (s->xfrm && s->nb_components == 3) { diff --git a/libavcodec/kgv1dec.c b/libavcodec/kgv1dec.c index 5359411c76..a6bd9400ac 100644 --- a/libavcodec/kgv1dec.c +++ b/libavcodec/kgv1dec.c @@ -62,6 +62,9 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, h = (buf[1] + 1) * 8; buf += 2; + if (avpkt->size < 2 + w*h / 513) + return AVERROR_INVALIDDATA; + if (w != avctx->width || h != avctx->height) { av_freep(&c->frame_buffer); av_freep(&c->last_frame_buffer); diff --git a/libavcodec/kmvc.c b/libavcodec/kmvc.c index 7acaba7d21..ffe6a142e9 100644 --- a/libavcodec/kmvc.c +++ b/libavcodec/kmvc.c @@ -268,7 +268,8 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame, int i, ret; int header; int blocksize; - const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL); + int pal_size; + const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, &pal_size); bytestream2_init(&ctx->g, avpkt->data, avpkt->size); @@ -303,9 +304,11 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame, } } - if (pal) { + if (pal && pal_size == AVPALETTE_SIZE) { frame->palette_has_changed = 1; memcpy(ctx->pal, pal, AVPALETTE_SIZE); + } else if (pal) { + av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", pal_size); } if (ctx->setpal) { diff --git a/libavcodec/lagarith.c b/libavcodec/lagarith.c index 94d723d319..ea069b3d04 100644 --- a/libavcodec/lagarith.c +++ b/libavcodec/lagarith.c @@ -98,7 +98,7 @@ static uint32_t softfloat_mul(uint32_t x, uint64_t mantissa) static uint8_t lag_calc_zero_run(int8_t x) { - return (x << 1) ^ (x >> 7); + return (x * 2) ^ (x >> 7); } static int lag_decode_prob(GetBitContext *gb, uint32_t *value) @@ -191,7 +191,9 @@ static int lag_read_prob_header(lag_rac *rac, GetBitContext *gb) } scale_factor++; - cumulative_target = 1 << scale_factor; + if (scale_factor >= 32U) + return AVERROR_INVALIDDATA; + cumulative_target = 1U << scale_factor; if (scaled_cumul_prob > cumulative_target) { av_log(rac->avctx, AV_LOG_ERROR, diff --git a/libavcodec/libfdk-aacdec.c b/libavcodec/libfdk-aacdec.c index e5f7c4ebdc..2857b9453f 100644 --- a/libavcodec/libfdk-aacdec.c +++ b/libavcodec/libfdk-aacdec.c @@ -325,7 +325,7 @@ static int fdk_aac_decode_frame(AVCodecContext *avctx, void *data, return AVERROR_INVALIDDATA; } - err = aacDecoder_DecodeFrame(s->handle, (INT_PCM *) s->decoder_buffer, s->decoder_buffer_size, 0); + err = aacDecoder_DecodeFrame(s->handle, (INT_PCM *) s->decoder_buffer, s->decoder_buffer_size / sizeof(INT_PCM), 0); if (err == AAC_DEC_NOT_ENOUGH_BITS) { ret = avpkt->size - valid; goto end; diff --git a/libavcodec/libopenjpegdec.c b/libavcodec/libopenjpegdec.c index cae3d20986..3f24a9c6cd 100644 --- a/libavcodec/libopenjpegdec.c +++ b/libavcodec/libopenjpegdec.c @@ -24,8 +24,6 @@ * JPEG 2000 decoder using libopenjpeg */ -#define OPJ_STATIC - #include "libavutil/common.h" #include "libavutil/imgutils.h" #include "libavutil/intreadwrite.h" diff --git a/libavcodec/libopenjpegenc.c b/libavcodec/libopenjpegenc.c index b67c320b2f..2ca7b2d4d2 100644 --- a/libavcodec/libopenjpegenc.c +++ b/libavcodec/libopenjpegenc.c @@ -24,8 +24,6 @@ * JPEG 2000 encoder using libopenjpeg */ -#define OPJ_STATIC - #include "libavutil/avassert.h" #include "libavutil/common.h" #include "libavutil/imgutils.h" @@ -54,7 +52,9 @@ typedef struct LibOpenJPEGContext { AVClass *avclass; +#if OPENJPEG_MAJOR_VERSION == 1 opj_image_t *image; +#endif // OPENJPEG_MAJOR_VERSION == 1 opj_cparameters_t enc_params; #if OPENJPEG_MAJOR_VERSION == 1 opj_event_mgr_t event_mgr; @@ -352,6 +352,12 @@ static av_cold int libopenjpeg_encode_init(AVCodecContext *avctx) ctx->enc_params.cp_cinema = ctx->cinema_mode; #endif + if (!ctx->numresolution) { + ctx->numresolution = 6; + while (FFMIN(avctx->width, avctx->height) >> ctx->numresolution < 1) + ctx->numresolution --; + } + ctx->enc_params.mode = !!avctx->global_quality; ctx->enc_params.prog_order = ctx->prog_order; ctx->enc_params.numresolution = ctx->numresolution; @@ -365,18 +371,22 @@ static av_cold int libopenjpeg_encode_init(AVCodecContext *avctx) cinema_parameters(&ctx->enc_params); } +#if OPENJPEG_MAJOR_VERSION == 1 ctx->image = mj2_create_image(avctx, &ctx->enc_params); if (!ctx->image) { av_log(avctx, AV_LOG_ERROR, "Error creating the mj2 image\n"); err = AVERROR(EINVAL); goto fail; } +#endif // OPENJPEG_MAJOR_VERSION == 1 return 0; fail: +#if OPENJPEG_MAJOR_VERSION == 1 opj_image_destroy(ctx->image); ctx->image = NULL; +#endif // OPENJPEG_MAJOR_VERSION == 1 return err; } @@ -411,7 +421,7 @@ static int libopenjpeg_copy_packed8(AVCodecContext *avctx, const AVFrame *frame, for (; y < image->comps[compno].h; ++y) { image_line = image->comps[compno].data + y * image->comps[compno].w; for (x = 0; x < image->comps[compno].w; ++x) { - image_line[x] = image_line[x - image->comps[compno].w]; + image_line[x] = image_line[x - (int)image->comps[compno].w]; } } } @@ -451,7 +461,7 @@ static int libopenjpeg_copy_packed12(AVCodecContext *avctx, const AVFrame *frame for (; y < image->comps[compno].h; ++y) { image_line = image->comps[compno].data + y * image->comps[compno].w; for (x = 0; x < image->comps[compno].w; ++x) { - image_line[x] = image_line[x - image->comps[compno].w]; + image_line[x] = image_line[x - (int)image->comps[compno].w]; } } } @@ -491,7 +501,7 @@ static int libopenjpeg_copy_packed16(AVCodecContext *avctx, const AVFrame *frame for (; y < image->comps[compno].h; ++y) { image_line = image->comps[compno].data + y * image->comps[compno].w; for (x = 0; x < image->comps[compno].w; ++x) { - image_line[x] = image_line[x - image->comps[compno].w]; + image_line[x] = image_line[x - (int)image->comps[compno].w]; } } } @@ -518,8 +528,8 @@ static int libopenjpeg_copy_unpacked8(AVCodecContext *avctx, const AVFrame *fram } for (compno = 0; compno < numcomps; ++compno) { - width = avctx->width / image->comps[compno].dx; - height = avctx->height / image->comps[compno].dy; + width = (avctx->width + image->comps[compno].dx - 1) / image->comps[compno].dx; + height = (avctx->height + image->comps[compno].dy - 1) / image->comps[compno].dy; for (y = 0; y < height; ++y) { image_line = image->comps[compno].data + y * image->comps[compno].w; frame_index = y * frame->linesize[compno]; @@ -532,7 +542,7 @@ static int libopenjpeg_copy_unpacked8(AVCodecContext *avctx, const AVFrame *fram for (; y < image->comps[compno].h; ++y) { image_line = image->comps[compno].data + y * image->comps[compno].w; for (x = 0; x < image->comps[compno].w; ++x) { - image_line[x] = image_line[x - image->comps[compno].w]; + image_line[x] = image_line[x - (int)image->comps[compno].w]; } } } @@ -560,8 +570,8 @@ static int libopenjpeg_copy_unpacked16(AVCodecContext *avctx, const AVFrame *fra } for (compno = 0; compno < numcomps; ++compno) { - width = avctx->width / image->comps[compno].dx; - height = avctx->height / image->comps[compno].dy; + width = (avctx->width + image->comps[compno].dx - 1) / image->comps[compno].dx; + height = (avctx->height + image->comps[compno].dy - 1) / image->comps[compno].dy; frame_ptr = (uint16_t *)frame->data[compno]; for (y = 0; y < height; ++y) { image_line = image->comps[compno].data + y * image->comps[compno].w; @@ -575,7 +585,7 @@ static int libopenjpeg_copy_unpacked16(AVCodecContext *avctx, const AVFrame *fra for (; y < image->comps[compno].h; ++y) { image_line = image->comps[compno].data + y * image->comps[compno].w; for (x = 0; x < image->comps[compno].w; ++x) { - image_line[x] = image_line[x - image->comps[compno].w]; + image_line[x] = image_line[x - (int)image->comps[compno].w]; } } } @@ -587,18 +597,24 @@ static int libopenjpeg_encode_frame(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *frame, int *got_packet) { LibOpenJPEGContext *ctx = avctx->priv_data; - opj_image_t *image = ctx->image; + int ret; + AVFrame *gbrframe; + int cpyresult = 0; #if OPENJPEG_MAJOR_VERSION == 1 + opj_image_t *image = ctx->image; opj_cinfo_t *compress = NULL; opj_cio_t *stream = NULL; int len; #else // OPENJPEG_MAJOR_VERSION == 2 opj_codec_t *compress = NULL; opj_stream_t *stream = NULL; + opj_image_t *image = mj2_create_image(avctx, &ctx->enc_params); + if (!image) { + av_log(avctx, AV_LOG_ERROR, "Error creating the mj2 image\n"); + ret = AVERROR(EINVAL); + goto done; + } #endif // OPENJPEG_MAJOR_VERSION == 1 - int cpyresult = 0; - int ret; - AVFrame *gbrframe; switch (avctx->pix_fmt) { case AV_PIX_FMT_RGB24: @@ -621,8 +637,10 @@ static int libopenjpeg_encode_frame(AVCodecContext *avctx, AVPacket *pkt, case AV_PIX_FMT_GBRP14: case AV_PIX_FMT_GBRP16: gbrframe = av_frame_clone(frame); - if (!gbrframe) - return AVERROR(ENOMEM); + if (!gbrframe) { + ret = AVERROR(ENOMEM); + goto done; + } gbrframe->data[0] = frame->data[2]; // swap to be rgb gbrframe->data[1] = frame->data[0]; gbrframe->data[2] = frame->data[1]; @@ -679,19 +697,21 @@ static int libopenjpeg_encode_frame(AVCodecContext *avctx, AVPacket *pkt, av_log(avctx, AV_LOG_ERROR, "The frame's pixel format '%s' is not supported\n", av_get_pix_fmt_name(avctx->pix_fmt)); - return AVERROR(EINVAL); + ret = AVERROR(EINVAL); + goto done; break; } if (!cpyresult) { av_log(avctx, AV_LOG_ERROR, "Could not copy the frame data to the internal image buffer\n"); - return -1; + ret = -1; + goto done; } #if OPENJPEG_MAJOR_VERSION == 2 if ((ret = ff_alloc_packet2(avctx, pkt, 1024, 0)) < 0) { - return ret; + goto done; } #endif // OPENJPEG_MAJOR_VERSION == 2 @@ -758,7 +778,7 @@ static int libopenjpeg_encode_frame(AVCodecContext *avctx, AVPacket *pkt, #error Missing call to opj_stream_set_user_data #endif - if (!opj_start_compress(compress, ctx->image, stream) || + if (!opj_start_compress(compress, image, stream) || !opj_encode(compress, stream) || !opj_end_compress(compress, stream)) { av_log(avctx, AV_LOG_ERROR, "Error during the opj encode\n"); @@ -777,6 +797,7 @@ done: #if OPENJPEG_MAJOR_VERSION == 2 opj_stream_destroy(stream); opj_destroy_codec(compress); + opj_image_destroy(image); #else opj_cio_close(stream); opj_destroy_compress(compress); @@ -786,10 +807,12 @@ done: static av_cold int libopenjpeg_encode_close(AVCodecContext *avctx) { +#if OPENJPEG_MAJOR_VERSION == 1 LibOpenJPEGContext *ctx = avctx->priv_data; opj_image_destroy(ctx->image); ctx->image = NULL; +#endif // OPENJPEG_MAJOR_VERSION == 1 return 0; } @@ -814,7 +837,7 @@ static const AVOption options[] = { { "rpcl", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = OPJ(RPCL) }, 0, 0, VE, "prog_order" }, { "pcrl", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = OPJ(PCRL) }, 0, 0, VE, "prog_order" }, { "cprl", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = OPJ(CPRL) }, 0, 0, VE, "prog_order" }, - { "numresolution", NULL, OFFSET(numresolution), AV_OPT_TYPE_INT, { .i64 = 6 }, 1, INT_MAX, VE }, + { "numresolution", NULL, OFFSET(numresolution), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE }, { "numlayers", NULL, OFFSET(numlayers), AV_OPT_TYPE_INT, { .i64 = 1 }, 1, 10, VE }, { "disto_alloc", NULL, OFFSET(disto_alloc), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, VE }, { "fixed_alloc", NULL, OFFSET(fixed_alloc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE }, diff --git a/libavcodec/libopusdec.c b/libavcodec/libopusdec.c index 1e97604181..f9480fbbb6 100644 --- a/libavcodec/libopusdec.c +++ b/libavcodec/libopusdec.c @@ -47,6 +47,13 @@ static av_cold int libopus_decode_init(AVCodecContext *avc) int ret, channel_map = 0, gain_db = 0, nb_streams, nb_coupled; uint8_t mapping_arr[8] = { 0, 1 }, *mapping; + avc->channels = avc->extradata_size >= 10 ? avc->extradata[9] : (avc->channels == 1) ? 1 : 2; + if (avc->channels <= 0) { + av_log(avc, AV_LOG_WARNING, + "Invalid number of channels %d, defaulting to stereo\n", avc->channels); + avc->channels = 2; + } + avc->sample_rate = 48000; avc->sample_fmt = avc->request_sample_fmt == AV_SAMPLE_FMT_FLT ? AV_SAMPLE_FMT_FLT : AV_SAMPLE_FMT_S16; @@ -119,7 +126,10 @@ static av_cold int libopus_decode_close(AVCodecContext *avc) { struct libopus_context *opus = avc->priv_data; - opus_multistream_decoder_destroy(opus->dec); + if (opus->dec) { + opus_multistream_decoder_destroy(opus->dec); + opus->dec = NULL; + } return 0; } @@ -193,6 +203,7 @@ AVCodec ff_libopus_decoder = { .decode = libopus_decode, .flush = libopus_flush, .capabilities = AV_CODEC_CAP_DR1, + .caps_internal = FF_CODEC_CAP_INIT_CLEANUP, .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE }, diff --git a/libavcodec/libopusenc.c b/libavcodec/libopusenc.c index 3f3e80d4a0..c1dcd0456a 100644 --- a/libavcodec/libopusenc.c +++ b/libavcodec/libopusenc.c @@ -362,7 +362,6 @@ static int libopus_encode(AVCodecContext *avctx, AVPacket *avpkt, // Check if subtraction resulted in an overflow if ((discard_padding < opus->opts.packet_size) != (avpkt->duration > 0)) { av_packet_unref(avpkt); - av_free(avpkt); return AVERROR(EINVAL); } if (discard_padding > 0) { @@ -371,7 +370,6 @@ static int libopus_encode(AVCodecContext *avctx, AVPacket *avpkt, 10); if(!side_data) { av_packet_unref(avpkt); - av_free(avpkt); return AVERROR(ENOMEM); } AV_WL32(side_data + 4, discard_padding); diff --git a/libavcodec/libschroedingerdec.c b/libavcodec/libschroedingerdec.c index 152cbe7d47..471077b2fe 100644 --- a/libavcodec/libschroedingerdec.c +++ b/libavcodec/libschroedingerdec.c @@ -218,6 +218,7 @@ static int libschroedinger_decode_frame(AVCodecContext *avctx, int outer = 1; SchroParseUnitContext parse_ctx; LibSchroFrameContext *framewithpts = NULL; + int ret; *got_frame = 0; @@ -307,11 +308,10 @@ static int libschroedinger_decode_frame(AVCodecContext *avctx, /* Grab next frame to be returned from the top of the queue. */ framewithpts = ff_schro_queue_pop(&p_schro_params->dec_frame_queue); - if (framewithpts && framewithpts->frame) { - int ret; + if (framewithpts && framewithpts->frame && framewithpts->frame->components[0].stride) { if ((ret = ff_get_buffer(avctx, avframe, 0)) < 0) - return ret; + goto end; memcpy(avframe->data[0], framewithpts->frame->components[0].data, @@ -332,15 +332,17 @@ static int libschroedinger_decode_frame(AVCodecContext *avctx, avframe->linesize[2] = framewithpts->frame->components[2].stride; *got_frame = 1; - - /* Now free the frame resources. */ - libschroedinger_decode_frame_free(framewithpts->frame); - av_free(framewithpts); } else { data = NULL; *got_frame = 0; } - return buf_size; + ret = buf_size; +end: + /* Now free the frame resources. */ + if (framewithpts && framewithpts->frame) + libschroedinger_decode_frame_free(framewithpts->frame); + av_freep(&framewithpts); + return ret; } diff --git a/libavcodec/libutvideodec.cpp b/libavcodec/libutvideodec.cpp index 7c60f4fb83..a456735d3c 100644 --- a/libavcodec/libutvideodec.cpp +++ b/libavcodec/libutvideodec.cpp @@ -222,9 +222,19 @@ static int utvideo_decode_frame(AVCodecContext *avctx, void *data, pic->data[0] = utv->buffer + utv->buf_size + pic->linesize[0]; break; } + pic->width = w; + pic->height = h; + pic->format = avctx->pix_fmt; + + if (avctx->refcounted_frames) { + int ret = av_frame_ref((AVFrame*)data, pic); + if (ret < 0) + return ret; + } else { + av_frame_move_ref((AVFrame*)data, pic); + } *got_frame = 1; - av_frame_move_ref((AVFrame*)data, pic); return avpkt->size; } diff --git a/libavcodec/libvpxenc.c b/libavcodec/libvpxenc.c index 8992497c70..31695d1276 100644 --- a/libavcodec/libvpxenc.c +++ b/libavcodec/libvpxenc.c @@ -792,7 +792,6 @@ FF_ENABLE_DEPRECATION_WARNINGS cx_frame->sz_alpha + 8); if(!side_data) { av_packet_unref(pkt); - av_free(pkt); return AVERROR(ENOMEM); } AV_WB64(side_data, 1); diff --git a/libavcodec/libwebpenc_animencoder.c b/libavcodec/libwebpenc_animencoder.c index d7437a9a57..91bf64ca8b 100644 --- a/libavcodec/libwebpenc_animencoder.c +++ b/libavcodec/libwebpenc_animencoder.c @@ -41,8 +41,9 @@ static av_cold int libwebp_anim_encode_init(AVCodecContext *avctx) int ret = ff_libwebp_encode_init_common(avctx); if (!ret) { LibWebPAnimContext *s = avctx->priv_data; - WebPAnimEncoderOptions enc_options; + WebPAnimEncoderOptions enc_options = { { 0 } }; WebPAnimEncoderOptionsInit(&enc_options); + enc_options.verbose = av_log_get_level() >= AV_LOG_VERBOSE; // TODO(urvang): Expose some options on command-line perhaps. s->enc = WebPAnimEncoderNew(avctx->width, avctx->height, &enc_options); if (!s->enc) diff --git a/libavcodec/libx264.c b/libavcodec/libx264.c index 5030d65f79..35339bc150 100644 --- a/libavcodec/libx264.c +++ b/libavcodec/libx264.c @@ -783,8 +783,8 @@ FF_ENABLE_DEPRECATION_WARNINGS if(x4->x264opts){ const char *p= x4->x264opts; while(p){ - char param[256]={0}, val[256]={0}; - if(sscanf(p, "%255[^:=]=%255[^:]", param, val) == 1){ + char param[4096]={0}, val[4096]={0}; + if(sscanf(p, "%4095[^:=]=%4095[^:]", param, val) == 1){ OPT_STR(param, "1"); }else OPT_STR(param, val); diff --git a/libavcodec/lpc.h b/libavcodec/lpc.h index edb1a6bc7d..704ffa9d4b 100644 --- a/libavcodec/lpc.h +++ b/libavcodec/lpc.h @@ -117,11 +117,14 @@ void ff_lpc_end(LPCContext *s); #if USE_FIXED typedef int LPC_TYPE; +typedef unsigned LPC_TYPE_U; #else #ifdef LPC_USE_DOUBLE typedef double LPC_TYPE; +typedef double LPC_TYPE_U; #else typedef float LPC_TYPE; +typedef float LPC_TYPE_U; #endif #endif // USE_FIXED @@ -192,8 +195,8 @@ static inline int AAC_RENAME(compute_lpc_coefs)(const LPC_TYPE *autoc, int max_o for(j=0; j < (i+1)>>1; j++) { LPC_TYPE f = lpc_last[ j]; LPC_TYPE b = lpc_last[i-1-j]; - lpc[ j] = f + AAC_MUL26(r, b); - lpc[i-1-j] = b + AAC_MUL26(r, f); + lpc[ j] = f + (LPC_TYPE_U)AAC_MUL26(r, b); + lpc[i-1-j] = b + (LPC_TYPE_U)AAC_MUL26(r, f); } if (fail && err < 0) diff --git a/libavcodec/lzf.c b/libavcodec/lzf.c index 409a7ffdd3..5b7526ef18 100644 --- a/libavcodec/lzf.c +++ b/libavcodec/lzf.c @@ -53,6 +53,7 @@ int ff_lzf_uncompress(GetByteContext *gb, uint8_t **buf, int64_t *size) ret = av_reallocp(buf, *size); if (ret < 0) return ret; + p = *buf + len; } bytestream2_get_buffer(gb, p, s); @@ -75,6 +76,7 @@ int ff_lzf_uncompress(GetByteContext *gb, uint8_t **buf, int64_t *size) ret = av_reallocp(buf, *size); if (ret < 0) return ret; + p = *buf + len; } av_memcpy_backptr(p, off, l); diff --git a/libavcodec/mdct_fixed.c b/libavcodec/mdct_fixed.c index a32cb00ca0..aabf0c88f8 100644 --- a/libavcodec/mdct_fixed.c +++ b/libavcodec/mdct_fixed.c @@ -39,13 +39,13 @@ void ff_mdct_calcw_c(FFTContext *s, FFTDouble *out, const FFTSample *input) /* pre rotation */ for(i=0;i> 6) +# define RSCALE(x, y) ((int)((x) + (unsigned)(y) + 32) >> 6) #else /* FFT_FIXED_32 */ -# define RSCALE(x) ((x) >> 1) +# define RSCALE(x, y) ((int)((x) + (unsigned)(y)) >> 1) #endif /* FFT_FIXED_32 */ #endif @@ -181,13 +181,13 @@ void ff_mdct_calc_c(FFTContext *s, FFTSample *out, const FFTSample *input) /* pre rotation */ for(i=0;i= 0xffff) return AVERROR_INVALIDDATA; a->last_dc[component] += diff; - block[0] = a->last_dc[component] << 3; + block[0] = a->last_dc[component] * (1 << 3); } i = 0; @@ -111,11 +111,11 @@ static inline int mdec_decode_block_intra(MDECContext *a, int16_t *block, int n) j = scantable[i]; if (level < 0) { level = -level; - level = (level * qscale * quant_matrix[j]) >> 3; + level = (level * (unsigned)qscale * quant_matrix[j]) >> 3; level = (level - 1) | 1; level = -level; } else { - level = (level * qscale * quant_matrix[j]) >> 3; + level = (level * (unsigned)qscale * quant_matrix[j]) >> 3; level = (level - 1) | 1; } } diff --git a/libavcodec/me_cmp.c b/libavcodec/me_cmp.c index dc76b07ba2..4234000487 100644 --- a/libavcodec/me_cmp.c +++ b/libavcodec/me_cmp.c @@ -555,7 +555,7 @@ static int dct_sad8x8_c(MpegEncContext *s, uint8_t *src1, av_assert2(h == 8); - s->pdsp.diff_pixels(temp, src1, src2, stride); + s->pdsp.diff_pixels_unaligned(temp, src1, src2, stride); s->fdsp.fdct(temp); return s->mecc.sum_abs_dctelem(temp); } @@ -595,7 +595,7 @@ static int dct264_sad8x8_c(MpegEncContext *s, uint8_t *src1, int16_t dct[8][8]; int i, sum = 0; - s->pdsp.diff_pixels(dct[0], src1, src2, stride); + s->pdsp.diff_pixels_unaligned(dct[0], src1, src2, stride); #define SRC(x) dct[i][x] #define DST(x, v) dct[i][x] = v @@ -622,7 +622,7 @@ static int dct_max8x8_c(MpegEncContext *s, uint8_t *src1, av_assert2(h == 8); - s->pdsp.diff_pixels(temp, src1, src2, stride); + s->pdsp.diff_pixels_unaligned(temp, src1, src2, stride); s->fdsp.fdct(temp); for (i = 0; i < 64; i++) @@ -641,7 +641,7 @@ static int quant_psnr8x8_c(MpegEncContext *s, uint8_t *src1, av_assert2(h == 8); s->mb_intra = 0; - s->pdsp.diff_pixels(temp, src1, src2, stride); + s->pdsp.diff_pixels_unaligned(temp, src1, src2, stride); memcpy(bak, temp, 64 * sizeof(int16_t)); @@ -744,7 +744,7 @@ static int bit8x8_c(MpegEncContext *s, uint8_t *src1, uint8_t *src2, av_assert2(h == 8); - s->pdsp.diff_pixels(temp, src1, src2, stride); + s->pdsp.diff_pixels_unaligned(temp, src1, src2, stride); s->block_last_index[0 /* FIXME */] = last = diff --git a/libavcodec/mimic.c b/libavcodec/mimic.c index 06fb393b92..b77171a822 100644 --- a/libavcodec/mimic.c +++ b/libavcodec/mimic.c @@ -262,7 +262,7 @@ static int vlc_decode_block(MimicContext *ctx, int num_coeffs, int qscale) coeff = vlcdec_lookup[num_bits][value]; if (pos < 3) - coeff <<= 4; + coeff *= 16; else /* TODO Use >> 10 instead of / 1001 */ coeff = (coeff * qscale) / 1001; @@ -390,9 +390,11 @@ static int mimic_decode_frame(AVCodecContext *avctx, void *data, return AVERROR_INVALIDDATA; } + res = ff_set_dimensions(avctx, width, height); + if (res < 0) + return res; + ctx->avctx = avctx; - avctx->width = width; - avctx->height = height; avctx->pix_fmt = AV_PIX_FMT_YUV420P; for (i = 0; i < 3; i++) { ctx->num_vblocks[i] = AV_CEIL_RSHIFT(height, 3 + !!i); diff --git a/libavcodec/mips/aaccoder_mips.c b/libavcodec/mips/aaccoder_mips.c index 8fbdfd230a..d690c8c24a 100644 --- a/libavcodec/mips/aaccoder_mips.c +++ b/libavcodec/mips/aaccoder_mips.c @@ -66,6 +66,7 @@ #include "libavcodec/aacenc_utils.h" #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 typedef struct BandCodingPath { int prev_idx; float cost; @@ -2477,10 +2478,12 @@ static void search_for_ms_mips(AACEncContext *s, ChannelElement *cpe) #include "libavcodec/aaccoder_trellis.h" +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM */ void ff_aac_coder_init_mips(AACEncContext *c) { #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 AACCoefficientsEncoder *e = c->coder; int option = c->options.coder; @@ -2494,5 +2497,6 @@ void ff_aac_coder_init_mips(AACEncContext *c) { #if HAVE_MIPSFPU e->search_for_ms = search_for_ms_mips; #endif /* HAVE_MIPSFPU */ +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM */ } diff --git a/libavcodec/mips/aacdec_mips.h b/libavcodec/mips/aacdec_mips.h index c4f6438570..758266fc16 100644 --- a/libavcodec/mips/aacdec_mips.h +++ b/libavcodec/mips/aacdec_mips.h @@ -61,6 +61,7 @@ #include "libavutil/mips/asmdefs.h" #if HAVE_INLINE_ASM && HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static inline float *VMUL2_mips(float *dst, const float *v, unsigned idx, const float *scale) { @@ -246,6 +247,7 @@ static inline float *VMUL4S_mips(float *dst, const float *v, unsigned idx, #define VMUL4 VMUL4_mips #define VMUL2S VMUL2S_mips #define VMUL4S VMUL4S_mips +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM && HAVE_MIPSFPU */ #endif /* AVCODEC_MIPS_AACDEC_MIPS_H */ diff --git a/libavcodec/mips/aacpsdsp_mips.c b/libavcodec/mips/aacpsdsp_mips.c index 695f9ef3c6..83fdc2f9db 100644 --- a/libavcodec/mips/aacpsdsp_mips.c +++ b/libavcodec/mips/aacpsdsp_mips.c @@ -188,6 +188,7 @@ static void ps_hybrid_synthesis_deint_mips(float out[2][38][64], } #if HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static void ps_add_squares_mips(float *dst, const float (*src)[2], int n) { int i; @@ -442,6 +443,7 @@ static void ps_stereo_interpolate_mips(float (*l)[2], float (*r)[2], : "memory" ); } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_MIPSFPU */ #endif /* HAVE_INLINE_ASM */ @@ -451,10 +453,12 @@ void ff_psdsp_init_mips(PSDSPContext *s) s->hybrid_analysis_ileave = ps_hybrid_analysis_ileave_mips; s->hybrid_synthesis_deint = ps_hybrid_synthesis_deint_mips; #if HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 s->add_squares = ps_add_squares_mips; s->mul_pair_single = ps_mul_pair_single_mips; s->decorrelate = ps_decorrelate_mips; s->stereo_interpolate[0] = ps_stereo_interpolate_mips; +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_MIPSFPU */ #endif /* HAVE_INLINE_ASM */ } diff --git a/libavcodec/mips/aacpsy_mips.h b/libavcodec/mips/aacpsy_mips.h index 42ff442a59..a1fe5ccea9 100644 --- a/libavcodec/mips/aacpsy_mips.h +++ b/libavcodec/mips/aacpsy_mips.h @@ -59,6 +59,7 @@ #include "libavutil/mips/asmdefs.h" #if HAVE_INLINE_ASM && HAVE_MIPSFPU && ( PSY_LAME_FIR_LEN == 21 ) +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static void calc_thr_3gpp_mips(const FFPsyWindowInfo *wi, const int num_bands, AacPsyChannel *pch, const uint8_t *band_sizes, const float *coefs, const int cutoff) @@ -232,5 +233,6 @@ static void psy_hp_filter_mips(const float *firbuf, float *hpfsmpl, const float #define calc_thr_3gpp calc_thr_3gpp_mips #define psy_hp_filter psy_hp_filter_mips +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM && HAVE_MIPSFPU */ #endif /* AVCODEC_MIPS_AACPSY_MIPS_H */ diff --git a/libavcodec/mips/aacsbr_mips.c b/libavcodec/mips/aacsbr_mips.c index e478290e47..56aa4e8682 100644 --- a/libavcodec/mips/aacsbr_mips.c +++ b/libavcodec/mips/aacsbr_mips.c @@ -311,6 +311,7 @@ static int sbr_x_gen_mips(SpectralBandReplication *sbr, float X[2][38][64], } #if HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static void sbr_hf_assemble_mips(float Y1[38][64][2], const float X_high[64][40][2], SpectralBandReplication *sbr, SBRData *ch_data, @@ -603,6 +604,7 @@ static void sbr_hf_inverse_filter_mips(SBRDSPContext *dsp, } } } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_MIPSFPU */ #endif /* HAVE_INLINE_ASM */ @@ -612,8 +614,10 @@ void ff_aacsbr_func_ptr_init_mips(AACSBRContext *c) c->sbr_lf_gen = sbr_lf_gen_mips; c->sbr_x_gen = sbr_x_gen_mips; #if HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 c->sbr_hf_inverse_filter = sbr_hf_inverse_filter_mips; c->sbr_hf_assemble = sbr_hf_assemble_mips; +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_MIPSFPU */ #endif /* HAVE_INLINE_ASM */ } diff --git a/libavcodec/mips/aacsbr_mips.h b/libavcodec/mips/aacsbr_mips.h index 13e55d26ea..4461e763ed 100644 --- a/libavcodec/mips/aacsbr_mips.h +++ b/libavcodec/mips/aacsbr_mips.h @@ -150,6 +150,7 @@ static void sbr_qmf_analysis_mips(AVFloatDSPContext *fdsp, FFTContext *mdct, } #if HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static void sbr_qmf_synthesis_mips(FFTContext *mdct, SBRDSPContext *sbrdsp, AVFloatDSPContext *fdsp, float *out, float X[2][38][64], @@ -488,6 +489,7 @@ static void sbr_qmf_synthesis_mips(FFTContext *mdct, #define sbr_qmf_analysis sbr_qmf_analysis_mips #define sbr_qmf_synthesis sbr_qmf_synthesis_mips +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_MIPSFPU */ #endif /* HAVE_INLINE_ASM */ diff --git a/libavcodec/mips/ac3dsp_mips.c b/libavcodec/mips/ac3dsp_mips.c index da4919f6eb..f9aaf15639 100644 --- a/libavcodec/mips/ac3dsp_mips.c +++ b/libavcodec/mips/ac3dsp_mips.c @@ -201,6 +201,7 @@ static void ac3_update_bap_counts_mips(uint16_t mant_cnt[16], uint8_t *bap, #endif #if HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static void float_to_fixed24_mips(int32_t *dst, const float *src, unsigned int len) { const float scale = 1 << 24; @@ -395,7 +396,8 @@ static void ac3_downmix_mips(float **samples, float (*matrix)[2], :"memory" ); } -#endif +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ +#endif /* HAVE_MIPSFPU */ #endif /* HAVE_INLINE_ASM */ void ff_ac3dsp_init_mips(AC3DSPContext *c, int bit_exact) { @@ -405,9 +407,11 @@ void ff_ac3dsp_init_mips(AC3DSPContext *c, int bit_exact) { c->update_bap_counts = ac3_update_bap_counts_mips; #endif #if HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 c->float_to_fixed24 = float_to_fixed24_mips; c->downmix = ac3_downmix_mips; #endif #endif +#endif } diff --git a/libavcodec/mips/acelp_filters_mips.c b/libavcodec/mips/acelp_filters_mips.c index ba789abe3f..478db855b2 100644 --- a/libavcodec/mips/acelp_filters_mips.c +++ b/libavcodec/mips/acelp_filters_mips.c @@ -57,6 +57,7 @@ #include "libavutil/mips/asmdefs.h" #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static void ff_acelp_interpolatef_mips(float *out, const float *in, const float *filter_coeffs, int precision, int frac_pos, int filter_length, int length) @@ -206,12 +207,15 @@ static void ff_acelp_apply_order_2_transfer_function_mips(float *out, const floa "$f12", "$f13", "$f14", "$f15", "$f16", "memory" ); } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM */ void ff_acelp_filter_init_mips(ACELPFContext *c) { #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 c->acelp_interpolatef = ff_acelp_interpolatef_mips; c->acelp_apply_order_2_transfer_function = ff_acelp_apply_order_2_transfer_function_mips; #endif +#endif } diff --git a/libavcodec/mips/acelp_vectors_mips.c b/libavcodec/mips/acelp_vectors_mips.c index ad9434866e..0ab2b6a87b 100644 --- a/libavcodec/mips/acelp_vectors_mips.c +++ b/libavcodec/mips/acelp_vectors_mips.c @@ -57,6 +57,7 @@ #include "libavutil/mips/asmdefs.h" #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static void ff_weighted_vector_sumf_mips( float *out, const float *in_a, const float *in_b, float weight_coeff_a, float weight_coeff_b, int length) @@ -92,11 +93,14 @@ static void ff_weighted_vector_sumf_mips( : "$f0", "$f1", "$f2", "$f3", "$f4", "$f5", "memory" ); } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM */ void ff_acelp_vectors_init_mips(ACELPVContext *c) { #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 c->weighted_vector_sumf = ff_weighted_vector_sumf_mips; #endif +#endif } diff --git a/libavcodec/mips/amrwbdec_mips.c b/libavcodec/mips/amrwbdec_mips.c index e933b8a6c5..5dc054361b 100644 --- a/libavcodec/mips/amrwbdec_mips.c +++ b/libavcodec/mips/amrwbdec_mips.c @@ -54,6 +54,7 @@ #include "amrwbdec_mips.h" #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 void ff_hb_fir_filter_mips(float *out, const float fir_coef[HB_FIR_SIZE + 1], float mem[HB_FIR_SIZE], const float *in) { @@ -184,4 +185,5 @@ void ff_hb_fir_filter_mips(float *out, const float fir_coef[HB_FIR_SIZE + 1], } memcpy(mem, data + AMRWB_SFR_SIZE_16k, HB_FIR_SIZE * sizeof(float)); } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM */ diff --git a/libavcodec/mips/amrwbdec_mips.h b/libavcodec/mips/amrwbdec_mips.h index ec46f95224..a9f66fef94 100644 --- a/libavcodec/mips/amrwbdec_mips.h +++ b/libavcodec/mips/amrwbdec_mips.h @@ -54,9 +54,11 @@ #include "config.h" #if HAVE_MIPSFPU && HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 void ff_hb_fir_filter_mips(float *out, const float fir_coef[], float mem[], const float *in); #define hb_fir_filter ff_hb_fir_filter_mips #endif +#endif #endif /* AVCODEC_MIPS_AMRWBDEC_MIPS_H */ diff --git a/libavcodec/mips/celp_filters_mips.c b/libavcodec/mips/celp_filters_mips.c index 88ac45841d..926f1cb334 100644 --- a/libavcodec/mips/celp_filters_mips.c +++ b/libavcodec/mips/celp_filters_mips.c @@ -58,6 +58,7 @@ #include "libavutil/mips/asmdefs.h" #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static void ff_celp_lp_synthesis_filterf_mips(float *out, const float *filter_coeffs, const float* in, int buffer_length, @@ -278,12 +279,15 @@ static void ff_celp_lp_zero_synthesis_filterf_mips(float *out, out[n] = sum_out1; } } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM */ void ff_celp_filter_init_mips(CELPFContext *c) { #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 c->celp_lp_synthesis_filterf = ff_celp_lp_synthesis_filterf_mips; c->celp_lp_zero_synthesis_filterf = ff_celp_lp_zero_synthesis_filterf_mips; #endif +#endif } diff --git a/libavcodec/mips/celp_math_mips.c b/libavcodec/mips/celp_math_mips.c index 008dd80308..ce711bd63c 100644 --- a/libavcodec/mips/celp_math_mips.c +++ b/libavcodec/mips/celp_math_mips.c @@ -56,6 +56,7 @@ #include "libavutil/mips/asmdefs.h" #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static float ff_dot_productf_mips(const float* a, const float* b, int length) { @@ -80,11 +81,14 @@ static float ff_dot_productf_mips(const float* a, const float* b, ); return sum; } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM */ void ff_celp_math_init_mips(CELPMContext *c) { #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 c->dot_productf = ff_dot_productf_mips; #endif +#endif } diff --git a/libavcodec/mips/compute_antialias_float.h b/libavcodec/mips/compute_antialias_float.h index f6cf46508b..e2b4f29f4a 100644 --- a/libavcodec/mips/compute_antialias_float.h +++ b/libavcodec/mips/compute_antialias_float.h @@ -58,6 +58,7 @@ #include "libavutil/mips/asmdefs.h" #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static void compute_antialias_mips_float(MPADecodeContext *s, GranuleDef *g) { @@ -179,6 +180,7 @@ static void compute_antialias_mips_float(MPADecodeContext *s, ); } #define compute_antialias compute_antialias_mips_float +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM */ #endif /* AVCODEC_MIPS_COMPUTE_ANTIALIAS_FLOAT_H */ diff --git a/libavcodec/mips/fft_mips.c b/libavcodec/mips/fft_mips.c index cf008c6561..3cb1a4c162 100644 --- a/libavcodec/mips/fft_mips.c +++ b/libavcodec/mips/fft_mips.c @@ -57,6 +57,7 @@ */ #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static void ff_fft_calc_mips(FFTContext *s, FFTComplex *z) { int nbits, i, n, num_transforms, offset, step; @@ -494,6 +495,7 @@ static void ff_imdct_calc_mips(FFTContext *s, FFTSample *output, const FFTSample output[n-k-4] = output[n2+k+3]; } } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM */ av_cold void ff_fft_init_mips(FFTContext *s) @@ -504,10 +506,12 @@ av_cold void ff_fft_init_mips(FFTContext *s) ff_init_ff_cos_tabs(16); #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 s->fft_calc = ff_fft_calc_mips; #if CONFIG_MDCT s->imdct_calc = ff_imdct_calc_mips; s->imdct_half = ff_imdct_half_mips; #endif #endif +#endif } diff --git a/libavcodec/mips/iirfilter_mips.c b/libavcodec/mips/iirfilter_mips.c index a5646cde8b..87db9ffe55 100644 --- a/libavcodec/mips/iirfilter_mips.c +++ b/libavcodec/mips/iirfilter_mips.c @@ -55,6 +55,7 @@ #include "libavcodec/iirfilter.h" #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 typedef struct FFIIRFilterCoeffs { int order; float gain; @@ -195,10 +196,13 @@ static void ff_iir_filter_flt_mips(const struct FFIIRFilterCoeffs *c, } } } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM */ void ff_iir_filter_init_mips(FFIIRFilterContext *f) { #if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 f->filter_flt = ff_iir_filter_flt_mips; +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM */ } diff --git a/libavcodec/mips/lsp_mips.h b/libavcodec/mips/lsp_mips.h index 1e899bcd7c..6219c5aa40 100644 --- a/libavcodec/mips/lsp_mips.h +++ b/libavcodec/mips/lsp_mips.h @@ -55,6 +55,7 @@ #define AVCODEC_MIPS_LSP_MIPS_H #if HAVE_MIPSFPU && HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 #include "libavutil/mips/asmdefs.h" static av_always_inline void ff_lsp2polyf_mips(const double *lsp, double *f, int lp_half_order) @@ -107,5 +108,6 @@ static av_always_inline void ff_lsp2polyf_mips(const double *lsp, double *f, int } } #define ff_lsp2polyf ff_lsp2polyf_mips +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_MIPSFPU && HAVE_INLINE_ASM */ #endif /* AVCODEC_MIPS_LSP_MIPS_H */ diff --git a/libavcodec/mips/mpegaudiodsp_mips_fixed.c b/libavcodec/mips/mpegaudiodsp_mips_fixed.c index 92d260b85f..ed8c89089e 100644 --- a/libavcodec/mips/mpegaudiodsp_mips_fixed.c +++ b/libavcodec/mips/mpegaudiodsp_mips_fixed.c @@ -57,6 +57,9 @@ #include "libavutil/mips/asmdefs.h" #include "libavcodec/mpegaudiodsp.h" +#if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 + static void ff_mpadsp_apply_window_mips_fixed(int32_t *synth_buf, int32_t *window, int *dither_state, int16_t *samples, int incr) { @@ -901,8 +904,15 @@ static void ff_imdct36_blocks_mips_fixed(int *out, int *buf, int *in, } } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ +#endif /* HAVE_INLINE_ASM */ + void ff_mpadsp_init_mipsdsp(MPADSPContext *s) { +#if HAVE_INLINE_ASM +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 s->apply_window_fixed = ff_mpadsp_apply_window_mips_fixed; s->imdct36_blocks_fixed = ff_imdct36_blocks_mips_fixed; +#endif +#endif } diff --git a/libavcodec/mips/mpegaudiodsp_mips_float.c b/libavcodec/mips/mpegaudiodsp_mips_float.c index bd36894d31..270838ebf1 100644 --- a/libavcodec/mips/mpegaudiodsp_mips_float.c +++ b/libavcodec/mips/mpegaudiodsp_mips_float.c @@ -58,6 +58,9 @@ #include "libavutil/mips/asmdefs.h" #include "libavcodec/mpegaudiodsp.h" +#if HAVE_INLINE_ASM && HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 + static void ff_mpadsp_apply_window_mips_float(float *synth_buf, float *window, int *dither_state, float *samples, int incr) { @@ -1243,9 +1246,16 @@ static void ff_imdct36_blocks_mips_float(float *out, float *buf, float *in, } } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ +#endif /* HAVE_INLINE_ASM && HAVE_MIPSFPU */ + void ff_mpadsp_init_mipsfpu(MPADSPContext *s) { +#if HAVE_INLINE_ASM && HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 s->apply_window_float = ff_mpadsp_apply_window_mips_float; s->imdct36_blocks_float = ff_imdct36_blocks_mips_float; s->dct32_float = ff_dct32_mips_float; +#endif +#endif } diff --git a/libavcodec/mips/sbrdsp_mips.c b/libavcodec/mips/sbrdsp_mips.c index c203095548..1b0a10608d 100644 --- a/libavcodec/mips/sbrdsp_mips.c +++ b/libavcodec/mips/sbrdsp_mips.c @@ -166,6 +166,7 @@ static void sbr_qmf_post_shuffle_mips(float W[32][2], const float *z) } #if HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static void sbr_sum64x5_mips(float *z) { int k; @@ -882,6 +883,7 @@ static void sbr_hf_apply_noise_3_mips(float (*Y)[2], const float *s_m, phi_sign = -phi_sign; } } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_MIPSFPU */ #endif /* HAVE_INLINE_ASM */ @@ -891,6 +893,7 @@ void ff_sbrdsp_init_mips(SBRDSPContext *s) s->qmf_pre_shuffle = sbr_qmf_pre_shuffle_mips; s->qmf_post_shuffle = sbr_qmf_post_shuffle_mips; #if HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 s->sum64x5 = sbr_sum64x5_mips; s->sum_square = sbr_sum_square_mips; s->qmf_deint_bfly = sbr_qmf_deint_bfly_mips; @@ -902,6 +905,7 @@ void ff_sbrdsp_init_mips(SBRDSPContext *s) s->hf_apply_noise[1] = sbr_hf_apply_noise_1_mips; s->hf_apply_noise[2] = sbr_hf_apply_noise_2_mips; s->hf_apply_noise[3] = sbr_hf_apply_noise_3_mips; +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_MIPSFPU */ #endif /* HAVE_INLINE_ASM */ } diff --git a/libavcodec/mjpegdec.c b/libavcodec/mjpegdec.c index 69c9cf3626..a4eefb24a7 100644 --- a/libavcodec/mjpegdec.c +++ b/libavcodec/mjpegdec.c @@ -306,6 +306,8 @@ int ff_mjpeg_decode_sof(MJpegDecodeContext *s) av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height); if (av_image_check_size(width, height, 0, s->avctx)) return AVERROR_INVALIDDATA; + if (s->buf_size && (width + 7) / 8 * ((height + 7) / 8) > s->buf_size * 4LL) + return AVERROR_INVALIDDATA; nb_components = get_bits(&s->gb, 8); if (nb_components <= 0 || @@ -592,6 +594,10 @@ unk_pixfmt: av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n"); return AVERROR_PATCHWELCOME; } + if ((AV_RB32(s->upscale_h) || AV_RB32(s->upscale_v)) && s->progressive && s->avctx->pix_fmt == AV_PIX_FMT_GBRP) { + avpriv_report_missing_feature(s->avctx, "progressive for weird subsampling"); + return AVERROR_PATCHWELCOME; + } if (s->ls) { memset(s->upscale_h, 0, sizeof(s->upscale_h)); memset(s->upscale_v, 0, sizeof(s->upscale_v)); @@ -686,8 +692,8 @@ static int decode_block(MJpegDecodeContext *s, int16_t *block, int component, av_log(s->avctx, AV_LOG_ERROR, "error dc\n"); return AVERROR_INVALIDDATA; } - val = val * quant_matrix[0] + s->last_dc[component]; - val = FFMIN(val, 32767); + val = val * (unsigned)quant_matrix[0] + s->last_dc[component]; + val = av_clip_int16(val); s->last_dc[component] = val; block[0] = val; /* AC coefs */ @@ -728,7 +734,7 @@ static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block, int component, int dc_index, int16_t *quant_matrix, int Al) { - int val; + unsigned val; s->bdsp.clear_block(block); val = mjpeg_decode_dc(s, dc_index); if (val == 0xfffff) { @@ -747,7 +753,8 @@ static int decode_block_progressive(MJpegDecodeContext *s, int16_t *block, int16_t *quant_matrix, int ss, int se, int Al, int *EOBRUN) { - int code, i, j, level, val, run; + int code, i, j, val, run; + unsigned level; if (*EOBRUN) { (*EOBRUN)--; @@ -976,6 +983,11 @@ static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int p for (mb_x = 0; mb_x < s->mb_width; mb_x++) { int modified_predictor = predictor; + if (get_bits_left(&s->gb) < 1) { + av_log(s->avctx, AV_LOG_ERROR, "bitstream end in rgb_scan\n"); + return AVERROR_INVALIDDATA; + } + if (s->restart_interval && !s->restart_count){ s->restart_count = s->restart_interval; resync_mb_x = mb_x; @@ -999,7 +1011,7 @@ static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int p return -1; left[i] = buffer[mb_x][i] = - mask & (pred + (dc * (1 << point_transform))); + mask & (pred + (unsigned)(dc * (1 << point_transform))); } if (s->restart_interval && !--s->restart_count) { @@ -1076,6 +1088,10 @@ static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, for (mb_y = 0; mb_y < s->mb_height; mb_y++) { for (mb_x = 0; mb_x < s->mb_width; mb_x++) { + if (get_bits_left(&s->gb) < 1) { + av_log(s->avctx, AV_LOG_ERROR, "bitstream end in yuv_scan\n"); + return AVERROR_INVALIDDATA; + } if (s->restart_interval && !s->restart_count){ s->restart_count = s->restart_interval; resync_mb_x = mb_x; @@ -1127,7 +1143,7 @@ static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, if (s->interlaced && s->bottom_field) ptr += linesize >> 1; pred &= mask; - *ptr= pred + (dc << point_transform); + *ptr= pred + ((unsigned)dc << point_transform); }else{ ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap if(y==0 && toprow){ @@ -1147,7 +1163,7 @@ static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, if (s->interlaced && s->bottom_field) ptr16 += linesize >> 1; pred &= mask; - *ptr16= pred + (dc << point_transform); + *ptr16= pred + ((unsigned)dc << point_transform); } if (++x == h) { x = 0; @@ -1186,13 +1202,13 @@ static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor); pred &= mask; - *ptr = pred + (dc << point_transform); + *ptr = pred + ((unsigned)dc << point_transform); }else{ ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor); pred &= mask; - *ptr16= pred + (dc << point_transform); + *ptr16= pred + ((unsigned)dc << point_transform); } if (++x == h) { @@ -1369,11 +1385,7 @@ static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int mb_x, mb_y; int EOBRUN = 0; int c = s->comp_index[0]; - uint8_t *data = s->picture_ptr->data[c]; - int linesize = s->linesize[c]; - int last_scan = 0; int16_t *quant_matrix = s->quant_matrixes[s->quant_sindex[0]]; - int bytes_per_pixel = 1 + (s->bits > 8); av_assert0(ss>=0 && Ah>=0 && Al>=0); if (se < ss || se > 63) { @@ -1381,23 +1393,20 @@ static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, return AVERROR_INVALIDDATA; } - if (!Al) { - // s->coefs_finished is a bitmask for coefficients coded - // ss and se are parameters telling start and end coefficients - s->coefs_finished[c] |= (2ULL << se) - (1ULL << ss); - last_scan = !~s->coefs_finished[c]; - } - - if (s->interlaced && s->bottom_field) - data += linesize >> 1; + // s->coefs_finished is a bitmask for coefficients coded + // ss and se are parameters telling start and end coefficients + s->coefs_finished[c] |= (2ULL << se) - (1ULL << ss); s->restart_count = 0; for (mb_y = 0; mb_y < s->mb_height; mb_y++) { - uint8_t *ptr = data + (mb_y * linesize * 8 >> s->avctx->lowres); int block_idx = mb_y * s->block_stride[c]; int16_t (*block)[64] = &s->blocks[c][block_idx]; uint8_t *last_nnz = &s->last_nnz[c][block_idx]; + if (get_bits_left(&s->gb) <= 0) { + av_log(s->avctx, AV_LOG_ERROR, "bitstream truncated in mjpeg_decode_scan_progressive_ac\n"); + return AVERROR_INVALIDDATA; + } for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) { int ret; if (s->restart_interval && !s->restart_count) @@ -1415,12 +1424,6 @@ static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, return AVERROR_INVALIDDATA; } - if (last_scan) { - s->idsp.idct_put(ptr, linesize, *block); - if (s->bits & 7) - shift_output(s, ptr, linesize); - ptr += bytes_per_pixel*8 >> s->avctx->lowres; - } if (handle_rstn(s, 0)) EOBRUN = 0; } @@ -1428,6 +1431,41 @@ static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, return 0; } +static void mjpeg_idct_scan_progressive_ac(MJpegDecodeContext *s) +{ + int mb_x, mb_y; + int c; + const int bytes_per_pixel = 1 + (s->bits > 8); + const int block_size = s->lossless ? 1 : 8; + + for (c = 0; c < s->nb_components; c++) { + uint8_t *data = s->picture_ptr->data[c]; + int linesize = s->linesize[c]; + int h = s->h_max / s->h_count[c]; + int v = s->v_max / s->v_count[c]; + int mb_width = (s->width + h * block_size - 1) / (h * block_size); + int mb_height = (s->height + v * block_size - 1) / (v * block_size); + + if (~s->coefs_finished[c]) + av_log(s->avctx, AV_LOG_WARNING, "component %d is incomplete\n", c); + + if (s->interlaced && s->bottom_field) + data += linesize >> 1; + + for (mb_y = 0; mb_y < mb_height; mb_y++) { + uint8_t *ptr = data + (mb_y * linesize * 8 >> s->avctx->lowres); + int block_idx = mb_y * s->block_stride[c]; + int16_t (*block)[64] = &s->blocks[c][block_idx]; + for (mb_x = 0; mb_x < mb_width; mb_x++, block++) { + s->idsp.idct_put(ptr, linesize, *block); + if (s->bits & 7) + shift_output(s, ptr, linesize); + ptr += bytes_per_pixel*8 >> s->avctx->lowres; + } + } + } +} + int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask, int mb_bitmask_size, const AVFrame *reference) { @@ -1442,6 +1480,15 @@ int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask, return -1; } + if (reference) { + if (reference->width != s->picture_ptr->width || + reference->height != s->picture_ptr->height || + reference->format != s->picture_ptr->format) { + av_log(s->avctx, AV_LOG_ERROR, "Reference mismatching\n"); + return AVERROR_INVALIDDATA; + } + } + av_assert0(s->picture_ptr->data[0]); /* XXX: verify len field validity */ len = get_bits(&s->gb, 16); @@ -2042,6 +2089,8 @@ int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, int ret = 0; int is16bit; + s->buf_size = buf_size; + av_dict_free(&s->exif_metadata); av_freep(&s->stereo3d); s->adobe_transform = -1; @@ -2086,6 +2135,9 @@ int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, /* Comment */ else if (start_code == COM) mjpeg_decode_com(s); + else if (start_code == DQT) { + ff_mjpeg_decode_dqt(s); + } ret = -1; @@ -2117,9 +2169,6 @@ int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, s->restart_count = 0; /* nothing to do on SOI */ break; - case DQT: - ff_mjpeg_decode_dqt(s); - break; case DHT: if ((ret = ff_mjpeg_decode_dht(s)) < 0) { av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n"); @@ -2164,6 +2213,8 @@ int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, break; case EOI: eoi_parser: + if (avctx->skip_frame != AVDISCARD_ALL && s->progressive && s->cur_scan && s->got_picture) + mjpeg_idct_scan_progressive_ac(s); s->cur_scan = 0; if (!s->got_picture) { av_log(avctx, AV_LOG_WARNING, @@ -2346,7 +2397,7 @@ the_end: } } } - if (s->flipped) { + if (s->flipped && !s->rgb) { int j; avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift); for (index=0; index<4; index++) { diff --git a/libavcodec/mjpegdec.h b/libavcodec/mjpegdec.h index fb811294a1..6781c7c03a 100644 --- a/libavcodec/mjpegdec.h +++ b/libavcodec/mjpegdec.h @@ -45,6 +45,7 @@ typedef struct MJpegDecodeContext { AVClass *class; AVCodecContext *avctx; GetBitContext gb; + int buf_size; int start_code; /* current start code */ int buffer_size; diff --git a/libavcodec/mjpegenc_common.c b/libavcodec/mjpegenc_common.c index 099d817d5f..7a6fe7468f 100644 --- a/libavcodec/mjpegenc_common.c +++ b/libavcodec/mjpegenc_common.c @@ -122,6 +122,16 @@ static void jpeg_put_comments(AVCodecContext *avctx, PutBitContext *p) uint8_t *ptr; if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) { + AVRational sar = avctx->sample_aspect_ratio; + + if (sar.num > 65535 || sar.den > 65535) { + if (!av_reduce(&sar.num, &sar.den, avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den, 65535)) + av_log(avctx, AV_LOG_WARNING, + "Cannot store exact aspect ratio %d:%d\n", + avctx->sample_aspect_ratio.num, + avctx->sample_aspect_ratio.den); + } + /* JFIF header */ put_marker(p, APP0); put_bits(p, 16, 16); @@ -131,8 +141,8 @@ static void jpeg_put_comments(AVCodecContext *avctx, PutBitContext *p) * released revision. */ put_bits(p, 16, 0x0102); put_bits(p, 8, 0); /* units type: 0 - aspect ratio */ - put_bits(p, 16, avctx->sample_aspect_ratio.num); - put_bits(p, 16, avctx->sample_aspect_ratio.den); + put_bits(p, 16, sar.num); + put_bits(p, 16, sar.den); put_bits(p, 8, 0); /* thumbnail width */ put_bits(p, 8, 0); /* thumbnail height */ } diff --git a/libavcodec/mlpdec.c b/libavcodec/mlpdec.c index c93b058dd7..c50dc73e25 100644 --- a/libavcodec/mlpdec.c +++ b/libavcodec/mlpdec.c @@ -264,7 +264,7 @@ static inline int read_huff_channels(MLPDecodeContext *m, GetBitContext *gbp, result = (result << lsb_bits) + get_bits(gbp, lsb_bits); result += cp->sign_huff_offset; - result <<= quant_step_size; + result *= 1 << quant_step_size; m->sample_buffer[pos + s->blockpos][channel] = result; } @@ -474,7 +474,7 @@ static int read_restart_header(MLPDecodeContext *m, GetBitContext *gbp, uint8_t checksum; uint8_t lossless_check; int start_count = get_bits_count(gbp); - int min_channel, max_channel, max_matrix_channel; + int min_channel, max_channel, max_matrix_channel, noise_type; const int std_max_matrix_channel = m->avctx->codec_id == AV_CODEC_ID_MLP ? MAX_MATRIX_CHANNEL_MLP : MAX_MATRIX_CHANNEL_TRUEHD; @@ -487,9 +487,9 @@ static int read_restart_header(MLPDecodeContext *m, GetBitContext *gbp, return AVERROR_INVALIDDATA; } - s->noise_type = get_bits1(gbp); + noise_type = get_bits1(gbp); - if (m->avctx->codec_id == AV_CODEC_ID_MLP && s->noise_type) { + if (m->avctx->codec_id == AV_CODEC_ID_MLP && noise_type) { av_log(m->avctx, AV_LOG_ERROR, "MLP must have 0x31ea sync word.\n"); return AVERROR_INVALIDDATA; } @@ -515,7 +515,7 @@ static int read_restart_header(MLPDecodeContext *m, GetBitContext *gbp, /* This should happen for TrueHD streams with >6 channels and MLP's noise * type. It is not yet known if this is allowed. */ - if (max_channel > MAX_MATRIX_CHANNEL_MLP && !s->noise_type) { + if (max_channel > MAX_MATRIX_CHANNEL_MLP && !noise_type) { avpriv_request_sample(m->avctx, "%d channels (more than the " "maximum supported by the decoder)", @@ -532,6 +532,7 @@ static int read_restart_header(MLPDecodeContext *m, GetBitContext *gbp, s->min_channel = min_channel; s->max_channel = max_channel; s->max_matrix_channel = max_matrix_channel; + s->noise_type = noise_type; if (m->avctx->request_channel_layout && (s->ch_layout & m->avctx->request_channel_layout) == m->avctx->request_channel_layout && m->max_decoded_substream > substr) { @@ -684,7 +685,7 @@ static int read_filter_params(MLPDecodeContext *m, GetBitContext *gbp, } for (i = 0; i < order; i++) - fcoeff[i] = get_sbits(gbp, coeff_bits) << coeff_shift; + fcoeff[i] = get_sbits(gbp, coeff_bits) * (1 << coeff_shift); if (get_bits1(gbp)) { int state_bits, state_shift; @@ -701,7 +702,7 @@ static int read_filter_params(MLPDecodeContext *m, GetBitContext *gbp, /* TODO: Check validity of state data. */ for (i = 0; i < order; i++) - fp->state[i] = state_bits ? get_sbits(gbp, state_bits) << state_shift : 0; + fp->state[i] = state_bits ? get_sbits(gbp, state_bits) * (1 << state_shift) : 0; } } @@ -729,7 +730,7 @@ static int read_matrix_params(MLPDecodeContext *m, unsigned int substr, GetBitCo av_log(m->avctx, AV_LOG_ERROR, "Number of primitive matrices cannot be greater than %d.\n", max_primitive_matrices); - return AVERROR_INVALIDDATA; + goto error; } for (mat = 0; mat < s->num_primitive_matrices; mat++) { @@ -742,12 +743,12 @@ static int read_matrix_params(MLPDecodeContext *m, unsigned int substr, GetBitCo av_log(m->avctx, AV_LOG_ERROR, "Invalid channel %d specified as output from matrix.\n", s->matrix_out_ch[mat]); - return AVERROR_INVALIDDATA; + goto error; } if (frac_bits > 14) { av_log(m->avctx, AV_LOG_ERROR, "Too many fractional bits specified.\n"); - return AVERROR_INVALIDDATA; + goto error; } max_chan = s->max_matrix_channel; @@ -759,7 +760,7 @@ static int read_matrix_params(MLPDecodeContext *m, unsigned int substr, GetBitCo if (get_bits1(gbp)) coeff_val = get_sbits(gbp, frac_bits + 2); - s->matrix_coeff[mat][ch] = coeff_val << (14 - frac_bits); + s->matrix_coeff[mat][ch] = coeff_val * (1 << (14 - frac_bits)); } if (s->noise_type) @@ -769,6 +770,11 @@ static int read_matrix_params(MLPDecodeContext *m, unsigned int substr, GetBitCo } return 0; +error: + s->num_primitive_matrices = 0; + memset(s->matrix_out_ch, 0, sizeof(s->matrix_out_ch)); + + return AVERROR_INVALIDDATA; } /** Read channel parameters. */ @@ -999,8 +1005,8 @@ static void generate_2_noise_channels(MLPDecodeContext *m, unsigned int substr) for (i = 0; i < s->blockpos; i++) { uint16_t seed_shr7 = seed >> 7; - m->sample_buffer[i][maxchan+1] = ((int8_t)(seed >> 15)) << s->noise_shift; - m->sample_buffer[i][maxchan+2] = ((int8_t) seed_shr7) << s->noise_shift; + m->sample_buffer[i][maxchan+1] = ((int8_t)(seed >> 15)) * (1 << s->noise_shift); + m->sample_buffer[i][maxchan+2] = ((int8_t) seed_shr7) * (1 << s->noise_shift); seed = (seed << 16) ^ seed_shr7 ^ (seed_shr7 << 5); } @@ -1162,6 +1168,11 @@ static int read_access_unit(AVCodecContext *avctx, void* data, substr_header_size += 2; } + if (length < header_size + substr_header_size) { + av_log(m->avctx, AV_LOG_ERROR, "Insuffient data for headers\n"); + goto error; + } + if (!(nonrestart_substr ^ m->is_major_sync_unit)) { av_log(m->avctx, AV_LOG_ERROR, "Invalid nonrestart_substr.\n"); goto error; diff --git a/libavcodec/mlpdsp.c b/libavcodec/mlpdsp.c index 3ae8c37708..32a4503b64 100644 --- a/libavcodec/mlpdsp.c +++ b/libavcodec/mlpdsp.c @@ -113,11 +113,11 @@ int32_t ff_mlp_pack_output(int32_t lossless_check_data, for (i = 0; i < blockpos; i++) { for (out_ch = 0; out_ch <= max_matrix_channel; out_ch++) { int mat_ch = ch_assign[out_ch]; - int32_t sample = sample_buffer[i][mat_ch] - << output_shift[mat_ch]; + int32_t sample = sample_buffer[i][mat_ch] * + (1U << output_shift[mat_ch]); lossless_check_data ^= (sample & 0xffffff) << mat_ch; if (is32) - *data_32++ = sample << 8; + *data_32++ = sample * 256U; else *data_16++ = sample >> 8; } diff --git a/libavcodec/movtextdec.c b/libavcodec/movtextdec.c index 8d0e8141d3..abf0539072 100644 --- a/libavcodec/movtextdec.c +++ b/libavcodec/movtextdec.c @@ -115,6 +115,8 @@ static void mov_text_cleanup(MovTextContext *m) av_freep(&m->s[i]); } av_freep(&m->s); + m->count_s = 0; + m->style_entries = 0; } } @@ -278,12 +280,14 @@ static int decode_hclr(const uint8_t *tsmb, MovTextContext *m, AVPacket *avpkt) static int decode_styl(const uint8_t *tsmb, MovTextContext *m, AVPacket *avpkt) { int i; - m->style_entries = AV_RB16(tsmb); + int style_entries = AV_RB16(tsmb); tsmb += 2; // A single style record is of length 12 bytes. - if (m->tracksize + m->size_var + 2 + m->style_entries * 12 > avpkt->size) + if (m->tracksize + m->size_var + 2 + style_entries * 12 > avpkt->size) return -1; + m->style_entries = style_entries; + m->box_flags |= STYL_BOX; for(i = 0; i < m->style_entries; i++) { m->s_temp = av_malloc(sizeof(*m->s_temp)); @@ -294,6 +298,14 @@ static int decode_styl(const uint8_t *tsmb, MovTextContext *m, AVPacket *avpkt) m->s_temp->style_start = AV_RB16(tsmb); tsmb += 2; m->s_temp->style_end = AV_RB16(tsmb); + + if ( m->s_temp->style_end < m->s_temp->style_start + || (m->count_s && m->s_temp->style_start < m->s[m->count_s - 1]->style_end)) { + av_freep(&m->s_temp); + mov_text_cleanup(m); + return AVERROR(ENOMEM); + } + tsmb += 2; m->s_temp->style_fontID = AV_RB16(tsmb); tsmb += 2; @@ -487,7 +499,12 @@ static int mov_text_decode_frame(AVCodecContext *avctx, m->size_var = 8; //size_var is equal to 8 or 16 depending on the size of box - if (m->tracksize + tsmb_size > avpkt->size) + if (tsmb_size == 0) { + av_log(avctx, AV_LOG_ERROR, "tsmb_size is 0\n"); + return AVERROR_INVALIDDATA; + } + + if (tsmb_size > avpkt->size - m->tracksize) break; for (size_t i = 0; i < box_count; i++) { diff --git a/libavcodec/mpc8.c b/libavcodec/mpc8.c index a8feb6c4ce..8894457c7e 100644 --- a/libavcodec/mpc8.c +++ b/libavcodec/mpc8.c @@ -415,10 +415,14 @@ static int mpc8_decode_frame(AVCodecContext * avctx, void *data, c->cur_frame++; c->last_bits_used = get_bits_count(gb); - if(get_bits_left(gb) < 8) // we have only padding left - c->last_bits_used = buf_size << 3; if(c->cur_frame >= c->frames) c->cur_frame = 0; + if(c->cur_frame == 0 && get_bits_left(gb) < 8) {// we have only padding left + c->last_bits_used = buf_size << 3; + } else if (get_bits_left(gb) < 0) { + av_log(avctx, AV_LOG_ERROR, "Overread %d\n", -get_bits_left(gb)); + c->last_bits_used = buf_size << 3; + } *got_frame_ptr = 1; diff --git a/libavcodec/mpeg12dec.c b/libavcodec/mpeg12dec.c index cc8ace8e3a..4ac31d65c8 100644 --- a/libavcodec/mpeg12dec.c +++ b/libavcodec/mpeg12dec.c @@ -563,7 +563,7 @@ static inline int mpeg2_decode_block_intra(MpegEncContext *s, dc = s->last_dc[component]; dc += diff; s->last_dc[component] = dc; - block[0] = dc << (3 - s->intra_dc_precision); + block[0] = dc * (1 << (3 - s->intra_dc_precision)); ff_tlog(s->avctx, "dc=%d\n", block[0]); mismatch = block[0] ^ 1; i = 0; @@ -914,8 +914,8 @@ static int mpeg_decode_mb(MpegEncContext *s, int16_t block[12][64]) s->last_mv[i][0][1]); /* full_pel: only for MPEG-1 */ if (s->full_pel[i]) { - s->mv[i][0][0] <<= 1; - s->mv[i][0][1] <<= 1; + s->mv[i][0][0] *= 2; + s->mv[i][0][1] *= 2; } } } @@ -997,8 +997,8 @@ static int mpeg_decode_mb(MpegEncContext *s, int16_t block[12][64]) dmy = get_dmv(s); - s->last_mv[i][0][1] = my << my_shift; - s->last_mv[i][1][1] = my << my_shift; + s->last_mv[i][0][1] = my * (1 << my_shift); + s->last_mv[i][1][1] = my * (1 << my_shift); s->mv[i][0][0] = mx; s->mv[i][0][1] = my; @@ -1043,7 +1043,7 @@ static int mpeg_decode_mb(MpegEncContext *s, int16_t block[12][64]) cbp = get_vlc2(&s->gb, ff_mb_pat_vlc.table, MB_PAT_VLC_BITS, 1); if (mb_block_count > 6) { - cbp <<= mb_block_count - 6; + cbp *= 1 << mb_block_count - 6; cbp |= get_bits(&s->gb, mb_block_count - 6); s->bdsp.clear_blocks(s->block[6]); } @@ -1291,7 +1291,8 @@ static int mpeg_decode_postinit(AVCodecContext *avctx) if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO) { // MPEG-1 aspect - avctx->sample_aspect_ratio = av_d2q(1.0 / ff_mpeg1_aspect[s->aspect_ratio_info], 255); + AVRational aspect_inv = av_d2q(ff_mpeg1_aspect[s->aspect_ratio_info], 255); + avctx->sample_aspect_ratio = (AVRational) { aspect_inv.den, aspect_inv.num }; } else { // MPEG-2 // MPEG-2 aspect if (s->aspect_ratio_info > 1) { @@ -2432,7 +2433,7 @@ FF_ENABLE_DEPRECATION_WARNINGS #endif s->closed_gop = get_bits1(&s->gb); - /* broken_link indicate that after editing the + /* broken_link indicates that after editing the * reference frames of the first B-Frames after GOP I-Frame * are missing (open gop) */ broken_link = get_bits1(&s->gb); @@ -2827,6 +2828,7 @@ static int mpeg_decode_frame(AVCodecContext *avctx, void *data, avctx->extradata, avctx->extradata_size); if (*got_output) { av_log(avctx, AV_LOG_ERROR, "picture in extradata\n"); + av_frame_unref(picture); *got_output = 0; } s->extradata_decoded = 1; diff --git a/libavcodec/mpeg4videodec.c b/libavcodec/mpeg4videodec.c index 527cbe96c5..7713a2194a 100644 --- a/libavcodec/mpeg4videodec.c +++ b/libavcodec/mpeg4videodec.c @@ -171,13 +171,15 @@ static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *g int a = 2 << s->sprite_warping_accuracy; int rho = 3 - s->sprite_warping_accuracy; int r = 16 / a; - int alpha = 0; + int alpha = 1; int beta = 0; int w = s->width; int h = s->height; int min_ab, i, w2, h2, w3, h3; int sprite_ref[4][2]; int virtual_ref[2][2]; + int64_t sprite_offset[2][2]; + int64_t sprite_delta[2][2]; // only true for rectangle shapes const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 }, @@ -242,71 +244,71 @@ static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *g * from w&h based to w2&h2 based which are of the 2^x form. */ virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) + ROUNDED_DIV(((w - w2) * - (r * sprite_ref[0][0] - 16 * vop_ref[0][0]) + - w2 * (r * sprite_ref[1][0] - 16 * vop_ref[1][0])), w); + (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + + w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w); virtual_ref[0][1] = 16 * vop_ref[0][1] + ROUNDED_DIV(((w - w2) * - (r * sprite_ref[0][1] - 16 * vop_ref[0][1]) + - w2 * (r * sprite_ref[1][1] - 16 * vop_ref[1][1])), w); + (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + + w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w); virtual_ref[1][0] = 16 * vop_ref[0][0] + - ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16 * vop_ref[0][0]) + - h2 * (r * sprite_ref[2][0] - 16 * vop_ref[2][0])), h); + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + + h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h); virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) + - ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16 * vop_ref[0][1]) + - h2 * (r * sprite_ref[2][1] - 16 * vop_ref[2][1])), h); + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + + h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h); switch (ctx->num_sprite_warping_points) { case 0: - s->sprite_offset[0][0] = - s->sprite_offset[0][1] = - s->sprite_offset[1][0] = - s->sprite_offset[1][1] = 0; - s->sprite_delta[0][0] = a; - s->sprite_delta[0][1] = - s->sprite_delta[1][0] = 0; - s->sprite_delta[1][1] = a; + sprite_offset[0][0] = + sprite_offset[0][1] = + sprite_offset[1][0] = + sprite_offset[1][1] = 0; + sprite_delta[0][0] = a; + sprite_delta[0][1] = + sprite_delta[1][0] = 0; + sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 1: // GMC only - s->sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0]; - s->sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1]; - s->sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) - + sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0]; + sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1]; + sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) - a * (vop_ref[0][0] / 2); - s->sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) - + sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) - a * (vop_ref[0][1] / 2); - s->sprite_delta[0][0] = a; - s->sprite_delta[0][1] = - s->sprite_delta[1][0] = 0; - s->sprite_delta[1][1] = a; + sprite_delta[0][0] = a; + sprite_delta[0][1] = + sprite_delta[1][0] = 0; + sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 2: - s->sprite_offset[0][0] = (sprite_ref[0][0] << (alpha + rho)) + - (-r * sprite_ref[0][0] + virtual_ref[0][0]) * - (-vop_ref[0][0]) + - (r * sprite_ref[0][1] - virtual_ref[0][1]) * - (-vop_ref[0][1]) + (1 << (alpha + rho - 1)); - s->sprite_offset[0][1] = (sprite_ref[0][1] << (alpha + rho)) + - (-r * sprite_ref[0][1] + virtual_ref[0][1]) * - (-vop_ref[0][0]) + - (-r * sprite_ref[0][0] + virtual_ref[0][0]) * - (-vop_ref[0][1]) + (1 << (alpha + rho - 1)); - s->sprite_offset[1][0] = ((-r * sprite_ref[0][0] + virtual_ref[0][0]) * - (-2 * vop_ref[0][0] + 1) + - (r * sprite_ref[0][1] - virtual_ref[0][1]) * - (-2 * vop_ref[0][1] + 1) + 2 * w2 * r * - sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1))); - s->sprite_offset[1][1] = ((-r * sprite_ref[0][1] + virtual_ref[0][1]) * - (-2 * vop_ref[0][0] + 1) + - (-r * sprite_ref[0][0] + virtual_ref[0][0]) * - (-2 * vop_ref[0][1] + 1) + 2 * w2 * r * - sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1))); - s->sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); - s->sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]); - s->sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]); - s->sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); + sprite_offset[0][0] = ((int64_t) sprite_ref[0][0] * (1 << alpha + rho)) + + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * + ((int64_t) -vop_ref[0][0]) + + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * + ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); + sprite_offset[0][1] = ((int64_t) sprite_ref[0][1] * (1 << alpha + rho)) + + ((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) * + ((int64_t) -vop_ref[0][0]) + + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * + ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); + sprite_offset[1][0] = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * + ((int64_t)-2 * vop_ref[0][0] + 1) + + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * + ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * + (int64_t) sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1))); + sprite_offset[1][1] = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * + ((int64_t)-2 * vop_ref[0][0] + 1) + + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * + ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * + (int64_t) sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1))); + sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); + sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]); + sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]); + sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); ctx->sprite_shift[0] = alpha + rho; ctx->sprite_shift[1] = alpha + rho + 2; @@ -315,69 +317,105 @@ static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *g min_ab = FFMIN(alpha, beta); w3 = w2 >> min_ab; h3 = h2 >> min_ab; - s->sprite_offset[0][0] = (sprite_ref[0][0] << (alpha + beta + rho - min_ab)) + - (-r * sprite_ref[0][0] + virtual_ref[0][0]) * - h3 * (-vop_ref[0][0]) + - (-r * sprite_ref[0][0] + virtual_ref[1][0]) * - w3 * (-vop_ref[0][1]) + - (1 << (alpha + beta + rho - min_ab - 1)); - s->sprite_offset[0][1] = (sprite_ref[0][1] << (alpha + beta + rho - min_ab)) + - (-r * sprite_ref[0][1] + virtual_ref[0][1]) * - h3 * (-vop_ref[0][0]) + - (-r * sprite_ref[0][1] + virtual_ref[1][1]) * - w3 * (-vop_ref[0][1]) + - (1 << (alpha + beta + rho - min_ab - 1)); - s->sprite_offset[1][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]) * - h3 * (-2 * vop_ref[0][0] + 1) + - (-r * sprite_ref[0][0] + virtual_ref[1][0]) * - w3 * (-2 * vop_ref[0][1] + 1) + 2 * w2 * h3 * - r * sprite_ref[0][0] - 16 * w2 * h3 + - (1 << (alpha + beta + rho - min_ab + 1)); - s->sprite_offset[1][1] = (-r * sprite_ref[0][1] + virtual_ref[0][1]) * - h3 * (-2 * vop_ref[0][0] + 1) + - (-r * sprite_ref[0][1] + virtual_ref[1][1]) * - w3 * (-2 * vop_ref[0][1] + 1) + 2 * w2 * h3 * - r * sprite_ref[0][1] - 16 * w2 * h3 + - (1 << (alpha + beta + rho - min_ab + 1)); - s->sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3; - s->sprite_delta[0][1] = (-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3; - s->sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3; - s->sprite_delta[1][1] = (-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3; + sprite_offset[0][0] = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) + + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) + + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) + + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); + sprite_offset[0][1] = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) + + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) + + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) + + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); + sprite_offset[1][0] = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) + + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) + + (int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 + + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); + sprite_offset[1][1] = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) + + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) + + (int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 + + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); + sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3; + sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3; + sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3; + sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3; ctx->sprite_shift[0] = alpha + beta + rho - min_ab; ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2; break; } /* try to simplify the situation */ - if (s->sprite_delta[0][0] == a << ctx->sprite_shift[0] && - s->sprite_delta[0][1] == 0 && - s->sprite_delta[1][0] == 0 && - s->sprite_delta[1][1] == a << ctx->sprite_shift[0]) { - s->sprite_offset[0][0] >>= ctx->sprite_shift[0]; - s->sprite_offset[0][1] >>= ctx->sprite_shift[0]; - s->sprite_offset[1][0] >>= ctx->sprite_shift[1]; - s->sprite_offset[1][1] >>= ctx->sprite_shift[1]; - s->sprite_delta[0][0] = a; - s->sprite_delta[0][1] = 0; - s->sprite_delta[1][0] = 0; - s->sprite_delta[1][1] = a; + if (sprite_delta[0][0] == a << ctx->sprite_shift[0] && + sprite_delta[0][1] == 0 && + sprite_delta[1][0] == 0 && + sprite_delta[1][1] == a << ctx->sprite_shift[0]) { + sprite_offset[0][0] >>= ctx->sprite_shift[0]; + sprite_offset[0][1] >>= ctx->sprite_shift[0]; + sprite_offset[1][0] >>= ctx->sprite_shift[1]; + sprite_offset[1][1] >>= ctx->sprite_shift[1]; + sprite_delta[0][0] = a; + sprite_delta[0][1] = 0; + sprite_delta[1][0] = 0; + sprite_delta[1][1] = a; ctx->sprite_shift[0] = 0; ctx->sprite_shift[1] = 0; s->real_sprite_warping_points = 1; } else { int shift_y = 16 - ctx->sprite_shift[0]; int shift_c = 16 - ctx->sprite_shift[1]; + for (i = 0; i < 2; i++) { - s->sprite_offset[0][i] <<= shift_y; - s->sprite_offset[1][i] <<= shift_c; - s->sprite_delta[0][i] <<= shift_y; - s->sprite_delta[1][i] <<= shift_y; + if (shift_c < 0 || shift_y < 0 || + FFABS( sprite_offset[0][i]) >= INT_MAX >> shift_y || + FFABS( sprite_offset[1][i]) >= INT_MAX >> shift_c || + FFABS( sprite_delta[0][i]) >= INT_MAX >> shift_y || + FFABS( sprite_delta[1][i]) >= INT_MAX >> shift_y + ) { + avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset"); + goto overflow; + } + } + + for (i = 0; i < 2; i++) { + sprite_offset[0][i] *= 1 << shift_y; + sprite_offset[1][i] *= 1 << shift_c; + sprite_delta[0][i] *= 1 << shift_y; + sprite_delta[1][i] *= 1 << shift_y; ctx->sprite_shift[i] = 16; + + } + for (i = 0; i < 2; i++) { + int64_t sd[2] = { + sprite_delta[i][0] - a * (1LL<<16), + sprite_delta[i][1] - a * (1LL<<16) + }; + + if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX || + llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || + llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || + llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX || + llabs(sprite_delta[i][1] * (h+16LL)) >= INT_MAX || + llabs(sd[0]) >= INT_MAX || + llabs(sd[1]) >= INT_MAX || + llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX || + llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX || + llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX + ) { + avpriv_request_sample(s->avctx, "Overflow on sprite points"); + goto overflow; + } } s->real_sprite_warping_points = ctx->num_sprite_warping_points; } + for (i = 0; i < 4; i++) { + s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1]; + s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1]; + } + return 0; +overflow: + memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); + memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); + return AVERROR_PATCHWELCOME; } static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) { @@ -421,7 +459,7 @@ int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx) } mb_num = get_bits(&s->gb, mb_num_bits); - if (mb_num >= s->mb_num) { + if (mb_num >= s->mb_num || !mb_num) { av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num); return -1; @@ -500,10 +538,10 @@ static inline int get_amv(Mpeg4DecContext *ctx, int n) len >>= s->quarter_sample; if (s->real_sprite_warping_points == 1) { - if (ctx->divx_version == 500 && ctx->divx_build == 413) + if (ctx->divx_version == 500 && ctx->divx_build == 413 && a >= s->quarter_sample) sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample)); else - sum = RSHIFT(s->sprite_offset[0][n] << s->quarter_sample, a); + sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a); } else { dx = s->sprite_delta[n][0]; dy = s->sprite_delta[n][1]; @@ -1212,10 +1250,12 @@ not_coded: */ static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64]) { - Mpeg4DecContext *ctx = (Mpeg4DecContext *)s; + Mpeg4DecContext *ctx = s->avctx->priv_data; int cbp, mb_type; const int xy = s->mb_x + s->mb_y * s->mb_stride; + av_assert2(s == (void*)ctx); + mb_type = s->current_picture.mb_type[xy]; cbp = s->cbp_table[xy]; @@ -1297,12 +1337,13 @@ static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64]) static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64]) { - Mpeg4DecContext *ctx = (Mpeg4DecContext *)s; + Mpeg4DecContext *ctx = s->avctx->priv_data; int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant; int16_t *mot_val; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; const int xy = s->mb_x + s->mb_y * s->mb_stride; + av_assert2(s == (void*)ctx); av_assert2(s->h263_pred); if (s->pict_type == AV_PICTURE_TYPE_P || @@ -2101,8 +2142,15 @@ static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb) e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build); if (e != 4) { e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1; - if (e > 1) - build = (ver << 16) + (ver2 << 8) + ver3; + if (e > 1) { + if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) { + av_log(s->avctx, AV_LOG_WARNING, + "Unknown Lavc version string encountered, %d.%d.%d; " + "clamping sub-version values to 8-bits.\n", + ver, ver2, ver3); + } + build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF); + } } if (e != 4) { if (strcmp(buf, "ffmpeg") == 0) @@ -2236,6 +2284,7 @@ static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) int time_incr, time_increment; int64_t pts; + s->mcsel = 0; s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* pict type: I = 0 , P = 1 */ if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay && ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) { @@ -2288,7 +2337,7 @@ static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) if (s->pict_type != AV_PICTURE_TYPE_B) { s->last_time_base = s->time_base; s->time_base += time_incr; - s->time = s->time_base * s->avctx->framerate.num + time_increment; + s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment; if (s->workaround_bugs & FF_BUG_UMP4) { if (s->time < s->last_non_b_time) { /* header is not mpeg-4-compatible, broken encoder, @@ -2300,7 +2349,7 @@ static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) s->pp_time = s->time - s->last_non_b_time; s->last_non_b_time = s->time; } else { - s->time = (s->last_time_base + time_incr) * s->avctx->framerate.num + time_increment; + s->time = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment; s->pb_time = s->pp_time - (s->last_non_b_time - s->time); if (s->pp_time <= s->pb_time || s->pp_time <= s->pp_time - s->pb_time || @@ -2403,16 +2452,20 @@ static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } - if (s->pict_type == AV_PICTURE_TYPE_S && - (ctx->vol_sprite_usage == STATIC_SPRITE || - ctx->vol_sprite_usage == GMC_SPRITE)) { - if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0) - return AVERROR_INVALIDDATA; - if (ctx->sprite_brightness_change) - av_log(s->avctx, AV_LOG_ERROR, - "sprite_brightness_change not supported\n"); - if (ctx->vol_sprite_usage == STATIC_SPRITE) - av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n"); + if (s->pict_type == AV_PICTURE_TYPE_S) { + if((ctx->vol_sprite_usage == STATIC_SPRITE || + ctx->vol_sprite_usage == GMC_SPRITE)) { + if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0) + return AVERROR_INVALIDDATA; + if (ctx->sprite_brightness_change) + av_log(s->avctx, AV_LOG_ERROR, + "sprite_brightness_change not supported\n"); + if (ctx->vol_sprite_usage == STATIC_SPRITE) + av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n"); + } else { + memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); + memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); + } } if (ctx->shape != BIN_ONLY_SHAPE) { @@ -2510,6 +2563,7 @@ int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; + int vol = 0; /* search next start code */ align_get_bits(gb); @@ -2598,6 +2652,11 @@ int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) } if (startcode >= 0x120 && startcode <= 0x12F) { + if (vol) { + av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); + continue; + } + vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { diff --git a/libavcodec/mpeg4videoenc.c b/libavcodec/mpeg4videoenc.c index 1ba92381ec..df12dc8d99 100644 --- a/libavcodec/mpeg4videoenc.c +++ b/libavcodec/mpeg4videoenc.c @@ -910,7 +910,7 @@ void ff_set_mpeg4_time(MpegEncContext *s) static void mpeg4_encode_gop_header(MpegEncContext *s) { - int hours, minutes, seconds; + int64_t hours, minutes, seconds; int64_t time; put_bits(&s->pb, 16, 0); diff --git a/libavcodec/mpeg_er.c b/libavcodec/mpeg_er.c index dd87ae9cc9..9bd269c440 100644 --- a/libavcodec/mpeg_er.c +++ b/libavcodec/mpeg_er.c @@ -71,6 +71,7 @@ static void mpeg_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type, s->mb_skipped = mb_skipped; s->mb_x = mb_x; s->mb_y = mb_y; + s->mcsel = 0; memcpy(s->mv, mv, sizeof(*mv)); ff_init_block_index(s); diff --git a/libavcodec/mpegaudio_parser.c b/libavcodec/mpegaudio_parser.c index 873f941237..a072851ecf 100644 --- a/libavcodec/mpegaudio_parser.c +++ b/libavcodec/mpegaudio_parser.c @@ -98,7 +98,9 @@ static int mpegaudio_parse(AVCodecParserContext *s1, } else if (codec_id == AV_CODEC_ID_MP3ADU) { avpriv_report_missing_feature(avctx, "MP3ADU full parser"); - return AVERROR_PATCHWELCOME; + *poutbuf = NULL; + *poutbuf_size = 0; + return 0; /* parsers must not return error codes */ } break; diff --git a/libavcodec/mpegaudiodec_template.c b/libavcodec/mpegaudiodec_template.c index 5e3fe7e986..79ca97a8eb 100644 --- a/libavcodec/mpegaudiodec_template.c +++ b/libavcodec/mpegaudiodec_template.c @@ -252,7 +252,7 @@ static inline int l3_unscale(int value, int exponent) #endif if (e > 31) return 0; - m = (m + (1 << (e - 1))) >> e; + m = (m + ((1U << e)>>1)) >> e; return m; } @@ -1663,7 +1663,7 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr, header = AV_RB32(buf); if (header>>8 == AV_RB32("TAG")>>8) { av_log(avctx, AV_LOG_DEBUG, "discarding ID3 tag\n"); - return buf_size; + return buf_size + skipped; } ret = avpriv_mpegaudio_decode_header((MPADecodeHeader *)s, header); if (ret < 0) { diff --git a/libavcodec/mpegaudiodsp.c b/libavcodec/mpegaudiodsp.c index a5d20df629..3cafca27bf 100644 --- a/libavcodec/mpegaudiodsp.c +++ b/libavcodec/mpegaudiodsp.c @@ -20,17 +20,21 @@ #include "config.h" #include "libavutil/attributes.h" +#include "libavutil/thread.h" #include "mpegaudiodsp.h" #include "dct.h" #include "dct32.h" +static AVOnce mpadsp_float_table_init = AV_ONCE_INIT; +static AVOnce mpadsp_fixed_table_init = AV_ONCE_INIT; + av_cold void ff_mpadsp_init(MPADSPContext *s) { DCTContext dct; ff_dct_init(&dct, 5, DCT_II); - ff_init_mpadsp_tabs_float(); - ff_init_mpadsp_tabs_fixed(); + ff_thread_once(&mpadsp_float_table_init, &ff_init_mpadsp_tabs_float); + ff_thread_once(&mpadsp_fixed_table_init, &ff_init_mpadsp_tabs_fixed); s->apply_window_float = ff_mpadsp_apply_window_float; s->apply_window_fixed = ff_mpadsp_apply_window_fixed; diff --git a/libavcodec/mpegvideo.c b/libavcodec/mpegvideo.c index 236987b3d4..f660a1cbec 100644 --- a/libavcodec/mpegvideo.c +++ b/libavcodec/mpegvideo.c @@ -822,9 +822,7 @@ static void clear_context(MpegEncContext *s) s->sc.b_scratchpad = s->sc.obmc_scratchpad = NULL; - s->parse_context.buffer = NULL; - s->parse_context.buffer_size = 0; - s->parse_context.overread = 0; + s->bitstream_buffer = NULL; s->allocated_bitstream_buffer_size = 0; s->picture = NULL; @@ -1216,6 +1214,8 @@ int ff_mpv_frame_start(MpegEncContext *s, AVCodecContext *avctx) } ff_mpeg_unref_picture(s->avctx, &s->current_picture); + ff_mpeg_unref_picture(s->avctx, &s->last_picture); + ff_mpeg_unref_picture(s->avctx, &s->next_picture); /* release non reference frames */ for (i = 0; i < MAX_PICTURE_COUNT; i++) { @@ -1367,14 +1367,12 @@ int ff_mpv_frame_start(MpegEncContext *s, AVCodecContext *avctx) memset(s->next_picture.f->data, 0, sizeof(s->next_picture.f->data)); #endif if (s->last_picture_ptr) { - ff_mpeg_unref_picture(s->avctx, &s->last_picture); if (s->last_picture_ptr->f->buf[0] && (ret = ff_mpeg_ref_picture(s->avctx, &s->last_picture, s->last_picture_ptr)) < 0) return ret; } if (s->next_picture_ptr) { - ff_mpeg_unref_picture(s->avctx, &s->next_picture); if (s->next_picture_ptr->f->buf[0] && (ret = ff_mpeg_ref_picture(s->avctx, &s->next_picture, s->next_picture_ptr)) < 0) diff --git a/libavcodec/mpegvideo_enc.c b/libavcodec/mpegvideo_enc.c index 297ff78840..4af65a6c95 100644 --- a/libavcodec/mpegvideo_enc.c +++ b/libavcodec/mpegvideo_enc.c @@ -2912,6 +2912,8 @@ int ff_mpv_reallocate_putbitbuffer(MpegEncContext *s, size_t threshold, size_t s return AVERROR(ENOMEM); } + emms_c(); + av_fast_padded_malloc(&new_buffer, &new_buffer_size, s->avctx->internal->byte_buffer_size + size_increase); if (!new_buffer) diff --git a/libavcodec/mpegvideo_motion.c b/libavcodec/mpegvideo_motion.c index 51ba435231..2d3a778ec4 100644 --- a/libavcodec/mpegvideo_motion.c +++ b/libavcodec/mpegvideo_motion.c @@ -48,8 +48,8 @@ static void gmc1_motion(MpegEncContext *s, motion_y = s->sprite_offset[0][1]; src_x = s->mb_x * 16 + (motion_x >> (s->sprite_warping_accuracy + 1)); src_y = s->mb_y * 16 + (motion_y >> (s->sprite_warping_accuracy + 1)); - motion_x <<= (3 - s->sprite_warping_accuracy); - motion_y <<= (3 - s->sprite_warping_accuracy); + motion_x *= 1 << (3 - s->sprite_warping_accuracy); + motion_y *= 1 << (3 - s->sprite_warping_accuracy); src_x = av_clip(src_x, -16, s->width); if (src_x == s->width) motion_x = 0; @@ -95,8 +95,8 @@ static void gmc1_motion(MpegEncContext *s, motion_y = s->sprite_offset[1][1]; src_x = s->mb_x * 8 + (motion_x >> (s->sprite_warping_accuracy + 1)); src_y = s->mb_y * 8 + (motion_y >> (s->sprite_warping_accuracy + 1)); - motion_x <<= (3 - s->sprite_warping_accuracy); - motion_y <<= (3 - s->sprite_warping_accuracy); + motion_x *= 1 << (3 - s->sprite_warping_accuracy); + motion_y *= 1 << (3 - s->sprite_warping_accuracy); src_x = av_clip(src_x, -8, s->width >> 1); if (src_x == s->width >> 1) motion_x = 0; diff --git a/libavcodec/msmpeg4dec.c b/libavcodec/msmpeg4dec.c index aaadd9c073..f407910f2b 100644 --- a/libavcodec/msmpeg4dec.c +++ b/libavcodec/msmpeg4dec.c @@ -141,7 +141,7 @@ static int msmpeg4v12_decode_mb(MpegEncContext *s, int16_t block[6][64]) if(s->msmpeg4_version==2) cbp= get_vlc2(&s->gb, v2_intra_cbpc_vlc.table, V2_INTRA_CBPC_VLC_BITS, 1); else - cbp= get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 1); + cbp= get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if(cbp<0 || cbp>3){ av_log(s->avctx, AV_LOG_ERROR, "cbpc %d invalid at %d %d\n", cbp, s->mb_x, s->mb_y); return -1; @@ -170,12 +170,23 @@ static int msmpeg4v12_decode_mb(MpegEncContext *s, int16_t block[6][64]) s->mv[0][0][1] = my; *mb_type_ptr = MB_TYPE_L0 | MB_TYPE_16x16; } else { + int v; if(s->msmpeg4_version==2){ s->ac_pred = get_bits1(&s->gb); - cbp|= get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1)<<2; //FIXME check errors + v = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); + if (v < 0) { + av_log(s->avctx, AV_LOG_ERROR, "cbpy vlc invalid\n"); + return -1; + } + cbp|= v<<2; } else{ s->ac_pred = 0; - cbp|= get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1)<<2; //FIXME check errors + v = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); + if (v < 0) { + av_log(s->avctx, AV_LOG_ERROR, "cbpy vlc invalid\n"); + return -1; + } + cbp|= v<<2; if(s->pict_type==AV_PICTURE_TYPE_P) cbp^=0x3C; } *mb_type_ptr = MB_TYPE_INTRA; diff --git a/libavcodec/msrle.c b/libavcodec/msrle.c index 3090a910c2..23858fe6d0 100644 --- a/libavcodec/msrle.c +++ b/libavcodec/msrle.c @@ -95,15 +95,21 @@ static int msrle_decode_frame(AVCodecContext *avctx, s->buf = buf; s->size = buf_size; + if (buf_size < 2) //Minimally a end of picture code should be there + return AVERROR_INVALIDDATA; + if ((ret = ff_reget_buffer(avctx, s->frame)) < 0) return ret; if (avctx->bits_per_coded_sample > 1 && avctx->bits_per_coded_sample <= 8) { - const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL); + int size; + const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, &size); - if (pal) { + if (pal && size == AVPALETTE_SIZE) { s->frame->palette_has_changed = 1; memcpy(s->pal, pal, AVPALETTE_SIZE); + } else if (pal) { + av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", size); } /* make the palette available */ memcpy(s->frame->data[1], s->pal, AVPALETTE_SIZE); diff --git a/libavcodec/mss2.c b/libavcodec/mss2.c index c640934986..cf325470b9 100644 --- a/libavcodec/mss2.c +++ b/libavcodec/mss2.c @@ -422,7 +422,13 @@ static int decode_wmv9(AVCodecContext *avctx, const uint8_t *buf, int buf_size, ff_vc1_decode_blocks(v); - ff_er_frame_end(&s->er); + if (v->end_mb_x == s->mb_width && s->end_mb_y == s->mb_height) { + ff_er_frame_end(&s->er); + } else { + av_log(v->s.avctx, AV_LOG_WARNING, + "disabling error correction due to block count mismatch %dx%d != %dx%d\n", + v->end_mb_x, s->end_mb_y, s->mb_width, s->mb_height); + } ff_mpv_frame_end(s); diff --git a/libavcodec/mss3.c b/libavcodec/mss3.c index 01941967a5..8344bfe8a7 100644 --- a/libavcodec/mss3.c +++ b/libavcodec/mss3.c @@ -356,8 +356,9 @@ static int rac_get_model2_sym(RangeCoder *c, Model2 *m) static int rac_get_model_sym(RangeCoder *c, Model *m) { - int prob, prob2, helper, val; + int val; int end, end2; + unsigned prob, prob2, helper; prob = 0; prob2 = c->range; diff --git a/libavcodec/mss34dsp.c b/libavcodec/mss34dsp.c index 0397add17d..4965ac514d 100644 --- a/libavcodec/mss34dsp.c +++ b/libavcodec/mss34dsp.c @@ -62,30 +62,30 @@ void ff_mss34_gen_quant_mat(uint16_t *qmat, int quality, int luma) } #define DCT_TEMPLATE(blk, step, SOP, shift) \ - const int t0 = -39409 * blk[7 * step] - 58980 * blk[1 * step]; \ - const int t1 = 39410 * blk[1 * step] - 58980 * blk[7 * step]; \ - const int t2 = -33410 * blk[5 * step] - 167963 * blk[3 * step]; \ - const int t3 = 33410 * blk[3 * step] - 167963 * blk[5 * step]; \ - const int t4 = blk[3 * step] + blk[7 * step]; \ - const int t5 = blk[1 * step] + blk[5 * step]; \ - const int t6 = 77062 * t4 + 51491 * t5; \ - const int t7 = 77062 * t5 - 51491 * t4; \ - const int t8 = 35470 * blk[2 * step] - 85623 * blk[6 * step]; \ - const int t9 = 35470 * blk[6 * step] + 85623 * blk[2 * step]; \ - const int tA = SOP(blk[0 * step] - blk[4 * step]); \ - const int tB = SOP(blk[0 * step] + blk[4 * step]); \ + const unsigned t0 =-39409U * blk[7 * step] - 58980U * blk[1 * step]; \ + const unsigned t1 = 39410U * blk[1 * step] - 58980U * blk[7 * step]; \ + const unsigned t2 =-33410U * blk[5 * step] -167963U * blk[3 * step]; \ + const unsigned t3 = 33410U * blk[3 * step] -167963U * blk[5 * step]; \ + const unsigned t4 = blk[3 * step] + blk[7 * step]; \ + const unsigned t5 = blk[1 * step] + blk[5 * step]; \ + const unsigned t6 = 77062U * t4 + 51491U * t5; \ + const unsigned t7 = 77062U * t5 - 51491U * t4; \ + const unsigned t8 = 35470U * blk[2 * step] - 85623U * blk[6 * step]; \ + const unsigned t9 = 35470U * blk[6 * step] + 85623U * blk[2 * step]; \ + const unsigned tA = SOP(blk[0 * step] - blk[4 * step]); \ + const unsigned tB = SOP(blk[0 * step] + blk[4 * step]); \ \ - blk[0 * step] = ( t1 + t6 + t9 + tB) >> shift; \ - blk[1 * step] = ( t3 + t7 + t8 + tA) >> shift; \ - blk[2 * step] = ( t2 + t6 - t8 + tA) >> shift; \ - blk[3 * step] = ( t0 + t7 - t9 + tB) >> shift; \ - blk[4 * step] = (-(t0 + t7) - t9 + tB) >> shift; \ - blk[5 * step] = (-(t2 + t6) - t8 + tA) >> shift; \ - blk[6 * step] = (-(t3 + t7) + t8 + tA) >> shift; \ - blk[7 * step] = (-(t1 + t6) + t9 + tB) >> shift; \ + blk[0 * step] = (int)( t1 + t6 + t9 + tB) >> shift; \ + blk[1 * step] = (int)( t3 + t7 + t8 + tA) >> shift; \ + blk[2 * step] = (int)( t2 + t6 - t8 + tA) >> shift; \ + blk[3 * step] = (int)( t0 + t7 - t9 + tB) >> shift; \ + blk[4 * step] = (int)(-(t0 + t7) - t9 + tB) >> shift; \ + blk[5 * step] = (int)(-(t2 + t6) - t8 + tA) >> shift; \ + blk[6 * step] = (int)(-(t3 + t7) + t8 + tA) >> shift; \ + blk[7 * step] = (int)(-(t1 + t6) + t9 + tB) >> shift; \ -#define SOP_ROW(a) (((a) << 16) + 0x2000) -#define SOP_COL(a) (((a) + 32) << 16) +#define SOP_ROW(a) (((a) * (1U << 16)) + 0x2000) +#define SOP_COL(a) (((a) + 32) * (1U << 16)) void ff_mss34_dct_put(uint8_t *dst, int stride, int *block) { diff --git a/libavcodec/msvideo1.c b/libavcodec/msvideo1.c index 891675fcb0..c53ca826cb 100644 --- a/libavcodec/msvideo1.c +++ b/libavcodec/msvideo1.c @@ -302,15 +302,24 @@ static int msvideo1_decode_frame(AVCodecContext *avctx, s->buf = buf; s->size = buf_size; + // Discard frame if its smaller than the minimum frame size + if (buf_size < (avctx->width/4) * (avctx->height/4) / 512) { + av_log(avctx, AV_LOG_ERROR, "Packet is too small\n"); + return AVERROR_INVALIDDATA; + } + if ((ret = ff_reget_buffer(avctx, s->frame)) < 0) return ret; if (s->mode_8bit) { - const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL); + int size; + const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, &size); - if (pal) { + if (pal && size == AVPALETTE_SIZE) { memcpy(s->pal, pal, AVPALETTE_SIZE); s->frame->palette_has_changed = 1; + } else if (pal) { + av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", size); } } diff --git a/libavcodec/nellymoser.c b/libavcodec/nellymoser.c index 0740c75a0f..d6d5b7a910 100644 --- a/libavcodec/nellymoser.c +++ b/libavcodec/nellymoser.c @@ -85,7 +85,7 @@ const int16_t ff_nelly_delta_table[32] = { static inline int signed_shift(int i, int shift) { if (shift > 0) - return i << shift; + return (unsigned)i << shift; return i >> -shift; } @@ -109,7 +109,7 @@ static int headroom(int *la) return 31; } l = 30 - av_log2(FFABS(*la)); - *la <<= l; + *la *= 1<frame_number; enum { NUV_UNCOMPRESSED = '0', @@ -198,6 +199,9 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, case NUV_RTJPEG_IN_LZO: case NUV_RTJPEG: keyframe = !buf[2]; + if (c->width < 16 || c->height < 16) { + return AVERROR_INVALIDDATA; + } break; case NUV_COPY_LAST: keyframe = 0; @@ -206,6 +210,16 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, keyframe = 1; break; } + switch (comptype) { + case NUV_UNCOMPRESSED: + minsize = c->width * c->height * 3 / 2; + break; + case NUV_RTJPEG: + minsize = c->width/16 * (c->height/16) * 6; + break; + } + if (buf_size < minsize / 4) + return AVERROR_INVALIDDATA; retry: // skip rest of the frameheader. buf = &buf[12]; diff --git a/libavcodec/options.c b/libavcodec/options.c index ea2563b571..fb23ee6ad4 100644 --- a/libavcodec/options.c +++ b/libavcodec/options.c @@ -179,6 +179,29 @@ void avcodec_free_context(AVCodecContext **pavctx) av_freep(pavctx); } +static void copy_context_reset(AVCodecContext *avctx) +{ + int i; + + av_opt_free(avctx); +#if FF_API_CODED_FRAME +FF_DISABLE_DEPRECATION_WARNINGS + av_frame_free(&avctx->coded_frame); +FF_ENABLE_DEPRECATION_WARNINGS +#endif + av_freep(&avctx->rc_override); + av_freep(&avctx->intra_matrix); + av_freep(&avctx->inter_matrix); + av_freep(&avctx->extradata); + av_freep(&avctx->subtitle_header); + for (i = 0; i < avctx->nb_coded_side_data; i++) + av_freep(&avctx->coded_side_data[i].data); + av_freep(&avctx->coded_side_data); + avctx->subtitle_header_size = 0; + avctx->nb_coded_side_data = 0; + avctx->extradata_size = 0; +} + int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src) { const AVCodec *orig_codec = dest->codec; @@ -191,12 +214,7 @@ int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src) return AVERROR(EINVAL); } - av_opt_free(dest); - av_freep(&dest->rc_override); - av_freep(&dest->intra_matrix); - av_freep(&dest->inter_matrix); - av_freep(&dest->extradata); - av_freep(&dest->subtitle_header); + copy_context_reset(dest); memcpy(dest, src, sizeof(*dest)); av_opt_copy(dest, src); @@ -221,10 +239,12 @@ FF_ENABLE_DEPRECATION_WARNINGS /* reallocate values that should be allocated separately */ dest->extradata = NULL; + dest->coded_side_data = NULL; dest->intra_matrix = NULL; dest->inter_matrix = NULL; dest->rc_override = NULL; dest->subtitle_header = NULL; + dest->nb_coded_side_data = 0; #define alloc_and_copy_or_fail(obj, size, pad) \ if (src->obj && size > 0) { \ @@ -248,14 +268,7 @@ FF_ENABLE_DEPRECATION_WARNINGS return 0; fail: - av_freep(&dest->rc_override); - av_freep(&dest->intra_matrix); - av_freep(&dest->inter_matrix); - av_freep(&dest->extradata); - av_freep(&dest->subtitle_header); - dest->subtitle_header_size = 0; - dest->extradata_size = 0; - av_opt_free(dest); + copy_context_reset(dest); return AVERROR(ENOMEM); } diff --git a/libavcodec/opus_parser.c b/libavcodec/opus_parser.c index c30fd7bbd4..1c61c0077f 100644 --- a/libavcodec/opus_parser.c +++ b/libavcodec/opus_parser.c @@ -43,6 +43,7 @@ static const uint8_t *parse_opus_ts_header(const uint8_t *start, int *payload_le const uint8_t *buf = start + 1; int start_trim_flag, end_trim_flag, control_extension_flag, control_extension_length; uint8_t flags; + uint64_t payload_len_tmp; GetByteContext gb; bytestream2_init(&gb, buf, buf_len); @@ -52,11 +53,11 @@ static const uint8_t *parse_opus_ts_header(const uint8_t *start, int *payload_le end_trim_flag = (flags >> 3) & 1; control_extension_flag = (flags >> 2) & 1; - *payload_len = 0; + payload_len_tmp = *payload_len = 0; while (bytestream2_peek_byte(&gb) == 0xff) - *payload_len += bytestream2_get_byte(&gb); + payload_len_tmp += bytestream2_get_byte(&gb); - *payload_len += bytestream2_get_byte(&gb); + payload_len_tmp += bytestream2_get_byte(&gb); if (start_trim_flag) bytestream2_skip(&gb, 2); @@ -67,6 +68,11 @@ static const uint8_t *parse_opus_ts_header(const uint8_t *start, int *payload_le bytestream2_skip(&gb, control_extension_length); } + if (bytestream2_tell(&gb) + payload_len_tmp > buf_len) + return NULL; + + *payload_len = payload_len_tmp; + return buf + bytestream2_tell(&gb); } @@ -104,6 +110,10 @@ static int opus_find_frame_end(AVCodecParserContext *ctx, AVCodecContext *avctx, state = (state << 8) | payload[i]; if ((state & OPUS_TS_MASK) == OPUS_TS_HEADER) { payload = parse_opus_ts_header(payload, &payload_len, buf_size - i); + if (!payload) { + av_log(avctx, AV_LOG_ERROR, "Error parsing Ogg TS header.\n"); + return AVERROR_INVALIDDATA; + } *header_len = payload - buf; start_found = 1; break; diff --git a/libavcodec/opus_silk.c b/libavcodec/opus_silk.c index 73526f9800..6418743b6b 100644 --- a/libavcodec/opus_silk.c +++ b/libavcodec/opus_silk.c @@ -851,8 +851,7 @@ static inline void silk_stabilize_lsf(int16_t nlsf[16], int order, const uint16_ if (nlsf[0] < min_delta[0]) nlsf[0] = min_delta[0]; for (i = 1; i < order; i++) - if (nlsf[i] < nlsf[i - 1] + min_delta[i]) - nlsf[i] = nlsf[i - 1] + min_delta[i]; + nlsf[i] = FFMAX(nlsf[i], FFMIN(nlsf[i - 1] + min_delta[i], 32767)); /* push backwards to increase distance */ if (nlsf[order-1] > 32768 - min_delta[order]) @@ -956,8 +955,10 @@ static void silk_lsf2lpc(const int16_t nlsf[16], float lpcf[16], int order) /* reconstruct A(z) */ for (k = 0; k < order>>1; k++) { - lpc32[k] = -p[k + 1] - p[k] - q[k + 1] + q[k]; - lpc32[order-k-1] = -p[k + 1] - p[k] + q[k + 1] - q[k]; + int32_t p_tmp = p[k + 1] + p[k]; + int32_t q_tmp = q[k + 1] - q[k]; + lpc32[k] = -q_tmp - p_tmp; + lpc32[order-k-1] = q_tmp - p_tmp; } /* limit the range of the LPC coefficients to each fit within an int16_t */ diff --git a/libavcodec/pafvideo.c b/libavcodec/pafvideo.c index cab3129f8f..6980ae1b35 100644 --- a/libavcodec/pafvideo.c +++ b/libavcodec/pafvideo.c @@ -181,6 +181,8 @@ static int decode_0(PAFVideoDecContext *c, uint8_t *pkt, uint8_t code) dend = c->frame[page] + c->frame_size; offset = (x & 0x7F) * 2; j = bytestream2_get_le16(&c->gb) + offset; + if (bytestream2_get_bytes_left(&c->gb) < (j - offset) * 16) + return AVERROR_INVALIDDATA; do { offset++; if (dst + 3 * c->width + 4 > dend) @@ -198,7 +200,8 @@ static int decode_0(PAFVideoDecContext *c, uint8_t *pkt, uint8_t code) do { set_src_position(c, &src, &send); if ((src + 3 * c->width + 4 > send) || - (dst + 3 * c->width + 4 > dend)) + (dst + 3 * c->width + 4 > dend) || + bytestream2_get_bytes_left(&c->gb) < 4) return AVERROR_INVALIDDATA; copy_block4(dst, src, c->width, c->width, 4); i++; @@ -267,12 +270,20 @@ static int paf_video_decode(AVCodecContext *avctx, void *data, uint8_t code, *dst, *end; int i, frame, ret; - if ((ret = ff_reget_buffer(avctx, c->pic)) < 0) - return ret; + if (pkt->size < 2) + return AVERROR_INVALIDDATA; bytestream2_init(&c->gb, pkt->data, pkt->size); code = bytestream2_get_byte(&c->gb); + if ((code & 0xF) > 4 || (code & 0xF) == 3) { + avpriv_request_sample(avctx, "unknown/invalid code"); + return AVERROR_INVALIDDATA; + } + + if ((ret = ff_reget_buffer(avctx, c->pic)) < 0) + return ret; + if (code & 0x20) { // frame is keyframe for (i = 0; i < 4; i++) memset(c->frame[i], 0, c->frame_size); @@ -367,8 +378,7 @@ static int paf_video_decode(AVCodecContext *avctx, void *data, } break; default: - avpriv_request_sample(avctx, "unknown/invalid code"); - return AVERROR_INVALIDDATA; + av_assert0(0); } av_image_copy_plane(c->pic->data[0], c->pic->linesize[0], diff --git a/libavcodec/pgssubdec.c b/libavcodec/pgssubdec.c index 07a2a78629..222c40a377 100644 --- a/libavcodec/pgssubdec.c +++ b/libavcodec/pgssubdec.c @@ -300,8 +300,11 @@ static int parse_object_segment(AVCodecContext *avctx, av_fast_padded_malloc(&object->rle, &object->rle_buffer_size, rle_bitmap_len); - if (!object->rle) + if (!object->rle) { + object->rle_data_len = 0; + object->rle_remaining_len = 0; return AVERROR(ENOMEM); + } memcpy(object->rle, buf, buf_size); object->rle_data_len = buf_size; @@ -354,8 +357,14 @@ static int parse_palette_segment(AVCodecContext *avctx, cb = bytestream_get_byte(&buf); alpha = bytestream_get_byte(&buf); - YUV_TO_RGB1(cb, cr); - YUV_TO_RGB2(r, g, b, y); + /* Default to BT.709 colorimetry. In case of <= 576 height use BT.601 */ + if (avctx->height <= 0 || avctx->height > 576) { + YUV_TO_RGB1_CCIR_BT709(cb, cr); + } else { + YUV_TO_RGB1_CCIR(cb, cr); + } + + YUV_TO_RGB2_CCIR(r, g, b, y); ff_dlog(avctx, "Color %d := (%d,%d,%d,%d)\n", color_id, r, g, b, alpha); @@ -552,12 +561,13 @@ static int display_end_segment(AVCodecContext *avctx, void *data, sub->rects[i]->x = ctx->presentation.objects[i].x; sub->rects[i]->y = ctx->presentation.objects[i].y; - sub->rects[i]->w = object->w; - sub->rects[i]->h = object->h; - - sub->rects[i]->linesize[0] = object->w; if (object->rle) { + sub->rects[i]->w = object->w; + sub->rects[i]->h = object->h; + + sub->rects[i]->linesize[0] = object->w; + if (object->rle_remaining_len) { av_log(avctx, AV_LOG_ERROR, "RLE data length %u is %u bytes shorter than expected\n", object->rle_data_len, object->rle_remaining_len); diff --git a/libavcodec/pictordec.c b/libavcodec/pictordec.c index ff6eb7f4fc..a09ee379c0 100644 --- a/libavcodec/pictordec.c +++ b/libavcodec/pictordec.c @@ -77,10 +77,10 @@ static void picmemset(PicContext *s, AVFrame *frame, int value, int run, if (*y < 0) { *y = s->height - 1; *plane += 1; + if (*plane >= s->nb_planes) + return; value <<= bits_per_plane; mask <<= bits_per_plane; - if (*plane >= s->nb_planes) - break; } } } @@ -142,7 +142,7 @@ static int decode_frame(AVCodecContext *avctx, if (av_image_check_size(s->width, s->height, 0, avctx) < 0) return -1; - if (s->width != avctx->width && s->height != avctx->height) { + if (s->width != avctx->width || s->height != avctx->height) { ret = ff_set_dimensions(avctx, s->width, s->height); if (ret < 0) return ret; @@ -236,7 +236,7 @@ static int decode_frame(AVCodecContext *avctx, } } - if (x < avctx->width) { + if (plane < s->nb_planes && x < avctx->width) { int run = (y + 1) * avctx->width - x; if (bits_per_plane == 8) picmemset_8bpp(s, frame, val, run, &x, &y); diff --git a/libavcodec/pixblockdsp.c b/libavcodec/pixblockdsp.c index f0883d3d08..6152fe40c3 100644 --- a/libavcodec/pixblockdsp.c +++ b/libavcodec/pixblockdsp.c @@ -82,6 +82,7 @@ av_cold void ff_pixblockdsp_init(PixblockDSPContext *c, AVCodecContext *avctx) { const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8; + c->diff_pixels_unaligned = c->diff_pixels = diff_pixels_c; switch (avctx->bits_per_raw_sample) { diff --git a/libavcodec/pixblockdsp.h b/libavcodec/pixblockdsp.h index 79ed86c3a6..b14514de7e 100644 --- a/libavcodec/pixblockdsp.h +++ b/libavcodec/pixblockdsp.h @@ -31,6 +31,11 @@ typedef struct PixblockDSPContext { const uint8_t *s1 /* align 8 */, const uint8_t *s2 /* align 8 */, int stride); + void (*diff_pixels_unaligned)(int16_t *av_restrict block /* align 16 */, + const uint8_t *s1, + const uint8_t *s2, + int stride); + } PixblockDSPContext; void ff_pixblockdsp_init(PixblockDSPContext *c, AVCodecContext *avctx); diff --git a/libavcodec/pngdec.c b/libavcodec/pngdec.c index 61857d0e5c..c0988e4f22 100644 --- a/libavcodec/pngdec.c +++ b/libavcodec/pngdec.c @@ -437,13 +437,13 @@ static int decode_zbuf(AVBPrint *bp, const uint8_t *data, av_bprint_init(bp, 0, -1); while (zstream.avail_in > 0) { - av_bprint_get_buffer(bp, 1, &buf, &buf_size); - if (!buf_size) { + av_bprint_get_buffer(bp, 2, &buf, &buf_size); + if (buf_size < 2) { ret = AVERROR(ENOMEM); goto fail; } zstream.next_out = buf; - zstream.avail_out = buf_size; + zstream.avail_out = buf_size - 1; ret = inflate(&zstream, Z_PARTIAL_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { ret = AVERROR_EXTERNAL; @@ -559,6 +559,11 @@ static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s, return AVERROR_INVALIDDATA; } s->bit_depth = bytestream2_get_byte(&s->gb); + if (s->bit_depth != 1 && s->bit_depth != 2 && s->bit_depth != 4 && + s->bit_depth != 8 && s->bit_depth != 16) { + av_log(avctx, AV_LOG_ERROR, "Invalid bit depth\n"); + goto error; + } s->color_type = bytestream2_get_byte(&s->gb); s->compression_type = bytestream2_get_byte(&s->gb); s->filter_type = bytestream2_get_byte(&s->gb); @@ -572,6 +577,10 @@ static int decode_ihdr_chunk(AVCodecContext *avctx, PNGDecContext *s, s->compression_type, s->filter_type, s->interlace_type); return 0; +error: + s->cur_w = s->cur_h = s->width = s->height = 0; + s->bit_depth = 8; + return AVERROR_INVALIDDATA; } static int decode_phys_chunk(AVCodecContext *avctx, PNGDecContext *s) @@ -602,8 +611,9 @@ static int decode_idat_chunk(AVCodecContext *avctx, PNGDecContext *s, } if (!(s->state & PNG_IDAT)) { /* init image info */ - avctx->width = s->width; - avctx->height = s->height; + ret = ff_set_dimensions(avctx, s->width, s->height); + if (ret < 0) + return ret; s->channels = ff_png_get_nb_channels(s->color_type); s->bits_per_pixel = s->bit_depth * s->channels; @@ -772,17 +782,28 @@ static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s, { int v, i; + if (!(s->state & PNG_IHDR)) { + av_log(avctx, AV_LOG_ERROR, "trns before IHDR\n"); + return AVERROR_INVALIDDATA; + } + + if (s->state & PNG_IDAT) { + av_log(avctx, AV_LOG_ERROR, "trns after IDAT\n"); + return AVERROR_INVALIDDATA; + } + if (s->color_type == PNG_COLOR_TYPE_PALETTE) { if (length > 256 || !(s->state & PNG_PLTE)) return AVERROR_INVALIDDATA; for (i = 0; i < length; i++) { - v = bytestream2_get_byte(&s->gb); + unsigned v = bytestream2_get_byte(&s->gb); s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24); } } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) { if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) || - (s->color_type == PNG_COLOR_TYPE_RGB && length != 6)) + (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) || + s->bit_depth == 1) return AVERROR_INVALIDDATA; for (i = 0; i < length / 2; i++) { @@ -1136,6 +1157,7 @@ static int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s, case MKTAG('p', 'H', 'Y', 's'): case MKTAG('t', 'E', 'X', 't'): case MKTAG('I', 'D', 'A', 'T'): + case MKTAG('t', 'R', 'N', 'S'): break; default: goto skip_tag; @@ -1240,6 +1262,8 @@ exit_loop: size_t raw_bpp = s->bpp - byte_depth; unsigned x, y; + av_assert0(s->bit_depth > 1); + for (y = 0; y < s->height; ++y) { uint8_t *row = &s->image_buf[s->image_linesize * y]; @@ -1334,7 +1358,7 @@ static int decode_frame_png(AVCodecContext *avctx, } if ((ret = av_frame_ref(data, s->picture.f)) < 0) - return ret; + goto the_end; *got_frame = 1; diff --git a/libavcodec/pnm.c b/libavcodec/pnm.c index 1675959fbf..8b4a4ac292 100644 --- a/libavcodec/pnm.c +++ b/libavcodec/pnm.c @@ -24,6 +24,7 @@ #include "libavutil/imgutils.h" #include "avcodec.h" +#include "internal.h" #include "pnm.h" static inline int pnm_space(int c) @@ -61,6 +62,7 @@ int ff_pnm_decode_header(AVCodecContext *avctx, PNMContext * const s) { char buf1[32], tuple_type[32]; int h, w, depth, maxval; + int ret; pnm_get(s, buf1, sizeof(buf1)); if(buf1[0] != 'P') @@ -110,8 +112,9 @@ int ff_pnm_decode_header(AVCodecContext *avctx, PNMContext * const s) if (w <= 0 || h <= 0 || maxval <= 0 || depth <= 0 || tuple_type[0] == '\0' || av_image_check_size(w, h, 0, avctx) || s->bytestream >= s->bytestream_end) return AVERROR_INVALIDDATA; - avctx->width = w; - avctx->height = h; + ret = ff_set_dimensions(avctx, w, h); + if (ret < 0) + return ret; s->maxval = maxval; if (depth == 1) { if (maxval == 1) { @@ -153,8 +156,9 @@ int ff_pnm_decode_header(AVCodecContext *avctx, PNMContext * const s) if(w <= 0 || h <= 0 || av_image_check_size(w, h, 0, avctx) || s->bytestream >= s->bytestream_end) return AVERROR_INVALIDDATA; - avctx->width = w; - avctx->height = h; + ret = ff_set_dimensions(avctx, w, h); + if (ret < 0) + return ret; if (avctx->pix_fmt != AV_PIX_FMT_MONOWHITE && avctx->pix_fmt != AV_PIX_FMT_MONOBLACK) { pnm_get(s, buf1, sizeof(buf1)); diff --git a/libavcodec/pnmdec.c b/libavcodec/pnmdec.c index d4261a4530..4e2045d2b3 100644 --- a/libavcodec/pnmdec.c +++ b/libavcodec/pnmdec.c @@ -43,7 +43,7 @@ static int pnm_decode_frame(AVCodecContext *avctx, void *data, int buf_size = avpkt->size; PNMContext * const s = avctx->priv_data; AVFrame * const p = data; - int i, j, n, linesize, h, upgrade = 0, is_mono = 0; + int i, j, k, n, linesize, h, upgrade = 0, is_mono = 0; unsigned char *ptr; int components, sample_len, ret; @@ -143,10 +143,14 @@ static int pnm_decode_frame(AVCodecContext *avctx, void *data, v = (*s->bytestream++)&1; } else { /* read a sequence of digits */ - do { + for (k = 0; k < 5 && c <= 9; k += 1) { v = 10*v + c; c = (*s->bytestream++) - '0'; - } while (c <= 9); + } + if (v > s->maxval) { + av_log(avctx, AV_LOG_ERROR, "value %d larger than maxval %d\n", v, s->maxval); + return AVERROR_INVALIDDATA; + } } if (sample_len == 16) { ((uint16_t*)ptr)[j] = (((1<maxval>>1))/s->maxval; diff --git a/libavcodec/ppc/pixblockdsp.c b/libavcodec/ppc/pixblockdsp.c index 84aa562bb6..f3a5050469 100644 --- a/libavcodec/ppc/pixblockdsp.c +++ b/libavcodec/ppc/pixblockdsp.c @@ -67,10 +67,10 @@ static void get_pixels_altivec(int16_t *restrict block, const uint8_t *pixels, ptrdiff_t line_size) { int i; - vec_u8 perm = vec_lvsl(0, pixels); const vec_u8 zero = (const vec_u8)vec_splat_u8(0); for (i = 0; i < 8; i++) { + vec_u8 perm = vec_lvsl(0, pixels); /* Read potentially unaligned pixels. * We're reading 16 pixels, and actually only want 8, * but we simply ignore the extras. */ @@ -157,8 +157,7 @@ static void diff_pixels_altivec(int16_t *restrict block, const uint8_t *s1, const uint8_t *s2, int stride) { int i; - vec_u8 perm1 = vec_lvsl(0, s1); - vec_u8 perm2 = vec_lvsl(0, s2); + vec_u8 perm; const vec_u8 zero = (const vec_u8)vec_splat_u8(0); vec_s16 shorts1, shorts2; @@ -166,17 +165,19 @@ static void diff_pixels_altivec(int16_t *restrict block, const uint8_t *s1, /* Read potentially unaligned pixels. * We're reading 16 pixels, and actually only want 8, * but we simply ignore the extras. */ + perm = vec_lvsl(0, s1); vec_u8 pixl = vec_ld(0, s1); vec_u8 pixr = vec_ld(15, s1); - vec_u8 bytes = vec_perm(pixl, pixr, perm1); + vec_u8 bytes = vec_perm(pixl, pixr, perm); // Convert the bytes into shorts. shorts1 = (vec_s16)vec_mergeh(zero, bytes); // Do the same for the second block of pixels. + perm = vec_lvsl(0, s2); pixl = vec_ld(0, s2); pixr = vec_ld(15, s2); - bytes = vec_perm(pixl, pixr, perm2); + bytes = vec_perm(pixl, pixr, perm); // Convert the bytes into shorts. shorts2 = (vec_s16)vec_mergeh(zero, bytes); @@ -197,17 +198,19 @@ static void diff_pixels_altivec(int16_t *restrict block, const uint8_t *s1, /* Read potentially unaligned pixels. * We're reading 16 pixels, and actually only want 8, * but we simply ignore the extras. */ + perm = vec_lvsl(0, s1); pixl = vec_ld(0, s1); pixr = vec_ld(15, s1); - bytes = vec_perm(pixl, pixr, perm1); + bytes = vec_perm(pixl, pixr, perm); // Convert the bytes into shorts. shorts1 = (vec_s16)vec_mergeh(zero, bytes); // Do the same for the second block of pixels. + perm = vec_lvsl(0, s2); pixl = vec_ld(0, s2); pixr = vec_ld(15, s2); - bytes = vec_perm(pixl, pixr, perm2); + bytes = vec_perm(pixl, pixr, perm); // Convert the bytes into shorts. shorts2 = (vec_s16)vec_mergeh(zero, bytes); diff --git a/libavcodec/proresdec2.c b/libavcodec/proresdec2.c index 2d47a13030..a1d783d243 100644 --- a/libavcodec/proresdec2.c +++ b/libavcodec/proresdec2.c @@ -267,6 +267,8 @@ static int decode_picture_header(AVCodecContext *avctx, const uint8_t *buf, cons \ if (q > switch_bits) { /* exp golomb */ \ bits = exp_order - switch_bits + (q<<1); \ + if (bits > FFMIN(MIN_CACHE_BITS, 31)) \ + return AVERROR_INVALIDDATA; \ val = SHOW_UBITS(re, gb, bits) - (1 << exp_order) + \ ((switch_bits + 1) << rice_order); \ SKIP_BITS(re, gb, bits); \ @@ -286,7 +288,7 @@ static int decode_picture_header(AVCodecContext *avctx, const uint8_t *buf, cons static const uint8_t dc_codebook[7] = { 0x04, 0x28, 0x28, 0x4D, 0x4D, 0x70, 0x70}; -static av_always_inline void decode_dc_coeffs(GetBitContext *gb, int16_t *out, +static av_always_inline int decode_dc_coeffs(GetBitContext *gb, int16_t *out, int blocks_per_slice) { int16_t prev_dc; @@ -310,6 +312,7 @@ static av_always_inline void decode_dc_coeffs(GetBitContext *gb, int16_t *out, out[0] = prev_dc; } CLOSE_READER(re, gb); + return 0; } // adaptive codebook switching lut according to previous run/level values @@ -376,7 +379,8 @@ static int decode_slice_luma(AVCodecContext *avctx, SliceContext *slice, init_get_bits(&gb, buf, buf_size << 3); - decode_dc_coeffs(&gb, blocks, blocks_per_slice); + if ((ret = decode_dc_coeffs(&gb, blocks, blocks_per_slice)) < 0) + return ret; if ((ret = decode_ac_coeffs(avctx, &gb, blocks, blocks_per_slice)) < 0) return ret; @@ -409,7 +413,8 @@ static int decode_slice_chroma(AVCodecContext *avctx, SliceContext *slice, init_get_bits(&gb, buf, buf_size << 3); - decode_dc_coeffs(&gb, blocks, blocks_per_slice); + if ((ret = decode_dc_coeffs(&gb, blocks, blocks_per_slice)) < 0) + return ret; if ((ret = decode_ac_coeffs(avctx, &gb, blocks, blocks_per_slice)) < 0) return ret; diff --git a/libavcodec/proresdec_lgpl.c b/libavcodec/proresdec_lgpl.c index 467a423f23..bc5bdb5a4d 100644 --- a/libavcodec/proresdec_lgpl.c +++ b/libavcodec/proresdec_lgpl.c @@ -625,7 +625,7 @@ static int decode_slice(AVCodecContext *avctx, void *tdata) /* if V or alpha component size is negative that means that previous component sizes are too large */ - if (v_data_size < 0 || a_data_size < 0 || hdr_size < 6) { + if (v_data_size < 0 || a_data_size < 0 || hdr_size < 6 || coff[3] > slice_data_size) { av_log(avctx, AV_LOG_ERROR, "invalid data size\n"); return AVERROR_INVALIDDATA; } diff --git a/libavcodec/qdrw.c b/libavcodec/qdrw.c index 0a31b41660..a7ea45fced 100644 --- a/libavcodec/qdrw.c +++ b/libavcodec/qdrw.c @@ -55,6 +55,8 @@ static int parse_palette(AVCodecContext *avctx, GetByteContext *gbc, bytestream2_skip(gbc, 6); continue; } + if (avctx->pix_fmt != AV_PIX_FMT_PAL8) + return AVERROR_INVALIDDATA; r = bytestream2_get_byte(gbc); bytestream2_skip(gbc, 1); g = bytestream2_get_byte(gbc); @@ -227,7 +229,9 @@ static int decode_frame(AVCodecContext *avctx, if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; - parse_palette(avctx, &gbc, (uint32_t *)p->data[1], colors); + ret = parse_palette(avctx, &gbc, (uint32_t *)p->data[1], colors); + if (ret < 0) + return ret; p->palette_has_changed = 1; /* jump to image data */ diff --git a/libavcodec/qpeg.c b/libavcodec/qpeg.c index 9eaf9b8054..9bfecc3a31 100644 --- a/libavcodec/qpeg.c +++ b/libavcodec/qpeg.c @@ -260,7 +260,8 @@ static int decode_frame(AVCodecContext *avctx, AVFrame * const ref = a->ref; uint8_t* outdata; int delta, ret; - const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL); + int pal_size; + const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, &pal_size); if (avpkt->size < 0x86) { av_log(avctx, AV_LOG_ERROR, "Packet is too small\n"); @@ -287,9 +288,11 @@ static int decode_frame(AVCodecContext *avctx, } /* make the palette available on the way out */ - if (pal) { + if (pal && pal_size == AVPALETTE_SIZE) { p->palette_has_changed = 1; memcpy(a->pal, pal, AVPALETTE_SIZE); + } else if (pal) { + av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", pal_size); } memcpy(p->data[1], a->pal, AVPALETTE_SIZE); diff --git a/libavcodec/qtrle.c b/libavcodec/qtrle.c index 3f482f4453..13b167f089 100644 --- a/libavcodec/qtrle.c +++ b/libavcodec/qtrle.c @@ -155,6 +155,8 @@ static inline void qtrle_decode_2n4bpp(QtrleContext *s, int row_ptr, CHECK_PIXEL_PTR(0); while ((rle_code = (int8_t)bytestream2_get_byte(&s->g)) != -1) { + if (bytestream2_get_bytes_left(&s->g) < 1) + return; if (rle_code == 0) { /* there's another skip code in the stream */ pixel_ptr += (num_pixels * (bytestream2_get_byte(&s->g) - 1)); @@ -210,6 +212,8 @@ static void qtrle_decode_8bpp(QtrleContext *s, int row_ptr, int lines_to_change) CHECK_PIXEL_PTR(0); while ((rle_code = (int8_t)bytestream2_get_byte(&s->g)) != -1) { + if (bytestream2_get_bytes_left(&s->g) < 1) + return; if (rle_code == 0) { /* there's another skip code in the stream */ pixel_ptr += (4 * (bytestream2_get_byte(&s->g) - 1)); @@ -259,6 +263,8 @@ static void qtrle_decode_16bpp(QtrleContext *s, int row_ptr, int lines_to_change CHECK_PIXEL_PTR(0); while ((rle_code = (int8_t)bytestream2_get_byte(&s->g)) != -1) { + if (bytestream2_get_bytes_left(&s->g) < 1) + return; if (rle_code == 0) { /* there's another skip code in the stream */ pixel_ptr += (bytestream2_get_byte(&s->g) - 1) * 2; @@ -303,6 +309,8 @@ static void qtrle_decode_24bpp(QtrleContext *s, int row_ptr, int lines_to_change CHECK_PIXEL_PTR(0); while ((rle_code = (int8_t)bytestream2_get_byte(&s->g)) != -1) { + if (bytestream2_get_bytes_left(&s->g) < 1) + return; if (rle_code == 0) { /* there's another skip code in the stream */ pixel_ptr += (bytestream2_get_byte(&s->g) - 1) * 3; @@ -350,6 +358,8 @@ static void qtrle_decode_32bpp(QtrleContext *s, int row_ptr, int lines_to_change CHECK_PIXEL_PTR(0); while ((rle_code = (int8_t)bytestream2_get_byte(&s->g)) != -1) { + if (bytestream2_get_bytes_left(&s->g) < 1) + return; if (rle_code == 0) { /* there's another skip code in the stream */ pixel_ptr += (bytestream2_get_byte(&s->g) - 1) * 4; @@ -506,11 +516,14 @@ static int qtrle_decode_frame(AVCodecContext *avctx, } if(has_palette) { - const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL); + int size; + const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, &size); - if (pal) { + if (pal && size == AVPALETTE_SIZE) { s->frame->palette_has_changed = 1; memcpy(s->pal, pal, AVPALETTE_SIZE); + } else if (pal) { + av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", size); } /* make the palette available on the way out */ diff --git a/libavcodec/ra144.c b/libavcodec/ra144.c index 696a49e7ab..3393d7a87f 100644 --- a/libavcodec/ra144.c +++ b/libavcodec/ra144.c @@ -1512,11 +1512,11 @@ static void add_wav(int16_t *dest, int n, int skip_first, int *m, v[0] = 0; for (i=!skip_first; i<3; i++) - v[i] = (ff_gain_val_tab[n][i] * m[i]) >> ff_gain_exp_tab[n]; + v[i] = (ff_gain_val_tab[n][i] * (unsigned)m[i]) >> ff_gain_exp_tab[n]; if (v[0]) { for (i=0; i < BLOCKSIZE; i++) - dest[i] = (s1[i]*v[0] + s2[i]*v[1] + s3[i]*v[2]) >> 12; + dest[i] = (int)((s1[i]*(unsigned)v[0]) + s2[i]*v[1] + s3[i]*v[2]) >> 12; } else { for (i=0; i < BLOCKSIZE; i++) dest[i] = ( s2[i]*v[1] + s3[i]*v[2]) >> 12; @@ -1569,11 +1569,11 @@ int ff_eval_refl(int *refl, const int16_t *coefs, AVCodecContext *avctx) b = 0x1000000 / b; for (j=0; j <= i; j++) { #if CONFIG_FTRAPV - int a = bp2[j] - ((refl[i+1] * bp2[i-j]) >> 12); + int a = bp2[j] - ((int)(refl[i+1] * (unsigned)bp2[i-j]) >> 12); if((int)(a*(unsigned)b) != a*(int64_t)b) return 1; #endif - bp1[j] = ((bp2[j] - ((refl[i+1] * bp2[i-j]) >> 12)) * b) >> 12; + bp1[j] = (int)((bp2[j] - ((int)(refl[i+1] * (unsigned)bp2[i-j]) >> 12)) * (unsigned)b) >> 12; } if ((unsigned) bp1[i] + 0x1000 > 0x1fff) @@ -1598,10 +1598,10 @@ void ff_eval_coefs(int *coefs, const int *refl) int i, j; for (i=0; i < LPC_ORDER; i++) { - b1[i] = refl[i] << 4; + b1[i] = refl[i] * 16; for (j=0; j < i; j++) - b1[j] = ((refl[i] * b2[i-j-1]) >> 12) + b2[j]; + b1[j] = ((int)(refl[i] * (unsigned)b2[i-j-1]) >> 12) + b2[j]; FFSWAP(int *, b1, b2); } @@ -1701,7 +1701,7 @@ void ff_subblock_synthesis(RA144Context *ractx, const int16_t *lpc_coefs, if (cba_idx) { cba_idx += BLOCKSIZE/2 - 1; ff_copy_and_dup(ractx->buffer_a, ractx->adapt_cb, cba_idx); - m[0] = (ff_irms(&ractx->adsp, ractx->buffer_a) * gval) >> 12; + m[0] = (ff_irms(&ractx->adsp, ractx->buffer_a) * (unsigned)gval) >> 12; } else { m[0] = 0; } diff --git a/libavcodec/ra144dec.c b/libavcodec/ra144dec.c index 3eed17c0da..c716c32e67 100644 --- a/libavcodec/ra144dec.c +++ b/libavcodec/ra144dec.c @@ -113,7 +113,7 @@ static int ra144_decode_frame(AVCodecContext * avctx, void *data, do_output_subblock(ractx, block_coefs[i], refl_rms[i], &gb); for (j=0; j < BLOCKSIZE; j++) - *samples++ = av_clip_int16(ractx->curr_sblock[j + 10] << 2); + *samples++ = av_clip_int16(ractx->curr_sblock[j + 10] * (1 << 2)); } ractx->old_energy = energy; diff --git a/libavcodec/raw.c b/libavcodec/raw.c index bfa2537b5a..d36b68bfae 100644 --- a/libavcodec/raw.c +++ b/libavcodec/raw.c @@ -31,6 +31,7 @@ const PixelFormatTag ff_raw_pix_fmt_tags[] = { { AV_PIX_FMT_YUV420P, MKTAG('I', '4', '2', '0') }, /* Planar formats */ { AV_PIX_FMT_YUV420P, MKTAG('I', 'Y', 'U', 'V') }, + { AV_PIX_FMT_YUV420P, MKTAG('y', 'v', '1', '2') }, { AV_PIX_FMT_YUV420P, MKTAG('Y', 'V', '1', '2') }, { AV_PIX_FMT_YUV410P, MKTAG('Y', 'U', 'V', '9') }, { AV_PIX_FMT_YUV410P, MKTAG('Y', 'V', 'U', '9') }, diff --git a/libavcodec/rawdec.c b/libavcodec/rawdec.c index 287be96955..fbdf4810fa 100644 --- a/libavcodec/rawdec.c +++ b/libavcodec/rawdec.c @@ -223,8 +223,9 @@ static int raw_decode(AVCodecContext *avctx, void *data, int *got_frame, } desc = av_pix_fmt_desc_get(avctx->pix_fmt); - if ((avctx->bits_per_coded_sample == 8 || avctx->bits_per_coded_sample == 4 - || avctx->bits_per_coded_sample <= 2) && + if ((avctx->bits_per_coded_sample == 8 || avctx->bits_per_coded_sample == 4 || + avctx->bits_per_coded_sample == 2 || avctx->bits_per_coded_sample == 1 || + (avctx->bits_per_coded_sample == 0 && (context->is_nut_pal8 || context->is_mono)) ) && (context->is_mono || context->is_pal8) && (!avctx->codec_tag || avctx->codec_tag == MKTAG('r','a','w',' ') || context->is_nut_mono || context->is_nut_pal8)) { @@ -382,8 +383,13 @@ static int raw_decode(AVCodecContext *avctx, void *data, int *got_frame, } if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { + int pal_size; const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, - NULL); + &pal_size); + if (pal && pal_size != AVPALETTE_SIZE) { + av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", pal_size); + pal = NULL; + } if (pal) { av_buffer_unref(&context->palette); diff --git a/libavcodec/resample.c b/libavcodec/resample.c index 0f5ee84942..4c5eb9f10e 100644 --- a/libavcodec/resample.c +++ b/libavcodec/resample.c @@ -291,12 +291,6 @@ int audio_resample(ReSampleContext *s, short *output, short *input, int nb_sampl short *output_bak = NULL; int lenout; - if (s->input_channels == s->output_channels && s->ratio == 1.0 && 0) { - /* nothing to do */ - memcpy(output, input, nb_samples * s->input_channels * sizeof(short)); - return nb_samples; - } - if (s->sample_fmt[0] != AV_SAMPLE_FMT_S16) { int istride[1] = { s->sample_size[0] }; int ostride[1] = { 2 }; diff --git a/libavcodec/rscc.c b/libavcodec/rscc.c index a2f7a0dc7c..78a8bcea0b 100644 --- a/libavcodec/rscc.c +++ b/libavcodec/rscc.c @@ -184,6 +184,12 @@ static int rscc_decode_frame(AVCodecContext *avctx, void *data, ctx->tiles[i].y = bytestream2_get_le16(gbc); ctx->tiles[i].h = bytestream2_get_le16(gbc); + if (pixel_size + ctx->tiles[i].w * (int64_t)ctx->tiles[i].h * 4 > INT_MAX) { + av_log(avctx, AV_LOG_ERROR, "Invalid tile dimensions\n"); + ret = AVERROR_INVALIDDATA; + goto end; + } + pixel_size += ctx->tiles[i].w * ctx->tiles[i].h * 4; ff_dlog(avctx, "tile %d orig(%d,%d) %dx%d.\n", i, @@ -223,6 +229,12 @@ static int rscc_decode_frame(AVCodecContext *avctx, void *data, ff_dlog(avctx, "pixel_size %d packed_size %d.\n", pixel_size, packed_size); + if (packed_size < 0) { + av_log(avctx, AV_LOG_ERROR, "Invalid tile size %d\n", packed_size); + ret = AVERROR_INVALIDDATA; + goto end; + } + /* Get pixels buffer, it may be deflated or just raw */ if (pixel_size == packed_size) { if (bytestream2_get_bytes_left(gbc) < pixel_size) { @@ -233,6 +245,11 @@ static int rscc_decode_frame(AVCodecContext *avctx, void *data, pixels = gbc->buffer; } else { uLongf len = ctx->inflated_size; + if (bytestream2_get_bytes_left(gbc) < packed_size) { + av_log(avctx, AV_LOG_ERROR, "Insufficient input for %d\n", packed_size); + ret = AVERROR_INVALIDDATA; + goto end; + } ret = uncompress(ctx->inflated_buf, &len, gbc->buffer, packed_size); if (ret) { av_log(avctx, AV_LOG_ERROR, "Pixel deflate error %d.\n", ret); diff --git a/libavcodec/rv34.c b/libavcodec/rv34.c index c2e84a3b57..3a6faae87b 100644 --- a/libavcodec/rv34.c +++ b/libavcodec/rv34.c @@ -1579,16 +1579,19 @@ int ff_rv34_decode_update_thread_context(AVCodecContext *dst, const AVCodecConte // Do no call ff_mpeg_update_thread_context on a partially initialized // decoder context. - if (!s1->linesize) + if (!s1->context_initialized) return 0; return ff_mpeg_update_thread_context(dst, src); } -static int get_slice_offset(AVCodecContext *avctx, const uint8_t *buf, int n) +static int get_slice_offset(AVCodecContext *avctx, const uint8_t *buf, int n, int slice_count, int buf_size) { - if(avctx->slice_count) return avctx->slice_offset[n]; - else return AV_RL32(buf + n*8 - 4) == 1 ? AV_RL32(buf + n*8) : AV_RB32(buf + n*8); + if (n < slice_count) { + if(avctx->slice_count) return avctx->slice_offset[n]; + else return AV_RL32(buf + n*8 - 4) == 1 ? AV_RL32(buf + n*8) : AV_RB32(buf + n*8); + } else + return buf_size; } static int finish_frame(AVCodecContext *avctx, AVFrame *pict) @@ -1627,7 +1630,7 @@ static AVRational update_sar(int old_w, int old_h, AVRational sar, int new_w, in if (!sar.num) sar = (AVRational){1, 1}; - sar = av_mul_q(sar, (AVRational){new_h * old_w, new_w * old_h}); + sar = av_mul_q(sar, av_mul_q((AVRational){new_h, new_w}, (AVRational){old_w, old_h})); return sar; } @@ -1646,6 +1649,7 @@ int ff_rv34_decode_frame(AVCodecContext *avctx, const uint8_t *slices_hdr = NULL; int last = 0; int faulty_b = 0; + int offset; /* no supplementary picture */ if (buf_size == 0) { @@ -1668,13 +1672,13 @@ int ff_rv34_decode_frame(AVCodecContext *avctx, }else slice_count = avctx->slice_count; + offset = get_slice_offset(avctx, slices_hdr, 0, slice_count, buf_size); //parse first slice header to check whether this frame can be decoded - if(get_slice_offset(avctx, slices_hdr, 0) < 0 || - get_slice_offset(avctx, slices_hdr, 0) > buf_size){ + if(offset < 0 || offset > buf_size){ av_log(avctx, AV_LOG_ERROR, "Slice offset is invalid\n"); return AVERROR_INVALIDDATA; } - init_get_bits(&s->gb, buf+get_slice_offset(avctx, slices_hdr, 0), (buf_size-get_slice_offset(avctx, slices_hdr, 0))*8); + init_get_bits(&s->gb, buf+offset, (buf_size-offset)*8); if(r->parse_slice_header(r, &r->s.gb, &si) < 0 || si.start){ av_log(avctx, AV_LOG_ERROR, "First slice header is incorrect\n"); return AVERROR_INVALIDDATA; @@ -1723,6 +1727,8 @@ int ff_rv34_decode_frame(AVCodecContext *avctx, if ((err = rv34_decoder_realloc(r)) < 0) return err; } + if (faulty_b) + return AVERROR_INVALIDDATA; s->pict_type = si.type ? si.type : AV_PICTURE_TYPE_I; if (ff_mpv_frame_start(s, s->avctx) < 0) return -1; @@ -1773,44 +1779,34 @@ int ff_rv34_decode_frame(AVCodecContext *avctx, "multithreading mode (start MB is %d).\n", si.start); return AVERROR_INVALIDDATA; } - if (faulty_b) - return AVERROR_INVALIDDATA; for(i = 0; i < slice_count; i++){ - int offset = get_slice_offset(avctx, slices_hdr, i); + int offset = get_slice_offset(avctx, slices_hdr, i , slice_count, buf_size); + int offset1 = get_slice_offset(avctx, slices_hdr, i+1, slice_count, buf_size); int size; - if(i+1 == slice_count) - size = buf_size - offset; - else - size = get_slice_offset(avctx, slices_hdr, i+1) - offset; - if(offset < 0 || offset > buf_size){ + if(offset < 0 || offset > offset1 || offset1 > buf_size){ av_log(avctx, AV_LOG_ERROR, "Slice offset is invalid\n"); break; } + size = offset1 - offset; r->si.end = s->mb_width * s->mb_height; s->mb_num_left = r->s.mb_x + r->s.mb_y*r->s.mb_width - r->si.start; if(i+1 < slice_count){ - if (get_slice_offset(avctx, slices_hdr, i+1) < 0 || - get_slice_offset(avctx, slices_hdr, i+1) > buf_size) { + int offset2 = get_slice_offset(avctx, slices_hdr, i+2, slice_count, buf_size); + if (offset2 < offset1 || offset2 > buf_size) { av_log(avctx, AV_LOG_ERROR, "Slice offset is invalid\n"); break; } - init_get_bits(&s->gb, buf+get_slice_offset(avctx, slices_hdr, i+1), (buf_size-get_slice_offset(avctx, slices_hdr, i+1))*8); + init_get_bits(&s->gb, buf+offset1, (buf_size-offset1)*8); if(r->parse_slice_header(r, &r->s.gb, &si) < 0){ - if(i+2 < slice_count) - size = get_slice_offset(avctx, slices_hdr, i+2) - offset; - else - size = buf_size - offset; + size = offset2 - offset; }else r->si.end = si.start; } - if (size < 0 || size > buf_size - offset) { - av_log(avctx, AV_LOG_ERROR, "Slice size is invalid\n"); - break; - } + av_assert0 (size >= 0 && size <= buf_size - offset); last = rv34_decode_slice(r, r->si.end, buf + offset, size); if(last) break; diff --git a/libavcodec/rv40.c b/libavcodec/rv40.c index 3ff1554d3c..e4c8400268 100644 --- a/libavcodec/rv40.c +++ b/libavcodec/rv40.c @@ -109,6 +109,8 @@ static int get_dimension(GetBitContext *gb, const int *dim) val = dim[get_bits1(gb) - val]; if(!val){ do{ + if (get_bits_left(gb) < 8) + return AVERROR_INVALIDDATA; t = get_bits(gb, 8); val += t << 2; }while(t == 0xFF); @@ -187,7 +189,7 @@ static int rv40_decode_intra_types(RV34DecContext *r, GetBitContext *gb, int8_t A = ptr[-r->intra_types_stride + 1]; // it won't be used for the last coefficient in a row B = ptr[-r->intra_types_stride]; C = ptr[-1]; - pattern = A + (B << 4) + (C << 8); + pattern = A + B * (1 << 4) + C * (1 << 8); for(k = 0; k < MODE2_PATTERNS_NUM; k++) if(pattern == rv40_aic_table_index[k]) break; diff --git a/libavcodec/rv40dsp.c b/libavcodec/rv40dsp.c index 19b0e93696..95ba0a9259 100644 --- a/libavcodec/rv40dsp.c +++ b/libavcodec/rv40dsp.c @@ -449,7 +449,7 @@ static av_always_inline void rv40_weak_loop_filter(uint8_t *src, if (u > 3 - (filter_p1 && filter_q1)) continue; - t <<= 2; + t *= 1 << 2; if (filter_p1 && filter_q1) t += src[-2*step] - src[1*step]; diff --git a/libavcodec/s302m.c b/libavcodec/s302m.c index ccfb5913a0..a68ac79f2c 100644 --- a/libavcodec/s302m.c +++ b/libavcodec/s302m.c @@ -120,10 +120,10 @@ static int s302m_decode_frame(AVCodecContext *avctx, void *data, if (avctx->bits_per_raw_sample == 24) { uint32_t *o = (uint32_t *)frame->data[0]; for (; buf_size > 6; buf_size -= 7) { - *o++ = (ff_reverse[buf[2]] << 24) | + *o++ = ((unsigned)ff_reverse[buf[2]] << 24) | (ff_reverse[buf[1]] << 16) | (ff_reverse[buf[0]] << 8); - *o++ = (ff_reverse[buf[6] & 0xf0] << 28) | + *o++ = ((unsigned)ff_reverse[buf[6] & 0xf0] << 28) | (ff_reverse[buf[5]] << 20) | (ff_reverse[buf[4]] << 12) | (ff_reverse[buf[3] & 0x0f] << 4); @@ -142,10 +142,10 @@ static int s302m_decode_frame(AVCodecContext *avctx, void *data, } else if (avctx->bits_per_raw_sample == 20) { uint32_t *o = (uint32_t *)frame->data[0]; for (; buf_size > 5; buf_size -= 6) { - *o++ = (ff_reverse[buf[2] & 0xf0] << 28) | + *o++ = ((unsigned)ff_reverse[buf[2] & 0xf0] << 28) | (ff_reverse[buf[1]] << 20) | (ff_reverse[buf[0]] << 12); - *o++ = (ff_reverse[buf[5] & 0xf0] << 28) | + *o++ = ((unsigned)ff_reverse[buf[5] & 0xf0] << 28) | (ff_reverse[buf[4]] << 20) | (ff_reverse[buf[3]] << 12); buf += 6; diff --git a/libavcodec/sanm.c b/libavcodec/sanm.c index 1aa002b6a5..065bf7aca1 100644 --- a/libavcodec/sanm.c +++ b/libavcodec/sanm.c @@ -462,11 +462,11 @@ static void destroy_buffers(SANMVideoContext *ctx) static av_cold int init_buffers(SANMVideoContext *ctx) { - av_fast_padded_malloc(&ctx->frm0, &ctx->frm0_size, ctx->buf_size); - av_fast_padded_malloc(&ctx->frm1, &ctx->frm1_size, ctx->buf_size); - av_fast_padded_malloc(&ctx->frm2, &ctx->frm2_size, ctx->buf_size); + av_fast_padded_mallocz(&ctx->frm0, &ctx->frm0_size, ctx->buf_size); + av_fast_padded_mallocz(&ctx->frm1, &ctx->frm1_size, ctx->buf_size); + av_fast_padded_mallocz(&ctx->frm2, &ctx->frm2_size, ctx->buf_size); if (!ctx->version) - av_fast_padded_malloc(&ctx->stored_frame, + av_fast_padded_mallocz(&ctx->stored_frame, &ctx->stored_frame_size, ctx->buf_size); if (!ctx->frm0 || !ctx->frm1 || !ctx->frm2 || diff --git a/libavcodec/sbrdsp_fixed.c b/libavcodec/sbrdsp_fixed.c index f4e3de0c71..07ef12117c 100644 --- a/libavcodec/sbrdsp_fixed.c +++ b/libavcodec/sbrdsp_fixed.c @@ -136,19 +136,19 @@ static av_always_inline void autocorrelate(const int x[40][2], SoftFloat phi[3][ if (lag) { for (i = 1; i < 38; i++) { - accu_re += (int64_t)x[i][0] * x[i+lag][0]; - accu_re += (int64_t)x[i][1] * x[i+lag][1]; - accu_im += (int64_t)x[i][0] * x[i+lag][1]; - accu_im -= (int64_t)x[i][1] * x[i+lag][0]; + accu_re += (uint64_t)x[i][0] * x[i+lag][0]; + accu_re += (uint64_t)x[i][1] * x[i+lag][1]; + accu_im += (uint64_t)x[i][0] * x[i+lag][1]; + accu_im -= (uint64_t)x[i][1] * x[i+lag][0]; } real_sum = accu_re; imag_sum = accu_im; - accu_re += (int64_t)x[ 0][0] * x[lag][0]; - accu_re += (int64_t)x[ 0][1] * x[lag][1]; - accu_im += (int64_t)x[ 0][0] * x[lag][1]; - accu_im -= (int64_t)x[ 0][1] * x[lag][0]; + accu_re += (uint64_t)x[ 0][0] * x[lag][0]; + accu_re += (uint64_t)x[ 0][1] * x[lag][1]; + accu_im += (uint64_t)x[ 0][0] * x[lag][1]; + accu_im -= (uint64_t)x[ 0][1] * x[lag][0]; phi[2-lag][1][0] = autocorr_calc(accu_re); phi[2-lag][1][1] = autocorr_calc(accu_im); @@ -156,28 +156,28 @@ static av_always_inline void autocorrelate(const int x[40][2], SoftFloat phi[3][ if (lag == 1) { accu_re = real_sum; accu_im = imag_sum; - accu_re += (int64_t)x[38][0] * x[39][0]; - accu_re += (int64_t)x[38][1] * x[39][1]; - accu_im += (int64_t)x[38][0] * x[39][1]; - accu_im -= (int64_t)x[38][1] * x[39][0]; + accu_re += (uint64_t)x[38][0] * x[39][0]; + accu_re += (uint64_t)x[38][1] * x[39][1]; + accu_im += (uint64_t)x[38][0] * x[39][1]; + accu_im -= (uint64_t)x[38][1] * x[39][0]; phi[0][0][0] = autocorr_calc(accu_re); phi[0][0][1] = autocorr_calc(accu_im); } } else { for (i = 1; i < 38; i++) { - accu_re += (int64_t)x[i][0] * x[i][0]; - accu_re += (int64_t)x[i][1] * x[i][1]; + accu_re += (uint64_t)x[i][0] * x[i][0]; + accu_re += (uint64_t)x[i][1] * x[i][1]; } real_sum = accu_re; - accu_re += (int64_t)x[ 0][0] * x[ 0][0]; - accu_re += (int64_t)x[ 0][1] * x[ 0][1]; + accu_re += (uint64_t)x[ 0][0] * x[ 0][0]; + accu_re += (uint64_t)x[ 0][1] * x[ 0][1]; phi[2][1][0] = autocorr_calc(accu_re); accu_re = real_sum; - accu_re += (int64_t)x[38][0] * x[38][0]; - accu_re += (int64_t)x[38][1] * x[38][1]; + accu_re += (uint64_t)x[38][0] * x[38][0]; + accu_re += (uint64_t)x[38][1] * x[38][1]; phi[1][0][0] = autocorr_calc(accu_re); } @@ -229,20 +229,22 @@ static void sbr_hf_gen_c(int (*X_high)[2], const int (*X_low)[2], static void sbr_hf_g_filt_c(int (*Y)[2], const int (*X_high)[40][2], const SoftFloat *g_filt, int m_max, intptr_t ixh) { - int m, r; + int m; int64_t accu; for (m = 0; m < m_max; m++) { - r = 1 << (22-g_filt[m].exp); - accu = (int64_t)X_high[m][ixh][0] * ((g_filt[m].mant + 0x40)>>7); - Y[m][0] = (int)((accu + r) >> (23-g_filt[m].exp)); + if (22 - g_filt[m].exp < 61) { + int64_t r = 1LL << (22-g_filt[m].exp); + accu = (int64_t)X_high[m][ixh][0] * ((g_filt[m].mant + 0x40)>>7); + Y[m][0] = (int)((accu + r) >> (23-g_filt[m].exp)); - accu = (int64_t)X_high[m][ixh][1] * ((g_filt[m].mant + 0x40)>>7); - Y[m][1] = (int)((accu + r) >> (23-g_filt[m].exp)); + accu = (int64_t)X_high[m][ixh][1] * ((g_filt[m].mant + 0x40)>>7); + Y[m][1] = (int)((accu + r) >> (23-g_filt[m].exp)); + } } } -static av_always_inline void sbr_hf_apply_noise(int (*Y)[2], +static av_always_inline int sbr_hf_apply_noise(int (*Y)[2], const SoftFloat *s_m, const SoftFloat *q_filt, int noise, @@ -253,14 +255,17 @@ static av_always_inline void sbr_hf_apply_noise(int (*Y)[2], int m; for (m = 0; m < m_max; m++) { - int y0 = Y[m][0]; - int y1 = Y[m][1]; + unsigned y0 = Y[m][0]; + unsigned y1 = Y[m][1]; noise = (noise + 1) & 0x1ff; if (s_m[m].mant) { int shift, round; shift = 22 - s_m[m].exp; - if (shift < 30) { + if (shift < 1) { + av_log(NULL, AV_LOG_ERROR, "Overflow in sbr_hf_apply_noise, shift=%d\n", shift); + return AVERROR(ERANGE); + } else if (shift < 30) { round = 1 << (shift-1); y0 += (s_m[m].mant * phi_sign0 + round) >> shift; y1 += (s_m[m].mant * phi_sign1 + round) >> shift; @@ -270,7 +275,10 @@ static av_always_inline void sbr_hf_apply_noise(int (*Y)[2], int64_t accu; shift = 22 - q_filt[m].exp; - if (shift < 30) { + if (shift < 1) { + av_log(NULL, AV_LOG_ERROR, "Overflow in sbr_hf_apply_noise, shift=%d\n", shift); + return AVERROR(ERANGE); + } else if (shift < 30) { round = 1 << (shift-1); accu = (int64_t)q_filt[m].mant * ff_sbr_noise_table_fixed[noise][0]; @@ -286,6 +294,7 @@ static av_always_inline void sbr_hf_apply_noise(int (*Y)[2], Y[m][1] = y1; phi_sign1 = -phi_sign1; } + return 0; } #include "sbrdsp_template.c" diff --git a/libavcodec/sbrdsp_template.c b/libavcodec/sbrdsp_template.c index b649dfd7ee..897a3bbffb 100644 --- a/libavcodec/sbrdsp_template.c +++ b/libavcodec/sbrdsp_template.c @@ -33,8 +33,13 @@ static void sbr_qmf_deint_bfly_c(INTFLOAT *v, const INTFLOAT *src0, const INTFLO { int i; for (i = 0; i < 64; i++) { - v[ i] = AAC_SRA_R((src0[i] - src1[63 - i]), 5); - v[127 - i] = AAC_SRA_R((src0[i] + src1[63 - i]), 5); +#if USE_FIXED + v[ i] = (int)(0x10U + src0[i] - src1[63 - i]) >> 5; + v[127 - i] = (int)(0x10U + src0[i] + src1[63 - i]) >> 5; +#else + v[ i] = src0[i] - src1[63 - i]; + v[127 - i] = src0[i] + src1[63 - i]; +#endif } } diff --git a/libavcodec/shorten.c b/libavcodec/shorten.c index 0f5be96eb7..6ec1632aac 100644 --- a/libavcodec/shorten.c +++ b/libavcodec/shorten.c @@ -156,8 +156,11 @@ static int allocate_buffers(ShortenContext *s) static inline unsigned int get_uint(ShortenContext *s, int k) { - if (s->version != 0) + if (s->version != 0) { k = get_ur_golomb_shorten(&s->gb, ULONGSIZE); + if (k > 31U) + return AVERROR_INVALIDDATA; + } return get_ur_golomb_shorten(&s->gb, k); } @@ -310,9 +313,9 @@ static int decode_subframe_lpc(ShortenContext *s, int command, int channel, for (i = 0; i < s->blocksize; i++) { sum = init_sum; for (j = 0; j < pred_order; j++) - sum += coeffs[j] * s->decoded[channel][i - j - 1]; + sum += coeffs[j] * (unsigned)s->decoded[channel][i - j - 1]; s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + - (sum >> qshift); + (unsigned)(sum >> qshift); } /* add offset to current samples */ @@ -366,10 +369,18 @@ static int read_header(ShortenContext *s) s->blocksize = blocksize; maxnlpc = get_uint(s, LPCQSIZE); + if (maxnlpc > 1024U) { + av_log(s->avctx, AV_LOG_ERROR, "maxnlpc is: %d\n", maxnlpc); + return AVERROR_INVALIDDATA; + } s->nmean = get_uint(s, 0); + if (s->nmean > 32768U) { + av_log(s->avctx, AV_LOG_ERROR, "nmean is: %d\n", s->nmean); + return AVERROR_INVALIDDATA; + } skip_bytes = get_uint(s, NSKIPSIZE); - if ((unsigned)skip_bytes > get_bits_left(&s->gb)/8) { + if ((unsigned)skip_bytes > FFMAX(get_bits_left(&s->gb), 0)/8) { av_log(s->avctx, AV_LOG_ERROR, "invalid skip_bytes: %d\n", skip_bytes); return AVERROR_INVALIDDATA; } @@ -507,6 +518,11 @@ static int shorten_decode_frame(AVCodecContext *avctx, void *data, switch (cmd) { case FN_VERBATIM: len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE); + if (len < 0 || len > get_bits_left(&s->gb)) { + av_log(avctx, AV_LOG_ERROR, "verbatim length %d invalid\n", + len); + return AVERROR_INVALIDDATA; + } while (len--) get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE); break; @@ -564,7 +580,7 @@ static int shorten_decode_frame(AVCodecContext *avctx, void *data, else { int32_t sum = (s->version < 2) ? 0 : s->nmean / 2; for (i = 0; i < s->nmean; i++) - sum += s->offset[channel][i]; + sum += (unsigned)s->offset[channel][i]; coffset = sum / s->nmean; if (s->version >= 2) coffset = s->bitshift == 0 ? coffset : coffset >> s->bitshift - 1 >> 1; @@ -582,7 +598,7 @@ static int shorten_decode_frame(AVCodecContext *avctx, void *data, /* update means with info from the current block */ if (s->nmean > 0) { - int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2; + int64_t sum = (s->version < 2) ? 0 : s->blocksize / 2; for (i = 0; i < s->blocksize; i++) sum += s->decoded[channel][i]; diff --git a/libavcodec/smacker.c b/libavcodec/smacker.c index 4014e8d04c..8dc474c42e 100644 --- a/libavcodec/smacker.c +++ b/libavcodec/smacker.c @@ -131,8 +131,12 @@ static int smacker_decode_tree(GetBitContext *gb, HuffContext *hc, uint32_t pref /** * Decode header tree */ -static int smacker_decode_bigtree(GetBitContext *gb, HuffContext *hc, DBCtx *ctx) +static int smacker_decode_bigtree(GetBitContext *gb, HuffContext *hc, DBCtx *ctx, int length) { + if(length > 500) { // Larger length can cause segmentation faults due to too deep recursion. + av_log(NULL, AV_LOG_ERROR, "length too long\n"); + return AVERROR_INVALIDDATA; + } if (hc->current + 1 >= hc->length) { av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n"); return AVERROR_INVALIDDATA; @@ -161,12 +165,12 @@ static int smacker_decode_bigtree(GetBitContext *gb, HuffContext *hc, DBCtx *ctx int r = 0, r_new, t; t = hc->current++; - r = smacker_decode_bigtree(gb, hc, ctx); + r = smacker_decode_bigtree(gb, hc, ctx, length + 1); if(r < 0) return r; hc->values[t] = SMK_NODE | r; r++; - r_new = smacker_decode_bigtree(gb, hc, ctx); + r_new = smacker_decode_bigtree(gb, hc, ctx, length + 1); if (r_new < 0) return r_new; return r + r_new; @@ -277,7 +281,7 @@ static int smacker_decode_header_tree(SmackVContext *smk, GetBitContext *gb, int goto error; } - if (smacker_decode_bigtree(gb, &huff, &ctx) < 0) + if (smacker_decode_bigtree(gb, &huff, &ctx, 0) < 0) err = -1; skip_bits1(gb); if(ctx.last[0] == -1) ctx.last[0] = huff.current++; diff --git a/libavcodec/smc.c b/libavcodec/smc.c index a423c455cc..66de691e2c 100644 --- a/libavcodec/smc.c +++ b/libavcodec/smc.c @@ -132,6 +132,10 @@ static void smc_decode_stream(SmcContext *s) row_ptr, image_size); return; } + if (bytestream2_get_bytes_left(&s->gb) < 1) { + av_log(s->avctx, AV_LOG_ERROR, "input too small\n"); + return; + } opcode = bytestream2_get_byte(&s->gb); switch (opcode & 0xF0) { @@ -433,6 +437,10 @@ static int smc_decode_frame(AVCodecContext *avctx, SmcContext *s = avctx->priv_data; const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL); int ret; + int total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4); + + if (total_blocks / 1024 > avpkt->size) + return AVERROR_INVALIDDATA; bytestream2_init(&s->gb, buf, buf_size); diff --git a/libavcodec/smvjpegdec.c b/libavcodec/smvjpegdec.c index 9057e86161..e319e5781b 100644 --- a/libavcodec/smvjpegdec.c +++ b/libavcodec/smvjpegdec.c @@ -152,6 +152,10 @@ static int smvjpeg_decode_frame(AVCodecContext *avctx, void *data, int *data_siz cur_frame = avpkt->pts % s->frames_per_jpeg; + /* cur_frame is later used to calculate the buffer offset, so it mustn't be negative */ + if (cur_frame < 0) + cur_frame += s->frames_per_jpeg; + /* Are we at the start of a block? */ if (!cur_frame) { av_frame_unref(mjpeg_data); diff --git a/libavcodec/snow.h b/libavcodec/snow.h index d126d68a49..7b5cf9418c 100644 --- a/libavcodec/snow.h +++ b/libavcodec/snow.h @@ -564,7 +564,8 @@ static inline int get_symbol(RangeCoder *c, uint8_t *state, int is_signed){ if(get_rac(c, state+0)) return 0; else{ - int i, e, a; + int i, e; + unsigned a; e= 0; while(get_rac(c, state+1 + FFMIN(e,9))){ //1..10 e++; diff --git a/libavcodec/snowdec.c b/libavcodec/snowdec.c index 042aecbbeb..a9fe91d251 100644 --- a/libavcodec/snowdec.c +++ b/libavcodec/snowdec.c @@ -140,7 +140,7 @@ static inline void decode_subband_slice_buffered(SnowContext *s, SubBand *b, sli v = b->x_coeff[new_index].coeff; x = b->x_coeff[new_index++].x; while(x < w){ - register int t= ( (v>>1)*qmul + qadd)>>QEXPSHIFT; + register int t= (int)( (v>>1)*(unsigned)qmul + qadd)>>QEXPSHIFT; register int u= -(v&1); line[x] = (t^u) - u; @@ -183,13 +183,22 @@ static int decode_q_branch(SnowContext *s, int level, int x, int y){ int my_context= av_log2(2*FFABS(left->my - top->my)) + 0*av_log2(2*FFABS(tr->my - top->my)); type= get_rac(&s->c, &s->block_state[1 + left->type + top->type]) ? BLOCK_INTRA : 0; - if(type){ + int ld, cbd, crd; pred_mv(s, &mx, &my, 0, left, top, tr); - l += get_symbol(&s->c, &s->block_state[32], 1); + ld = get_symbol(&s->c, &s->block_state[32], 1); + if (ld < -255 || ld > 255) { + return AVERROR_INVALIDDATA; + } + l += ld; if (s->nb_planes > 2) { - cb+= get_symbol(&s->c, &s->block_state[64], 1); - cr+= get_symbol(&s->c, &s->block_state[96], 1); + cbd = get_symbol(&s->c, &s->block_state[64], 1); + crd = get_symbol(&s->c, &s->block_state[96], 1); + if (cbd < -255 || cbd > 255 || crd < -255 || crd > 255) { + return AVERROR_INVALIDDATA; + } + cb += cbd; + cr += crd; } }else{ if(s->ref_frames > 1) @@ -199,8 +208,8 @@ static int decode_q_branch(SnowContext *s, int level, int x, int y){ return AVERROR_INVALIDDATA; } pred_mv(s, &mx, &my, ref, left, top, tr); - mx+= get_symbol(&s->c, &s->block_state[128 + 32*(mx_context + 16*!!ref)], 1); - my+= get_symbol(&s->c, &s->block_state[128 + 32*(my_context + 16*!!ref)], 1); + mx+= (unsigned)get_symbol(&s->c, &s->block_state[128 + 32*(mx_context + 16*!!ref)], 1); + my+= (unsigned)get_symbol(&s->c, &s->block_state[128 + 32*(my_context + 16*!!ref)], 1); } set_blocks(s, level, x, y, l, cb, cr, mx, my, ref, type); }else{ @@ -354,9 +363,10 @@ static int decode_header(SnowContext *s){ int htaps, i, sum=0; Plane *p= &s->plane[plane_index]; p->diag_mc= get_rac(&s->c, s->header_state); - htaps= get_symbol(&s->c, s->header_state, 0)*2 + 2; - if((unsigned)htaps > HTAPS_MAX || htaps==0) + htaps= get_symbol(&s->c, s->header_state, 0); + if((unsigned)htaps >= HTAPS_MAX/2 - 1) return AVERROR_INVALIDDATA; + htaps = htaps*2 + 2; p->htaps= htaps; for(i= htaps/2; i; i--){ p->hcoeff[i]= get_symbol(&s->c, s->header_state, 0) * (1-2*(i&1)); @@ -374,7 +384,7 @@ static int decode_header(SnowContext *s){ } } - s->spatial_decomposition_type+= get_symbol(&s->c, s->header_state, 1); + s->spatial_decomposition_type+= (unsigned)get_symbol(&s->c, s->header_state, 1); if(s->spatial_decomposition_type > 1U){ av_log(s->avctx, AV_LOG_ERROR, "spatial_decomposition_type %d not supported\n", s->spatial_decomposition_type); return AVERROR_INVALIDDATA; @@ -384,15 +394,25 @@ static int decode_header(SnowContext *s){ av_log(s->avctx, AV_LOG_ERROR, "spatial_decomposition_count %d too large for size\n", s->spatial_decomposition_count); return AVERROR_INVALIDDATA; } + if (s->avctx->width > 65536-4) { + av_log(s->avctx, AV_LOG_ERROR, "Width %d is too large\n", s->avctx->width); + return AVERROR_INVALIDDATA; + } - s->qlog += get_symbol(&s->c, s->header_state, 1); - s->mv_scale += get_symbol(&s->c, s->header_state, 1); - s->qbias += get_symbol(&s->c, s->header_state, 1); - s->block_max_depth+= get_symbol(&s->c, s->header_state, 1); - if(s->block_max_depth > 1 || s->block_max_depth < 0){ + s->qlog += (unsigned)get_symbol(&s->c, s->header_state, 1); + s->mv_scale += (unsigned)get_symbol(&s->c, s->header_state, 1); + s->qbias += (unsigned)get_symbol(&s->c, s->header_state, 1); + s->block_max_depth+= (unsigned)get_symbol(&s->c, s->header_state, 1); + if(s->block_max_depth > 1 || s->block_max_depth < 0 || s->mv_scale > 256U){ av_log(s->avctx, AV_LOG_ERROR, "block_max_depth= %d is too large\n", s->block_max_depth); s->block_max_depth= 0; + s->mv_scale = 0; + return AVERROR_INVALIDDATA; + } + if (FFABS(s->qbias) > 127) { + av_log(s->avctx, AV_LOG_ERROR, "qbias %d is too large\n", s->qbias); + s->qbias = 0; return AVERROR_INVALIDDATA; } @@ -418,6 +438,8 @@ static int decode_blocks(SnowContext *s){ for(y=0; yc.bytestream >= s->c.bytestream_end) + return AVERROR_INVALIDDATA; if ((res = decode_q_branch(s, 0, x, y)) < 0) return res; } @@ -577,7 +599,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, for(; yqsb, yq); for(x=0; x> 20; - output[stride * 2 + offset] = (z1 + z2) * qmul + 0x80000 >> 20; - output[stride * 8 + offset] = (z1 - z2) * qmul + 0x80000 >> 20; - output[stride * 10 + offset] = (z0 - z3) * qmul + 0x80000 >> 20; + output[stride * 0 + offset] = (int)((z0 + z3) * qmul + 0x80000) >> 20; + output[stride * 2 + offset] = (int)((z1 + z2) * qmul + 0x80000) >> 20; + output[stride * 8 + offset] = (int)((z1 - z2) * qmul + 0x80000) >> 20; + output[stride * 10 + offset] = (int)((z0 - z3) * qmul + 0x80000) >> 20; } } #undef stride @@ -206,7 +206,7 @@ void ff_svq3_add_idct_c(uint8_t *dst, int16_t *block, int i; if (dc) { - dc = 13 * 13 * (dc == 1 ? 1538 * block[0] + dc = 13 * 13 * (dc == 1 ? 1538U* block[0] : qmul * (block[0] >> 3) / 2); block[0] = 0; } @@ -224,16 +224,16 @@ void ff_svq3_add_idct_c(uint8_t *dst, int16_t *block, } for (i = 0; i < 4; i++) { - const int z0 = 13 * (block[i + 4 * 0] + block[i + 4 * 2]); - const int z1 = 13 * (block[i + 4 * 0] - block[i + 4 * 2]); - const int z2 = 7 * block[i + 4 * 1] - 17 * block[i + 4 * 3]; - const int z3 = 17 * block[i + 4 * 1] + 7 * block[i + 4 * 3]; - const int rr = (dc + 0x80000); + const unsigned z0 = 13 * (block[i + 4 * 0] + block[i + 4 * 2]); + const unsigned z1 = 13 * (block[i + 4 * 0] - block[i + 4 * 2]); + const unsigned z2 = 7 * block[i + 4 * 1] - 17 * block[i + 4 * 3]; + const unsigned z3 = 17 * block[i + 4 * 1] + 7 * block[i + 4 * 3]; + const int rr = (dc + 0x80000u); - dst[i + stride * 0] = av_clip_uint8(dst[i + stride * 0] + ((z0 + z3) * qmul + rr >> 20)); - dst[i + stride * 1] = av_clip_uint8(dst[i + stride * 1] + ((z1 + z2) * qmul + rr >> 20)); - dst[i + stride * 2] = av_clip_uint8(dst[i + stride * 2] + ((z1 - z2) * qmul + rr >> 20)); - dst[i + stride * 3] = av_clip_uint8(dst[i + stride * 3] + ((z0 - z3) * qmul + rr >> 20)); + dst[i + stride * 0] = av_clip_uint8(dst[i + stride * 0] + ((int)((z0 + z3) * qmul + rr) >> 20)); + dst[i + stride * 1] = av_clip_uint8(dst[i + stride * 1] + ((int)((z1 + z2) * qmul + rr) >> 20)); + dst[i + stride * 2] = av_clip_uint8(dst[i + stride * 2] + ((int)((z1 - z2) * qmul + rr) >> 20)); + dst[i + stride * 3] = av_clip_uint8(dst[i + stride * 3] + ((int)((z0 - z3) * qmul + rr) >> 20)); } memset(block, 0, 16 * sizeof(int16_t)); @@ -397,8 +397,8 @@ static inline int svq3_mc_dir(SVQ3Context *s, int size, int mode, if (mode != PREDICT_MODE) { pred_motion(h, sl, k, part_width >> 2, dir, 1, &mx, &my); } else { - mx = s->next_pic->motion_val[0][b_xy][0] << 1; - my = s->next_pic->motion_val[0][b_xy][1] << 1; + mx = s->next_pic->motion_val[0][b_xy][0] * 2; + my = s->next_pic->motion_val[0][b_xy][1] * 2; if (dir == 0) { mx = mx * h->frame_num_offset / @@ -435,8 +435,8 @@ static inline int svq3_mc_dir(SVQ3Context *s, int size, int mode, int fx, fy; mx = (mx + 1 >> 1) + dx; my = (my + 1 >> 1) + dy; - fx = (unsigned)(mx + 0x3000) / 3 - 0x1000; - fy = (unsigned)(my + 0x3000) / 3 - 0x1000; + fx = (unsigned)(mx + 0x30000) / 3 - 0x10000; + fy = (unsigned)(my + 0x30000) / 3 - 0x10000; dxy = (mx - 3 * fx) + 4 * (my - 3 * fy); svq3_mc_dir_part(s, x, y, part_width, part_height, @@ -444,8 +444,8 @@ static inline int svq3_mc_dir(SVQ3Context *s, int size, int mode, mx += mx; my += my; } else if (mode == HALFPEL_MODE || mode == PREDICT_MODE) { - mx = (unsigned)(mx + 1 + 0x3000) / 3 + dx - 0x1000; - my = (unsigned)(my + 1 + 0x3000) / 3 + dy - 0x1000; + mx = (unsigned)(mx + 1 + 0x30000) / 3 + dx - 0x10000; + my = (unsigned)(my + 1 + 0x30000) / 3 + dy - 0x10000; dxy = (mx & 1) + 2 * (my & 1); svq3_mc_dir_part(s, x, y, part_width, part_height, @@ -453,8 +453,8 @@ static inline int svq3_mc_dir(SVQ3Context *s, int size, int mode, mx *= 3; my *= 3; } else { - mx = (unsigned)(mx + 3 + 0x6000) / 6 + dx - 0x1000; - my = (unsigned)(my + 3 + 0x6000) / 6 + dy - 0x1000; + mx = (unsigned)(mx + 3 + 0x60000) / 6 + dx - 0x10000; + my = (unsigned)(my + 3 + 0x60000) / 6 + dy - 0x10000; svq3_mc_dir_part(s, x, y, part_width, part_height, mx, my, 0, 0, dir, avg); diff --git a/libavcodec/tableprint_vlc.h b/libavcodec/tableprint_vlc.h index 675251a836..3004be3f9c 100644 --- a/libavcodec/tableprint_vlc.h +++ b/libavcodec/tableprint_vlc.h @@ -35,6 +35,7 @@ #define av_freep(p) while(0) #define AVCODEC_AVCODEC_H #define AVCODEC_INTERNAL_H +#define AV_INPUT_BUFFER_PADDING_SIZE 64 // the value does not matter for this #include "tableprint.h" #include "get_bits.h" #include "mathtables.c" diff --git a/libavcodec/takdec.c b/libavcodec/takdec.c index d057e0a1cb..b494c5888d 100644 --- a/libavcodec/takdec.c +++ b/libavcodec/takdec.c @@ -195,7 +195,7 @@ static void decode_lpc(int32_t *coeffs, int mode, int length) int a1 = *coeffs++; for (i = 0; i < length - 1 >> 1; i++) { *coeffs += a1; - coeffs[1] += *coeffs; + coeffs[1] += (unsigned)*coeffs; a1 = coeffs[1]; coeffs += 2; } @@ -227,6 +227,7 @@ static void decode_lpc(int32_t *coeffs, int mode, int length) int a3 = coeffs[2]; int a4 = a3 + a1; int a5 = a4 + a2; + coeffs[2] = a5; coeffs += 3; for (i = 0; i < length - 3; i++) { a3 += *coeffs; @@ -255,11 +256,11 @@ static int decode_segment(TAKDecContext *s, int8_t mode, int32_t *decoded, int l code = xcodes[mode - 1]; for (i = 0; i < len; i++) { - int x = get_bits_long(gb, code.init); + unsigned x = get_bits_long(gb, code.init); if (x >= code.escape && get_bits1(gb)) { x |= 1 << code.init; if (x >= code.aescape) { - int scale = get_unary(gb, 1, 9); + unsigned scale = get_unary(gb, 1, 9); if (scale == 9) { int scale_bits = get_bits(gb, 3); if (scale_bits > 0) { @@ -421,19 +422,19 @@ static int decode_subframe(TAKDecContext *s, int32_t *decoded, s->predictors[0] = get_sbits(gb, 10); s->predictors[1] = get_sbits(gb, 10); - s->predictors[2] = get_sbits(gb, size) << (10 - size); - s->predictors[3] = get_sbits(gb, size) << (10 - size); + s->predictors[2] = get_sbits(gb, size) * (1 << (10 - size)); + s->predictors[3] = get_sbits(gb, size) * (1 << (10 - size)); if (filter_order > 4) { int tmp = size - get_bits1(gb); for (i = 4; i < filter_order; i++) { if (!(i & 3)) x = tmp - get_bits(gb, 2); - s->predictors[i] = get_sbits(gb, x) << (10 - size); + s->predictors[i] = get_sbits(gb, x) * (1 << (10 - size)); } } - tfilter[0] = s->predictors[0] << 6; + tfilter[0] = s->predictors[0] * 64; for (i = 1; i < filter_order; i++) { int32_t *p1 = &tfilter[0]; int32_t *p2 = &tfilter[i - 1]; @@ -445,7 +446,7 @@ static int decode_subframe(TAKDecContext *s, int32_t *decoded, p2--; } - tfilter[i] = s->predictors[i] << 6; + tfilter[i] = s->predictors[i] * 64; } x = 1 << (32 - (15 - filter_quant)); @@ -471,15 +472,15 @@ static int decode_subframe(TAKDecContext *s, int32_t *decoded, int v = 1 << (filter_quant - 1); if (filter_order & -16) - v += s->adsp.scalarproduct_int16(&s->residues[i], s->filter, + v += (unsigned)s->adsp.scalarproduct_int16(&s->residues[i], s->filter, filter_order & -16); for (j = filter_order & -16; j < filter_order; j += 4) { - v += s->residues[i + j + 3] * s->filter[j + 3] + - s->residues[i + j + 2] * s->filter[j + 2] + - s->residues[i + j + 1] * s->filter[j + 1] + - s->residues[i + j ] * s->filter[j ]; + v += s->residues[i + j + 3] * (unsigned)s->filter[j + 3] + + s->residues[i + j + 2] * (unsigned)s->filter[j + 2] + + s->residues[i + j + 1] * (unsigned)s->filter[j + 1] + + s->residues[i + j ] * (unsigned)s->filter[j ]; } - v = (av_clip_intp2(v >> filter_quant, 13) << dshift) - *decoded; + v = (av_clip_intp2(v >> filter_quant, 13) * (1 << dshift)) - (unsigned)*decoded; *decoded++ = v; s->residues[filter_order + i] = v >> dshift; } @@ -850,7 +851,7 @@ static int tak_decode_frame(AVCodecContext *avctx, void *data, if (s->sample_shift[chan] > 0) for (i = 0; i < s->nb_samples; i++) - decoded[i] <<= s->sample_shift[chan]; + decoded[i] *= 1U << s->sample_shift[chan]; } } @@ -877,7 +878,7 @@ static int tak_decode_frame(AVCodecContext *avctx, void *data, uint8_t *samples = (uint8_t *)frame->extended_data[chan]; int32_t *decoded = s->decoded[chan]; for (i = 0; i < s->nb_samples; i++) - samples[i] = decoded[i] + 0x80; + samples[i] = decoded[i] + 0x80U; } break; case AV_SAMPLE_FMT_S16P: @@ -892,7 +893,7 @@ static int tak_decode_frame(AVCodecContext *avctx, void *data, for (chan = 0; chan < avctx->channels; chan++) { int32_t *samples = (int32_t *)frame->extended_data[chan]; for (i = 0; i < s->nb_samples; i++) - samples[i] <<= 8; + samples[i] *= 1U << 8; } break; } diff --git a/libavcodec/targa_y216dec.c b/libavcodec/targa_y216dec.c index 21b3d35d67..443d48a92f 100644 --- a/libavcodec/targa_y216dec.c +++ b/libavcodec/targa_y216dec.c @@ -35,7 +35,8 @@ static int y216_decode_frame(AVCodecContext *avctx, void *data, { AVFrame *pic = data; const uint16_t *src = (uint16_t *)avpkt->data; - uint16_t *y, *u, *v, aligned_width = FFALIGN(avctx->width, 4); + uint16_t *y, *u, *v; + int aligned_width = FFALIGN(avctx->width, 4); int i, j, ret; if (avpkt->size < 4 * avctx->height * aligned_width) { diff --git a/libavcodec/texturedsp.c b/libavcodec/texturedsp.c index c5e6cc6270..9283f2973b 100644 --- a/libavcodec/texturedsp.c +++ b/libavcodec/texturedsp.c @@ -35,7 +35,7 @@ #define RGBA(r, g, b, a) (((uint8_t)(r) << 0) | \ ((uint8_t)(g) << 8) | \ ((uint8_t)(b) << 16) | \ - ((uint8_t)(a) << 24)) + ((unsigned)(uint8_t)(a) << 24)) static av_always_inline void extract_color(uint32_t colors[4], uint16_t color0, @@ -158,7 +158,7 @@ static inline void dxt3_block_internal(uint8_t *dst, ptrdiff_t stride, for (x = 0; x < 4; x++) { uint8_t alpha = alpha_values[x]; - uint32_t pixel = colors[code & 3] | (alpha << 24); + uint32_t pixel = colors[code & 3] | ((unsigned)alpha << 24); code >>= 2; AV_WL32(dst + x * 4, pixel); @@ -291,7 +291,7 @@ static inline void dxt5_block_internal(uint8_t *dst, ptrdiff_t stride, } } } - pixel = colors[code & 3] | (alpha << 24); + pixel = colors[code & 3] | ((unsigned)alpha << 24); code >>= 2; AV_WL32(dst + x * 4, pixel); } diff --git a/libavcodec/tiertexseqv.c b/libavcodec/tiertexseqv.c index df12ee3809..f86ae2aac1 100644 --- a/libavcodec/tiertexseqv.c +++ b/libavcodec/tiertexseqv.c @@ -213,10 +213,15 @@ static int seqvideo_decode(SeqVideoContext *seq, const unsigned char *data, int static av_cold int seqvideo_decode_init(AVCodecContext *avctx) { SeqVideoContext *seq = avctx->priv_data; + int ret; seq->avctx = avctx; avctx->pix_fmt = AV_PIX_FMT_PAL8; + ret = ff_set_dimensions(avctx, 256, 128); + if (ret < 0) + return ret; + seq->frame = av_frame_alloc(); if (!seq->frame) return AVERROR(ENOMEM); diff --git a/libavcodec/tiff.c b/libavcodec/tiff.c index 4be587d569..fcfa32dc8b 100644 --- a/libavcodec/tiff.c +++ b/libavcodec/tiff.c @@ -408,7 +408,7 @@ static int tiff_unpack_lzma(TiffContext *s, AVFrame *p, uint8_t *dst, int stride const uint8_t *src, int size, int width, int lines, int strip_start, int is_yuv) { - uint64_t outlen = width * lines; + uint64_t outlen = width * (uint64_t)lines; int ret, line; uint8_t *buf = av_malloc(outlen); if (!buf) @@ -904,6 +904,11 @@ static int tiff_decode_tag(TiffContext *s, AVFrame *frame) break; case TIFF_STRIP_OFFS: if (count == 1) { + if (value > INT_MAX) { + av_log(s->avctx, AV_LOG_ERROR, + "strippos %u too large\n", value); + return AVERROR_INVALIDDATA; + } s->strippos = 0; s->stripoff = value; } else @@ -915,6 +920,11 @@ static int tiff_decode_tag(TiffContext *s, AVFrame *frame) break; case TIFF_STRIP_SIZE: if (count == 1) { + if (value > INT_MAX) { + av_log(s->avctx, AV_LOG_ERROR, + "stripsize %u too large\n", value); + return AVERROR_INVALIDDATA; + } s->stripsizesoff = 0; s->stripsize = value; s->strips = 1; @@ -1008,6 +1018,7 @@ static int tiff_decode_tag(TiffContext *s, AVFrame *frame) s->subsampling[i] = ff_tget(&s->gb, type, s->le); if (s->subsampling[i] <= 0) { av_log(s->avctx, AV_LOG_ERROR, "subsampling %d is invalid\n", s->subsampling[i]); + s->subsampling[i] = 1; return AVERROR_INVALIDDATA; } } @@ -1035,6 +1046,10 @@ static int tiff_decode_tag(TiffContext *s, AVFrame *frame) ADD_METADATA(count, "ModelTiepointTag", NULL); break; case TIFF_GEO_KEY_DIRECTORY: + if (s->geotag_count) { + avpriv_request_sample(s->avctx, "Multiple geo key directories\n"); + return AVERROR_INVALIDDATA; + } ADD_METADATA(1, "GeoTIFF_Version", NULL); ADD_METADATA(2, "GeoTIFF_Key_Revision", "."); s->geotag_count = ff_tget_short(&s->gb, s->le); @@ -1042,7 +1057,8 @@ static int tiff_decode_tag(TiffContext *s, AVFrame *frame) s->geotag_count = count / 4 - 1; av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n"); } - if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4) { + if ( bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4 + || s->geotag_count == 0) { s->geotag_count = 0; return -1; } @@ -1080,6 +1096,8 @@ static int tiff_decode_tag(TiffContext *s, AVFrame *frame) if (s->geotags[i].count == 0 || s->geotags[i].offset + s->geotags[i].count > count) { av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key); + } else if (s->geotags[i].val) { + av_log(s->avctx, AV_LOG_WARNING, "Duplicate GeoTIFF key %d\n", s->geotags[i].key); } else { char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", "); if (!ap) { @@ -1106,6 +1124,8 @@ static int tiff_decode_tag(TiffContext *s, AVFrame *frame) bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET); if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count) return AVERROR_INVALIDDATA; + if (s->geotags[i].val) + return AVERROR_INVALIDDATA; ap = av_malloc(s->geotags[i].count); if (!ap) { av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n"); @@ -1268,6 +1288,8 @@ static int decode_frame(AVCodecContext *avctx, stride = p->linesize[plane]; dst = p->data[plane]; for (i = 0; i < s->height; i += s->rps) { + if (i) + dst += s->rps * stride; if (s->stripsizesoff) ssize = ff_tget(&stripsizes, s->sstype, le); else @@ -1288,7 +1310,6 @@ static int decode_frame(AVCodecContext *avctx, return ret; break; } - dst += s->rps * stride; } if (s->predictor == 2) { if (s->photometric == TIFF_PHOTOMETRIC_YCBCR) { diff --git a/libavcodec/truemotion1.c b/libavcodec/truemotion1.c index da843c4440..28dccaae47 100644 --- a/libavcodec/truemotion1.c +++ b/libavcodec/truemotion1.c @@ -177,10 +177,10 @@ static int make_ydt15_entry(int p1, int p2, int16_t *ydt) int lo, hi; lo = ydt[p1]; - lo += (lo << 5) + (lo << 10); + lo += (lo * 32) + (lo * 1024); hi = ydt[p2]; - hi += (hi << 5) + (hi << 10); - return (lo + (hi << 16)) << 1; + hi += (hi * 32) + (hi * 1024); + return (lo + (hi * (1U << 16))) * 2; } static int make_cdt15_entry(int p1, int p2, int16_t *cdt) @@ -188,9 +188,9 @@ static int make_cdt15_entry(int p1, int p2, int16_t *cdt) int r, b, lo; b = cdt[p2]; - r = cdt[p1] << 10; + r = cdt[p1] * 1024; lo = b + r; - return (lo + (lo << 16)) << 1; + return (lo + (lo * (1U << 16))) * 2; } #if HAVE_BIGENDIAN diff --git a/libavcodec/truemotion2.c b/libavcodec/truemotion2.c index 245a32a8d7..b689efdb99 100644 --- a/libavcodec/truemotion2.c +++ b/libavcodec/truemotion2.c @@ -63,6 +63,7 @@ typedef struct TM2Context { AVFrame *pic; GetBitContext gb; + int error; BswapDSPContext bdsp; uint8_t *buffer; @@ -272,7 +273,7 @@ static int tm2_read_deltas(TM2Context *ctx, int stream_id) for (i = 0; i < d; i++) { v = get_bits_long(&ctx->gb, mb); if (v & (1 << (mb - 1))) - ctx->deltas[stream_id][i] = v - (1 << mb); + ctx->deltas[stream_id][i] = v - (1U << mb); else ctx->deltas[stream_id][i] = v; } @@ -298,15 +299,15 @@ static int tm2_read_stream(TM2Context *ctx, const uint8_t *buf, int stream_id, i /* get stream length in dwords */ bytestream2_init(&gb, buf, buf_size); len = bytestream2_get_be32(&gb); - skip = len * 4 + 4; if (len == 0) return 4; - if (len >= INT_MAX / 4 - 1 || len < 0 || skip > buf_size) { + if (len >= INT_MAX / 4 - 1 || len < 0 || len * 4 + 4 > buf_size) { av_log(ctx->avctx, AV_LOG_ERROR, "Error, invalid stream size.\n"); return AVERROR_INVALIDDATA; } + skip = len * 4 + 4; toks = bytestream2_get_be32(&gb); if (toks & 1) { @@ -398,6 +399,7 @@ static inline int GET_TOK(TM2Context *ctx,int type) { if (ctx->tok_ptrs[type] >= ctx->tok_lens[type]) { av_log(ctx->avctx, AV_LOG_ERROR, "Read token from stream %i out of bounds (%i>=%i)\n", type, ctx->tok_ptrs[type], ctx->tok_lens[type]); + ctx->error = 1; return 0; } if (type <= TM2_MOT) { @@ -441,15 +443,15 @@ static inline int GET_TOK(TM2Context *ctx,int type) /* recalculate last and delta values for next blocks */ #define TM2_RECALC_BLOCK(CHR, stride, last, CD) {\ - CD[0] = CHR[1] - last[1];\ - CD[1] = (int)CHR[stride + 1] - (int)CHR[1];\ + CD[0] = (unsigned)CHR[ 1] - (unsigned)last[1];\ + CD[1] = (unsigned)CHR[stride + 1] - (unsigned) CHR[1];\ last[0] = (int)CHR[stride + 0];\ last[1] = (int)CHR[stride + 1];} /* common operations - add deltas to 4x4 block of luma or 2x2 blocks of chroma */ static inline void tm2_apply_deltas(TM2Context *ctx, int* Y, int stride, int *deltas, int *last) { - int ct, d; + unsigned ct, d; int i, j; for (j = 0; j < 4; j++){ @@ -465,7 +467,7 @@ static inline void tm2_apply_deltas(TM2Context *ctx, int* Y, int stride, int *de } } -static inline void tm2_high_chroma(int *data, int stride, int *last, int *CD, int *deltas) +static inline void tm2_high_chroma(int *data, int stride, int *last, unsigned *CD, int *deltas) { int i, j; for (j = 0; j < 2; j++) { @@ -809,6 +811,8 @@ static int tm2_decode_blocks(TM2Context *ctx, AVFrame *p) default: av_log(ctx->avctx, AV_LOG_ERROR, "Skipping unknown block type %i\n", type); } + if (ctx->error) + return AVERROR_INVALIDDATA; } } @@ -889,6 +893,8 @@ static int decode_frame(AVCodecContext *avctx, int offset = TM2_HEADER_SIZE; int i, t, ret; + l->error = 0; + av_fast_padded_malloc(&l->buffer, &l->buffer_size, buf_size); if (!l->buffer) { av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n"); @@ -915,7 +921,8 @@ static int decode_frame(AVCodecContext *avctx, buf_size - offset); if (t < 0) { int j = tm2_stream_order[i]; - memset(l->tokens[j], 0, sizeof(**l->tokens) * l->tok_lens[j]); + if (l->tok_lens[j]) + memset(l->tokens[j], 0, sizeof(**l->tokens) * l->tok_lens[j]); return t; } offset += t; diff --git a/libavcodec/tscc.c b/libavcodec/tscc.c index 8c5ec68cf4..3dd476aee5 100644 --- a/libavcodec/tscc.c +++ b/libavcodec/tscc.c @@ -99,11 +99,14 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, /* make the palette available on the way out */ if (c->avctx->pix_fmt == AV_PIX_FMT_PAL8) { - const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL); + int size; + const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, &size); - if (pal) { + if (pal && size == AVPALETTE_SIZE) { frame->palette_has_changed = 1; memcpy(c->pal, pal, AVPALETTE_SIZE); + } else if (pal) { + av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", size); } memcpy(frame->data[1], c->pal, AVPALETTE_SIZE); } diff --git a/libavcodec/ttaenc.c b/libavcodec/ttaenc.c index 0df1fcb6aa..2f1c8db556 100644 --- a/libavcodec/ttaenc.c +++ b/libavcodec/ttaenc.c @@ -114,9 +114,12 @@ static int tta_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, { TTAEncContext *s = avctx->priv_data; PutBitContext pb; - int ret, i, out_bytes, cur_chan = 0, res = 0, samples = 0; + int ret, i, out_bytes, cur_chan, res, samples; + int64_t pkt_size = frame->nb_samples * 2LL * avctx->channels * s->bps; - if ((ret = ff_alloc_packet2(avctx, avpkt, frame->nb_samples * 2 * avctx->channels * s->bps, 0)) < 0) +pkt_alloc: + cur_chan = 0, res = 0, samples = 0; + if ((ret = ff_alloc_packet2(avctx, avpkt, pkt_size, 0)) < 0) return ret; init_put_bits(&pb, avpkt->data, avpkt->size); @@ -174,6 +177,14 @@ static int tta_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, rice->k1++; unary = 1 + (outval >> k); + if (unary + 100LL > put_bits_left(&pb)) { + if (pkt_size < INT_MAX/2) { + pkt_size *= 2; + av_packet_unref(avpkt); + goto pkt_alloc; + } else + return AVERROR(ENOMEM); + } do { if (unary > 31) { put_bits(&pb, 31, 0x7FFFFFFF); diff --git a/libavcodec/ulti.c b/libavcodec/ulti.c index e6f4374981..9e4c088b10 100644 --- a/libavcodec/ulti.c +++ b/libavcodec/ulti.c @@ -50,6 +50,8 @@ static av_cold int ulti_decode_init(AVCodecContext *avctx) s->width = avctx->width; s->height = avctx->height; s->blocks = (s->width / 8) * (s->height / 8); + if (s->blocks == 0) + return AVERROR_INVALIDDATA; avctx->pix_fmt = AV_PIX_FMT_YUV410P; s->ulti_codebook = ulti_codebook; diff --git a/libavcodec/unary.h b/libavcodec/unary.h index 908dc93507..d57f9f70c5 100644 --- a/libavcodec/unary.h +++ b/libavcodec/unary.h @@ -28,7 +28,20 @@ * @param gb GetBitContext * @param[in] stop The bitstop value (unary code of 1's or 0's) * @param[in] len Maximum length - * @return Unary length/index + * @return unary 0 based code index. This is also the length in bits of the + * code excluding the stop bit. + * (in case len=1) + * 1 0 + * 0 1 + * (in case len=2) + * 1 0 + * 01 1 + * 00 2 + * (in case len=3) + * 1 0 + * 01 1 + * 001 2 + * 000 3 */ static inline int get_unary(GetBitContext *gb, int stop, int len) { diff --git a/libavcodec/utils.c b/libavcodec/utils.c index f532824f45..f8d30c4248 100644 --- a/libavcodec/utils.c +++ b/libavcodec/utils.c @@ -373,6 +373,10 @@ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, w_align = 4; h_align = 4; } + if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) { + w_align = 8; + h_align = 8; + } break; case AV_PIX_FMT_PAL8: case AV_PIX_FMT_BGR8: @@ -382,7 +386,8 @@ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, w_align = 4; h_align = 4; } - if (s->codec_id == AV_CODEC_ID_JV) { + if (s->codec_id == AV_CODEC_ID_JV || + s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) { w_align = 8; h_align = 8; } @@ -410,7 +415,10 @@ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, *width = FFALIGN(*width, w_align); *height = FFALIGN(*height, h_align); - if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) { + if (s->codec_id == AV_CODEC_ID_H264 || s->lowres || + s->codec_id == AV_CODEC_ID_VP5 || s->codec_id == AV_CODEC_ID_VP6 || + s->codec_id == AV_CODEC_ID_VP6F || s->codec_id == AV_CODEC_ID_VP6A + ) { // some of the optimized chroma MC reads one line too much // which is also done in mpeg decoders with lowres > 0 *height += 2; @@ -957,6 +965,7 @@ int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, v if (ret) ret[i] = r; } + emms_c(); return 0; } @@ -969,6 +978,7 @@ int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, if (ret) ret[i] = r; } + emms_c(); return 0; } @@ -1126,6 +1136,10 @@ int av_codec_get_max_lowres(const AVCodec *codec) return codec->max_lowres; } +int avpriv_codec_get_cap_skip_frame_fill_param(const AVCodec *codec){ + return !!(codec->caps_internal & FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM); +} + static void get_subtitle_defaults(AVSubtitle *sub) { memset(sub, 0, sizeof(*sub)); @@ -1198,7 +1212,7 @@ int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *code if (ret < 0) return ret; - avctx->internal = av_mallocz(sizeof(AVCodecInternal)); + avctx->internal = av_mallocz(sizeof(*avctx->internal)); if (!avctx->internal) { ret = AVERROR(ENOMEM); goto end; @@ -1476,7 +1490,7 @@ FF_ENABLE_DEPRECATION_WARNINGS } if (!avctx->rc_initial_buffer_occupancy) - avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4; + avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4; if (avctx->ticks_per_frame && avctx->time_base.num && avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) { @@ -2254,7 +2268,7 @@ int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx, skip_reason = AV_RL8(side + 8); discard_reason = AV_RL8(side + 9); } - if (avctx->internal->skip_samples && *got_frame_ptr && + if (avctx->internal->skip_samples > 0 && *got_frame_ptr && !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) { if(frame->nb_samples <= avctx->internal->skip_samples){ *got_frame_ptr = 0; @@ -2523,7 +2537,7 @@ void avsubtitle_free(AVSubtitle *sub) av_freep(&sub->rects); - memset(sub, 0, sizeof(AVSubtitle)); + memset(sub, 0, sizeof(*sub)); } av_cold int avcodec_close(AVCodecContext *avctx) diff --git a/libavcodec/utvideodec.c b/libavcodec/utvideodec.c index 760d9e5a7f..160528e007 100644 --- a/libavcodec/utvideodec.c +++ b/libavcodec/utvideodec.c @@ -28,6 +28,7 @@ #include #include "libavutil/intreadwrite.h" +#include "libavutil/pixdesc.h" #include "avcodec.h" #include "bswapdsp.h" #include "bytestream.h" @@ -474,6 +475,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, static av_cold int decode_init(AVCodecContext *avctx) { UtvideoContext * const c = avctx->priv_data; + int h_shift, v_shift; c->avctx = avctx; @@ -538,6 +540,13 @@ static av_cold int decode_init(AVCodecContext *avctx) return AVERROR_INVALIDDATA; } + av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &h_shift, &v_shift); + if ((avctx->width & ((1<height & ((1<avctx, AV_LOG_ERROR, "Insufficient data\n"); + return AVERROR_INVALIDDATA; + } blocktypes = bytestream2_get_byte(&g); } switch (blocktypes & 0xC0) { @@ -205,6 +209,10 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, if (flags & VB_HAS_GMC) { i = (int16_t)bytestream2_get_le16(&c->stream); j = (int16_t)bytestream2_get_le16(&c->stream); + if (FFABS(j) > avctx->height) { + av_log(avctx, AV_LOG_ERROR, "GMV out of range\n"); + return AVERROR_INVALIDDATA; + } offset = i + j * avctx->width; } if (flags & VB_HAS_VIDEO) { diff --git a/libavcodec/vc1_block.c b/libavcodec/vc1_block.c index 255ba1da70..1b219c9adf 100644 --- a/libavcodec/vc1_block.c +++ b/libavcodec/vc1_block.c @@ -594,7 +594,7 @@ static int vc1_decode_i_block(VC1Context *v, int16_t block[64], int n, scale = s->c_dc_scale; block[0] = dcdiff * scale; - ac_val = s->ac_val[0][0] + s->block_index[n] * 16; + ac_val = s->ac_val[0][s->block_index[n]]; ac_val2 = ac_val; if (dc_pred_dir) // left ac_val -= 16; @@ -745,7 +745,7 @@ static int vc1_decode_i_block_adv(VC1Context *v, int16_t block[64], int n, scale = mquant * 2 + ((mquant == v->pq) ? v->halfpq : 0); - ac_val = s->ac_val[0][0] + s->block_index[n] * 16; + ac_val = s->ac_val[0][s->block_index[n]]; ac_val2 = ac_val; if (dc_pred_dir) // left ac_val -= 16; @@ -946,7 +946,7 @@ static int vc1_decode_intra_block(VC1Context *v, int16_t block[64], int n, if (!a_avail) dc_pred_dir = 1; if (!c_avail) dc_pred_dir = 0; if (!a_avail && !c_avail) use_pred = 0; - ac_val = s->ac_val[0][0] + s->block_index[n] * 16; + ac_val = s->ac_val[0][s->block_index[n]]; ac_val2 = ac_val; scale = mquant * 2 + v->halfpq; diff --git a/libavcodec/vc2enc.c b/libavcodec/vc2enc.c index 5472609efd..ac551caaa1 100644 --- a/libavcodec/vc2enc.c +++ b/libavcodec/vc2enc.c @@ -658,7 +658,8 @@ static int rate_control(AVCodecContext *avctx, void *arg) VC2EncContext *s = slice_dat->ctx; const int sx = slice_dat->x; const int sy = slice_dat->y; - int quant_buf[2], bits_buf[2], quant = s->q_start, range = s->q_start/3; + int bits_last = INT_MAX, quant_buf[2] = {-1, -1}; + int quant = s->q_start, range = s->q_start/3; const int64_t top = slice_dat->bits_ceil; const double percent = s->tolerance; const double bottom = top - top*(percent/100.0f); @@ -670,14 +671,13 @@ static int rate_control(AVCodecContext *avctx, void *arg) bits = count_hq_slice(s, sx, sy, quant); range = av_clip(range/2, 1, s->q_ceil); if (quant_buf[1] == quant) { - quant = bits_buf[0] < bits ? quant_buf[0] : quant; - bits = bits_buf[0] < bits ? bits_buf[0] : bits; + quant = bits_last < bits ? quant_buf[0] : quant; + bits = bits_last < bits ? bits_last : bits; break; } quant_buf[1] = quant_buf[0]; quant_buf[0] = quant; - bits_buf[1] = bits_buf[0]; - bits_buf[0] = bits; + bits_last = bits; } slice_dat->quant_idx = av_clip(quant, 0, s->q_ceil); slice_dat->bytes = FFALIGN((bits >> 3), s->size_scaler) + 4 + s->prefix_bytes; @@ -867,7 +867,7 @@ static int dwt_plane(AVCodecContext *avctx, void *arg) } } - memset(buf, 0, (p->coef_stride*p->dwt_height - p->height*p->width)*sizeof(dwtcoef)); + memset(buf, 0, p->coef_stride * (p->dwt_height - p->height) * sizeof(dwtcoef)); for (level = s->wavelet_depth-1; level >= 0; level--) { const SubBand *b = &p->band[level][0]; @@ -1088,7 +1088,7 @@ static av_cold int vc2_encode_init(AVCodecContext *avctx) p->dwt_width = w = FFALIGN(p->width, (1 << s->wavelet_depth)); p->dwt_height = h = FFALIGN(p->height, (1 << s->wavelet_depth)); p->coef_stride = FFALIGN(p->dwt_width, 32); - p->coef_buf = av_malloc(p->coef_stride*p->dwt_height*sizeof(dwtcoef)); + p->coef_buf = av_mallocz(p->coef_stride*p->dwt_height*sizeof(dwtcoef)); if (!p->coef_buf) goto alloc_fail; for (level = s->wavelet_depth-1; level >= 0; level--) { @@ -1106,8 +1106,9 @@ static av_cold int vc2_encode_init(AVCodecContext *avctx) /* DWT init */ if (ff_vc2enc_init_transforms(&s->transform_args[i].t, - s->plane[0].coef_stride, - s->plane[0].dwt_height)) + s->plane[i].coef_stride, + s->plane[i].dwt_height, + s->slice_width, s->slice_height)) goto alloc_fail; } diff --git a/libavcodec/vc2enc_dwt.c b/libavcodec/vc2enc_dwt.c index eb341684cd..0265db8dac 100644 --- a/libavcodec/vc2enc_dwt.c +++ b/libavcodec/vc2enc_dwt.c @@ -211,19 +211,25 @@ static void vc2_subband_dwt_53(VC2TransformContext *t, dwtcoef *data, deinterleave(data, stride, width, height, synth); } -av_cold int ff_vc2enc_init_transforms(VC2TransformContext *s, int p_width, int p_height) +av_cold int ff_vc2enc_init_transforms(VC2TransformContext *s, int p_stride, + int p_height, int slice_w, int slice_h) { s->vc2_subband_dwt[VC2_TRANSFORM_9_7] = vc2_subband_dwt_97; s->vc2_subband_dwt[VC2_TRANSFORM_5_3] = vc2_subband_dwt_53; - s->buffer = av_malloc(2*p_width*p_height*sizeof(dwtcoef)); + /* Pad by the slice size, only matters for non-Haar wavelets */ + s->buffer = av_calloc((p_stride + slice_w)*(p_height + slice_h), sizeof(dwtcoef)); if (!s->buffer) return 1; + s->padding = (slice_h >> 1)*p_stride + (slice_w >> 1); + s->buffer += s->padding; + return 0; } av_cold void ff_vc2enc_free_transforms(VC2TransformContext *s) { - av_freep(&s->buffer); + av_free(s->buffer - s->padding); + s->buffer = NULL; } diff --git a/libavcodec/vc2enc_dwt.h b/libavcodec/vc2enc_dwt.h index 8e1b61498e..7be682bcd9 100644 --- a/libavcodec/vc2enc_dwt.h +++ b/libavcodec/vc2enc_dwt.h @@ -44,12 +44,14 @@ enum VC2TransformType { typedef struct VC2TransformContext { dwtcoef *buffer; + int padding; void (*vc2_subband_dwt[VC2_TRANSFORMS_NB])(struct VC2TransformContext *t, dwtcoef *data, ptrdiff_t stride, int width, int height); } VC2TransformContext; -int ff_vc2enc_init_transforms(VC2TransformContext *t, int p_width, int p_height); +int ff_vc2enc_init_transforms(VC2TransformContext *t, int p_stride, int p_height, + int slice_w, int slice_h); void ff_vc2enc_free_transforms(VC2TransformContext *t); #endif /* AVCODEC_VC2ENC_DWT_H */ diff --git a/libavcodec/vdpau_hevc.c b/libavcodec/vdpau_hevc.c index 3c1dc5f223..3223f5e2eb 100644 --- a/libavcodec/vdpau_hevc.c +++ b/libavcodec/vdpau_hevc.c @@ -245,7 +245,7 @@ static int vdpau_hevc_start_frame(AVCodecContext *avctx, const HEVCFrame *frame = &h->DPB[i]; if (frame != h->ref && (frame->flags & (HEVC_FRAME_FLAG_LONG_REF | HEVC_FRAME_FLAG_SHORT_REF))) { - if (j > 16) { + if (j > 15) { av_log(avctx, AV_LOG_WARNING, "VDPAU only supports up to 16 references in the DPB. " "This frame may not be decoded correctly.\n"); diff --git a/libavcodec/vmnc.c b/libavcodec/vmnc.c index 49abb776f2..dfabfd394a 100644 --- a/libavcodec/vmnc.c +++ b/libavcodec/vmnc.c @@ -374,6 +374,12 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, w = bytestream2_get_be16(gb); h = bytestream2_get_be16(gb); enc = bytestream2_get_be32(gb); + if ((dx + w > c->width) || (dy + h > c->height)) { + av_log(avctx, AV_LOG_ERROR, + "Incorrect frame size: %ix%i+%ix%i of %ix%i\n", + w, h, dx, dy, c->width, c->height); + return AVERROR_INVALIDDATA; + } outptr = c->pic->data[0] + dx * c->bpp2 + dy * c->pic->linesize[0]; size_left = bytestream2_get_bytes_left(gb); switch (enc) { @@ -451,12 +457,6 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, bytestream2_skip(gb, 2); break; case 0x00000000: // raw rectangle data - if ((dx + w > c->width) || (dy + h > c->height)) { - av_log(avctx, AV_LOG_ERROR, - "Incorrect frame size: %ix%i+%ix%i of %ix%i\n", - w, h, dx, dy, c->width, c->height); - return AVERROR_INVALIDDATA; - } if (size_left < w * h * c->bpp2) { av_log(avctx, AV_LOG_ERROR, "Premature end of data! (need %i got %i)\n", @@ -467,12 +467,6 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, c->pic->linesize[0]); break; case 0x00000005: // HexTile encoded rectangle - if ((dx + w > c->width) || (dy + h > c->height)) { - av_log(avctx, AV_LOG_ERROR, - "Incorrect frame size: %ix%i+%ix%i of %ix%i\n", - w, h, dx, dy, c->width, c->height); - return AVERROR_INVALIDDATA; - } res = decode_hextile(c, outptr, gb, w, h, c->pic->linesize[0]); if (res < 0) return res; diff --git a/libavcodec/vorbis.c b/libavcodec/vorbis.c index 86d10407f4..80d5198c62 100644 --- a/libavcodec/vorbis.c +++ b/libavcodec/vorbis.c @@ -73,7 +73,7 @@ int ff_vorbis_len2vlc(uint8_t *bits, uint32_t *codes, unsigned num) if (bits[p] > 32) return AVERROR_INVALIDDATA; for (i = 0; i < bits[p]; ++i) - exit_at_level[i+1] = 1 << i; + exit_at_level[i+1] = 1u << i; #ifdef DEBUG av_log(NULL, AV_LOG_INFO, " %u. of %u code len %d code %d - ", p, num, bits[p], codes[p]); @@ -105,7 +105,7 @@ int ff_vorbis_len2vlc(uint8_t *bits, uint32_t *codes, unsigned num) exit_at_level[i] = 0; // construct code (append 0s to end) and introduce new exits for (j = i + 1 ;j <= bits[p]; ++j) - exit_at_level[j] = code + (1 << (j - 1)); + exit_at_level[j] = code + (1u << (j - 1)); codes[p] = code; #ifdef DEBUG diff --git a/libavcodec/vp3.c b/libavcodec/vp3.c index 5bbf47b52d..165a051541 100644 --- a/libavcodec/vp3.c +++ b/libavcodec/vp3.c @@ -951,9 +951,11 @@ static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb, Vp3Fragment *all_fragments = s->all_fragments; VLC_TYPE(*vlc_table)[2] = table->table; - if (num_coeffs < 0) + if (num_coeffs < 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of coefficents at level %d\n", coeff_index); + return AVERROR_INVALIDDATA; + } if (eob_run > num_coeffs) { coeff_i = @@ -978,6 +980,9 @@ static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb, if (eob_run_get_bits[token]) eob_run += get_bits(gb, eob_run_get_bits[token]); + if (!eob_run) + eob_run = INT_MAX; + // record only the number of blocks ended in this plane, // any spill will be recorded in the next plane. if (eob_run > num_coeffs - coeff_i) { @@ -1071,6 +1076,9 @@ static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb) s->dct_tokens[0][0] = s->dct_tokens_base; + if (get_bits_left(gb) < 16) + return AVERROR_INVALIDDATA; + /* fetch the DC table indexes */ dc_y_table = get_bits(gb, 4); dc_c_table = get_bits(gb, 4); @@ -1080,6 +1088,8 @@ static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb) 0, residual_eob_run); if (residual_eob_run < 0) return residual_eob_run; + if (get_bits_left(gb) < 8) + return AVERROR_INVALIDDATA; /* reverse prediction of the Y-plane DC coefficients */ reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]); @@ -1102,6 +1112,8 @@ static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb) s->fragment_width[1], s->fragment_height[1]); } + if (get_bits_left(gb) < 8) + return AVERROR_INVALIDDATA; /* fetch the AC table indexes */ ac_y_table = get_bits(gb, 4); ac_c_table = get_bits(gb, 4); @@ -2022,8 +2034,9 @@ static int vp3_decode_frame(AVCodecContext *avctx, ret = vp3_decode_init(avctx); if (ret < 0) { vp3_decode_end(avctx); + return ret; } - return ret; + return buf_size; } else if (type == 2) { vp3_decode_end(avctx); ret = theora_decode_tables(avctx, &gb); @@ -2031,8 +2044,9 @@ static int vp3_decode_frame(AVCodecContext *avctx, ret = vp3_decode_init(avctx); if (ret < 0) { vp3_decode_end(avctx); + return ret; } - return ret; + return buf_size; } av_log(avctx, AV_LOG_ERROR, diff --git a/libavcodec/vp3dsp.c b/libavcodec/vp3dsp.c index d8a3e0a354..37997431d3 100644 --- a/libavcodec/vp3dsp.c +++ b/libavcodec/vp3dsp.c @@ -41,7 +41,7 @@ #define xC6S2 25080 #define xC7S1 12785 -#define M(a, b) (((a) * (b)) >> 16) +#define M(a, b) ((int)((SUINT)(a) * (b)) >> 16) static av_always_inline void idct(uint8_t *dst, int stride, int16_t *input, int type) diff --git a/libavcodec/vp5.c b/libavcodec/vp5.c index 5bcf9b6217..7100bb455d 100644 --- a/libavcodec/vp5.c +++ b/libavcodec/vp5.c @@ -39,8 +39,11 @@ static int vp5_parse_header(VP56Context *s, const uint8_t *buf, int buf_size) { VP56RangeCoder *c = &s->c; int rows, cols; + int ret; - ff_vp56_init_range_decoder(&s->c, buf, buf_size); + ret = ff_vp56_init_range_decoder(&s->c, buf, buf_size); + if (ret < 0) + return ret; s->frames[VP56_FRAME_CURRENT]->key_frame = !vp56_rac_get(c); vp56_rac_get(c); ff_vp56_init_dequant(s, vp56_rac_gets(c, 6)); @@ -171,7 +174,7 @@ static int vp5_parse_coeff_models(VP56Context *s) return 0; } -static void vp5_parse_coeff(VP56Context *s) +static int vp5_parse_coeff(VP56Context *s) { VP56RangeCoder *c = &s->c; VP56Model *model = s->modelp; @@ -181,6 +184,11 @@ static void vp5_parse_coeff(VP56Context *s) int b, i, cg, idx, ctx, ctx_last; int pt = 0; /* plane type (0 for Y, 1 for U or V) */ + if (c->end <= c->buffer && c->bits >= 0) { + av_log(s->avctx, AV_LOG_ERROR, "End of AC stream reached in vp5_parse_coeff\n"); + return AVERROR_INVALIDDATA; + } + for (b=0; b<6; b++) { int ct = 1; /* code type */ @@ -246,6 +254,7 @@ static void vp5_parse_coeff(VP56Context *s) s->coeff_ctx[ff_vp56_b6to4[b]][i] = 5; s->above_blocks[s->above_block_idx[b]].not_null_dc = s->coeff_ctx[ff_vp56_b6to4[b]][0]; } + return 0; } static void vp5_default_models_init(VP56Context *s) diff --git a/libavcodec/vp56.c b/libavcodec/vp56.c index 631924828d..bfc3d3bc7c 100644 --- a/libavcodec/vp56.c +++ b/libavcodec/vp56.c @@ -261,6 +261,25 @@ static VP56mb vp56_decode_mv(VP56Context *s, int row, int col) return s->mb_type; } +static VP56mb vp56_conceal_mv(VP56Context *s, int row, int col) +{ + VP56mv *mv, vect = {0,0}; + int b; + + s->mb_type = VP56_MB_INTER_NOVEC_PF; + s->macroblocks[row * s->mb_width + col].type = s->mb_type; + + mv = &vect; + + s->macroblocks[row*s->mb_width + col].mv = *mv; + + /* same vector for all blocks */ + for (b=0; b<6; b++) + s->mv[b] = *mv; + + return s->mb_type; +} + static void vp56_add_predictors_dc(VP56Context *s, VP56Frame ref_frame) { int idx = s->idct_scantable[0]; @@ -381,20 +400,11 @@ static void vp56_mc(VP56Context *s, int b, int plane, uint8_t *src, } } -static void vp56_decode_mb(VP56Context *s, int row, int col, int is_alpha) +static av_always_inline void vp56_render_mb(VP56Context *s, int row, int col, int is_alpha, VP56mb mb_type) { - AVFrame *frame_current, *frame_ref; - VP56mb mb_type; - VP56Frame ref_frame; int b, ab, b_max, plane, off; - - if (s->frames[VP56_FRAME_CURRENT]->key_frame) - mb_type = VP56_MB_INTRA; - else - mb_type = vp56_decode_mv(s, row, col); - ref_frame = ff_vp56_reference_frame[mb_type]; - - s->parse_coeff(s); + AVFrame *frame_current, *frame_ref; + VP56Frame ref_frame = ff_vp56_reference_frame[mb_type]; vp56_add_predictors_dc(s, ref_frame); @@ -453,6 +463,39 @@ static void vp56_decode_mb(VP56Context *s, int row, int col, int is_alpha) } } +static int vp56_decode_mb(VP56Context *s, int row, int col, int is_alpha) +{ + VP56mb mb_type; + int ret; + + if (s->frames[VP56_FRAME_CURRENT]->key_frame) + mb_type = VP56_MB_INTRA; + else + mb_type = vp56_decode_mv(s, row, col); + + ret = s->parse_coeff(s); + if (ret < 0) + return ret; + + vp56_render_mb(s, row, col, is_alpha, mb_type); + + return 0; +} + +static int vp56_conceal_mb(VP56Context *s, int row, int col, int is_alpha) +{ + VP56mb mb_type; + + if (s->frames[VP56_FRAME_CURRENT]->key_frame) + mb_type = VP56_MB_INTRA; + else + mb_type = vp56_conceal_mv(s, row, col); + + vp56_render_mb(s, row, col, is_alpha, mb_type); + + return 0; +} + static int vp56_size_changed(VP56Context *s) { AVCodecContext *avctx = s->avctx; @@ -464,6 +507,8 @@ static int vp56_size_changed(VP56Context *s) s->plane_height[0] = s->plane_height[3] = avctx->coded_height; s->plane_height[1] = s->plane_height[2] = avctx->coded_height/2; + s->have_undamaged_frame = 0; + for (i=0; i<4; i++) s->stride[i] = s->flip * s->frames[VP56_FRAME_CURRENT]->linesize[i]; @@ -529,13 +574,18 @@ int ff_vp56_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, } ret = ff_get_buffer(avctx, p, AV_GET_BUFFER_FLAG_REF); - if (ret < 0) + if (ret < 0) { + if (res == VP56_SIZE_CHANGE) + ff_set_dimensions(avctx, 0, 0); return ret; + } if (avctx->pix_fmt == AV_PIX_FMT_YUVA420P) { av_frame_unref(s->alpha_context->frames[VP56_FRAME_CURRENT]); if ((ret = av_frame_ref(s->alpha_context->frames[VP56_FRAME_CURRENT], p)) < 0) { av_frame_unref(p); + if (res == VP56_SIZE_CHANGE) + ff_set_dimensions(avctx, 0, 0); return ret; } } @@ -569,8 +619,12 @@ int ff_vp56_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, } } + s->discard_frame = 0; avctx->execute2(avctx, ff_vp56_decode_mbs, 0, 0, (avctx->pix_fmt == AV_PIX_FMT_YUVA420P) + 1); + if (s->discard_frame) + return AVERROR_INVALIDDATA; + if ((res = av_frame_ref(data, p)) < 0) return res; *got_frame = 1; @@ -589,6 +643,7 @@ static int ff_vp56_decode_mbs(AVCodecContext *avctx, void *data, int block, y, uv; ptrdiff_t stride_y, stride_uv; int res; + int damaged = 0; if (p->key_frame) { p->pict_type = AV_PICTURE_TYPE_I; @@ -653,7 +708,18 @@ static int ff_vp56_decode_mbs(AVCodecContext *avctx, void *data, s->block_offset[5] = s->block_offset[4]; for (mb_col=0; mb_colmb_width; mb_col++) { - vp56_decode_mb(s, mb_row, mb_col, is_alpha); + if (!damaged) { + int ret = vp56_decode_mb(s, mb_row, mb_col, is_alpha); + if (ret < 0) { + damaged = 1; + if (!s->have_undamaged_frame || !avctx->error_concealment) { + s->discard_frame = 1; + return AVERROR_INVALIDDATA; + } + } + } + if (damaged) + vp56_conceal_mb(s, mb_row, mb_col, is_alpha); for (y=0; y<4; y++) { s->above_block_idx[y] += 2; @@ -667,6 +733,9 @@ static int ff_vp56_decode_mbs(AVCodecContext *avctx, void *data, } } + if (!damaged) + s->have_undamaged_frame = 1; + next: if (p->key_frame || s->golden_frame) { av_frame_unref(s->frames[VP56_FRAME_GOLDEN]); diff --git a/libavcodec/vp56.h b/libavcodec/vp56.h index 56c30919b7..c049399df8 100644 --- a/libavcodec/vp56.h +++ b/libavcodec/vp56.h @@ -74,7 +74,7 @@ typedef void (*VP56ParseVectorAdjustment)(VP56Context *s, typedef void (*VP56Filter)(VP56Context *s, uint8_t *dst, uint8_t *src, int offset1, int offset2, int stride, VP56mv mv, int mask, int select, int luma); -typedef void (*VP56ParseCoeff)(VP56Context *s); +typedef int (*VP56ParseCoeff)(VP56Context *s); typedef void (*VP56DefaultModelsInit)(VP56Context *s); typedef void (*VP56ParseVectorModels)(VP56Context *s); typedef int (*VP56ParseCoeffModels)(VP56Context *s); @@ -203,6 +203,9 @@ struct vp56_context { VLC runv_vlc[2]; VLC ract_vlc[2][3][6]; unsigned int nb_null[2][2]; /* number of consecutive NULL DC/AC */ + + int have_undamaged_frame; + int discard_frame; }; @@ -221,7 +224,7 @@ int ff_vp56_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, */ extern const uint8_t ff_vp56_norm_shift[256]; -void ff_vp56_init_range_decoder(VP56RangeCoder *c, const uint8_t *buf, int buf_size); +int ff_vp56_init_range_decoder(VP56RangeCoder *c, const uint8_t *buf, int buf_size); static av_always_inline unsigned int vp56_rac_renorm(VP56RangeCoder *c) { diff --git a/libavcodec/vp56rac.c b/libavcodec/vp56rac.c index 6061b7ee72..e70302bf85 100644 --- a/libavcodec/vp56rac.c +++ b/libavcodec/vp56rac.c @@ -37,11 +37,14 @@ const uint8_t ff_vp56_norm_shift[256]= { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; -void ff_vp56_init_range_decoder(VP56RangeCoder *c, const uint8_t *buf, int buf_size) +int ff_vp56_init_range_decoder(VP56RangeCoder *c, const uint8_t *buf, int buf_size) { c->high = 255; c->bits = -16; c->buffer = buf; c->end = buf + buf_size; + if (buf_size < 1) + return AVERROR_INVALIDDATA; c->code_word = bytestream_get_be24(&c->buffer); + return 0; } diff --git a/libavcodec/vp6.c b/libavcodec/vp6.c index a2bb4578d5..4afd67b3a4 100644 --- a/libavcodec/vp6.c +++ b/libavcodec/vp6.c @@ -40,8 +40,8 @@ #define VP6_MAX_HUFF_SIZE 12 -static void vp6_parse_coeff(VP56Context *s); -static void vp6_parse_coeff_huffman(VP56Context *s); +static int vp6_parse_coeff(VP56Context *s); +static int vp6_parse_coeff_huffman(VP56Context *s); static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size) { @@ -52,6 +52,7 @@ static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size) int sub_version; int rows, cols; int res = 0; + int ret; int separated_coeff = buf[0] & 1; s->frames[VP56_FRAME_CURRENT]->key_frame = !(buf[0] & 0x80); @@ -93,7 +94,7 @@ static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size) s->avctx->coded_width = 16 * cols; s->avctx->coded_height = 16 * rows; } else { - int ret = ff_set_dimensions(s->avctx, 16 * cols, 16 * rows); + ret = ff_set_dimensions(s->avctx, 16 * cols, 16 * rows); if (ret < 0) return ret; @@ -105,7 +106,9 @@ static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size) res = VP56_SIZE_CHANGE; } - ff_vp56_init_range_decoder(c, buf+6, buf_size-6); + ret = ff_vp56_init_range_decoder(c, buf+6, buf_size-6); + if (ret < 0) + goto fail; vp56_rac_gets(c, 2); parse_filter_info = s->filter_header; @@ -122,7 +125,9 @@ static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size) buf += 2; buf_size -= 2; } - ff_vp56_init_range_decoder(c, buf+1, buf_size-1); + ret = ff_vp56_init_range_decoder(c, buf+1, buf_size-1); + if (ret < 0) + return ret; s->golden_frame = vp56_rac_get(c); if (s->filter_header) { @@ -157,15 +162,16 @@ static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size) buf += coeff_offset; buf_size -= coeff_offset; if (buf_size < 0) { - if (s->frames[VP56_FRAME_CURRENT]->key_frame) - ff_set_dimensions(s->avctx, 0, 0); - return AVERROR_INVALIDDATA; + ret = AVERROR_INVALIDDATA; + goto fail; } if (s->use_huffman) { s->parse_coeff = vp6_parse_coeff_huffman; init_get_bits(&s->gb, buf, buf_size<<3); } else { - ff_vp56_init_range_decoder(&s->cc, buf, buf_size); + ret = ff_vp56_init_range_decoder(&s->cc, buf, buf_size); + if (ret < 0) + goto fail; s->ccp = &s->cc; } } else { @@ -173,6 +179,10 @@ static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size) } return res; +fail: + if (res == VP56_SIZE_CHANGE) + ff_set_dimensions(s->avctx, 0, 0); + return ret; } static void vp6_coeff_order_table_init(VP56Context *s) @@ -380,7 +390,7 @@ static unsigned vp6_get_nb_null(VP56Context *s) return val; } -static void vp6_parse_coeff_huffman(VP56Context *s) +static int vp6_parse_coeff_huffman(VP56Context *s) { VP56Model *model = s->modelp; uint8_t *permute = s->idct_scantable; @@ -402,7 +412,7 @@ static void vp6_parse_coeff_huffman(VP56Context *s) break; } else { if (get_bits_left(&s->gb) <= 0) - return; + return AVERROR_INVALIDDATA; coeff = get_vlc2(&s->gb, vlc_coeff->table, FF_HUFFMAN_BITS, 3); if (coeff == 0) { if (coeff_idx) { @@ -437,9 +447,10 @@ static void vp6_parse_coeff_huffman(VP56Context *s) vlc_coeff = &s->ract_vlc[pt][ct][cg]; } } + return 0; } -static void vp6_parse_coeff(VP56Context *s) +static int vp6_parse_coeff(VP56Context *s) { VP56RangeCoder *c = s->ccp; VP56Model *model = s->modelp; @@ -449,6 +460,11 @@ static void vp6_parse_coeff(VP56Context *s) int b, i, cg, idx, ctx; int pt = 0; /* plane type (0 for Y, 1 for U or V) */ + if (c->end <= c->buffer && c->bits >= 0) { + av_log(s->avctx, AV_LOG_ERROR, "End of AC stream reached in vp6_parse_coeff\n"); + return AVERROR_INVALIDDATA; + } + for (b=0; b<6; b++) { int ct = 1; /* code type */ int run = 1; @@ -512,6 +528,7 @@ static void vp6_parse_coeff(VP56Context *s) s->left_block[ff_vp56_b6to4[b]].not_null_dc = s->above_blocks[s->above_block_idx[b]].not_null_dc = !!s->block_coeff[b][0]; } + return 0; } static int vp6_block_variance(uint8_t *src, int stride) diff --git a/libavcodec/vp8.c b/libavcodec/vp8.c index 64037fc089..06d768a576 100644 --- a/libavcodec/vp8.c +++ b/libavcodec/vp8.c @@ -260,6 +260,7 @@ static int setup_partitions(VP8Context *s, const uint8_t *buf, int buf_size) { const uint8_t *sizes = buf; int i; + int ret; s->num_coeff_partitions = 1 << vp8_rac_get_uint(&s->c, 2); @@ -273,13 +274,13 @@ static int setup_partitions(VP8Context *s, const uint8_t *buf, int buf_size) if (buf_size - size < 0) return -1; - ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, size); + ret = ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, size); + if (ret < 0) + return ret; buf += size; buf_size -= size; } - ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, buf_size); - - return 0; + return ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, buf_size); } static void vp7_get_quants(VP8Context *s) @@ -517,7 +518,9 @@ static int vp7_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_si memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_epel_pixels_tab, sizeof(s->put_pixels_tab)); - ff_vp56_init_range_decoder(c, buf, part1_size); + ret = ff_vp56_init_range_decoder(c, buf, part1_size); + if (ret < 0) + return ret; buf += part1_size; buf_size -= part1_size; @@ -569,7 +572,9 @@ static int vp7_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_si s->lf_delta.enabled = 0; s->num_coeff_partitions = 1; - ff_vp56_init_range_decoder(&s->coeff_partition[0], buf, buf_size); + ret = ff_vp56_init_range_decoder(&s->coeff_partition[0], buf, buf_size); + if (ret < 0) + return ret; if (!s->macroblocks_base || /* first frame */ width != s->avctx->width || height != s->avctx->height || @@ -600,6 +605,8 @@ static int vp7_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_si s->fade_present = vp8_rac_get(c); } + if (c->end <= c->buffer && c->bits >= 0) + return AVERROR_INVALIDDATA; /* E. Fading information for previous frame */ if (s->fade_present && vp8_rac_get(c)) { if ((ret = vp7_fade_frame(s ,c)) < 0) @@ -698,7 +705,9 @@ static int vp8_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_si memset(&s->lf_delta, 0, sizeof(s->lf_delta)); } - ff_vp56_init_range_decoder(c, buf, header_size); + ret = ff_vp56_init_range_decoder(c, buf, header_size); + if (ret < 0) + return ret; buf += header_size; buf_size -= header_size; @@ -2274,7 +2283,7 @@ static void vp8_decode_mv_mb_modes(AVCodecContext *avctx, VP8Frame *cur_frame, #define update_pos(td, mb_y, mb_x) while(0) #endif -static av_always_inline void decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata, +static av_always_inline int decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr, int is_vp7) { VP8Context *s = avctx->priv_data; @@ -2290,6 +2299,10 @@ static av_always_inline void decode_mb_row_no_filter(AVCodecContext *avctx, void curframe->tf.f->data[1] + 8 * mb_y * s->uvlinesize, curframe->tf.f->data[2] + 8 * mb_y * s->uvlinesize }; + + if (c->end <= c->buffer && c->bits >= 0) + return AVERROR_INVALIDDATA; + if (mb_y == 0) prev_td = td; else @@ -2318,6 +2331,8 @@ static av_always_inline void decode_mb_row_no_filter(AVCodecContext *avctx, void s->mv_max.x = ((s->mb_width - 1) << 6) + MARGIN; for (mb_x = 0; mb_x < s->mb_width; mb_x++, mb_xy++, mb++) { + if (c->end <= c->buffer && c->bits >= 0) + return AVERROR_INVALIDDATA; // Wait for previous thread to read mb_x+2, and reach mb_y-1. if (prev_td != td) { if (threadnr != 0) { @@ -2393,18 +2408,19 @@ static av_always_inline void decode_mb_row_no_filter(AVCodecContext *avctx, void update_pos(td, mb_y, mb_x); } } + return 0; } -static void vp7_decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata, +static int vp7_decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr) { - decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr, 1); + return decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr, 1); } -static void vp8_decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata, +static int vp8_decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr) { - decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr, 0); + return decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr, 0); } static av_always_inline void filter_mb_row(AVCodecContext *avctx, void *tdata, @@ -2487,13 +2503,16 @@ int vp78_decode_mb_row_sliced(AVCodecContext *avctx, void *tdata, int jobnr, VP8ThreadData *next_td = NULL, *prev_td = NULL; VP8Frame *curframe = s->curframe; int mb_y, num_jobs = s->num_jobs; + int ret; td->thread_nr = threadnr; for (mb_y = jobnr; mb_y < s->mb_height; mb_y += num_jobs) { - if (mb_y >= s->mb_height) - break; td->thread_mb_pos = mb_y << 16; - s->decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr); + ret = s->decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr); + if (ret < 0) { + update_pos(td, s->mb_height, INT_MAX & 0xFFFF); + return ret; + } if (s->deblock_filter) s->filter_mb_row(avctx, tdata, jobnr, threadnr); update_pos(td, mb_y, INT_MAX & 0xFFFF); @@ -2530,6 +2549,8 @@ int vp78_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, enum AVDiscard skip_thresh; VP8Frame *av_uninit(curframe), *prev_frame; + av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVA420P || avctx->pix_fmt == AV_PIX_FMT_YUV420P); + if (is_vp7) ret = vp7_decode_frame_header(s, avpkt->data, avpkt->size); else diff --git a/libavcodec/vp8.h b/libavcodec/vp8.h index cfd82aaaba..81ffe2c144 100644 --- a/libavcodec/vp8.h +++ b/libavcodec/vp8.h @@ -275,7 +275,7 @@ typedef struct VP8Context { */ int mb_layout; - void (*decode_mb_row_no_filter)(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr); + int (*decode_mb_row_no_filter)(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr); void (*filter_mb_row)(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr); int vp7; diff --git a/libavcodec/vp8dsp.c b/libavcodec/vp8dsp.c index 07bea69c78..fed5c67a90 100644 --- a/libavcodec/vp8dsp.c +++ b/libavcodec/vp8dsp.c @@ -53,7 +53,8 @@ static void name ## _idct_dc_add4y_c(uint8_t *dst, int16_t block[4][16], \ #if CONFIG_VP7_DECODER static void vp7_luma_dc_wht_c(int16_t block[4][4][16], int16_t dc[16]) { - int i, a1, b1, c1, d1; + int i; + unsigned a1, b1, c1, d1; int16_t tmp[16]; for (i = 0; i < 4; i++) { @@ -61,10 +62,10 @@ static void vp7_luma_dc_wht_c(int16_t block[4][4][16], int16_t dc[16]) b1 = (dc[i * 4 + 0] - dc[i * 4 + 2]) * 23170; c1 = dc[i * 4 + 1] * 12540 - dc[i * 4 + 3] * 30274; d1 = dc[i * 4 + 1] * 30274 + dc[i * 4 + 3] * 12540; - tmp[i * 4 + 0] = (a1 + d1) >> 14; - tmp[i * 4 + 3] = (a1 - d1) >> 14; - tmp[i * 4 + 1] = (b1 + c1) >> 14; - tmp[i * 4 + 2] = (b1 - c1) >> 14; + tmp[i * 4 + 0] = (int)(a1 + d1) >> 14; + tmp[i * 4 + 3] = (int)(a1 - d1) >> 14; + tmp[i * 4 + 1] = (int)(b1 + c1) >> 14; + tmp[i * 4 + 2] = (int)(b1 - c1) >> 14; } for (i = 0; i < 4; i++) { @@ -73,10 +74,10 @@ static void vp7_luma_dc_wht_c(int16_t block[4][4][16], int16_t dc[16]) c1 = tmp[i + 4] * 12540 - tmp[i + 12] * 30274; d1 = tmp[i + 4] * 30274 + tmp[i + 12] * 12540; AV_ZERO64(dc + i * 4); - block[0][i][0] = (a1 + d1 + 0x20000) >> 18; - block[3][i][0] = (a1 - d1 + 0x20000) >> 18; - block[1][i][0] = (b1 + c1 + 0x20000) >> 18; - block[2][i][0] = (b1 - c1 + 0x20000) >> 18; + block[0][i][0] = (int)(a1 + d1 + 0x20000) >> 18; + block[3][i][0] = (int)(a1 - d1 + 0x20000) >> 18; + block[1][i][0] = (int)(b1 + c1 + 0x20000) >> 18; + block[2][i][0] = (int)(b1 - c1 + 0x20000) >> 18; } } @@ -95,7 +96,8 @@ static void vp7_luma_dc_wht_dc_c(int16_t block[4][4][16], int16_t dc[16]) static void vp7_idct_add_c(uint8_t *dst, int16_t block[16], ptrdiff_t stride) { - int i, a1, b1, c1, d1; + int i; + unsigned a1, b1, c1, d1; int16_t tmp[16]; for (i = 0; i < 4; i++) { @@ -104,10 +106,10 @@ static void vp7_idct_add_c(uint8_t *dst, int16_t block[16], ptrdiff_t stride) c1 = block[i * 4 + 1] * 12540 - block[i * 4 + 3] * 30274; d1 = block[i * 4 + 1] * 30274 + block[i * 4 + 3] * 12540; AV_ZERO64(block + i * 4); - tmp[i * 4 + 0] = (a1 + d1) >> 14; - tmp[i * 4 + 3] = (a1 - d1) >> 14; - tmp[i * 4 + 1] = (b1 + c1) >> 14; - tmp[i * 4 + 2] = (b1 - c1) >> 14; + tmp[i * 4 + 0] = (int)(a1 + d1) >> 14; + tmp[i * 4 + 3] = (int)(a1 - d1) >> 14; + tmp[i * 4 + 1] = (int)(b1 + c1) >> 14; + tmp[i * 4 + 2] = (int)(b1 - c1) >> 14; } for (i = 0; i < 4; i++) { @@ -116,13 +118,13 @@ static void vp7_idct_add_c(uint8_t *dst, int16_t block[16], ptrdiff_t stride) c1 = tmp[i + 4] * 12540 - tmp[i + 12] * 30274; d1 = tmp[i + 4] * 30274 + tmp[i + 12] * 12540; dst[0 * stride + i] = av_clip_uint8(dst[0 * stride + i] + - ((a1 + d1 + 0x20000) >> 18)); + ((int)(a1 + d1 + 0x20000) >> 18)); dst[3 * stride + i] = av_clip_uint8(dst[3 * stride + i] + - ((a1 - d1 + 0x20000) >> 18)); + ((int)(a1 - d1 + 0x20000) >> 18)); dst[1 * stride + i] = av_clip_uint8(dst[1 * stride + i] + - ((b1 + c1 + 0x20000) >> 18)); + ((int)(b1 + c1 + 0x20000) >> 18)); dst[2 * stride + i] = av_clip_uint8(dst[2 * stride + i] + - ((b1 - c1 + 0x20000) >> 18)); + ((int)(b1 - c1 + 0x20000) >> 18)); } } diff --git a/libavcodec/vp9.c b/libavcodec/vp9.c index 5d8ad12b21..e4229eb13f 100644 --- a/libavcodec/vp9.c +++ b/libavcodec/vp9.c @@ -842,7 +842,10 @@ static int decode_frame_header(AVCodecContext *ctx, av_log(ctx, AV_LOG_ERROR, "Invalid compressed header size\n"); return AVERROR_INVALIDDATA; } - ff_vp56_init_range_decoder(&s->c, data2, size2); + res = ff_vp56_init_range_decoder(&s->c, data2, size2); + if (res < 0) + return res; + if (vp56_rac_get_prob_branchy(&s->c, 128)) { // marker bit av_log(ctx, AV_LOG_ERROR, "Marker bit was set\n"); return AVERROR_INVALIDDATA; @@ -3703,11 +3706,10 @@ static av_always_inline void adapt_prob(uint8_t *p, unsigned ct0, unsigned ct1, if (!ct) return; + update_factor = FASTDIV(update_factor * FFMIN(ct, max_count), max_count); p1 = *p; - p2 = ((ct0 << 8) + (ct >> 1)) / ct; + p2 = ((((int64_t) ct0) << 8) + (ct >> 1)) / ct; p2 = av_clip(p2, 1, 255); - ct = FFMIN(ct, max_count); - update_factor = FASTDIV(update_factor * ct, max_count); // (p1 * (256 - update_factor) + p2 * update_factor + 128) >> 8 *p = p1 + (((p2 - p1) * update_factor + 128) >> 8); @@ -4127,7 +4129,9 @@ static int vp9_decode_frame(AVCodecContext *ctx, void *frame, ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, INT_MAX, 0); return AVERROR_INVALIDDATA; } - ff_vp56_init_range_decoder(&s->c_b[tile_col], data, tile_size); + res = ff_vp56_init_range_decoder(&s->c_b[tile_col], data, tile_size); + if (res < 0) + return res; if (vp56_rac_get_prob_branchy(&s->c_b[tile_col], 128)) { // marker bit ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, INT_MAX, 0); return AVERROR_INVALIDDATA; diff --git a/libavcodec/vp9_parser.c b/libavcodec/vp9_parser.c index 2e9235e657..9900e7ab1f 100644 --- a/libavcodec/vp9_parser.c +++ b/libavcodec/vp9_parser.c @@ -28,6 +28,7 @@ typedef struct VP9ParseContext { int n_frames; // 1-8 int size[8]; + int marker_size; int64_t pts; } VP9ParseContext; @@ -88,6 +89,21 @@ static int parse(AVCodecParserContext *ctx, return 0; } + if (s->n_frames > 0) { + int i; + int size_sum = 0; + + for (i = 0; i < s->n_frames ;i++) + size_sum += s->size[i]; + size_sum += s->marker_size; + + if (size_sum != size) { + av_log(avctx, AV_LOG_ERROR, "Inconsistent input frame sizes %d %d\n", + size_sum, size); + s->n_frames = 0; + } + } + if (s->n_frames > 0) { *out_data = data; *out_size = s->size[--s->n_frames]; @@ -131,6 +147,7 @@ static int parse(AVCodecParserContext *ctx, data += sz; \ size -= sz; \ } \ + s->marker_size = size; \ parse_frame(ctx, *out_data, *out_size); \ return s->n_frames > 0 ? *out_size : full_size diff --git a/libavcodec/wavpack.c b/libavcodec/wavpack.c index b6022f0fa5..c7855090fc 100644 --- a/libavcodec/wavpack.c +++ b/libavcodec/wavpack.c @@ -85,7 +85,7 @@ typedef struct WavpackContext { #define LEVEL_DECAY(a) (((a) + 0x80) >> 8) -static av_always_inline int get_tail(GetBitContext *gb, int k) +static av_always_inline unsigned get_tail(GetBitContext *gb, int k) { int p, e, res; @@ -184,7 +184,7 @@ static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb, goto error; t += t2; } else { - if (get_bits_left(gb) < t2 - 1) + if (t2 >= 32 || get_bits_left(gb) < t2 - 1) goto error; t += get_bits_long(gb, t2 - 1) | (1 << (t2 - 1)); } @@ -219,7 +219,7 @@ static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb, INC_MED(1); DEC_MED(2); } else { - base = GET_MED(0) + GET_MED(1) + GET_MED(2) * (t - 2); + base = GET_MED(0) + GET_MED(1) + GET_MED(2) * (t - 2U); add = GET_MED(2) - 1; INC_MED(0); INC_MED(1); @@ -239,7 +239,7 @@ static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb, if (get_bits_left(gb) <= 0) goto error; if (get_bits1(gb)) { - add -= (mid - base); + add -= (mid - (unsigned)base); base = mid; } else add = mid - base - 1; @@ -267,7 +267,7 @@ static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc, int bit; if (s->extra_bits) { - S <<= s->extra_bits; + S *= 1 << s->extra_bits; if (s->got_extra_bits && get_bits_left(&s->gb_extra_bits) >= s->extra_bits) { @@ -307,8 +307,8 @@ static float wv_get_value_float(WavpackFrameContext *s, uint32_t *crc, int S) S <<= s->float_shift; sign = S < 0; if (sign) - S = -S; - if (S >= 0x1000000) { + S = -(unsigned)S; + if (S >= 0x1000000U) { if (s->got_extra_bits && get_bits1(&s->gb_extra_bits)) S = get_bits(&s->gb_extra_bits, 23); else @@ -474,7 +474,7 @@ static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb, } if (type == AV_SAMPLE_FMT_S16P) { - if (FFABS(L) + FFABS(R) > (1<<19)) { + if (FFABS((int64_t)L) + FFABS((int64_t)R) > (1<<19)) { av_log(s->avctx, AV_LOG_ERROR, "sample %d %d too large\n", L, R); return AVERROR_INVALIDDATA; } @@ -548,7 +548,7 @@ static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb, if (type != AV_SAMPLE_FMT_S16P) S = T + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10); else - S = T + ((s->decorr[i].weightA * A + 512) >> 10); + S = T + ((int)(s->decorr[i].weightA * (unsigned)A + 512) >> 10); if (A && T) s->decorr[i].weightA -= ((((T ^ A) >> 30) & 2) - 1) * s->decorr[i].delta; s->decorr[i].samplesA[j] = T = S; @@ -682,7 +682,7 @@ static int wavpack_decode_block(AVCodecContext *avctx, int block_no, s->hybrid_bitrate = s->frame_flags & WV_HYBRID_BITRATE; s->post_shift = bpp * 8 - orig_bpp + ((s->frame_flags >> 13) & 0x1f); s->hybrid_maxclip = ((1LL << (orig_bpp - 1)) - 1); - s->hybrid_minclip = ((-1LL << (orig_bpp - 1))); + s->hybrid_minclip = ((-1UL << (orig_bpp - 1))); s->CRC = bytestream2_get_le32(&gb); // parse metadata blocks @@ -736,13 +736,13 @@ static int wavpack_decode_block(AVCodecContext *avctx, int block_no, } for (i = 0; i < weights; i++) { t = (int8_t)bytestream2_get_byte(&gb); - s->decorr[s->terms - i - 1].weightA = t << 3; + s->decorr[s->terms - i - 1].weightA = t * (1 << 3); if (s->decorr[s->terms - i - 1].weightA > 0) s->decorr[s->terms - i - 1].weightA += (s->decorr[s->terms - i - 1].weightA + 64) >> 7; if (s->stereo_in) { t = (int8_t)bytestream2_get_byte(&gb); - s->decorr[s->terms - i - 1].weightB = t << 3; + s->decorr[s->terms - i - 1].weightB = t * (1 << 3); if (s->decorr[s->terms - i - 1].weightB > 0) s->decorr[s->terms - i - 1].weightB += (s->decorr[s->terms - i - 1].weightB + 64) >> 7; @@ -837,9 +837,9 @@ static int wavpack_decode_block(AVCodecContext *avctx, int block_no, continue; } bytestream2_get_buffer(&gb, val, 4); - if (val[0] > 32) { + if (val[0] > 30) { av_log(avctx, AV_LOG_ERROR, - "Invalid INT32INFO, extra_bits = %d (> 32)\n", val[0]); + "Invalid INT32INFO, extra_bits = %d (> 30)\n", val[0]); continue; } else if (val[0]) { s->extra_bits = val[0]; @@ -872,6 +872,12 @@ static int wavpack_decode_block(AVCodecContext *avctx, int block_no, s->float_flag = bytestream2_get_byte(&gb); s->float_shift = bytestream2_get_byte(&gb); s->float_max_exp = bytestream2_get_byte(&gb); + if (s->float_shift > 31) { + av_log(avctx, AV_LOG_ERROR, + "Invalid FLOATINFO, shift = %d (> 31)\n", s->float_shift); + s->float_shift = 0; + continue; + } got_float = 1; bytestream2_skip(&gb, 1); break; diff --git a/libavcodec/wavpack.h b/libavcodec/wavpack.h index a1b46d5bd7..7fd366a73b 100644 --- a/libavcodec/wavpack.h +++ b/libavcodec/wavpack.h @@ -94,13 +94,13 @@ typedef struct Decorr { typedef struct WvChannel { int median[3]; int slow_level, error_limit; - int bitrate_acc, bitrate_delta; + unsigned bitrate_acc, bitrate_delta; } WvChannel; // macros for manipulating median values #define GET_MED(n) ((c->median[n] >> 4) + 1) -#define DEC_MED(n) c->median[n] -= ((c->median[n] + (128 >> (n)) - 2) / (128 >> (n))) * 2 -#define INC_MED(n) c->median[n] += ((c->median[n] + (128 >> (n)) ) / (128 >> (n))) * 5 +#define DEC_MED(n) c->median[n] -= ((int)(c->median[n] + (128U >> (n)) - 2) / (128 >> (n))) * 2U +#define INC_MED(n) c->median[n] += ((int)(c->median[n] + (128U >> (n)) ) / (128 >> (n))) * 5U // macros for applying weight #define UPDATE_WEIGHT_CLIP(weight, delta, samples, in) \ diff --git a/libavcodec/webp.c b/libavcodec/webp.c index 5c2961ff19..1b3b68c121 100644 --- a/libavcodec/webp.c +++ b/libavcodec/webp.c @@ -694,7 +694,7 @@ static int decode_entropy_coded_image(WebPContext *s, enum ImageRole role, length = offset + get_bits(&s->gb, extra_bits) + 1; } prefix_code = huff_reader_get_symbol(&hg[HUFF_IDX_DIST], &s->gb); - if (prefix_code > 39) { + if (prefix_code > 39U) { av_log(s->avctx, AV_LOG_ERROR, "distance prefix code too large: %d\n", prefix_code); return AVERROR_INVALIDDATA; @@ -1043,7 +1043,7 @@ static int apply_color_indexing_transform(WebPContext *s) uint8_t *line; int pixel_bits = 8 >> pal->size_reduction; - line = av_malloc(img->frame->linesize[0]); + line = av_malloc(img->frame->linesize[0] + AV_INPUT_BUFFER_PADDING_SIZE); if (!line) return AVERROR(ENOMEM); @@ -1099,6 +1099,21 @@ static int apply_color_indexing_transform(WebPContext *s) return 0; } +static void update_canvas_size(AVCodecContext *avctx, int w, int h) +{ + WebPContext *s = avctx->priv_data; + if (s->width && s->width != w) { + av_log(avctx, AV_LOG_WARNING, "Width mismatch. %d != %d\n", + s->width, w); + } + s->width = w; + if (s->height && s->height != h) { + av_log(avctx, AV_LOG_WARNING, "Height mismatch. %d != %d\n", + s->height, h); + } + s->height = h; +} + static int vp8_lossless_decode_frame(AVCodecContext *avctx, AVFrame *p, int *got_frame, uint8_t *data_start, unsigned int data_size, int is_alpha_chunk) @@ -1123,16 +1138,8 @@ static int vp8_lossless_decode_frame(AVCodecContext *avctx, AVFrame *p, w = get_bits(&s->gb, 14) + 1; h = get_bits(&s->gb, 14) + 1; - if (s->width && s->width != w) { - av_log(avctx, AV_LOG_WARNING, "Width mismatch. %d != %d\n", - s->width, w); - } - s->width = w; - if (s->height && s->height != h) { - av_log(avctx, AV_LOG_WARNING, "Height mismatch. %d != %d\n", - s->width, w); - } - s->height = h; + + update_canvas_size(avctx, w, h); ret = ff_set_dimensions(avctx, s->width, s->height); if (ret < 0) @@ -1327,9 +1334,8 @@ static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p, if (!s->initialized) { ff_vp8_decode_init(avctx); s->initialized = 1; - if (s->has_alpha) - avctx->pix_fmt = AV_PIX_FMT_YUVA420P; } + avctx->pix_fmt = s->has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P; s->lossless = 0; if (data_size > INT_MAX) { @@ -1342,6 +1348,14 @@ static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p, pkt.size = data_size; ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt); + if (ret < 0) + return ret; + + if (!*got_frame) + return AVERROR_INVALIDDATA; + + update_canvas_size(avctx, avctx->width, avctx->height); + if (s->has_alpha) { ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data, s->alpha_data_size); diff --git a/libavcodec/wmalosslessdec.c b/libavcodec/wmalosslessdec.c index 8a5ffb86a5..49eaff694f 100644 --- a/libavcodec/wmalosslessdec.c +++ b/libavcodec/wmalosslessdec.c @@ -1129,6 +1129,7 @@ static void save_bits(WmallDecodeCtx *s, GetBitContext* gb, int len, if (len <= 0 || buflen > MAX_FRAMESIZE) { avpriv_request_sample(s->avctx, "Too small input buffer"); s->packet_loss = 1; + s->num_saved_bits = 0; return; } @@ -1237,7 +1238,9 @@ static int decode_packet(AVCodecContext *avctx, void *data, int *got_frame_ptr, (frame_size = show_bits(gb, s->log2_frame_size)) && frame_size <= remaining_bits(s, gb)) { save_bits(s, gb, frame_size, 0); - s->packet_done = !decode_frame(s); + + if (!s->packet_loss) + s->packet_done = !decode_frame(s); } else if (!s->len_prefix && s->num_saved_bits > get_bits_count(&s->gb)) { /* when the frames do not have a length prefix, we don't know the @@ -1252,6 +1255,11 @@ static int decode_packet(AVCodecContext *avctx, void *data, int *got_frame_ptr, } } + if (remaining_bits(s, gb) < 0) { + av_log(avctx, AV_LOG_ERROR, "Overread %d\n", -remaining_bits(s, gb)); + s->packet_loss = 1; + } + if (s->packet_done && !s->packet_loss && remaining_bits(s, gb) > 0) { /* save the rest of the data so that it can be decoded diff --git a/libavcodec/wmv2dec.c b/libavcodec/wmv2dec.c index 99c95d397a..98df381509 100644 --- a/libavcodec/wmv2dec.c +++ b/libavcodec/wmv2dec.c @@ -30,7 +30,7 @@ #include "wmv2.h" -static void parse_mb_skip(Wmv2Context *w) +static int parse_mb_skip(Wmv2Context *w) { int mb_x, mb_y; MpegEncContext *const s = &w->s; @@ -45,6 +45,8 @@ static void parse_mb_skip(Wmv2Context *w) MB_TYPE_16x16 | MB_TYPE_L0; break; case SKIP_TYPE_MPEG: + if (get_bits_left(&s->gb) < s->mb_height * s->mb_width) + return AVERROR_INVALIDDATA; for (mb_y = 0; mb_y < s->mb_height; mb_y++) for (mb_x = 0; mb_x < s->mb_width; mb_x++) mb_type[mb_y * s->mb_stride + mb_x] = @@ -52,6 +54,8 @@ static void parse_mb_skip(Wmv2Context *w) break; case SKIP_TYPE_ROW: for (mb_y = 0; mb_y < s->mb_height; mb_y++) { + if (get_bits_left(&s->gb) < 1) + return AVERROR_INVALIDDATA; if (get_bits1(&s->gb)) { for (mb_x = 0; mb_x < s->mb_width; mb_x++) mb_type[mb_y * s->mb_stride + mb_x] = @@ -65,6 +69,8 @@ static void parse_mb_skip(Wmv2Context *w) break; case SKIP_TYPE_COL: for (mb_x = 0; mb_x < s->mb_width; mb_x++) { + if (get_bits_left(&s->gb) < 1) + return AVERROR_INVALIDDATA; if (get_bits1(&s->gb)) { for (mb_y = 0; mb_y < s->mb_height; mb_y++) mb_type[mb_y * s->mb_stride + mb_x] = @@ -77,6 +83,7 @@ static void parse_mb_skip(Wmv2Context *w) } break; } + return 0; } static int decode_ext_header(Wmv2Context *w) @@ -170,9 +177,12 @@ int ff_wmv2_decode_secondary_picture_header(MpegEncContext *s) } } else { int cbp_index; + int ret; w->j_type = 0; - parse_mb_skip(w); + ret = parse_mb_skip(w); + if (ret < 0) + return ret; cbp_index = decode012(&s->gb); w->cbp_table_index = wmv2_get_cbp_table_index(s, cbp_index); @@ -352,6 +362,8 @@ int ff_wmv2_decode_mb(MpegEncContext *s, int16_t block[6][64]) w->hshift = 0; return 0; } + if (get_bits_left(&s->gb) <= 0) + return AVERROR_INVALIDDATA; code = get_vlc2(&s->gb, ff_mb_non_intra_vlc[w->cbp_table_index].table, MB_NON_INTRA_VLC_BITS, 3); @@ -362,6 +374,8 @@ int ff_wmv2_decode_mb(MpegEncContext *s, int16_t block[6][64]) cbp = code & 0x3f; } else { s->mb_intra = 1; + if (get_bits_left(&s->gb) <= 0) + return AVERROR_INVALIDDATA; code = get_vlc2(&s->gb, ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS, 2); if (code < 0) { av_log(s->avctx, AV_LOG_ERROR, diff --git a/libavcodec/wmv2dsp.c b/libavcodec/wmv2dsp.c index 40e0bef0da..7b59d10a43 100644 --- a/libavcodec/wmv2dsp.c +++ b/libavcodec/wmv2dsp.c @@ -48,8 +48,8 @@ static void wmv2_idct_row(short * b) a4 = W0 * b[0] - W0 * b[4]; /* step 2 */ - s1 = (181 * (a1 - a5 + a7 - a3) + 128) >> 8; // 1, 3, 5, 7 - s2 = (181 * (a1 - a5 - a7 + a3) + 128) >> 8; + s1 = (int)(181U * (a1 - a5 + a7 - a3) + 128) >> 8; // 1, 3, 5, 7 + s2 = (int)(181U * (a1 - a5 - a7 + a3) + 128) >> 8; /* step 3 */ b[0] = (a0 + a2 + a1 + a5 + (1 << 7)) >> 8; @@ -78,8 +78,8 @@ static void wmv2_idct_col(short * b) a4 = (W0 * b[8 * 0] - W0 * b[8 * 4] ) >> 3; /* step 2 */ - s1 = (181 * (a1 - a5 + a7 - a3) + 128) >> 8; - s2 = (181 * (a1 - a5 - a7 + a3) + 128) >> 8; + s1 = (int)(181U * (a1 - a5 + a7 - a3) + 128) >> 8; + s2 = (int)(181U * (a1 - a5 - a7 + a3) + 128) >> 8; /* step 3 */ b[8 * 0] = (a0 + a2 + a1 + a5 + (1 << 13)) >> 14; diff --git a/libavcodec/wnv1.c b/libavcodec/wnv1.c index 9ff99b2f98..915e9c7dc9 100644 --- a/libavcodec/wnv1.c +++ b/libavcodec/wnv1.c @@ -52,7 +52,7 @@ static inline int wnv1_get_code(WNV1Context *w, int base_value) if (v == 15) return ff_reverse[get_bits(&w->gb, 8 - w->shift)]; else - return base_value + ((v - 7) << w->shift); + return base_value + ((v - 7U) << w->shift); } static int decode_frame(AVCodecContext *avctx, @@ -68,7 +68,7 @@ static int decode_frame(AVCodecContext *avctx, int prev_y = 0, prev_u = 0, prev_v = 0; uint8_t *rbuf; - if (buf_size <= 8) { + if (buf_size < 8 + avctx->height * (avctx->width/2)/8) { av_log(avctx, AV_LOG_ERROR, "Packet size %d is too small\n", buf_size); return AVERROR_INVALIDDATA; } diff --git a/libavcodec/x86/hevcdsp_init.c b/libavcodec/x86/hevcdsp_init.c index 0de01637ad..09eb06d0c9 100644 --- a/libavcodec/x86/hevcdsp_init.c +++ b/libavcodec/x86/hevcdsp_init.c @@ -753,6 +753,10 @@ void ff_hevc_dsp_init_x86(HEVCDSPContext *c, const int bit_depth) c->transform_add[3] = ff_hevc_transform_add32_8_avx; } if (EXTERNAL_AVX2(cpu_flags)) { + c->sao_band_filter[0] = ff_hevc_sao_band_filter_8_8_avx2; + c->sao_band_filter[1] = ff_hevc_sao_band_filter_16_8_avx2; + } + if (EXTERNAL_AVX2_FAST(cpu_flags)) { c->idct_dc[2] = ff_hevc_idct16x16_dc_8_avx2; c->idct_dc[3] = ff_hevc_idct32x32_dc_8_avx2; if (ARCH_X86_64) { @@ -897,7 +901,9 @@ void ff_hevc_dsp_init_x86(HEVCDSPContext *c, const int bit_depth) SAO_BAND_INIT(10, avx); } if (EXTERNAL_AVX2(cpu_flags)) { - + c->sao_band_filter[0] = ff_hevc_sao_band_filter_8_10_avx2; + } + if (EXTERNAL_AVX2_FAST(cpu_flags)) { c->idct_dc[2] = ff_hevc_idct16x16_dc_10_avx2; c->idct_dc[3] = ff_hevc_idct32x32_dc_10_avx2; if (ARCH_X86_64) { @@ -1095,6 +1101,9 @@ void ff_hevc_dsp_init_x86(HEVCDSPContext *c, const int bit_depth) SAO_BAND_INIT(12, avx); } if (EXTERNAL_AVX2(cpu_flags)) { + c->sao_band_filter[0] = ff_hevc_sao_band_filter_8_12_avx2; + } + if (EXTERNAL_AVX2_FAST(cpu_flags)) { c->idct_dc[2] = ff_hevc_idct16x16_dc_12_avx2; c->idct_dc[3] = ff_hevc_idct32x32_dc_12_avx2; diff --git a/libavcodec/x86/huffyuvencdsp.asm b/libavcodec/x86/huffyuvencdsp.asm index a55a1de65d..7a1ce2e839 100644 --- a/libavcodec/x86/huffyuvencdsp.asm +++ b/libavcodec/x86/huffyuvencdsp.asm @@ -42,10 +42,11 @@ cglobal diff_bytes, 4,5,2, dst, src1, src2, w %define i t0q %endmacro -; label to jump to if w < regsize -%macro DIFF_BYTES_LOOP_PREP 1 +; labels to jump to if w < regsize and w < 0 +%macro DIFF_BYTES_LOOP_PREP 2 mov i, wq and i, -2 * regsize + js %2 jz %1 add dstq, i add src1q, i @@ -87,7 +88,7 @@ cglobal diff_bytes, 4,5,2, dst, src1, src2, w %if mmsize > 16 ; fall back to narrower xmm %define regsize mmsize / 2 - DIFF_BYTES_LOOP_PREP .setup_loop_gpr_aa + DIFF_BYTES_LOOP_PREP .setup_loop_gpr_aa, .end_aa .loop2_%1%2: DIFF_BYTES_LOOP_CORE %1, %2, xm0, xm1 add i, 2 * regsize @@ -114,7 +115,7 @@ cglobal diff_bytes, 4,5,2, dst, src1, src2, w INIT_MMX mmx DIFF_BYTES_PROLOGUE %define regsize mmsize - DIFF_BYTES_LOOP_PREP .skip_main_aa + DIFF_BYTES_LOOP_PREP .skip_main_aa, .end_aa DIFF_BYTES_BODY a, a %undef i %endif @@ -122,7 +123,7 @@ DIFF_BYTES_PROLOGUE INIT_XMM sse2 DIFF_BYTES_PROLOGUE %define regsize mmsize - DIFF_BYTES_LOOP_PREP .skip_main_aa + DIFF_BYTES_LOOP_PREP .skip_main_aa, .end_aa test dstq, regsize - 1 jnz .loop_uu test src1q, regsize - 1 @@ -138,7 +139,7 @@ DIFF_BYTES_PROLOGUE %define regsize mmsize ; Directly using unaligned SSE2 version is marginally faster than ; branching based on arguments. - DIFF_BYTES_LOOP_PREP .skip_main_uu + DIFF_BYTES_LOOP_PREP .skip_main_uu, .end_uu test dstq, regsize - 1 jnz .loop_uu test src1q, regsize - 1 diff --git a/libavcodec/x86/huffyuvencdsp_mmx.c b/libavcodec/x86/huffyuvencdsp_mmx.c index 0ba4358165..9767b212da 100644 --- a/libavcodec/x86/huffyuvencdsp_mmx.c +++ b/libavcodec/x86/huffyuvencdsp_mmx.c @@ -98,7 +98,7 @@ av_cold void ff_huffyuvencdsp_init_x86(HuffYUVEncDSPContext *c) c->diff_bytes = ff_diff_bytes_sse2; } - if (EXTERNAL_AVX2(cpu_flags)) { + if (EXTERNAL_AVX2_FAST(cpu_flags)) { c->diff_bytes = ff_diff_bytes_avx2; } } diff --git a/libavcodec/x86/jpeg2000dsp_init.c b/libavcodec/x86/jpeg2000dsp_init.c index 0dbd2db7f5..baa81383ea 100644 --- a/libavcodec/x86/jpeg2000dsp_init.c +++ b/libavcodec/x86/jpeg2000dsp_init.c @@ -44,7 +44,7 @@ av_cold void ff_jpeg2000dsp_init_x86(Jpeg2000DSPContext *c) c->mct_decode[FF_DWT97] = ff_ict_float_avx; } - if (EXTERNAL_AVX2(cpu_flags)) { + if (EXTERNAL_AVX2_FAST(cpu_flags)) { c->mct_decode[FF_DWT53] = ff_rct_int_avx2; } } diff --git a/libavcodec/x86/mlpdsp_init.c b/libavcodec/x86/mlpdsp_init.c index e9d9b1bf18..7f5e6b11d5 100644 --- a/libavcodec/x86/mlpdsp_init.c +++ b/libavcodec/x86/mlpdsp_init.c @@ -199,6 +199,6 @@ av_cold void ff_mlpdsp_init_x86(MLPDSPContext *c) #endif if (ARCH_X86_64 && EXTERNAL_SSE4(cpu_flags)) c->mlp_rematrix_channel = ff_mlp_rematrix_channel_sse4; - if (ARCH_X86_64 && EXTERNAL_AVX2(cpu_flags) && cpu_flags & AV_CPU_FLAG_BMI2) + if (ARCH_X86_64 && EXTERNAL_AVX2_FAST(cpu_flags) && cpu_flags & AV_CPU_FLAG_BMI2) c->mlp_rematrix_channel = ff_mlp_rematrix_channel_avx2_bmi2; } diff --git a/libavcodec/x86/mpegvideodsp.c b/libavcodec/x86/mpegvideodsp.c index 941a8e2e4c..5dcfd76a61 100644 --- a/libavcodec/x86/mpegvideodsp.c +++ b/libavcodec/x86/mpegvideodsp.c @@ -53,8 +53,9 @@ static void gmc_mmx(uint8_t *dst, uint8_t *src, const int dyh = (dyy - (1 << (16 + shift))) * (h - 1); const int dxh = dxy * (h - 1); const int dyw = dyx * (w - 1); - int need_emu = (unsigned) ix >= width - w || - (unsigned) iy >= height - h; + int need_emu = (unsigned) ix >= width - w || width < w || + (unsigned) iy >= height - h || height< h + ; if ( // non-constant fullpel offset (3% of blocks) ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) | diff --git a/libavcodec/x86/pixblockdsp_init.c b/libavcodec/x86/pixblockdsp_init.c index 4d06a44c6d..b9027dee54 100644 --- a/libavcodec/x86/pixblockdsp_init.c +++ b/libavcodec/x86/pixblockdsp_init.c @@ -39,12 +39,14 @@ av_cold void ff_pixblockdsp_init_x86(PixblockDSPContext *c, if (EXTERNAL_MMX(cpu_flags)) { if (!high_bit_depth) c->get_pixels = ff_get_pixels_mmx; + c->diff_pixels_unaligned = c->diff_pixels = ff_diff_pixels_mmx; } if (EXTERNAL_SSE2(cpu_flags)) { if (!high_bit_depth) c->get_pixels = ff_get_pixels_sse2; + c->diff_pixels_unaligned = c->diff_pixels = ff_diff_pixels_sse2; } } diff --git a/libavcodec/x86/synth_filter_init.c b/libavcodec/x86/synth_filter_init.c index 0649ea20a6..9ef00cdb0a 100644 --- a/libavcodec/x86/synth_filter_init.c +++ b/libavcodec/x86/synth_filter_init.c @@ -67,7 +67,7 @@ av_cold void ff_synth_filter_init_x86(SynthFilterContext *s) if (EXTERNAL_AVX_FAST(cpu_flags)) { s->synth_filter_float = synth_filter_avx; } - if (EXTERNAL_FMA3(cpu_flags) && !(cpu_flags & AV_CPU_FLAG_AVXSLOW)) { + if (EXTERNAL_FMA3_FAST(cpu_flags)) { s->synth_filter_float = synth_filter_fma3; } #endif /* HAVE_YASM */ diff --git a/libavcodec/x86/v210enc_init.c b/libavcodec/x86/v210enc_init.c index ee48e80538..8abb152c4f 100644 --- a/libavcodec/x86/v210enc_init.c +++ b/libavcodec/x86/v210enc_init.c @@ -45,7 +45,7 @@ av_cold void ff_v210enc_init_x86(V210EncContext *s) if (EXTERNAL_AVX(cpu_flags)) s->pack_line_8 = ff_v210_planar_pack_8_avx; - if (EXTERNAL_AVX2(cpu_flags)) { + if (EXTERNAL_AVX2_FAST(cpu_flags)) { s->pack_line_8 = ff_v210_planar_pack_8_avx2; s->pack_line_10 = ff_v210_planar_pack_10_avx2; s->sample_factor = 2; diff --git a/libavcodec/x86/vc1dsp_init.c b/libavcodec/x86/vc1dsp_init.c index c8943fa2f7..c53a1328f2 100644 --- a/libavcodec/x86/vc1dsp_init.c +++ b/libavcodec/x86/vc1dsp_init.c @@ -106,10 +106,12 @@ av_cold void ff_vc1dsp_init_x86(VC1DSPContext *dsp) { int cpu_flags = av_get_cpu_flags(); - if (HAVE_6REGS && INLINE_MMX(cpu_flags) && EXTERNAL_MMX(cpu_flags)) + if (HAVE_6REGS && INLINE_MMX(cpu_flags)) + if (EXTERNAL_MMX(cpu_flags)) ff_vc1dsp_init_mmx(dsp); - if (HAVE_6REGS && INLINE_MMXEXT(cpu_flags) && EXTERNAL_MMXEXT(cpu_flags)) + if (HAVE_6REGS && INLINE_MMXEXT(cpu_flags)) + if (EXTERNAL_MMXEXT(cpu_flags)) ff_vc1dsp_init_mmxext(dsp); #define ASSIGN_LF(EXT) \ diff --git a/libavcodec/x86/vp9dsp_init.c b/libavcodec/x86/vp9dsp_init.c index 8efb18c89f..469a661717 100644 --- a/libavcodec/x86/vp9dsp_init.c +++ b/libavcodec/x86/vp9dsp_init.c @@ -377,7 +377,7 @@ av_cold void ff_vp9dsp_init_x86(VP9DSPContext *dsp, int bpp, int bitexact) init_ipred(32, avx, v, VERT); } - if (EXTERNAL_AVX2(cpu_flags)) { + if (EXTERNAL_AVX2_FAST(cpu_flags)) { init_fpel_func(1, 1, 32, avg, _8, avx2); init_fpel_func(0, 1, 64, avg, _8, avx2); if (ARCH_X86_64) { diff --git a/libavcodec/x86/vp9dsp_init_16bpp.c b/libavcodec/x86/vp9dsp_init_16bpp.c index 4ceb4d4b49..eb67499c96 100644 --- a/libavcodec/x86/vp9dsp_init_16bpp.c +++ b/libavcodec/x86/vp9dsp_init_16bpp.c @@ -129,7 +129,7 @@ av_cold void ff_vp9dsp_init_16bpp_x86(VP9DSPContext *dsp) init_ipred_funcs(hd, HOR_DOWN, 16, avx); } - if (EXTERNAL_AVX2(cpu_flags)) { + if (EXTERNAL_AVX2_FAST(cpu_flags)) { init_fpel_func(2, 1, 32, avg, _16, avx2); init_fpel_func(1, 1, 64, avg, _16, avx2); init_fpel_func(0, 1, 128, avg, _16, avx2); diff --git a/libavcodec/x86/vp9dsp_init_16bpp_template.c b/libavcodec/x86/vp9dsp_init_16bpp_template.c index 90cdcc9ace..4840b2844e 100644 --- a/libavcodec/x86/vp9dsp_init_16bpp_template.c +++ b/libavcodec/x86/vp9dsp_init_16bpp_template.c @@ -225,7 +225,7 @@ av_cold void INIT_FUNC(VP9DSPContext *dsp, int bitexact) init_lpf_funcs(BPC, avx); } - if (EXTERNAL_AVX2(cpu_flags)) { + if (EXTERNAL_AVX2_FAST(cpu_flags)) { #if HAVE_AVX2_EXTERNAL init_subpel3_32_64(0, put, BPC, avx2); init_subpel3_32_64(1, avg, BPC, avx2); diff --git a/libavcodec/xan.c b/libavcodec/xan.c index 662386af9a..cafcbed9dc 100644 --- a/libavcodec/xan.c +++ b/libavcodec/xan.c @@ -130,7 +130,10 @@ static int xan_huffman_decode(uint8_t *dest, int dest_len, return ret; while (val != 0x16) { - unsigned idx = val - 0x17 + get_bits1(&gb) * byte; + unsigned idx; + if (get_bits_left(&gb) < 1) + return AVERROR_INVALIDDATA; + idx = val - 0x17 + get_bits1(&gb) * byte; if (idx >= 2 * byte) return AVERROR_INVALIDDATA; val = src[idx]; @@ -262,7 +265,7 @@ static inline void xan_wc3_copy_pixel_run(XanContext *s, AVFrame *frame, prevframe_index = (y + motion_y) * stride + x + motion_x; prevframe_x = x + motion_x; - if (prev_palette_plane == palette_plane && FFABS(curframe_index - prevframe_index) < pixel_count) { + if (prev_palette_plane == palette_plane && FFABS(motion_x + width*motion_y) < pixel_count) { avpriv_request_sample(s->avctx, "Overlapping copy"); return ; } diff --git a/libavcodec/xwddec.c b/libavcodec/xwddec.c index 64cd8418a2..25c64e0e14 100644 --- a/libavcodec/xwddec.c +++ b/libavcodec/xwddec.c @@ -39,6 +39,7 @@ static int xwd_decode_frame(AVCodecContext *avctx, void *data, uint32_t pixformat, pixdepth, bunit, bitorder, bpad; uint32_t rgb[3]; uint8_t *ptr; + int width, height; GetByteContext gb; if (buf_size < XWD_HEADER_SIZE) @@ -60,8 +61,8 @@ static int xwd_decode_frame(AVCodecContext *avctx, void *data, pixformat = bytestream2_get_be32u(&gb); pixdepth = bytestream2_get_be32u(&gb); - avctx->width = bytestream2_get_be32u(&gb); - avctx->height = bytestream2_get_be32u(&gb); + width = bytestream2_get_be32u(&gb); + height = bytestream2_get_be32u(&gb); xoffset = bytestream2_get_be32u(&gb); be = bytestream2_get_be32u(&gb); bunit = bytestream2_get_be32u(&gb); @@ -77,6 +78,9 @@ static int xwd_decode_frame(AVCodecContext *avctx, void *data, ncolors = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, header_size - (XWD_HEADER_SIZE - 20)); + if ((ret = ff_set_dimensions(avctx, width, height)) < 0) + return ret; + av_log(avctx, AV_LOG_DEBUG, "pixformat %"PRIu32", pixdepth %"PRIu32", bunit %"PRIu32", bitorder %"PRIu32", bpad %"PRIu32"\n", pixformat, pixdepth, bunit, bitorder, bpad); @@ -157,9 +161,9 @@ static int xwd_decode_frame(AVCodecContext *avctx, void *data, case XWD_GRAY_SCALE: if (bpp != 1 && bpp != 8) return AVERROR_INVALIDDATA; - if (pixdepth == 1) { + if (bpp == 1 && pixdepth == 1) { avctx->pix_fmt = AV_PIX_FMT_MONOWHITE; - } else if (pixdepth == 8) { + } else if (bpp == 8 && pixdepth == 8) { avctx->pix_fmt = AV_PIX_FMT_GRAY8; } break; diff --git a/libavcodec/y41pdec.c b/libavcodec/y41pdec.c index 1b177d4262..85a39e4ae2 100644 --- a/libavcodec/y41pdec.c +++ b/libavcodec/y41pdec.c @@ -43,7 +43,7 @@ static int y41p_decode_frame(AVCodecContext *avctx, void *data, uint8_t *y, *u, *v; int i, j, ret; - if (avpkt->size < 3LL * avctx->height * avctx->width / 2) { + if (avpkt->size < 3LL * avctx->height * FFALIGN(avctx->width, 8) / 2) { av_log(avctx, AV_LOG_ERROR, "Insufficient input data.\n"); return AVERROR(EINVAL); } diff --git a/libavcodec/zmbv.c b/libavcodec/zmbv.c index 25a1cd215d..41525cc08c 100644 --- a/libavcodec/zmbv.c +++ b/libavcodec/zmbv.c @@ -408,6 +408,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPac int zret = Z_OK; // Zlib return code int len = buf_size; int hi_ver, lo_ver, ret; + int expected_size; /* parse header */ if (len < 1) @@ -504,6 +505,14 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPac memset(c->prev, 0, avctx->width * avctx->height * (c->bpp / 8)); c->decode_intra= decode_intra; } + if (c->flags & ZMBV_KEYFRAME) { + expected_size = avctx->width * avctx->height * (c->bpp / 8); + } else { + expected_size = (c->bx * c->by * 2 + 3) & ~3; + } + if (avctx->pix_fmt == AV_PIX_FMT_PAL8 && + (c->flags & (ZMBV_DELTAPAL | ZMBV_KEYFRAME))) + expected_size += 768; if (!c->decode_intra) { av_log(avctx, AV_LOG_ERROR, "Error! Got no format or no keyframe!\n"); @@ -519,6 +528,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPac return AVERROR_INVALIDDATA; } memcpy(c->decomp_buf, buf, len); + c->decomp_len = len; } else { // ZLIB-compressed data c->zstream.total_in = c->zstream.total_out = 0; c->zstream.next_in = (uint8_t*)buf; @@ -532,6 +542,11 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPac } c->decomp_len = c->zstream.total_out; } + if (expected_size > c->decomp_len || + (c->flags & ZMBV_KEYFRAME) && expected_size < c->decomp_len) { + av_log(avctx, AV_LOG_ERROR, "decompressed size %d is incorrect, expected %d\n", c->decomp_len, expected_size); + return AVERROR_INVALIDDATA; + } if (c->flags & ZMBV_KEYFRAME) { frame->key_frame = 1; frame->pict_type = AV_PICTURE_TYPE_I; @@ -539,6 +554,8 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPac } else { frame->key_frame = 0; frame->pict_type = AV_PICTURE_TYPE_P; + if (c->decomp_len < 2LL * ((c->width + c->bw - 1) / c->bw) * ((c->height + c->bh - 1) / c->bh)) + return AVERROR_INVALIDDATA; if (c->decomp_len) c->decode_xor(c); } diff --git a/libavdevice/iec61883.c b/libavdevice/iec61883.c index c45ae9ae5c..382b989fb1 100644 --- a/libavdevice/iec61883.c +++ b/libavdevice/iec61883.c @@ -118,14 +118,16 @@ static int iec61883_callback(unsigned char *data, int length, goto exit; } - packet->buf = av_malloc(length); + packet->buf = av_malloc(length + AV_INPUT_BUFFER_PADDING_SIZE); if (!packet->buf) { + av_free(packet); ret = -1; goto exit; } packet->len = length; memcpy(packet->buf, data, length); + memset(packet->buf + length, 0, AV_INPUT_BUFFER_PADDING_SIZE); if (dv->queue_first) { dv->queue_last->next = packet; @@ -199,13 +201,21 @@ static int iec61883_parse_queue_dv(struct iec61883_data *dv, AVPacket *pkt) size = avpriv_dv_produce_packet(dv->dv_demux, pkt, packet->buf, packet->len, -1); dv->queue_first = packet->next; + if (size < 0) + av_free(packet->buf); av_free(packet); dv->packets--; - if (size > 0) - return size; + if (size < 0) + return -1; - return -1; + if (av_packet_from_data(pkt, pkt->data, pkt->size) < 0) { + av_freep(&pkt->data); + av_packet_unref(pkt); + return -1; + } + + return size; } static int iec61883_parse_queue_hdv(struct iec61883_data *dv, AVPacket *pkt) @@ -453,6 +463,7 @@ static int iec61883_close(AVFormatContext *context) } else { iec61883_dv_fb_stop(dv->iec61883_dv); iec61883_dv_fb_close(dv->iec61883_dv); + av_freep(&dv->dv_demux); } while (dv->queue_first) { DVPacket *packet = dv->queue_first; diff --git a/libavfilter/af_amix.c b/libavfilter/af_amix.c index e64e289108..3e5e7ee118 100644 --- a/libavfilter/af_amix.c +++ b/libavfilter/af_amix.c @@ -312,6 +312,9 @@ static int output_frame(AVFilterLink *outlink) calculate_scales(s, nb_samples); + if (nb_samples == 0) + return 0; + out_buf = ff_get_audio_buffer(outlink, nb_samples); if (!out_buf) return AVERROR(ENOMEM); diff --git a/libavfilter/af_dcshift.c b/libavfilter/af_dcshift.c index 7332c12b19..5dbe40824c 100644 --- a/libavfilter/af_dcshift.c +++ b/libavfilter/af_dcshift.c @@ -28,7 +28,7 @@ typedef struct DCShiftContext { const AVClass *class; double dcshift; - double limiterthreshhold; + double limiterthreshold; double limitergain; } DCShiftContext; @@ -47,7 +47,7 @@ static av_cold int init(AVFilterContext *ctx) { DCShiftContext *s = ctx->priv; - s->limiterthreshhold = INT32_MAX * (1.0 - (fabs(s->dcshift) - s->limitergain)); + s->limiterthreshold = INT32_MAX * (1.0 - (fabs(s->dcshift) - s->limitergain)); return 0; } @@ -106,14 +106,14 @@ static int filter_frame(AVFilterLink *inlink, AVFrame *in) d = src[j]; - if (d > s->limiterthreshhold && dcshift > 0) { - d = (d - s->limiterthreshhold) * s->limitergain / - (INT32_MAX - s->limiterthreshhold) + - s->limiterthreshhold + dcshift; - } else if (d < -s->limiterthreshhold && dcshift < 0) { - d = (d + s->limiterthreshhold) * s->limitergain / - (INT32_MAX - s->limiterthreshhold) - - s->limiterthreshhold + dcshift; + if (d > s->limiterthreshold && dcshift > 0) { + d = (d - s->limiterthreshold) * s->limitergain / + (INT32_MAX - s->limiterthreshold) + + s->limiterthreshold + dcshift; + } else if (d < -s->limiterthreshold && dcshift < 0) { + d = (d + s->limiterthreshold) * s->limitergain / + (INT32_MAX - s->limiterthreshold) - + s->limiterthreshold + dcshift; } else { d = dcshift * INT32_MAX + d; } diff --git a/libavfilter/af_pan.c b/libavfilter/af_pan.c index 1eb102c10a..7c02f6720d 100644 --- a/libavfilter/af_pan.c +++ b/libavfilter/af_pan.c @@ -109,7 +109,7 @@ static av_cold int init(AVFilterContext *ctx) if (!pan->args) { av_log(ctx, AV_LOG_ERROR, "pan filter needs a channel layout and a set " - "of channels definitions as parameter\n"); + "of channel definitions as parameter\n"); return AVERROR(EINVAL); } if (!args) @@ -276,7 +276,7 @@ static int config_props(AVFilterLink *link) if (link->channels > MAX_CHANNELS || pan->nb_output_channels > MAX_CHANNELS) { av_log(ctx, AV_LOG_ERROR, - "af_pan support a maximum of %d channels. " + "af_pan supports a maximum of %d channels. " "Feel free to ask for a higher limit.\n", MAX_CHANNELS); return AVERROR_PATCHWELCOME; } diff --git a/libavfilter/af_silenceremove.c b/libavfilter/af_silenceremove.c index f156d1883d..3d3651a76f 100644 --- a/libavfilter/af_silenceremove.c +++ b/libavfilter/af_silenceremove.c @@ -186,8 +186,17 @@ static int config_input(AVFilterLink *inlink) s->start_duration = av_rescale(s->start_duration, inlink->sample_rate, AV_TIME_BASE); + if (s->start_duration < 0) { + av_log(ctx, AV_LOG_WARNING, "start duration must be non-negative\n"); + s->start_duration = -s->start_duration; + } + s->stop_duration = av_rescale(s->stop_duration, inlink->sample_rate, AV_TIME_BASE); + if (s->stop_duration < 0) { + av_log(ctx, AV_LOG_WARNING, "stop duration must be non-negative\n"); + s->stop_duration = -s->stop_duration; + } s->start_holdoff = av_malloc_array(FFMAX(s->start_duration, 1), sizeof(*s->start_holdoff) * diff --git a/libavfilter/af_sofalizer.c b/libavfilter/af_sofalizer.c index 0f1231f884..eda98b08bb 100644 --- a/libavfilter/af_sofalizer.c +++ b/libavfilter/af_sofalizer.c @@ -375,7 +375,7 @@ static int get_speaker_pos(AVFilterContext *ctx, /* set speaker positions according to input channel configuration: */ for (m = 0, ch = 0; ch < n_conv && m < 64; m++) { - uint64_t mask = channels_layout & (1 << m); + uint64_t mask = channels_layout & (1ULL << m); switch (mask) { case AV_CH_FRONT_LEFT: azim[ch] = 30; break; diff --git a/libavfilter/avfiltergraph.c b/libavfilter/avfiltergraph.c index 9f50b4120d..b6f795bff8 100644 --- a/libavfilter/avfiltergraph.c +++ b/libavfilter/avfiltergraph.c @@ -858,6 +858,8 @@ static void swap_samplerates_on_filter(AVFilterContext *filter) for (j = 0; j < outlink->in_samplerates->nb_formats; j++) { int diff = abs(sample_rate - outlink->in_samplerates->formats[j]); + av_assert0(diff < INT_MAX); // This would lead to the use of uninitialized best_diff but is only possible with invalid sample rates + if (diff < best_diff) { best_diff = diff; best_idx = j; diff --git a/libavfilter/formats.c b/libavfilter/formats.c index f12dcf4783..8cb77b27b1 100644 --- a/libavfilter/formats.c +++ b/libavfilter/formats.c @@ -72,7 +72,7 @@ do { for (j = 0; j < b->nb; j++) \ if (a->fmts[i] == b->fmts[j]) { \ if(k >= FFMIN(a->nb, b->nb)){ \ - av_log(NULL, AV_LOG_ERROR, "Duplicate formats in avfilter_merge_formats() detected\n"); \ + av_log(NULL, AV_LOG_ERROR, "Duplicate formats in %s detected\n", __FUNCTION__); \ av_free(ret->fmts); \ av_free(ret); \ return NULL; \ diff --git a/libavfilter/src_movie.c b/libavfilter/src_movie.c index 82d2bcda10..eab24589dc 100644 --- a/libavfilter/src_movie.c +++ b/libavfilter/src_movie.c @@ -240,7 +240,7 @@ static av_cold int movie_common_init(AVFilterContext *ctx) timestamp = movie->seek_point; // add the stream start time, should it exist if (movie->format_ctx->start_time != AV_NOPTS_VALUE) { - if (timestamp > INT64_MAX - movie->format_ctx->start_time) { + if (timestamp > 0 && movie->format_ctx->start_time > INT64_MAX - timestamp) { av_log(ctx, AV_LOG_ERROR, "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n", movie->file_name, movie->format_ctx->start_time, movie->seek_point); diff --git a/libavfilter/vf_blackframe.c b/libavfilter/vf_blackframe.c index ad6d488b3a..9fe2a42942 100644 --- a/libavfilter/vf_blackframe.c +++ b/libavfilter/vf_blackframe.c @@ -104,8 +104,8 @@ static int filter_frame(AVFilterLink *inlink, AVFrame *frame) #define OFFSET(x) offsetof(BlackFrameContext, x) #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM static const AVOption blackframe_options[] = { - { "amount", "Percentage of the pixels that have to be below the threshold " - "for the frame to be considered black.", OFFSET(bamount), AV_OPT_TYPE_INT, { .i64 = 98 }, 0, 100, FLAGS }, + { "amount", "percentage of the pixels that have to be below the threshold " + "for the frame to be considered black", OFFSET(bamount), AV_OPT_TYPE_INT, { .i64 = 98 }, 0, 100, FLAGS }, { "threshold", "threshold below which a pixel value is considered black", OFFSET(bthresh), AV_OPT_TYPE_INT, { .i64 = 32 }, 0, 255, FLAGS }, { "thresh", "threshold below which a pixel value is considered black", diff --git a/libavfilter/vf_drawtext.c b/libavfilter/vf_drawtext.c index 1ef3ecb31f..65c2c58b6f 100644 --- a/libavfilter/vf_drawtext.c +++ b/libavfilter/vf_drawtext.c @@ -1222,7 +1222,9 @@ static int draw_text(AVFilterContext *ctx, AVFrame *frame, dummy.code = code; glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL); if (!glyph) { - load_glyph(ctx, &glyph, code); + ret = load_glyph(ctx, &glyph, code); + if (ret < 0) + return ret; } y_min = FFMIN(glyph->bbox.yMin, y_min); diff --git a/libavfilter/vf_telecine.c b/libavfilter/vf_telecine.c index 182c670849..58babca9a1 100644 --- a/libavfilter/vf_telecine.c +++ b/libavfilter/vf_telecine.c @@ -190,6 +190,7 @@ static int filter_frame(AVFilterLink *inlink, AVFrame *inpicref) } if (s->occupied) { + av_frame_make_writable(s->frame[nout]); for (i = 0; i < s->nb_planes; i++) { // fill in the EARLIER field from the buffered pic av_image_copy_plane(s->frame[nout]->data[i] + s->frame[nout]->linesize[i] * s->first_field, @@ -213,6 +214,7 @@ static int filter_frame(AVFilterLink *inlink, AVFrame *inpicref) while (len >= 2) { // output THIS image as-is + av_frame_make_writable(s->frame[nout]); for (i = 0; i < s->nb_planes; i++) av_image_copy_plane(s->frame[nout]->data[i], s->frame[nout]->linesize[i], inpicref->data[i], inpicref->linesize[i], diff --git a/libavfilter/vf_transpose.c b/libavfilter/vf_transpose.c index 9555ff20c8..8f2ff8e33c 100644 --- a/libavfilter/vf_transpose.c +++ b/libavfilter/vf_transpose.c @@ -27,6 +27,7 @@ #include +#include "libavutil/avassert.h" #include "libavutil/imgutils.h" #include "libavutil/internal.h" #include "libavutil/intreadwrite.h" @@ -54,6 +55,7 @@ enum TransposeDir { typedef struct TransContext { const AVClass *class; int hsub, vsub; + int planes; int pixsteps[4]; int passthrough; ///< PassthroughType, landscape passthrough mode enabled @@ -106,6 +108,10 @@ static int config_props_output(AVFilterLink *outlink) s->hsub = desc_in->log2_chroma_w; s->vsub = desc_in->log2_chroma_h; + s->planes = av_pix_fmt_count_planes(outlink->format); + + av_assert0(desc_in->nb_components == desc_out->nb_components); + av_image_fill_max_pixsteps(s->pixsteps, NULL, desc_out); @@ -148,7 +154,7 @@ static int filter_slice(AVFilterContext *ctx, void *arg, int jobnr, AVFrame *in = td->in; int plane; - for (plane = 0; out->data[plane]; plane++) { + for (plane = 0; plane < s->planes; plane++) { int hsub = plane == 1 || plane == 2 ? s->hsub : 0; int vsub = plane == 1 || plane == 2 ? s->vsub : 0; int pixstep = s->pixsteps[plane]; diff --git a/libavfilter/vf_uspp.c b/libavfilter/vf_uspp.c index f963254e11..41f72161d9 100644 --- a/libavfilter/vf_uspp.c +++ b/libavfilter/vf_uspp.c @@ -227,8 +227,8 @@ static void filter(USPPContext *p, uint8_t *dst[3], uint8_t *src[3], p->frame->quality = ff_norm_qscale((qpsum + qpcount/2) / qpcount, p->qscale_type) * FF_QP2LAMBDA; } // init per MB qscale stuff FIXME - p->frame->height = height; - p->frame->width = width; + p->frame->height = height + BLOCK; + p->frame->width = width + BLOCK; for (i = 0; i < count; i++) { const int x1 = offset[i+count-1][0]; diff --git a/libavformat/allformats.c b/libavformat/allformats.c index 02bb16a71e..fb1a67797b 100644 --- a/libavformat/allformats.c +++ b/libavformat/allformats.c @@ -54,7 +54,6 @@ void av_register_all(void) if (initialized) return; - initialized = 1; avcodec_register_all(); @@ -418,4 +417,6 @@ void av_register_all(void) REGISTER_PROTOCOL(LIBRTMPTE, librtmpte); REGISTER_PROTOCOL(LIBSSH, libssh); REGISTER_PROTOCOL(LIBSMBCLIENT, libsmbclient); + + initialized = 1; } diff --git a/libavformat/apngdec.c b/libavformat/apngdec.c index c6403a191d..d9f9ee3f30 100644 --- a/libavformat/apngdec.c +++ b/libavformat/apngdec.c @@ -269,7 +269,7 @@ static int decode_fctl_chunk(AVFormatContext *s, APNGDemuxContext *ctx, AVPacket /* default is hundredths of seconds */ if (!delay_den) delay_den = 100; - if (!delay_num || delay_den / delay_num > ctx->max_fps) { + if (!delay_num || (ctx->max_fps && delay_den / delay_num > ctx->max_fps)) { delay_num = 1; delay_den = ctx->default_fps; } diff --git a/libavformat/asfdec_f.c b/libavformat/asfdec_f.c index 3ee0fcd473..dec347cfeb 100644 --- a/libavformat/asfdec_f.c +++ b/libavformat/asfdec_f.c @@ -749,13 +749,15 @@ static int asf_read_marker(AVFormatContext *s, int64_t size) count = avio_rl32(pb); // markers count avio_rl16(pb); // reserved 2 bytes name_len = avio_rl16(pb); // name length - for (i = 0; i < name_len; i++) - avio_r8(pb); // skip the name + avio_skip(pb, name_len); for (i = 0; i < count; i++) { int64_t pres_time; int name_len; + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; + avio_rl64(pb); // offset, 8 bytes pres_time = avio_rl64(pb); // presentation time pres_time -= asf->hdr.preroll * 10000; @@ -1608,6 +1610,11 @@ static int asf_build_simple_index(AVFormatContext *s, int stream_index) int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum; int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); + if (avio_feof(s->pb)) { + ret = AVERROR_INVALIDDATA; + goto end; + } + if (pos != last_pos) { av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d pts: %"PRId64"\n", pktnum, pktct, index_pts); diff --git a/libavformat/avformat.h b/libavformat/avformat.h index 34bad436cd..06a71c97ff 100644 --- a/libavformat/avformat.h +++ b/libavformat/avformat.h @@ -1866,6 +1866,13 @@ typedef struct AVFormatContext { * A callback for closing the streams opened with AVFormatContext.io_open(). */ void (*io_close)(struct AVFormatContext *s, AVIOContext *pb); + + /** + * The maximum number of streams. + * - encoding: unused + * - decoding: set by user through AVOptions (NO direct access) + */ + int max_streams; } AVFormatContext; int av_format_get_probe_score(const AVFormatContext *s); diff --git a/libavformat/avidec.c b/libavformat/avidec.c index 38598107fc..efb5d8639e 100644 --- a/libavformat/avidec.c +++ b/libavformat/avidec.c @@ -344,14 +344,14 @@ static void avi_metadata_creation_time(AVDictionary **metadata, char *date) static void avi_read_nikon(AVFormatContext *s, uint64_t end) { - while (avio_tell(s->pb) < end) { + while (avio_tell(s->pb) < end && !avio_feof(s->pb)) { uint32_t tag = avio_rl32(s->pb); uint32_t size = avio_rl32(s->pb); switch (tag) { case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */ { uint64_t tag_end = avio_tell(s->pb) + size; - while (avio_tell(s->pb) < tag_end) { + while (avio_tell(s->pb) < tag_end && !avio_feof(s->pb)) { uint16_t tag = avio_rl16(s->pb); uint16_t size = avio_rl16(s->pb); const char *name = NULL; @@ -608,6 +608,7 @@ static int avi_read_header(AVFormatContext *s) if (s->streams[0]->info) av_freep(&s->streams[0]->info->duration_error); av_freep(&s->streams[0]->info); + av_freep(&s->streams[0]->internal); av_freep(&s->streams[0]); s->nb_streams = 0; if (CONFIG_DV_DEMUXER) { @@ -666,7 +667,7 @@ static int avi_read_header(AVFormatContext *s) st->start_time = 0; avio_rl32(pb); /* buffer size */ avio_rl32(pb); /* quality */ - if (ast->cum_len*ast->scale/ast->rate > 3600) { + if (ast->cum_len > 3600LL * ast->rate / ast->scale) { av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n"); ast->cum_len = 0; } @@ -1084,6 +1085,9 @@ static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt) if (!sub_demuxer) goto error; + if (strcmp(sub_demuxer->name, "srt") && strcmp(sub_demuxer->name, "ass")) + goto error; + if (!(ast->sub_ctx = avformat_alloc_context())) goto error; @@ -1093,6 +1097,8 @@ static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt) goto error; if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) { + if (ast->sub_ctx->nb_streams != 1) + goto error; ff_read_packet(ast->sub_ctx, &ast->sub_pkt); *st->codec = *ast->sub_ctx->streams[0]->codec; ast->sub_ctx->streams[0]->codec->extradata = NULL; @@ -1188,7 +1194,8 @@ start_sync: if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) || // parse JUNK (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') || - (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')) { + (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1') || + (d[0] == 'i' && d[1] == 'n' && d[2] == 'd' && d[3] == 'x')) { avio_skip(pb, size); goto start_sync; } @@ -1695,6 +1702,8 @@ static int guess_ni_flag(AVFormatContext *s) size = avio_rl32(s->pb); if (get_stream_idx(tag) == i && pos + size > st->index_entries[1].pos) last_start = INT64_MAX; + if (get_stream_idx(tag) == i && size == st->index_entries[0].size + 8) + last_start = INT64_MAX; } if (st->index_entries[0].pos > last_start) @@ -1843,7 +1852,6 @@ static int avi_read_seek(AVFormatContext *s, int stream_index, continue; // av_assert1(st2->codec->block_align); - av_assert0(fabs(av_q2d(st2->time_base) - ast2->scale / (double)ast2->rate) < av_q2d(st2->time_base) * 0.00000001); index = av_index_search_timestamp(st2, av_rescale_q(timestamp, st->time_base, diff --git a/libavformat/aviobuf.c b/libavformat/aviobuf.c index 213ee96f91..4c8bf3a9c1 100644 --- a/libavformat/aviobuf.c +++ b/libavformat/aviobuf.c @@ -227,6 +227,8 @@ int64_t avio_seek(AVIOContext *s, int64_t offset, int whence) offset1 = pos + (s->buf_ptr - s->buffer); if (offset == 0) return offset1; + if (offset > INT64_MAX - offset1) + return AVERROR(EINVAL); offset += offset1; } if (offset < 0) diff --git a/libavformat/cache.c b/libavformat/cache.c index 8e8b9e8412..8aed37eb2d 100644 --- a/libavformat/cache.c +++ b/libavformat/cache.c @@ -283,6 +283,12 @@ resolve_eof: return ret; } +static int enu_free(void *opaque, void *elem) +{ + av_free(elem); + return 0; +} + static int cache_close(URLContext *h) { Context *c= h->priv_data; @@ -292,6 +298,7 @@ static int cache_close(URLContext *h) close(c->fd); ffurl_close(c->inner); + av_tree_enumerate(c->root, NULL, NULL, enu_free); av_tree_destroy(c->root); return 0; diff --git a/libavformat/cinedec.c b/libavformat/cinedec.c index 318408436f..e68622a5a3 100644 --- a/libavformat/cinedec.c +++ b/libavformat/cinedec.c @@ -267,8 +267,12 @@ static int cine_read_header(AVFormatContext *avctx) /* parse image offsets */ avio_seek(pb, offImageOffsets, SEEK_SET); - for (i = 0; i < st->duration; i++) + for (i = 0; i < st->duration; i++) { + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; + av_add_index_entry(st, avio_rl64(pb), i, 0, 0, AVINDEX_KEYFRAME); + } return 0; } diff --git a/libavformat/concatdec.c b/libavformat/concatdec.c index d226e1504e..9c7484eb95 100644 --- a/libavformat/concatdec.c +++ b/libavformat/concatdec.c @@ -193,8 +193,11 @@ static int detect_stream_specific(AVFormatContext *avf, int idx) ConcatStream *cs = &cat->cur_file->streams[idx]; AVBitStreamFilterContext *bsf; - if (cat->auto_convert && st->codec->codec_id == AV_CODEC_ID_H264 && - (st->codec->extradata_size < 4 || AV_RB32(st->codec->extradata) != 1)) { + if (cat->auto_convert && st->codec->codec_id == AV_CODEC_ID_H264) { + if (!st->codec->extradata_size || + (st->codec->extradata_size >= 3 && AV_RB24(st->codec->extradata) == 1) || + (st->codec->extradata_size >= 4 && AV_RB32(st->codec->extradata) == 1)) + return 0; av_log(cat->avf, AV_LOG_INFO, "Auto-inserting h264_mp4toannexb bitstream filter\n"); if (!(bsf = av_bitstream_filter_init("h264_mp4toannexb"))) { @@ -710,7 +713,7 @@ static int concat_seek(AVFormatContext *avf, int stream, static const AVOption options[] = { { "safe", "enable safe mode", - OFFSET(safe), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, DEC }, + OFFSET(safe), AV_OPT_TYPE_BOOL, {.i64 = 1}, -1, 1, DEC }, { "auto_convert", "automatically convert bitstream format", OFFSET(auto_convert), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, DEC }, { "segment_time_metadata", "output file segment start time and duration as packet metadata", diff --git a/libavformat/dcstr.c b/libavformat/dcstr.c index 2ae61dec85..e9714e504f 100644 --- a/libavformat/dcstr.c +++ b/libavformat/dcstr.c @@ -33,6 +33,7 @@ static int dcstr_probe(AVProbeData *p) static int dcstr_read_header(AVFormatContext *s) { unsigned codec, align; + int mult; AVStream *st; st = avformat_new_stream(s, NULL); @@ -46,7 +47,12 @@ static int dcstr_read_header(AVFormatContext *s) align = avio_rl32(s->pb); avio_skip(s->pb, 4); st->duration = avio_rl32(s->pb); - st->codec->channels *= avio_rl32(s->pb); + mult = avio_rl32(s->pb); + if (st->codec->channels <= 0 || mult <= 0 || mult > INT_MAX / st->codec->channels) { + av_log(s, AV_LOG_ERROR, "invalid number of channels %d x %d\n", st->codec->channels, mult); + return AVERROR_INVALIDDATA; + } + st->codec->channels *= mult; if (!align || align > INT_MAX / st->codec->channels) return AVERROR_INVALIDDATA; st->codec->block_align = align * st->codec->channels; diff --git a/libavformat/ffmdec.c b/libavformat/ffmdec.c index 41c518f3c7..44110af701 100644 --- a/libavformat/ffmdec.c +++ b/libavformat/ffmdec.c @@ -27,6 +27,7 @@ #include "libavutil/opt.h" #include "libavutil/avassert.h" #include "libavutil/avstring.h" +#include "libavutil/pixdesc.h" #include "avformat.h" #include "internal.h" #include "ffm.h" @@ -361,7 +362,7 @@ static int ffm2_read_header(AVFormatContext *s) } break; case MKBETAG('S', 'T', 'V', 'I'): - if (f_stvi++) { + if (f_stvi++ || codec->codec_type != AVMEDIA_TYPE_VIDEO) { ret = AVERROR(EINVAL); goto fail; } @@ -377,6 +378,11 @@ static int ffm2_read_header(AVFormatContext *s) codec->height = avio_rb16(pb); codec->gop_size = avio_rb16(pb); codec->pix_fmt = avio_rb32(pb); + if (!av_pix_fmt_desc_get(codec->pix_fmt)) { + av_log(s, AV_LOG_ERROR, "Invalid pix fmt id: %d\n", codec->pix_fmt); + codec->pix_fmt = AV_PIX_FMT_NONE; + goto fail; + } codec->qmin = avio_r8(pb); codec->qmax = avio_r8(pb); codec->max_qdiff = avio_r8(pb); @@ -417,7 +423,7 @@ static int ffm2_read_header(AVFormatContext *s) codec->refs = avio_rb32(pb); break; case MKBETAG('S', 'T', 'A', 'U'): - if (f_stau++) { + if (f_stau++ || codec->codec_type != AVMEDIA_TYPE_AUDIO) { ret = AVERROR(EINVAL); goto fail; } @@ -443,7 +449,7 @@ static int ffm2_read_header(AVFormatContext *s) } break; case MKBETAG('S', '2', 'V', 'I'): - if (f_stvi++ || !size) { + if (f_stvi++ || !size || codec->codec_type != AVMEDIA_TYPE_VIDEO) { ret = AVERROR(EINVAL); goto fail; } @@ -458,7 +464,7 @@ static int ffm2_read_header(AVFormatContext *s) goto fail; break; case MKBETAG('S', '2', 'A', 'U'): - if (f_stau++ || !size) { + if (f_stau++ || !size || codec->codec_type != AVMEDIA_TYPE_AUDIO) { ret = AVERROR(EINVAL); goto fail; } @@ -569,6 +575,11 @@ static int ffm_read_header(AVFormatContext *s) codec->height = avio_rb16(pb); codec->gop_size = avio_rb16(pb); codec->pix_fmt = avio_rb32(pb); + if (!av_pix_fmt_desc_get(codec->pix_fmt)) { + av_log(s, AV_LOG_ERROR, "Invalid pix fmt id: %d\n", codec->pix_fmt); + codec->pix_fmt = AV_PIX_FMT_NONE; + goto fail; + } codec->qmin = avio_r8(pb); codec->qmax = avio_r8(pb); codec->max_qdiff = avio_r8(pb); @@ -775,8 +786,8 @@ static int ffm_probe(AVProbeData *p) static const AVOption options[] = { {"server_attached", NULL, offsetof(FFMContext, server_attached), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_EXPORT }, - {"ffm_write_index", NULL, offsetof(FFMContext, write_index), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, 1, AV_OPT_FLAG_EXPORT }, - {"ffm_file_size", NULL, offsetof(FFMContext, file_size), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, 1, AV_OPT_FLAG_EXPORT }, + {"ffm_write_index", NULL, offsetof(FFMContext, write_index), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, AV_OPT_FLAG_EXPORT }, + {"ffm_file_size", NULL, offsetof(FFMContext, file_size), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, AV_OPT_FLAG_EXPORT }, { NULL }, }; diff --git a/libavformat/file.c b/libavformat/file.c index 595ba3607e..544647f5e6 100644 --- a/libavformat/file.c +++ b/libavformat/file.c @@ -349,7 +349,7 @@ URLProtocol ff_file_protocol = { .url_open_dir = file_open_dir, .url_read_dir = file_read_dir, .url_close_dir = file_close_dir, - .default_whitelist = "file" + .default_whitelist = "file,crypto" }; #endif /* CONFIG_FILE_PROTOCOL */ @@ -388,7 +388,7 @@ URLProtocol ff_pipe_protocol = { .url_check = file_check, .priv_data_size = sizeof(FileContext), .priv_data_class = &pipe_class, - .default_whitelist = "none" + .default_whitelist = "crypto" }; #endif /* CONFIG_PIPE_PROTOCOL */ diff --git a/libavformat/filmstripdec.c b/libavformat/filmstripdec.c index cdbb93b11a..b28854fa5e 100644 --- a/libavformat/filmstripdec.c +++ b/libavformat/filmstripdec.c @@ -25,6 +25,7 @@ */ #include "libavutil/intreadwrite.h" +#include "libavutil/imgutils.h" #include "avformat.h" #include "internal.h" @@ -68,10 +69,8 @@ static int read_header(AVFormatContext *s) st->codec->height = avio_rb16(pb); film->leading = avio_rb16(pb); - if (st->codec->width * 4LL * st->codec->height >= INT_MAX) { - av_log(s, AV_LOG_ERROR, "dimensions too large\n"); - return AVERROR_PATCHWELCOME; - } + if (av_image_check_size(st->codec->width, st->codec->height, 0, s) < 0) + return AVERROR_INVALIDDATA; avpriv_set_pts_info(st, 64, 1, avio_rb16(pb)); diff --git a/libavformat/flacdec.c b/libavformat/flacdec.c index eb92216c45..9553106f34 100644 --- a/libavformat/flacdec.c +++ b/libavformat/flacdec.c @@ -65,7 +65,8 @@ static int flac_read_header(AVFormatContext *s) /* process metadata blocks */ while (!avio_feof(s->pb) && !metadata_last) { - avio_read(s->pb, header, 4); + if (avio_read(s->pb, header, 4) != 4) + return AVERROR(AVERROR_INVALIDDATA); flac_parse_block_header(header, &metadata_last, &metadata_type, &metadata_size); switch (metadata_type) { @@ -259,8 +260,10 @@ static av_unused int64_t flac_read_timestamp(AVFormatContext *s, int stream_inde if (ret < 0){ if (ret == AVERROR(EAGAIN)) continue; - else - break; + else { + av_packet_unref(&pkt); + av_assert1(!pkt.size); + } } av_init_packet(&out_pkt); av_parser_parse2(parser, st->codec, @@ -277,7 +280,8 @@ static av_unused int64_t flac_read_timestamp(AVFormatContext *s, int stream_inde pts = parser->pts; break; } - } + } else if (ret < 0) + break; } av_parser_close(parser); return pts; diff --git a/libavformat/flvdec.c b/libavformat/flvdec.c index 5090ac2157..03bbf98d5e 100644 --- a/libavformat/flvdec.c +++ b/libavformat/flvdec.c @@ -1144,7 +1144,7 @@ retry_duration: leave: last = avio_rb32(s->pb); - if (last != orig_size + 11 && + if (last != orig_size + 11 && last != orig_size + 10 && (last != orig_size || !last) && last != flv->sum_flv_tag_size && !flv->broken_sizes) { av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d\n", last, orig_size + 11); diff --git a/libavformat/format.c b/libavformat/format.c index 15fe167fb2..f0abb5deeb 100644 --- a/libavformat/format.c +++ b/libavformat/format.c @@ -62,20 +62,24 @@ void av_register_input_format(AVInputFormat *format) { AVInputFormat **p = last_iformat; - format->next = NULL; - while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, format)) + // Note, format could be added after the first 2 checks but that implies that *p is no longer NULL + while(p != &format->next && !format->next && avpriv_atomic_ptr_cas((void * volatile *)p, NULL, format)) p = &(*p)->next; - last_iformat = &format->next; + + if (!format->next) + last_iformat = &format->next; } void av_register_output_format(AVOutputFormat *format) { AVOutputFormat **p = last_oformat; - format->next = NULL; - while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, format)) + // Note, format could be added after the first 2 checks but that implies that *p is no longer NULL + while(p != &format->next && !format->next && avpriv_atomic_ptr_cas((void * volatile *)p, NULL, format)) p = &(*p)->next; - last_oformat = &format->next; + + if (!format->next) + last_oformat = &format->next; } int av_match_ext(const char *filename, const char *extensions) diff --git a/libavformat/hevc.c b/libavformat/hevc.c index 7c294ef8a2..4c7ffc3312 100644 --- a/libavformat/hevc.c +++ b/libavformat/hevc.c @@ -668,6 +668,8 @@ static uint8_t *nal_unit_extract_rbsp(const uint8_t *src, uint32_t src_len, while (i < src_len) dst[len++] = src[i++]; + memset(dst + len, 0, AV_INPUT_BUFFER_PADDING_SIZE); + *dst_len = len; return dst; } diff --git a/libavformat/hls.c b/libavformat/hls.c index fc1ff38e05..ca8056522d 100644 --- a/libavformat/hls.c +++ b/libavformat/hls.c @@ -200,6 +200,8 @@ typedef struct HLSContext { char *http_proxy; ///< holds the address of the HTTP proxy server AVDictionary *avio_opts; int strict_std_compliance; + char *allowed_extensions; + int max_reload; } HLSContext; static int read_chomp_line(AVIOContext *s, char *buf, int maxlen) @@ -625,8 +627,19 @@ static int open_url(HLSContext *c, URLContext **uc, const char *url, AVDictionar return AVERROR_INVALIDDATA; // only http(s) & file are allowed - if (!av_strstart(proto_name, "http", NULL) && !av_strstart(proto_name, "file", NULL)) + if (av_strstart(proto_name, "file", NULL)) { + if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) { + av_log(c, AV_LOG_ERROR, + "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n" + "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n", + url); + return AVERROR_INVALIDDATA; + } + } else if (av_strstart(proto_name, "http", NULL)) { + ; + } else return AVERROR_INVALIDDATA; + if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':') ; else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5)) @@ -1242,6 +1255,7 @@ static int read_data(void *opaque, uint8_t *buf, int buf_size) HLSContext *c = v->parent->priv_data; int ret, i; int just_opened = 0; + int reload_count = 0; restart: if (!v->needed) @@ -1273,6 +1287,9 @@ restart: reload_interval = default_reload_interval(v); reload: + reload_count++; + if (reload_count > c->max_reload) + return AVERROR_EOF; if (!v->finished && av_gettime_relative() - v->last_load_time >= reload_interval) { if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) { @@ -2005,6 +2022,12 @@ static int hls_probe(AVProbeData *p) static const AVOption hls_options[] = { {"live_start_index", "segment index to start live streams at (negative values are from the end)", OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS}, + {"allowed_extensions", "List of file extensions that hls is allowed to access", + OFFSET(allowed_extensions), AV_OPT_TYPE_STRING, + {.str = "3gp,aac,avi,flac,mkv,m3u8,m4a,m4s,m4v,mpg,mov,mp2,mp3,mp4,mpeg,mpegts,ogg,ogv,oga,ts,vob,wav"}, + INT_MIN, INT_MAX, FLAGS}, + {"max_reload", "Maximum number of times a insufficient list is attempted to be reloaded", + OFFSET(max_reload), AV_OPT_TYPE_INT, {.i64 = 1000}, 0, INT_MAX, FLAGS}, {NULL} }; diff --git a/libavformat/hlsenc.c b/libavformat/hlsenc.c index 7ab7cbb9ab..85a0907e67 100644 --- a/libavformat/hlsenc.c +++ b/libavformat/hlsenc.c @@ -396,7 +396,7 @@ static int hls_window(AVFormatContext *s, int last) set_http_options(&options, hls); snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename); - if ((ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL)) < 0) + if ((ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, &options)) < 0) goto fail; for (en = hls->segments; en; en = en->next) { diff --git a/libavformat/http.c b/libavformat/http.c index d1b91e23d6..b2cba61797 100644 --- a/libavformat/http.c +++ b/libavformat/http.c @@ -62,8 +62,8 @@ typedef struct HTTPContext { int line_count; int http_code; /* Used if "Transfer-Encoding: chunked" otherwise -1. */ - int64_t chunksize; - int64_t off, end_off, filesize; + uint64_t chunksize; + uint64_t off, end_off, filesize; char *location; HTTPAuthState auth_state; HTTPAuthState proxy_auth_state; @@ -92,9 +92,9 @@ typedef struct HTTPContext { AVDictionary *cookie_dict; int icy; /* how much data was read since the last ICY metadata packet */ - int icy_data_read; + uint64_t icy_data_read; /* after how many bytes of read data a new metadata packet will be found */ - int icy_metaint; + uint64_t icy_metaint; char *icy_metadata_headers; char *icy_metadata_packet; AVDictionary *metadata; @@ -480,7 +480,7 @@ static int http_open(URLContext *h, const char *uri, int flags, else h->is_streamed = 1; - s->filesize = -1; + s->filesize = UINT64_MAX; s->location = av_strdup(uri); if (!s->location) return AVERROR(ENOMEM); @@ -526,7 +526,11 @@ static int http_accept(URLContext *s, URLContext **c) goto fail; cc->hd = cl; cc->is_multi_client = 1; + return 0; fail: + if (c) { + ffurl_closep(c); + } return ret; } @@ -607,9 +611,9 @@ static void parse_content_range(URLContext *h, const char *p) if (!strncmp(p, "bytes ", 6)) { p += 6; - s->off = strtoll(p, NULL, 10); + s->off = strtoull(p, NULL, 10); if ((slash = strchr(p, '/')) && strlen(slash) > 0) - s->filesize = strtoll(slash + 1, NULL, 10); + s->filesize = strtoull(slash + 1, NULL, 10); } if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647)) h->is_streamed = 0; /* we _can_ in fact seek */ @@ -799,8 +803,9 @@ static int process_line(URLContext *h, char *line, int line_count, if ((ret = parse_location(s, p)) < 0) return ret; *new_location = 1; - } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) { - s->filesize = strtoll(p, NULL, 10); + } else if (!av_strcasecmp(tag, "Content-Length") && + s->filesize == UINT64_MAX) { + s->filesize = strtoull(p, NULL, 10); } else if (!av_strcasecmp(tag, "Content-Range")) { parse_content_range(h, p); } else if (!av_strcasecmp(tag, "Accept-Ranges") && @@ -809,7 +814,7 @@ static int process_line(URLContext *h, char *line, int line_count, h->is_streamed = 0; } else if (!av_strcasecmp(tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) { - s->filesize = -1; + s->filesize = UINT64_MAX; s->chunksize = 0; } else if (!av_strcasecmp(tag, "WWW-Authenticate")) { ff_http_auth_handle_header(&s->auth_state, tag, p); @@ -833,7 +838,7 @@ static int process_line(URLContext *h, char *line, int line_count, if (parse_cookie(s, p, &s->cookie_dict)) av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p); } else if (!av_strcasecmp(tag, "Icy-MetaInt")) { - s->icy_metaint = strtoll(p, NULL, 10); + s->icy_metaint = strtoull(p, NULL, 10); } else if (!av_strncasecmp(tag, "Icy-", 4)) { if ((ret = parse_icy(s, tag, p)) < 0) return ret; @@ -963,7 +968,7 @@ static int http_read_header(URLContext *h, int *new_location) char line[MAX_URL_SIZE]; int err = 0; - s->chunksize = -1; + s->chunksize = UINT64_MAX; for (;;) { if ((err = http_get_line(s, line, sizeof(line))) < 0) @@ -997,10 +1002,11 @@ static int http_connect(URLContext *h, const char *path, const char *local_path, int post, err; char headers[HTTP_HEADERS_SIZE] = ""; char *authstr = NULL, *proxyauthstr = NULL; - int64_t off = s->off; + uint64_t off = s->off; int len = 0; const char *method; int send_expect_100 = 0; + int ret; /* send http header */ post = h->flags & AVIO_FLAG_WRITE; @@ -1045,7 +1051,7 @@ static int http_connect(URLContext *h, const char *path, const char *local_path, // server supports seeking by analysing the reply headers. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) { len += av_strlcatf(headers + len, sizeof(headers) - len, - "Range: bytes=%"PRId64"-", s->off); + "Range: bytes=%"PRIu64"-", s->off); if (s->end_off) len += av_strlcatf(headers + len, sizeof(headers) - len, "%"PRId64, s->end_off - 1); @@ -1091,7 +1097,7 @@ static int http_connect(URLContext *h, const char *path, const char *local_path, if (s->headers) av_strlcpy(headers + len, s->headers, sizeof(headers) - len); - snprintf(s->buffer, sizeof(s->buffer), + ret = snprintf(s->buffer, sizeof(s->buffer), "%s %s HTTP/1.1\r\n" "%s" "%s" @@ -1107,6 +1113,14 @@ static int http_connect(URLContext *h, const char *path, const char *local_path, av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer); + if (strlen(headers) + 1 == sizeof(headers) || + ret >= sizeof(s->buffer)) { + av_log(h, AV_LOG_ERROR, "overlong headers\n"); + err = AVERROR(EINVAL); + goto done; + } + + if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0) goto done; @@ -1120,7 +1134,7 @@ static int http_connect(URLContext *h, const char *path, const char *local_path, s->line_count = 0; s->off = 0; s->icy_data_read = 0; - s->filesize = -1; + s->filesize = UINT64_MAX; s->willclose = 0; s->end_chunked_post = 0; s->end_header = 0; @@ -1152,6 +1166,34 @@ static int http_buf_read(URLContext *h, uint8_t *buf, int size) { HTTPContext *s = h->priv_data; int len; + + if (s->chunksize != UINT64_MAX) { + if (!s->chunksize) { + char line[32]; + int err; + + do { + if ((err = http_get_line(s, line, sizeof(line))) < 0) + return err; + } while (!*line); /* skip CR LF from last chunk */ + + s->chunksize = strtoull(line, NULL, 16); + + av_log(h, AV_LOG_TRACE, + "Chunked encoding data size: %"PRIu64"'\n", + s->chunksize); + + if (!s->chunksize) + return 0; + else if (s->chunksize == UINT64_MAX) { + av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n", + s->chunksize); + return AVERROR(EINVAL); + } + } + size = FFMIN(size, s->chunksize); + } + /* read bytes from input buffer first */ len = s->buf_end - s->buf_ptr; if (len > 0) { @@ -1160,15 +1202,13 @@ static int http_buf_read(URLContext *h, uint8_t *buf, int size) memcpy(buf, s->buf_ptr, len); s->buf_ptr += len; } else { - int64_t target_end = s->end_off ? s->end_off : s->filesize; - if ((!s->willclose || s->chunksize < 0) && - target_end >= 0 && s->off >= target_end) + uint64_t target_end = s->end_off ? s->end_off : s->filesize; + if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end) return AVERROR_EOF; len = ffurl_read(s->hd, buf, size); - if (!len && (!s->willclose || s->chunksize < 0) && - target_end >= 0 && s->off < target_end) { + if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) { av_log(h, AV_LOG_ERROR, - "Stream ends prematurely at %"PRId64", should be %"PRId64"\n", + "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n", s->off, target_end ); return AVERROR(EIO); @@ -1176,8 +1216,10 @@ static int http_buf_read(URLContext *h, uint8_t *buf, int size) } if (len > 0) { s->off += len; - if (s->chunksize > 0) + if (s->chunksize > 0) { + av_assert0(s->chunksize >= len); s->chunksize -= len; + } } return len; } @@ -1231,25 +1273,6 @@ static int http_read_stream(URLContext *h, uint8_t *buf, int size) return err; } - if (s->chunksize >= 0) { - if (!s->chunksize) { - char line[32]; - - do { - if ((err = http_get_line(s, line, sizeof(line))) < 0) - return err; - } while (!*line); /* skip CR LF from last chunk */ - - s->chunksize = strtoll(line, NULL, 16); - - av_log(NULL, AV_LOG_TRACE, "Chunked encoding data size: %"PRId64"'\n", - s->chunksize); - - if (!s->chunksize) - return 0; - } - size = FFMIN(size, s->chunksize); - } #if CONFIG_ZLIB if (s->compressed) return http_buf_read_compressed(h, buf, size); @@ -1257,17 +1280,17 @@ static int http_read_stream(URLContext *h, uint8_t *buf, int size) read_ret = http_buf_read(h, buf, size); if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize) || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) { - int64_t target = h->is_streamed ? 0 : s->off; + uint64_t target = h->is_streamed ? 0 : s->off; if (s->reconnect_delay > s->reconnect_delay_max) return AVERROR(EIO); - av_log(h, AV_LOG_INFO, "Will reconnect at %"PRId64" error=%s.\n", s->off, av_err2str(read_ret)); + av_log(h, AV_LOG_INFO, "Will reconnect at %"PRIu64" error=%s.\n", s->off, av_err2str(read_ret)); av_usleep(1000U*1000*s->reconnect_delay); s->reconnect_delay = 1 + 2*s->reconnect_delay; seek_ret = http_seek_internal(h, target, SEEK_SET, 1); if (seek_ret != target) { - av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRId64".\n", target); + av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target); return read_ret; } @@ -1322,10 +1345,11 @@ static int store_icy(URLContext *h, int size) { HTTPContext *s = h->priv_data; /* until next metadata packet */ - int remaining = s->icy_metaint - s->icy_data_read; + uint64_t remaining; - if (remaining < 0) + if (s->icy_metaint < s->icy_data_read) return AVERROR_INVALIDDATA; + remaining = s->icy_metaint - s->icy_data_read; if (!remaining) { /* The metadata packet is variable sized. It has a 1 byte header @@ -1439,7 +1463,7 @@ static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int fo { HTTPContext *s = h->priv_data; URLContext *old_hd = s->hd; - int64_t old_off = s->off; + uint64_t old_off = s->off; uint8_t old_buf[BUFFER_SIZE]; int old_buf_size, ret; AVDictionary *options = NULL; @@ -1450,7 +1474,7 @@ static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int fo ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))) return s->off; - else if ((s->filesize == -1 && whence == SEEK_END)) + else if ((s->filesize == UINT64_MAX && whence == SEEK_END)) return AVERROR(ENOSYS); if (whence == SEEK_CUR) @@ -1522,7 +1546,7 @@ URLProtocol ff_http_protocol = { .priv_data_size = sizeof(HTTPContext), .priv_data_class = &http_context_class, .flags = URL_PROTOCOL_FLAG_NETWORK, - .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto" + .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy" }; #endif /* CONFIG_HTTP_PROTOCOL */ @@ -1541,7 +1565,7 @@ URLProtocol ff_https_protocol = { .priv_data_size = sizeof(HTTPContext), .priv_data_class = &https_context_class, .flags = URL_PROTOCOL_FLAG_NETWORK, - .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto" + .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy" }; #endif /* CONFIG_HTTPS_PROTOCOL */ @@ -1605,7 +1629,7 @@ redo: s->buf_ptr = s->buffer; s->buf_end = s->buffer; s->line_count = 0; - s->filesize = -1; + s->filesize = UINT64_MAX; cur_auth_type = s->proxy_auth_state.auth_type; /* Note: This uses buffering, potentially reading more than the diff --git a/libavformat/icodec.c b/libavformat/icodec.c index 6ddb901b7e..bd83ef4c95 100644 --- a/libavformat/icodec.c +++ b/libavformat/icodec.c @@ -60,7 +60,7 @@ static int probe(AVProbeData *p) offset = AV_RL32(p->buf + 18 + i * 16); if (offset < 22) return FFMIN(i, AVPROBE_SCORE_MAX / 4); - if (offset + 8 > p->buf_size) + if (offset > p->buf_size - 8) return AVPROBE_SCORE_MAX / 4 + FFMIN(i, 1); if (p->buf[offset] != 40 && AV_RB64(p->buf + offset) != PNGSIG) return FFMIN(i, AVPROBE_SCORE_MAX / 4); @@ -105,6 +105,10 @@ static int read_header(AVFormatContext *s) avio_skip(pb, 5); ico->images[i].size = avio_rl32(pb); + if (ico->images[i].size <= 0) { + av_log(s, AV_LOG_ERROR, "Invalid image size %d\n", ico->images[i].size); + return AVERROR_INVALIDDATA; + } ico->images[i].offset = avio_rl32(pb); if (avio_seek(pb, ico->images[i].offset, SEEK_SET) < 0) @@ -170,8 +174,10 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt) bytestream_put_le16(&buf, 0); bytestream_put_le32(&buf, 0); - if ((ret = avio_read(pb, buf, image->size)) < 0) - return ret; + if ((ret = avio_read(pb, buf, image->size)) != image->size) { + av_packet_unref(pkt); + return ret < 0 ? ret : AVERROR_INVALIDDATA; + } st->codec->bits_per_coded_sample = AV_RL16(buf + 14); @@ -193,6 +199,13 @@ static int read_packet(AVFormatContext *s, AVPacket *pkt) return 0; } +static int ico_read_close(AVFormatContext * s) +{ + IcoDemuxContext *ico = s->priv_data; + av_freep(&ico->images); + return 0; +} + AVInputFormat ff_ico_demuxer = { .name = "ico", .long_name = NULL_IF_CONFIG_SMALL("Microsoft Windows ICO"), @@ -200,5 +213,6 @@ AVInputFormat ff_ico_demuxer = { .read_probe = probe, .read_header = read_header, .read_packet = read_packet, + .read_close = ico_read_close, .flags = AVFMT_NOTIMESTAMPS, }; diff --git a/libavformat/idroqdec.c b/libavformat/idroqdec.c index 76bb3924b1..d733953a04 100644 --- a/libavformat/idroqdec.c +++ b/libavformat/idroqdec.c @@ -157,6 +157,9 @@ static int roq_read_packet(AVFormatContext *s, chunk_size = AV_RL32(&preamble[2]) + RoQ_CHUNK_PREAMBLE_SIZE * 2 + codebook_size; + if (chunk_size > INT_MAX) + return AVERROR_INVALIDDATA; + /* rewind */ avio_seek(pb, codebook_offset, SEEK_SET); diff --git a/libavformat/librtmp.c b/libavformat/librtmp.c index bfa9a718f1..5a138adad4 100644 --- a/libavformat/librtmp.c +++ b/libavformat/librtmp.c @@ -193,6 +193,8 @@ static int rtmp_open(URLContext *s, const char *uri, int flags) if (sep) p = sep + 1; + else + break; } } if (ctx->playpath) { diff --git a/libavformat/libssh.c b/libavformat/libssh.c index 3c056f874a..4cf7963e70 100644 --- a/libavformat/libssh.c +++ b/libavformat/libssh.c @@ -103,7 +103,7 @@ static av_cold int libssh_authentication(LIBSSHContext *libssh, const char *user } } - if (!authorized && (auth_methods & SSH_AUTH_METHOD_PASSWORD)) { + if (!authorized && password && (auth_methods & SSH_AUTH_METHOD_PASSWORD)) { if (ssh_userauth_password(libssh->session, NULL, password) == SSH_AUTH_SUCCESS) { av_log(libssh, AV_LOG_DEBUG, "Authentication successful with password.\n"); authorized = 1; diff --git a/libavformat/lrcdec.c b/libavformat/lrcdec.c index d3655fccd5..1f0533f2d1 100644 --- a/libavformat/lrcdec.c +++ b/libavformat/lrcdec.c @@ -212,6 +212,7 @@ static int lrc_read_header(AVFormatContext *s) } ff_subtitles_queue_finalize(s, &lrc->q); ff_metadata_conv_ctx(s, NULL, ff_lrc_metadata_conv); + av_bprint_finalize(&line, NULL); return 0; } diff --git a/libavformat/matroskadec.c b/libavformat/matroskadec.c index d788232150..e52edeeadf 100644 --- a/libavformat/matroskadec.c +++ b/libavformat/matroskadec.c @@ -87,6 +87,7 @@ typedef const struct EbmlSyntax { int list_elem_size; int data_offset; union { + int64_t i; uint64_t u; double f; const char *s; @@ -590,7 +591,7 @@ static const EbmlSyntax matroska_segments[] = { }; static const EbmlSyntax matroska_blockmore[] = { - { MATROSKA_ID_BLOCKADDID, EBML_UINT, 0, offsetof(MatroskaBlock,additional_id) }, + { MATROSKA_ID_BLOCKADDID, EBML_UINT, 0, offsetof(MatroskaBlock,additional_id), { .u = 1 } }, { MATROSKA_ID_BLOCKADDITIONAL, EBML_BIN, 0, offsetof(MatroskaBlock,additional) }, { 0 } }; @@ -606,7 +607,7 @@ static const EbmlSyntax matroska_blockgroup[] = { { MATROSKA_ID_SIMPLEBLOCK, EBML_BIN, 0, offsetof(MatroskaBlock, bin) }, { MATROSKA_ID_BLOCKDURATION, EBML_UINT, 0, offsetof(MatroskaBlock, duration) }, { MATROSKA_ID_DISCARDPADDING, EBML_SINT, 0, offsetof(MatroskaBlock, discard_padding) }, - { MATROSKA_ID_BLOCKREFERENCE, EBML_SINT, 0, offsetof(MatroskaBlock, reference) }, + { MATROSKA_ID_BLOCKREFERENCE, EBML_SINT, 0, offsetof(MatroskaBlock, reference), { .i = INT64_MIN } }, { MATROSKA_ID_CODECSTATE, EBML_NONE }, { 1, EBML_UINT, 0, offsetof(MatroskaBlock, non_simple), { .u = 1 } }, { 0 } @@ -977,6 +978,9 @@ static int ebml_parse_nest(MatroskaDemuxContext *matroska, EbmlSyntax *syntax, for (i = 0; syntax[i].id; i++) switch (syntax[i].type) { + case EBML_SINT: + *(int64_t *) ((char *) data + syntax[i].data_offset) = syntax[i].def.i; + break; case EBML_UINT: *(uint64_t *) ((char *) data + syntax[i].data_offset) = syntax[i].def.u; break; @@ -1778,8 +1782,16 @@ static int matroska_parse_tracks(AVFormatContext *s) } if (track->type == MATROSKA_TRACK_TYPE_VIDEO) { - if (!track->default_duration && track->video.frame_rate > 0) - track->default_duration = 1000000000 / track->video.frame_rate; + if (!track->default_duration && track->video.frame_rate > 0) { + double default_duration = 1000000000 / track->video.frame_rate; + if (default_duration > UINT64_MAX || default_duration < 0) { + av_log(matroska->ctx, AV_LOG_WARNING, + "Invalid frame rate %e. Cannot calculate default duration.\n", + track->video.frame_rate); + } else { + track->default_duration = default_duration; + } + } if (track->video.display_width == -1) track->video.display_width = track->video.pixel_width; if (track->video.display_height == -1) @@ -3097,7 +3109,7 @@ static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska) matroska->current_cluster_num_blocks = blocks_list->nb_elem; i = blocks_list->nb_elem - 1; if (blocks[i].bin.size > 0 && blocks[i].bin.data) { - int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1; + int is_keyframe = blocks[i].non_simple ? blocks[i].reference == INT64_MIN : -1; uint8_t* additional = blocks[i].additional.size > 0 ? blocks[i].additional.data : NULL; if (!blocks[i].non_simple) @@ -3135,7 +3147,7 @@ static int matroska_parse_cluster(MatroskaDemuxContext *matroska) blocks = blocks_list->elem; for (i = 0; i < blocks_list->nb_elem; i++) if (blocks[i].bin.size > 0 && blocks[i].bin.data) { - int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1; + int is_keyframe = blocks[i].non_simple ? blocks[i].reference == INT64_MIN : -1; res = matroska_parse_block(matroska, blocks[i].bin.data, blocks[i].bin.size, blocks[i].bin.pos, cluster.timecode, blocks[i].duration, @@ -3579,6 +3591,11 @@ static int webm_dash_manifest_read_header(AVFormatContext *s) av_log(s, AV_LOG_ERROR, "Failed to read file headers\n"); return -1; } + if (!s->nb_streams) { + matroska_read_close(s); + av_log(s, AV_LOG_ERROR, "No streams found\n"); + return AVERROR_INVALIDDATA; + } if (!matroska->is_live) { buf = av_asprintf("%g", matroska->duration); diff --git a/libavformat/mlvdec.c b/libavformat/mlvdec.c index 288b2a1010..253ad61383 100644 --- a/libavformat/mlvdec.c +++ b/libavformat/mlvdec.c @@ -77,7 +77,7 @@ static int check_file_header(AVIOContext *pb, uint64_t guid) return 0; } -static void read_string(AVFormatContext *avctx, AVIOContext *pb, const char *tag, int size) +static void read_string(AVFormatContext *avctx, AVIOContext *pb, const char *tag, unsigned size) { char * value = av_malloc(size + 1); if (!value) { diff --git a/libavformat/mms.c b/libavformat/mms.c index 807aadef0f..9f675f2dd0 100644 --- a/libavformat/mms.c +++ b/libavformat/mms.c @@ -94,24 +94,26 @@ int ff_mms_asf_header_parser(MMSContext *mms) } } } else if (!memcmp(p, ff_asf_stream_header, sizeof(ff_asf_guid))) { - flags = AV_RL16(p + sizeof(ff_asf_guid)*3 + 24); - stream_id = flags & 0x7F; - //The second condition is for checking CS_PKT_STREAM_ID_REQUEST packet size, - //we can calcuate the packet size by stream_num. - //Please see function send_stream_selection_request(). - if (mms->stream_num < MMS_MAX_STREAMS && - 46 + mms->stream_num * 6 < sizeof(mms->out_buffer)) { - mms->streams = av_fast_realloc(mms->streams, - &mms->nb_streams_allocated, - (mms->stream_num + 1) * sizeof(MMSStream)); - if (!mms->streams) - return AVERROR(ENOMEM); - mms->streams[mms->stream_num].id = stream_id; - mms->stream_num++; - } else { - av_log(NULL, AV_LOG_ERROR, - "Corrupt stream (too many A/V streams)\n"); - return AVERROR_INVALIDDATA; + if (end - p >= (sizeof(ff_asf_guid) * 3 + 26)) { + flags = AV_RL16(p + sizeof(ff_asf_guid)*3 + 24); + stream_id = flags & 0x7F; + //The second condition is for checking CS_PKT_STREAM_ID_REQUEST packet size, + //we can calcuate the packet size by stream_num. + //Please see function send_stream_selection_request(). + if (mms->stream_num < MMS_MAX_STREAMS && + 46 + mms->stream_num * 6 < sizeof(mms->out_buffer)) { + mms->streams = av_fast_realloc(mms->streams, + &mms->nb_streams_allocated, + (mms->stream_num + 1) * sizeof(MMSStream)); + if (!mms->streams) + return AVERROR(ENOMEM); + mms->streams[mms->stream_num].id = stream_id; + mms->stream_num++; + } else { + av_log(NULL, AV_LOG_ERROR, + "Corrupt stream (too many A/V streams)\n"); + return AVERROR_INVALIDDATA; + } } } else if (!memcmp(p, ff_asf_ext_stream_header, sizeof(ff_asf_guid))) { if (end - p >= 88) { @@ -143,6 +145,12 @@ int ff_mms_asf_header_parser(MMSContext *mms) } } else if (!memcmp(p, ff_asf_head1_guid, sizeof(ff_asf_guid))) { chunksize = 46; // see references [2] section 3.4. This should be set 46. + if (chunksize > end - p) { + av_log(NULL, AV_LOG_ERROR, + "Corrupt stream (header chunksize %"PRId64" is invalid)\n", + chunksize); + return AVERROR_INVALIDDATA; + } } p += chunksize; } diff --git a/libavformat/mov.c b/libavformat/mov.c index 149e3b4a0e..1ea8b4094a 100644 --- a/libavformat/mov.c +++ b/libavformat/mov.c @@ -380,11 +380,11 @@ retry: return ret; } else if (!key && c->found_hdlr_mdta && c->meta_keys) { uint32_t index = AV_RB32(&atom.type); - if (index < c->meta_keys_count) { + if (index < c->meta_keys_count && index > 0) { key = c->meta_keys[index]; } else { av_log(c->fc, AV_LOG_WARNING, - "The index of 'data' is out of range: %d >= %d.\n", + "The index of 'data' is out of range: %d < 1 or >= %d.\n", index, c->meta_keys_count); } } @@ -674,6 +674,8 @@ static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom) title_size = atom.size - 24; if (title_size > 0) { + if (title_size > FFMIN(INT_MAX, SIZE_MAX-1)) + return AVERROR_INVALIDDATA; title_str = av_malloc(title_size + 1); /* Add null terminator */ if (!title_str) return AVERROR(ENOMEM); @@ -2246,6 +2248,8 @@ static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom) avio_rb24(pb); /* flags */ entries = avio_rb32(pb); + if ((uint64_t)entries * 12 + 4 > atom.size) + return AVERROR_INVALIDDATA; av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries); @@ -2266,6 +2270,29 @@ static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom) } sc->stsc_count = i; + for (i = sc->stsc_count - 1; i < UINT_MAX; i--) { + int64_t first_min = i + 1; + if ((i+1 < sc->stsc_count && sc->stsc_data[i].first >= sc->stsc_data[i+1].first) || + (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first) || + sc->stsc_data[i].first < first_min || + sc->stsc_data[i].count < 1 || + sc->stsc_data[i].id < 1) { + av_log(c->fc, AV_LOG_WARNING, "STSC entry %d is invalid (first=%d count=%d id=%d)\n", i, sc->stsc_data[i].first, sc->stsc_data[i].count, sc->stsc_data[i].id); + if (i+1 >= sc->stsc_count) { + sc->stsc_data[i].first = FFMAX(sc->stsc_data[i].first, first_min); + if (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first) + sc->stsc_data[i].first = FFMIN(sc->stsc_data[i-1].first + 1LL, INT_MAX); + sc->stsc_data[i].count = FFMAX(sc->stsc_data[i].count, 1); + sc->stsc_data[i].id = FFMAX(sc->stsc_data[i].id, 1); + continue; + } + av_assert0(sc->stsc_data[i+1].first >= 2); + // We replace this entry by the next valid + sc->stsc_data[i].first = sc->stsc_data[i+1].first - 1; + sc->stsc_data[i].count = sc->stsc_data[i+1].count; + sc->stsc_data[i].id = sc->stsc_data[i+1].id; + } + } if (pb->eof_reached) return AVERROR_EOF; @@ -2492,14 +2519,19 @@ static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom) && total_sample_count > 100 && sample_duration/10 > duration / total_sample_count) sample_duration = duration / total_sample_count; - duration+=(int64_t)sample_duration*sample_count; + duration+=(int64_t)sample_duration*(uint64_t)sample_count; total_sample_count+=sample_count; } sc->stts_count = i; - sc->duration_for_fps += duration; - sc->nb_frames_for_fps += total_sample_count; + if (duration > 0 && + duration <= INT64_MAX - sc->duration_for_fps && + total_sample_count <= INT64_MAX - sc->nb_frames_for_fps + ) { + sc->duration_for_fps += duration; + sc->nb_frames_for_fps += total_sample_count; + } if (pb->eof_reached) return AVERROR_EOF; @@ -2750,7 +2782,12 @@ static void mov_build_index(MOVContext *mov, AVStream *st) sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample]; if (sc->pseudo_stream_id == -1 || sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) { - AVIndexEntry *e = &st->index_entries[st->nb_index_entries++]; + AVIndexEntry *e; + if (sample_size > 0x3FFFFFFF) { + av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size); + return; + } + e = &st->index_entries[st->nb_index_entries++]; e->pos = current_offset; e->timestamp = current_dts; e->size = sample_size; @@ -2800,6 +2837,9 @@ static void mov_build_index(MOVContext *mov, AVStream *st) } else { unsigned chunk_samples, total = 0; + if (!sc->chunk_count) + return; + // compute total chunk count for (i = 0; i < sc->stsc_count; i++) { unsigned count, chunk_count; @@ -2875,6 +2915,10 @@ static void mov_build_index(MOVContext *mov, AVStream *st) av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total); return; } + if (size > 0x3FFFFFFF) { + av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size); + return; + } e = &st->index_entries[st->nb_index_entries++]; e->pos = current_offset; e->timestamp = current_dts; @@ -3033,6 +3077,11 @@ static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom) st->index); return 0; } + if (sc->chunk_count && sc->stsc_count && sc->stsc_data[ sc->stsc_count - 1 ].first > sc->chunk_count) { + av_log(c->fc, AV_LOG_ERROR, "stream %d, contradictionary STSC and STCO\n", + st->index); + return AVERROR_INVALIDDATA; + } fix_timescale(c, sc); @@ -3140,7 +3189,7 @@ static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom) avio_skip(pb, 4); count = avio_rb32(pb); - if (count > UINT_MAX / sizeof(*c->meta_keys)) { + if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) { av_log(c->fc, AV_LOG_ERROR, "The 'keys' atom with the invalid key count: %d\n", count); return AVERROR_INVALIDDATA; @@ -3609,7 +3658,7 @@ static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom) } av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts); } else { - dts = frag->time; + dts = frag->time - sc->time_offset; av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64 ", using it for dts\n", dts); } @@ -3636,8 +3685,13 @@ static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom) dts += sample_duration; offset += sample_size; sc->data_size += sample_size; - sc->duration_for_fps += sample_duration; - sc->nb_frames_for_fps ++; + + if (sample_duration <= INT64_MAX - sc->duration_for_fps && + 1 <= INT64_MAX - sc->nb_frames_for_fps + ) { + sc->duration_for_fps += sample_duration; + sc->nb_frames_for_fps ++; + } } if (pb->eof_reached) @@ -3666,7 +3720,7 @@ static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom) version = avio_r8(pb); if (version > 1) { avpriv_request_sample(c->fc, "sidx version %u", version); - return AVERROR_PATCHWELCOME; + return 0; } avio_rb24(pb); // flags @@ -3679,8 +3733,8 @@ static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom) } } if (!st) { - av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", track_id); - return AVERROR_INVALIDDATA; + av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id); + return 0; } sc = st->priv_data; @@ -3890,7 +3944,7 @@ static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom) 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac }; - if (atom.size < sizeof(uuid) || atom.size == INT64_MAX) + if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX)) return AVERROR_INVALIDDATA; ret = avio_read(pb, uuid, sizeof(uuid)); @@ -4053,8 +4107,8 @@ static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom) avio_rb32(pb); /* entries */ - if (atom.size < 8) { - av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" too small\n", atom.size); + if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) { + av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size); return AVERROR_INVALIDDATA; } @@ -4244,7 +4298,7 @@ static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom) if (atom.size < 0) atom.size = INT64_MAX; - while (total_size + 8 <= atom.size && !avio_feof(pb)) { + while (total_size <= atom.size - 8 && !avio_feof(pb)) { int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL; a.size = atom.size; a.type=0; @@ -4691,6 +4745,13 @@ static int read_tfra(MOVContext *mov, AVIOContext *f) } for (i = 0; i < index->item_count; i++) { int64_t time, offset; + + if (avio_feof(f)) { + index->item_count = 0; + av_freep(&index->items); + return AVERROR_INVALIDDATA; + } + if (version == 1) { time = avio_rb64(f); offset = avio_rb64(f); @@ -4955,6 +5016,7 @@ static int should_retry(AVIOContext *pb, int error_code) { static int mov_switch_root(AVFormatContext *s, int64_t target) { + int ret; MOVContext *mov = s->priv_data; int i, j; int already_read = 0; @@ -4991,8 +5053,10 @@ static int mov_switch_root(AVFormatContext *s, int64_t target) mov->found_mdat = 0; - if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 || - avio_feof(s->pb)) + ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }); + if (ret < 0) + return ret; + if (avio_feof(s->pb)) return AVERROR_EOF; av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb)); @@ -5077,7 +5141,9 @@ static int mov_read_packet(AVFormatContext *s, AVPacket *pkt) } else { int64_t next_dts = (sc->current_sample < st->nb_index_entries) ? st->index_entries[sc->current_sample].timestamp : st->duration; - pkt->duration = next_dts - pkt->dts; + + if (next_dts >= pkt->dts) + pkt->duration = next_dts - pkt->dts; pkt->pts = pkt->dts; } if (st->discard == AVDISCARD_ALL) diff --git a/libavformat/movenc.c b/libavformat/movenc.c index b9c0f7ae67..c093c48ae1 100644 --- a/libavformat/movenc.c +++ b/libavformat/movenc.c @@ -377,6 +377,11 @@ static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) info->ec3_done = 1; goto concatenate; } + } else { + if (hdr->substreamid != 0) { + avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams"); + return AVERROR_PATCHWELCOME; + } } /* fill the info needed for the "dec3" atom */ @@ -4342,15 +4347,10 @@ static int mov_auto_flush_fragment(AVFormatContext *s, int force) return ret; } -int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt) +static int check_pkt(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; - AVIOContext *pb = s->pb; MOVTrack *trk = &mov->tracks[pkt->stream_index]; - AVCodecContext *enc = trk->enc; - unsigned int samples_in_chunk = 0; - int size = pkt->size, ret = 0; - uint8_t *reformatted_data = NULL; if (trk->entry) { int64_t duration = pkt->dts - trk->cluster[trk->entry - 1].dts; @@ -4362,11 +4362,35 @@ int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt) pkt->dts = trk->cluster[trk->entry - 1].dts + 1; pkt->pts = AV_NOPTS_VALUE; } + } else if (pkt->dts <= INT_MIN || pkt->dts >= INT_MAX) { + av_log(s, AV_LOG_ERROR, "Application provided initial timestamp: %"PRId64" is out of range for mov/mp4 format\n", + pkt->dts + ); + + pkt->dts = 0; + pkt->pts = AV_NOPTS_VALUE; } if (pkt->duration < 0 || pkt->duration > INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration); return AVERROR(EINVAL); } + return 0; +} + +int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt) +{ + MOVMuxContext *mov = s->priv_data; + AVIOContext *pb = s->pb; + MOVTrack *trk = &mov->tracks[pkt->stream_index]; + AVCodecContext *enc = trk->enc; + unsigned int samples_in_chunk = 0; + int size = pkt->size, ret = 0; + uint8_t *reformatted_data = NULL; + + ret = check_pkt(s, pkt); + if (ret < 0) + return ret; + if (mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret; if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { @@ -4413,6 +4437,11 @@ int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt) else samples_in_chunk = 1; + if (samples_in_chunk < 1) { + av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n"); + return AVERROR_PATCHWELCOME; + } + /* copy extradata if it exists */ if (trk->vos_len == 0 && enc->extradata_size > 0 && !TAG_IS_AVCI(trk->tag) && @@ -4631,6 +4660,10 @@ static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt) int64_t frag_duration = 0; int size = pkt->size; + int ret = check_pkt(s, pkt); + if (ret < 0) + return ret; + if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) { int i; for (i = 0; i < s->nb_streams; i++) diff --git a/libavformat/mp3dec.c b/libavformat/mp3dec.c index c76b21ebd6..50bf52cf27 100644 --- a/libavformat/mp3dec.c +++ b/libavformat/mp3dec.c @@ -64,6 +64,7 @@ static int check(AVIOContext *pb, int64_t pos, uint32_t *header); static int mp3_read_probe(AVProbeData *p) { int max_frames, first_frames = 0; + int whole_used = 0; int frames, ret; uint32_t header; const uint8_t *buf, *buf0, *buf2, *end; @@ -88,8 +89,11 @@ static int mp3_read_probe(AVProbeData *p) buf2 += h.frame_size; } max_frames = FFMAX(max_frames, frames); - if(buf == buf0) + if(buf == buf0) { first_frames= frames; + if (buf2 == end + sizeof(uint32_t)) + whole_used = 1; + } } // keep this in sync with ac3 probe, both need to avoid // issues with MPEG-files! @@ -98,6 +102,7 @@ static int mp3_read_probe(AVProbeData *p) else if(max_frames>=4 && max_frames >= p->buf_size/10000) return AVPROBE_SCORE_EXTENSION / 2; else if(ff_id3v2_match(buf0, ID3v2_DEFAULT_MAGIC) && 2*ff_id3v2_tag_len(buf0) >= p->buf_size) return p->buf_size < PROBE_BUF_MAX ? AVPROBE_SCORE_EXTENSION / 4 : AVPROBE_SCORE_EXTENSION - 2; + else if(first_frames > 1 && whole_used) return 5; else if(max_frames>=1 && max_frames >= p->buf_size/10000) return 1; else return 0; //mpegps_mp3_unrecognized_format.mpg has max_frames=3 diff --git a/libavformat/mpeg.c b/libavformat/mpeg.c index 69685cf890..db8f1f99a5 100644 --- a/libavformat/mpeg.c +++ b/libavformat/mpeg.c @@ -112,7 +112,7 @@ static int mpegps_probe(AVProbeData *p) : AVPROBE_SCORE_EXTENSION / 2; // 1 more than .mpg if ((!!vid ^ !!audio) && (audio > 4 || vid > 1) && !sys && !pspack && p->buf_size > 2048 && vid + audio > invalid) /* PES stream */ - return (audio > 12 || vid > 3 + 2 * invalid) ? AVPROBE_SCORE_EXTENSION + 2 + return (audio > 12 || vid > 6 + 2 * invalid) ? AVPROBE_SCORE_EXTENSION + 2 : AVPROBE_SCORE_EXTENSION / 2; // 02-Penguin.flac has sys:0 priv1:0 pspack:0 vid:0 audio:1 @@ -138,7 +138,7 @@ typedef struct MpegDemuxContext { static int mpegps_read_header(AVFormatContext *s) { MpegDemuxContext *m = s->priv_data; - char buffer[7]; + char buffer[7] = { 0 }; int64_t last_pos = avio_tell(s->pb); m->header_state = 0xff; diff --git a/libavformat/mpegts.c b/libavformat/mpegts.c index 22874e6f83..c85c30ddad 100644 --- a/libavformat/mpegts.c +++ b/libavformat/mpegts.c @@ -1769,8 +1769,11 @@ int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type case 0x05: /* registration descriptor */ st->codec->codec_tag = bytestream_get_le32(pp); av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codec->codec_tag); - if (st->codec->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) + if (st->codec->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) { mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types); + if (st->codec->codec_tag == MKTAG('B', 'S', 'S', 'D')) + st->request_probe = 50; + } break; case 0x52: /* stream identifier descriptor */ st->stream_identifier = 1 + get8(pp, desc_end); @@ -2441,7 +2444,7 @@ static int mpegts_probe(AVProbeData *p) #define CHECK_COUNT 10 #define CHECK_BLOCK 100 - if (check_count < CHECK_COUNT) + if (!check_count) return 0; for (i = 0; i 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT; - else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT; - else + if (check_count > CHECK_COUNT && sumscore > 6) { + return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT; + } else if (check_count >= CHECK_COUNT && sumscore > 6) { + return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT; + } else if (check_count >= CHECK_COUNT && maxscore > 6) { + return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT; + } else if (sumscore > 6) { + return 2; + } else { return 0; + } } /* return the 90kHz PCR and the extension for the 27MHz PCR. return @@ -2575,8 +2585,17 @@ static int mpegts_read_header(AVFormatContext *s) packet_count[nb_pcrs] = nb_packets; pcrs[nb_pcrs] = pcr_h * 300 + pcr_l; nb_pcrs++; - if (nb_pcrs >= 2) - break; + if (nb_pcrs >= 2) { + if (pcrs[1] - pcrs[0] > 0) { + /* the difference needs to be positive to make sense for bitrate computation */ + break; + } else { + av_log(ts->stream, AV_LOG_WARNING, "invalid pcr pair %"PRId64" >= %"PRId64"\n", pcrs[0], pcrs[1]); + pcrs[0] = pcrs[1]; + packet_count[0] = packet_count[1]; + nb_pcrs--; + } + } } else { finished_reading_packet(s, ts->raw_packet_size); } diff --git a/libavformat/mpegtsenc.c b/libavformat/mpegtsenc.c index 765672067a..6bf5461b64 100644 --- a/libavformat/mpegtsenc.c +++ b/libavformat/mpegtsenc.c @@ -56,6 +56,7 @@ typedef struct MpegTSService { int pcr_pid; int pcr_packet_count; int pcr_packet_period; + AVProgram *program; } MpegTSService; // service_type values as defined in ETSI 300 468 @@ -275,15 +276,12 @@ static int mpegts_write_pmt(AVFormatContext *s, MpegTSService *service) AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0); if (s->nb_programs) { - int j, k, found = 0; + int k, found = 0; + AVProgram *program = service->program; - for (j = 0; j < s->nb_programs; j++) - if (s->programs[j]->id == service->sid) { - for (k = 0; k < s->programs[j]->nb_stream_indexes; k++) - if (s->programs[j]->stream_index[k] == i) { - found = 1; - break; - } + for (k = 0; k < program->nb_stream_indexes; k++) + if (program->stream_index[k] == i) { + found = 1; break; } @@ -784,6 +782,7 @@ static int mpegts_init(AVFormatContext *s) service->pmt.write_packet = section_write_packet; service->pmt.opaque = s; service->pmt.cc = 15; + service->program = program; } } @@ -807,6 +806,7 @@ static int mpegts_init(AVFormatContext *s) /* assign pids to each stream */ for (i = 0; i < s->nb_streams; i++) { + AVProgram *program; st = s->streams[i]; ts_st = av_mallocz(sizeof(MpegTSWriteStream)); @@ -824,6 +824,17 @@ static int mpegts_init(AVFormatContext *s) ret = AVERROR(ENOMEM); goto fail; } + + program = av_find_program_from_stream(s, NULL, i); + if (program) { + for (j = 0; j < ts->nb_services; j++) { + if (ts->services[j]->program == program) { + service = ts->services[j]; + break; + } + } + } + ts_st->service = service; /* MPEG pid values < 16 are reserved. Applications which set st->id in * this range are assigned a calculated pid. */ diff --git a/libavformat/mux.c b/libavformat/mux.c index 789c811cd8..48e266e0f2 100644 --- a/libavformat/mux.c +++ b/libavformat/mux.c @@ -400,7 +400,8 @@ FF_ENABLE_DEPRECATION_WARNINGS } if (s->oformat->init && (ret = s->oformat->init(s)) < 0) { - s->oformat->deinit(s); + if (s->oformat->deinit) + s->oformat->deinit(s); goto fail; } @@ -649,7 +650,7 @@ static int write_packet(AVFormatContext *s, AVPacket *pkt) av_log(s, AV_LOG_WARNING, "failed to avoid negative " "pts %s in stream %d.\n" "Try -avoid_negative_ts 1 as a possible workaround.\n", - av_ts2str(pkt->dts), + av_ts2str(pkt->pts), pkt->stream_index ); } diff --git a/libavformat/mvdec.c b/libavformat/mvdec.c index 7aa6452f66..e3feda6687 100644 --- a/libavformat/mvdec.c +++ b/libavformat/mvdec.c @@ -338,6 +338,8 @@ static int mv_read_header(AVFormatContext *avctx) uint32_t pos = avio_rb32(pb); uint32_t asize = avio_rb32(pb); uint32_t vsize = avio_rb32(pb); + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; avio_skip(pb, 8); av_add_index_entry(ast, pos, timestamp, asize, 0, AVINDEX_KEYFRAME); av_add_index_entry(vst, pos + asize, i, vsize, 0, AVINDEX_KEYFRAME); diff --git a/libavformat/mxfdec.c b/libavformat/mxfdec.c index f4222fcab5..bb0513aaa2 100644 --- a/libavformat/mxfdec.c +++ b/libavformat/mxfdec.c @@ -382,7 +382,7 @@ static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv) for (i = 0; i < s->nb_streams; i++) { MXFTrack *track = s->streams[i]->priv_data; /* SMPTE 379M 7.3 */ - if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number))) + if (track && !memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number))) return i; } /* return 0 if only one stream, for OP Atom files with 0 as track number */ @@ -491,7 +491,7 @@ static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, U avpriv_request_sample(pb, "Primer pack item length %d", item_len); return AVERROR_PATCHWELCOME; } - if (item_num > 65536) { + if (item_num > 65536 || item_num < 0) { av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num); return AVERROR_INVALIDDATA; } @@ -826,7 +826,7 @@ static inline int mxf_read_utf16_string(AVIOContext *pb, int size, char** str, i int ret; size_t buf_size; - if (size < 0) + if (size < 0 || size > INT_MAX/2) return AVERROR(EINVAL); buf_size = size + size / 2 + 1; @@ -887,6 +887,8 @@ static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *seg segment->nb_index_entries = avio_rb32(pb); length = avio_rb32(pb); + if(segment->nb_index_entries && length < 11) + return AVERROR_INVALIDDATA; if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) || !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) || @@ -897,6 +899,8 @@ static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *seg } for (i = 0; i < segment->nb_index_entries; i++) { + if(avio_feof(pb)) + return AVERROR_INVALIDDATA; segment->temporal_offset_entries[i] = avio_r8(pb); avio_r8(pb); /* KeyFrameOffset */ segment->flag_entries[i] = avio_r8(pb); @@ -3012,7 +3016,7 @@ static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt) if (mxf->nb_index_tables >= 1 && mxf->current_edit_unit < t->nb_ptses) { pkt->dts = mxf->current_edit_unit + t->first_dts; pkt->pts = t->ptses[mxf->current_edit_unit]; - } else if (track->intra_only) { + } else if (track && track->intra_only) { /* intra-only -> PTS = EditUnit. * let utils.c figure out DTS since it can be < PTS if low_delay = 0 (Sony IMX30) */ pkt->pts = mxf->current_edit_unit; diff --git a/libavformat/nsvdec.c b/libavformat/nsvdec.c index 95fab644a7..26e61507dc 100644 --- a/libavformat/nsvdec.c +++ b/libavformat/nsvdec.c @@ -177,6 +177,7 @@ typedef struct NSVContext { AVRational framerate; uint32_t *nsvs_timestamps; //DVDemuxContext* dv_demux; + int nsvf; } NSVContext; static const AVCodecTag nsv_codec_video_tags[] = { @@ -280,6 +281,12 @@ static int nsv_parse_NSVf_header(AVFormatContext *s) nsv->state = NSV_UNSYNC; /* in case we fail */ + if (nsv->nsvf) { + av_log(s, AV_LOG_TRACE, "Multiple NSVf\n"); + return 0; + } + nsv->nsvf = 1; + size = avio_rl32(pb); if (size < 28) return -1; @@ -350,8 +357,11 @@ static int nsv_parse_NSVf_header(AVFormatContext *s) if (!nsv->nsvs_file_offset) return AVERROR(ENOMEM); - for(i=0;insvs_file_offset[i] = avio_rl32(pb) + size; + } if(table_entries > table_entries_used && avio_rl32(pb) == MKTAG('T','O','C','2')) { diff --git a/libavformat/oggdec.c b/libavformat/oggdec.c index 2d99b4af25..99e51b8b65 100644 --- a/libavformat/oggdec.c +++ b/libavformat/oggdec.c @@ -643,6 +643,8 @@ static int ogg_get_length(AVFormatContext *s) int64_t pts; if (i < 0) continue; pts = ogg_calc_pts(s, i, NULL); + if (s->streams[i]->duration == AV_NOPTS_VALUE) + continue; if (pts != AV_NOPTS_VALUE && s->streams[i]->start_time == AV_NOPTS_VALUE && !ogg->streams[i].got_start) { s->streams[i]->duration -= pts; ogg->streams[i].got_start= 1; @@ -701,13 +703,16 @@ static int ogg_read_header(AVFormatContext *s) if (ogg->streams[i].header < 0) { av_log(s, AV_LOG_ERROR, "Header parsing failed for stream %d\n", i); ogg->streams[i].codec = NULL; + av_freep(&ogg->streams[i].private); } else if (os->codec && os->nb_header < os->codec->nb_header) { av_log(s, AV_LOG_WARNING, "Headers mismatch for stream %d: " "expected %d received %d.\n", i, os->codec->nb_header, os->nb_header); - if (s->error_recognition & AV_EF_EXPLODE) + if (s->error_recognition & AV_EF_EXPLODE) { + ogg_read_close(s); return AVERROR_INVALIDDATA; + } } if (os->start_granule != OGG_NOGRANULE_VALUE) os->lastpts = s->streams[i]->start_time = diff --git a/libavformat/oggdec.h b/libavformat/oggdec.h index d7af1cfabd..4a2b6ddee8 100644 --- a/libavformat/oggdec.h +++ b/libavformat/oggdec.h @@ -162,6 +162,11 @@ ogg_gptopts (AVFormatContext * s, int i, uint64_t gp, int64_t *dts) if (dts) *dts = pts; } + if (pts > INT64_MAX && pts != AV_NOPTS_VALUE) { + // The return type is unsigned, we thus cannot return negative pts + av_log(s, AV_LOG_ERROR, "invalid pts %"PRId64"\n", pts); + pts = AV_NOPTS_VALUE; + } return pts; } diff --git a/libavformat/oggparsecelt.c b/libavformat/oggparsecelt.c index 2c0c511c7b..6880314055 100644 --- a/libavformat/oggparsecelt.c +++ b/libavformat/oggparsecelt.c @@ -65,9 +65,14 @@ static int celt_header(AVFormatContext *s, int idx) st->codec->channels = nb_channels; if (sample_rate) avpriv_set_pts_info(st, 64, 1, sample_rate); - priv->extra_headers_left = 1 + extra_headers; - av_free(os->private); + + if (os->private) { + av_free(priv); + priv = os->private; + } os->private = priv; + priv->extra_headers_left = 1 + extra_headers; + AV_WL32(st->codec->extradata + 0, overlap); AV_WL32(st->codec->extradata + 4, version); return 1; diff --git a/libavformat/oggparsedaala.c b/libavformat/oggparsedaala.c index 3651ca188b..41dc059ecd 100644 --- a/libavformat/oggparsedaala.c +++ b/libavformat/oggparsedaala.c @@ -126,6 +126,7 @@ static int daala_header(AVFormatContext *s, int idx) if (hdr->gpshift >= 32) { av_log(s, AV_LOG_ERROR, "Too large gpshift %d (>= 32).\n", hdr->gpshift); + hdr->gpshift = 0; return AVERROR_INVALIDDATA; } hdr->gpmask = (1U << hdr->gpshift) - 1; @@ -217,6 +218,7 @@ static int daala_packet(AVFormatContext *s, int idx) int seg, duration = 1; struct ogg *ogg = s->priv_data; struct ogg_stream *os = ogg->streams + idx; + int64_t pts; /* * first packet handling: here we parse the duration of each packet in the @@ -229,10 +231,13 @@ static int daala_packet(AVFormatContext *s, int idx) if (os->segments[seg] < 255) duration++; - os->lastpts = os->lastdts = daala_gptopts(s, idx, os->granule, NULL) - duration; + pts = daala_gptopts(s, idx, os->granule, NULL); + if (pts != AV_NOPTS_VALUE) + pts -= duration; + os->lastpts = os->lastdts = pts; if(s->streams[idx]->start_time == AV_NOPTS_VALUE) { s->streams[idx]->start_time = os->lastpts; - if (s->streams[idx]->duration) + if (s->streams[idx]->duration != AV_NOPTS_VALUE) s->streams[idx]->duration -= s->streams[idx]->start_time; } } diff --git a/libavformat/oggparseogm.c b/libavformat/oggparseogm.c index d63c83b1c2..37284925e7 100644 --- a/libavformat/oggparseogm.c +++ b/libavformat/oggparseogm.c @@ -172,11 +172,14 @@ ogm_packet(AVFormatContext *s, int idx) os->pflags |= AV_PKT_FLAG_KEY; lb = ((*p & 2) << 1) | ((*p >> 6) & 3); + if (os->psize < lb + 1) + return AVERROR_INVALIDDATA; + os->pstart += lb + 1; os->psize -= lb + 1; while (lb--) - os->pduration += p[lb+1] << (lb*8); + os->pduration += (uint64_t)p[lb+1] << (lb*8); return 0; } diff --git a/libavformat/oggparseopus.c b/libavformat/oggparseopus.c index c8b02fab4d..8bb2a41366 100644 --- a/libavformat/oggparseopus.c +++ b/libavformat/oggparseopus.c @@ -117,6 +117,10 @@ static int opus_packet(AVFormatContext *avf, int idx) if (!os->psize) return AVERROR_INVALIDDATA; + if (os->granule > (1LL << 62)) { + av_log(avf, AV_LOG_ERROR, "Unsupported huge granule pos %"PRId64 "\n", os->granule); + return AVERROR_INVALIDDATA; + } if ((!os->lastpts || os->lastpts == AV_NOPTS_VALUE) && !(os->flags & OGG_FLAG_EOS)) { int seg, d; diff --git a/libavformat/oggparsespeex.c b/libavformat/oggparsespeex.c index c86b12713e..3440a501c4 100644 --- a/libavformat/oggparsespeex.c +++ b/libavformat/oggparsespeex.c @@ -76,6 +76,13 @@ static int speex_header(AVFormatContext *s, int idx) { spxp->packet_size = AV_RL32(p + 56); frames_per_packet = AV_RL32(p + 64); + if (spxp->packet_size < 0 || + frames_per_packet < 0 || + spxp->packet_size * (int64_t)frames_per_packet > INT32_MAX / 256) { + av_log(s, AV_LOG_ERROR, "invalid packet_size, frames_per_packet %d %d\n", spxp->packet_size, frames_per_packet); + spxp->packet_size = 0; + return AVERROR_INVALIDDATA; + } if (frames_per_packet) spxp->packet_size *= frames_per_packet; diff --git a/libavformat/oggparsetheora.c b/libavformat/oggparsetheora.c index 5f057c3c8a..6db3d9f848 100644 --- a/libavformat/oggparsetheora.c +++ b/libavformat/oggparsetheora.c @@ -181,6 +181,7 @@ static int theora_packet(AVFormatContext *s, int idx) if ((!os->lastpts || os->lastpts == AV_NOPTS_VALUE) && !(os->flags & OGG_FLAG_EOS)) { int seg; + int64_t pts; duration = 1; for (seg = os->segp; seg < os->nsegs; seg++) { @@ -188,7 +189,10 @@ static int theora_packet(AVFormatContext *s, int idx) duration ++; } - os->lastpts = os->lastdts = theora_gptopts(s, idx, os->granule, NULL) - duration; + pts = theora_gptopts(s, idx, os->granule, NULL); + if (pts != AV_NOPTS_VALUE) + pts -= duration; + os->lastpts = os->lastdts = pts; if(s->streams[idx]->start_time == AV_NOPTS_VALUE) { s->streams[idx]->start_time = os->lastpts; if (s->streams[idx]->duration > 0) diff --git a/libavformat/oggparsevorbis.c b/libavformat/oggparsevorbis.c index b96be98974..1c8acc3f94 100644 --- a/libavformat/oggparsevorbis.c +++ b/libavformat/oggparsevorbis.c @@ -228,6 +228,10 @@ static int fixup_vorbis_headers(AVFormatContext *as, len = priv->len[0] + priv->len[1] + priv->len[2]; buf_len = len + len / 255 + 64; + + if (*buf) + return AVERROR_INVALIDDATA; + ptr = *buf = av_realloc(NULL, buf_len); if (!ptr) return AVERROR(ENOMEM); diff --git a/libavformat/oggparsevp8.c b/libavformat/oggparsevp8.c index 7aed8abad3..54f1fa6544 100644 --- a/libavformat/oggparsevp8.c +++ b/libavformat/oggparsevp8.c @@ -82,7 +82,11 @@ static uint64_t vp8_gptopts(AVFormatContext *s, int idx, struct ogg *ogg = s->priv_data; struct ogg_stream *os = ogg->streams + idx; - uint64_t pts = (granule >> 32); + int invcnt = !((granule >> 30) & 3); + // If page granule is that of an invisible vp8 frame, its pts will be + // that of the end of the next visible frame. We substract 1 for those + // to prevent messing up pts calculations. + uint64_t pts = (granule >> 32) - invcnt; uint32_t dist = (granule >> 3) & 0x07ffffff; if (!dist) @@ -121,7 +125,7 @@ static int vp8_packet(AVFormatContext *s, int idx) os->lastdts = vp8_gptopts(s, idx, os->granule, NULL) - duration; if(s->streams[idx]->start_time == AV_NOPTS_VALUE) { s->streams[idx]->start_time = os->lastpts; - if (s->streams[idx]->duration) + if (s->streams[idx]->duration && s->streams[idx]->duration != AV_NOPTS_VALUE) s->streams[idx]->duration -= s->streams[idx]->start_time; } } diff --git a/libavformat/options.c b/libavformat/options.c index 8fe0017196..9d5593e060 100644 --- a/libavformat/options.c +++ b/libavformat/options.c @@ -102,6 +102,18 @@ static const AVClass av_format_context_class = { static int io_open_default(AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **options) { + int loglevel; + + if (!strcmp(url, s->filename) || + s->iformat && !strcmp(s->iformat->name, "image2") || + s->oformat && !strcmp(s->oformat->name, "image2") + ) { + loglevel = AV_LOG_DEBUG; + } else + loglevel = AV_LOG_INFO; + + av_log(s, loglevel, "Opening \'%s\' for %s\n", url, flags & AVIO_FLAG_WRITE ? "writing" : "reading"); + #if FF_API_OLD_OPEN_CALLBACKS FF_DISABLE_DEPRECATION_WARNINGS if (s->open_cb) diff --git a/libavformat/options_table.h b/libavformat/options_table.h index 8926fe5734..20f87c4024 100644 --- a/libavformat/options_table.h +++ b/libavformat/options_table.h @@ -87,6 +87,7 @@ static const AVOption avformat_options[] = { {"max_interleave_delta", "maximum buffering duration for interleaving", OFFSET(max_interleave_delta), AV_OPT_TYPE_INT64, { .i64 = 10000000 }, 0, INT64_MAX, E }, {"f_strict", "how strictly to follow the standards (deprecated; use strict, save via avconv)", OFFSET(strict_std_compliance), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, D|E, "strict"}, {"strict", "how strictly to follow the standards", OFFSET(strict_std_compliance), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, D|E, "strict"}, +{"very", "strictly conform to a older more strict version of the spec or reference software", 0, AV_OPT_TYPE_CONST, {.i64 = FF_COMPLIANCE_VERY_STRICT }, INT_MIN, INT_MAX, D|E, "strict"}, {"strict", "strictly conform to all the things in the spec no matter what the consequences", 0, AV_OPT_TYPE_CONST, {.i64 = FF_COMPLIANCE_STRICT }, INT_MIN, INT_MAX, D|E, "strict"}, {"normal", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_COMPLIANCE_NORMAL }, INT_MIN, INT_MAX, D|E, "strict"}, {"unofficial", "allow unofficial extensions", 0, AV_OPT_TYPE_CONST, {.i64 = FF_COMPLIANCE_UNOFFICIAL }, INT_MIN, INT_MAX, D|E, "strict"}, @@ -101,6 +102,7 @@ static const AVOption avformat_options[] = { {"codec_whitelist", "List of decoders that are allowed to be used", OFFSET(codec_whitelist), AV_OPT_TYPE_STRING, { .str = NULL }, CHAR_MIN, CHAR_MAX, D }, {"format_whitelist", "List of demuxers that are allowed to be used", OFFSET(format_whitelist), AV_OPT_TYPE_STRING, { .str = NULL }, CHAR_MIN, CHAR_MAX, D }, {"protocol_whitelist", "List of protocols that are allowed to be used", OFFSET(protocol_whitelist), AV_OPT_TYPE_STRING, { .str = NULL }, CHAR_MIN, CHAR_MAX, D }, +{"max_streams", "maximum number of streams", OFFSET(max_streams), AV_OPT_TYPE_INT, { .i64 = 1000 }, 0, INT_MAX, D }, {NULL}, }; diff --git a/libavformat/pva.c b/libavformat/pva.c index 900ad6133d..9714fb186c 100644 --- a/libavformat/pva.c +++ b/libavformat/pva.c @@ -134,6 +134,10 @@ recover: pes_flags = avio_rb16(pb); pes_header_data_length = avio_r8(pb); + if (avio_feof(pb)) { + return AVERROR_EOF; + } + if (pes_signal != 1 || pes_header_data_length == 0) { pva_log(s, AV_LOG_WARNING, "expected non empty signaled PES packet, " "trying to recover\n"); diff --git a/libavformat/rl2.c b/libavformat/rl2.c index 5017016644..dacd65cd84 100644 --- a/libavformat/rl2.c +++ b/libavformat/rl2.c @@ -170,12 +170,21 @@ static av_cold int rl2_read_header(AVFormatContext *s) } /** read offset and size tables */ - for(i=0; i < frame_count;i++) + for(i=0; i < frame_count;i++) { + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; chunk_size[i] = avio_rl32(pb); - for(i=0; i < frame_count;i++) + } + for(i=0; i < frame_count;i++) { + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; chunk_offset[i] = avio_rl32(pb); - for(i=0; i < frame_count;i++) + } + for(i=0; i < frame_count;i++) { + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; audio_size[i] = avio_rl32(pb) & 0xFFFF; + } /** build the sample index */ for(i=0;ipb, st2, st2->priv_data, - size2, mime); + size2, NULL); if (ret < 0) return ret; } @@ -1231,8 +1231,11 @@ static int ivr_read_header(AVFormatContext *s) av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4) { av_log(s, AV_LOG_DEBUG, "%s = '0x", key); - for (j = 0; j < len; j++) + for (j = 0; j < len; j++) { + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); + } av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "StreamCount", tlen)) { nb_streams = value = avio_rb32(pb); @@ -1275,6 +1278,8 @@ static int ivr_read_header(AVFormatContext *s) if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) { ret = rm_read_multi(s, pb, st, NULL); } else { + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; avio_seek(pb, -4, SEEK_CUR); ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL); } diff --git a/libavformat/rsd.c b/libavformat/rsd.c index dd1f3723d0..c773c0aa9e 100644 --- a/libavformat/rsd.c +++ b/libavformat/rsd.c @@ -84,8 +84,10 @@ static int rsd_read_header(AVFormatContext *s) } codec->channels = avio_rl32(pb); - if (!codec->channels) + if (codec->channels <= 0 || codec->channels > INT_MAX / 36) { + av_log(s, AV_LOG_ERROR, "Invalid number of channels: %d\n", codec->channels); return AVERROR_INVALIDDATA; + } avio_skip(pb, 4); // Bit depth codec->sample_rate = avio_rl32(pb); diff --git a/libavformat/rtmppkt.c b/libavformat/rtmppkt.c index 0d693c27f7..ca7838868e 100644 --- a/libavformat/rtmppkt.c +++ b/libavformat/rtmppkt.c @@ -235,6 +235,14 @@ static int rtmp_packet_read_one_chunk(URLContext *h, RTMPPacket *p, if (hdr != RTMP_PS_TWELVEBYTES) timestamp += prev_pkt[channel_id].timestamp; + if (prev_pkt[channel_id].read && size != prev_pkt[channel_id].size) { + av_log(NULL, AV_LOG_ERROR, "RTMP packet size mismatch %d != %d\n", + size, + prev_pkt[channel_id].size); + ff_rtmp_packet_destroy(&prev_pkt[channel_id]); + prev_pkt[channel_id].read = 0; + } + if (!prev_pkt[channel_id].read) { if ((ret = ff_rtmp_packet_create(p, channel_id, type, timestamp, size)) < 0) @@ -425,97 +433,142 @@ void ff_rtmp_packet_destroy(RTMPPacket *pkt) pkt->size = 0; } -int ff_amf_tag_size(const uint8_t *data, const uint8_t *data_end) +static int amf_tag_skip(GetByteContext *gb) { - const uint8_t *base = data; AMFDataType type; unsigned nb = -1; int parse_key = 1; - if (data >= data_end) + if (bytestream2_get_bytes_left(gb) < 1) return -1; - switch ((type = *data++)) { - case AMF_DATA_TYPE_NUMBER: return 9; - case AMF_DATA_TYPE_BOOL: return 2; - case AMF_DATA_TYPE_STRING: return 3 + AV_RB16(data); - case AMF_DATA_TYPE_LONG_STRING: return 5 + AV_RB32(data); - case AMF_DATA_TYPE_NULL: return 1; - case AMF_DATA_TYPE_DATE: return 11; + + type = bytestream2_get_byte(gb); + switch (type) { + case AMF_DATA_TYPE_NUMBER: + bytestream2_get_be64(gb); + return 0; + case AMF_DATA_TYPE_BOOL: + bytestream2_get_byte(gb); + return 0; + case AMF_DATA_TYPE_STRING: + bytestream2_skip(gb, bytestream2_get_be16(gb)); + return 0; + case AMF_DATA_TYPE_LONG_STRING: + bytestream2_skip(gb, bytestream2_get_be32(gb)); + return 0; + case AMF_DATA_TYPE_NULL: + return 0; + case AMF_DATA_TYPE_DATE: + bytestream2_skip(gb, 10); + return 0; case AMF_DATA_TYPE_ARRAY: parse_key = 0; case AMF_DATA_TYPE_MIXEDARRAY: - nb = bytestream_get_be32(&data); + nb = bytestream2_get_be32(gb); case AMF_DATA_TYPE_OBJECT: while (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY) { int t; if (parse_key) { - int size = bytestream_get_be16(&data); + int size = bytestream2_get_be16(gb); if (!size) { - data++; + bytestream2_get_byte(gb); break; } - if (size < 0 || size >= data_end - data) + if (size < 0 || size >= bytestream2_get_bytes_left(gb)) return -1; - data += size; + bytestream2_skip(gb, size); } - t = ff_amf_tag_size(data, data_end); - if (t < 0 || t >= data_end - data) + t = amf_tag_skip(gb); + if (t < 0 || bytestream2_get_bytes_left(gb) <= 0) return -1; - data += t; } - return data - base; - case AMF_DATA_TYPE_OBJECT_END: return 1; + return 0; + case AMF_DATA_TYPE_OBJECT_END: return 0; default: return -1; } } -int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end, +int ff_amf_tag_size(const uint8_t *data, const uint8_t *data_end) +{ + GetByteContext gb; + int ret; + + if (data >= data_end) + return -1; + + bytestream2_init(&gb, data, data_end - data); + + ret = amf_tag_skip(&gb); + if (ret < 0 || bytestream2_get_bytes_left(&gb) <= 0) + return -1; + av_assert0(bytestream2_tell(&gb) >= 0 && bytestream2_tell(&gb) <= data_end - data); + return bytestream2_tell(&gb); +} + +static int amf_get_field_value2(GetByteContext *gb, const uint8_t *name, uint8_t *dst, int dst_size) { int namelen = strlen(name); int len; - while (*data != AMF_DATA_TYPE_OBJECT && data < data_end) { - len = ff_amf_tag_size(data, data_end); - if (len < 0) - len = data_end - data; - data += len; + while (bytestream2_peek_byte(gb) != AMF_DATA_TYPE_OBJECT && bytestream2_get_bytes_left(gb) > 0) { + int ret = amf_tag_skip(gb); + if (ret < 0) + return -1; } - if (data_end - data < 3) + if (bytestream2_get_bytes_left(gb) < 3) return -1; - data++; + bytestream2_get_byte(gb); + for (;;) { - int size = bytestream_get_be16(&data); + int size = bytestream2_get_be16(gb); if (!size) break; - if (size < 0 || size >= data_end - data) + if (size < 0 || size >= bytestream2_get_bytes_left(gb)) return -1; - data += size; - if (size == namelen && !memcmp(data-size, name, namelen)) { - switch (*data++) { + bytestream2_skip(gb, size); + if (size == namelen && !memcmp(gb->buffer-size, name, namelen)) { + switch (bytestream2_get_byte(gb)) { case AMF_DATA_TYPE_NUMBER: - snprintf(dst, dst_size, "%g", av_int2double(AV_RB64(data))); + snprintf(dst, dst_size, "%g", av_int2double(bytestream2_get_be64(gb))); break; case AMF_DATA_TYPE_BOOL: - snprintf(dst, dst_size, "%s", *data ? "true" : "false"); + snprintf(dst, dst_size, "%s", bytestream2_get_byte(gb) ? "true" : "false"); break; case AMF_DATA_TYPE_STRING: - len = bytestream_get_be16(&data); - av_strlcpy(dst, data, FFMIN(len+1, dst_size)); + len = bytestream2_get_be16(gb); + if (dst_size < 1) + return -1; + if (dst_size < len + 1) + len = dst_size - 1; + bytestream2_get_buffer(gb, dst, len); + dst[len] = 0; break; default: return -1; } return 0; } - len = ff_amf_tag_size(data, data_end); - if (len < 0 || len >= data_end - data) + len = amf_tag_skip(gb); + if (len < 0 || bytestream2_get_bytes_left(gb) <= 0) return -1; - data += len; } return -1; } +int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end, + const uint8_t *name, uint8_t *dst, int dst_size) +{ + GetByteContext gb; + + if (data >= data_end) + return -1; + + bytestream2_init(&gb, data, data_end - data); + + return amf_get_field_value2(&gb, name, dst, dst_size); +} + static const char* rtmp_packet_type(int type) { switch (type) { diff --git a/libavformat/rtpdec_asf.c b/libavformat/rtpdec_asf.c index 2b1ddf140d..1c88580f84 100644 --- a/libavformat/rtpdec_asf.c +++ b/libavformat/rtpdec_asf.c @@ -101,7 +101,7 @@ int ff_wms_parse_sdp_a_line(AVFormatContext *s, const char *p) { int ret = 0; if (av_strstart(p, "pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,", &p)) { - AVIOContext pb; + AVIOContext pb = { 0 }; RTSPState *rt = s->priv_data; AVDictionary *opts = NULL; int len = strlen(p) * 6 / 8; diff --git a/libavformat/rtpdec_jpeg.c b/libavformat/rtpdec_jpeg.c index f3a2060523..397b5cf56c 100644 --- a/libavformat/rtpdec_jpeg.c +++ b/libavformat/rtpdec_jpeg.c @@ -193,16 +193,17 @@ static void create_default_qtables(uint8_t *qtables, uint8_t q) { int factor = q; int i; + uint16_t S; factor = av_clip(q, 1, 99); if (q < 50) - q = 5000 / factor; + S = 5000 / factor; else - q = 200 - factor * 2; + S = 200 - factor * 2; for (i = 0; i < 128; i++) { - int val = (default_quantizers[i] * q + 50) / 100; + int val = (default_quantizers[i] * S + 50) / 100; /* Limit the quantizers to 1 <= q <= 255. */ val = av_clip(val, 1, 255); diff --git a/libavformat/rtpenc.c b/libavformat/rtpenc.c index 31569d60b7..00b69f5765 100644 --- a/libavformat/rtpenc.c +++ b/libavformat/rtpenc.c @@ -271,7 +271,8 @@ static void rtcp_send_sr(AVFormatContext *s1, int64_t ntp_time, int bye) avio_w8(s1->pb, RTCP_SR); avio_wb16(s1->pb, 6); /* length in words - 1 */ avio_wb32(s1->pb, s->ssrc); - avio_wb64(s1->pb, NTP_TO_RTP_FORMAT(ntp_time)); + avio_wb32(s1->pb, ntp_time / 1000000); + avio_wb32(s1->pb, ((ntp_time % 1000000) << 32) / 1000000); avio_wb32(s1->pb, rtp_ts); avio_wb32(s1->pb, s->packet_count); avio_wb32(s1->pb, s->octet_count); diff --git a/libavformat/sbgdec.c b/libavformat/sbgdec.c index 03cd9226c9..659dfc81ff 100644 --- a/libavformat/sbgdec.c +++ b/libavformat/sbgdec.c @@ -927,7 +927,7 @@ static void expand_timestamps(void *log, struct sbg_script *s) } } if (s->start_ts == AV_NOPTS_VALUE) - s->start_ts = s->opt_start_at_first ? s->tseq[0].ts.t : now; + s->start_ts = (s->opt_start_at_first && s->tseq) ? s->tseq[0].ts.t : now; s->end_ts = s->opt_duration ? s->start_ts + s->opt_duration : AV_NOPTS_VALUE; /* may be overridden later by -E option */ cur_ts = now; diff --git a/libavformat/svag.c b/libavformat/svag.c index ab7f36c81a..08fc06b1ba 100644 --- a/libavformat/svag.c +++ b/libavformat/svag.c @@ -48,7 +48,7 @@ static int svag_read_header(AVFormatContext *s) if (st->codec->sample_rate <= 0) return AVERROR_INVALIDDATA; st->codec->channels = avio_rl32(s->pb); - if (st->codec->channels <= 0) + if (st->codec->channels <= 0 || st->codec->channels > 8) return AVERROR_INVALIDDATA; st->duration = size / (16 * st->codec->channels) * 28; align = avio_rl32(s->pb); diff --git a/libavformat/swfdec.c b/libavformat/swfdec.c index eb17e82e08..518ca1fcb9 100644 --- a/libavformat/swfdec.c +++ b/libavformat/swfdec.c @@ -119,10 +119,10 @@ retry: z->avail_out = buf_size; ret = inflate(z, Z_NO_FLUSH); - if (ret < 0) - return AVERROR(EINVAL); if (ret == Z_STREAM_END) return AVERROR_EOF; + if (ret != Z_OK) + return AVERROR(EINVAL); if (buf_size - z->avail_out == 0) goto retry; diff --git a/libavformat/utils.c b/libavformat/utils.c index 129a49d699..3f02149ef4 100644 --- a/libavformat/utils.c +++ b/libavformat/utils.c @@ -297,7 +297,7 @@ static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, int score; AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score); - if (fmt && st->request_probe <= score) { + if (fmt) { int i; av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n", @@ -305,6 +305,9 @@ static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, fmt->name, score); for (i = 0; fmt_id_type[i].name; i++) { if (!strcmp(fmt->name, fmt_id_type[i].name)) { + if (st->request_probe > score && + st->codec->codec_id != fmt_id_type[i].id) + continue; st->codec->codec_id = fmt_id_type[i].id; st->codec->codec_type = fmt_id_type[i].type; return score; @@ -445,6 +448,7 @@ int avformat_open_input(AVFormatContext **ps, const char *filename, if ((ret = av_opt_set_dict(s, &tmp)) < 0) goto fail; + av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename)); if ((ret = init_input(s, filename, &tmp)) < 0) goto fail; s->probe_score = ret; @@ -474,7 +478,6 @@ int avformat_open_input(AVFormatContext **ps, const char *filename, } s->duration = s->start_time = AV_NOPTS_VALUE; - av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename)); /* Allocate private data. */ if (s->iformat->priv_data_size > 0) { @@ -705,7 +708,7 @@ int ff_read_packet(AVFormatContext *s, AVPacket *pkt) return ret; for (i = 0; i < s->nb_streams; i++) { st = s->streams[i]; - if (st->probe_packets) + if (st->probe_packets || st->request_probe > 0) if ((err = probe_codec(s, st, NULL)) < 0) return err; av_assert0(st->request_probe <= 0); @@ -934,6 +937,7 @@ static void update_initial_timestamps(AVFormatContext *s, int stream_index, if (st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE || + st->cur_dts < INT_MIN + RELATIVE_TS_BASE || is_relative(dts)) return; @@ -1153,7 +1157,7 @@ static void compute_pkt_fields(AVFormatContext *s, AVStream *st, /* This is tricky: the dts must be incremented by the duration * of the frame we are displaying, i.e. the last I- or P-frame. */ - if (st->last_IP_duration == 0) + if (st->last_IP_duration == 0 && (uint64_t)pkt->duration <= INT32_MAX) st->last_IP_duration = pkt->duration; if (pkt->dts != AV_NOPTS_VALUE) st->cur_dts = pkt->dts + st->last_IP_duration; @@ -1165,7 +1169,8 @@ static void compute_pkt_fields(AVFormatContext *s, AVStream *st, next_pts != AV_NOPTS_VALUE) pkt->pts = next_dts; - st->last_IP_duration = pkt->duration; + if ((uint64_t)pkt->duration <= INT32_MAX) + st->last_IP_duration = pkt->duration; st->last_IP_pts = pkt->pts; /* Cannot compute PTS if not present (we can compute it only * by knowing the future. */ @@ -1186,12 +1191,13 @@ static void compute_pkt_fields(AVFormatContext *s, AVStream *st, } } - if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY && has_decode_delay_been_guessed(st)) { + if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) { st->pts_buffer[0] = pkt->pts; for (i = 0; ipts_buffer[i] > st->pts_buffer[i + 1]; i++) FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]); - pkt->dts = select_from_pts_buffer(st, st->pts_buffer, pkt->dts); + if(has_decode_delay_been_guessed(st)) + pkt->dts = select_from_pts_buffer(st, st->pts_buffer, pkt->dts); } // We skipped it above so we try here. if (!onein_oneout) @@ -1534,10 +1540,11 @@ int av_read_frame(AVFormatContext *s, AVPacket *pkt) // last dts seen for this stream. if any of packets following // current one had no dts, we will set this to AV_NOPTS_VALUE. int64_t last_dts = next_pkt->dts; + av_assert2(wrap_bits <= 64); while (pktl && next_pkt->pts == AV_NOPTS_VALUE) { if (pktl->pkt.stream_index == next_pkt->stream_index && - (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0)) { - if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { + av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2ULL << (wrap_bits - 1)) < 0) { + if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2ULL << (wrap_bits - 1))) { // not B-frame next_pkt->pts = pktl->pkt.dts; } @@ -2280,6 +2287,7 @@ int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, max_ts = av_rescale_rnd(max_ts, time_base.den, time_base.num * (int64_t)AV_TIME_BASE, AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX); + stream_index = 0; } ret = s->iformat->read_seek2(s, stream_index, min_ts, @@ -2369,7 +2377,7 @@ static void update_stream_timings(AVFormatContext *ic) end_time1 = av_rescale_q_rnd(st->duration, st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); - if (end_time1 != AV_NOPTS_VALUE) { + if (end_time1 != AV_NOPTS_VALUE && (end_time1 > 0 ? start_time1 <= INT64_MAX - end_time1 : start_time1 >= INT64_MIN - end_time1)) { end_time1 += start_time1; end_time = FFMAX(end_time, end_time1); } @@ -2397,17 +2405,20 @@ static void update_stream_timings(AVFormatContext *ic) if (ic->nb_programs) { for (i = 0; i < ic->nb_programs; i++) { p = ic->programs[i]; - if (p->start_time != AV_NOPTS_VALUE && p->end_time > p->start_time) + if (p->start_time != AV_NOPTS_VALUE && + p->end_time > p->start_time && + p->end_time - (uint64_t)p->start_time <= INT64_MAX) duration = FFMAX(duration, p->end_time - p->start_time); } - } else + } else if (end_time >= start_time && end_time - (uint64_t)start_time <= INT64_MAX) { duration = FFMAX(duration, end_time - start_time); + } } } if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) { ic->duration = duration; } - if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration != AV_NOPTS_VALUE) { + if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration > 0) { /* compute the bitrate */ double bitrate = (double) filesize * 8.0 * AV_TIME_BASE / (double) ic->duration; @@ -2832,6 +2843,9 @@ enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag) enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags) { + if (bps <= 0 || bps > 64) + return AV_CODEC_ID_NONE; + if (flt) { switch (bps) { case 32: @@ -2915,7 +2929,7 @@ static void compute_chapters_end(AVFormatContext *s) unsigned int i, j; int64_t max_time = 0; - if (s->duration > 0) + if (s->duration > 0 && s->start_time < INT64_MAX - s->duration) max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time); @@ -3350,8 +3364,8 @@ int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options) * sequence, we treat it as a discontinuity. */ if (st->info->fps_last_dts != AV_NOPTS_VALUE && st->info->fps_last_dts_idx > st->info->fps_first_dts_idx && - (pkt->dts - st->info->fps_last_dts) / 1000 > - (st->info->fps_last_dts - st->info->fps_first_dts) / + (pkt->dts - (uint64_t)st->info->fps_last_dts) / 1000 > + (st->info->fps_last_dts - (uint64_t)st->info->fps_first_dts) / (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) { av_log(ic, AV_LOG_WARNING, "DTS discontinuity in stream %d: packet %d with DTS " @@ -3464,12 +3478,6 @@ int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options) } } - // close codecs which were opened in try_decode_frame() - for (i = 0; i < ic->nb_streams; i++) { - st = ic->streams[i]; - avcodec_close(st->codec); - } - ff_rfps_calculate(ic); for (i = 0; i < ic->nb_streams; i++) { @@ -3585,6 +3593,7 @@ find_stream_info_err: ic->streams[i]->codec->thread_count = 0; if (st->info) av_freep(&st->info->duration_error); + avcodec_close(st->codec); av_freep(&ic->streams[i]->info); } if (ic->pb) @@ -3717,9 +3726,7 @@ static void free_stream(AVStream **pst) av_dict_free(&st->metadata); av_freep(&st->probe_data.buf); av_freep(&st->index_entries); - av_freep(&st->codec->extradata); - av_freep(&st->codec->subtitle_header); - av_freep(&st->codec); + avcodec_free_context(&st->codec); av_freep(&st->priv_data); if (st->info) av_freep(&st->info->duration_error); @@ -3769,8 +3776,8 @@ void avformat_free_context(AVFormatContext *s) av_freep(&s->chapters); av_dict_free(&s->metadata); av_freep(&s->streams); - av_freep(&s->internal); flush_packet_queue(s); + av_freep(&s->internal); av_free(s); } @@ -3808,8 +3815,11 @@ AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c) int i; AVStream **streams; - if (s->nb_streams >= INT_MAX/sizeof(*streams)) + if (s->nb_streams >= FFMIN(s->max_streams, INT_MAX/sizeof(*streams))) { + if (s->max_streams < INT_MAX/sizeof(*streams)) + av_log(s, AV_LOG_ERROR, "Number of streams exceeds max_streams parameter (%d), see the documentation if you wish to increase it\n", s->max_streams); return NULL; + } streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams)); if (!streams) return NULL; diff --git a/libavformat/wavdec.c b/libavformat/wavdec.c index d95596f6ed..a9ba03f557 100644 --- a/libavformat/wavdec.c +++ b/libavformat/wavdec.c @@ -804,6 +804,8 @@ static int w64_read_header(AVFormatContext *s) chunk_key[4] = 0; avio_read(pb, chunk_key, 4); chunk_size = avio_rl32(pb); + if (chunk_size == UINT32_MAX) + return AVERROR_INVALIDDATA; value = av_mallocz(chunk_size + 1); if (!value) diff --git a/libavformat/webmdashenc.c b/libavformat/webmdashenc.c index 301c045b41..757cf8b030 100644 --- a/libavformat/webmdashenc.c +++ b/libavformat/webmdashenc.c @@ -428,6 +428,10 @@ static int parse_adaptation_sets(AVFormatContext *s) char *p = w->adaptation_sets; char *q; enum { new_set, parsed_id, parsing_streams } state; + if (!w->adaptation_sets) { + av_log(s, AV_LOG_ERROR, "The 'adaptation_sets' option must be set.\n"); + return AVERROR(EINVAL); + } // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on state = new_set; while (p < w->adaptation_sets + strlen(w->adaptation_sets)) { @@ -458,7 +462,11 @@ static int parse_adaptation_sets(AVFormatContext *s) if (as->streams == NULL) return AVERROR(ENOMEM); as->streams[as->nb_streams - 1] = to_integer(p, q - p + 1); - if (as->streams[as->nb_streams - 1] < 0) return -1; + if (as->streams[as->nb_streams - 1] < 0 || + as->streams[as->nb_streams - 1] >= s->nb_streams) { + av_log(s, AV_LOG_ERROR, "Invalid value for 'streams' in adapation_sets.\n"); + return AVERROR(EINVAL); + } if (*q == '\0') break; if (*q == ' ') state = new_set; p = ++q; diff --git a/libavformat/wtvdec.c b/libavformat/wtvdec.c index 71deaf0aa6..882fde13f4 100644 --- a/libavformat/wtvdec.c +++ b/libavformat/wtvdec.c @@ -1033,7 +1033,7 @@ static int read_header(AVFormatContext *s) while (1) { uint64_t frame_nb = avio_rl64(pb); uint64_t position = avio_rl64(pb); - while (frame_nb > e->size && e <= e_end) { + while (e <= e_end && frame_nb > e->size) { e->pos = last_position; e++; } diff --git a/libavutil/channel_layout.c b/libavutil/channel_layout.c index 601c7e677c..26c87c96a8 100644 --- a/libavutil/channel_layout.c +++ b/libavutil/channel_layout.c @@ -94,7 +94,7 @@ static const struct { { "6.0(front)", 6, AV_CH_LAYOUT_6POINT0_FRONT }, { "hexagonal", 6, AV_CH_LAYOUT_HEXAGONAL }, { "6.1", 7, AV_CH_LAYOUT_6POINT1 }, - { "6.1", 7, AV_CH_LAYOUT_6POINT1_BACK }, + { "6.1(back)", 7, AV_CH_LAYOUT_6POINT1_BACK }, { "6.1(front)", 7, AV_CH_LAYOUT_6POINT1_FRONT }, { "7.0", 7, AV_CH_LAYOUT_7POINT0 }, { "7.0(front)", 7, AV_CH_LAYOUT_7POINT0_FRONT }, diff --git a/libavutil/colorspace.h b/libavutil/colorspace.h index 826ffd52c4..7d3f7110c9 100644 --- a/libavutil/colorspace.h +++ b/libavutil/colorspace.h @@ -41,6 +41,16 @@ b_add = FIX(1.77200*255.0/224.0) * cb + ONE_HALF;\ } +#define YUV_TO_RGB1_CCIR_BT709(cb1, cr1)\ +{\ + cb = (cb1) - 128;\ + cr = (cr1) - 128;\ + r_add = FIX(1.5747*255.0/224.0) * cr + ONE_HALF;\ + g_add = - FIX(0.1873*255.0/224.0) * cb - FIX(0.4682*255.0/224.0) * cr + \ + ONE_HALF;\ + b_add = FIX(1.8556*255.0/224.0) * cb + ONE_HALF;\ +} + #define YUV_TO_RGB2_CCIR(r, g, b, y1)\ {\ y = ((y1) - 16) * FIX(255.0/219.0);\ diff --git a/libavutil/common.h b/libavutil/common.h index 8142b31fdb..58ead80514 100644 --- a/libavutil/common.h +++ b/libavutil/common.h @@ -158,7 +158,7 @@ static av_always_inline av_const int64_t av_clip64_c(int64_t a, int64_t amin, in */ static av_always_inline av_const uint8_t av_clip_uint8_c(int a) { - if (a&(~0xFF)) return (-a)>>31; + if (a&(~0xFF)) return (~a)>>31; else return a; } @@ -180,7 +180,7 @@ static av_always_inline av_const int8_t av_clip_int8_c(int a) */ static av_always_inline av_const uint16_t av_clip_uint16_c(int a) { - if (a&(~0xFFFF)) return (-a)>>31; + if (a&(~0xFFFF)) return (~a)>>31; else return a; } @@ -228,7 +228,7 @@ static av_always_inline av_const int av_clip_intp2_c(int a, int p) */ static av_always_inline av_const unsigned av_clip_uintp2_c(int a, int p) { - if (a & ~((1<> 31 & ((1<> 31 & ((1<0 && (int)h>0 && (w+128)*(uint64_t)(h+128) < INT_MAX/8) - return 0; + if ((int)w<=0 || (int)h<=0 || stride >= INT_MAX || stride*(uint64_t)(h+128) >= INT_MAX) { + av_log(&imgutils, AV_LOG_ERROR, "Picture size %ux%u is invalid\n", w, h); + return AVERROR(EINVAL); + } - av_log(&imgutils, AV_LOG_ERROR, "Picture size %ux%u is invalid\n", w, h); - return AVERROR(EINVAL); + if (max_pixels < INT64_MAX) { + if (w*(int64_t)h > max_pixels) { + av_log(&imgutils, AV_LOG_ERROR, + "Picture size %ux%u exceeds specified max pixel count %"PRId64", see the documentation if you wish to increase it\n", + w, h, max_pixels); + return AVERROR(EINVAL); + } + } + + return 0; +} + +int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx) +{ + return av_image_check_size2(w, h, INT64_MAX, AV_PIX_FMT_NONE, log_offset, log_ctx); } int av_image_check_sar(unsigned int w, unsigned int h, AVRational sar) diff --git a/libavutil/imgutils.h b/libavutil/imgutils.h index 23282a38fa..19f34deced 100644 --- a/libavutil/imgutils.h +++ b/libavutil/imgutils.h @@ -191,6 +191,20 @@ int av_image_copy_to_buffer(uint8_t *dst, int dst_size, */ int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx); +/** + * Check if the given dimension of an image is valid, meaning that all + * bytes of the image can be addressed with a signed int. + * + * @param w the width of the picture + * @param h the height of the picture + * @param max_pixels the maximum number of pixels the user wants to accept + * @param pix_fmt the pixel format, can be AV_PIX_FMT_NONE if unknown. + * @param log_offset the offset to sum to the log level for logging with log_ctx + * @param log_ctx the parent logging context, it may be NULL + * @return >= 0 if valid, a negative error code otherwise + */ +int av_image_check_size2(unsigned int w, unsigned int h, int64_t max_pixels, enum AVPixelFormat pix_fmt, int log_offset, void *log_ctx); + /** * Check if the given sample aspect ratio of an image is valid. * diff --git a/libavutil/integer.c b/libavutil/integer.c index 6d6855fa1b..ba4aa778c9 100644 --- a/libavutil/integer.c +++ b/libavutil/integer.c @@ -74,7 +74,7 @@ AVInteger av_mul_i(AVInteger a, AVInteger b){ if(a.v[i]) for(j=i; j>16) + out.v[j] + a.v[i]*b.v[j-i]; + carry= (carry>>16) + out.v[j] + a.v[i]*(unsigned)b.v[j-i]; out.v[j]= carry; } } diff --git a/libavutil/internal.h b/libavutil/internal.h index c4bcf37ab8..25e7703baa 100644 --- a/libavutil/internal.h +++ b/libavutil/internal.h @@ -30,6 +30,9 @@ # define NDEBUG #endif +// This can be enabled to allow detection of additional integer overflows with ubsan +//#define CHECKED + #include #include #include @@ -257,6 +260,16 @@ void avpriv_request_sample(void *avc, # define ff_dlog(ctx, ...) do { if (0) av_log(ctx, AV_LOG_DEBUG, __VA_ARGS__); } while (0) #endif +// For debuging we use signed operations so overflows can be detected (by ubsan) +// For production we use unsigned so there are no undefined operations +#ifdef CHECKED +#define SUINT int +#define SUINT32 int32_t +#else +#define SUINT unsigned +#define SUINT32 uint32_t +#endif + /** * Clip and convert a double value into the long long amin-amax range. * This function is needed because conversion of floating point to integers when @@ -313,6 +326,22 @@ static av_always_inline float ff_exp10f(float x) return exp2f(M_LOG2_10 * x); } +/** + * Compute x^y for floating point x, y. Note: this function is faster than the + * libm variant due to mainly 2 reasons: + * 1. It does not handle any edge cases. In particular, this is only guaranteed + * to work correctly for x > 0. + * 2. It is not as accurate as a standard nearly "correctly rounded" libm variant. + * @param x base + * @param y exponent + * @return x^y + */ +static av_always_inline float ff_fast_powf(float x, float y) +{ + return expf(logf(x) * y); +} + + /** * A wrapper for open() setting O_CLOEXEC. */ diff --git a/libavutil/mem.h b/libavutil/mem.h index d25b3229b7..376fd2e07c 100644 --- a/libavutil/mem.h +++ b/libavutil/mem.h @@ -183,7 +183,7 @@ av_alloc_size(2, 3) void *av_realloc_array(void *ptr, size_t nmemb, size_t size) * The situation is undefined according to POSIX and may crash with * some libc implementations. */ -av_alloc_size(2, 3) int av_reallocp_array(void *ptr, size_t nmemb, size_t size); +int av_reallocp_array(void *ptr, size_t nmemb, size_t size); /** * Free a memory block which has been allocated with av_malloc(z)() or diff --git a/libavutil/mips/float_dsp_mips.c b/libavutil/mips/float_dsp_mips.c index b3a812ceeb..0943d6f343 100644 --- a/libavutil/mips/float_dsp_mips.c +++ b/libavutil/mips/float_dsp_mips.c @@ -56,6 +56,7 @@ #include "libavutil/mips/asmdefs.h" #if HAVE_INLINE_ASM && HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 static void vector_fmul_mips(float *dst, const float *src0, const float *src1, int len) { @@ -339,14 +340,17 @@ static void vector_fmul_reverse_mips(float *dst, const float *src0, const float ); } } +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM && HAVE_MIPSFPU */ void ff_float_dsp_init_mips(AVFloatDSPContext *fdsp) { #if HAVE_INLINE_ASM && HAVE_MIPSFPU +#if !HAVE_MIPS32R6 && !HAVE_MIPS64R6 fdsp->vector_fmul = vector_fmul_mips; fdsp->vector_fmul_scalar = vector_fmul_scalar_mips; fdsp->vector_fmul_window = vector_fmul_window_mips; fdsp->butterflies_float = butterflies_float_mips; fdsp->vector_fmul_reverse = vector_fmul_reverse_mips; +#endif /* !HAVE_MIPS32R6 && !HAVE_MIPS64R6 */ #endif /* HAVE_INLINE_ASM && HAVE_MIPSFPU */ } diff --git a/libavutil/mips/generic_macros_msa.h b/libavutil/mips/generic_macros_msa.h index b1d18dd9d3..0a59619e7b 100644 --- a/libavutil/mips/generic_macros_msa.h +++ b/libavutil/mips/generic_macros_msa.h @@ -85,12 +85,12 @@ #else // !(__mips == 64) #define LD(psrc) \ ( { \ - uint8_t *psrc_m = (uint8_t *) (psrc); \ + uint8_t *psrc_ld_m = (uint8_t *) (psrc); \ uint32_t val0_m, val1_m; \ uint64_t val_m = 0; \ \ - val0_m = LW(psrc_m); \ - val1_m = LW(psrc_m + 4); \ + val0_m = LW(psrc_ld_m); \ + val1_m = LW(psrc_ld_m + 4); \ \ val_m = (uint64_t) (val1_m); \ val_m = (uint64_t) ((val_m << 32) & 0xFFFFFFFF00000000); \ @@ -172,12 +172,12 @@ #else // !(__mips == 64) #define LD(psrc) \ ( { \ - uint8_t *psrc_m1 = (uint8_t *) (psrc); \ + uint8_t *psrc_ld_m = (uint8_t *) (psrc); \ uint32_t val0_m, val1_m; \ uint64_t val_m = 0; \ \ - val0_m = LW(psrc_m1); \ - val1_m = LW(psrc_m1 + 4); \ + val0_m = LW(psrc_ld_m); \ + val1_m = LW(psrc_ld_m + 4); \ \ val_m = (uint64_t) (val1_m); \ val_m = (uint64_t) ((val_m << 32) & 0xFFFFFFFF00000000); \ diff --git a/libavutil/opt.h b/libavutil/opt.h index 753434d628..f6ab2839ed 100644 --- a/libavutil/opt.h +++ b/libavutil/opt.h @@ -58,7 +58,7 @@ * The following example illustrates an AVOptions-enabled struct: * @code * typedef struct test_struct { - * AVClass *class; + * const AVClass *class; * int int_opt; * char *str_opt; * uint8_t *bin_opt; @@ -96,7 +96,7 @@ * @code * test_struct *alloc_test_struct(void) * { - * test_struct *ret = av_malloc(sizeof(*ret)); + * test_struct *ret = av_mallocz(sizeof(*ret)); * ret->class = &test_class; * av_opt_set_defaults(ret); * return ret; diff --git a/libavutil/pixdesc.c b/libavutil/pixdesc.c index 58833cfb8e..dd7de7ee25 100644 --- a/libavutil/pixdesc.c +++ b/libavutil/pixdesc.c @@ -2275,6 +2275,7 @@ enum AVPixelFormat av_pix_fmt_swap_endianness(enum AVPixelFormat pix_fmt) #define FF_COLOR_GRAY 1 /**< gray color space */ #define FF_COLOR_YUV 2 /**< YUV color space. 16 <= Y <= 235, 16 <= U, V <= 240 */ #define FF_COLOR_YUV_JPEG 3 /**< YUV color space. 0 <= Y <= 255, 0 <= U, V <= 255 */ +#define FF_COLOR_XYZ 4 #define pixdesc_has_alpha(pixdesc) \ ((pixdesc)->nb_components == 2 || (pixdesc)->nb_components == 4 || (pixdesc)->flags & AV_PIX_FMT_FLAG_PAL) @@ -2290,6 +2291,9 @@ static int get_color_type(const AVPixFmtDescriptor *desc) { if(desc->name && !strncmp(desc->name, "yuvj", 4)) return FF_COLOR_YUV_JPEG; + if(desc->name && !strncmp(desc->name, "xyz", 3)) + return FF_COLOR_XYZ; + if(desc->flags & AV_PIX_FMT_FLAG_RGB) return FF_COLOR_RGB; diff --git a/libavutil/pixfmt.h b/libavutil/pixfmt.h index c01c0575f7..fd7f6153c2 100644 --- a/libavutil/pixfmt.h +++ b/libavutil/pixfmt.h @@ -43,6 +43,10 @@ * This is stored as BGRA on little-endian CPU architectures and ARGB on * big-endian CPUs. * + * @note + * If the resolution is not a multiple of the chroma subsampling factor + * then the chroma plane resolution must be rounded up. + * * @par * When the pixel format is palettized RGB32 (AV_PIX_FMT_PAL8), the palettized * image data is stored in AVFrame.data[0]. The palette is transported in diff --git a/libavutil/random_seed.c b/libavutil/random_seed.c index 205a636f92..69bf43466c 100644 --- a/libavutil/random_seed.c +++ b/libavutil/random_seed.c @@ -67,6 +67,7 @@ static uint32_t get_generic_seed(void) uint8_t tmp[120]; struct AVSHA *sha = (void*)tmp; clock_t last_t = 0; + clock_t last_td = 0; static uint64_t i = 0; static uint32_t buffer[512] = { 0 }; unsigned char digest[20]; @@ -86,19 +87,25 @@ static uint32_t get_generic_seed(void) for (;;) { clock_t t = clock(); - - if (last_t == t) { - buffer[i & 511]++; + if (last_t + 2*last_td + (CLOCKS_PER_SEC > 1000) >= t) { + last_td = t - last_t; + buffer[i & 511] = 1664525*buffer[i & 511] + 1013904223 + (last_td % 3294638521U); } else { - buffer[++i & 511] += (t - last_t) % 3294638521U; + last_td = t - last_t; + buffer[++i & 511] += last_td % 3294638521U; if (last_i && i - last_i > 4 || i - last_i > 64 || TEST && i - last_i > 8) break; } last_t = t; } - if(TEST) + if(TEST) { buffer[0] = buffer[1] = 0; + } else { +#ifdef AV_READ_TIME + buffer[111] += AV_READ_TIME(); +#endif + } av_sha_init(sha, 160); av_sha_update(sha, (const uint8_t *)buffer, sizeof(buffer)); diff --git a/libavutil/softfloat.h b/libavutil/softfloat.h index 4b895f014b..64696450e2 100644 --- a/libavutil/softfloat.h +++ b/libavutil/softfloat.h @@ -27,7 +27,7 @@ #include "avassert.h" #include "softfloat_tables.h" -#define MIN_EXP -126 +#define MIN_EXP -149 #define MAX_EXP 126 #define ONE_BITS 29 @@ -43,6 +43,7 @@ static const SoftFloat FLOAT_EPSILON = { 0x29F16B12, -16}; static const SoftFloat FLOAT_1584893192 = { 0x32B771ED, 1}; static const SoftFloat FLOAT_100000 = { 0x30D40000, 17}; static const SoftFloat FLOAT_0999999 = { 0x3FFFFBCE, 0}; +static const SoftFloat FLOAT_MIN = { 0x20000000, MIN_EXP}; static inline av_const double av_sf2double(SoftFloat v) { v.exp -= ONE_BITS +1; @@ -110,8 +111,15 @@ static inline av_const SoftFloat av_mul_sf(SoftFloat a, SoftFloat b){ * @return Will not be more denormalized than a. */ static inline av_const SoftFloat av_div_sf(SoftFloat a, SoftFloat b){ + int64_t temp = (int64_t)a.mant * (1<<(ONE_BITS+1)); + temp /= b.mant; a.exp -= b.exp; - a.mant = ((int64_t)a.mant<<(ONE_BITS+1)) / b.mant; + a.mant = temp; + while (a.mant != temp) { + temp /= 2; + a.exp--; + a.mant = temp; + } a = av_normalize1_sf(a); if (!a.mant || a.exp < MIN_EXP) return FLOAT_0; @@ -150,12 +158,14 @@ static inline av_const SoftFloat av_sub_sf(SoftFloat a, SoftFloat b){ //FIXME log, exp, pow /** - * Converts a mantisse and exponent to a SoftFloat - * @returns a SoftFloat with value v * 2^frac_bits + * Converts a mantisse and exponent to a SoftFloat. + * This converts a fixed point value v with frac_bits fractional bits to a + * SoftFloat. + * @returns a SoftFloat with value v * 2^-frac_bits */ static inline av_const SoftFloat av_int2sf(int v, int frac_bits){ int exp_offset = 0; - if(v == INT_MIN){ + if(v <= INT_MIN + 1){ exp_offset = 1; v>>=1; } @@ -214,12 +224,12 @@ static av_unused void av_sincos_sf(int a, int *s, int *c) int st, ct; idx = a >> 26; - sign = (idx << 27) >> 31; + sign = (int32_t)((unsigned)idx << 27) >> 31; cv = av_costbl_1_sf[idx & 0xf]; cv = (cv ^ sign) - sign; idx -= 8; - sign = (idx << 27) >> 31; + sign = (int32_t)((unsigned)idx << 27) >> 31; sv = av_costbl_1_sf[idx & 0xf]; sv = (sv ^ sign) - sign; diff --git a/libavutil/x86/cpu.h b/libavutil/x86/cpu.h index dc102c6015..f171037f1c 100644 --- a/libavutil/x86/cpu.h +++ b/libavutil/x86/cpu.h @@ -68,8 +68,12 @@ #define EXTERNAL_AVX_SLOW(flags) CPUEXT_SUFFIX_SLOW(flags, _EXTERNAL, AVX) #define EXTERNAL_XOP(flags) CPUEXT_SUFFIX(flags, _EXTERNAL, XOP) #define EXTERNAL_FMA3(flags) CPUEXT_SUFFIX(flags, _EXTERNAL, FMA3) +#define EXTERNAL_FMA3_FAST(flags) CPUEXT_SUFFIX_FAST2(flags, _EXTERNAL, FMA3, AVX) +#define EXTERNAL_FMA3_SLOW(flags) CPUEXT_SUFFIX_SLOW2(flags, _EXTERNAL, FMA3, AVX) #define EXTERNAL_FMA4(flags) CPUEXT_SUFFIX(flags, _EXTERNAL, FMA4) #define EXTERNAL_AVX2(flags) CPUEXT_SUFFIX(flags, _EXTERNAL, AVX2) +#define EXTERNAL_AVX2_FAST(flags) CPUEXT_SUFFIX_FAST2(flags, _EXTERNAL, AVX2, AVX) +#define EXTERNAL_AVX2_SLOW(flags) CPUEXT_SUFFIX_SLOW2(flags, _EXTERNAL, AVX2, AVX) #define EXTERNAL_AESNI(flags) CPUEXT_SUFFIX(flags, _EXTERNAL, AESNI) #define INLINE_AMD3DNOW(flags) CPUEXT_SUFFIX(flags, _INLINE, AMD3DNOW) diff --git a/libavutil/x86/float_dsp_init.c b/libavutil/x86/float_dsp_init.c index f211f2396b..c836a78e1b 100644 --- a/libavutil/x86/float_dsp_init.c +++ b/libavutil/x86/float_dsp_init.c @@ -92,7 +92,7 @@ av_cold void ff_float_dsp_init_x86(AVFloatDSPContext *fdsp) fdsp->vector_fmul_add = ff_vector_fmul_add_avx; fdsp->vector_fmul_reverse = ff_vector_fmul_reverse_avx; } - if (EXTERNAL_FMA3(cpu_flags) && !(cpu_flags & AV_CPU_FLAG_AVXSLOW)) { + if (EXTERNAL_FMA3_FAST(cpu_flags)) { fdsp->vector_fmac_scalar = ff_vector_fmac_scalar_fma3; fdsp->vector_fmul_add = ff_vector_fmul_add_fma3; } diff --git a/libavutil/x86/lls_init.c b/libavutil/x86/lls_init.c index 9f0d862b0e..1c5dca42dc 100644 --- a/libavutil/x86/lls_init.c +++ b/libavutil/x86/lls_init.c @@ -39,7 +39,7 @@ av_cold void ff_init_lls_x86(LLSModel *m) if (EXTERNAL_AVX_FAST(cpu_flags)) { m->update_lls = ff_update_lls_avx; } - if (EXTERNAL_FMA3(cpu_flags) && !(cpu_flags & AV_CPU_FLAG_AVXSLOW)) { + if (EXTERNAL_FMA3_FAST(cpu_flags)) { m->update_lls = ff_update_lls_fma3; } } diff --git a/libpostproc/postprocess.c b/libpostproc/postprocess.c index 3b86f93980..1dc719cf93 100644 --- a/libpostproc/postprocess.c +++ b/libpostproc/postprocess.c @@ -973,7 +973,7 @@ void pp_postprocess(const uint8_t * src[3], const int srcStride[3], int i; const int count= FFMAX(mbHeight * absQPStride, mbWidth); for(i=0; i<(count>>2); i++){ - ((uint32_t*)c->stdQPTable)[i] = (((const uint32_t*)QP_store)[i]>>1) & 0x7F7F7F7F; + AV_WN32(c->stdQPTable + (i<<2), AV_RN32(QP_store + (i<<2)) >> 1 & 0x7F7F7F7F); } for(i<<=2; istdQPTable[i] = QP_store[i]>>1; diff --git a/libswresample/arm/audio_convert_neon.S b/libswresample/arm/audio_convert_neon.S index 1f88316dde..085d50aafa 100644 --- a/libswresample/arm/audio_convert_neon.S +++ b/libswresample/arm/audio_convert_neon.S @@ -22,6 +22,7 @@ #include "libavutil/arm/asm.S" function swri_oldapi_conv_flt_to_s16_neon, export=1 +.L_swri_oldapi_conv_flt_to_s16_neon: subs r2, r2, #8 vld1.32 {q0}, [r1,:128]! vcvt.s32.f32 q8, q0, #31 @@ -66,6 +67,7 @@ function swri_oldapi_conv_flt_to_s16_neon, export=1 endfunc function swri_oldapi_conv_fltp_to_s16_2ch_neon, export=1 +.L_swri_oldapi_conv_fltp_to_s16_2ch_neon: ldm r1, {r1, r3} subs r2, r2, #8 vld1.32 {q0}, [r1,:128]! @@ -133,8 +135,8 @@ function swri_oldapi_conv_fltp_to_s16_nch_neon, export=1 cmp r3, #2 itt lt ldrlt r1, [r1] - blt X(swri_oldapi_conv_flt_to_s16_neon) - beq X(swri_oldapi_conv_fltp_to_s16_2ch_neon) + blt .L_swri_oldapi_conv_flt_to_s16_neon + beq .L_swri_oldapi_conv_fltp_to_s16_2ch_neon push {r4-r8, lr} cmp r3, #4 diff --git a/libswresample/rematrix.c b/libswresample/rematrix.c index 932088ffb7..7ab74edd05 100644 --- a/libswresample/rematrix.c +++ b/libswresample/rematrix.c @@ -32,6 +32,9 @@ #define TEMPLATE_REMATRIX_S16 #include "rematrix_template.c" +#define TEMPLATE_CLIP +#include "rematrix_template.c" +#undef TEMPLATE_CLIP #undef TEMPLATE_REMATRIX_S16 #define TEMPLATE_REMATRIX_S32 @@ -65,8 +68,10 @@ int swr_set_matrix(struct SwrContext *s, const double *matrix, int stride) if (!s || s->in_convert) // s needs to be allocated but not initialized return AVERROR(EINVAL); memset(s->matrix, 0, sizeof(s->matrix)); - nb_in = av_get_channel_layout_nb_channels(s->user_in_ch_layout); - nb_out = av_get_channel_layout_nb_channels(s->user_out_ch_layout); + nb_in = (s->user_in_ch_count > 0) ? s->user_in_ch_count : + av_get_channel_layout_nb_channels(s->user_in_ch_layout); + nb_out = (s->user_out_ch_count > 0) ? s->user_out_ch_count : + av_get_channel_layout_nb_channels(s->user_out_ch_layout); for (out = 0; out < nb_out; out++) { for (in = 0; in < nb_in; in++) s->matrix[out][in] = matrix[in]; @@ -367,17 +372,33 @@ av_cold int swri_rematrix_init(SwrContext *s){ return r; } if (s->midbuf.fmt == AV_SAMPLE_FMT_S16P){ + int maxsum = 0; s->native_matrix = av_calloc(nb_in * nb_out, sizeof(int)); s->native_one = av_mallocz(sizeof(int)); if (!s->native_matrix || !s->native_one) return AVERROR(ENOMEM); - for (i = 0; i < nb_out; i++) - for (j = 0; j < nb_in; j++) - ((int*)s->native_matrix)[i * nb_in + j] = lrintf(s->matrix[i][j] * 32768); + for (i = 0; i < nb_out; i++) { + double rem = 0; + int sum = 0; + + for (j = 0; j < nb_in; j++) { + double target = s->matrix[i][j] * 32768 + rem; + ((int*)s->native_matrix)[i * nb_in + j] = lrintf(target); + rem += target - ((int*)s->native_matrix)[i * nb_in + j]; + sum += FFABS(((int*)s->native_matrix)[i * nb_in + j]); + } + maxsum = FFMAX(maxsum, sum); + } *((int*)s->native_one) = 32768; - s->mix_1_1_f = (mix_1_1_func_type*)copy_s16; - s->mix_2_1_f = (mix_2_1_func_type*)sum2_s16; - s->mix_any_f = (mix_any_func_type*)get_mix_any_func_s16(s); + if (maxsum <= 32768) { + s->mix_1_1_f = (mix_1_1_func_type*)copy_s16; + s->mix_2_1_f = (mix_2_1_func_type*)sum2_s16; + s->mix_any_f = (mix_any_func_type*)get_mix_any_func_s16(s); + } else { + s->mix_1_1_f = (mix_1_1_func_type*)copy_clip_s16; + s->mix_2_1_f = (mix_2_1_func_type*)sum2_clip_s16; + s->mix_any_f = (mix_any_func_type*)get_mix_any_func_clip_s16(s); + } }else if(s->midbuf.fmt == AV_SAMPLE_FMT_FLTP){ s->native_matrix = av_calloc(nb_in * nb_out, sizeof(float)); s->native_one = av_mallocz(sizeof(float)); diff --git a/libswresample/rematrix_template.c b/libswresample/rematrix_template.c index 95a3b9a8c0..add65e3155 100644 --- a/libswresample/rematrix_template.c +++ b/libswresample/rematrix_template.c @@ -31,11 +31,16 @@ # define INTER double # define RENAME(x) x ## _double #elif defined(TEMPLATE_REMATRIX_S16) -# define R(x) (((x) + 16384)>>15) # define SAMPLE int16_t # define COEFF int # define INTER int +# ifdef TEMPLATE_CLIP +# define R(x) av_clip_int16(((x) + 16384)>>15) +# define RENAME(x) x ## _clip_s16 +# else +# define R(x) (((x) + 16384)>>15) # define RENAME(x) x ## _s16 +# endif #elif defined(TEMPLATE_REMATRIX_S32) # define R(x) (((x) + 16384)>>15) # define SAMPLE int32_t diff --git a/libswresample/resample.c b/libswresample/resample.c index 7888e570a3..a19af17516 100644 --- a/libswresample/resample.c +++ b/libswresample/resample.c @@ -203,7 +203,7 @@ static int build_filter(ResampleContext *c, void *filter, double factor, int tap case AV_SAMPLE_FMT_S16P: for(i=0;ifilter_bank); + av_freep(cc); +} + static ResampleContext *resample_init(ResampleContext *c, int out_rate, int in_rate, int filter_size, int phase_shift, int linear, double cutoff0, enum AVSampleFormat format, enum SwrFilterType filter_type, double kaiser_beta, double precision, int cheby) @@ -306,6 +314,7 @@ static ResampleContext *resample_init(ResampleContext *c, int out_rate, int in_r if (!c || c->phase_shift != phase_shift || c->linear!=linear || c->factor != factor || c->filter_length != FFMAX((int)ceil(filter_size/factor), 1) || c->format != format || c->filter_type != filter_type || c->kaiser_beta != kaiser_beta) { + resample_free(&c); c = av_mallocz(sizeof(*c)); if (!c) return NULL; @@ -375,13 +384,6 @@ error: return NULL; } -static void resample_free(ResampleContext **c){ - if(!*c) - return; - av_freep(&(*c)->filter_bank); - av_freep(c); -} - static int set_compensation(ResampleContext *c, int sample_delta, int compensation_distance){ c->compensation_distance= compensation_distance; if (compensation_distance) diff --git a/libswresample/swresample.c b/libswresample/swresample.c index 8e238998e9..54180e220c 100644 --- a/libswresample/swresample.c +++ b/libswresample/swresample.c @@ -316,7 +316,7 @@ av_cold int swr_init(struct SwrContext *s){ av_assert0(s->used_ch_count); av_assert0(s->out.ch_count); - s->resample_first= RSC*s->out.ch_count/s->in.ch_count - RSC < s->out_sample_rate/(float)s-> in_sample_rate - 1.0; + s->resample_first= RSC*s->out.ch_count/s->used_ch_count - RSC < s->out_sample_rate/(float)s-> in_sample_rate - 1.0; s->in_buffer= s->in; s->silence = s->in; @@ -667,7 +667,7 @@ static int swr_convert_internal(struct SwrContext *s, AudioData *out, int out_co s->mix_2_1_simd(conv_src->ch[ch], preout->ch[ch], s->dither.noise.ch[ch] + s->dither.noise.bps * s->dither.noise_pos, s->native_simd_one, 0, 0, len1); if(out_count != len1) for(ch=0; chch_count; ch++) - s->mix_2_1_f(conv_src->ch[ch] + off, preout->ch[ch] + off, s->dither.noise.ch[ch] + s->dither.noise.bps * s->dither.noise_pos + off + len1, s->native_one, 0, 0, out_count - len1); + s->mix_2_1_f(conv_src->ch[ch] + off, preout->ch[ch] + off, s->dither.noise.ch[ch] + s->dither.noise.bps * s->dither.noise_pos + off, s->native_one, 0, 0, out_count - len1); } else { for(ch=0; chch_count; ch++) s->mix_2_1_f(conv_src->ch[ch], preout->ch[ch], s->dither.noise.ch[ch] + s->dither.noise.bps * s->dither.noise_pos, s->native_one, 0, 0, out_count); diff --git a/libswresample/x86/audio_convert_init.c b/libswresample/x86/audio_convert_init.c index 5e5e91d142..bb89cf604b 100644 --- a/libswresample/x86/audio_convert_init.c +++ b/libswresample/x86/audio_convert_init.c @@ -174,7 +174,7 @@ MULTI_CAPS_FUNC(SSE2, sse2) ac->simd_f = ff_pack_8ch_float_to_int32_a_avx; } } - if(EXTERNAL_AVX2(mm_flags)) { + if(EXTERNAL_AVX2_FAST(mm_flags)) { if( out_fmt == AV_SAMPLE_FMT_S32 && in_fmt == AV_SAMPLE_FMT_FLT || out_fmt == AV_SAMPLE_FMT_S32P && in_fmt == AV_SAMPLE_FMT_FLTP) ac->simd_f = ff_float_to_int32_a_avx2; } diff --git a/libswresample/x86/resample_init.c b/libswresample/x86/resample_init.c index bc444cfb8b..9d7d5cf89e 100644 --- a/libswresample/x86/resample_init.c +++ b/libswresample/x86/resample_init.c @@ -71,7 +71,7 @@ av_cold void swri_resample_dsp_x86_init(ResampleContext *c) c->dsp.resample = c->linear ? ff_resample_linear_float_avx : ff_resample_common_float_avx; } - if (EXTERNAL_FMA3(mm_flags) && !(mm_flags & AV_CPU_FLAG_AVXSLOW)) { + if (EXTERNAL_FMA3_FAST(mm_flags)) { c->dsp.resample = c->linear ? ff_resample_linear_float_fma3 : ff_resample_common_float_fma3; } diff --git a/libswscale/input.c b/libswscale/input.c index 1df84a9865..ac76aee7f7 100644 --- a/libswscale/input.c +++ b/libswscale/input.c @@ -885,6 +885,19 @@ static av_always_inline void planar_rgb16_to_y(uint8_t *_dst, const uint8_t *_sr } } +static av_always_inline void planar_rgb16_to_a(uint8_t *_dst, const uint8_t *_src[4], + int width, int bpc, int is_be, int32_t *rgb2yuv) +{ + int i; + const uint16_t **src = (const uint16_t **)_src; + uint16_t *dst = (uint16_t *)_dst; + int shift = bpc < 16 ? bpc : 14; + + for (i = 0; i < width; i++) { + dst[i] = rdpx(src[3] + i) << (14 - shift); + } +} + static av_always_inline void planar_rgb16_to_uv(uint8_t *_dstU, uint8_t *_dstV, const uint8_t *_src[4], int width, int bpc, int is_be, int32_t *rgb2yuv) @@ -913,6 +926,11 @@ static void planar_rgb##nbits##endian_name##_to_y(uint8_t *dst, const uint8_t *s { \ planar_rgb16_to_y(dst, src, w, nbits, endian, rgb2yuv); \ } \ +static void planar_rgb##nbits##endian_name##_to_a(uint8_t *dst, const uint8_t *src[4], \ + int w, int32_t *rgb2yuv) \ +{ \ + planar_rgb16_to_a(dst, src, w, nbits, endian, rgb2yuv); \ +} \ static void planar_rgb##nbits##endian_name##_to_uv(uint8_t *dstU, uint8_t *dstV, \ const uint8_t *src[4], int w, int32_t *rgb2yuv) \ { \ @@ -1248,6 +1266,7 @@ av_cold void ff_sws_init_input_funcs(SwsContext *c) c->readLumPlanar = planar_rgb14le_to_y; break; case AV_PIX_FMT_GBRAP16LE: + c->readAlpPlanar = planar_rgb16le_to_a; case AV_PIX_FMT_GBRP16LE: c->readLumPlanar = planar_rgb16le_to_y; break; @@ -1264,6 +1283,7 @@ av_cold void ff_sws_init_input_funcs(SwsContext *c) c->readLumPlanar = planar_rgb14be_to_y; break; case AV_PIX_FMT_GBRAP16BE: + c->readAlpPlanar = planar_rgb16be_to_a; case AV_PIX_FMT_GBRP16BE: c->readLumPlanar = planar_rgb16be_to_y; break; diff --git a/libswscale/swscale-test.c b/libswscale/swscale-test.c index 4d8d08bd1a..b1a526dcac 100644 --- a/libswscale/swscale-test.c +++ b/libswscale/swscale-test.c @@ -307,10 +307,10 @@ static int fileTest(uint8_t *ref[4], int refStride[4], int w, int h, FILE *fp, struct Results r; enum AVPixelFormat srcFormat; char srcStr[12]; - int srcW, srcH; + int srcW = 0, srcH = 0; enum AVPixelFormat dstFormat; char dstStr[12]; - int dstW, dstH; + int dstW = 0, dstH = 0; int flags; int ret; diff --git a/libswscale/swscale_unscaled.c b/libswscale/swscale_unscaled.c index 74f3467428..b2d1401e6f 100644 --- a/libswscale/swscale_unscaled.c +++ b/libswscale/swscale_unscaled.c @@ -352,6 +352,7 @@ static int packed_16bpc_bswap(SwsContext *c, const uint8_t *src[], int min_stride = FFMIN(FFABS(srcstr), FFABS(dststr)); if(!dstPtr || !srcPtr) continue; + dstPtr += (srcSliceY >> c->chrDstVSubSample) * dststr; for (i = 0; i < (srcSliceH >> c->chrDstVSubSample); i++) { for (j = 0; j < min_stride; j++) { dstPtr[j] = av_bswap16(srcPtr[j]); @@ -557,6 +558,8 @@ static int Rgb16ToPlanarRgb16Wrapper(SwsContext *c, const uint8_t *src[], int bpc = dst_format->comp[0].depth; int alpha = src_format->flags & AV_PIX_FMT_FLAG_ALPHA; int swap = 0; + int i; + if ( HAVE_BIGENDIAN && !(src_format->flags & AV_PIX_FMT_FLAG_BE) || !HAVE_BIGENDIAN && src_format->flags & AV_PIX_FMT_FLAG_BE) swap++; @@ -570,6 +573,12 @@ static int Rgb16ToPlanarRgb16Wrapper(SwsContext *c, const uint8_t *src[], src_format->name, dst_format->name); return srcSliceH; } + + for(i=0; i<4; i++) { + dst2013[i] += stride2013[i] * srcSliceY / 2; + dst1023[i] += stride1023[i] * srcSliceY / 2; + } + switch (c->srcFormat) { case AV_PIX_FMT_RGB48LE: case AV_PIX_FMT_RGB48BE: diff --git a/libswscale/utils.c b/libswscale/utils.c index ef4241ac37..0beb7538cb 100644 --- a/libswscale/utils.c +++ b/libswscale/utils.c @@ -1354,6 +1354,7 @@ av_cold int sws_init_context(SwsContext *c, SwsFilter *srcFilter, srcFormat != AV_PIX_FMT_GBRP12BE && srcFormat != AV_PIX_FMT_GBRP12LE && srcFormat != AV_PIX_FMT_GBRP14BE && srcFormat != AV_PIX_FMT_GBRP14LE && srcFormat != AV_PIX_FMT_GBRP16BE && srcFormat != AV_PIX_FMT_GBRP16LE && + srcFormat != AV_PIX_FMT_GBRAP16BE && srcFormat != AV_PIX_FMT_GBRAP16LE && ((dstW >> c->chrDstHSubSample) <= (srcW >> 1) || (flags & SWS_FAST_BILINEAR))) c->chrSrcHSubSample = 1; diff --git a/libswscale/x86/output.asm b/libswscale/x86/output.asm index 9ea4af9535..133817cb71 100644 --- a/libswscale/x86/output.asm +++ b/libswscale/x86/output.asm @@ -54,6 +54,118 @@ SECTION .text ; int32_t if $output_size is 16. $filter is 12-bits. $filterSize is a multiple ; of 2. $offset is either 0 or 3. $dither holds 8 values. ;----------------------------------------------------------------------------- +%macro yuv2planeX_mainloop 2 +.pixelloop_%2: +%assign %%i 0 + ; the rep here is for the 8bit output mmx case, where dither covers + ; 8 pixels but we can only handle 2 pixels per register, and thus 4 + ; pixels per iteration. In order to not have to keep track of where + ; we are w.r.t. dithering, we unroll the mmx/8bit loop x2. +%if %1 == 8 +%assign %%repcnt 16/mmsize +%else +%assign %%repcnt 1 +%endif + +%rep %%repcnt + +%if %1 == 8 +%if ARCH_X86_32 + mova m2, [rsp+mmsize*(0+%%i)] + mova m1, [rsp+mmsize*(1+%%i)] +%else ; x86-64 + mova m2, m8 + mova m1, m_dith +%endif ; x86-32/64 +%else ; %1 == 9/10/16 + mova m1, [yuv2yuvX_%1_start] + mova m2, m1 +%endif ; %1 == 8/9/10/16 + movsx cntr_reg, fltsizem +.filterloop_%2_ %+ %%i: + ; input pixels + mov r6, [srcq+gprsize*cntr_reg-2*gprsize] +%if %1 == 16 + mova m3, [r6+r5*4] + mova m5, [r6+r5*4+mmsize] +%else ; %1 == 8/9/10 + mova m3, [r6+r5*2] +%endif ; %1 == 8/9/10/16 + mov r6, [srcq+gprsize*cntr_reg-gprsize] +%if %1 == 16 + mova m4, [r6+r5*4] + mova m6, [r6+r5*4+mmsize] +%else ; %1 == 8/9/10 + mova m4, [r6+r5*2] +%endif ; %1 == 8/9/10/16 + + ; coefficients + movd m0, [filterq+2*cntr_reg-4] ; coeff[0], coeff[1] +%if %1 == 16 + pshuflw m7, m0, 0 ; coeff[0] + pshuflw m0, m0, 0x55 ; coeff[1] + pmovsxwd m7, m7 ; word -> dword + pmovsxwd m0, m0 ; word -> dword + + pmulld m3, m7 + pmulld m5, m7 + pmulld m4, m0 + pmulld m6, m0 + + paddd m2, m3 + paddd m1, m5 + paddd m2, m4 + paddd m1, m6 +%else ; %1 == 10/9/8 + punpcklwd m5, m3, m4 + punpckhwd m3, m4 + SPLATD m0 + + pmaddwd m5, m0 + pmaddwd m3, m0 + + paddd m2, m5 + paddd m1, m3 +%endif ; %1 == 8/9/10/16 + + sub cntr_reg, 2 + jg .filterloop_%2_ %+ %%i + +%if %1 == 16 + psrad m2, 31 - %1 + psrad m1, 31 - %1 +%else ; %1 == 10/9/8 + psrad m2, 27 - %1 + psrad m1, 27 - %1 +%endif ; %1 == 8/9/10/16 + +%if %1 == 8 + packssdw m2, m1 + packuswb m2, m2 + movh [dstq+r5*1], m2 +%else ; %1 == 9/10/16 +%if %1 == 16 + packssdw m2, m1 + paddw m2, [minshort] +%else ; %1 == 9/10 +%if cpuflag(sse4) + packusdw m2, m1 +%else ; mmxext/sse2 + packssdw m2, m1 + pmaxsw m2, m6 +%endif ; mmxext/sse2/sse4/avx + pminsw m2, [yuv2yuvX_%1_upper] +%endif ; %1 == 9/10/16 + mov%2 [dstq+r5*2], m2 +%endif ; %1 == 8/9/10/16 + + add r5, mmsize/2 + sub wd, mmsize/2 + +%assign %%i %%i+2 +%endrep + jg .pixelloop_%2 +%endmacro %macro yuv2planeX_fn 3 @@ -123,116 +235,16 @@ cglobal yuv2planeX_%1, %3, 8, %2, filter, fltsize, src, dst, w, dither, offset xor r5, r5 -.pixelloop: -%assign %%i 0 - ; the rep here is for the 8bit output mmx case, where dither covers - ; 8 pixels but we can only handle 2 pixels per register, and thus 4 - ; pixels per iteration. In order to not have to keep track of where - ; we are w.r.t. dithering, we unroll the mmx/8bit loop x2. -%if %1 == 8 -%assign %%repcnt 16/mmsize -%else -%assign %%repcnt 1 -%endif - -%rep %%repcnt - -%if %1 == 8 -%if ARCH_X86_32 - mova m2, [rsp+mmsize*(0+%%i)] - mova m1, [rsp+mmsize*(1+%%i)] -%else ; x86-64 - mova m2, m8 - mova m1, m_dith -%endif ; x86-32/64 -%else ; %1 == 9/10/16 - mova m1, [yuv2yuvX_%1_start] - mova m2, m1 -%endif ; %1 == 8/9/10/16 - movsx cntr_reg, fltsizem -.filterloop_ %+ %%i: - ; input pixels - mov r6, [srcq+gprsize*cntr_reg-2*gprsize] -%if %1 == 16 - mova m3, [r6+r5*4] - mova m5, [r6+r5*4+mmsize] -%else ; %1 == 8/9/10 - mova m3, [r6+r5*2] -%endif ; %1 == 8/9/10/16 - mov r6, [srcq+gprsize*cntr_reg-gprsize] -%if %1 == 16 - mova m4, [r6+r5*4] - mova m6, [r6+r5*4+mmsize] -%else ; %1 == 8/9/10 - mova m4, [r6+r5*2] -%endif ; %1 == 8/9/10/16 - - ; coefficients - movd m0, [filterq+2*cntr_reg-4] ; coeff[0], coeff[1] -%if %1 == 16 - pshuflw m7, m0, 0 ; coeff[0] - pshuflw m0, m0, 0x55 ; coeff[1] - pmovsxwd m7, m7 ; word -> dword - pmovsxwd m0, m0 ; word -> dword - - pmulld m3, m7 - pmulld m5, m7 - pmulld m4, m0 - pmulld m6, m0 - - paddd m2, m3 - paddd m1, m5 - paddd m2, m4 - paddd m1, m6 -%else ; %1 == 10/9/8 - punpcklwd m5, m3, m4 - punpckhwd m3, m4 - SPLATD m0 - - pmaddwd m5, m0 - pmaddwd m3, m0 - - paddd m2, m5 - paddd m1, m3 -%endif ; %1 == 8/9/10/16 - - sub cntr_reg, 2 - jg .filterloop_ %+ %%i - -%if %1 == 16 - psrad m2, 31 - %1 - psrad m1, 31 - %1 -%else ; %1 == 10/9/8 - psrad m2, 27 - %1 - psrad m1, 27 - %1 -%endif ; %1 == 8/9/10/16 - -%if %1 == 8 - packssdw m2, m1 - packuswb m2, m2 - movh [dstq+r5*1], m2 -%else ; %1 == 9/10/16 -%if %1 == 16 - packssdw m2, m1 - paddw m2, [minshort] -%else ; %1 == 9/10 -%if cpuflag(sse4) - packusdw m2, m1 -%else ; mmxext/sse2 - packssdw m2, m1 - pmaxsw m2, m6 -%endif ; mmxext/sse2/sse4/avx - pminsw m2, [yuv2yuvX_%1_upper] -%endif ; %1 == 9/10/16 - mova [dstq+r5*2], m2 -%endif ; %1 == 8/9/10/16 - - add r5, mmsize/2 - sub wd, mmsize/2 - -%assign %%i %%i+2 -%endrep - jg .pixelloop +%if mmsize == 8 || %1 == 8 + yuv2planeX_mainloop %1, a +%else ; mmsize == 16 + test dstq, 15 + jnz .unaligned + yuv2planeX_mainloop %1, a + REP_RET +.unaligned: + yuv2planeX_mainloop %1, u +%endif ; mmsize == 8/16 %if %1 == 8 %if ARCH_X86_32 diff --git a/tests/api/api-codec-param-test.c b/tests/api/api-codec-param-test.c index fa51964bbd..377a5e9c79 100644 --- a/tests/api/api-codec-param-test.c +++ b/tests/api/api-codec-param-test.c @@ -50,7 +50,7 @@ static int try_decode_video_frame(AVCodecContext *codec_ctx, AVPacket *pkt, int goto end; } - if (!decode && codec_ctx->codec->caps_internal & FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM) { + if (!decode && avpriv_codec_get_cap_skip_frame_fill_param(codec_ctx->codec)) { codec_ctx->skip_frame = AVDISCARD_ALL; } diff --git a/tests/checkasm/checkasm.c b/tests/checkasm/checkasm.c index 1e73e34c76..797ecd5d19 100644 --- a/tests/checkasm/checkasm.c +++ b/tests/checkasm/checkasm.c @@ -92,7 +92,7 @@ static const struct { #if CONFIG_JPEG2000_DECODER { "jpeg2000dsp", checkasm_check_jpeg2000dsp }, #endif - #if CONFIG_PIXBLOCKDSP + #if CONFIG_PIXBLOCKDSP && !(ARCH_PPC64 && HAVE_BIGENDIAN) { "pixblockdsp", checkasm_check_pixblockdsp }, #endif #if CONFIG_V210_ENCODER diff --git a/tests/fate/aac.mak b/tests/fate/aac.mak index 8d1e30368b..324b05d4f5 100644 --- a/tests/fate/aac.mak +++ b/tests/fate/aac.mak @@ -175,7 +175,7 @@ fate-aac-pns-encode: REF = $(SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.w fate-aac-pns-encode: CMP_SHIFT = -4096 fate-aac-pns-encode: CMP_TARGET = 616 fate-aac-pns-encode: SIZE_TOLERANCE = 3560 -fate-aac-pns-encode: FUZZ = 72 +fate-aac-pns-encode: FUZZ = 74 FATE_AAC_ENCODE += fate-aac-tns-encode fate-aac-tns-encode: CMD = enc_dec_pcm adts wav s16le $(TARGET_SAMPLES)/audio-reference/luckynight_2ch_44kHz_s16.wav -c:a aac -aac_tns 1 -aac_is 0 -aac_pns 0 -aac_ms 0 -b:a 128k -cutoff 22050 -fflags +bitexact -flags +bitexact diff --git a/tests/fate/source-check.sh b/tests/fate/source-check.sh index 33affae24d..ac2878d9f7 100755 --- a/tests/fate/source-check.sh +++ b/tests/fate/source-check.sh @@ -2,7 +2,7 @@ cd "$1"/.. -git --version > /dev/null || { cat tests/ref/fate/source ; exit 0; } +git show > /dev/null 2> /dev/null || { cat tests/ref/fate/source ; exit 0; } echo Files without standard license headers: git grep -L -E "This file is part of FFmpeg|This file is part of libswresample|"\ diff --git a/tests/ref/fate/filter-pixfmts-fieldmatch b/tests/ref/fate/filter-pixfmts-fieldmatch index 44622d060c..99946c8d1d 100644 --- a/tests/ref/fate/filter-pixfmts-fieldmatch +++ b/tests/ref/fate/filter-pixfmts-fieldmatch @@ -1,5 +1,5 @@ yuv410p a6c9b4065e8253d8120772f69be0bf04 yuv411p b913e634ad37ce046240252bed8681fb -yuv420p d448d95326eadeeb12ea0cc348067958 +yuv420p a9286560141eb14595e427dbe5829b00 yuv422p 11ad22ce00c5e8a30d0472f29fb15434 yuv444p 9350a3f23cd7d95ec441a49f63f55953 diff --git a/tests/ref/fate/mkv b/tests/ref/fate/mkv index aea378a881..765798cbfe 100644 --- a/tests/ref/fate/mkv +++ b/tests/ref/fate/mkv @@ -25,9 +25,9 @@ 1, 264, 264, 21, 609, 0xc0dc255c 1, 285, 285, 21, 619, 0x9ac52dd1 0, 292, 292, 41, 16751, 0xf293ab46, F=0x0 -0, 292, 417, 41, 22029, 0x3696462b, F=0x0 1, 306, 306, 21, 574, 0xf6410d4d 1, 327, 327, 22, 565, 0xfd561191 +0, 334, 417, 41, 22029, 0x3696462b, F=0x0 1, 350, 350, 21, 713, 0x48425147 1, 371, 371, 21, 537, 0x09bbf515 0, 375, 375, 41, 5044, 0xa0344ae6, F=0x0 diff --git a/tests/ref/fate/vp5 b/tests/ref/fate/vp5 index 0e601ba811..f044567fd9 100644 --- a/tests/ref/fate/vp5 +++ b/tests/ref/fate/vp5 @@ -245,4 +245,4 @@ 0, 243, 243, 1, 233472, 0x6f530ac6 0, 244, 244, 1, 233472, 0x94f7466c 0, 245, 245, 1, 233472, 0xa8c1d365 -0, 246, 246, 1, 233472, 0xedcff050 +0, 246, 246, 1, 233472, 0xbf73f1b7 diff --git a/tools/ismindex.c b/tools/ismindex.c index dfef118653..363b7eead7 100644 --- a/tools/ismindex.c +++ b/tools/ismindex.c @@ -375,7 +375,7 @@ static int read_tfra(struct Tracks *tracks, int start_index, AVIOContext *f) track->duration - track->offsets[track->chunks - 1].time; } - // Now try and read the actual durations from the trun sample data. + // Now try to read the actual durations from the trun sample data. for (i = 0; i < track->chunks; i++) { int64_t duration = read_moof_duration(f, track->offsets[i].offset); if (duration > 0 && llabs(duration - track->offsets[i].duration) > 3) { diff --git a/tools/zmqsend.c b/tools/zmqsend.c index d47bf216b4..6148bd623c 100644 --- a/tools/zmqsend.c +++ b/tools/zmqsend.c @@ -53,7 +53,7 @@ int main(int argc, char **argv) { AVBPrint src; char c, *src_buf, *recv_buf; - int recv_buf_size, ret; + int recv_buf_size, ret = 0; void *zmq_ctx, *socket; const char *bind_address = "tcp://localhost:5555"; const char *infilename = NULL;