]> git.sesse.net Git - ffmpeg/commitdiff
Merge remote-tracking branch 'qatar/master'
authorMichael Niedermayer <michaelni@gmx.at>
Sat, 26 May 2012 20:37:37 +0000 (22:37 +0200)
committerMichael Niedermayer <michaelni@gmx.at>
Sat, 26 May 2012 20:37:37 +0000 (22:37 +0200)
* qatar/master:
  opt: Add av_opt_set_bin()
  avconv: Display the error returned by avformat_write_header
  rtpenc_chain: Return an error code instead of just a plain pointer
  rtpenc_chain: Free the URLContext on failure
  rtpenc: Expose the ssrc as an avoption
  avprobe: display the codec profile in show_stream()
  avprobe: fix function prototype
  cosmetics: Fix indentation
  avprobe: changelog entry
  avprobe: update documentation
  avprobe: provide JSON output
  avprobe: output proper INI format
  avprobe: improve formatting
  rtmp: fix url parsing
  fate: document TARGET_EXEC and its usage

Conflicts:
doc/APIchanges
doc/fate.texi
doc/ffprobe.texi
ffprobe.c
libavformat/version.h
libavutil/avutil.h

Merged-by: Michael Niedermayer <michaelni@gmx.at>
16 files changed:
1  2 
Changelog
doc/APIchanges
doc/fate.texi
doc/protocols.texi
ffmpeg.c
libavformat/movenchint.c
libavformat/rtmpproto.c
libavformat/rtpenc.c
libavformat/rtpenc_chain.c
libavformat/rtpenc_chain.h
libavformat/rtsp.c
libavformat/sapenc.c
libavformat/version.h
libavutil/avutil.h
libavutil/opt.c
libavutil/opt.h

diff --combined Changelog
index 18b5d49f6f436c93c8c9a6d22355cff5857281c5,822f062d83a0a36b62ec4087eb1dea043479a53c..0c01ec41393d5320520b06e59b95e4ef564ad062
+++ b/Changelog
@@@ -1,97 -1,49 +1,97 @@@
  Entries are sorted chronologically from oldest to youngest within each release,
  releases are sorted from youngest to oldest.
  
 -version <next>:
 -
 -- XWD encoder and decoder
 -- Support for fragmentation in the mov/mp4 muxer
 -- ISMV (Smooth Streaming) muxer
 +version next:
 +
 +version 0.11:
 +Fixes:CVE-2012-2772, CVE-2012-2774, CVE-2012-2775, CVE-2012-2776, CVE-2012-2777,
 +      CVE-2012-2779, CVE-2012-2782, CVE-2012-2783, CVE-2012-2784, CVE-2012-2785,
 +      CVE-2012-2786, CVE-2012-2787, CVE-2012-2788, CVE-2012-2789, CVE-2012-2790,
 +      CVE-2012-2791, CVE-2012-2792, CVE-2012-2793, CVE-2012-2794, CVE-2012-2795,
 +      CVE-2012-2796, CVE-2012-2797, CVE-2012-2798, CVE-2012-2799, CVE-2012-2800,
 +      CVE-2012-2801, CVE-2012-2802, CVE-2012-2803, CVE-2012-2804,
 +- v408 Quicktime and Microsoft AYUV Uncompressed 4:4:4:4 encoder and decoder
 +- setfield filter
  - CDXL demuxer and decoder
  - Apple ProRes encoder
 +- ffprobe -count_packets and -count_frames options
  - Sun Rasterfile Encoder
 -- remove libpostproc
  - ID3v2 attached pictures reading and writing
  - WMA Lossless decoder
 -- XBM encoder
 +- bluray protocol
 +- blackdetect filter
 +- libutvideo encoder wrapper (--enable-libutvideo)
 +- swapuv filter
 +- bbox filter
 +- XBM encoder and decoder
  - RealAudio Lossless decoder
  - ZeroCodec decoder
 -- drop support for avconv without libavfilter
 -- add libavresample audio conversion library
 +- tile video filter
 +- Metal Gear Solid: The Twin Snakes demuxer
 +- OpenEXR image decoder
 +- removelogo filter
 +- drop support for ffmpeg without libavfilter
 +- drawtext video filter: fontconfig support
 +- ffmpeg -benchmark_all option
 +- super2xsai filter ported from libmpcodecs
 +- add libavresample audio conversion library for compatibility
 +- MicroDVD decoder
 +- Avid Meridien (AVUI) encoder and decoder
 +- accept + prefix to -pix_fmt option to disable automatic conversions.
  - audio filters support in libavfilter and avconv
  - add fps filter
  - audio split filter
 +- vorbis parser
 +- png parser
  - audio mix filter
+ - avprobe output is now standard INI or JSON.
  
 -version 0.8:
 -
 +version 0.10:
 +- Fixes: CVE-2011-3929, CVE-2011-3934, CVE-2011-3935, CVE-2011-3936,
 +         CVE-2011-3937, CVE-2011-3940, CVE-2011-3941, CVE-2011-3944,
 +         CVE-2011-3945, CVE-2011-3946, CVE-2011-3947, CVE-2011-3949,
 +         CVE-2011-3950, CVE-2011-3951, CVE-2011-3952
 +- v410 Quicktime Uncompressed 4:4:4 10-bit encoder and decoder
 +- SBaGen (SBG) binaural beats script demuxer
 +- OpenMG Audio muxer
 +- Timecode extraction in DV and MOV
 +- thumbnail video filter
 +- XML output in ffprobe
 +- asplit audio filter
 +- tinterlace video filter
 +- astreamsync audio filter
 +- amerge audio filter
 +- ISMV (Smooth Streaming) muxer
  - GSM audio parser
  - SMJPEG muxer
 -
 -
 -version 0.8_beta2:
 -
 +- XWD encoder and decoder
  - Automatic thread count based on detection number of (available) CPU cores
 -- Deprecate libpostproc. If desired, the switch --enable-postproc will
 -  enable it but it may be removed in a later Libav release.
 +- y41p Brooktree Uncompressed 4:1:1 12-bit encoder and decoder
 +- ffprobe -show_error option
 +- Avid 1:1 10-bit RGB Packer codec
 +- v308 Quicktime Uncompressed 4:4:4 encoder and decoder
 +- yuv4 libquicktime packed 4:2:0 encoder and decoder
 +- ffprobe -show_frames option
 +- silencedetect audio filter
 +- ffprobe -show_program_version, -show_library_versions, -show_versions options
  - rv34: frame-level multi-threading
  - optimized iMDCT transform on x86 using SSE for for mpegaudiodec
 +- Improved PGS subtitle decoder
 +- dumpgraph option to lavfi device
 +- r210 and r10k encoders
 +- ffwavesynth decoder
 +- aviocat tool
 +- ffeval tool
  
  
 -version 0.8_beta1:
 +version 0.9:
  
 +- openal input device added
 +- boxblur filter added
  - BWF muxer
  - Flash Screen Video 2 decoder
 -- ffplay/ffprobe/ffserver renamed to avplay/avprobe/avserver
 -- ffmpeg deprecated, added avconv, which is almost the same for now, except
 +- lavfi input device added
 +- added avconv, which is almost the same for now, except
  for a few incompatible changes in the options, which will hopefully make them
  easier to use. The changes are:
      * The options placement is now strictly enforced! While in theory the
      * -vframes/-aframes/-dframes options are now aliases to the new -frames option.
      * -vtag/-atag/-stag options are now aliases to the new -tag option.
  - XMV demuxer
 +- LOAS demuxer
 +- ashowinfo filter added
  - Windows Media Image decoder
 +- amovie source added
  - LATM muxer/demuxer
 -- showinfo filter
 -- split filter
 +- Speex encoder via libspeex
 +- JSON output in ffprobe
 +- WTV muxer
 +- Optional C++ Support (needed for libstagefright)
 +- H.264 Decoding on Android via Stagefright
 +- Prores decoder
 +- BIN/XBIN/ADF/IDF text file decoder
 +- aconvert audio filter added
 +- audio support to lavfi input device added
  - libcdio-paranoia input device for audio CD grabbing
 -- select filter
  - Apple ProRes decoder
  - CELT in Ogg demuxing
 +- G.723.1 demuxer and decoder
 +- libmodplug support (--enable-libmodplug)
  - VC-1 interlaced decoding
 -- lut, lutrgb, and lutyuv filters
 -- boxblur filter
 +- libutvideo wrapper (--enable-libutvideo)
 +- aevalsrc audio source added
  - Ut Video decoder
  - Speex encoding via libspeex
  - 4:2:2 H.264 decoding support
  - 4:2:2 and 4:4:4 H.264 encoding with libx264
  - Pulseaudio input device
 +- Prores encoder
 +- Video Decoder Acceleration (VDA) HWAccel module.
  - replacement Indeo 3 decoder
 +- new ffmpeg option: -map_channel
 +- volume audio filter added
 +- earwax audio filter added
 +- libv4l2 support (--enable-libv4l2)
  - TLS/SSL and HTTPS protocol support
  - AVOptions API rewritten and documented
  - most of CODEC_FLAG2_*, some CODEC_FLAG_* and many codec-specific fields in
  - Discworld II BMV decoding support
  - VBLE Decoder
  - OS X Video Decoder Acceleration (VDA) support
 +- compact and csv output in ffprobe
 +- pan audio filter
 +- IFF Amiga Continuous Bitmap (ACBM) decoder
 +- ass filter
  - CRI ADX audio format muxer and demuxer
  - Playstation Portable PMP format demuxer
 +- Microsoft Windows ICO demuxer
 +- life source
  - PCM format support in OMA demuxer
  - CLJR encoder
 +- new option: -report
  - Dxtory capture format decoder
 -- v410 QuickTime uncompressed 4:4:4 10-bit encoder and decoder
 -- OpenMG Audio muxer
 +- cellauto source
  - Simple segmenting muxer
  - Indeo 4 decoder
  - SMJPEG demuxer
  
  
 -version 0.7:
 -
 -- E-AC-3 audio encoder
 -- ac3enc: add channel coupling support
 -- floating-point sample format support for (E-)AC-3, DCA, AAC, Vorbis decoders
 -- H.264/MPEG frame-level multithreading
 -- av_metadata_* functions renamed to av_dict_* and moved to libavutil
 -- 4:4:4 H.264 decoding support
 -- 10-bit H.264 optimizations for x86
 -- bump libswscale for recently reported ABI break
 -
 -
 -version 0.7_beta2:
 -
 -- VP8 frame-level multithreading
 -- NEON optimizations for VP8
 -- removed a lot of deprecated API cruft
 -- FFT and IMDCT optimizations for AVX (Sandy Bridge) processors
 -- DPX image encoder
 -- SMPTE 302M AES3 audio decoder
 -- ffmpeg no longer quits after the 'q' key is pressed; use 'ctrl+c' instead
 -- 9bit and 10bit per sample support in the H.264 decoder
 -
 -
 -version 0.7_beta1:
 +version 0.8:
  
 +- many many things we forgot because we rather write code than changelogs
  - WebM support in Matroska de/muxer
  - low overhead Ogg muxing
  - MMS-TCP support
  - Demuxer for On2's IVF format
  - Pictor/PC Paint decoder
  - HE-AAC v2 decoder
 +- HE-AAC v2 encoding with libaacplus
  - libfaad2 wrapper removed
  - DTS-ES extension (XCh) decoding support
  - native VP8 decoder
  - RTP depacketization of QDM2
  - ANSI/ASCII art playback system
  - Lego Mindstorms RSO de/muxer
 +- libavcore added (and subsequently removed)
  - SubRip subtitle file muxer and demuxer
  - Chinese AVS encoding via libxavs
  - ffprobe -show_packets option added
  - replace the ocv_smooth filter with a more generic ocv filter
  - Windows Televison (WTV) demuxer
  - FFmpeg metadata format muxer and demuxer
 -- SubRip (srt) subtitle decoder
 +- SubRip (srt) subtitle encoder and decoder
  - floating-point AC-3 encoder added
  - Lagarith decoder
  - ffmpeg -copytb option added
  - sndio support for playback and record
  - Linux framebuffer input device added
  - Chronomaster DFA decoder
 -- Mobotix MxPEG decoder
 +- DPX image encoder
 +- MicroDVD subtitle file muxer and demuxer
 +- Playstation Portable PMP format demuxer
 +- fieldorder video filter added
  - AAC encoding via libvo-aacenc
  - AMR-WB encoding via libvo-amrwbenc
  - xWMA demuxer
 -- fieldorder video filter added
 +- Mobotix MxPEG decoder
 +- VP8 frame-multithreading
 +- NEON optimizations for VP8
 +- Lots of deprecated API cruft removed
 +- fft and imdct optimizations for AVX (Sandy Bridge) processors
 +- showinfo filter added
 +- SMPTE 302M AES3 audio decoder
 +- Apple Core Audio Format muxer
 +- 9bit and 10bit per sample support in the H.264 decoder
 +- 9bit and 10bit FFV1 encoding / decoding
 +- split filter added
 +- select filter added
 +- sdl output device added
 +- libmpcodecs video filter support (3 times as many filters than before)
 +- mpeg2 aspect ratio dection fixed
 +- libxvid aspect pickiness fixed
 +- Frame multithreaded decoding
 +- E-AC-3 audio encoder
 +- ac3enc: add channel coupling support
 +- floating-point sample format support to the ac3, eac3, dca, aac, and vorbis decoders.
 +- H264/MPEG frame-level multi-threading
 +- All av_metadata_* functions renamed to av_dict_* and moved to libavutil
 +- 4:4:4 H.264 decoding support
 +- 10-bit H.264 optimizations for x86
 +- lut, lutrgb, and lutyuv filters added
 +- buffersink libavfilter sink added
 +- Bump libswscale for recently reported ABI break
 +- New J2K encoder (via OpenJPEG)
 +
 +
 +version 0.7:
 +
 +- all the changes for 0.8, but keeping API/ABI compatibility with the 0.6 release
  
  
  version 0.6:
@@@ -584,7 -499,6 +584,7 @@@ version 0.5
  - Gopher client support
  - MXF D-10 muxer
  - generic metadata API
 +- flash ScreenVideo2 encoder
  
  
  version 0.4.9-pre1:
@@@ -787,7 -701,7 +787,7 @@@ version 0.4.5
  - MPEG-4 vol header fixes (Jonathan Marsden <snmjbm at pacbell.net>)
  - ARM optimizations (Lionel Ulmer <lionel.ulmer at free.fr>).
  - Windows porting of file converter
 -- added MJPEG raw format (input/ouput)
 +- added MJPEG raw format (input/output)
  - added JPEG image format support (input/output)
  
  
diff --combined doc/APIchanges
index b6b78b523780499f5b8e39d65031e3b094ab49d7,dca33aa0eb5670e451ceaeff308e6cae89014801..b14204af2900048a56c0ba20f4fb1bcf627d89ef
@@@ -7,30 -7,19 +7,33 @@@ libavdevice:   2011-04-1
  libavfilter:   2011-04-18
  libavformat:   2012-01-27
  libavresample: 2012-04-24
 +libpostproc:   2011-04-18
 +libswresample: 2011-09-19
  libswscale:    2011-06-20
  libavutil:     2011-04-18
  
  
  API changes, most recent first:
  
 -2012-05-xx - xxxxxxx - lavf 54.3.0
 -  Add AVFMT_TS_NONSTRICT format flag to indicate that a muxer supports
 -  non-increasing monotone timestamps.
 -
 +2012-05-24 - xxxxxxx - lavu 51.54.100
 +  Move AVPALETTE_SIZE and AVPALETTE_COUNT macros from
 +  libavcodec/avcodec.h to libavutil/pixfmt.h.
 +
 +2012-05-07 - xxxxxxx - lavf 54.5.100
 +  Add av_guess_sample_aspect_ratio() function.
 +
 +2012-04-20 - xxxxxxx - lavfi 2.70.100
 +  Add avfilter_unref_bufferp() to avfilter.h.
 +
 +2012-04-12 - xxxxxxx - lavfi 2.68.100
 +  Install libavfilter/asrc_abuffer.h public header.
 +
 +2012-03-26 - a67d9cf - lavfi 2.66.100
 +  Add avfilter_fill_frame_from_{audio_,}buffer_ref() functions.
 +
+ 2012-05-25 - e0e0793 - lavu 51.31.0 - opt.h
+   Add av_opt_set_bin()
  2012-05-15 - lavfi 2.17.0
    Add support for audio filters
    ac71230/a2cd9be - add video/audio buffer sink in a new installed
  
  2012-04-14 - lavfi 2.16.0 - avfiltergraph.h
    d7bcc71 Add avfilter_graph_parse2().
 -  91d3cbe Add avfilter_inout_alloc() and avfilter_inout_free().
  
  2012-04-08 - 4d693b0 - lavu 51.27.0 - samplefmt.h
    Add av_get_packed_sample_fmt() and av_get_planar_sample_fmt()
  
 -2012-04-05 - 5cc51a5 - lavu 51.26.0 - audioconvert.h
 -  Add av_get_default_channel_layout()
 +2012-03-21 - b75c67d - lavu 51.43.100
 +  Add bprint.h for bprint API.
 +
 +2012-02-21 - 9cbf17e - lavc 54.4.100
 +  Add av_get_pcm_codec() function.
 +
 +2012-02-16 - 560b224 - libswr 0.7.100
 +  Add swr_set_matrix() function.
 +
 +2012-02-09 - c28e7af - lavu 51.39.100
 +  Add a new installed header libavutil/timestamp.h with timestamp
 +  utilities.
 +
 +2012-02-06 - 70ffda3 - lavu 51.38.100
 +  Add av_parse_ratio() function to parseutils.h.
  
 -2012-03-06 - 4d851f8 - lavu 51.25.0 - cpu.h
 -  Add av_set_cpu_flags_mask().
 +2012-02-06 - 70ffda3 - lavu 51.38.100
 +  Add AV_LOG_MAX_OFFSET macro to log.h.
 +
 +2012-02-02 - 0eaa123 - lavu 51.37.100
 +  Add public timecode helpers.
 +
 +2012-01-24 - 0c3577b - lavfi 2.60.100
 +  Add avfilter_graph_dump.
  
  2012-03-05 - lavc 54.8.0
    6699d07 Add av_get_exact_bits_per_sample()
            muxers supporting it (av_write_frame makes sure it is called
            only for muxers with this flag).
  
 -------------------------------8<-------------------------------------
 -                   0.8 branch was cut here
 ------------------------------>8--------------------------------------
 -
  2012-01-15 - lavc 53.34.0
    New audio encoding API:
    b2c75b6 Add CODEC_CAP_VARIABLE_FRAME_SIZE capability for use by audio
  2012-01-12 - 3167dc9 - lavfi 2.15.0
    Add a new installed header -- libavfilter/version.h -- with version macros.
  
 -2011-01-03 - b73ec05 - lavu 51.21.0
 -  Add av_popcount64
 +2011-12-08 - a502939 - lavfi 2.52.0
 +  Add av_buffersink_poll_frame() to buffersink.h.
 +
 +2011-12-08 - 26c6fec - lavu 51.31.0
 +  Add av_log_format_line.
 +
 +2011-12-03 - 976b095 - lavu 51.30.0
 +  Add AVERROR_BUG.
 +
 +2011-11-24 - 573ffbb - lavu 51.28.1
 +  Add av_get_alt_sample_fmt() to samplefmt.h.
 +
 +2011-11-03 - 96949da - lavu 51.23.0
 +  Add av_strcasecmp() and av_strncasecmp() to avstring.h.
  
 -2011-12-25 - lavfi 2.14.0
 -  e1d9dbf Add a new installed header - buffersrc.h
 -  It contains a new function av_buffersrc_buffer() that allows passing
 -  frames to the 'buffer' filter, but unlike av_vsrc_buffer_add_frame()
 -  it allows for direct rendering.
 -  1c9e340 Add avfilter_copy_frame_props() for copying properties from
 -  AVFrame to AVFilterBufferRef.
 +2011-10-20 - b35e9e1 - lavu 51.22.0
 +  Add av_strtok() to avstring.h.
  
 -2011-12-25 - lavc 53.31.0
 -  Add the following new fields to AVFrame:
 -    b58dbb5 sample_aspect_ratio
 -    3a2ddf7 width, height
 -    8a4a5f6 format
 +2011-01-03 - b73ec05 - lavu 51.21.0
 +  Add av_popcount64
  
  2011-12-18 - 8400b12 - lavc 53.28.1
    Deprecate AVFrame.age. The field is unused.
    - 641c7af new functions - av_opt_child_next, av_opt_child_class_next
      and av_opt_find2()
  
 -2011-09-03 - fb4ca26 - lavc 53.10.0
 -                       lavf 53.6.0
 +2011-09-22 - a70e787 - lavu 51.17.0
 +  Add av_x_if_null().
 +
 +2011-09-18 - 645cebb - lavc 53.16.0
 +  Add showall flag2
 +
 +2011-09-16 - ea8de10 - lavfi 2.42.0
 +  Add avfilter_all_channel_layouts.
 +
 +2011-09-16 - 9899037 - lavfi 2.41.0
 +  Rename avfilter_all_* function names to avfilter_make_all_*.
 +
 +  In particular, apply the renames:
 +  avfilter_all_formats         -> avfilter_make_all_formats
 +  avfilter_all_channel_layouts -> avfilter_make_all_channel_layouts
 +  avfilter_all_packing_formats -> avfilter_make_all_packing_formats
 +
 +2011-09-12 - 4381bdd - lavfi 2.40.0
 +  Change AVFilterBufferRefAudioProps.sample_rate type from uint32_t to int.
 +
 +2011-09-12 - 2c03174 - lavfi 2.40.0
 +  Simplify signature for avfilter_get_audio_buffer(), make it
 +  consistent with avfilter_get_video_buffer().
 +
 +2011-09-06 - 4f7dfe1 - lavfi 2.39.0
 +  Rename libavfilter/vsink_buffer.h to libavfilter/buffersink.h.
 +
 +2011-09-06 - c4415f6 - lavfi 2.38.0
 +  Unify video and audio sink API.
 +
 +  In particular, add av_buffersink_get_buffer_ref(), deprecate
 +  av_vsink_buffer_get_video_buffer_ref() and change the value for the
 +  opaque field passed to the abuffersink init function.
 +
 +2011-09-04 - 61e2e29 - lavu 51.16.0
 +  Add av_asprintf().
 +
 +2011-08-22 - dacd827 - lavf 53.10.0
 +  Add av_find_program_from_stream().
 +
 +2011-08-20 - 69e2c1a - lavu 51.13.0
 +  Add av_get_media_type_string().
 +
 +2011-09-03 - fb4ca26 - lavc 53.13.0
 +                       lavf 53.11.0
                         lsws  2.1.0
    Add {avcodec,avformat,sws}_get_class().
  
 -2011-09-03 - c11fb82 - lavu 51.10.0
 +2011-08-03 - c11fb82 - lavu 51.15.0
    Add AV_OPT_SEARCH_FAKE_OBJ flag for av_opt_find() function.
  
 +2011-08-14 - 323b930 - lavu 51.12.0
 +  Add av_fifo_peek2(), deprecate av_fifo_peek().
 +
  2011-08-26 - lavu 51.9.0
 -  - f2011ed Add av_fifo_peek2(), deprecate av_fifo_peek().
    - add41de..abc78a5 Do not include intfloat_readwrite.h,
      mathematics.h, rational.h, pixfmt.h, or log.h from avutil.h.
  
 -2011-08-16 - 48f9e45 - lavf 53.4.0
 +2011-08-16 - 48f9e45 - lavf 53.8.0
    Add avformat_query_codec().
  
 -2011-08-16 - bca06e7 - lavc 53.8.0
 +2011-08-16 - bca06e7 - lavc 53.11.0
    Add avcodec_get_type().
  
 -2011-08-06 - 2f63440 - lavf 53.4.0
 +2011-08-06 - 2f63440 - lavf 53.7.0
    Add error_recognition to AVFormatContext.
  
 -2011-08-02 - 9d39cbf - lavc 53.7.1
 +2011-08-02 - 9d39cbf - lavc 53.9.1
    Add AV_PKT_FLAG_CORRUPT AVPacket flag.
  
 -2011-07-10 - a67c061 - lavf 53.3.0
 +2011-07-16 - b57df29 - lavfi 2.27.0
 +  Add audio packing negotiation fields and helper functions.
 +
 +  In particular, add AVFilterPacking enum, planar, in_packings and
 +  out_packings fields to AVFilterLink, and the functions:
 +  avfilter_set_common_packing_formats()
 +  avfilter_all_packing_formats()
 +
 +2011-07-10 - a67c061 - lavf 53.6.0
    Add avformat_find_stream_info(), deprecate av_find_stream_info().
    NOTE: this was backported to 0.7
  
 -2011-07-10 - 0b950fe - lavc 53.6.0
 +2011-07-10 - 0b950fe - lavc 53.8.0
    Add avcodec_open2(), deprecate avcodec_open().
    NOTE: this was backported to 0.7
  
    Add avcodec_alloc_context3. Deprecate avcodec_alloc_context() and
    avcodec_alloc_context2().
  
 +2011-07-01 - b442ca6 - lavf 53.5.0 - avformat.h
 +  Add function av_get_output_timestamp().
 +
 +2011-06-28 - 5129336 - lavu 51.11.0 - avutil.h
 +  Define the AV_PICTURE_TYPE_NONE value in AVPictureType enum.
 +
 +2011-06-19 - fd2c0a5 - lavfi 2.23.0 - avfilter.h
 +  Add layout negotiation fields and helper functions.
 +
 +  In particular, add in_chlayouts and out_chlayouts to AVFilterLink,
 +  and the functions:
 +  avfilter_set_common_sample_formats()
 +  avfilter_set_common_channel_layouts()
 +  avfilter_all_channel_layouts()
 +
 +2011-06-19 - 527ca39 - lavfi 2.22.0 - AVFilterFormats
 +  Change type of AVFilterFormats.formats from int * to int64_t *,
 +  and update formats handling API accordingly.
 +
 +  avfilter_make_format_list() still takes a int32_t array and converts
 +  it to int64_t. A new function, avfilter_make_format64_list(), that
 +  takes int64_t arrays has been added.
 +
 +2011-06-19 - 44f669e - lavfi 2.21.0 - vsink_buffer.h
 +  Add video sink buffer and vsink_buffer.h public header.
 +
 +2011-06-12 - 9fdf772 - lavfi 2.18.0 - avcodec.h
 +  Add avfilter_get_video_buffer_ref_from_frame() function in
 +  libavfilter/avcodec.h.
 +
 +2011-06-12 - c535494 - lavfi 2.17.0 - avfiltergraph.h
 +  Add avfilter_inout_alloc() and avfilter_inout_free() functions.
 +
 +2011-06-12 - 6119b23 - lavfi 2.16.0 - avfilter_graph_parse()
 +  Change avfilter_graph_parse() signature.
 +
  2011-06-23 - 67e9ae1 - lavu 51.8.0 - attributes.h
    Add av_printf_format().
  
 -------------------------------8<-------------------------------------
 -                   0.7 branch was cut here
 ------------------------------>8--------------------------------------
 -
  2011-06-16 - 05e84c9, 25de595 - lavf 53.2.0 - avformat.h
    Add avformat_open_input and avformat_write_header().
    Deprecate av_open_input_stream, av_open_input_file,
  2011-06-10 - cb7c11c - lavu 51.6.0 - opt.h
    Add av_opt_flag_is_set().
  
 -2011-06-08 - d9f80ea - lavu 51.5.0 - AVMetadata
 +2011-06-10 - c381960 - lavfi 2.15.0 - avfilter_get_audio_buffer_ref_from_arrays
 +  Add avfilter_get_audio_buffer_ref_from_arrays() to avfilter.h.
 +
 +2011-06-09 - d9f80ea - lavu 51.8.0 - AVMetadata
    Move AVMetadata from lavf to lavu and rename it to
    AVDictionary -- new installed header dict.h.
    All av_metadata_* functions renamed to av_dict_*.
  
 -2011-06-07 - a6703fa - lavu 51.4.0 - av_get_bytes_per_sample()
 +2011-06-07 - a6703fa - lavu 51.8.0 - av_get_bytes_per_sample()
    Add av_get_bytes_per_sample() in libavutil/samplefmt.h.
    Deprecate av_get_bits_per_sample_fmt().
  
 -2011-06-05 - b39b062 - lavu 51.3.0 - opt.h
 +2011-06-05 - b39b062 - lavu 51.8.0 - opt.h
    Add av_opt_free convenience function.
  
 -2011-05-28 - 0420bd7 - lavu 51.2.0 - pixdesc.h
 +2011-06-06 - 95a0242 - lavfi 2.14.0 - AVFilterBufferRefAudioProps
 +  Remove AVFilterBufferRefAudioProps.size, and use nb_samples in
 +  avfilter_get_audio_buffer() and avfilter_default_get_audio_buffer() in
 +  place of size.
 +
 +2011-06-06 - 0bc2cca - lavu 51.6.0 - av_samples_alloc()
 +  Switch nb_channels and nb_samples parameters order in
 +  av_samples_alloc().
 +
 +2011-06-06 - e1c7414 - lavu 51.5.0 - av_samples_*
 +  Change the data layout created by av_samples_fill_arrays() and
 +  av_samples_alloc().
 +
 +2011-06-06 - 27bcf55 - lavfi 2.13.0 - vsrc_buffer.h
 +  Make av_vsrc_buffer_add_video_buffer_ref() accepts an additional
 +  flags parameter in input.
 +
 +2011-06-03 - e977ca2 - lavfi 2.12.0 - avfilter_link_free()
 +  Add avfilter_link_free() function.
 +
 +2011-06-02 - 5ad38d9 - lavu 51.4.0 - av_force_cpu_flags()
 +  Add av_cpu_flags() in libavutil/cpu.h.
 +
 +2011-05-28 - e71f260 - lavu 51.3.0 - pixdesc.h
    Add av_get_pix_fmt_name() in libavutil/pixdesc.h, and deprecate
    avcodec_get_pix_fmt_name() in libavcodec/avcodec.h in its favor.
  
 -2011-05-25 - 30315a8 - lavf 53.1.0 - avformat.h
 +2011-05-25 - 30315a8 - lavf 53.3.0 - avformat.h
    Add fps_probe_size to AVFormatContext.
  
 -2011-05-18 - 64150ff - lavc 53.4.0 - AVCodecContext.request_sample_fmt
 +2011-05-22 - 5ecdfd0 - lavf 53.2.0 - avformat.h
 +  Introduce avformat_alloc_output_context2() and deprecate
 +  avformat_alloc_output_context().
 +
 +2011-05-22 - 83db719 - lavfi 2.10.0 - vsrc_buffer.h
 +  Make libavfilter/vsrc_buffer.h public.
 +
 +2011-05-19 - c000a9f - lavfi 2.8.0 - avcodec.h
 +  Add av_vsrc_buffer_add_frame() to libavfilter/avcodec.h.
 +
 +2011-05-14 - 9fdf772 - lavfi 2.6.0 - avcodec.h
 +  Add avfilter_get_video_buffer_ref_from_frame() to libavfilter/avcodec.h.
 +
 +2011-05-18 - 64150ff - lavc 53.7.0 - AVCodecContext.request_sample_fmt
    Add request_sample_fmt field to AVCodecContext.
  
 -2011-05-10 - 188dea1 - lavc 53.3.0 - avcodec.h
 +2011-05-10 - 188dea1 - lavc 53.6.0 - avcodec.h
    Deprecate AVLPCType and the following fields in
    AVCodecContext: lpc_coeff_precision, prediction_order_method,
    min_partition_order, max_partition_order, lpc_type, lpc_passes.
    Corresponding FLAC encoder options should be used instead.
  
 +2011-05-07 - 9fdf772 - lavfi 2.5.0 - avcodec.h
 +  Add libavfilter/avcodec.h header and avfilter_copy_frame_props()
 +  function.
 +
 +2011-05-07 - 18ded93 - lavc 53.5.0 - AVFrame
 +  Add format field to AVFrame.
 +
 +2011-05-07 - 22333a6 - lavc 53.4.0 - AVFrame
 +  Add width and height fields to AVFrame.
 +
 +2011-05-01 - 35fe66a - lavfi 2.4.0 - avfilter.h
 +  Rename AVFilterBufferRefVideoProps.pixel_aspect to
 +  sample_aspect_ratio.
 +
 +2011-05-01 - 77e9dee - lavc 53.3.0 - AVFrame
 +  Add a sample_aspect_ratio field to AVFrame.
 +
 +2011-05-01 - 1ba5727 - lavc 53.2.0 - AVFrame
 +  Add a pkt_pos field to AVFrame.
 +
 +2011-04-29 - 35ceaa7 - lavu 51.2.0 - mem.h
 +  Add av_dynarray_add function for adding
 +  an element to a dynamic array.
 +
  2011-04-26 - bebe72f - lavu 51.1.0 - avutil.h
    Add AVPictureType enum and av_get_picture_type_char(), deprecate
    FF_*_TYPE defines and av_get_pict_type_char() defined in
      333e894 deprecate url_open_protocol
      e230705 deprecate url_poll and URLPollEntry
  
 -2011-04-10 - lavu  50.40.0 - pixfmt.h
 -  Add PIX_FMT_BGR48LE and PIX_FMT_BGR48BE pixel formats
 -
  2011-04-08 - lavf 52.106.0 - avformat.h
    Minor avformat.h cleanup:
      a9bf9d8 deprecate av_guess_image2_codec
      d9d86e0 rename url_fprintf -> avio_printf
      59f65d9 deprecate url_setbufsize
      3e68b3b deprecate url_ferror
 -    66e5b1d deprecate url_feof
      e8bb2e2 deprecate url_fget_max_packet_size
      76aa876 rename url_fsize -> avio_size
      e519753 deprecate url_fgetc
  2011-03-25 - 34b47d7 - lavc 52.115.0 - AVCodecContext.audio_service_type
    Add audio_service_type field to AVCodecContext.
  
 +2011-03-17 - e309fdc - lavu 50.40.0 - pixfmt.h
 +  Add PIX_FMT_BGR48LE and PIX_FMT_BGR48BE pixel formats
 +
  2011-03-02 - 863c471 - lavf  52.103.0 - av_pkt_dump2, av_pkt_dump_log2
    Add new functions av_pkt_dump2, av_pkt_dump_log2 that uses the
    source stream timebase for outputting timestamps. Deprecate
  2011-02-02 - dfd2a00 - lavu 50.37.0 - log.h
    Make av_dlog public.
  
 +2011-01-31 - 7b3ea55 - lavfi 1.76.0 - vsrc_buffer
 +  Add sample_aspect_ratio fields to vsrc_buffer arguments
 +
 +2011-01-31 - 910b5b8 - lavfi 1.75.0 - AVFilterLink sample_aspect_ratio
 +  Add sample_aspect_ratio field to AVFilterLink.
 +
  2011-01-15 - a242ac3 - lavfi 1.74.0 - AVFilterBufferRefAudioProps
    Rename AVFilterBufferRefAudioProps.samples_nb to nb_samples.
  
diff --combined doc/fate.texi
index 07d8c53599d9d2c16f35851c5913245610d3f9ed,4b0250582b4fef151273cd048f0c2f002a15c7dc..cfb694ab659eb6f804b075f68c9e09d2ab23a0b3
  @center @titlefont{FATE Automated Testing Environment}
  @end titlepage
  
 +@node Top
  @top
  
  @contents
  
  @chapter Introduction
  
 -FATE provides a regression testsuite embedded within the Libav build system.
 -It can be run locally and optionally configured to send reports to a web
 -aggregator and viewer @url{http://fate.libav.org}.
 +  FATE is an extended regression suite on the client-side and a means
 +for results aggregation and presentation on the server-side.
  
 -It is advised to run FATE before submitting patches to the current codebase
 -and provide new tests when submitting patches to add additional features.
 +  The first part of this document explains how you can use FATE from
 +your FFmpeg source directory to test your ffmpeg binary. The second
 +part describes how you can run FATE to submit the results to FFmpeg's
 +FATE server.
  
 -@chapter Running FATE
 +  In any way you can have a look at the publicly viewable FATE results
 +by visiting this website:
  
 -@section Samples and References
 -In order to run, FATE needs a large amount of data (samples and references)
 -that is provided separately from the actual source distribution.
 +  @url{http://fate.ffmpeg.org/}
  
 -To inform the build system about the testsuite location, pass
 -@option{--samples=<path to the samples>} to @command{configure} or set the
 -@var{SAMPLES} Make variable or the @var{LIBAV_SAMPLES} environment variable
 -to a suitable value.
 +  This is especially recommended for all people contributing source
 +code to FFmpeg, as it can be seen if some test on some platform broke
 +with there recent contribution. This usually happens on the platforms
 +the developers could not test on.
 +
 +  The second part of this document describes how you can run FATE to
 +submit your results to FFmpeg's FATE server. If you want to submit your
 +results be sure to check that your combination of CPU, OS and compiler
 +is not already listed on the above mentioned website.
 +
 +  In the third part you can find a comprehensive listing of FATE makefile
 +targets and variables.
  
 -To use a custom wrapper to run the test, pass @option{--target-exec} to
 -@command{configure} or set the @var{TARGET_EXEC} Make variable.
  
 -The dataset is available through @command{rsync}, is possible to fetch
 -the current sample using the straight rsync command or through a specific
 -@ref{Makefile target}.
 +@chapter Using FATE from your FFmpeg source directory
 +
 +  If you want to run FATE on your machine you need to have the samples
 +in place. You can get the samples via the build target fate-rsync.
 +Use this command from the top-level source directory:
  
  @example
 -# rsync -aL rsync://fate-suite.libav.org/fate-suite/ fate-suite
 +make fate-rsync SAMPLES=fate-suite/
 +make fate       SAMPLES=fate-suite/
  @end example
  
 +  The above commands set the samples location by passing a makefile
 +variable via command line. It is also possible to set the samples
 +location at source configuration time by invoking configure with
 +`--samples=<path to the samples directory>'. Afterwards you can
 +invoke the makefile targets without setting the SAMPLES makefile
 +variable. This is illustrated by the following commands:
 +
  @example
 -# make fate-rsync SAMPLES=fate-suite
 +./configure --samples=fate-suite/
 +make fate-rsync
 +make fate
  @end example
  
 +  Yet another way to tell FATE about the location of the sample
 +directory is by making sure the environment variable FATE_SAMPLES
 +contains the path to your samples directory. This can be achieved
 +by e.g. putting that variable in your shell profile or by setting
 +it in your interactive session.
 +
 +@example
 +FATE_SAMPLES=fate-suite/ make fate
 +@end example
 +
 +@float NOTE
 +Do not put a '~' character in the samples path to indicate a home
 +directory. Because of shell nuances, this will cause FATE to fail.
 +@end float
 +
++To use a custom wrapper to run the test, pass @option{--target-exec} to
++@command{configure} or set the @var{TARGET_EXEC} Make variable.
++
 +
 +@chapter Submitting the results to the FFmpeg result aggregation server
 +
 +  To submit your results to the server you should run fate through the
 +shell script tests/fate.sh from the FFmpeg sources. This script needs
 +to be invoked with a configuration file as its first argument.
 +
 +@example
 +tests/fate.sh /path/to/fate_config
 +@end example
 +
 +  A configuration file template with comments describing the individual
 +configuration variables can be found at @file{tests/fate_config.sh.template}.
 +
 +@ifhtml
 +  The mentioned configuration template is also available here:
 +@verbatiminclude ../tests/fate_config.sh.template
 +@end ifhtml
 +
 +  Create a configuration that suits your needs, based on the configuration
 +template. The `slot' configuration variable can be any string that is not
 +yet used, but it is suggested that you name it adhering to the following
 +pattern <arch>-<os>-<compiler>-<compiler version>. The configuration file
 +itself will be sourced in a shell script, therefore all shell features may
 +be used. This enables you to setup the environment as you need it for your
 +build.
 +
 +  For your first test runs the `fate_recv' variable should be empty or
 +commented out. This will run everything as normal except that it will omit
 +the submission of the results to the server. The following files should be
 +present in $workdir as specified in the configuration file:
 +
 +@itemize
 +    @item configure.log
 +    @item compile.log
 +    @item test.log
 +    @item report
 +    @item version
 +@end itemize
 +
 +  When you have everything working properly you can create an SSH key and
 +send its public part to the FATE server administrator.
  
 -@chapter Manual Run
 -FATE regression test can be run through @command{make}.
 -Specific Makefile targets and Makefile variables are available:
 +  Configure your SSH client to use public key authentication with that key
 +when connecting to the FATE server. Also do not forget to check the identity
 +of the server and to accept its host key. This can usually be achieved by
 +running your SSH client manually and killing it after you accepted the key.
 +The FATE server's fingerprint is:
 +
 +  b1:31:c8:79:3f:04:1d:f8:f2:23:26:5a:fd:55:fa:92
 +
 +  The only thing left is to automate the execution of the fate.sh script and
 +the synchronisation of the samples directory.
 +
 +
 +@chapter FATE makefile targets and variables
 +
 +@section Makefile targets
  
 -@anchor{Makefile target}
 -@section FATE Makefile targets
  @table @option
 -@item fate-list
 -List all fate/regression test targets.
  @item fate-rsync
 -Shortcut to download the fate test samples to the specified testsuite location.
 +    Download/synchronize sample files to the configured samples directory.
 +
 +@item fate-list
 +    Will list all fate/regression test targets.
 +
  @item fate
 -Run the FATE test suite (requires the fate-suite dataset).
 +    Run the FATE test suite (requires the fate-suite dataset).
  @end table
  
 -@section FATE Makefile variables
 +@section Makefile variables
 +
  @table @option
  @item V
 -Verbosity level, can be set to 0, 1 or 2.
 -@table @option
 -    @item 0
 -    show just the test arguments
 -    @item 1
 -    show just the command used in the test
 -    @item 2
 -    show everything
 -@end table
 +    Verbosity level, can be set to 0, 1 or 2.
 +    @itemize
 +        @item 0: show just the test arguments
 +        @item 1: show just the command used in the test
 +        @item 2: show everything
 +    @end itemize
 +
  @item SAMPLES
 -Specify or override the path to the FATE samples at make time, it has a
 -meaning only while running the regression tests.
 +    Specify or override the path to the FATE samples at make time, it has a
 +    meaning only while running the regression tests.
 +
  @item THREADS
 -Specify how many threads to use while running regression tests, it is
 -quite useful to detect thread-related regressions.
 +    Specify how many threads to use while running regression tests, it is
 +    quite useful to detect thread-related regressions.
  @item CPUFLAGS
 -Specify a mask to be applied to autodetected CPU flags.
 +    Specify CPU flags.
+ @item TARGET_EXEC
 -Specify or override the wrapper used to run the tests.
++    Specify or override the wrapper used to run the tests.
++    The @var{TARGET_EXEC} option provides a way to run FATE wrapped in
++    @command{valgrind}, @command{qemu-user} or @command{wine} or on remote targets
++    through @command{ssh}.
  @end table
  
 +Example:
  @example
 -    make V=1 SAMPLES=/var/fate/samples THREADS=2 CPUFLAGS=mmx fate
 -@end example
 -
 -@chapter Automated Tests
 -In order to automatically testing specific configurations, e.g. multiple
 -compilers, @command{tests/fate.sh} is provided.
 -
 -This shell script builds Libav, runs the regression tests and prepares
 -a report that can be sent to @url{http://fate.libav.org/} or directly
 -examined locally.
 -
 -@section Testing Profiles
 -The configuration file passed to @command{fate.sh} is shell scripts as well.
 -
 -It must provide at least a @var{slot} identifier, the @var{repo} from
 -which fetch the sources, the @var{samples} directory, a @var{workdir} with
 -enough space to build and run all the tests.
 -Optional submit command @var{fate_recv} and a @var{comment} to describe
 -the testing profile are available.
 -
 -Additional optional parameter to tune the Libav building and reporting process
 -can be passed.
 -
 -@example
 -slot=                                   # some unique identifier
 -repo=git://git.libav.org/libav.git      # the source repository
 -samples=/path/to/fate/samples
 -workdir=                                # directory in which to do all the work
 -fate_recv="ssh -T fate@@fate.libav.org"  # command to submit report
 -comment=                                # optional description
 -
 -# the following are optional and map to configure options
 -arch=
 -cpu=
 -cross_prefix=
 -cc=
 -target_os=
 -sysroot=
 -target_exec=
 -target_path=
 -extra_cflags=
 -extra_ldflags=
 -extra_libs=
 -extra_conf=     # extra configure options not covered above
 -
 -#make=          # name of GNU make if not 'make'
 -makeopts=       # extra options passed to 'make'
 -#tar=           # command to create a tar archive from its arguments on
 -                # stdout, defaults to 'tar c'
 +make V=1 SAMPLES=/var/fate/samples THREADS=2 CPUFLAGS=mmx fate
  @end example
 -
 -@section Special Instances
 -The @var{TARGET_EXEC} option provides a way to run FATE wrapped in
 -@command{valgrind}, @command{qemu-user} or @command{wine} or on remote targets
 -through @command{ssh}.
 -
 -@section Submitting Reports
 -In order to send reports you need to create an @command{ssh} key and send it
 -to @email{root@@libav.org}.
 -The current server fingerprint is @var{a4:99:d7:d3:1c:92:0d:56:d6:d5:61:be:01:ae:7d:e6}
diff --combined doc/protocols.texi
index ae1c9b84e63307744742625e3ac7fa0b4bef8898,172184e501103360b1219aab4f8a12ae0407eb66..4575a679b9514a5c4bffbf4490716dbc2e1e7900
@@@ -1,10 -1,10 +1,10 @@@
  @chapter Protocols
  @c man begin PROTOCOLS
  
 -Protocols are configured elements in Libav which allow to access
 +Protocols are configured elements in FFmpeg which allow to access
  resources which require the use of a particular protocol.
  
 -When you configure your Libav build, all the supported protocols are
 +When you configure your FFmpeg build, all the supported protocols are
  enabled by default. You can list all available ones using the
  configure option "--list-protocols".
  
@@@ -19,36 -19,6 +19,36 @@@ supported protocols
  
  A description of the currently available protocols follows.
  
 +@section bluray
 +
 +Read BluRay playlist.
 +
 +The accepted options are:
 +@table @option
 +
 +@item angle
 +BluRay angle
 +
 +@item chapter
 +Start chapter (1...N)
 +
 +@item playlist
 +Playlist to read (BDMV/PLAYLIST/?????.mpls)
 +
 +@end table
 +
 +Examples:
 +
 +Read longest playlist from BluRay mounted to /mnt/bluray:
 +@example
 +bluray:/mnt/bluray
 +@end example
 +
 +Read angle 2 of playlist 4 from BluRay mounted to /mnt/bluray, start from chapter 2:
 +@example
 +-playlist 4 -angle 2 -chapter 2 bluray:/mnt/bluray
 +@end example
 +
  @section concat
  
  Physical concatenation protocol.
@@@ -66,10 -36,10 +66,10 @@@ resource to be concatenated, each one p
  protocol.
  
  For example to read a sequence of files @file{split1.mpeg},
 -@file{split2.mpeg}, @file{split3.mpeg} with @command{avplay} use the
 +@file{split2.mpeg}, @file{split3.mpeg} with @command{ffplay} use the
  command:
  @example
 -avplay concat:split1.mpeg\|split2.mpeg\|split3.mpeg
 +ffplay concat:split1.mpeg\|split2.mpeg\|split3.mpeg
  @end example
  
  Note that you may need to escape the character "|" which is special for
@@@ -81,10 -51,10 +81,10 @@@ File access protocol
  
  Allow to read from or read to a file.
  
 -For example to read from a file @file{input.mpeg} with @command{avconv}
 +For example to read from a file @file{input.mpeg} with @command{ffmpeg}
  use the command:
  @example
 -avconv -i file:input.mpeg output.mpeg
 +ffmpeg -i file:input.mpeg output.mpeg
  @end example
  
  The ff* tools default to the file protocol, that is a resource
@@@ -143,10 -113,10 +143,10 @@@ be used to test muxers without writing 
  Some examples follow.
  @example
  # Write the MD5 hash of the encoded AVI file to the file output.avi.md5.
 -avconv -i input.flv -f avi -y md5:output.avi.md5
 +ffmpeg -i input.flv -f avi -y md5:output.avi.md5
  
  # Write the MD5 hash of the encoded AVI file to stdout.
 -avconv -i input.flv -f avi -y md5:
 +ffmpeg -i input.flv -f avi -y md5:
  @end example
  
  Note that some formats (typically MOV) require the output protocol to
@@@ -168,18 -138,18 +168,18 @@@ pipe (e.g. 0 for stdin, 1 for stdout, 
  is not specified, by default the stdout file descriptor will be used
  for writing, stdin for reading.
  
 -For example to read from stdin with @command{avconv}:
 +For example to read from stdin with @command{ffmpeg}:
  @example
 -cat test.wav | avconv -i pipe:0
 +cat test.wav | ffmpeg -i pipe:0
  # ...this is the same as...
 -cat test.wav | avconv -i pipe:
 +cat test.wav | ffmpeg -i pipe:
  @end example
  
 -For writing to stdout with @command{avconv}:
 +For writing to stdout with @command{ffmpeg}:
  @example
 -avconv -i test.wav -f avi pipe:1 | cat > test.avi
 +ffmpeg -i test.wav -f avi pipe:1 | cat > test.avi
  # ...this is the same as...
 -avconv -i test.wav -f avi pipe: | cat > test.avi
 +ffmpeg -i test.wav -f avi pipe: | cat > test.avi
  @end example
  
  Note that some formats (typically MOV), require the output protocol to
@@@ -194,7 -164,7 +194,7 @@@ content across a TCP/IP network
  
  The required syntax is:
  @example
- rtmp://@var{server}[:@var{port}][/@var{app}][/@var{playpath}]
+ rtmp://@var{server}[:@var{port}][/@var{app}][/@var{instance}][/@var{playpath}]
  @end example
  
  The accepted parameters are:
@@@ -217,10 -187,10 +217,10 @@@ application specified in @var{app}, ma
  
  @end table
  
 -For example to read with @command{avplay} a multimedia resource named
 +For example to read with @command{ffplay} a multimedia resource named
  "sample" from the application "vod" from an RTMP server "myserver":
  @example
 -avplay rtmp://myserver/vod/sample
 +ffplay rtmp://myserver/vod/sample
  @end example
  
  @section rtmp, rtmpe, rtmps, rtmpt, rtmpte
@@@ -253,14 -223,14 +253,14 @@@ meaning as specified for the RTMP nativ
  See the librtmp manual page (man 3 librtmp) for more information.
  
  For example, to stream a file in real-time to an RTMP server using
 -@command{avconv}:
 +@command{ffmpeg}:
  @example
 -avconv -re -i myfile -f flv rtmp://myserver/live/mystream
 +ffmpeg -re -i myfile -f flv rtmp://myserver/live/mystream
  @end example
  
 -To play the same stream using @command{avplay}:
 +To play the same stream using @command{ffplay}:
  @example
 -avplay "rtmp://myserver/live/mystream live=1"
 +ffplay "rtmp://myserver/live/mystream live=1"
  @end example
  
  @section rtp
@@@ -283,7 -253,7 +283,7 @@@ The required syntax for a RTSP url is
  rtsp://@var{hostname}[:@var{port}]/@var{path}
  @end example
  
 -The following options (set on the @command{avconv}/@command{avplay} command
 +The following options (set on the @command{ffmpeg}/@command{ffplay} command
  line, or set in code via @code{AVOption}s or in @code{avformat_open_input}),
  are supported:
  
@@@ -322,7 -292,7 +322,7 @@@ When receiving data over UDP, the demux
  can be disabled by setting the maximum demuxing delay to zero (via
  the @code{max_delay} field of AVFormatContext).
  
 -When watching multi-bitrate Real-RTSP streams with @command{avplay}, the
 +When watching multi-bitrate Real-RTSP streams with @command{ffplay}, the
  streams to display can be chosen with @code{-vst} @var{n} and
  @code{-ast} @var{n} for video and audio respectively, and can be switched
  on the fly by pressing @code{v} and @code{a}.
@@@ -332,19 -302,19 +332,19 @@@ Example command lines
  To watch a stream over UDP, with a max reordering delay of 0.5 seconds:
  
  @example
 -avplay -max_delay 500000 -rtsp_transport udp rtsp://server/video.mp4
 +ffplay -max_delay 500000 -rtsp_transport udp rtsp://server/video.mp4
  @end example
  
  To watch a stream tunneled over HTTP:
  
  @example
 -avplay -rtsp_transport http rtsp://server/video.mp4
 +ffplay -rtsp_transport http rtsp://server/video.mp4
  @end example
  
  To send a stream in realtime to a RTSP server, for others to watch:
  
  @example
 -avconv -re -i @var{input} -f rtsp -muxdelay 0.1 rtsp://server/live.sdp
 +ffmpeg -re -i @var{input} -f rtsp -muxdelay 0.1 rtsp://server/live.sdp
  @end example
  
  @section sap
@@@ -396,19 -366,19 +396,19 @@@ Example command lines follow
  To broadcast a stream on the local subnet, for watching in VLC:
  
  @example
 -avconv -re -i @var{input} -f sap sap://224.0.0.255?same_port=1
 +ffmpeg -re -i @var{input} -f sap sap://224.0.0.255?same_port=1
  @end example
  
 -Similarly, for watching in avplay:
 +Similarly, for watching in @command{ffplay}:
  
  @example
 -avconv -re -i @var{input} -f sap sap://224.0.0.255
 +ffmpeg -re -i @var{input} -f sap sap://224.0.0.255
  @end example
  
 -And for watching in avplay, over IPv6:
 +And for watching in @command{ffplay}, over IPv6:
  
  @example
 -avconv -re -i @var{input} -f sap sap://[ff0e::1:2:3:4]
 +ffmpeg -re -i @var{input} -f sap sap://[ff0e::1:2:3:4]
  @end example
  
  @subsection Demuxer
@@@ -430,13 -400,13 +430,13 @@@ Example command lines follow
  To play back the first stream announced on the normal SAP multicast address:
  
  @example
 -avplay sap://
 +ffplay sap://
  @end example
  
  To play back the first stream announced on one the default IPv6 SAP multicast address:
  
  @example
 -avplay sap://[ff0e::2:7ffe]
 +ffplay sap://[ff0e::2:7ffe]
  @end example
  
  @section tcp
@@@ -454,8 -424,8 +454,8 @@@ tcp://@var{hostname}:@var{port}[?@var{o
  Listen for an incoming connection
  
  @example
 -avconv -i @var{input} -f @var{format} tcp://@var{hostname}:@var{port}?listen
 -avplay tcp://@var{hostname}:@var{port}
 +ffmpeg -i @var{input} -f @var{format} tcp://@var{hostname}:@var{port}?listen
 +ffplay tcp://@var{hostname}:@var{port}
  @end example
  
  @end table
@@@ -506,21 -476,21 +506,21 @@@ For receiving, this gives the benefit o
  the specified peer address/port.
  @end table
  
 -Some usage examples of the udp protocol with @command{avconv} follow.
 +Some usage examples of the udp protocol with @command{ffmpeg} follow.
  
  To stream over UDP to a remote endpoint:
  @example
 -avconv -i @var{input} -f @var{format} udp://@var{hostname}:@var{port}
 +ffmpeg -i @var{input} -f @var{format} udp://@var{hostname}:@var{port}
  @end example
  
  To stream in mpegts format over UDP using 188 sized UDP packets, using a large input buffer:
  @example
 -avconv -i @var{input} -f mpegts udp://@var{hostname}:@var{port}?pkt_size=188&buffer_size=65535
 +ffmpeg -i @var{input} -f mpegts udp://@var{hostname}:@var{port}?pkt_size=188&buffer_size=65535
  @end example
  
  To receive over UDP from a remote endpoint:
  @example
 -avconv -i udp://[@var{multicast-address}]:@var{port}
 +ffmpeg -i udp://[@var{multicast-address}]:@var{port}
  @end example
  
  @c man end PROTOCOLS
diff --combined ffmpeg.c
index fad21c0b61e171209829c13dc4c0b67189ea8d2c,5861f1bbf245b93f2e1863debd6eea7aa61080bc..d8396dc1f925b6adbc7117df4fcfcb201762cf70
+++ b/ffmpeg.c
@@@ -1,28 -1,24 +1,28 @@@
  /*
 - * avconv main
 - * Copyright (c) 2000-2011 The libav developers.
 + * Copyright (c) 2000-2003 Fabrice Bellard
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
 +/**
 + * @file
 + * multimedia converter based on the FFmpeg libraries
 + */
 +
  #include "config.h"
  #include <ctype.h>
  #include <string.h>
@@@ -35,7 -31,7 +35,7 @@@
  #include "libavformat/avformat.h"
  #include "libavdevice/avdevice.h"
  #include "libswscale/swscale.h"
 -#include "libavresample/avresample.h"
 +#include "libswresample/swresample.h"
  #include "libavutil/opt.h"
  #include "libavutil/audioconvert.h"
  #include "libavutil/parseutils.h"
  #include "libavutil/avstring.h"
  #include "libavutil/libm.h"
  #include "libavutil/imgutils.h"
 +#include "libavutil/timestamp.h"
 +#include "libavutil/bprint.h"
  #include "libavformat/os_support.h"
  
 +#include "libavformat/ffm.h" // not public API
 +
 +# include "libavfilter/avcodec.h"
  # include "libavfilter/avfilter.h"
  # include "libavfilter/avfiltergraph.h"
  # include "libavfilter/buffersrc.h"
  # include "libavfilter/buffersink.h"
 -# include "libavfilter/vsrc_buffer.h"
  
  #if HAVE_SYS_RESOURCE_H
  #include <sys/types.h>
  #include <sys/select.h>
  #endif
  
 +#if HAVE_TERMIOS_H
 +#include <fcntl.h>
 +#include <sys/ioctl.h>
 +#include <sys/time.h>
 +#include <termios.h>
 +#elif HAVE_KBHIT
 +#include <conio.h>
 +#endif
  #include <time.h>
  
  #include "cmdutils.h"
  #define VSYNC_PASSTHROUGH 0
  #define VSYNC_CFR         1
  #define VSYNC_VFR         2
 +#define VSYNC_DROP        0xff
  
 -const char program_name[] = "avconv";
 +#define SINKA
 +
 +const char program_name[] = "ffmpeg";
  const int program_birth_year = 2000;
  
  /* select an input stream for an output stream */
@@@ -112,40 -93,34 +112,40 @@@ typedef struct StreamMap 
      char *linklabel;       /** name of an output link, for mapping lavfi outputs */
  } StreamMap;
  
 -/**
 - * select an input file for an output file
 - */
 -typedef struct MetadataMap {
 -    int  file;      ///< file index
 -    char type;      ///< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
 -    int  index;     ///< stream/chapter/program number
 -} MetadataMap;
 +typedef struct {
 +    int  file_idx,  stream_idx,  channel_idx; // input
 +    int ofile_idx, ostream_idx;               // output
 +} AudioChannelMap;
  
  static const OptionDef options[];
  
 +#define MAX_STREAMS 1024    /* arbitrary sanity check value */
 +
 +static int frame_bits_per_raw_sample = 0;
  static int video_discard = 0;
  static int same_quant = 0;
  static int do_deinterlace = 0;
  static int intra_dc_precision = 8;
  static int qp_hist = 0;
 +static int intra_only = 0;
 +static const char *video_codec_name    = NULL;
 +static const char *audio_codec_name    = NULL;
 +static const char *subtitle_codec_name = NULL;
  
  static int file_overwrite = 0;
 +static int no_file_overwrite = 0;
  static int do_benchmark = 0;
 +static int do_benchmark_all = 0;
  static int do_hex_dump = 0;
  static int do_pkt_dump = 0;
 +static int do_psnr = 0;
  static int do_pass = 0;
 -static char *pass_logfilename_prefix = NULL;
 +static const char *pass_logfilename_prefix;
  static int video_sync_method = VSYNC_AUTO;
  static int audio_sync_method = 0;
  static float audio_drift_threshold = 0.1;
  static int copy_ts = 0;
 -static int copy_tb = 1;
 +static int copy_tb = -1;
  static int opt_shortest = 0;
  static char *vstats_filename;
  static FILE *vstats_file;
@@@ -154,8 -129,6 +154,8 @@@ static int audio_volume = 256
  
  static int exit_on_error = 0;
  static int using_stdin = 0;
 +static int run_as_daemon  = 0;
 +static volatile int received_nb_signals = 0;
  static int64_t video_size = 0;
  static int64_t audio_size = 0;
  static int64_t extra_size = 0;
@@@ -164,13 -137,10 +164,13 @@@ static int nb_frames_drop = 0
  static int input_sync;
  
  static float dts_delta_threshold = 10;
 +static float dts_error_threshold = 3600*30;
  
  static int print_stats = 1;
 +static int debug_ts = 0;
 +static int current_time;
  
 -#define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
 +#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
  
  typedef struct InputFilter {
      AVFilterContext    *filter;
@@@ -225,13 -195,10 +225,13 @@@ typedef struct InputStream 
       * several frames in a packet) of the next frame in current packet */
      int64_t       next_dts;
      /* dts of the last packet read for this stream */
 -    int64_t       last_dts;
 -    PtsCorrectionContext pts_ctx;
 +    int64_t       dts;
 +
 +    int64_t       next_pts;  /* synthetic pts for the next decode frame */
 +    int64_t       pts;       /* current pts of the decoded frame */
      double ts_scale;
      int is_start;            /* is 1 at the start and after a discontinuity */
 +    int saw_first_ts;
      int showed_multi_packet_warning;
      AVDictionary *opts;
  
  
      /* a pool of free buffers for decoded data */
      FrameBuffer *buffer_pool;
 +    int dr1;
  
      /* decoded data from this stream goes into all those filters
       * currently video and audio only */
  typedef struct InputFile {
      AVFormatContext *ctx;
      int eof_reached;      /* true if eof reached */
 -    int ist_index;        /* index of first stream in ist_table */
 +    int ist_index;        /* index of first stream in input_streams */
      int buffer_size;      /* current total buffer size */
      int64_t ts_offset;
 -    int nb_streams;       /* number of stream that avconv is aware of; may be different
 +    int nb_streams;       /* number of stream that ffmpeg is aware of; may be different
                               from ctx.nb_streams if new streams appear during av_read_frame() */
      int rate_emu;
  } InputFile;
@@@ -274,6 -240,7 +274,6 @@@ typedef struct OutputStream 
      int frame_number;
      /* input pts and corresponding output pts
         for A/V sync */
 -    // double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
      struct InputStream *sync_ist; /* input stream to sync against */
      int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
      /* pts of the first frame encoded for this stream, used for limiting
      int forced_kf_count;
      int forced_kf_index;
  
 +    /* audio only */
 +    int audio_channels_map[SWR_CH_MAX];  /* list of the channels id to pick from the source stream */
 +    int audio_channels_mapped;           /* number of channels in audio_channels_map */
 +
      FILE *logfile;
  
      OutputFilter *filter;
      char *avfilter;
  
      int64_t sws_flags;
 +    int64_t swr_dither_method;
 +    double swr_dither_scale;
      AVDictionary *opts;
      int is_past_recording_time;
      int stream_copy;
      const char *attachment_filename;
      int copy_initial_nonkeyframes;
  
 -    enum PixelFormat pix_fmts[2];
 +    int keep_pix_fmt;
  } OutputStream;
  
  
 +#if HAVE_TERMIOS_H
 +
 +/* init terminal so that we can grab keys */
 +static struct termios oldtty;
 +static int restore_tty;
 +#endif
 +
  typedef struct OutputFile {
      AVFormatContext *ctx;
      AVDictionary *opts;
      int ost_index;       /* index of the first stream in output_streams */
      int64_t recording_time; /* desired length of the resulting file in microseconds */
      int64_t start_time;     /* start time in microseconds */
 -    uint64_t limit_filesize;
 +    uint64_t limit_filesize; /* filesize limit expressed in bytes */
  } OutputFile;
  
  static InputStream **input_streams = NULL;
@@@ -378,8 -332,9 +378,8 @@@ typedef struct OptionsContext 
      /* output options */
      StreamMap *stream_maps;
      int     nb_stream_maps;
 -    /* first item specifies output metadata, second is input */
 -    MetadataMap (*meta_data_maps)[2];
 -    int nb_meta_data_maps;
 +    AudioChannelMap *audio_channel_maps; /* one info entry per -map_channel */
 +    int           nb_audio_channel_maps; /* number of (valid) -map_channel settings */
      int metadata_global_manual;
      int metadata_streams_manual;
      int metadata_chapters_manual;
      int        nb_filters;
  } OptionsContext;
  
 +static void do_video_stats(AVFormatContext *os, OutputStream *ost, int frame_size);
 +
  #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
  {\
      int i, ret;\
      }\
  }
  
 -static void reset_options(OptionsContext *o)
 +static int64_t getutime(void)
 +{
 +#if HAVE_GETRUSAGE
 +    struct rusage rusage;
 +
 +    getrusage(RUSAGE_SELF, &rusage);
 +    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
 +#elif HAVE_GETPROCESSTIMES
 +    HANDLE proc;
 +    FILETIME c, e, k, u;
 +    proc = GetCurrentProcess();
 +    GetProcessTimes(proc, &c, &e, &k, &u);
 +    return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
 +#else
 +    return av_gettime();
 +#endif
 +}
 +
 +static void update_benchmark(const char *fmt, ...)
 +{
 +    if (do_benchmark_all) {
 +        int64_t t = getutime();
 +        va_list va;
 +        char buf[1024];
 +
 +        if (fmt) {
 +            va_start(va, fmt);
 +            vsnprintf(buf, sizeof(buf), fmt, va);
 +            va_end(va);
 +            printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
 +        }
 +        current_time = t;
 +    }
 +}
 +
 +static void reset_options(OptionsContext *o, int is_input)
  {
      const OptionDef *po = options;
 +    OptionsContext bak= *o;
      int i;
  
      /* all OPT_SPEC and OPT_STRING can be freed in generic way */
      for (i = 0; i < o->nb_stream_maps; i++)
          av_freep(&o->stream_maps[i].linklabel);
      av_freep(&o->stream_maps);
 -    av_freep(&o->meta_data_maps);
 +    av_freep(&o->audio_channel_maps);
      av_freep(&o->streamid_map);
  
      memset(o, 0, sizeof(*o));
  
 +    if(is_input) o->recording_time = bak.recording_time;
 +    else         o->recording_time = INT64_MAX;
      o->mux_max_delay  = 0.7;
 -    o->recording_time = INT64_MAX;
      o->limit_filesize = UINT64_MAX;
      o->chapters_input_file = INT_MAX;
  
@@@ -542,13 -458,12 +542,13 @@@ static int alloc_buffer(InputStream *is
      if (!buf)
          return AVERROR(ENOMEM);
  
 +    avcodec_align_dimensions(s, &w, &h);
 +
      if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
          w += 2*edge;
          h += 2*edge;
      }
  
 -    avcodec_align_dimensions(s, &w, &h);
      if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
                                s->pix_fmt, 32)) < 0) {
          av_freep(&buf);
      for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
          const int h_shift = i==0 ? 0 : h_chroma_shift;
          const int v_shift = i==0 ? 0 : v_chroma_shift;
 -        if (s->flags & CODEC_FLAG_EMU_EDGE)
 +        if ((s->flags & CODEC_FLAG_EMU_EDGE) || !buf->linesize[1] || !buf->base[i])
              buf->data[i] = buf->base[i];
          else
              buf->data[i] = buf->base[i] +
@@@ -594,12 -509,9 +594,12 @@@ static void free_buffer_pool(InputStrea
  
  static void unref_buffer(InputStream *ist, FrameBuffer *buf)
  {
 -    av_assert0(buf->refcount);
 +    av_assert0(buf->refcount > 0);
      buf->refcount--;
      if (!buf->refcount) {
 +        FrameBuffer *tmp;
 +        for(tmp= ist->buffer_pool; tmp; tmp= tmp->next)
 +            av_assert1(tmp != buf);
          buf->next = ist->buffer_pool;
          ist->buffer_pool = buf;
      }
@@@ -611,9 -523,6 +611,9 @@@ static int codec_get_buffer(AVCodecCont
      FrameBuffer *buf;
      int ret, i;
  
 +    if(av_image_check_size(s->width, s->height, 0, s) || s->pix_fmt<0)
 +        return -1;
 +
      if (!ist->buffer_pool && (ret = alloc_buffer(ist, s, &ist->buffer_pool)) < 0)
          return ret;
  
          if ((ret = alloc_buffer(ist, s, &buf)) < 0)
              return ret;
      }
 +    av_assert0(!buf->refcount);
      buf->refcount++;
  
      frame->opaque        = buf;
@@@ -653,9 -561,6 +653,9 @@@ static void codec_release_buffer(AVCode
      FrameBuffer *buf = frame->opaque;
      int i;
  
 +    if(frame->type!=FF_BUFFER_TYPE_USER)
 +        return avcodec_default_release_buffer(s, frame);
 +
      for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
          frame->data[i] = NULL;
  
@@@ -669,80 -574,6 +669,80 @@@ static void filter_release_buffer(AVFil
      unref_buffer(buf->ist, buf);
  }
  
 +static enum PixelFormat choose_pixel_fmt(AVStream *st, AVCodec *codec, enum PixelFormat target)
 +{
 +    if (codec && codec->pix_fmts) {
 +        const enum PixelFormat *p = codec->pix_fmts;
 +        int has_alpha= av_pix_fmt_descriptors[target].nb_components % 2 == 0;
 +        enum PixelFormat best= PIX_FMT_NONE;
 +        if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
 +            if (st->codec->codec_id == CODEC_ID_MJPEG) {
 +                p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
 +            } else if (st->codec->codec_id == CODEC_ID_LJPEG) {
 +                p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
 +                                                 PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
 +            }
 +        }
 +        for (; *p != PIX_FMT_NONE; p++) {
 +            best= avcodec_find_best_pix_fmt2(best, *p, target, has_alpha, NULL);
 +            if (*p == target)
 +                break;
 +        }
 +        if (*p == PIX_FMT_NONE) {
 +            if (target != PIX_FMT_NONE)
 +                av_log(NULL, AV_LOG_WARNING,
 +                       "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
 +                       av_pix_fmt_descriptors[target].name,
 +                       codec->name,
 +                       av_pix_fmt_descriptors[best].name);
 +            return best;
 +        }
 +    }
 +    return target;
 +}
 +
 +static char *choose_pix_fmts(OutputStream *ost)
 +{
 +     if (ost->keep_pix_fmt) {
 +        if (ost->filter)
 +            avfilter_graph_set_auto_convert(ost->filter->graph->graph,
 +                                            AVFILTER_AUTO_CONVERT_NONE);
 +        if (ost->st->codec->pix_fmt == PIX_FMT_NONE)
 +            return NULL;
 +        return av_strdup(av_get_pix_fmt_name(ost->st->codec->pix_fmt));
 +    }
 +    if (ost->st->codec->pix_fmt != PIX_FMT_NONE) {
 +        return av_strdup(av_get_pix_fmt_name(choose_pixel_fmt(ost->st, ost->enc, ost->st->codec->pix_fmt)));
 +    } else if (ost->enc && ost->enc->pix_fmts) {
 +        const enum PixelFormat *p;
 +        AVIOContext *s = NULL;
 +        uint8_t *ret;
 +        int len;
 +
 +        if (avio_open_dyn_buf(&s) < 0)
 +            exit_program(1);
 +
 +        p = ost->enc->pix_fmts;
 +        if (ost->st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
 +            if (ost->st->codec->codec_id == CODEC_ID_MJPEG) {
 +                p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
 +            } else if (ost->st->codec->codec_id == CODEC_ID_LJPEG) {
 +                p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
 +                                                    PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
 +            }
 +        }
 +
 +        for (; *p != PIX_FMT_NONE; p++) {
 +            const char *name = av_get_pix_fmt_name(*p);
 +            avio_printf(s, "%s:", name);
 +        }
 +        len = avio_close_dyn_buf(s, &ret);
 +        ret[len - 1] = 0;
 +        return ret;
 +    } else
 +        return NULL;
 +}
 +
  /**
   * Define a function for building a string containing a list of
   * allowed formats,
@@@ -776,8 -607,8 +776,8 @@@ static char *choose_ ## var ## s(Output
  #define GET_PIX_FMT_NAME(pix_fmt)\
      const char *name = av_get_pix_fmt_name(pix_fmt);
  
 -DEF_CHOOSE_FORMAT(enum PixelFormat, pix_fmt, pix_fmts, PIX_FMT_NONE,
 -                  GET_PIX_FMT_NAME, ":")
 +// DEF_CHOOSE_FORMAT(enum PixelFormat, pix_fmt, pix_fmts, PIX_FMT_NONE,
 +//                   GET_PIX_FMT_NAME, ":")
  
  #define GET_SAMPLE_FMT_NAME(sample_fmt)\
      const char *name = av_get_sample_fmt_name(sample_fmt)
@@@ -825,7 -656,7 +825,7 @@@ static int configure_audio_filters(Filt
          return ret;
  
      ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,
 -                                       avfilter_get_by_name("abuffersink"),
 +                                       avfilter_get_by_name("abuffersink_old"),
                                         "out", NULL, NULL, fg->graph);
      if (ret < 0)
          return ret;
          *out_filter = format;
      }
  
 -    if (audio_sync_method > 0) {
 -        AVFilterContext *async;
 -        char args[256];
 -        int  len = 0;
 +#define AUTO_INSERT_FILTER(opt_name, filter_name, arg) do {                 \
 +    AVFilterContext *filt_ctx;                                              \
 +                                                                            \
 +    av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \
 +           "similarly to -af " filter_name "=%s.\n", arg);                  \
 +                                                                            \
 +    ret = avfilter_graph_create_filter(&filt_ctx,                           \
 +                                       avfilter_get_by_name(filter_name),   \
 +                                       filter_name, arg, NULL, fg->graph);  \
 +    if (ret < 0)                                                            \
 +        return ret;                                                         \
 +                                                                            \
 +    ret = avfilter_link(*in_filter, 0, filt_ctx, 0);                        \
 +    if (ret < 0)                                                            \
 +        return ret;                                                         \
 +                                                                            \
 +    *in_filter = filt_ctx;                                                  \
 +} while (0)
  
 -        av_log(NULL, AV_LOG_WARNING, "-async has been deprecated. Used the "
 -               "asyncts audio filter instead.\n");
 +    if (audio_sync_method > 0) {
 +        char args[256] = {0};
  
 +        av_strlcatf(args, sizeof(args), "min_comp=0.001:min_hard_comp=%f", audio_drift_threshold);
          if (audio_sync_method > 1)
 -            len += snprintf(args + len, sizeof(args) - len, "compensate=1:"
 -                            "max_comp=%d:", audio_sync_method);
 -        snprintf(args + len, sizeof(args) - len, "min_delta=%f",
 -                 audio_drift_threshold);
 +            av_strlcatf(args, sizeof(args), ":max_soft_comp=%f", audio_sync_method/(double)icodec->sample_rate);
 +        AUTO_INSERT_FILTER("-async", "aresample", args);
 +    }
  
 -        ret = avfilter_graph_create_filter(&async,
 -                                           avfilter_get_by_name("asyncts"),
 -                                           "async", args, NULL, fg->graph);
 -        if (ret < 0)
 -            return ret;
 +    if (ost->audio_channels_mapped) {
 +        int i;
 +        AVBPrint pan_buf;
  
 -        ret = avfilter_link(*in_filter, 0, async, 0);
 -        if (ret < 0)
 -            return ret;
 +        av_bprint_init(&pan_buf, 256, 8192);
 +        av_bprintf(&pan_buf, "0x%"PRIx64,
 +                   av_get_default_channel_layout(ost->audio_channels_mapped));
 +        for (i = 0; i < ost->audio_channels_mapped; i++)
 +            if (ost->audio_channels_map[i] != -1)
 +                av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
 +
 +        AUTO_INSERT_FILTER("-map_channel", "pan", pan_buf.str);
 +        av_bprint_finalize(&pan_buf, NULL);
 +    }
 +
 +    if (audio_volume != 256) {
 +        char args[256];
  
 -        *in_filter = async;
 +        snprintf(args, sizeof(args), "%lf", audio_volume / 256.);
 +        AUTO_INSERT_FILTER("-vol", "volume", args);
      }
  
      return 0;
@@@ -932,7 -740,6 +932,7 @@@ static int configure_video_filters(Filt
      OutputStream *ost = fg->outputs[0]->ost;
      AVFilterContext *filter;
      AVCodecContext *codec = ost->st->codec;
 +    AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
      char *pix_fmts;
      AVRational sample_aspect_ratio;
      char args[255];
      } else
          sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
  
 -    snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
 +    snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d:flags=%d", ist->st->codec->width,
               ist->st->codec->height, ist->st->codec->pix_fmt,
               ist->st->time_base.num, ist->st->time_base.den,
 -             sample_aspect_ratio.num, sample_aspect_ratio.den);
 +             sample_aspect_ratio.num, sample_aspect_ratio.den,
 +             SWS_BILINEAR + ((ist->st->codec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
  
      ret = avfilter_graph_create_filter(&fg->inputs[0]->filter,
                                         avfilter_get_by_name("buffer"),
                                         "src", args, NULL, fg->graph);
      if (ret < 0)
          return ret;
 +
 +#if FF_API_OLD_VSINK_API
      ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,
                                         avfilter_get_by_name("buffersink"),
                                         "out", NULL, NULL, fg->graph);
 +#else
 +    ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,
 +                                       avfilter_get_by_name("buffersink"),
 +                                       "out", NULL, buffersink_params, fg->graph);
 +#endif
 +    av_freep(&buffersink_params);
 +
      if (ret < 0)
          return ret;
      *in_filter  = fg->inputs[0]->filter;
          *in_filter = filter;
      }
  
 -    if (ost->frame_rate.num) {
 -        snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
 -                 ost->frame_rate.den);
 -        ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("fps"),
 -                                           "fps", args, NULL, fg->graph);
 -        if (ret < 0)
 -            return ret;
 -
 -        ret = avfilter_link(filter, 0, *out_filter, 0);
 -        if (ret < 0)
 -            return ret;
 -        *out_filter = filter;
 -    }
 -
      if ((pix_fmts = choose_pix_fmts(ost))) {
          if ((ret = avfilter_graph_create_filter(&filter,
                                                  avfilter_get_by_name("format"),
@@@ -1011,8 -822,6 +1011,8 @@@ static int configure_simple_filtergraph
  
      avfilter_graph_free(&fg->graph);
      fg->graph = avfilter_graph_alloc();
 +    if (!fg->graph)
 +        return AVERROR(ENOMEM);
  
      switch (ost->st->codec->codec_type) {
      case AVMEDIA_TYPE_VIDEO:
          inputs->pad_idx = 0;
          inputs->next    = NULL;
  
 -        if ((ret = avfilter_graph_parse(fg->graph, ost->avfilter, inputs, outputs, NULL)) < 0)
 +        if ((ret = avfilter_graph_parse(fg->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
              return ret;
 +        av_freep(&ost->avfilter);
      } else {
          if ((ret = avfilter_link(in_filter, 0, out_filter, 0)) < 0)
              return ret;
      }
  
 +    if (ost->keep_pix_fmt)
 +        avfilter_graph_set_auto_convert(fg->graph,
 +                                        AVFILTER_AUTO_CONVERT_NONE);
 +
      if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
          return ret;
  
@@@ -1095,7 -899,7 +1095,7 @@@ static FilterGraph *init_simple_filterg
  
  static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
  {
 -    InputStream *ist;
 +    InputStream *ist = NULL;
      enum AVMediaType type = in->filter_ctx->input_pads[in->pad_idx].type;
      int i;
  
          int file_idx = strtol(in->name, &p, 0);
  
          if (file_idx < 0 || file_idx >= nb_input_files) {
 -            av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtegraph description %s.\n",
 +            av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtergraph description %s.\n",
                     file_idx, fg->graph_desc);
              exit_program(1);
          }
@@@ -1170,19 -974,11 +1170,19 @@@ static int configure_output_video_filte
      AVFilterContext *last_filter = out->filter_ctx;
      int pad_idx = out->pad_idx;
      int ret;
 +    AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
  
 -
 +#if FF_API_OLD_VSINK_API
 +    ret = avfilter_graph_create_filter(&ofilter->filter,
 +                                       avfilter_get_by_name("buffersink"),
 +                                       "out", NULL, NULL, fg->graph);
 +#else
      ret = avfilter_graph_create_filter(&ofilter->filter,
                                         avfilter_get_by_name("buffersink"),
 -                                       "out", NULL, pix_fmts, fg->graph);
 +                                       "out", NULL, buffersink_params, fg->graph);
 +#endif
 +    av_freep(&buffersink_params);
 +
      if (ret < 0)
          return ret;
  
@@@ -1351,8 -1147,7 +1351,8 @@@ static int configure_complex_filter(Fil
                    ist->st->sample_aspect_ratio :
                    ist->st->codec->sample_aspect_ratio;
              snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
 -                     ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
 +                     ist->st->codec->height, ist->st->codec->pix_fmt,
 +                     ist->st->time_base.num, ist->st->time_base.den,
                       sar.num, sar.den);
              filter = avfilter_get_by_name("buffer");
              break;
@@@ -1433,51 -1228,22 +1433,51 @@@ static int ist_in_filtergraph(FilterGra
  
  static void term_exit(void)
  {
 -    av_log(NULL, AV_LOG_QUIET, "");
 +    av_log(NULL, AV_LOG_QUIET, "%s", "");
 +#if HAVE_TERMIOS_H
 +    if(restore_tty)
 +        tcsetattr (0, TCSANOW, &oldtty);
 +#endif
  }
  
  static volatile int received_sigterm = 0;
 -static volatile int received_nb_signals = 0;
  
 -static void
 -sigterm_handler(int sig)
 +static void sigterm_handler(int sig)
  {
      received_sigterm = sig;
      received_nb_signals++;
      term_exit();
 +    if(received_nb_signals > 3)
 +        exit(123);
  }
  
  static void term_init(void)
  {
 +#if HAVE_TERMIOS_H
 +    if(!run_as_daemon){
 +        struct termios tty;
 +
 +        if (tcgetattr (0, &tty) == 0) {
 +            oldtty = tty;
 +            restore_tty = 1;
 +            atexit(term_exit);
 +
 +            tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
 +                             |INLCR|IGNCR|ICRNL|IXON);
 +            tty.c_oflag |= OPOST;
 +            tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
 +            tty.c_cflag &= ~(CSIZE|PARENB);
 +            tty.c_cflag |= CS8;
 +            tty.c_cc[VMIN] = 1;
 +            tty.c_cc[VTIME] = 0;
 +
 +            tcsetattr (0, TCSANOW, &tty);
 +        }
 +        signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
 +    }
 +#endif
 +    avformat_network_deinit();
 +
      signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
      signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
  #ifdef SIGXCPU
  #endif
  }
  
 +/* read a key without blocking */
 +static int read_key(void)
 +{
 +    unsigned char ch;
 +#if HAVE_TERMIOS_H
 +    int n = 1;
 +    struct timeval tv;
 +    fd_set rfds;
 +
 +    FD_ZERO(&rfds);
 +    FD_SET(0, &rfds);
 +    tv.tv_sec = 0;
 +    tv.tv_usec = 0;
 +    n = select(1, &rfds, NULL, NULL, &tv);
 +    if (n > 0) {
 +        n = read(0, &ch, 1);
 +        if (n == 1)
 +            return ch;
 +
 +        return n;
 +    }
 +#elif HAVE_KBHIT
 +#    if HAVE_PEEKNAMEDPIPE
 +    static int is_pipe;
 +    static HANDLE input_handle;
 +    DWORD dw, nchars;
 +    if(!input_handle){
 +        input_handle = GetStdHandle(STD_INPUT_HANDLE);
 +        is_pipe = !GetConsoleMode(input_handle, &dw);
 +    }
 +
 +    if (stdin->_cnt > 0) {
 +        read(0, &ch, 1);
 +        return ch;
 +    }
 +    if (is_pipe) {
 +        /* When running under a GUI, you will end here. */
 +        if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL))
 +            return -1;
 +        //Read it
 +        if(nchars != 0) {
 +            read(0, &ch, 1);
 +            return ch;
 +        }else{
 +            return -1;
 +        }
 +    }
 +#    endif
 +    if(kbhit())
 +        return(getch());
 +#endif
 +    return -1;
 +}
 +
  static int decode_interrupt_cb(void *ctx)
  {
      return received_nb_signals > 1;
  
  static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
  
 -void exit_program(int ret)
 +void av_noreturn exit_program(int ret)
  {
      int i, j;
  
          }
          output_streams[i]->bitstream_filters = NULL;
  
 -        av_freep(&output_streams[i]->avfilter);
          av_freep(&output_streams[i]->filtered_frame);
          av_freep(&output_streams[i]);
      }
@@@ -1644,25 -1357,43 +1644,25 @@@ static void assert_codec_experimental(A
      }
  }
  
 -/**
 - * Update the requested input sample format based on the output sample format.
 - * This is currently only used to request float output from decoders which
 - * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
 - * Ideally this will be removed in the future when decoders do not do format
 - * conversion and only output in their native format.
 - */
 -static void update_sample_fmt(AVCodecContext *dec, AVCodec *dec_codec,
 -                              AVCodecContext *enc)
 +static void choose_sample_fmt(AVStream *st, AVCodec *codec)
  {
 -    /* if sample formats match or a decoder sample format has already been
 -       requested, just return */
 -    if (enc->sample_fmt == dec->sample_fmt ||
 -        dec->request_sample_fmt > AV_SAMPLE_FMT_NONE)
 -        return;
 -
 -    /* if decoder supports more than one output format */
 -    if (dec_codec && dec_codec->sample_fmts &&
 -        dec_codec->sample_fmts[0] != AV_SAMPLE_FMT_NONE &&
 -        dec_codec->sample_fmts[1] != AV_SAMPLE_FMT_NONE) {
 -        const enum AVSampleFormat *p;
 -        int min_dec = -1, min_inc = -1;
 -
 -        /* find a matching sample format in the encoder */
 -        for (p = dec_codec->sample_fmts; *p != AV_SAMPLE_FMT_NONE; p++) {
 -            if (*p == enc->sample_fmt) {
 -                dec->request_sample_fmt = *p;
 -                return;
 -            } else if (*p > enc->sample_fmt) {
 -                min_inc = FFMIN(min_inc, *p - enc->sample_fmt);
 -            } else
 -                min_dec = FFMIN(min_dec, enc->sample_fmt - *p);
 +    if (codec && codec->sample_fmts) {
 +        const enum AVSampleFormat *p = codec->sample_fmts;
 +        for (; *p != -1; p++) {
 +            if (*p == st->codec->sample_fmt)
 +                break;
 +        }
 +        if (*p == -1) {
 +            if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
 +                av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
 +            if(av_get_sample_fmt_name(st->codec->sample_fmt))
 +            av_log(NULL, AV_LOG_WARNING,
 +                   "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
 +                   av_get_sample_fmt_name(st->codec->sample_fmt),
 +                   codec->name,
 +                   av_get_sample_fmt_name(codec->sample_fmts[0]));
 +            st->codec->sample_fmt = codec->sample_fmts[0];
          }
 -
 -        /* if none match, provide the one that matches quality closest */
 -        dec->request_sample_fmt = min_inc > 0 ? enc->sample_fmt + min_inc :
 -                                  enc->sample_fmt - min_dec;
      }
  }
  
@@@ -1672,18 -1403,6 +1672,18 @@@ static void write_frame(AVFormatContex
      AVCodecContext          *avctx = ost->st->codec;
      int ret;
  
 +    if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
 +        (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
 +        pkt->pts = pkt->dts = AV_NOPTS_VALUE;
 +
 +    if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
 +        int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
 +        if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE &&  max > pkt->dts) {
 +            av_log(s, max - pkt->dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt->dts, max);
 +            pkt->pts = pkt->dts = max;
 +        }
 +    }
 +
      /*
       * Audio encoders may split the packets --  #frames in != #packets out.
       * But there is no reordering, so we can limit the number of output packets
              av_free_packet(pkt);
              new_pkt.destruct = av_destruct_packet;
          } else if (a < 0) {
 -            av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
 +            av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
                     bsfc->filter->name, pkt->stream_index,
                     avctx->codec ? avctx->codec->name : "copy");
              print_error("", a);
@@@ -1752,21 -1471,18 +1752,21 @@@ static void do_audio_out(AVFormatContex
      av_init_packet(&pkt);
      pkt.data = NULL;
      pkt.size = 0;
 -
 +#if 0
      if (!check_recording_time(ost))
          return;
 -
 +#endif
      if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
          frame->pts = ost->sync_opts;
      ost->sync_opts = frame->pts + frame->nb_samples;
  
 +    av_assert0(pkt.size || !pkt.data);
 +    update_benchmark(NULL);
      if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
 -        av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
 +        av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
          exit_program(1);
      }
 +    update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
  
      if (got_packet) {
          if (pkt.pts != AV_NOPTS_VALUE)
          if (pkt.duration > 0)
              pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
  
 +        if (debug_ts) {
 +            av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
 +                   "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
 +                   av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
 +                   av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
 +        }
 +
          write_frame(s, &pkt, ost);
  
          audio_size += pkt.size;
 +        av_free_packet(&pkt);
      }
  }
  
@@@ -1864,6 -1572,8 +1864,6 @@@ static void do_subtitle_out(AVFormatCon
  
      for (i = 0; i < nb; i++) {
          ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
 -        if (!check_recording_time(ost))
 -            return;
  
          sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
          // start_display_time is required to be 0
  static void do_video_out(AVFormatContext *s,
                           OutputStream *ost,
                           AVFrame *in_picture,
 -                         int *frame_size, float quality)
 +                         float quality)
  {
      int ret, format_video_sync;
      AVPacket pkt;
      AVCodecContext *enc = ost->st->codec;
 +    int nb_frames, i;
 +    double sync_ipts, delta;
 +    double duration = 0;
 +    int frame_size = 0;
 +    InputStream *ist = NULL;
 +
 +    if (ost->source_index >= 0)
 +        ist = input_streams[ost->source_index];
  
 -    *frame_size = 0;
 +    if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
 +        duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
 +
 +    sync_ipts = in_picture->pts;
 +    delta = sync_ipts - ost->sync_opts + duration;
 +
 +    /* by default, we output a single frame */
 +    nb_frames = 1;
  
      format_video_sync = video_sync_method;
      if (format_video_sync == VSYNC_AUTO)
 -        format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
 -                            (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
 -    if (format_video_sync != VSYNC_PASSTHROUGH &&
 -        ost->frame_number &&
 -        in_picture->pts != AV_NOPTS_VALUE &&
 -        in_picture->pts < ost->sync_opts) {
 +        format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;
 +
 +    switch (format_video_sync) {
 +    case VSYNC_CFR:
 +        // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
 +        if (delta < -1.1)
 +            nb_frames = 0;
 +        else if (delta > 1.1)
 +            nb_frames = lrintf(delta);
 +        break;
 +    case VSYNC_VFR:
 +        if (delta <= -0.6)
 +            nb_frames = 0;
 +        else if (delta > 0.6)
 +            ost->sync_opts = lrint(sync_ipts);
 +        break;
 +    case VSYNC_DROP:
 +    case VSYNC_PASSTHROUGH:
 +        ost->sync_opts = lrint(sync_ipts);
 +        break;
 +    default:
 +        av_assert0(0);
 +    }
 +
 +    nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
 +    if (nb_frames == 0) {
          nb_frames_drop++;
          av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
          return;
 +    } else if (nb_frames > 1) {
 +        nb_frames_dup += nb_frames - 1;
 +        av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
      }
  
 -    if (in_picture->pts == AV_NOPTS_VALUE)
 -        in_picture->pts = ost->sync_opts;
 -    ost->sync_opts = in_picture->pts;
 -
 -
 -    if (!ost->frame_number)
 -        ost->first_pts = in_picture->pts;
  
 +duplicate_frame:
      av_init_packet(&pkt);
      pkt.data = NULL;
      pkt.size = 0;
  
 -    if (!check_recording_time(ost) ||
 -        ost->frame_number >= ost->max_frames)
 -        return;
 +    in_picture->pts = ost->sync_opts;
  
      if (s->oformat->flags & AVFMT_RAWPICTURE &&
          enc->codec->id == CODEC_ID_RAWVIDEO) {
              big_picture.pict_type = AV_PICTURE_TYPE_I;
              ost->forced_kf_index++;
          }
 +        update_benchmark(NULL);
          ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
 +        update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
          if (ret < 0) {
              av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
              exit_program(1);
          }
  
          if (got_packet) {
 +            if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
 +                pkt.pts = ost->sync_opts;
 +
              if (pkt.pts != AV_NOPTS_VALUE)
                  pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
              if (pkt.dts != AV_NOPTS_VALUE)
                  pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  
 +            if (debug_ts) {
 +                av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
 +                    "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
 +                    av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
 +                    av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
 +            }
 +
              write_frame(s, &pkt, ost);
 -            *frame_size = pkt.size;
 +            frame_size = pkt.size;
              video_size += pkt.size;
 +            av_free_packet(&pkt);
  
              /* if two pass, output log */
              if (ost->logfile && enc->stats_out) {
       * flush, we need to limit them here, before they go into encoder.
       */
      ost->frame_number++;
 +
 +    if(--nb_frames)
 +        goto duplicate_frame;
 +
 +    if (vstats_filename && frame_size)
 +        do_video_stats(output_files[ost->file_index]->ctx, ost, frame_size);
  }
  
  static double psnr(double d)
@@@ -2098,114 -1759,73 +2098,114 @@@ static int poll_filters(void
  {
      AVFilterBufferRef *picref;
      AVFrame *filtered_frame = NULL;
 -    int i, frame_size;
 +    int i, ret, ret_all;
 +    unsigned nb_success, nb_eof;
 +    int64_t frame_pts;
  
 -    for (i = 0; i < nb_output_streams; i++) {
 -        OutputStream *ost = output_streams[i];
 -        OutputFile    *of = output_files[ost->file_index];
 -        int ret = 0;
 +    while (1) {
 +        /* Reap all buffers present in the buffer sinks */
 +        for (i = 0; i < nb_output_streams; i++) {
 +            OutputStream *ost = output_streams[i];
 +            OutputFile    *of = output_files[ost->file_index];
 +            int ret = 0;
  
 -        if (!ost->filter || ost->is_past_recording_time)
 -            continue;
 +            if (!ost->filter || ost->is_past_recording_time)
 +                continue;
  
 -        if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
 -            return AVERROR(ENOMEM);
 -        } else
 -            avcodec_get_frame_defaults(ost->filtered_frame);
 -        filtered_frame = ost->filtered_frame;
 -
 -        while (ret >= 0) {
 -            if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
 -                !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
 -                ret = av_buffersink_read_samples(ost->filter->filter, &picref,
 -                                                 ost->st->codec->frame_size);
 -            else
 -                ret = av_buffersink_read(ost->filter->filter, &picref);
 +            if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
 +                return AVERROR(ENOMEM);
 +            } else
 +                avcodec_get_frame_defaults(ost->filtered_frame);
 +            filtered_frame = ost->filtered_frame;
 +
 +            while (1) {
 +                AVRational ist_pts_tb = ost->filter->filter->inputs[0]->time_base;
 +                if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
 +                    !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
 +                    ret = av_buffersink_read_samples(ost->filter->filter, &picref,
 +                                                    ost->st->codec->frame_size);
 +                else
 +#ifdef SINKA
 +                    ret = av_buffersink_read(ost->filter->filter, &picref);
 +#else
 +                    ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
 +                                                       AV_BUFFERSINK_FLAG_NO_REQUEST);
 +#endif
 +                if (ret < 0) {
 +                    if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
 +                        char buf[256];
 +                        av_strerror(ret, buf, sizeof(buf));
 +                        av_log(NULL, AV_LOG_WARNING,
 +                               "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
 +                    }
 +                    break;
 +                }
 +                frame_pts = AV_NOPTS_VALUE;
 +                if (picref->pts != AV_NOPTS_VALUE) {
 +                    filtered_frame->pts = frame_pts = av_rescale_q(picref->pts,
 +                                                    ost->filter->filter->inputs[0]->time_base,
 +                                                    ost->st->codec->time_base) -
 +                                        av_rescale_q(of->start_time,
 +                                                    AV_TIME_BASE_Q,
 +                                                    ost->st->codec->time_base);
 +
 +                    if (of->start_time && filtered_frame->pts < 0) {
 +                        avfilter_unref_buffer(picref);
 +                        continue;
 +                    }
 +                }
 +                //if (ost->source_index >= 0)
 +                //    *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
  
 -            if (ret < 0)
 -                break;
  
 -            avfilter_copy_buf_props(filtered_frame, picref);
 -            if (picref->pts != AV_NOPTS_VALUE)
 -                filtered_frame->pts = av_rescale_q(picref->pts,
 -                                                   ost->filter->filter->inputs[0]->time_base,
 -                                                   ost->st->codec->time_base) -
 -                                      av_rescale_q(of->start_time,
 -                                                   AV_TIME_BASE_Q,
 -                                                   ost->st->codec->time_base);
 +                switch (ost->filter->filter->inputs[0]->type) {
 +                case AVMEDIA_TYPE_VIDEO:
 +                    avfilter_fill_frame_from_video_buffer_ref(filtered_frame, picref);
 +                    filtered_frame->pts = frame_pts;
 +                    if (!ost->frame_aspect_ratio)
 +                        ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
 +
 +                    do_video_out(of->ctx, ost, filtered_frame,
 +                                 same_quant ? ost->last_quality :
 +                                              ost->st->codec->global_quality);
 +                    break;
 +                case AVMEDIA_TYPE_AUDIO:
 +                    avfilter_copy_buf_props(filtered_frame, picref);
 +                    filtered_frame->pts = frame_pts;
 +                    do_audio_out(of->ctx, ost, filtered_frame);
 +                    break;
 +                default:
 +                    // TODO support subtitle filters
 +                    av_assert0(0);
 +                }
  
 -            if (of->start_time && filtered_frame->pts < of->start_time) {
                  avfilter_unref_buffer(picref);
 -                continue;
              }
 -
 -            switch (ost->filter->filter->inputs[0]->type) {
 -            case AVMEDIA_TYPE_VIDEO:
 -                if (!ost->frame_aspect_ratio)
 -                    ost->st->codec->sample_aspect_ratio = picref->video->pixel_aspect;
 -
 -                do_video_out(of->ctx, ost, filtered_frame, &frame_size,
 -                             same_quant ? ost->last_quality :
 -                                          ost->st->codec->global_quality);
 -                if (vstats_filename && frame_size)
 -                    do_video_stats(of->ctx, ost, frame_size);
 -                break;
 -            case AVMEDIA_TYPE_AUDIO:
 -                do_audio_out(of->ctx, ost, filtered_frame);
 -                break;
 -            default:
 -                // TODO support subtitle filters
 -                av_assert0(0);
 +        }
 +        /* Request frames through all the graphs */
 +        ret_all = nb_success = nb_eof = 0;
 +        for (i = 0; i < nb_filtergraphs; i++) {
 +            ret = avfilter_graph_request_oldest(filtergraphs[i]->graph);
 +            if (!ret) {
 +                nb_success++;
 +            } else if (ret == AVERROR_EOF) {
 +                nb_eof++;
 +            } else if (ret != AVERROR(EAGAIN)) {
 +                char buf[256];
 +                av_strerror(ret, buf, sizeof(buf));
 +                av_log(NULL, AV_LOG_WARNING,
 +                       "Error in request_frame(): %s\n", buf);
 +                ret_all = ret;
              }
 -
 -            avfilter_unref_buffer(picref);
          }
 +        if (!nb_success)
 +            break;
 +        /* Try again if anything succeeded */
      }
 -    return 0;
 +    return nb_eof == nb_filtergraphs ? AVERROR_EOF : ret_all;
  }
  
 -static void print_report(int is_last_report, int64_t timer_start)
 +static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
  {
      char buf[1024];
      OutputStream *ost;
      int64_t total_size;
      AVCodecContext *enc;
      int frame_number, vid, i;
 -    double bitrate, ti1, pts;
 +    double bitrate;
 +    int64_t pts = INT64_MAX;
      static int64_t last_time = -1;
      static int qp_histogram[52];
 +    int hours, mins, secs, us;
  
      if (!print_stats && !is_last_report)
          return;
  
      if (!is_last_report) {
 -        int64_t cur_time;
 -        /* display the report every 0.5 seconds */
 -        cur_time = av_gettime();
          if (last_time == -1) {
              last_time = cur_time;
              return;
      oc = output_files[0]->ctx;
  
      total_size = avio_size(oc->pb);
 -    if (total_size < 0) // FIXME improve avio_size() so it works with non seekable output too
 +    if (total_size < 0) // FIXME improve avio_size() so it works with non seekable output too
          total_size = avio_tell(oc->pb);
 +        if (total_size < 0)
 +            total_size = 0;
 +    }
  
      buf[0] = '\0';
 -    ti1 = 1e10;
      vid = 0;
      for (i = 0; i < nb_output_streams; i++) {
          float q = -1;
              snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
          }
          if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
 -            float t = (av_gettime() - timer_start) / 1000000.0;
 +            float fps, t = (cur_time-timer_start) / 1000000.0;
  
              frame_number = ost->frame_number;
 -            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
 -                     frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
 +            fps = t > 1 ? frame_number / t : 0;
 +            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
 +                     frame_number, fps < 9.95, fps, q);
              if (is_last_report)
                  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
              if (qp_hist) {
              vid = 1;
          }
          /* compute min output value */
 -        pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
 -        if ((pts < ti1) && (pts > 0))
 -            ti1 = pts;
 +        pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
 +                                      ost->st->time_base, AV_TIME_BASE_Q));
      }
 -    if (ti1 < 0.01)
 -        ti1 = 0.01;
  
 -    bitrate = (double)(total_size * 8) / ti1 / 1000.0;
 +    secs = pts / AV_TIME_BASE;
 +    us = pts % AV_TIME_BASE;
 +    mins = secs / 60;
 +    secs %= 60;
 +    hours = mins / 60;
 +    mins %= 60;
  
 +    bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
 +
 +    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
 +             "size=%8.0fkB time=", total_size / 1024.0);
      snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
 -            "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
 -            (double)total_size / 1024, ti1, bitrate);
 +             "%02d:%02d:%02d.%02d ", hours, mins, secs,
 +             (100 * us) / AV_TIME_BASE);
 +    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
 +             "bitrate=%6.1fkbits/s", bitrate);
  
      if (nb_frames_dup || nb_frames_drop)
          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
                 extra_size / 1024.0,
                 100.0 * (total_size - raw) / raw
          );
 +        if(video_size + audio_size + extra_size == 0){
 +            av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
 +        }
      }
  }
  
@@@ -2384,14 -1991,12 +2384,14 @@@ static void flush_encoders(void
                  pkt.data = NULL;
                  pkt.size = 0;
  
 +                update_benchmark(NULL);
                  ret = encode(enc, &pkt, NULL, &got_packet);
 +                update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
                  if (ret < 0) {
                      av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
                      exit_program(1);
                  }
 -                *size += ret;
 +                *size += pkt.size;
                  if (ost->logfile && enc->stats_out) {
                      fprintf(ost->logfile, "%s", enc->stats_out);
                  }
@@@ -2423,15 -2028,8 +2423,15 @@@ static int check_output_constraints(Inp
      if (ost->source_index != ist_index)
          return 0;
  
 -    if (of->start_time && ist->last_dts < of->start_time)
 +    if (of->start_time && ist->pts < of->start_time)
 +        return 0;
 +
 +    if (of->recording_time != INT64_MAX &&
 +        av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
 +                      (AVRational){ 1, 1000000 }) >= 0) {
 +        ost->is_past_recording_time = 1;
          return 0;
 +    }
  
      return 1;
  }
@@@ -2440,7 -2038,6 +2440,7 @@@ static void do_streamcopy(InputStream *
  {
      OutputFile *of = output_files[ost->file_index];
      int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
 +    AVPicture pict;
      AVPacket opkt;
  
      av_init_packet(&opkt);
          !ost->copy_initial_nonkeyframes)
          return;
  
 -    if (of->recording_time != INT64_MAX &&
 -        ist->last_dts >= of->recording_time + of->start_time) {
 -        ost->is_past_recording_time = 1;
 -        return;
 -    }
 -
      /* force the input stream PTS */
      if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
          audio_size += pkt->size;
          opkt.pts = AV_NOPTS_VALUE;
  
      if (pkt->dts == AV_NOPTS_VALUE)
 -        opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);
 +        opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
      else
          opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
      opkt.dts -= ost_tb_start_time;
          opkt.data = pkt->data;
          opkt.size = pkt->size;
      }
 +    if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
 +        /* store AVPicture in AVPacket, as expected by the output format */
 +        avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
 +        opkt.data = (uint8_t *)&pict;
 +        opkt.size = sizeof(AVPicture);
 +        opkt.flags |= AV_PKT_FLAG_KEY;
 +    }
  
      write_frame(of->ctx, &opkt, ost);
      ost->st->codec->frame_number++;
  static void rate_emu_sleep(InputStream *ist)
  {
      if (input_files[ist->file_index]->rate_emu) {
 -        int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
 +        int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
          int64_t now = av_gettime() - ist->start;
          if (pts > now)
              usleep(pts - now);
@@@ -2528,6 -2124,7 +2528,6 @@@ static int decode_audio(InputStream *is
  {
      AVFrame *decoded_frame;
      AVCodecContext *avctx = ist->st->codec;
 -    int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
      int i, ret, resample_changed;
  
      if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
          avcodec_get_frame_defaults(ist->decoded_frame);
      decoded_frame = ist->decoded_frame;
  
 +    update_benchmark(NULL);
      ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
 +    update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
      if (ret < 0) {
          return ret;
      }
 +    if (avctx->sample_rate <= 0) {
 +        av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
 +        return AVERROR_INVALIDDATA;
 +    }
  
      if (!*got_output) {
          /* no audio frame */
          if (!pkt->size)
              for (i = 0; i < ist->nb_filters; i++)
 -                av_buffersrc_buffer(ist->filters[i]->filter, NULL);
 +                av_buffersrc_add_ref(ist->filters[i]->filter, NULL,
 +                                     AV_BUFFERSRC_FLAG_NO_COPY);
          return ret;
      }
  
      /* 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->next_dts = decoded_frame->pts;
 +        ist->dts = ist->next_dts = ist->pts = ist->next_pts = decoded_frame->pts;
      else if (pkt->pts != AV_NOPTS_VALUE) {
          decoded_frame->pts = pkt->pts;
          pkt->pts           = AV_NOPTS_VALUE;
 -    }
 +    }else
 +        decoded_frame->pts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  
 -    // preprocess audio (volume)
 -    if (audio_volume != 256) {
 -        int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
 -        void *samples = decoded_frame->data[0];
 -        switch (avctx->sample_fmt) {
 -        case AV_SAMPLE_FMT_U8:
 -        {
 -            uint8_t *volp = samples;
 -            for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
 -                int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
 -                *volp++ = av_clip_uint8(v);
 -            }
 -            break;
 -        }
 -        case AV_SAMPLE_FMT_S16:
 -        {
 -            int16_t *volp = samples;
 -            for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
 -                int v = ((*volp) * audio_volume + 128) >> 8;
 -                *volp++ = av_clip_int16(v);
 -            }
 -            break;
 -        }
 -        case AV_SAMPLE_FMT_S32:
 -        {
 -            int32_t *volp = samples;
 -            for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
 -                int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
 -                *volp++ = av_clipl_int32(v);
 -            }
 -            break;
 -        }
 -        case AV_SAMPLE_FMT_FLT:
 -        {
 -            float *volp = samples;
 -            float scale = audio_volume / 256.f;
 -            for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
 -                *volp++ *= scale;
 -            }
 -            break;
 -        }
 -        case AV_SAMPLE_FMT_DBL:
 -        {
 -            double *volp = samples;
 -            double scale = audio_volume / 256.;
 -            for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
 -                *volp++ *= scale;
 -            }
 -            break;
 -        }
 -        default:
 -            av_log(NULL, AV_LOG_FATAL,
 -                   "Audio volume adjustment on sample format %s is not supported.\n",
 -                   av_get_sample_fmt_name(ist->st->codec->sample_fmt));
 -            exit_program(1);
 -        }
 -    }
 +
 +#if 1
 +    /* increment next_dts to use for the case where the input stream does not
 +       have timestamps or there are multiple frames in the packet */
 +    ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
 +                     avctx->sample_rate;
 +    ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
 +                     avctx->sample_rate;
 +#endif
  
      rate_emu_sleep(ist);
  
      }
  
      for (i = 0; i < ist->nb_filters; i++)
 -        av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
 +        av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0);
  
      return ret;
  }
@@@ -2630,8 -2267,6 +2630,8 @@@ static int decode_video(InputStream *is
      AVFrame *decoded_frame;
      void *buffer_to_free = NULL;
      int i, ret = 0, resample_changed;
 +    int64_t best_effort_timestamp;
 +    AVRational *frame_sample_aspect;
      float quality;
  
      if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
      else
          avcodec_get_frame_defaults(ist->decoded_frame);
      decoded_frame = ist->decoded_frame;
 +    pkt->dts  = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  
 +    update_benchmark(NULL);
      ret = avcodec_decode_video2(ist->st->codec,
                                  decoded_frame, got_output, pkt);
 +    update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
      if (ret < 0)
          return ret;
  
          /* no picture yet */
          if (!pkt->size)
              for (i = 0; i < ist->nb_filters; i++)
 -                av_buffersrc_buffer(ist->filters[i]->filter, NULL);
 +                av_buffersrc_add_ref(ist->filters[i]->filter, NULL, AV_BUFFERSRC_FLAG_NO_COPY);
          return ret;
      }
 -    decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
 -                                           decoded_frame->pkt_dts);
 +
 +    best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
 +    if(best_effort_timestamp != AV_NOPTS_VALUE)
 +        ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
 +
      pkt->size = 0;
      pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
  
              }
      }
  
 +    frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
      for (i = 0; i < ist->nb_filters; i++) {
 +        int changed =      ist->st->codec->width   != ist->filters[i]->filter->outputs[0]->w
 +                        || ist->st->codec->height  != ist->filters[i]->filter->outputs[0]->h
 +                        || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
          // XXX what an ugly hack
          if (ist->filters[i]->graph->nb_outputs == 1)
              ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
  
 -        if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {
 +        if (!frame_sample_aspect->num)
 +            *frame_sample_aspect = ist->st->sample_aspect_ratio;
 +        if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
              FrameBuffer      *buf = decoded_frame->opaque;
              AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
                                          decoded_frame->data, decoded_frame->linesize,
              fb->buf->priv           = buf;
              fb->buf->free           = filter_release_buffer;
  
 +            av_assert0(buf->refcount>0);
              buf->refcount++;
 -            av_buffersrc_buffer(ist->filters[i]->filter, fb);
 +            av_buffersrc_add_ref(ist->filters[i]->filter, fb,
 +                                 AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
 +                                 AV_BUFFERSRC_FLAG_NO_COPY);
          } else
 -            av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
 +        if(av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0)<0) {
 +            av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
 +            exit_program(1);
 +        }
 +
      }
  
      av_free(buffer_to_free);
@@@ -2759,24 -2375,12 +2759,24 @@@ static int transcode_subtitles(InputStr
  /* pkt = NULL means EOF (needed to flush decoder buffers) */
  static int output_packet(InputStream *ist, const AVPacket *pkt)
  {
 -    int i;
 +    int ret = 0, i;
      int got_output;
 +
      AVPacket avpkt;
 +    if (!ist->saw_first_ts) {
 +        ist->dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
 +        ist->pts = 0;
 +        if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
 +            ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
 +            ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
 +        }
 +        ist->saw_first_ts = 1;
 +    }
  
      if (ist->next_dts == AV_NOPTS_VALUE)
 -        ist->next_dts = ist->last_dts;
 +        ist->next_dts = ist->dts;
 +    if (ist->next_pts == AV_NOPTS_VALUE)
 +        ist->next_pts = ist->pts;
  
      if (pkt == NULL) {
          /* EOF handling */
          avpkt = *pkt;
      }
  
 -    if (pkt->dts != AV_NOPTS_VALUE)
 -        ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
 +    if (pkt->dts != AV_NOPTS_VALUE) {
 +        ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
 +        if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
 +            ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
 +    }
  
      // while we have more to decode or while the decoder did output something on EOF
      while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
 -        int ret = 0;
 +        int duration;
      handle_eof:
  
 -        ist->last_dts = ist->next_dts;
 +        ist->pts = ist->next_pts;
 +        ist->dts = ist->next_dts;
  
          if (avpkt.size && avpkt.size != pkt->size) {
              av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
              break;
          case AVMEDIA_TYPE_VIDEO:
              ret = decode_video    (ist, &avpkt, &got_output);
 -            if (avpkt.duration)
 -                ist->next_dts += av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
 -            else if (ist->st->r_frame_rate.num)
 -                ist->next_dts += av_rescale_q(1, (AVRational){ist->st->r_frame_rate.den,
 -                                                              ist->st->r_frame_rate.num},
 -                                              AV_TIME_BASE_Q);
 -            else if (ist->st->codec->time_base.num != 0) {
 -                int ticks      = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
 -                                                   ist->st->codec->ticks_per_frame;
 -                ist->next_dts += av_rescale_q(ticks, ist->st->codec->time_base, AV_TIME_BASE_Q);
 -            }
 +            if (avpkt.duration) {
 +                duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
 +            } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
 +                int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
 +                duration = ((int64_t)AV_TIME_BASE *
 +                                ist->st->codec->time_base.num * ticks) /
 +                                ist->st->codec->time_base.den;
 +            } else
 +                duration = 0;
 +
 +            if(ist->dts != AV_NOPTS_VALUE && duration) {
 +                ist->next_dts += duration;
 +            }else
 +                ist->next_dts = AV_NOPTS_VALUE;
 +
 +            if (got_output)
 +                ist->next_pts += duration; //FIXME the duration is not correct in some cases
              break;
          case AVMEDIA_TYPE_SUBTITLE:
              ret = transcode_subtitles(ist, &avpkt, &got_output);
  
          if (ret < 0)
              return ret;
 +
 +        avpkt.dts=
 +        avpkt.pts= AV_NOPTS_VALUE;
 +
          // touch data and size only if not EOF
          if (pkt) {
 +            if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
 +                ret = avpkt.size;
              avpkt.data += ret;
              avpkt.size -= ret;
          }
      /* handle stream copy */
      if (!ist->decoding_needed) {
          rate_emu_sleep(ist);
 -        ist->last_dts = ist->next_dts;
 +        ist->dts = ist->next_dts;
          switch (ist->st->codec->codec_type) {
          case AVMEDIA_TYPE_AUDIO:
              ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
                               ist->st->codec->sample_rate;
              break;
          case AVMEDIA_TYPE_VIDEO:
 -            if (ist->st->codec->time_base.num != 0) {
 -                int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
 +            if (pkt->duration) {
 +                ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
 +            } else if(ist->st->codec->time_base.num != 0) {
 +                int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
                  ist->next_dts += ((int64_t)AV_TIME_BASE *
                                    ist->st->codec->time_base.num * ticks) /
                                    ist->st->codec->time_base.den;
              }
              break;
          }
 +        ist->pts = ist->dts;
 +        ist->next_pts = ist->next_dts;
      }
      for (i = 0; pkt && i < nb_output_streams; i++) {
          OutputStream *ost = output_streams[i];
@@@ -2911,18 -2495,27 +2911,18 @@@ static void print_sdp(void
  
  static int init_input_stream(int ist_index, char *error, int error_len)
  {
 -    int i;
      InputStream *ist = input_streams[ist_index];
 +
      if (ist->decoding_needed) {
          AVCodec *codec = ist->dec;
          if (!codec) {
 -            snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
 -                    ist->st->codec->codec_id, ist->file_index, ist->st->index);
 +            snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
 +                    avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
              return AVERROR(EINVAL);
          }
  
 -        /* update requested sample format for the decoder based on the
 -           corresponding encoder sample format */
 -        for (i = 0; i < nb_output_streams; i++) {
 -            OutputStream *ost = output_streams[i];
 -            if (ost->source_index == ist_index) {
 -                update_sample_fmt(ist->st->codec, codec, ost->st->codec);
 -                break;
 -            }
 -        }
 -
 -        if (codec->type == AVMEDIA_TYPE_VIDEO && codec->capabilities & CODEC_CAP_DR1) {
 +        ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !do_deinterlace;
 +        if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
              ist->st->codec->get_buffer     = codec_get_buffer;
              ist->st->codec->release_buffer = codec_release_buffer;
              ist->st->codec->opaque         = ist;
          assert_avoptions(ist->opts);
      }
  
 -    ist->last_dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
 +    ist->next_pts = AV_NOPTS_VALUE;
      ist->next_dts = AV_NOPTS_VALUE;
 -    init_pts_correction(&ist->pts_ctx);
      ist->is_start = 1;
  
      return 0;
@@@ -3046,37 -2640,14 +3046,37 @@@ static int transcode_init(void
                  return AVERROR(ENOMEM);
              }
              memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
 -            codec->extradata_size = icodec->extradata_size;
 -            if (!copy_tb) {
 -                codec->time_base      = icodec->time_base;
 -                codec->time_base.num *= icodec->ticks_per_frame;
 -                av_reduce(&codec->time_base.num, &codec->time_base.den,
 -                          codec->time_base.num, codec->time_base.den, INT_MAX);
 -            } else
 -                codec->time_base = ist->st->time_base;
 +            codec->extradata_size= icodec->extradata_size;
 +            codec->bits_per_coded_sample  = icodec->bits_per_coded_sample;
 +
 +            codec->time_base = ist->st->time_base;
 +            /*
 +             * Avi is a special case here because it supports variable fps but
 +             * having the fps and timebase differe significantly adds quite some
 +             * overhead
 +             */
 +            if(!strcmp(oc->oformat->name, "avi")) {
 +                if (   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
 +                                 && av_q2d(ist->st->time_base) < 1.0/500
 +                    || copy_tb==0){
 +                    codec->time_base = icodec->time_base;
 +                    codec->time_base.num *= icodec->ticks_per_frame;
 +                    codec->time_base.den *= 2;
 +                    codec->ticks_per_frame = 2;
 +                }
 +            } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
 +                      && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
 +                      && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
 +            ) {
 +                if(   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
 +                                && av_q2d(ist->st->time_base) < 1.0/500
 +                   || copy_tb==0){
 +                    codec->time_base = icodec->time_base;
 +                    codec->time_base.num *= icodec->ticks_per_frame;
 +                }
 +            }
 +            av_reduce(&codec->time_base.num, &codec->time_base.den,
 +                        codec->time_base.num, codec->time_base.den, INT_MAX);
  
              switch (codec->codec_type) {
              case AVMEDIA_TYPE_AUDIO:
                  codec->frame_size         = icodec->frame_size;
                  codec->audio_service_type = icodec->audio_service_type;
                  codec->block_align        = icodec->block_align;
 +                if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
 +                    codec->block_align= 0;
 +                if(codec->codec_id == CODEC_ID_AC3)
 +                    codec->block_align= 0;
                  break;
              case AVMEDIA_TYPE_VIDEO:
                  codec->pix_fmt            = icodec->pix_fmt;
                          ist->st->codec->sample_aspect_ratio.num ?
                          ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
                  }
 +                ost->st->avg_frame_rate = ist->st->avg_frame_rate;
                  break;
              case AVMEDIA_TYPE_SUBTITLE:
                  codec->width  = icodec->width;
                  abort();
              }
          } else {
 +            if (!ost->enc)
 +                ost->enc = avcodec_find_encoder(codec->codec_id);
              if (!ost->enc) {
                  /* should only happen when a default codec is not present. */
 -                snprintf(error, sizeof(error), "Automatic encoder selection "
 -                         "failed for output stream #%d:%d. Default encoder for "
 -                         "format %s is probably disabled. Please choose an "
 -                         "encoder manually.\n", ost->file_index, ost->index,
 -                         oc->oformat->name);
 +                snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
 +                         avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
                  ret = AVERROR(EINVAL);
                  goto dump_format;
              }
                  ist->decoding_needed = 1;
              ost->encoding_needed = 1;
  
 -            /*
 -             * We want CFR output if and only if one of those is true:
 -             * 1) user specified output framerate with -r
 -             * 2) user specified -vsync cfr
 -             * 3) output format is CFR and the user didn't force vsync to
 -             *    something else than CFR
 -             *
 -             * in such a case, set ost->frame_rate
 -             */
 -            if (codec->codec_type == AVMEDIA_TYPE_VIDEO &&
 -                !ost->frame_rate.num && ist &&
 -                (video_sync_method ==  VSYNC_CFR ||
 -                 (video_sync_method ==  VSYNC_AUTO &&
 -                  !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {
 -                ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
 +            if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
 +                if (ist && !ost->frame_rate.num)
 +                    ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
                  if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
                      int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
                      ost->frame_rate = ost->enc->supported_framerates[idx];
                  codec->time_base      = (AVRational){ 1, codec->sample_rate };
                  break;
              case AVMEDIA_TYPE_VIDEO:
 -                codec->time_base = ost->filter->filter->inputs[0]->time_base;
 +                codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
 +                if (   av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
 +                   && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
 +                    av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
 +                                               "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
 +                }
 +                for (j = 0; j < ost->forced_kf_count; j++)
 +                    ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
 +                                                         AV_TIME_BASE_Q,
 +                                                         codec->time_base);
  
                  codec->width  = ost->filter->filter->inputs[0]->w;
                  codec->height = ost->filter->filter->inputs[0]->h;
                  if (codec->width   != icodec->width  ||
                      codec->height  != icodec->height ||
                      codec->pix_fmt != icodec->pix_fmt) {
 -                    codec->bits_per_raw_sample = 0;
 +                    codec->bits_per_raw_sample = frame_bits_per_raw_sample;
                  }
  
                  break;
                  break;
              }
              /* two pass mode */
 -            if ((codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
 +            if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
                  char logfilename[1024];
                  FILE *f;
  
                  if (!strcmp(ost->enc->name, "libx264")) {
                      av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
                  } else {
 -                    if (codec->flags & CODEC_FLAG_PASS1) {
 -                        f = fopen(logfilename, "wb");
 -                        if (!f) {
 -                            av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
 -                                   logfilename, strerror(errno));
 -                            exit_program(1);
 -                        }
 -                        ost->logfile = f;
 -                    } else {
 +                    if (codec->flags & CODEC_FLAG_PASS2) {
                          char  *logbuffer;
                          size_t logbuffer_size;
                          if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
                          }
                          codec->stats_in = logbuffer;
                      }
 +                    if (codec->flags & CODEC_FLAG_PASS1) {
 +                        f = fopen(logfilename, "wb");
 +                        if (!f) {
 +                            av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
 +                                logfilename, strerror(errno));
 +                            exit_program(1);
 +                        }
 +                        ost->logfile = f;
 +                    }
                  }
              }
          }
              assert_avoptions(ost->opts);
              if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
                  av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
 -                                             "It takes bits/s as argument, not kbits/s\n");
 +                                             " It takes bits/s as argument, not kbits/s\n");
              extra_size += ost->st->codec->extradata_size;
  
              if (ost->st->codec->me_threshold)
      for (i = 0; i < nb_output_files; i++) {
          oc = output_files[i]->ctx;
          oc->interrupt_callback = int_cb;
-         if (avformat_write_header(oc, &output_files[i]->opts) < 0) {
-             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
+         if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
+             char errbuf[128];
+             const char *errbuf_ptr = errbuf;
+             if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
+                 errbuf_ptr = strerror(AVUNERROR(ret));
+             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
              ret = AVERROR(EINVAL);
              goto dump_format;
          }
 -        assert_avoptions(output_files[i]->opts);
 +//         assert_avoptions(output_files[i]->opts);
          if (strcmp(oc->oformat->name, "rtp")) {
              want_sdp = 0;
          }
@@@ -3398,7 -2971,6 +3402,7 @@@ static int transcode(void
      uint8_t *no_packet;
      int no_packet_count = 0;
      int64_t timer_start;
 +    int key;
  
      if (!(no_packet = av_mallocz(nb_input_files)))
          exit_program(1);
      if (ret < 0)
          goto fail;
  
 -    av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
 -    term_init();
 +    if (!using_stdin) {
 +        av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
 +    }
  
      timer_start = av_gettime();
  
          int file_index, ist_index, past_recording_time = 1;
          AVPacket pkt;
          int64_t ipts_min;
 +        int64_t cur_time= av_gettime();
  
          ipts_min = INT64_MAX;
 +        /* if 'q' pressed, exits */
 +        if (!using_stdin) {
 +            static int64_t last_time;
 +            if (received_nb_signals)
 +                break;
 +            /* read_key() returns 0 on EOF */
 +            if(cur_time - last_time >= 100000 && !run_as_daemon){
 +                key =  read_key();
 +                last_time = cur_time;
 +            }else
 +                key = -1;
 +            if (key == 'q')
 +                break;
 +            if (key == '+') av_log_set_level(av_log_get_level()+10);
 +            if (key == '-') av_log_set_level(av_log_get_level()-10);
 +            if (key == 's') qp_hist     ^= 1;
 +            if (key == 'h'){
 +                if (do_hex_dump){
 +                    do_hex_dump = do_pkt_dump = 0;
 +                } else if(do_pkt_dump){
 +                    do_hex_dump = 1;
 +                } else
 +                    do_pkt_dump = 1;
 +                av_log_set_level(AV_LOG_DEBUG);
 +            }
 +            if (key == 'c' || key == 'C'){
 +                char buf[4096], target[64], command[256], arg[256] = {0};
 +                double time;
 +                int k, n = 0;
 +                fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
 +                i = 0;
 +                while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
 +                    if (k > 0)
 +                        buf[i++] = k;
 +                buf[i] = 0;
 +                if (k > 0 &&
 +                    (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
 +                    av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
 +                           target, time, command, arg);
 +                    for (i = 0; i < nb_filtergraphs; i++) {
 +                        FilterGraph *fg = filtergraphs[i];
 +                        if (fg->graph) {
 +                            if (time < 0) {
 +                                ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
 +                                                                  key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
 +                                fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
 +                            } else {
 +                                ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
 +                            }
 +                        }
 +                    }
 +                } else {
 +                    av_log(NULL, AV_LOG_ERROR,
 +                           "Parse error, at least 3 arguments were expected, "
 +                           "only %d given in string '%s'\n", n, buf);
 +                }
 +            }
 +            if (key == 'd' || key == 'D'){
 +                int debug=0;
 +                if(key == 'D') {
 +                    debug = input_streams[0]->st->codec->debug<<1;
 +                    if(!debug) debug = 1;
 +                    while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
 +                        debug += debug;
 +                }else
 +                    if(scanf("%d", &debug)!=1)
 +                        fprintf(stderr,"error parsing debug value\n");
 +                for(i=0;i<nb_input_streams;i++) {
 +                    input_streams[i]->st->codec->debug = debug;
 +                }
 +                for(i=0;i<nb_output_streams;i++) {
 +                    ost = output_streams[i];
 +                    ost->st->codec->debug = debug;
 +                }
 +                if(debug) av_log_set_level(AV_LOG_DEBUG);
 +                fprintf(stderr,"debug=%d\n", debug);
 +            }
 +            if (key == '?'){
 +                fprintf(stderr, "key    function\n"
 +                                "?      show this help\n"
 +                                "+      increase verbosity\n"
 +                                "-      decrease verbosity\n"
 +                                "c      Send command to filtergraph\n"
 +                                "D      cycle through available debug modes\n"
 +                                "h      dump packets/hex press to cycle through the 3 states\n"
 +                                "q      quit\n"
 +                                "s      Show QP histogram\n"
 +                );
 +            }
 +        }
  
          /* check if there's any stream where output is still needed */
          for (i = 0; i < nb_output_streams; i++) {
              if (ost->is_past_recording_time ||
                  (os->pb && avio_tell(os->pb) >= of->limit_filesize))
                  continue;
 -            if (ost->frame_number > ost->max_frames) {
 +            if (ost->frame_number >= ost->max_frames) {
                  int j;
                  for (j = 0; j < of->ctx->nb_streams; j++)
                      output_streams[of->ost_index + j]->is_past_recording_time = 1;
          for (i = 0; i < nb_input_streams; i++) {
              int64_t ipts;
              ist = input_streams[i];
 -            ipts = ist->last_dts;
 +            ipts = ist->pts;
              if (ist->discard || no_packet[ist->file_index])
                  continue;
              if (!input_files[ist->file_index]->eof_reached) {
          if (pkt.dts != AV_NOPTS_VALUE)
              pkt.dts *= ist->ts_scale;
  
 -        //fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n",
 -        //        ist->next_dts,
 -        //        pkt.dts, input_files[ist->file_index].ts_offset,
 -        //        ist->st->codec->codec_type);
 -        if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE
 -            && (is->iformat->flags & AVFMT_TS_DISCONT)) {
 +        if (debug_ts) {
 +            av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
 +                    "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s  pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%"PRId64"\n",
 +                    ist_index, av_get_media_type_string(ist->st->codec->codec_type),
 +                    av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &ist->st->time_base),
 +                    av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &ist->st->time_base),
 +                    av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
 +                    av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
 +                    input_files[ist->file_index]->ts_offset);
 +        }
 +
 +        if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
              int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
              int64_t delta   = pkt_dts - ist->next_dts;
 -            if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
 +            if (is->iformat->flags & AVFMT_TS_DISCONT) {
 +            if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
 +                (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
 +                 ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
 +                pkt_dts+1<ist->pts){
                  input_files[ist->file_index]->ts_offset -= delta;
                  av_log(NULL, AV_LOG_DEBUG,
                         "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
                  if (pkt.pts != AV_NOPTS_VALUE)
                      pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
              }
 +            } else {
 +                if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
 +                    (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
 +                     pkt_dts+1<ist->pts){
 +                    av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
 +                    pkt.dts = AV_NOPTS_VALUE;
 +                }
 +                if (pkt.pts != AV_NOPTS_VALUE){
 +                    int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
 +                    delta   = pkt_pts - ist->next_dts;
 +                    if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
 +                        (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
 +                        pkt_pts+1<ist->pts) {
 +                        av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
 +                        pkt.pts = AV_NOPTS_VALUE;
 +                    }
 +                }
 +            }
          }
  
          // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
 -        if (output_packet(ist, &pkt) < 0 || poll_filters() < 0) {
 +        if (output_packet(ist, &pkt) < 0 ||
 +            ((ret = poll_filters()) < 0 && ret != AVERROR_EOF)) {
              av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
                     ist->file_index, ist->st->index);
              if (exit_on_error)
          av_free_packet(&pkt);
  
          /* dump report by using the output first video and audio streams */
 -        print_report(0, timer_start);
 +        print_report(0, timer_start, cur_time);
      }
  
      /* at the end of stream, we must flush the decoder buffers */
      }
  
      /* dump report by using the first video and audio streams */
 -    print_report(1, timer_start);
 +    print_report(1, timer_start, av_gettime());
  
      /* close each encoder */
      for (i = 0; i < nb_output_streams; i++) {
      return ret;
  }
  
 -static double parse_frame_aspect_ratio(const char *arg)
 +static int opt_frame_crop(const char *opt, const char *arg)
  {
 -    int x = 0, y = 0;
 -    double ar = 0;
 -    const char *p;
 -    char *end;
 -
 -    p = strchr(arg, ':');
 -    if (p) {
 -        x = strtol(arg, &end, 10);
 -        if (end == p)
 -            y = strtol(end + 1, &end, 10);
 -        if (x > 0 && y > 0)
 -            ar = (double)x / (double)y;
 -    } else
 -        ar = strtod(arg, NULL);
 +    av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
 +    return AVERROR(EINVAL);
 +}
  
 -    if (!ar) {
 -        av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
 -        exit_program(1);
 -    }
 -    return ar;
 +static int opt_pad(const char *opt, const char *arg)
 +{
 +    av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
 +    return -1;
 +}
 +
 +static int opt_video_channel(const char *opt, const char *arg)
 +{
 +    av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
 +    return opt_default("channel", arg);
 +}
 +
 +static int opt_video_standard(const char *opt, const char *arg)
 +{
 +    av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
 +    return opt_default("standard", arg);
  }
  
  static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
  {
 +    audio_codec_name = arg;
      return parse_option(o, "codec:a", arg, options);
  }
  
  static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
  {
 +    video_codec_name = arg;
      return parse_option(o, "codec:v", arg, options);
  }
  
  static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
  {
 +    subtitle_codec_name = arg;
      return parse_option(o, "codec:s", arg, options);
  }
  
@@@ -3786,7 -3234,7 +3790,7 @@@ static int opt_map(OptionsContext *o, c
  {
      StreamMap *m = NULL;
      int i, negative = 0, file_idx;
 -    int sync_file_idx = -1, sync_stream_idx;
 +    int sync_file_idx = -1, sync_stream_idx = 0;
      char *p, *sync;
      char *map;
  
@@@ -3886,66 -3334,6 +3890,66 @@@ static int opt_attach(OptionsContext *o
      return 0;
  }
  
 +static int opt_map_channel(OptionsContext *o, const char *opt, const char *arg)
 +{
 +    int n;
 +    AVStream *st;
 +    AudioChannelMap *m;
 +
 +    o->audio_channel_maps =
 +        grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
 +                   &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
 +    m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
 +
 +    /* muted channel syntax */
 +    n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
 +    if ((n == 1 || n == 3) && m->channel_idx == -1) {
 +        m->file_idx = m->stream_idx = -1;
 +        if (n == 1)
 +            m->ofile_idx = m->ostream_idx = -1;
 +        return 0;
 +    }
 +
 +    /* normal syntax */
 +    n = sscanf(arg, "%d.%d.%d:%d.%d",
 +               &m->file_idx,  &m->stream_idx, &m->channel_idx,
 +               &m->ofile_idx, &m->ostream_idx);
 +
 +    if (n != 3 && n != 5) {
 +        av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
 +               "[file.stream.channel|-1][:syncfile:syncstream]\n");
 +        exit_program(1);
 +    }
 +
 +    if (n != 5) // only file.stream.channel specified
 +        m->ofile_idx = m->ostream_idx = -1;
 +
 +    /* check input */
 +    if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
 +        av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
 +               m->file_idx);
 +        exit_program(1);
 +    }
 +    if (m->stream_idx < 0 ||
 +        m->stream_idx >= input_files[m->file_idx]->nb_streams) {
 +        av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
 +               m->file_idx, m->stream_idx);
 +        exit_program(1);
 +    }
 +    st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
 +    if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
 +        av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
 +               m->file_idx, m->stream_idx);
 +        exit_program(1);
 +    }
 +    if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
 +        av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
 +               m->file_idx, m->stream_idx, m->channel_idx);
 +        exit_program(1);
 +    }
 +    return 0;
 +}
 +
  /**
   * Parse a metadata specifier in arg.
   * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
@@@ -3982,7 -3370,7 +3986,7 @@@ static void parse_meta_type(char *arg, 
  static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
  {
      AVDictionary **meta_in = NULL;
 -    AVDictionary **meta_out;
 +    AVDictionary **meta_out = NULL;
      int i, ret = 0;
      char type_in, type_out;
      const char *istream_spec = NULL, *ostream_spec = NULL;
      parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);
      parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
  
 +    if (!ic) {
 +        if (type_out == 'g' || !*outspec)
 +            o->metadata_global_manual = 1;
 +        if (type_out == 's' || !*outspec)
 +            o->metadata_streams_manual = 1;
 +        if (type_out == 'c' || !*outspec)
 +            o->metadata_chapters_manual = 1;
 +        return 0;
 +    }
 +
      if (type_in == 'g' || type_out == 'g')
          o->metadata_global_manual = 1;
      if (type_in == 's' || type_out == 's')
      return 0;
  }
  
 +static int opt_recording_timestamp(OptionsContext *o, const char *opt, const char *arg)
 +{
 +    char buf[128];
 +    int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
 +    struct tm time = *gmtime((time_t*)&recording_timestamp);
 +    strftime(buf, sizeof(buf), "creation_time=%FT%T%z", &time);
 +    parse_option(o, "metadata", buf, options);
 +
 +    av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
 +                                 "tag instead.\n", opt);
 +    return 0;
 +}
 +
  static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
  {
      const char *codec_string = encoder ? "encoder" : "decoder";
@@@ -4114,7 -3479,6 +4118,7 @@@ static AVCodec *choose_decoder(OptionsC
  static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
  {
      int i;
 +    char *next, *codec_tag = NULL;
  
      for (i = 0; i < ic->nb_streams; i++) {
          AVStream *st = ic->streams[i];
          ist->file_index = nb_input_files;
          ist->discard = 1;
          st->discard  = AVDISCARD_ALL;
 -        ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st);
 +        ist->opts = filter_codec_opts(codec_opts, choose_decoder(o, ic, st), ic, st);
  
          ist->ts_scale = 1.0;
          MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
  
 +        MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
 +        if (codec_tag) {
 +            uint32_t tag = strtol(codec_tag, &next, 0);
 +            if (*next)
 +                tag = AV_RL32(codec_tag);
 +            st->codec->codec_tag = tag;
 +        }
 +
          ist->dec = choose_decoder(o, ic, st);
  
          switch (dec->codec_type) {
          case AVMEDIA_TYPE_VIDEO:
 +            if(!ist->dec)
 +                ist->dec = avcodec_find_decoder(dec->codec_id);
 +            if (dec->lowres) {
 +                dec->flags |= CODEC_FLAG_EMU_EDGE;
 +            }
 +
              ist->resample_height  = dec->height;
              ist->resample_width   = dec->width;
              ist->resample_pix_fmt = dec->pix_fmt;
              break;
          case AVMEDIA_TYPE_DATA:
          case AVMEDIA_TYPE_SUBTITLE:
 +            if(!ist->dec)
 +                ist->dec = avcodec_find_decoder(dec->codec_id);
 +            break;
          case AVMEDIA_TYPE_ATTACHMENT:
          case AVMEDIA_TYPE_UNKNOWN:
              break;
  
  static void assert_file_overwrite(const char *filename)
  {
 -    if (!file_overwrite &&
 +    if ((!file_overwrite || no_file_overwrite) &&
          (strchr(filename, ':') == NULL || filename[1] == ':' ||
           av_strstart(filename, "file:", NULL))) {
          if (avio_check(filename, 0) == 0) {
 -            if (!using_stdin) {
 +            if (!using_stdin && (!no_file_overwrite || file_overwrite)) {
                  fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
                  fflush(stderr);
 +                term_exit();
 +                signal(SIGINT, SIG_DFL);
                  if (!read_yesno()) {
 -                    fprintf(stderr, "Not overwriting - exiting\n");
 +                    av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
                      exit_program(1);
                  }
 +                term_init();
              }
              else {
 -                fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
 +                av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
                  exit_program(1);
              }
          }
@@@ -4293,16 -3637,10 +4297,16 @@@ static int opt_input_file(OptionsContex
      if (o->nb_frame_pix_fmts)
          av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
  
 +    ic->video_codec_id   = video_codec_name ?
 +        find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0)->id : CODEC_ID_NONE;
 +    ic->audio_codec_id   = audio_codec_name ?
 +        find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0)->id : CODEC_ID_NONE;
 +    ic->subtitle_codec_id= subtitle_codec_name ?
 +        find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0)->id : CODEC_ID_NONE;
      ic->flags |= AVFMT_FLAG_NONBLOCK;
      ic->interrupt_callback = int_cb;
  
 -    /* open the input file with generic libav function */
 +    /* open the input file with generic avformat function */
      err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
      if (err < 0) {
          print_error(filename, err);
          av_dict_free(&opts[i]);
      av_freep(&opts);
  
 -    reset_options(o);
 +    reset_options(o, 1);
      return 0;
  }
  
 -static void parse_forced_key_frames(char *kf, OutputStream *ost,
 -                                    AVCodecContext *avctx)
 +static void parse_forced_key_frames(char *kf, OutputStream *ost)
  {
      char *p;
      int n = 1, i;
 -    int64_t t;
  
      for (p = kf; *p; p++)
          if (*p == ',')
          av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
          exit_program(1);
      }
 +    p = kf;
      for (i = 0; i < n; i++) {
 -        p = i ? strchr(p, ',') + 1 : kf;
 -        t = parse_time_or_die("force_key_frames", p, 1);
 -        ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
 +        char *next = strchr(p, ',');
 +        if (next) *next++ = 0;
 +        ost->forced_kf_pts[i] = parse_time_or_die("force_key_frames", p, 1);
 +        p = next;
      }
  }
  
@@@ -4461,7 -3799,7 +4465,7 @@@ static void choose_encoder(OptionsConte
      }
  }
  
 -static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
 +static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
  {
      OutputStream *ost;
      AVStream *st = avformat_new_stream(oc, NULL);
      st->codec->codec_type = type;
      choose_encoder(o, oc, ost);
      if (ost->enc) {
 -        ost->opts  = filter_codec_opts(codec_opts, ost->enc->id, oc, st);
 +        ost->opts  = filter_codec_opts(codec_opts, ost->enc, oc, st);
      }
  
      avcodec_get_context_defaults3(st->codec, ost->enc);
          st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
  
      av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
 +    av_opt_get_int   (swr_opts, "dither_method", 0, &ost->swr_dither_method);
 +    av_opt_get_double(swr_opts, "dither_scale" , 0, &ost->swr_dither_scale);
  
 -    ost->pix_fmts[0] = ost->pix_fmts[1] = PIX_FMT_NONE;
 +    ost->source_index = source_index;
 +    if (source_index >= 0) {
 +        ost->sync_ist = input_streams[source_index];
 +        input_streams[source_index]->discard = 0;
 +        input_streams[source_index]->st->discard = AVDISCARD_NONE;
 +    }
  
      return ost;
  }
@@@ -4591,13 -3922,13 +4595,13 @@@ static void parse_matrix_coeffs(uint16_
      }
  }
  
 -static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
 +static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
  {
      AVStream *st;
      OutputStream *ost;
      AVCodecContext *video_enc;
  
 -    ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
 +    ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
      st  = ost->st;
      video_enc = st->codec;
  
          }
  
          MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
 -        if (frame_aspect_ratio)
 -            ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
 +        if (frame_aspect_ratio) {
 +            AVRational q;
 +            if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
 +                q.num <= 0 || q.den <= 0) {
 +                av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
 +                exit_program(1);
 +            }
 +            ost->frame_aspect_ratio = av_q2d(q);
 +        }
  
 +        video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
          MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
 +        if (frame_pix_fmt && *frame_pix_fmt == '+') {
 +            ost->keep_pix_fmt = 1;
 +            if (!*++frame_pix_fmt)
 +                frame_pix_fmt = NULL;
 +        }
          if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
              av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
              exit_program(1);
          }
          st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
  
 +        if (intra_only)
 +            video_enc->gop_size = 0;
          MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
          if (intra_matrix) {
              if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
                  av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
                  exit_program(1);
              }
 +            /* FIXME realloc failure */
              video_enc->rc_override =
                  av_realloc(video_enc->rc_override,
                             sizeof(RcOverride) * (i + 1));
              video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
          video_enc->intra_dc_precision = intra_dc_precision - 8;
  
 +        if (do_psnr)
 +            video_enc->flags|= CODEC_FLAG_PSNR;
 +
          /* two pass mode */
          if (do_pass) {
 -            if (do_pass == 1) {
 +            if (do_pass & 1) {
                  video_enc->flags |= CODEC_FLAG_PASS1;
 -            } else {
 +            }
 +            if (do_pass & 2) {
                  video_enc->flags |= CODEC_FLAG_PASS2;
              }
          }
  
          MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
          if (forced_key_frames)
 -            parse_forced_key_frames(forced_key_frames, ost, video_enc);
 +            parse_forced_key_frames(forced_key_frames, ost);
  
          MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
  
      return ost;
  }
  
 -static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
 +static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
  {
 +    int n;
      AVStream *st;
      OutputStream *ost;
      AVCodecContext *audio_enc;
  
 -    ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
 +    ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
      st  = ost->st;
  
      audio_enc = st->codec;
      audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
  
      if (!ost->stream_copy) {
 -        char *sample_fmt = NULL, *filters = NULL;;
 +        char *sample_fmt = NULL, *filters = NULL;
  
          MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
  
          MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
          if (filters)
              ost->avfilter = av_strdup(filters);
 +
 +        /* check for channel mapping for this audio stream */
 +        for (n = 0; n < o->nb_audio_channel_maps; n++) {
 +            AudioChannelMap *map = &o->audio_channel_maps[n];
 +            InputStream *ist = input_streams[ost->source_index];
 +            if ((map->channel_idx == -1 || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) &&
 +                (map->ofile_idx   == -1 || ost->file_index == map->ofile_idx) &&
 +                (map->ostream_idx == -1 || ost->st->index  == map->ostream_idx)) {
 +                if (ost->audio_channels_mapped < FF_ARRAY_ELEMS(ost->audio_channels_map))
 +                    ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
 +                else
 +                    av_log(NULL, AV_LOG_FATAL, "Max channel mapping for output %d.%d reached\n",
 +                           ost->file_index, ost->st->index);
 +            }
 +        }
      }
  
      return ost;
  }
  
 -static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
 +static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
  {
      OutputStream *ost;
  
 -    ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
 +    ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
      if (!ost->stream_copy) {
          av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
          exit_program(1);
      return ost;
  }
  
 -static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc)
 +static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
  {
 -    OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT);
 +    OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
      ost->stream_copy = 1;
      return ost;
  }
  
 -static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc)
 +static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
  {
      AVStream *st;
      OutputStream *ost;
      AVCodecContext *subtitle_enc;
  
 -    ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE);
 +    ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
      st  = ost->st;
      subtitle_enc = st->codec;
  
      subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
  
 +    MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc, st);
 +
      return ost;
  }
  
@@@ -4828,7 -4121,7 +4832,7 @@@ static int opt_streamid(OptionsContext 
          exit_program(1);
      }
      *p++ = '\0';
 -    idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, INT_MAX);
 +    idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
      o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
      o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
      return 0;
@@@ -4866,7 -4159,7 +4870,7 @@@ static int copy_chapters(InputFile *ifi
              av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
  
          os->nb_chapters++;
 -        os->chapters = av_realloc(os->chapters, sizeof(AVChapter) * os->nb_chapters);
 +        os->chapters = av_realloc_f(os->chapters, os->nb_chapters, sizeof(AVChapter));
          if (!os->chapters)
              return AVERROR(ENOMEM);
          os->chapters[os->nb_chapters - 1] = out_ch;
      return 0;
  }
  
 +static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
 +{
 +    int i, err;
 +    AVFormatContext *ic = avformat_alloc_context();
 +
 +    ic->interrupt_callback = int_cb;
 +    err = avformat_open_input(&ic, filename, NULL, NULL);
 +    if (err < 0)
 +        return err;
 +    /* copy stream format */
 +    for(i=0;i<ic->nb_streams;i++) {
 +        AVStream *st;
 +        OutputStream *ost;
 +        AVCodec *codec;
 +        AVCodecContext *avctx;
 +
 +        codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
 +        ost   = new_output_stream(o, s, codec->type, -1);
 +        st    = ost->st;
 +        avctx = st->codec;
 +        ost->enc = codec;
 +
 +        // FIXME: a more elegant solution is needed
 +        memcpy(st, ic->streams[i], sizeof(AVStream));
 +        st->cur_dts = 0;
 +        st->info = av_malloc(sizeof(*st->info));
 +        memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
 +        st->codec= avctx;
 +        avcodec_copy_context(st->codec, ic->streams[i]->codec);
 +
 +        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
 +            choose_sample_fmt(st, codec);
 +        else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
 +            choose_pixel_fmt(st, codec, st->codec->pix_fmt);
 +    }
 +
 +    avformat_close_input(&ic);
 +    return 0;
 +}
 +
  static void init_output_filter(OutputFilter *ofilter, OptionsContext *o,
                                 AVFormatContext *oc)
  {
      OutputStream *ost;
  
      switch (ofilter->out_tmp->filter_ctx->output_pads[ofilter->out_tmp->pad_idx].type) {
 -    case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc); break;
 -    case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc); break;
 +    case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc, -1); break;
 +    case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc, -1); break;
      default:
          av_log(NULL, AV_LOG_FATAL, "Only video and audio filters are supported "
                 "currently.\n");
@@@ -4964,13 -4217,30 +4968,13 @@@ static void opt_output_file(void *optct
      if (!strcmp(filename, "-"))
          filename = "pipe:";
  
 -    oc = avformat_alloc_context();
 +    err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
      if (!oc) {
 -        print_error(filename, AVERROR(ENOMEM));
 +        print_error(filename, err);
          exit_program(1);
      }
 -
 -    if (o->format) {
 -        file_oformat = av_guess_format(o->format, NULL, NULL);
 -        if (!file_oformat) {
 -            av_log(NULL, AV_LOG_FATAL, "Requested output format '%s' is not a suitable output format\n", o->format);
 -            exit_program(1);
 -        }
 -    } else {
 -        file_oformat = av_guess_format(NULL, filename, NULL);
 -        if (!file_oformat) {
 -            av_log(NULL, AV_LOG_FATAL, "Unable to find a suitable output format for '%s'\n",
 -                   filename);
 -            exit_program(1);
 -        }
 -    }
 -
 -    oc->oformat = file_oformat;
 +    file_oformat= oc->oformat;
      oc->interrupt_callback = int_cb;
 -    av_strlcpy(oc->filename, filename, sizeof(oc->filename));
  
      /* create streams for all unlabeled output pads */
      for (i = 0; i < nb_filtergraphs; i++) {
          }
      }
  
 -    if (!o->nb_stream_maps) {
 -        /* pick the "best" stream of each type */
 -#define NEW_STREAM(type, index)\
 -        if (index >= 0) {\
 -            ost = new_ ## type ## _stream(o, oc);\
 -            ost->source_index = index;\
 -            ost->sync_ist     = input_streams[index];\
 -            input_streams[index]->discard = 0;\
 -            input_streams[index]->st->discard = AVDISCARD_NONE;\
 +    if (!strcmp(file_oformat->name, "ffm") &&
 +        av_strstart(filename, "http:", NULL)) {
 +        int j;
 +        /* special case for files sent to ffserver: we get the stream
 +           parameters from ffserver */
 +        int err = read_ffserver_streams(o, oc, filename);
 +        if (err < 0) {
 +            print_error(filename, err);
 +            exit_program(1);
          }
 +        for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {
 +            ost = output_streams[j];
 +            for (i = 0; i < nb_input_streams; i++) {
 +                ist = input_streams[i];
 +                if(ist->st->codec->codec_type == ost->st->codec->codec_type){
 +                    ost->sync_ist= ist;
 +                    ost->source_index= i;
 +                    ist->discard = 0;
 +                    ist->st->discard = AVDISCARD_NONE;
 +                    break;
 +                }
 +            }
 +            if(!ost->sync_ist){
 +                av_log(NULL, AV_LOG_FATAL, "Missing %s stream which is required by this ffm\n", av_get_media_type_string(ost->st->codec->codec_type));
 +                exit_program(1);
 +            }
 +        }
 +    } else if (!o->nb_stream_maps) {
 +        /* pick the "best" stream of each type */
  
          /* video: highest resolution */
          if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
                      idx = i;
                  }
              }
 -            NEW_STREAM(video, idx);
 +            if (idx >= 0)
 +                new_video_stream(o, oc, idx);
          }
  
          /* audio: most channels */
                      idx = i;
                  }
              }
 -            NEW_STREAM(audio, idx);
 +            if (idx >= 0)
 +                new_audio_stream(o, oc, idx);
          }
  
          /* subtitles: pick first */
 -        if (!o->subtitle_disable && oc->oformat->subtitle_codec != CODEC_ID_NONE) {
 +        if (!o->subtitle_disable && (oc->oformat->subtitle_codec != CODEC_ID_NONE || subtitle_codec_name)) {
              for (i = 0; i < nb_input_streams; i++)
                  if (input_streams[i]->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
 -                    NEW_STREAM(subtitle, i);
 +                    new_subtitle_stream(o, oc, i);
                      break;
                  }
          }
      } else {
          for (i = 0; i < o->nb_stream_maps; i++) {
              StreamMap *map = &o->stream_maps[i];
 +            int src_idx = input_files[map->file_index]->ist_index + map->stream_index;
  
              if (map->disabled)
                  continue;
@@@ -5091,42 -4339,27 +5095,42 @@@ loop_end
                  init_output_filter(ofilter, o, oc);
              } else {
                  ist = input_streams[input_files[map->file_index]->ist_index + map->stream_index];
 +                if(o->subtitle_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
 +                    continue;
 +                if(o->   audio_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
 +                    continue;
 +                if(o->   video_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
 +                    continue;
 +                if(o->    data_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_DATA)
 +                    continue;
 +
                  switch (ist->st->codec->codec_type) {
 -                case AVMEDIA_TYPE_VIDEO:    ost = new_video_stream(o, oc);    break;
 -                case AVMEDIA_TYPE_AUDIO:    ost = new_audio_stream(o, oc);    break;
 -                case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc); break;
 -                case AVMEDIA_TYPE_DATA:     ost = new_data_stream(o, oc);     break;
 -                case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc); break;
 +                case AVMEDIA_TYPE_VIDEO:      ost = new_video_stream     (o, oc, src_idx); break;
 +                case AVMEDIA_TYPE_AUDIO:      ost = new_audio_stream     (o, oc, src_idx); break;
 +                case AVMEDIA_TYPE_SUBTITLE:   ost = new_subtitle_stream  (o, oc, src_idx); break;
 +                case AVMEDIA_TYPE_DATA:       ost = new_data_stream      (o, oc, src_idx); break;
 +                case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;
                  default:
                      av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
                             map->file_index, map->stream_index);
                      exit_program(1);
                  }
 -
 -                ost->source_index = input_files[map->file_index]->ist_index + map->stream_index;
 -                ost->sync_ist     = input_streams[input_files[map->sync_file_index]->ist_index +
 -                                               map->sync_stream_index];
 -                ist->discard = 0;
 -                ist->st->discard = AVDISCARD_NONE;
              }
          }
      }
  
 +
 +    for (i = nb_output_streams - oc->nb_streams; i < nb_output_streams; i++) { //for all streams of this output file
 +        AVDictionaryEntry *e;
 +        ost = output_streams[i];
 +
 +        if (   ost->stream_copy
 +            && (e = av_dict_get(codec_opts, "flags", NULL, AV_DICT_IGNORE_SUFFIX))
 +            && (!e->key[5] || check_stream_specifier(oc, ost->st, e->key+6)))
 +            if (av_opt_set(ost->st->codec, "flags", e->value, 0) < 0)
 +                exit_program(1);
 +    }
 +
      /* handle attached files */
      for (i = 0; i < o->nb_attachments; i++) {
          AVIOContext *pb;
          }
          avio_read(pb, attachment, len);
  
 -        ost = new_attachment_stream(o, oc);
 +        ost = new_attachment_stream(o, oc, -1);
          ost->stream_copy               = 0;
 -        ost->source_index              = -1;
          ost->attachment_filename       = o->attachments[i];
          ost->st->codec->extradata      = attachment;
          ost->st->codec->extradata_size = len;
          av_dict_set(&output_files[nb_output_files - 1]->opts, "preload", buf, 0);
      }
      oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
 -    oc->flags |= AVFMT_FLAG_NONBLOCK;
  
      /* copy metadata */
      for (i = 0; i < o->nb_metadata_map; i++) {
          char *p;
          int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
  
 -        if (in_file_index < 0)
 -            continue;
          if (in_file_index >= nb_input_files) {
              av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
              exit_program(1);
          }
 -        copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, input_files[in_file_index]->ctx, o);
 +        copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, in_file_index >= 0 ? input_files[in_file_index]->ctx : NULL, o);
      }
  
      /* copy chapters */
                        !o->metadata_chapters_manual);
  
      /* copy global metadata by default */
 -    if (!o->metadata_global_manual && nb_input_files)
 +    if (!o->metadata_global_manual && nb_input_files){
          av_dict_copy(&oc->metadata, input_files[0]->ctx->metadata,
                       AV_DICT_DONT_OVERWRITE);
 +        if(o->recording_time != INT64_MAX)
 +            av_dict_set(&oc->metadata, "duration", NULL, 0);
 +    }
      if (!o->metadata_streams_manual)
          for (i = output_files[nb_output_files - 1]->ost_index; i < nb_output_streams; i++) {
              InputStream *ist;
          AVDictionary **m;
          char type, *val;
          const char *stream_spec;
 -        int index = 0, j, ret;
 +        int index = 0, j, ret = 0;
  
          val = strchr(o->metadata[i].u.str, '=');
          if (!val) {
          }
      }
  
 -    reset_options(o);
 +    reset_options(o, 0);
  }
  
  /* same option as mencoder */
  static int opt_pass(const char *opt, const char *arg)
  {
 -    do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 2);
 +    do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 3);
      return 0;
  }
  
 -static int64_t getutime(void)
 -{
 -#if HAVE_GETRUSAGE
 -    struct rusage rusage;
 -
 -    getrusage(RUSAGE_SELF, &rusage);
 -    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
 -#elif HAVE_GETPROCESSTIMES
 -    HANDLE proc;
 -    FILETIME c, e, k, u;
 -    proc = GetCurrentProcess();
 -    GetProcessTimes(proc, &c, &e, &k, &u);
 -    return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
 -#else
 -    return av_gettime();
 -#endif
 -}
 -
  static int64_t getmaxrss(void)
  {
  #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
@@@ -5331,12 -4583,12 +5335,12 @@@ static int opt_audio_qscale(OptionsCont
  
  static void show_usage(void)
  {
 -    printf("Hyper fast Audio and Video encoder\n");
 -    printf("usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
 -    printf("\n");
 +    av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
 +    av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
 +    av_log(NULL, AV_LOG_INFO, "\n");
  }
  
 -static void show_help(void)
 +static int opt_help(const char *opt, const char *arg)
  {
      int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
      av_log_set_callback(log_callback_help);
      show_help_children(avcodec_get_class(), flags);
      show_help_children(avformat_get_class(), flags);
      show_help_children(sws_get_class(), flags);
 +
 +    return 0;
  }
  
  static int opt_target(OptionsContext *o, const char *opt, const char *arg)
          parse_option(o, "r", frame_rates[norm], options);
          opt_default("g", norm == PAL ? "15" : "18");
  
 -        opt_default("b", "1150000");
 +        opt_default("b:v", "1150000");
          opt_default("maxrate", "1150000");
          opt_default("minrate", "1150000");
          opt_default("bufsize", "327680"); // 40*1024*8;
  
          parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
          parse_option(o, "r", frame_rates[norm], options);
 +        parse_option(o, "pix_fmt", "yuv420p", options);
          opt_default("g", norm == PAL ? "15" : "18");
  
 -        opt_default("b", "2040000");
 +        opt_default("b:v", "2040000");
          opt_default("maxrate", "2516000");
          opt_default("minrate", "0"); // 1145000;
          opt_default("bufsize", "1835008"); // 224*1024*8;
 -        opt_default("flags", "+scan_offset");
 +        opt_default("scan_offset", "1");
  
  
          opt_default("b:a", "224000");
  
          parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
          parse_option(o, "r", frame_rates[norm], options);
 +        parse_option(o, "pix_fmt", "yuv420p", options);
          opt_default("g", norm == PAL ? "15" : "18");
  
 -        opt_default("b", "6000000");
 +        opt_default("b:v", "6000000");
          opt_default("maxrate", "9000000");
          opt_default("minrate", "0"); // 1500000;
          opt_default("bufsize", "1835008"); // 224*1024*8;
@@@ -5543,103 -4791,19 +5547,103 @@@ static int opt_data_frames(OptionsConte
      return parse_option(o, "frames:d", arg, options);
  }
  
 -static int opt_video_tag(OptionsContext *o, const char *opt, const char *arg)
 +static int opt_preset(OptionsContext *o, const char *opt, const char *arg)
 +{
 +    FILE *f=NULL;
 +    char filename[1000], line[1000], tmp_line[1000];
 +    const char *codec_name = *opt == 'v' ? video_codec_name :
 +                             *opt == 'a' ? audio_codec_name :
 +                                           subtitle_codec_name;
 +
 +    if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
 +        if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
 +            av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
 +        }else
 +            av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
 +        exit_program(1);
 +    }
 +
 +    while (fgets(line, sizeof(line), f)) {
 +        char *key = tmp_line, *value, *endptr;
 +
 +        if (strcspn(line, "#\n\r") == 0)
 +            continue;
 +        strcpy(tmp_line, line);
 +        if (!av_strtok(key,   "=",    &value) ||
 +            !av_strtok(value, "\r\n", &endptr)) {
 +            av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
 +            exit_program(1);
 +        }
 +        av_log(NULL, AV_LOG_DEBUG, "ffpreset[%s]: set '%s' = '%s'\n", filename, key, value);
 +
 +        if      (!strcmp(key, "acodec")) opt_audio_codec   (o, key, value);
 +        else if (!strcmp(key, "vcodec")) opt_video_codec   (o, key, value);
 +        else if (!strcmp(key, "scodec")) opt_subtitle_codec(o, key, value);
 +        else if (!strcmp(key, "dcodec")) opt_data_codec    (o, key, value);
 +        else if (opt_default(key, value) < 0) {
 +            av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n",
 +                   filename, line, key, value);
 +            exit_program(1);
 +        }
 +    }
 +
 +    fclose(f);
 +
 +    return 0;
 +}
 +
 +static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
 +{
 +}
 +
 +static int opt_passlogfile(const char *opt, const char *arg)
 +{
 +    pass_logfilename_prefix = arg;
 +#if CONFIG_LIBX264_ENCODER
 +    return opt_default(opt, arg);
 +#else
 +    return 0;
 +#endif
 +}
 +
 +static int opt_old2new(OptionsContext *o, const char *opt, const char *arg)
 +{
 +    char *s = av_asprintf("%s:%c", opt + 1, *opt);
 +    int ret = parse_option(o, s, arg, options);
 +    av_free(s);
 +    return ret;
 +}
 +
 +static int opt_bitrate(OptionsContext *o, const char *opt, const char *arg)
  {
 -    return parse_option(o, "tag:v", arg, options);
 +    if(!strcmp(opt, "b")){
 +        av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
 +        return parse_option(o, "b:v", arg, options);
 +    }
 +    return opt_default(opt, arg);
  }
  
 -static int opt_audio_tag(OptionsContext *o, const char *opt, const char *arg)
 +static int opt_qscale(OptionsContext *o, const char *opt, const char *arg)
  {
 -    return parse_option(o, "tag:a", arg, options);
 +    char *s;
 +    int ret;
 +    if(!strcmp(opt, "qscale")){
 +        av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
 +        return parse_option(o, "q:v", arg, options);
 +    }
 +    s = av_asprintf("q%s", opt + 6);
 +    ret = parse_option(o, s, arg, options);
 +    av_free(s);
 +    return ret;
  }
  
 -static int opt_subtitle_tag(OptionsContext *o, const char *opt, const char *arg)
 +static int opt_profile(OptionsContext *o, const char *opt, const char *arg)
  {
 -    return parse_option(o, "tag:s", arg, options);
 +    if(!strcmp(opt, "profile")){
 +        av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
 +        return parse_option(o, "profile:v", arg, options);
 +    }
 +    return opt_default(opt, arg);
  }
  
  static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
@@@ -5657,7 -4821,6 +5661,7 @@@ static int opt_vsync(const char *opt, c
      if      (!av_strcasecmp(arg, "cfr"))         video_sync_method = VSYNC_CFR;
      else if (!av_strcasecmp(arg, "vfr"))         video_sync_method = VSYNC_VFR;
      else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
 +    else if (!av_strcasecmp(arg, "drop"))        video_sync_method = VSYNC_DROP;
  
      if (video_sync_method == VSYNC_AUTO)
          video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
@@@ -5671,6 -4834,17 +5675,6 @@@ static int opt_deinterlace(const char *
      return 0;
  }
  
 -static int opt_cpuflags(const char *opt, const char *arg)
 -{
 -    int flags = av_parse_cpu_flags(arg);
 -
 -    if (flags < 0)
 -        return flags;
 -
 -    av_set_cpu_flags_mask(flags);
 -    return 0;
 -}
 -
  static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
  {
      int idx = locate_option(argc, argv, options, "cpuflags");
@@@ -5731,12 -4905,10 +5735,12 @@@ static const OptionDef options[] = 
      { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
      { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
      { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
 +    { "n", OPT_BOOL, {(void*)&no_file_overwrite}, "do not overwrite output files" },
      { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
      { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
      { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
      { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
 +    { "map_channel", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map_channel}, "map an audio channel from one stream to another", "file.stream.channel[:syncfile.syncstream]" },
      { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata_map)}, "set metadata information of outfile from infile",
        "outfile[,metadata]:infile[,metadata]" },
      { "map_chapters",  OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)},  "set chapters mapping", "input_file_index" },
      { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
      { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
      { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
 +    { "timestamp", HAS_ARG | OPT_FUNC2, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
      { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
      { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
      { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
        "add timings for benchmarking" },
 +    { "benchmark_all", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark_all},
 +      "add timings for each task" },
      { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
      { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
        "dump each input packet" },
      { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
      { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
      { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
 -    { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying" },
 +    { "copytb", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying", "mode" },
      { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
      { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
 +    { "dts_error_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_error_threshold}, "timestamp error delta threshold", "threshold" },
      { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
      { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
      { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
      { "tag",   OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
      { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
 -    { "qscale", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
 +    { "qscale", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_qscale}, "use fixed quality scale (VBR)", "q" },
 +    { "profile", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_profile}, "set profile", "profile" },
      { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
      { "filter_complex", HAS_ARG | OPT_EXPERT, {(void*)opt_filter_complex}, "create a complex filtergraph", "graph_description" },
      { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
      { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
      { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
 -    { "cpuflags", HAS_ARG | OPT_EXPERT, {(void*)opt_cpuflags}, "set CPU flags mask", "mask" },
 +    { "debug_ts", OPT_BOOL | OPT_EXPERT, {&debug_ts}, "print timestamp debugging info" },
  
      /* video options */
      { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
      { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
      { "aspect", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_aspect_ratios)}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
      { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
 +    { "bits_per_raw_sample", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&frame_bits_per_raw_sample}, "set the number of bits per raw sample", "number" },
 +    { "croptop",  HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
 +    { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
 +    { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
 +    { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
 +    { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
 +    { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
 +    { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
 +    { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
 +    { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
 +    { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "deprecated use -g 1"},
      { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
      { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
      { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
      { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
 +    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant}, "use same quantizer as source (implies VBR)" },
      { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
        "use same quantizer as source (implies VBR)" },
      { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
 -    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename_prefix}, "select two pass log file name prefix", "prefix" },
 +    { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
      { "deinterlace", OPT_EXPERT | OPT_VIDEO, {(void*)opt_deinterlace},
        "this option is deprecated, use the yadif filter instead" },
 +    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
      { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
      { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
      { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
      { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
      { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
      { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
 -    { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
 +    { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_old2new}, "force video tag/fourcc", "fourcc/tag" },
      { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
      { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
      { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
      { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(forced_key_frames)}, "force key frames at specified timestamps", "timestamps" },
 +    { "b", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_bitrate}, "video bitrate (please use -b:v)", "bitrate" },
  
      /* audio options */
      { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
      { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
      { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
      { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
 -    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
 +    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_old2new}, "force audio tag/fourcc", "fourcc/tag" },
      { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
      { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
      { "channel_layout", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_channel_layout}, "set channel layout", "layout" },
      /* subtitle options */
      { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
      { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
 -    { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
 +    { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_old2new}, "force subtitle tag/fourcc", "fourcc/tag" },
  
      /* grab options */
 +    { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "deprecated, use -channel", "channel" },
 +    { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "deprecated, use -standard", "standard" },
      { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
  
      /* muxer options */
      { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)},   "set the initial demux-decode delay", "seconds" },
  
      { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
 +    { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "audio bitstream_filters" },
 +    { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "video bitstream_filters" },
  
 +    { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
 +    { "vpre", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
 +    { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
 +    { "fpre", HAS_ARG | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
      /* data codec support */
      { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
 +    { "dn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(data_disable)}, "disable data" },
  
      { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
      { NULL, },
@@@ -5872,18 -5016,11 +5876,18 @@@ int main(int argc, char **argv
      OptionsContext o = { 0 };
      int64_t ti;
  
 -    reset_options(&o);
 +    reset_options(&o, 0);
  
      av_log_set_flags(AV_LOG_SKIP_REPEATED);
      parse_loglevel(argc, argv, options);
  
 +    if(argc>1 && !strcmp(argv[1], "-d")){
 +        run_as_daemon=1;
 +        av_log_set_callback(log_callback_null);
 +        argc--;
 +        argv++;
 +    }
 +
      avcodec_register_all();
  #if CONFIG_AVDEVICE
      avdevice_register_all();
      av_register_all();
      avformat_network_init();
  
 -    show_banner();
 +    show_banner(argc, argv, options);
 +
 +    term_init();
  
      parse_cpuflags(argc, argv, options);
  
  
      /* file converter / grab */
      if (nb_output_files <= 0) {
 -        fprintf(stderr, "At least one output file must be specified\n");
 +        av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
          exit_program(1);
      }
  
          exit_program(1);
      }
  
 -    ti = getutime();
 +    current_time = ti = getutime();
      if (transcode() < 0)
          exit_program(1);
      ti = getutime() - ti;
diff --combined libavformat/movenchint.c
index 1ee59877d26fd56a926aea9f02cb90999b61cb5c,5ef90f154ad420f8d1c3871036407f2ff6c47129..9c4ddeb3720daaa48ece9e9777c34f86fc94c2f1
@@@ -2,20 -2,20 +2,20 @@@
   * MOV, 3GP, MP4 muxer RTP hinting
   * Copyright (c) 2010 Martin Storsjo
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
@@@ -43,9 -43,9 +43,9 @@@ int ff_mov_init_hinting(AVFormatContex
      track->enc->codec_type = AVMEDIA_TYPE_DATA;
      track->enc->codec_tag  = track->tag;
  
-     track->rtp_ctx = ff_rtp_chain_mux_open(s, src_st, NULL,
-                                            RTP_MAX_PACKET_SIZE);
-     if (!track->rtp_ctx)
+     ret = ff_rtp_chain_mux_open(&track->rtp_ctx, s, src_st, NULL,
+                                 RTP_MAX_PACKET_SIZE);
+     if (ret < 0)
          goto fail;
  
      /* Copy the RTP AVStream timebase back to the hint AVStream */
diff --combined libavformat/rtmpproto.c
index 0f643e6c8a3156d7a01b80fb44dc50907991c645,807e899f3408cbfe9252b5113366ea9db6c6b8ae..a9e39a50bba614d7fd4f6825ecd10cce13034627
@@@ -2,20 -2,20 +2,20 @@@
   * RTMP network protocol
   * Copyright (c) 2009 Kostya Shishkov
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
@@@ -886,7 -886,7 +886,7 @@@ static int get_packet(URLContext *s, in
              }
          }
          rt->bytes_read += ret;
 -        if (rt->bytes_read > rt->last_bytes_read + rt->client_report_size) {
 +        if (rt->bytes_read - rt->last_bytes_read > rt->client_report_size) {
              av_log(s, AV_LOG_DEBUG, "Sending bytes read report\n");
              if ((ret = gen_bytes_read(s, rt, rpkt.timestamp + 1)) < 0)
                  return ret;
@@@ -1037,9 -1037,10 +1037,10 @@@ static int rtmp_open(URLContext *s, con
              fname = next;
              rt->app[0] = '\0';
          } else {
+             // make sure we do not mismatch a playpath for an application instance
              char *c = strchr(p + 1, ':');
              fname = strchr(p + 1, '/');
-             if (!fname || c < fname) {
+             if (!fname || (c && c < fname)) {
                  fname = p + 1;
                  av_strlcpy(rt->app, path + 1, p - path);
              } else {
diff --combined libavformat/rtpenc.c
index c2736b17289eb2e9669867b4c757feebc4f6500f,71eeb7e32f32bc346cd88c1141b9b6f66a502005..57d025a3644d97ac1ba9f8234b4cba8d9c561095
@@@ -2,20 -2,20 +2,20 @@@
   * RTP output format
   * Copyright (c) 2002 Fabrice Bellard
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
@@@ -33,6 -33,7 +33,7 @@@
  static const AVOption options[] = {
      FF_RTP_FLAG_OPTS(RTPMuxContext, flags)
      { "payload_type", "Specify RTP payload type", offsetof(RTPMuxContext, payload_type), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, 127, AV_OPT_FLAG_ENCODING_PARAM },
+     { "ssrc", "Stream identifier", offsetof(RTPMuxContext, ssrc), AV_OPT_TYPE_INT, { 0 }, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
      { NULL },
  };
  
@@@ -91,7 -92,7 +92,7 @@@ static int rtp_write_header(AVFormatCon
      }
      st = s1->streams[0];
      if (!is_supported(st->codec->codec_id)) {
 -        av_log(s1, AV_LOG_ERROR, "Unsupported codec %x\n", st->codec->codec_id);
 +        av_log(s1, AV_LOG_ERROR, "Unsupported codec %s\n", avcodec_get_name(st->codec->codec_id));
  
          return -1;
      }
      s->base_timestamp = av_get_random_seed();
      s->timestamp = s->base_timestamp;
      s->cur_timestamp = 0;
-     s->ssrc = av_get_random_seed();
+     if (!s->ssrc)
+         s->ssrc = av_get_random_seed();
      s->first_packet = 1;
      s->first_rtcp_ntp_time = ff_ntp_time();
      if (s1->start_time_realtime)
index e4edfc28e1e71b42cfa4ff66e11ed920fe9d296b,374209931406bc560e5e900d82ea08d66466a7bf..c0f9530ac8f52457ca097e3ad331dda6e407f8e0
@@@ -2,20 -2,20 +2,20 @@@
   * RTP muxer chaining code
   * Copyright (c) 2010 Martin Storsjo
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
  #include "avio_internal.h"
  #include "libavutil/opt.h"
  
AVFormatContext *ff_rtp_chain_mux_open(AVFormatContext *s, AVStream *st,
-                                        URLContext *handle, int packet_size)
int ff_rtp_chain_mux_open(AVFormatContext **out, AVFormatContext *s,
+                           AVStream *st, URLContext *handle, int packet_size)
  {
-     AVFormatContext *rtpctx;
+     AVFormatContext *rtpctx = NULL;
      int ret;
      AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
      uint8_t *rtpflags;
      AVDictionary *opts = NULL;
  
-     if (!rtp_format)
-         return NULL;
+     if (!rtp_format) {
+         ret = AVERROR(ENOSYS);
+         goto fail;
+     }
  
      /* Allocate an AVFormatContext for each output stream */
      rtpctx = avformat_alloc_context();
-     if (!rtpctx)
-         return NULL;
+     if (!rtpctx) {
+         ret = AVERROR(ENOMEM);
+         goto fail;
+     }
  
      rtpctx->oformat = rtp_format;
      if (!avformat_new_stream(rtpctx, NULL)) {
-         av_free(rtpctx);
-         return NULL;
+         ret = AVERROR(ENOMEM);
+         goto fail;
      }
      /* Pass the interrupt callback on */
      rtpctx->interrupt_callback = s->interrupt_callback;
@@@ -53,7 -57,6 +57,7 @@@
      rtpctx->max_delay = s->max_delay;
      /* Copy other stream parameters. */
      rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
 +    rtpctx->flags |= s->flags & AVFMT_FLAG_MP4A_LATM;
  
      if (av_opt_get(s, "rtpflags", AV_OPT_SEARCH_CHILDREN, &rtpflags) >= 0)
          av_dict_set(&opts, "rtpflags", rtpflags, AV_DICT_DONT_STRDUP_VAL);
              av_free(ptr);
          }
          avformat_free_context(rtpctx);
-         return NULL;
+         return ret;
      }
  
-     return rtpctx;
+     *out = rtpctx;
+     return 0;
+ fail:
+     av_free(rtpctx);
+     if (handle)
+         ffurl_close(handle);
+     return ret;
  }
index 8e6b80aa3feb47292b4508a8006f52e1526831a4,66b9e4cd0aeb2bf99b97e9768e432919df37d66b..1ba361718899f61505ca2adbb935eb127432ce6a
@@@ -2,20 -2,20 +2,20 @@@
   * RTP muxer chaining code
   * Copyright (c) 2010 Martin Storsjo
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
@@@ -25,7 -25,7 +25,7 @@@
  #include "avformat.h"
  #include "url.h"
  
AVFormatContext *ff_rtp_chain_mux_open(AVFormatContext *s, AVStream *st,
-                                        URLContext *handle, int packet_size);
int ff_rtp_chain_mux_open(AVFormatContext **out, AVFormatContext *s,
+                           AVStream *st, URLContext *handle, int packet_size);
  
  #endif /* AVFORMAT_RTPENC_CHAIN_H */
diff --combined libavformat/rtsp.c
index 504b9f850d511313262214c95e8fcb5a42b64fd9,f53aadf191f4a76bdf3b4e4d3511f4a3e8c85965..e3b6e1df5f8320a3ac32315db11dbd0948aa626c
@@@ -2,20 -2,20 +2,20 @@@
   * RTSP/SDP client
   * Copyright (c) 2002 Fabrice Bellard
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
@@@ -606,11 -606,13 +606,13 @@@ static int rtsp_open_transport_ctx(AVFo
          s->ctx_flags |= AVFMTCTX_NOHEADER;
  
      if (s->oformat && CONFIG_RTSP_MUXER) {
-         rtsp_st->transport_priv = ff_rtp_chain_mux_open(s, st,
-                                       rtsp_st->rtp_handle,
-                                       RTSP_TCP_MAX_PACKET_SIZE);
+         int ret = ff_rtp_chain_mux_open(&rtsp_st->transport_priv, s, st,
+                                         rtsp_st->rtp_handle,
+                                         RTSP_TCP_MAX_PACKET_SIZE);
          /* Ownership of rtp_handle is passed to the rtp mux context */
          rtsp_st->rtp_handle = NULL;
+         if (ret < 0)
+             return ret;
      } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
          rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
                                              rtsp_st->dynamic_protocol_context,
@@@ -1179,6 -1181,10 +1181,6 @@@ int ff_rtsp_make_setup_request(AVFormat
      /* default timeout: 1 minute */
      rt->timeout = 60;
  
 -    /* for each stream, make the setup request */
 -    /* XXX: we assume the same server is used for the control of each
 -     * RTSP stream */
 -
      /* Choose a random starting offset within the first half of the
       * port range, to allow for a number of ports to try even if the offset
       * happens to be at the end of the random range. */
                                 &s->interrupt_callback, NULL))
                      goto rtp_opened;
              }
 -
              av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
              err = AVERROR(EIO);
              goto fail;
diff --combined libavformat/sapenc.c
index 609dab4b40c7a540b4fd5286890cdcf4b1c24d86,7e84a3fb991bee39c5fec23fe9a052f3461f3ab7..c1923f31c678bd85da907b98aa1499e10e6393c3
@@@ -2,20 -2,20 +2,20 @@@
   * Session Announcement Protocol (RFC 2974) muxer
   * Copyright (c) 2010 Martin Storsjo
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
@@@ -150,8 -150,10 +150,10 @@@ static int sap_write_header(AVFormatCon
              ret = AVERROR(EIO);
              goto fail;
          }
-         s->streams[i]->priv_data = contexts[i] =
-             ff_rtp_chain_mux_open(s, s->streams[i], fd, 0);
+         ret = ff_rtp_chain_mux_open(&contexts[i], s, s->streams[i], fd, 0);
+         if (ret < 0)
+             goto fail;
+         s->streams[i]->priv_data = contexts[i];
          av_strlcpy(contexts[i]->filename, url, sizeof(contexts[i]->filename));
      }
  
      pos += strlen(&sap->ann[pos]) + 1;
  
      if (av_sdp_create(contexts, s->nb_streams, &sap->ann[pos],
-                        sap->ann_size - pos)) {
+                       sap->ann_size - pos)) {
          ret = AVERROR_INVALIDDATA;
          goto fail;
      }
diff --combined libavformat/version.h
index 1158fdf212a5dcd0859307da8f5e848b14b40c8d,b00701eefa34023a0e6b3051b123be4bdd626eb0..7042990579a468bcf545995dbaf529e5b4a5cb9b
@@@ -1,20 -1,20 +1,20 @@@
  /*
   * Version macros.
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
@@@ -30,8 -30,8 +30,8 @@@
  #include "libavutil/avutil.h"
  
  #define LIBAVFORMAT_VERSION_MAJOR 54
 -#define LIBAVFORMAT_VERSION_MINOR  3
 -#define LIBAVFORMAT_VERSION_MICRO  1
 +#define LIBAVFORMAT_VERSION_MINOR  6
- #define LIBAVFORMAT_VERSION_MICRO 100
++#define LIBAVFORMAT_VERSION_MICRO 101
  
  #define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \
                                                 LIBAVFORMAT_VERSION_MINOR, \
   * Those FF_API_* defines are not part of public API.
   * They may change, break or disappear at any time.
   */
 +#ifndef FF_API_OLD_AVIO
 +#define FF_API_OLD_AVIO                (LIBAVFORMAT_VERSION_MAJOR < 55)
 +#endif
 +#ifndef FF_API_PKT_DUMP
 +#define FF_API_PKT_DUMP                (LIBAVFORMAT_VERSION_MAJOR < 54)
 +#endif
 +#ifndef FF_API_ALLOC_OUTPUT_CONTEXT
 +#define FF_API_ALLOC_OUTPUT_CONTEXT    (LIBAVFORMAT_VERSION_MAJOR < 55)
 +#endif
 +#ifndef FF_API_FORMAT_PARAMETERS
 +#define FF_API_FORMAT_PARAMETERS       (LIBAVFORMAT_VERSION_MAJOR < 55)
 +#endif
 +#ifndef FF_API_NEW_STREAM
 +#define FF_API_NEW_STREAM              (LIBAVFORMAT_VERSION_MAJOR < 55)
 +#endif
 +#ifndef FF_API_SET_PTS_INFO
 +#define FF_API_SET_PTS_INFO            (LIBAVFORMAT_VERSION_MAJOR < 55)
 +#endif
  #ifndef FF_API_CLOSE_INPUT_FILE
  #define FF_API_CLOSE_INPUT_FILE        (LIBAVFORMAT_VERSION_MAJOR < 55)
  #endif
diff --combined libavutil/avutil.h
index ee8b0713832b40e09f7e918b05d8e9dd1980def1,1c8e0767df3287e5973f5340b32cb924eb473637..acef213c1c7128487065adfbf1bd7483fadc6b4b
@@@ -1,20 -1,20 +1,20 @@@
  /*
   * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
   * external API header
   */
  
 -/**
 +/*
   * @mainpage
   *
   * @section libav_intro Introduction
   *
   * This document describes the usage of the different libraries
 - * provided by Libav.
 + * provided by FFmpeg.
   *
   * @li @ref libavc "libavcodec" encoding/decoding library
   * @li @subpage libavfilter graph based frame editing library
   * @li @ref libavf "libavformat" I/O and muxing/demuxing library
   * @li @ref lavd "libavdevice" special devices muxing/demuxing library
   * @li @ref lavu "libavutil" common utility library
 + * @li @subpage libpostproc post processing library
   * @li @subpage libswscale  color conversion and scaling library
   */
  
@@@ -47,7 -46,7 +47,7 @@@
   * @defgroup lavu Common utility functions
   *
   * @brief
 - * libavutil contains the code shared across all the other Libav
 + * libavutil contains the code shared across all the other FFmpeg
   * libraries
   *
   * @note In order to use the functions provided by avutil you must include
   */
  
  #define LIBAVUTIL_VERSION_MAJOR 51
- #define LIBAVUTIL_VERSION_MINOR 54
 -#define LIBAVUTIL_VERSION_MINOR 31
 -#define LIBAVUTIL_VERSION_MICRO  0
++#define LIBAVUTIL_VERSION_MINOR 55
 +#define LIBAVUTIL_VERSION_MICRO 100
  
  #define LIBAVUTIL_VERSION_INT   AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \
                                                 LIBAVUTIL_VERSION_MINOR, \
   *
   * @{
   */
 +#ifndef FF_API_OLD_EVAL_NAMES
 +#define FF_API_OLD_EVAL_NAMES (LIBAVUTIL_VERSION_MAJOR < 52)
 +#endif
  #ifndef FF_API_GET_BITS_PER_SAMPLE_FMT
  #define FF_API_GET_BITS_PER_SAMPLE_FMT (LIBAVUTIL_VERSION_MAJOR < 52)
  #endif
@@@ -237,12 -233,6 +237,12 @@@ enum AVMediaType 
      AVMEDIA_TYPE_NB
  };
  
 +/**
 + * Return a string describing the media_type enum, NULL if media_type
 + * is unknown.
 + */
 +const char *av_get_media_type_string(enum AVMediaType media_type);
 +
  /**
   * @defgroup lavu_const Constants
   * @{
   * @}
   * @defgroup lavu_time Timestamp specific
   *
 - * Libav internal timebase and timestamp definitions
 + * FFmpeg internal timebase and timestamp definitions
   *
   * @{
   */
   */
  
  enum AVPictureType {
 -    AV_PICTURE_TYPE_I = 1, ///< Intra
 +    AV_PICTURE_TYPE_NONE = 0, ///< Undefined
 +    AV_PICTURE_TYPE_I,     ///< Intra
      AV_PICTURE_TYPE_P,     ///< Predicted
      AV_PICTURE_TYPE_B,     ///< Bi-dir predicted
      AV_PICTURE_TYPE_S,     ///< S(GMC)-VOP MPEG4
@@@ -326,19 -315,6 +326,19 @@@ char av_get_picture_type_char(enum AVPi
  
  #include "common.h"
  #include "error.h"
 +#include "mathematics.h"
 +#include "rational.h"
 +#include "intfloat_readwrite.h"
 +#include "log.h"
 +#include "pixfmt.h"
 +
 +/**
 + * Return x default pointer in case p is NULL.
 + */
 +static inline void *av_x_if_null(const void *p, const void *x)
 +{
 +    return (void *)(intptr_t)(p ? p : x);
 +}
  
  /**
   * @}
diff --combined libavutil/opt.c
index 3f4a5fe9570922e71dfeb729de1c9fc2aad9cd7c,af8df7a2eb102c53de2ce8087cef8a6d6345a782..956edf5ce70f7bed4b25a75c491d59011e028f4e
@@@ -2,20 -2,20 +2,20 @@@
   * AVOptions
   * Copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
  #include "eval.h"
  #include "dict.h"
  #include "log.h"
 +#include "parseutils.h"
  
  #if FF_API_FIND_OPT
  //FIXME order them and do a bin search
  const AVOption *av_find_opt(void *v, const char *name, const char *unit, int mask, int flags)
  {
 -    AVClass *c= *(AVClass**)v; //FIXME silly way of storing AVClass
 -    const AVOption *o= c->option;
 +    const AVOption *o = NULL;
  
 -    for (; o && o->name; o++) {
 +    while ((o = av_next_option(v, o))) {
          if (!strcmp(o->name, name) && (!unit || (o->unit && !strcmp(o->unit, unit))) && (o->flags & mask) == flags)
              return o;
      }
@@@ -73,7 -73,6 +73,7 @@@ static int read_number(const AVOption *
      case AV_OPT_TYPE_RATIONAL:  *intnum = ((AVRational*)dst)->num;
                                  *den    = ((AVRational*)dst)->den;
                                                          return 0;
 +    case AV_OPT_TYPE_CONST:     *num    = o->default_val.dbl; return 0;
      }
      return AVERROR(EINVAL);
  }
@@@ -81,7 -80,7 +81,7 @@@
  static int write_number(void *obj, const AVOption *o, void *dst, double num, int den, int64_t intnum)
  {
      if (o->max*den < num*intnum || o->min*den > num*intnum) {
 -        av_log(obj, AV_LOG_ERROR, "Value %lf for parameter '%s' out of range\n", num, o->name);
 +        av_log(obj, AV_LOG_ERROR, "Value %f for parameter '%s' out of range\n", num*intnum/den, o->name);
          return AVERROR(ERANGE);
      }
  
@@@ -225,12 -224,11 +225,12 @@@ int av_set_string3(void *obj, const cha
  
  int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
  {
 +    int ret;
      void *dst, *target_obj;
      const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
      if (!o || !target_obj)
          return AVERROR_OPTION_NOT_FOUND;
 -    if (!val)
 +    if (!val && o->type != AV_OPT_TYPE_STRING)
          return AVERROR(EINVAL);
  
      dst = ((uint8_t*)target_obj) + o->offset;
      case AV_OPT_TYPE_FLOAT:
      case AV_OPT_TYPE_DOUBLE:
      case AV_OPT_TYPE_RATIONAL: return set_string_number(obj, o, val, dst);
 +    case AV_OPT_TYPE_IMAGE_SIZE:
 +        ret = av_parse_video_size(dst, ((int *)dst) + 1, val);
 +        if (ret < 0)
 +            av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as image size\n", val);
 +        return ret;
      }
  
      av_log(obj, AV_LOG_ERROR, "Invalid option type.\n");
@@@ -323,6 -316,35 +323,35 @@@ int av_opt_set_q(void *obj, const char 
      return set_number(obj, name, val.num, val.den, 1, search_flags);
  }
  
+ int av_opt_set_bin(void *obj, const char *name, const uint8_t *val, int len, int search_flags)
+ {
+     void *target_obj;
+     const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+     uint8_t *ptr;
+     uint8_t **dst;
+     int *lendst;
+     if (!o || !target_obj)
+         return AVERROR_OPTION_NOT_FOUND;
+     if (o->type != AV_OPT_TYPE_BINARY)
+         return AVERROR(EINVAL);
+     ptr = av_malloc(len);
+     if (!ptr)
+         return AVERROR(ENOMEM);
+     dst = (uint8_t **)(((uint8_t *)target_obj) + o->offset);
+     lendst = (int *)(dst + 1);
+     av_free(*dst);
+     *dst = ptr;
+     *lendst = len;
+     memcpy(ptr, val, len);
+     return 0;
+ }
  #if FF_API_OLD_AVOPTIONS
  /**
   *
   */
  const char *av_get_string(void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len)
  {
 -    const AVOption *o = av_opt_find(obj, name, NULL, 0, 0);
 +    const AVOption *o = av_opt_find(obj, name, NULL, 0, AV_OPT_SEARCH_CHILDREN);
      void *dst;
      uint8_t *bin;
      int len, i;
      case AV_OPT_TYPE_FLOAT:     snprintf(buf, buf_len, "%f" , *(float  *)dst);break;
      case AV_OPT_TYPE_DOUBLE:    snprintf(buf, buf_len, "%f" , *(double *)dst);break;
      case AV_OPT_TYPE_RATIONAL:  snprintf(buf, buf_len, "%d/%d", ((AVRational*)dst)->num, ((AVRational*)dst)->den);break;
 +    case AV_OPT_TYPE_CONST:     snprintf(buf, buf_len, "%f" , o->default_val.dbl);break;
      case AV_OPT_TYPE_STRING:    return *(void**)dst;
      case AV_OPT_TYPE_BINARY:
          len = *(int*)(((uint8_t *)dst) + sizeof(uint8_t *));
@@@ -371,7 -392,7 +400,7 @@@ int av_opt_get(void *obj, const char *n
      uint8_t *bin, buf[128];
      int len, i, ret;
  
 -    if (!o || !target_obj)
 +    if (!o || !target_obj || (o->offset<=0 && o->type != AV_OPT_TYPE_CONST))
          return AVERROR_OPTION_NOT_FOUND;
  
      dst = (uint8_t*)target_obj + o->offset;
      case AV_OPT_TYPE_FLOAT:     ret = snprintf(buf, sizeof(buf), "%f" ,     *(float  *)dst);break;
      case AV_OPT_TYPE_DOUBLE:    ret = snprintf(buf, sizeof(buf), "%f" ,     *(double *)dst);break;
      case AV_OPT_TYPE_RATIONAL:  ret = snprintf(buf, sizeof(buf), "%d/%d",   ((AVRational*)dst)->num, ((AVRational*)dst)->den);break;
 +    case AV_OPT_TYPE_CONST:     ret = snprintf(buf, sizeof(buf), "%f" ,     o->default_val.dbl);break;
      case AV_OPT_TYPE_STRING:
          if (*(uint8_t**)dst)
              *out_val = av_strdup(*(uint8_t**)dst);
          for (i = 0; i < len; i++)
              snprintf(*out_val + i*2, 3, "%02X", bin[i]);
          return 0;
 +    case AV_OPT_TYPE_IMAGE_SIZE:
 +        ret = snprintf(buf, sizeof(buf), "%dx%d", ((int *)dst)[0], ((int *)dst)[1]);
 +        break;
      default:
          return AVERROR(EINVAL);
      }
@@@ -573,9 -590,6 +602,9 @@@ static void opt_list(void *obj, void *a
              case AV_OPT_TYPE_BINARY:
                  av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<binary>");
                  break;
 +            case AV_OPT_TYPE_IMAGE_SIZE:
 +                av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "<image_size>");
 +                break;
              case AV_OPT_TYPE_CONST:
              default:
                  av_log(av_log_obj, AV_LOG_INFO, "%-7s ", "");
@@@ -653,7 -667,6 +682,7 @@@ void av_opt_set_defaults2(void *s, int 
              }
              break;
              case AV_OPT_TYPE_STRING:
 +            case AV_OPT_TYPE_IMAGE_SIZE:
                  av_opt_set(s, opt->name, opt->default_val.str, 0);
                  break;
              case AV_OPT_TYPE_BINARY:
@@@ -698,7 -711,7 +727,7 @@@ static int parse_key_value_pair(void *c
          return AVERROR(EINVAL);
      }
  
 -    av_log(ctx, AV_LOG_DEBUG, "Setting value '%s' for key '%s'\n", val, key);
 +    av_log(ctx, AV_LOG_DEBUG, "Setting entry with key '%s' to value '%s'\n", key, val);
  
      ret = av_opt_set(ctx, key, val, 0);
      if (ret == AVERROR_OPTION_NOT_FOUND)
@@@ -767,14 -780,9 +796,14 @@@ const AVOption *av_opt_find(void *obj, 
  const AVOption *av_opt_find2(void *obj, const char *name, const char *unit,
                               int opt_flags, int search_flags, void **target_obj)
  {
 -    const AVClass  *c = *(AVClass**)obj;
 +    const AVClass  *c;
      const AVOption *o = NULL;
  
 +    if(!obj)
 +        return NULL;
 +
 +    c= *(AVClass**)obj;
 +
      if (search_flags & AV_OPT_SEARCH_CHILDREN) {
          if (search_flags & AV_OPT_SEARCH_FAKE_OBJ) {
              const AVClass *child = NULL;
      while (o = av_opt_next(obj, o)) {
          if (!strcmp(o->name, name) && (o->flags & opt_flags) == opt_flags &&
              ((!unit && o->type != AV_OPT_TYPE_CONST) ||
 -             (unit  && o->unit && !strcmp(o->unit, unit)))) {
 +             (unit  && o->type == AV_OPT_TYPE_CONST && o->unit && !strcmp(o->unit, unit)))) {
              if (target_obj) {
                  if (!(search_flags & AV_OPT_SEARCH_FAKE_OBJ))
                      *target_obj = obj;
@@@ -820,14 -828,6 +849,14 @@@ const AVClass *av_opt_child_class_next(
      return NULL;
  }
  
 +void *av_opt_ptr(const AVClass *class, void *obj, const char *name)
 +{
 +    const AVOption *opt= av_opt_find2(&class, name, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ, NULL);
 +    if(!opt)
 +        return NULL;
 +    return (uint8_t*)obj + opt->offset;
 +}
 +
  #ifdef TEST
  
  #undef printf
diff --combined libavutil/opt.h
index 1b1ebe2e41d649c9d4f68d67af168ef470b4e2af,8f800fcf988144397fa454b565b3c511c45b3d9e..dc0dfa791e5ffc872932ae1483bfb8bac1735f9e
@@@ -2,20 -2,20 +2,20 @@@
   * AVOptions
   * copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
@@@ -44,7 -44,7 +44,7 @@@
   * This section describes how to add AVOptions capabilities to a struct.
   *
   * All AVOptions-related information is stored in an AVClass. Therefore
 - * the first member of the struct must be a pointer to an AVClass describing it.
 + * the first member of the struct should be a pointer to an AVClass describing it.
   * The option field of the AVClass must be set to a NULL-terminated static array
   * of AVOptions. Each AVOption must have a non-empty name, a type, a default
   * value and for number-type AVOptions also a range of allowed values. It must
@@@ -81,7 -81,7 +81,7 @@@
   * @endcode
   *
   * Next, when allocating your struct, you must ensure that the AVClass pointer
 - * is set to the correct value. Then, av_opt_set_defaults() must be called to
 + * is set to the correct value. Then, av_opt_set_defaults() can be called to
   * initialize defaults. After that the struct is ready to be used with the
   * AVOptions API.
   *
   *
   * @section avoptions_use Using AVOptions
   * This section deals with accessing options in an AVOptions-enabled struct.
 - * Such structs in Libav are e.g. AVCodecContext in libavcodec or
 + * Such structs in FFmpeg are e.g. AVCodecContext in libavcodec or
   * AVFormatContext in libavformat.
   *
   * @subsection avoptions_use_examine Examining AVOptions
@@@ -225,7 -225,6 +225,7 @@@ enum AVOptionType
      AV_OPT_TYPE_RATIONAL,
      AV_OPT_TYPE_BINARY,  ///< offset must point to a pointer immediately followed by an int for the length
      AV_OPT_TYPE_CONST = 128,
 +    AV_OPT_TYPE_IMAGE_SIZE = MKBETAG('S','I','Z','E'), ///< offset must point to two consecutive integers
  #if FF_API_OLD_AVOPTIONS
      FF_OPT_TYPE_FLAGS = 0,
      FF_OPT_TYPE_INT,
@@@ -341,9 -340,9 +341,9 @@@ attribute_deprecated const AVOption *av
  attribute_deprecated const AVOption *av_set_q(void *obj, const char *name, AVRational n);
  attribute_deprecated const AVOption *av_set_int(void *obj, const char *name, int64_t n);
  
 -attribute_deprecated double av_get_double(void *obj, const char *name, const AVOption **o_out);
 -attribute_deprecated AVRational av_get_q(void *obj, const char *name, const AVOption **o_out);
 -attribute_deprecated int64_t av_get_int(void *obj, const char *name, const AVOption **o_out);
 +double av_get_double(void *obj, const char *name, const AVOption **o_out);
 +AVRational av_get_q(void *obj, const char *name, const AVOption **o_out);
 +int64_t av_get_int(void *obj, const char *name, const AVOption **o_out);
  attribute_deprecated const char *av_get_string(void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len);
  attribute_deprecated const AVOption *av_next_option(void *obj, const AVOption *last);
  #endif
@@@ -377,7 -376,6 +377,7 @@@ void av_opt_set_defaults2(void *s, int 
   * key. ctx must be an AVClass context, storing is done using
   * AVOptions.
   *
 + * @param opts options string to parse, may be NULL
   * @param key_val_sep a 0-terminated list of characters used to
   * separate key from value
   * @param pairs_sep a 0-terminated list of characters used to separate
@@@ -562,6 -560,7 +562,7 @@@ int av_opt_set       (void *obj, const 
  int av_opt_set_int   (void *obj, const char *name, int64_t     val, int search_flags);
  int av_opt_set_double(void *obj, const char *name, double      val, int search_flags);
  int av_opt_set_q     (void *obj, const char *name, AVRational  val, int search_flags);
+ int av_opt_set_bin   (void *obj, const char *name, const uint8_t *val, int size, int search_flags);
  /**
   * @}
   */
@@@ -587,17 -586,6 +588,17 @@@ int av_opt_get_double(void *obj, const 
  int av_opt_get_q     (void *obj, const char *name, int search_flags, AVRational *out_val);
  /**
   * @}
 + */
 +/**
 + * Gets a pointer to the requested field in a struct.
 + * This function allows accessing a struct even when its fields are moved or
 + * renamed since the application making the access has been compiled,
 + *
 + * @returns a pointer to the field, it can be cast to the correct type and read
 + *          or written to.
 + */
 +void *av_opt_ptr(const AVClass *avclass, void *obj, const char *name);
 +/**
   * @}
   */