Merge remote-tracking branch 'qatar/master'
authorMichael Niedermayer <michaelni@gmx.at>
Tue, 14 Aug 2012 13:31:43 +0000 (15:31 +0200)
committerMichael Niedermayer <michaelni@gmx.at>
Tue, 14 Aug 2012 13:34:39 +0000 (15:34 +0200)
* qatar/master:
  g723.1: simplify scale_vector()
  g723.1: simplify normalize_bits()
  vda: cosmetics: fix Doxygen comment formatting
  vda: better frame allocation
  vda: Merge implementation into one file
  vda: support synchronous decoding
  vda: Reuse the bitstream buffer and reallocate it only if needed
  build: Factor out mpegvideo encoding dependencies to CONFIG_MPEGVIDEOENC
  avprobe: Include libm.h for the log2 fallback
  proresenc: use the edge emulation buffer
  rtmp: handle bytes read reports
  configure: Fix typo in mpeg2video/svq1 decoder dependency declaration
  Use log2(x) instead of log(x) / log(2)
  x86: swscale: fix fragile memory accesses
  x86: swscale: remove disabled code
  x86: yadif: fix asm with suncc
  x86: cabac: allow building with suncc
  x86: mlpdsp: avoid taking address of void
  ARM: intmath: use native-size return types for clipping functions

Conflicts:
configure
ffprobe.c
libavcodec/Makefile
libavcodec/g723_1.c
libavcodec/v210dec.h
libavcodec/vda.h
libavcodec/vda_h264.c
libavcodec/x86/cabac.h
libavfilter/x86/yadif_template.c
libswscale/x86/rgb2rgb_template.c

Merged-by: Michael Niedermayer <michaelni@gmx.at>
17 files changed:
1  2 
configure
ffmpeg.c
ffprobe.c
libavcodec/Makefile
libavcodec/g723_1.c
libavcodec/imc.c
libavcodec/snowenc.c
libavcodec/vda.h
libavcodec/vda_h264.c
libavcodec/version.h
libavcodec/x86/cabac.h
libavcodec/x86/h264_i386.h
libavcodec/x86/mlpdsp.c
libavfilter/x86/yadif_template.c
libavformat/rtmpproto.c
libavutil/arm/intmath.h
libswscale/x86/rgb2rgb_template.c

diff --cc configure
+++ b/configure
@@@ -1520,8 -1355,7 +1522,8 @@@ cavs_decoder_select="golomb mpegvideo
  cook_decoder_select="mdct sinewin"
  cscd_decoder_suggest="zlib"
  dca_decoder_select="mdct"
- dnxhd_encoder_select="aandcttables mpegvideo"
 +dirac_decoder_select="dwt golomb"
+ dnxhd_encoder_select="aandcttables mpegvideoenc"
  dxa_decoder_select="zlib"
  eac3_decoder_select="ac3_decoder"
  eac3_encoder_select="mdct ac3dsp"
@@@ -1579,17 -1409,13 +1581,17 @@@ mpeg_vdpau_decoder_select="vdpau mpegvi
  mpeg_xvmc_decoder_deps="X11_extensions_XvMClib_h"
  mpeg_xvmc_decoder_select="mpegvideo_decoder"
  mpeg1_vdpau_decoder_select="vdpau mpeg1video_decoder"
 +mpeg1_vdpau_hwaccel_select="vdpau mpeg1video_decoder"
  mpeg1video_decoder_select="mpegvideo"
- mpeg1video_encoder_select="aandcttables mpegvideo"
+ mpeg1video_encoder_select="aandcttables mpegvideoenc"
 +mpeg2_crystalhd_decoder_select="crystalhd"
  mpeg2_dxva2_hwaccel_deps="dxva2api_h"
  mpeg2_dxva2_hwaccel_select="dxva2 mpeg2video_decoder"
 +mpeg2_vdpau_hwaccel_select="vdpau mpeg2video_decoder"
  mpeg2_vaapi_hwaccel_select="vaapi mpeg2video_decoder"
- mpeg2video_encoder_select="mpegvideo"
- mpeg2video_encoder_select="aandcttables mpegvideo"
+ mpeg2video_decoder_select="mpegvideo"
+ mpeg2video_encoder_select="aandcttables mpegvideoenc"
 +mpeg4_crystalhd_decoder_select="crystalhd"
  mpeg4_decoder_select="h263_decoder mpeg4video_parser"
  mpeg4_encoder_select="h263_encoder"
  mpeg4_vaapi_hwaccel_select="vaapi mpeg4_decoder"
@@@ -1618,12 -1443,9 +1620,12 @@@ rv40_decoder_select="golomb h264chroma 
  shorten_decoder_select="golomb"
  sipr_decoder_select="lsp"
  snow_decoder_select="dwt"
- snow_encoder_select="aandcttables dwt mpegvideo"
+ snow_encoder_select="aandcttables dwt mpegvideoenc"
 +sonic_decoder_select="golomb"
 +sonic_encoder_select="golomb"
 +sonic_ls_encoder_select="golomb"
- svq1_encoder_select="mpegvideo"
- svq1_encoder_select="aandcttables mpegvideo"
+ svq1_decoder_select="mpegvideo"
+ svq1_encoder_select="aandcttables mpegvideoenc"
  svq3_decoder_select="golomb h264chroma h264dsp h264pred h264qpel mpegvideo"
  svq3_decoder_suggest="zlib"
  theora_decoder_select="vp3_decoder"
diff --cc ffmpeg.c
index 043f68c,0000000..b97ad7b
mode 100644,000000..100644
--- /dev/null
+++ b/ffmpeg.c
@@@ -1,3133 -1,0 +1,3133 @@@
-                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
 +/*
 + * Copyright (c) 2000-2003 Fabrice Bellard
 + *
 + * This file is part of FFmpeg.
 + *
 + * 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.
 + *
 + * 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 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>
 +#include <math.h>
 +#include <stdlib.h>
 +#include <errno.h>
 +#include <limits.h>
 +#if HAVE_ISATTY
 +#include <unistd.h>
 +#endif
 +#include "libavformat/avformat.h"
 +#include "libavdevice/avdevice.h"
 +#include "libswscale/swscale.h"
 +#include "libswresample/swresample.h"
 +#include "libavutil/opt.h"
 +#include "libavutil/audioconvert.h"
 +#include "libavutil/parseutils.h"
 +#include "libavutil/samplefmt.h"
 +#include "libavutil/colorspace.h"
 +#include "libavutil/fifo.h"
 +#include "libavutil/intreadwrite.h"
 +#include "libavutil/dict.h"
 +#include "libavutil/mathematics.h"
 +#include "libavutil/pixdesc.h"
 +#include "libavutil/avstring.h"
 +#include "libavutil/libm.h"
 +#include "libavutil/imgutils.h"
 +#include "libavutil/timestamp.h"
 +#include "libavutil/bprint.h"
 +#include "libavutil/time.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"
 +
 +#if HAVE_SYS_RESOURCE_H
 +#include <sys/types.h>
 +#include <sys/resource.h>
 +#elif HAVE_GETPROCESSTIMES
 +#include <windows.h>
 +#endif
 +#if HAVE_GETPROCESSMEMORYINFO
 +#include <windows.h>
 +#include <psapi.h>
 +#endif
 +
 +#if HAVE_SYS_SELECT_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
 +
 +#if HAVE_PTHREADS
 +#include <pthread.h>
 +#endif
 +
 +#include <time.h>
 +
 +#include "ffmpeg.h"
 +#include "cmdutils.h"
 +
 +#include "libavutil/avassert.h"
 +
 +const char program_name[] = "ffmpeg";
 +const int program_birth_year = 2000;
 +
 +static FILE *vstats_file;
 +
 +static void do_video_stats(AVFormatContext *os, OutputStream *ost, int frame_size);
 +static int64_t getutime(void);
 +
 +static int run_as_daemon  = 0;
 +static int64_t video_size = 0;
 +static int64_t audio_size = 0;
 +static int64_t subtitle_size = 0;
 +static int64_t extra_size = 0;
 +static int nb_frames_dup = 0;
 +static int nb_frames_drop = 0;
 +
 +static int current_time;
 +AVIOContext *progress_avio = NULL;
 +
 +static uint8_t *subtitle_out;
 +
 +#if HAVE_PTHREADS
 +/* signal to input threads that they should exit; set by the main thread */
 +static int transcoding_finished;
 +#endif
 +
 +#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
 +
 +InputStream **input_streams = NULL;
 +int        nb_input_streams = 0;
 +InputFile   **input_files   = NULL;
 +int        nb_input_files   = 0;
 +
 +OutputStream **output_streams = NULL;
 +int         nb_output_streams = 0;
 +OutputFile   **output_files   = NULL;
 +int         nb_output_files   = 0;
 +
 +FilterGraph **filtergraphs;
 +int        nb_filtergraphs;
 +
 +#if HAVE_TERMIOS_H
 +
 +/* init terminal so that we can grab keys */
 +static struct termios oldtty;
 +static int restore_tty;
 +#endif
 +
 +
 +/* sub2video hack:
 +   Convert subtitles to video with alpha to insert them in filter graphs.
 +   This is a temporary solution until libavfilter gets real subtitles support.
 + */
 +
 +
 +
 +static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
 +                                AVSubtitleRect *r)
 +{
 +    uint32_t *pal, *dst2;
 +    uint8_t *src, *src2;
 +    int x, y;
 +
 +    if (r->type != SUBTITLE_BITMAP) {
 +        av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
 +        return;
 +    }
 +    if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
 +        av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");
 +        return;
 +    }
 +
 +    dst += r->y * dst_linesize + r->x * 4;
 +    src = r->pict.data[0];
 +    pal = (uint32_t *)r->pict.data[1];
 +    for (y = 0; y < r->h; y++) {
 +        dst2 = (uint32_t *)dst;
 +        src2 = src;
 +        for (x = 0; x < r->w; x++)
 +            *(dst2++) = pal[*(src2++)];
 +        dst += dst_linesize;
 +        src += r->pict.linesize[0];
 +    }
 +}
 +
 +static void sub2video_push_ref(InputStream *ist, int64_t pts)
 +{
 +    AVFilterBufferRef *ref = ist->sub2video.ref;
 +    int i;
 +
 +    ist->sub2video.last_pts = ref->pts = pts;
 +    for (i = 0; i < ist->nb_filters; i++)
 +        av_buffersrc_add_ref(ist->filters[i]->filter,
 +                             avfilter_ref_buffer(ref, ~0),
 +                             AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
 +                             AV_BUFFERSRC_FLAG_NO_COPY);
 +}
 +
 +static void sub2video_update(InputStream *ist, AVSubtitle *sub, int64_t pts)
 +{
 +    int w = ist->sub2video.w, h = ist->sub2video.h;
 +    AVFilterBufferRef *ref = ist->sub2video.ref;
 +    int8_t *dst;
 +    int     dst_linesize;
 +    int i;
 +
 +    if (!ref)
 +        return;
 +    dst          = ref->data    [0];
 +    dst_linesize = ref->linesize[0];
 +    memset(dst, 0, h * dst_linesize);
 +    for (i = 0; i < sub->num_rects; i++)
 +        sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);
 +    sub2video_push_ref(ist, pts);
 +}
 +
 +static void sub2video_heartbeat(InputStream *ist, int64_t pts)
 +{
 +    InputFile *infile = input_files[ist->file_index];
 +    int i, j, nb_reqs;
 +    int64_t pts2;
 +
 +    /* When a frame is read from a file, examine all sub2video streams in
 +       the same file and send the sub2video frame again. Otherwise, decoded
 +       video frames could be accumulating in the filter graph while a filter
 +       (possibly overlay) is desperately waiting for a subtitle frame. */
 +    for (i = 0; i < infile->nb_streams; i++) {
 +        InputStream *ist2 = input_streams[infile->ist_index + i];
 +        if (!ist2->sub2video.ref)
 +            continue;
 +        /* subtitles seem to be usually muxed ahead of other streams;
 +           if not, substracting a larger time here is necessary */
 +        pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
 +        /* do not send the heartbeat frame if the subtitle is already ahead */
 +        if (pts2 <= ist2->sub2video.last_pts)
 +            continue;
 +        for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
 +            nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
 +        if (nb_reqs)
 +            sub2video_push_ref(ist2, pts2);
 +    }
 +}
 +
 +static void sub2video_flush(InputStream *ist)
 +{
 +    int i;
 +
 +    for (i = 0; i < ist->nb_filters; i++)
 +        av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
 +}
 +
 +/* end of sub2video hack */
 +
 +void term_exit(void)
 +{
 +    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)
 +{
 +    received_sigterm = sig;
 +    received_nb_signals++;
 +    term_exit();
 +    if(received_nb_signals > 3)
 +        exit(123);
 +}
 +
 +void term_init(void)
 +{
 +#if HAVE_TERMIOS_H
 +    if(!run_as_daemon){
 +        struct termios tty;
 +        int istty = 1;
 +#if HAVE_ISATTY
 +        istty = isatty(0) && isatty(2);
 +#endif
 +        if (istty && 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
 +    signal(SIGXCPU, sigterm_handler);
 +#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;
 +}
 +
 +const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
 +
 +void av_noreturn exit_program(int ret)
 +{
 +    int i, j;
 +
 +    for (i = 0; i < nb_filtergraphs; i++) {
 +        avfilter_graph_free(&filtergraphs[i]->graph);
 +        for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
 +            av_freep(&filtergraphs[i]->inputs[j]->name);
 +            av_freep(&filtergraphs[i]->inputs[j]);
 +        }
 +        av_freep(&filtergraphs[i]->inputs);
 +        for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
 +            av_freep(&filtergraphs[i]->outputs[j]->name);
 +            av_freep(&filtergraphs[i]->outputs[j]);
 +        }
 +        av_freep(&filtergraphs[i]->outputs);
 +        av_freep(&filtergraphs[i]);
 +    }
 +    av_freep(&filtergraphs);
 +
 +    av_freep(&subtitle_out);
 +
 +    /* close files */
 +    for (i = 0; i < nb_output_files; i++) {
 +        AVFormatContext *s = output_files[i]->ctx;
 +        if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
 +            avio_close(s->pb);
 +        avformat_free_context(s);
 +        av_dict_free(&output_files[i]->opts);
 +        av_freep(&output_files[i]);
 +    }
 +    for (i = 0; i < nb_output_streams; i++) {
 +        AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
 +        while (bsfc) {
 +            AVBitStreamFilterContext *next = bsfc->next;
 +            av_bitstream_filter_close(bsfc);
 +            bsfc = next;
 +        }
 +        output_streams[i]->bitstream_filters = NULL;
 +
 +        av_freep(&output_streams[i]->forced_keyframes);
 +        av_freep(&output_streams[i]->avfilter);
 +        av_freep(&output_streams[i]->filtered_frame);
 +        av_freep(&output_streams[i]);
 +    }
 +    for (i = 0; i < nb_input_files; i++) {
 +        avformat_close_input(&input_files[i]->ctx);
 +        av_freep(&input_files[i]);
 +    }
 +    for (i = 0; i < nb_input_streams; i++) {
 +        av_freep(&input_streams[i]->decoded_frame);
 +        av_dict_free(&input_streams[i]->opts);
 +        free_buffer_pool(&input_streams[i]->buffer_pool);
 +        avfilter_unref_bufferp(&input_streams[i]->sub2video.ref);
 +        av_freep(&input_streams[i]->filters);
 +        av_freep(&input_streams[i]);
 +    }
 +
 +    if (vstats_file)
 +        fclose(vstats_file);
 +    av_free(vstats_filename);
 +
 +    av_freep(&input_streams);
 +    av_freep(&input_files);
 +    av_freep(&output_streams);
 +    av_freep(&output_files);
 +
 +    uninit_opts();
 +
 +    avfilter_uninit();
 +    avformat_network_deinit();
 +
 +    if (received_sigterm) {
 +        av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
 +               (int) received_sigterm);
 +        exit (255);
 +    }
 +
 +    exit(ret);
 +}
 +
 +void assert_avoptions(AVDictionary *m)
 +{
 +    AVDictionaryEntry *t;
 +    if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
 +        av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
 +        exit_program(1);
 +    }
 +}
 +
 +static void assert_codec_experimental(AVCodecContext *c, int encoder)
 +{
 +    const char *codec_string = encoder ? "encoder" : "decoder";
 +    AVCodec *codec;
 +    if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
 +        c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
 +        av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
 +                "results.\nAdd '-strict experimental' if you want to use it.\n",
 +                codec_string, c->codec->name);
 +        codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
 +        if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
 +            av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
 +                   codec_string, codec->name);
 +        exit_program(1);
 +    }
 +}
 +
 +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 write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
 +{
 +    AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
 +    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
 +     * by simply dropping them here.
 +     * Counting encoded video frames needs to be done separately because of
 +     * reordering, see do_video_out()
 +     */
 +    if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
 +        if (ost->frame_number >= ost->max_frames) {
 +            av_free_packet(pkt);
 +            return;
 +        }
 +        ost->frame_number++;
 +    }
 +
 +    while (bsfc) {
 +        AVPacket new_pkt = *pkt;
 +        int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
 +                                           &new_pkt.data, &new_pkt.size,
 +                                           pkt->data, pkt->size,
 +                                           pkt->flags & AV_PKT_FLAG_KEY);
 +        if(a == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
 +            uint8_t *t = av_malloc(new_pkt.size + FF_INPUT_BUFFER_PADDING_SIZE); //the new should be a subset of the old so cannot overflow
 +            if(t) {
 +                memcpy(t, new_pkt.data, new_pkt.size);
 +                memset(t + new_pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
 +                new_pkt.data = t;
 +                a = 1;
 +            } else
 +                a = AVERROR(ENOMEM);
 +        }
 +        if (a > 0) {
 +            av_free_packet(pkt);
 +            new_pkt.destruct = av_destruct_packet;
 +        } else if (a < 0) {
 +            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);
 +            if (exit_on_error)
 +                exit_program(1);
 +        }
 +        *pkt = new_pkt;
 +
 +        bsfc = bsfc->next;
 +    }
 +
 +    pkt->stream_index = ost->index;
 +    ret = av_interleaved_write_frame(s, pkt);
 +    if (ret < 0) {
 +        print_error("av_interleaved_write_frame()", ret);
 +        exit_program(1);
 +    }
 +}
 +
 +static int check_recording_time(OutputStream *ost)
 +{
 +    OutputFile *of = output_files[ost->file_index];
 +
 +    if (of->recording_time != INT64_MAX &&
 +        av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
 +                      AV_TIME_BASE_Q) >= 0) {
 +        ost->finished = 1;
 +        return 0;
 +    }
 +    return 1;
 +}
 +
 +static void do_audio_out(AVFormatContext *s, OutputStream *ost,
 +                         AVFrame *frame)
 +{
 +    AVCodecContext *enc = ost->st->codec;
 +    AVPacket pkt;
 +    int got_packet = 0;
 +
 +    av_init_packet(&pkt);
 +    pkt.data = NULL;
 +    pkt.size = 0;
 +
 +    if (!check_recording_time(ost))
 +        return;
 +
 +    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 (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)
 +            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 (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);
 +    }
 +}
 +
 +static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
 +{
 +    AVCodecContext *dec;
 +    AVPicture *picture2;
 +    AVPicture picture_tmp;
 +    uint8_t *buf = 0;
 +
 +    dec = ist->st->codec;
 +
 +    /* deinterlace : must be done before any resize */
 +    if (do_deinterlace) {
 +        int size;
 +
 +        /* create temporary picture */
 +        size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
 +        buf  = av_malloc(size);
 +        if (!buf)
 +            return;
 +
 +        picture2 = &picture_tmp;
 +        avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
 +
 +        if (avpicture_deinterlace(picture2, picture,
 +                                 dec->pix_fmt, dec->width, dec->height) < 0) {
 +            /* if error, do not deinterlace */
 +            av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
 +            av_free(buf);
 +            buf = NULL;
 +            picture2 = picture;
 +        }
 +    } else {
 +        picture2 = picture;
 +    }
 +
 +    if (picture != picture2)
 +        *picture = *picture2;
 +    *bufp = buf;
 +}
 +
 +static void do_subtitle_out(AVFormatContext *s,
 +                            OutputStream *ost,
 +                            InputStream *ist,
 +                            AVSubtitle *sub,
 +                            int64_t pts)
 +{
 +    int subtitle_out_max_size = 1024 * 1024;
 +    int subtitle_out_size, nb, i;
 +    AVCodecContext *enc;
 +    AVPacket pkt;
 +
 +    if (pts == AV_NOPTS_VALUE) {
 +        av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
 +        if (exit_on_error)
 +            exit_program(1);
 +        return;
 +    }
 +
 +    enc = ost->st->codec;
 +
 +    if (!subtitle_out) {
 +        subtitle_out = av_malloc(subtitle_out_max_size);
 +    }
 +
 +    /* Note: DVB subtitle need one packet to draw them and one other
 +       packet to clear them */
 +    /* XXX: signal it in the codec context ? */
 +    if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
 +        nb = 2;
 +    else
 +        nb = 1;
 +
 +    /* shift timestamp to honor -ss and make check_recording_time() work with -t */
 +    pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q)
 +        - output_files[ost->file_index]->start_time;
 +    for (i = 0; i < nb; i++) {
 +        ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
 +        if (!check_recording_time(ost))
 +            return;
 +
 +        sub->pts = pts;
 +        // start_display_time is required to be 0
 +        sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
 +        sub->end_display_time  -= sub->start_display_time;
 +        sub->start_display_time = 0;
 +        if (i == 1)
 +            sub->num_rects = 0;
 +        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
 +                                                    subtitle_out_max_size, sub);
 +        if (subtitle_out_size < 0) {
 +            av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
 +            exit_program(1);
 +        }
 +
 +        av_init_packet(&pkt);
 +        pkt.data = subtitle_out;
 +        pkt.size = subtitle_out_size;
 +        pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
 +        pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
 +        if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
 +            /* XXX: the pts correction is handled here. Maybe handling
 +               it in the codec would be better */
 +            if (i == 0)
 +                pkt.pts += 90 * sub->start_display_time;
 +            else
 +                pkt.pts += 90 * sub->end_display_time;
 +        }
 +        write_frame(s, &pkt, ost);
 +        subtitle_size += pkt.size;
 +    }
 +}
 +
 +static void do_video_out(AVFormatContext *s,
 +                         OutputStream *ost,
 +                         AVFrame *in_picture,
 +                         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];
 +
 +    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_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) {
 +        if (nb_frames > dts_error_threshold * 30) {
 +            av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skiping\n", nb_frames - 1);
 +            nb_frames_drop++;
 +            return;
 +        }
 +        nb_frames_dup += nb_frames - 1;
 +        av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
 +    }
 +
 +  /* duplicates frame if needed */
 +  for (i = 0; i < nb_frames; i++) {
 +    av_init_packet(&pkt);
 +    pkt.data = NULL;
 +    pkt.size = 0;
 +
 +    in_picture->pts = ost->sync_opts;
 +
 +    if (!check_recording_time(ost))
 +        return;
 +
 +    if (s->oformat->flags & AVFMT_RAWPICTURE &&
 +        enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
 +        /* raw pictures are written as AVPicture structure to
 +           avoid any copies. We support temporarily the older
 +           method. */
 +        enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
 +        enc->coded_frame->top_field_first  = in_picture->top_field_first;
 +        pkt.data   = (uint8_t *)in_picture;
 +        pkt.size   =  sizeof(AVPicture);
 +        pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
 +        pkt.flags |= AV_PKT_FLAG_KEY;
 +
 +        write_frame(s, &pkt, ost);
 +        video_size += pkt.size;
 +    } else {
 +        int got_packet;
 +        AVFrame big_picture;
 +
 +        big_picture = *in_picture;
 +        /* better than nothing: use input picture interlaced
 +           settings */
 +        big_picture.interlaced_frame = in_picture->interlaced_frame;
 +        if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
 +            if (ost->top_field_first == -1)
 +                big_picture.top_field_first = in_picture->top_field_first;
 +            else
 +                big_picture.top_field_first = !!ost->top_field_first;
 +        }
 +
 +        /* handles same_quant here. This is not correct because it may
 +           not be a global option */
 +        big_picture.quality = quality;
 +        if (!enc->me_threshold)
 +            big_picture.pict_type = 0;
 +        if (ost->forced_kf_index < ost->forced_kf_count &&
 +            big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
 +            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;
 +            video_size += pkt.size;
 +            av_free_packet(&pkt);
 +
 +            /* if two pass, output log */
 +            if (ost->logfile && enc->stats_out) {
 +                fprintf(ost->logfile, "%s", enc->stats_out);
 +            }
 +        }
 +    }
 +    ost->sync_opts++;
 +    /*
 +     * For video, number of frames in == number of packets out.
 +     * But there may be reordering, so we can't throw away frames on encoder
 +     * flush, we need to limit them here, before they go into encoder.
 +     */
 +    ost->frame_number++;
 +  }
 +
 +    if (vstats_filename && frame_size)
 +        do_video_stats(output_files[ost->file_index]->ctx, ost, frame_size);
 +}
 +
 +static double psnr(double d)
 +{
 +    return -10.0 * log(d) / log(10.0);
 +}
 +
 +static void do_video_stats(AVFormatContext *os, OutputStream *ost,
 +                           int frame_size)
 +{
 +    AVCodecContext *enc;
 +    int frame_number;
 +    double ti1, bitrate, avg_bitrate;
 +
 +    /* this is executed just the first time do_video_stats is called */
 +    if (!vstats_file) {
 +        vstats_file = fopen(vstats_filename, "w");
 +        if (!vstats_file) {
 +            perror("fopen");
 +            exit_program(1);
 +        }
 +    }
 +
 +    enc = ost->st->codec;
 +    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
 +        frame_number = ost->frame_number;
 +        fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
 +        if (enc->flags&CODEC_FLAG_PSNR)
 +            fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
 +
 +        fprintf(vstats_file,"f_size= %6d ", frame_size);
 +        /* compute pts value */
 +        ti1 = ost->sync_opts * av_q2d(enc->time_base);
 +        if (ti1 < 0.01)
 +            ti1 = 0.01;
 +
 +        bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
 +        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
 +        fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
 +               (double)video_size / 1024, ti1, bitrate, avg_bitrate);
 +        fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
 +    }
 +}
 +
 +/* check for new output on any of the filtergraphs */
 +static int poll_filters(void)
 +{
 +    AVFilterBufferRef *picref;
 +    AVFrame *filtered_frame = NULL;
 +    int i, ret, ret_all;
 +    unsigned nb_success = 1, av_uninit(nb_eof);
 +    int64_t frame_pts;
 +
 +    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)
 +                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 (1) {
 +                ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
 +                                                   AV_BUFFERSINK_FLAG_NO_REQUEST);
 +                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
 +
 +
 +                switch (ost->filter->filter->inputs[0]->type) {
 +                case AVMEDIA_TYPE_VIDEO:
 +                    avfilter_copy_buf_props(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);
 +                }
 +
 +                avfilter_unref_buffer(picref);
 +            }
 +        }
 +        if (!nb_success) /* from last round */
 +            break;
 +        /* 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;
 +            }
 +        }
 +        /* Try again if anything succeeded */
 +    }
 +    return nb_eof == nb_filtergraphs ? AVERROR_EOF : ret_all;
 +}
 +
 +static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
 +{
 +    char buf[1024];
 +    AVBPrint buf_script;
 +    OutputStream *ost;
 +    AVFormatContext *oc;
 +    int64_t total_size;
 +    AVCodecContext *enc;
 +    int frame_number, vid, i;
 +    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 && !progress_avio)
 +        return;
 +
 +    if (!is_last_report) {
 +        if (last_time == -1) {
 +            last_time = cur_time;
 +            return;
 +        }
 +        if ((cur_time - last_time) < 500000)
 +            return;
 +        last_time = cur_time;
 +    }
 +
 +
 +    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
 +        total_size = avio_tell(oc->pb);
 +        if (total_size < 0)
 +            total_size = 0;
 +    }
 +
 +    buf[0] = '\0';
 +    vid = 0;
 +    av_bprint_init(&buf_script, 0, 1);
 +    for (i = 0; i < nb_output_streams; i++) {
 +        float q = -1;
 +        ost = output_streams[i];
 +        enc = ost->st->codec;
 +        if (!ost->stream_copy && enc->coded_frame)
 +            q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
 +        if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
 +            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
 +            av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
 +                       ost->file_index, ost->index, q);
 +        }
 +        if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
 +            float fps, t = (cur_time-timer_start) / 1000000.0;
 +
 +            frame_number = ost->frame_number;
 +            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);
 +            av_bprintf(&buf_script, "frame=%d\n", frame_number);
 +            av_bprintf(&buf_script, "fps=%.1f\n", fps);
 +            av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
 +                       ost->file_index, ost->index, q);
 +            if (is_last_report)
 +                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
 +            if (qp_hist) {
 +                int j;
 +                int qp = lrintf(q);
 +                if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
 +                    qp_histogram[qp]++;
 +                for (j = 0; j < 32; j++)
++                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
 +            }
 +            if (enc->flags&CODEC_FLAG_PSNR) {
 +                int j;
 +                double error, error_sum = 0;
 +                double scale, scale_sum = 0;
 +                double p;
 +                char type[3] = { 'Y','U','V' };
 +                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
 +                for (j = 0; j < 3; j++) {
 +                    if (is_last_report) {
 +                        error = enc->error[j];
 +                        scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
 +                    } else {
 +                        error = enc->coded_frame->error[j];
 +                        scale = enc->width * enc->height * 255.0 * 255.0;
 +                    }
 +                    if (j)
 +                        scale /= 4;
 +                    error_sum += error;
 +                    scale_sum += scale;
 +                    p = psnr(error / scale);
 +                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
 +                    av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
 +                               ost->file_index, ost->index, type[i] | 32, p);
 +                }
 +                p = psnr(error_sum / scale_sum);
 +                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
 +                av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
 +                           ost->file_index, ost->index, p);
 +            }
 +            vid = 1;
 +        }
 +        /* compute min output value */
 +        pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
 +                                      ost->st->time_base, AV_TIME_BASE_Q));
 +    }
 +
 +    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),
 +             "%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);
 +    av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
 +    av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
 +    av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
 +               hours, mins, secs, us);
 +
 +    if (nb_frames_dup || nb_frames_drop)
 +        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
 +                nb_frames_dup, nb_frames_drop);
 +    av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
 +    av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
 +
 +    if (print_stats || is_last_report) {
 +    av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
 +
 +    fflush(stderr);
 +    }
 +
 +    if (progress_avio) {
 +        av_bprintf(&buf_script, "progress=%s\n",
 +                   is_last_report ? "end" : "continue");
 +        avio_write(progress_avio, buf_script.str,
 +                   FFMIN(buf_script.len, buf_script.size - 1));
 +        avio_flush(progress_avio);
 +        av_bprint_finalize(&buf_script, NULL);
 +        if (is_last_report) {
 +            avio_close(progress_avio);
 +            progress_avio = NULL;
 +        }
 +    }
 +
 +    if (is_last_report) {
 +        int64_t raw= audio_size + video_size + subtitle_size + extra_size;
 +        av_log(NULL, AV_LOG_INFO, "\n");
 +        av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
 +               video_size / 1024.0,
 +               audio_size / 1024.0,
 +               subtitle_size / 1024.0,
 +               extra_size / 1024.0,
 +               100.0 * (total_size - raw) / raw
 +        );
 +        if(video_size + audio_size + subtitle_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");
 +        }
 +    }
 +}
 +
 +static void flush_encoders(void)
 +{
 +    int i, ret;
 +
 +    for (i = 0; i < nb_output_streams; i++) {
 +        OutputStream   *ost = output_streams[i];
 +        AVCodecContext *enc = ost->st->codec;
 +        AVFormatContext *os = output_files[ost->file_index]->ctx;
 +        int stop_encoding = 0;
 +
 +        if (!ost->encoding_needed)
 +            continue;
 +
 +        if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
 +            continue;
 +        if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
 +            continue;
 +
 +        for (;;) {
 +            int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
 +            const char *desc;
 +            int64_t *size;
 +
 +            switch (ost->st->codec->codec_type) {
 +            case AVMEDIA_TYPE_AUDIO:
 +                encode = avcodec_encode_audio2;
 +                desc   = "Audio";
 +                size   = &audio_size;
 +                break;
 +            case AVMEDIA_TYPE_VIDEO:
 +                encode = avcodec_encode_video2;
 +                desc   = "Video";
 +                size   = &video_size;
 +                break;
 +            default:
 +                stop_encoding = 1;
 +            }
 +
 +            if (encode) {
 +                AVPacket pkt;
 +                int got_packet;
 +                av_init_packet(&pkt);
 +                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 += pkt.size;
 +                if (ost->logfile && enc->stats_out) {
 +                    fprintf(ost->logfile, "%s", enc->stats_out);
 +                }
 +                if (!got_packet) {
 +                    stop_encoding = 1;
 +                    break;
 +                }
 +                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);
 +                write_frame(os, &pkt, ost);
 +            }
 +
 +            if (stop_encoding)
 +                break;
 +        }
 +    }
 +}
 +
 +/*
 + * Check whether a packet from ist should be written into ost at this time
 + */
 +static int check_output_constraints(InputStream *ist, OutputStream *ost)
 +{
 +    OutputFile *of = output_files[ost->file_index];
 +    int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
 +
 +    if (ost->source_index != ist_index)
 +        return 0;
 +
 +    if (of->start_time && ist->pts < of->start_time)
 +        return 0;
 +
 +    return 1;
 +}
 +
 +static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
 +{
 +    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);
 +
 +    if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
 +        !ost->copy_initial_nonkeyframes)
 +        return;
 +
 +    if (of->recording_time != INT64_MAX &&
 +        ist->pts >= of->recording_time + of->start_time) {
 +        ost->finished = 1;
 +        return;
 +    }
 +
 +    /* force the input stream PTS */
 +    if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
 +        audio_size += pkt->size;
 +    else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
 +        video_size += pkt->size;
 +        ost->sync_opts++;
 +    } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
 +        subtitle_size += pkt->size;
 +    }
 +
 +    if (pkt->pts != AV_NOPTS_VALUE)
 +        opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
 +    else
 +        opkt.pts = AV_NOPTS_VALUE;
 +
 +    if (pkt->dts == AV_NOPTS_VALUE)
 +        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.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
 +    opkt.flags    = pkt->flags;
 +
 +    // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
 +    if (  ost->st->codec->codec_id != AV_CODEC_ID_H264
 +       && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
 +       && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
 +       && ost->st->codec->codec_id != AV_CODEC_ID_VC1
 +       ) {
 +        if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
 +            opkt.destruct = av_destruct_packet;
 +    } else {
 +        opkt.data = pkt->data;
 +        opkt.size = pkt->size;
 +    }
 +
 +    if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (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++;
 +    av_free_packet(&opkt);
 +}
 +
 +static void rate_emu_sleep(InputStream *ist)
 +{
 +    if (input_files[ist->file_index]->rate_emu) {
 +        int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
 +        int64_t now = av_gettime() - ist->start;
 +        if (pts > now)
 +            av_usleep(pts - now);
 +    }
 +}
 +
 +int guess_input_channel_layout(InputStream *ist)
 +{
 +    AVCodecContext *dec = ist->st->codec;
 +
 +    if (!dec->channel_layout) {
 +        char layout_name[256];
 +
 +        dec->channel_layout = av_get_default_channel_layout(dec->channels);
 +        if (!dec->channel_layout)
 +            return 0;
 +        av_get_channel_layout_string(layout_name, sizeof(layout_name),
 +                                     dec->channels, dec->channel_layout);
 +        av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for  Input Stream "
 +               "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
 +    }
 +    return 1;
 +}
 +
 +static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
 +{
 +    AVFrame *decoded_frame;
 +    AVCodecContext *avctx = ist->st->codec;
 +    int i, ret, resample_changed;
 +    AVRational decoded_frame_tb;
 +
 +    if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
 +        return AVERROR(ENOMEM);
 +    else
 +        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 && avctx->sample_rate <= 0) {
 +        av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
 +        return AVERROR_INVALIDDATA;
 +    }
 +
 +    if (!*got_output || ret < 0) {
 +        if (!pkt->size) {
 +            for (i = 0; i < ist->nb_filters; i++)
 +                av_buffersrc_add_ref(ist->filters[i]->filter, NULL,
 +                                     AV_BUFFERSRC_FLAG_NO_COPY);
 +        }
 +        return ret;
 +    }
 +
 +#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);
 +
 +    resample_changed = ist->resample_sample_fmt     != decoded_frame->format         ||
 +                       ist->resample_channels       != avctx->channels               ||
 +                       ist->resample_channel_layout != decoded_frame->channel_layout ||
 +                       ist->resample_sample_rate    != decoded_frame->sample_rate;
 +    if (resample_changed) {
 +        char layout1[64], layout2[64];
 +
 +        if (!guess_input_channel_layout(ist)) {
 +            av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
 +                   "layout for Input Stream #%d.%d\n", ist->file_index,
 +                   ist->st->index);
 +            exit_program(1);
 +        }
 +        decoded_frame->channel_layout = avctx->channel_layout;
 +
 +        av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
 +                                     ist->resample_channel_layout);
 +        av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
 +                                     decoded_frame->channel_layout);
 +
 +        av_log(NULL, AV_LOG_INFO,
 +               "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",
 +               ist->file_index, ist->st->index,
 +               ist->resample_sample_rate,  av_get_sample_fmt_name(ist->resample_sample_fmt),
 +               ist->resample_channels, layout1,
 +               decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
 +               avctx->channels, layout2);
 +
 +        ist->resample_sample_fmt     = decoded_frame->format;
 +        ist->resample_sample_rate    = decoded_frame->sample_rate;
 +        ist->resample_channel_layout = decoded_frame->channel_layout;
 +        ist->resample_channels       = avctx->channels;
 +
 +        for (i = 0; i < nb_filtergraphs; i++)
 +            if (ist_in_filtergraph(filtergraphs[i], ist)) {
 +                FilterGraph *fg = filtergraphs[i];
 +                int j;
 +                if (configure_filtergraph(fg) < 0) {
 +                    av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
 +                    exit_program(1);
 +                }
 +                for (j = 0; j < fg->nb_outputs; j++) {
 +                    OutputStream *ost = fg->outputs[j]->ost;
 +                    if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
 +                        !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
 +                        av_buffersink_set_frame_size(ost->filter->filter,
 +                                                     ost->st->codec->frame_size);
 +                }
 +            }
 +    }
 +
 +    /* if the decoder provides a pts, use it instead of the last packet pts.
 +       the decoder could be delaying output by a packet or more. */
 +    if (decoded_frame->pts != AV_NOPTS_VALUE) {
 +        ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
 +        decoded_frame_tb   = avctx->time_base;
 +    } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
 +        decoded_frame->pts = decoded_frame->pkt_pts;
 +        pkt->pts           = AV_NOPTS_VALUE;
 +        decoded_frame_tb   = ist->st->time_base;
 +    } else if (pkt->pts != AV_NOPTS_VALUE) {
 +        decoded_frame->pts = pkt->pts;
 +        pkt->pts           = AV_NOPTS_VALUE;
 +        decoded_frame_tb   = ist->st->time_base;
 +    }else {
 +        decoded_frame->pts = ist->dts;
 +        decoded_frame_tb   = AV_TIME_BASE_Q;
 +    }
 +    if (decoded_frame->pts != AV_NOPTS_VALUE)
 +        decoded_frame->pts = av_rescale_q(decoded_frame->pts,
 +                                          decoded_frame_tb,
 +                                          (AVRational){1, ist->st->codec->sample_rate});
 +    for (i = 0; i < ist->nb_filters; i++)
 +        av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0);
 +
 +    decoded_frame->pts = AV_NOPTS_VALUE;
 +
 +    return ret;
 +}
 +
 +static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
 +{
 +    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()))
 +        return AVERROR(ENOMEM);
 +    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 (!*got_output || ret < 0) {
 +        if (!pkt->size) {
 +            for (i = 0; i < ist->nb_filters; i++)
 +                av_buffersrc_add_ref(ist->filters[i]->filter, NULL, AV_BUFFERSRC_FLAG_NO_COPY);
 +        }
 +        return ret;
 +    }
 +
 +    quality = same_quant ? decoded_frame->quality : 0;
 +
 +    if(ist->top_field_first>=0)
 +        decoded_frame->top_field_first = ist->top_field_first;
 +
 +    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);
 +
 +    if (debug_ts) {
 +        av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
 +                "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
 +                ist->st->index, av_ts2str(decoded_frame->pts),
 +                av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
 +                best_effort_timestamp,
 +                av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
 +                decoded_frame->key_frame, decoded_frame->pict_type);
 +    }
 +
 +    pkt->size = 0;
 +    pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
 +
 +    rate_emu_sleep(ist);
 +
 +    if (ist->st->sample_aspect_ratio.num)
 +        decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
 +
 +    resample_changed = ist->resample_width   != decoded_frame->width  ||
 +                       ist->resample_height  != decoded_frame->height ||
 +                       ist->resample_pix_fmt != decoded_frame->format;
 +    if (resample_changed) {
 +        av_log(NULL, AV_LOG_INFO,
 +               "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
 +               ist->file_index, ist->st->index,
 +               ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),
 +               decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
 +
 +        ist->resample_width   = decoded_frame->width;
 +        ist->resample_height  = decoded_frame->height;
 +        ist->resample_pix_fmt = decoded_frame->format;
 +
 +        for (i = 0; i < nb_filtergraphs; i++)
 +            if (ist_in_filtergraph(filtergraphs[i], ist) &&
 +                configure_filtergraph(filtergraphs[i]) < 0) {
 +                av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
 +                exit_program(1);
 +            }
 +    }
 +
 +    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 (!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,
 +                                        AV_PERM_READ | AV_PERM_PRESERVE,
 +                                        ist->st->codec->width, ist->st->codec->height,
 +                                        ist->st->codec->pix_fmt);
 +
 +            avfilter_copy_frame_props(fb, decoded_frame);
 +            fb->buf->priv           = buf;
 +            fb->buf->free           = filter_release_buffer;
 +
 +            av_assert0(buf->refcount>0);
 +            buf->refcount++;
 +            av_buffersrc_add_ref(ist->filters[i]->filter, fb,
 +                                 AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
 +                                 AV_BUFFERSRC_FLAG_NO_COPY);
 +        } else
 +        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);
 +    return ret;
 +}
 +
 +static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
 +{
 +    AVSubtitle subtitle;
 +    int64_t pts = pkt->pts;
 +    int i, ret = avcodec_decode_subtitle2(ist->st->codec,
 +                                          &subtitle, got_output, pkt);
 +    if (ret < 0 || !*got_output) {
 +        if (!pkt->size)
 +            sub2video_flush(ist);
 +        return ret;
 +    }
 +
 +    if (ist->fix_sub_duration) {
 +        if (ist->prev_sub.got_output) {
 +            int end = av_rescale_q(pts - ist->prev_sub.pts, ist->st->time_base,
 +                                   (AVRational){ 1, 1000 });
 +            if (end < ist->prev_sub.subtitle.end_display_time) {
 +                av_log(ist->st->codec, AV_LOG_DEBUG,
 +                       "Subtitle duration reduced from %d to %d\n",
 +                       ist->prev_sub.subtitle.end_display_time, end);
 +                ist->prev_sub.subtitle.end_display_time = end;
 +            }
 +        }
 +        FFSWAP(int64_t,    pts,         ist->prev_sub.pts);
 +        FFSWAP(int,        *got_output, ist->prev_sub.got_output);
 +        FFSWAP(int,        ret,         ist->prev_sub.ret);
 +        FFSWAP(AVSubtitle, subtitle,    ist->prev_sub.subtitle);
 +    }
 +
 +    if (!*got_output || !subtitle.num_rects)
 +        return ret;
 +
 +    rate_emu_sleep(ist);
 +
 +    sub2video_update(ist, &subtitle, pkt->pts);
 +
 +    for (i = 0; i < nb_output_streams; i++) {
 +        OutputStream *ost = output_streams[i];
 +
 +        if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
 +            continue;
 +
 +        do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pts);
 +    }
 +
 +    avsubtitle_free(&subtitle);
 +    return ret;
 +}
 +
 +/* pkt = NULL means EOF (needed to flush decoder buffers) */
 +static int output_packet(InputStream *ist, const AVPacket *pkt)
 +{
 +    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->dts;
 +    if (ist->next_pts == AV_NOPTS_VALUE)
 +        ist->next_pts = ist->pts;
 +
 +    if (pkt == NULL) {
 +        /* EOF handling */
 +        av_init_packet(&avpkt);
 +        avpkt.data = NULL;
 +        avpkt.size = 0;
 +        goto handle_eof;
 +    } else {
 +        avpkt = *pkt;
 +    }
 +
 +    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 duration;
 +    handle_eof:
 +
 +        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,
 +                   "Multiple frames in a packet from stream %d\n", pkt->stream_index);
 +            ist->showed_multi_packet_warning = 1;
 +        }
 +
 +        switch (ist->st->codec->codec_type) {
 +        case AVMEDIA_TYPE_AUDIO:
 +            ret = decode_audio    (ist, &avpkt, &got_output);
 +            break;
 +        case AVMEDIA_TYPE_VIDEO:
 +            ret = decode_video    (ist, &avpkt, &got_output);
 +            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);
 +            break;
 +        default:
 +            return -1;
 +        }
 +
 +        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;
 +        }
 +        if (!got_output) {
 +            continue;
 +        }
 +    }
 +
 +    /* handle stream copy */
 +    if (!ist->decoding_needed) {
 +        rate_emu_sleep(ist);
 +        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 (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];
 +
 +        if (!check_output_constraints(ist, ost) || ost->encoding_needed)
 +            continue;
 +
 +        do_streamcopy(ist, ost, pkt);
 +    }
 +
 +    return 0;
 +}
 +
 +static void print_sdp(void)
 +{
 +    char sdp[2048];
 +    int i;
 +    AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
 +
 +    if (!avc)
 +        exit_program(1);
 +    for (i = 0; i < nb_output_files; i++)
 +        avc[i] = output_files[i]->ctx;
 +
 +    av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
 +    printf("SDP:\n%s\n", sdp);
 +    fflush(stdout);
 +    av_freep(&avc);
 +}
 +
 +static int init_input_stream(int ist_index, char *error, int error_len)
 +{
 +    InputStream *ist = input_streams[ist_index];
 +
 +    if (ist->decoding_needed) {
 +        AVCodec *codec = ist->dec;
 +        if (!codec) {
 +            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);
 +        }
 +
 +        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->buffer_pool;
 +        }
 +
 +        if (!av_dict_get(ist->opts, "threads", NULL, 0))
 +            av_dict_set(&ist->opts, "threads", "auto", 0);
 +        if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
 +            snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
 +                    ist->file_index, ist->st->index);
 +            return AVERROR(EINVAL);
 +        }
 +        assert_codec_experimental(ist->st->codec, 0);
 +        assert_avoptions(ist->opts);
 +    }
 +
 +    ist->next_pts = AV_NOPTS_VALUE;
 +    ist->next_dts = AV_NOPTS_VALUE;
 +    ist->is_start = 1;
 +
 +    return 0;
 +}
 +
 +static InputStream *get_input_stream(OutputStream *ost)
 +{
 +    if (ost->source_index >= 0)
 +        return input_streams[ost->source_index];
 +    return NULL;
 +}
 +
 +static void parse_forced_key_frames(char *kf, OutputStream *ost,
 +                                    AVCodecContext *avctx)
 +{
 +    char *p;
 +    int n = 1, i;
 +    int64_t t;
 +
 +    for (p = kf; *p; p++)
 +        if (*p == ',')
 +            n++;
 +    ost->forced_kf_count = n;
 +    ost->forced_kf_pts   = av_malloc(sizeof(*ost->forced_kf_pts) * n);
 +    if (!ost->forced_kf_pts) {
 +        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++) {
 +        char *next = strchr(p, ',');
 +
 +        if (next)
 +            *next++ = 0;
 +
 +        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);
 +
 +        p = next;
 +    }
 +}
 +
 +static void report_new_stream(int input_index, AVPacket *pkt)
 +{
 +    InputFile *file = input_files[input_index];
 +    AVStream *st = file->ctx->streams[pkt->stream_index];
 +
 +    if (pkt->stream_index < file->nb_streams_warn)
 +        return;
 +    av_log(file->ctx, AV_LOG_WARNING,
 +           "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
 +           av_get_media_type_string(st->codec->codec_type),
 +           input_index, pkt->stream_index,
 +           pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
 +    file->nb_streams_warn = pkt->stream_index + 1;
 +}
 +
 +static int transcode_init(void)
 +{
 +    int ret = 0, i, j, k;
 +    AVFormatContext *oc;
 +    AVCodecContext *codec;
 +    OutputStream *ost;
 +    InputStream *ist;
 +    char error[1024];
 +    int want_sdp = 1;
 +
 +    /* init framerate emulation */
 +    for (i = 0; i < nb_input_files; i++) {
 +        InputFile *ifile = input_files[i];
 +        if (ifile->rate_emu)
 +            for (j = 0; j < ifile->nb_streams; j++)
 +                input_streams[j + ifile->ist_index]->start = av_gettime();
 +    }
 +
 +    /* output stream init */
 +    for (i = 0; i < nb_output_files; i++) {
 +        oc = output_files[i]->ctx;
 +        if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
 +            av_dump_format(oc, i, oc->filename, 1);
 +            av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
 +            return AVERROR(EINVAL);
 +        }
 +    }
 +
 +    /* init complex filtergraphs */
 +    for (i = 0; i < nb_filtergraphs; i++)
 +        if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
 +            return ret;
 +
 +    /* for each output stream, we compute the right encoding parameters */
 +    for (i = 0; i < nb_output_streams; i++) {
 +        AVCodecContext *icodec = NULL;
 +        ost = output_streams[i];
 +        oc  = output_files[ost->file_index]->ctx;
 +        ist = get_input_stream(ost);
 +
 +        if (ost->attachment_filename)
 +            continue;
 +
 +        codec  = ost->st->codec;
 +
 +        if (ist) {
 +            icodec = ist->st->codec;
 +
 +            ost->st->disposition          = ist->st->disposition;
 +            codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
 +            codec->chroma_sample_location = icodec->chroma_sample_location;
 +        }
 +
 +        if (ost->stream_copy) {
 +            uint64_t extra_size;
 +
 +            av_assert0(ist && !ost->filter);
 +
 +            extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
 +
 +            if (extra_size > INT_MAX) {
 +                return AVERROR(EINVAL);
 +            }
 +
 +            /* if stream_copy is selected, no need to decode or encode */
 +            codec->codec_id   = icodec->codec_id;
 +            codec->codec_type = icodec->codec_type;
 +
 +            if (!codec->codec_tag) {
 +                if (!oc->oformat->codec_tag ||
 +                     av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
 +                     av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
 +                    codec->codec_tag = icodec->codec_tag;
 +            }
 +
 +            codec->bit_rate       = icodec->bit_rate;
 +            codec->rc_max_rate    = icodec->rc_max_rate;
 +            codec->rc_buffer_size = icodec->rc_buffer_size;
 +            codec->field_order    = icodec->field_order;
 +            codec->extradata      = av_mallocz(extra_size);
 +            if (!codec->extradata) {
 +                return AVERROR(ENOMEM);
 +            }
 +            memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
 +            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(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
 +                               && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
 +                               && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
 +                               && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
 +                     || copy_tb==2){
 +                    codec->time_base.num = ist->st->r_frame_rate.den;
 +                    codec->time_base.den = 2*ist->st->r_frame_rate.num;
 +                    codec->ticks_per_frame = 2;
 +                } else 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;
 +                }
 +            }
 +
 +            if(ost->frame_rate.num)
 +                codec->time_base = av_inv_q(ost->frame_rate);
 +
 +            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:
 +                if (audio_volume != 256) {
 +                    av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
 +                    exit_program(1);
 +                }
 +                codec->channel_layout     = icodec->channel_layout;
 +                codec->sample_rate        = icodec->sample_rate;
 +                codec->channels           = icodec->channels;
 +                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->block_align == 1152) && codec->codec_id == AV_CODEC_ID_MP3)
 +                    codec->block_align= 0;
 +                if(codec->codec_id == AV_CODEC_ID_AC3)
 +                    codec->block_align= 0;
 +                break;
 +            case AVMEDIA_TYPE_VIDEO:
 +                codec->pix_fmt            = icodec->pix_fmt;
 +                codec->width              = icodec->width;
 +                codec->height             = icodec->height;
 +                codec->has_b_frames       = icodec->has_b_frames;
 +                if (!codec->sample_aspect_ratio.num) {
 +                    codec->sample_aspect_ratio   =
 +                    ost->st->sample_aspect_ratio =
 +                        ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
 +                        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;
 +                codec->height = icodec->height;
 +                break;
 +            case AVMEDIA_TYPE_DATA:
 +            case AVMEDIA_TYPE_ATTACHMENT:
 +                break;
 +            default:
 +                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), "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;
 +            }
 +
 +            if (ist)
 +                ist->decoding_needed = 1;
 +            ost->encoding_needed = 1;
 +
 +            if (!ost->filter &&
 +                (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
 +                 codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
 +                    FilterGraph *fg;
 +                    fg = init_simple_filtergraph(ist, ost);
 +                    if (configure_filtergraph(fg)) {
 +                        av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
 +                        exit(1);
 +                    }
 +            }
 +
 +            if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
 +                if (ost->filter && !ost->frame_rate.num)
 +                    ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
 +                if (ist && !ost->frame_rate.num)
 +                    ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
 +//                    ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
 +                if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
 +                    int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
 +                    ost->frame_rate = ost->enc->supported_framerates[idx];
 +                }
 +            }
 +
 +            switch (codec->codec_type) {
 +            case AVMEDIA_TYPE_AUDIO:
 +                codec->sample_fmt     = ost->filter->filter->inputs[0]->format;
 +                codec->sample_rate    = ost->filter->filter->inputs[0]->sample_rate;
 +                codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
 +                codec->channels       = av_get_channel_layout_nb_channels(codec->channel_layout);
 +                codec->time_base      = (AVRational){ 1, codec->sample_rate };
 +                break;
 +            case AVMEDIA_TYPE_VIDEO:
 +                codec->time_base = av_inv_q(ost->frame_rate);
 +                if (ost->filter && !(codec->time_base.num && codec->time_base.den))
 +                    codec->time_base = ost->filter->filter->inputs[0]->time_base;
 +                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;
 +                codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
 +                    ost->frame_aspect_ratio ? // overridden by the -aspect cli option
 +                    av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
 +                    ost->filter->filter->inputs[0]->sample_aspect_ratio;
 +                codec->pix_fmt = ost->filter->filter->inputs[0]->format;
 +
 +                if (!icodec ||
 +                    codec->width   != icodec->width  ||
 +                    codec->height  != icodec->height ||
 +                    codec->pix_fmt != icodec->pix_fmt) {
 +                    codec->bits_per_raw_sample = frame_bits_per_raw_sample;
 +                }
 +
 +                if (ost->forced_keyframes)
 +                    parse_forced_key_frames(ost->forced_keyframes, ost,
 +                                            ost->st->codec);
 +                break;
 +            case AVMEDIA_TYPE_SUBTITLE:
 +                codec->time_base = (AVRational){1, 1000};
 +                if (!codec->width) {
 +                    codec->width     = input_streams[ost->source_index]->st->codec->width;
 +                    codec->height    = input_streams[ost->source_index]->st->codec->height;
 +                }
 +                break;
 +            default:
 +                abort();
 +                break;
 +            }
 +            /* two pass mode */
 +            if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
 +                char logfilename[1024];
 +                FILE *f;
 +
 +                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
 +                         pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
 +                         i);
 +                if (!strcmp(ost->enc->name, "libx264")) {
 +                    av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
 +                } else {
 +                    if (codec->flags & CODEC_FLAG_PASS2) {
 +                        char  *logbuffer;
 +                        size_t logbuffer_size;
 +                        if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
 +                            av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
 +                                   logfilename);
 +                            exit_program(1);
 +                        }
 +                        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;
 +                    }
 +                }
 +            }
 +        }
 +    }
 +
 +    /* open each encoder */
 +    for (i = 0; i < nb_output_streams; i++) {
 +        ost = output_streams[i];
 +        if (ost->encoding_needed) {
 +            AVCodec      *codec = ost->enc;
 +            AVCodecContext *dec = NULL;
 +
 +            if ((ist = get_input_stream(ost)))
 +                dec = ist->st->codec;
 +            if (dec && dec->subtitle_header) {
 +                /* ASS code assumes this buffer is null terminated so add extra byte. */
 +                ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
 +                if (!ost->st->codec->subtitle_header) {
 +                    ret = AVERROR(ENOMEM);
 +                    goto dump_format;
 +                }
 +                memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
 +                ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
 +            }
 +            if (!av_dict_get(ost->opts, "threads", NULL, 0))
 +                av_dict_set(&ost->opts, "threads", "auto", 0);
 +            if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
 +                snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
 +                        ost->file_index, ost->index);
 +                ret = AVERROR(EINVAL);
 +                goto dump_format;
 +            }
 +            if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
 +                !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
 +                av_buffersink_set_frame_size(ost->filter->filter,
 +                                             ost->st->codec->frame_size);
 +            assert_codec_experimental(ost->st->codec, 1);
 +            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");
 +            extra_size += ost->st->codec->extradata_size;
 +
 +            if (ost->st->codec->me_threshold)
 +                input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
 +        }
 +    }
 +
 +    /* init input streams */
 +    for (i = 0; i < nb_input_streams; i++)
 +        if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
 +            goto dump_format;
 +
 +    /* discard unused programs */
 +    for (i = 0; i < nb_input_files; i++) {
 +        InputFile *ifile = input_files[i];
 +        for (j = 0; j < ifile->ctx->nb_programs; j++) {
 +            AVProgram *p = ifile->ctx->programs[j];
 +            int discard  = AVDISCARD_ALL;
 +
 +            for (k = 0; k < p->nb_stream_indexes; k++)
 +                if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
 +                    discard = AVDISCARD_DEFAULT;
 +                    break;
 +                }
 +            p->discard = discard;
 +        }
 +    }
 +
 +    /* open files and write file headers */
 +    for (i = 0; i < nb_output_files; i++) {
 +        oc = output_files[i]->ctx;
 +        oc->interrupt_callback = int_cb;
 +        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);
 +        if (strcmp(oc->oformat->name, "rtp")) {
 +            want_sdp = 0;
 +        }
 +    }
 +
 + dump_format:
 +    /* dump the file output parameters - cannot be done before in case
 +       of stream copy */
 +    for (i = 0; i < nb_output_files; i++) {
 +        av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
 +    }
 +
 +    /* dump the stream mapping */
 +    av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
 +    for (i = 0; i < nb_input_streams; i++) {
 +        ist = input_streams[i];
 +
 +        for (j = 0; j < ist->nb_filters; j++) {
 +            if (ist->filters[j]->graph->graph_desc) {
 +                av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
 +                       ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
 +                       ist->filters[j]->name);
 +                if (nb_filtergraphs > 1)
 +                    av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
 +                av_log(NULL, AV_LOG_INFO, "\n");
 +            }
 +        }
 +    }
 +
 +    for (i = 0; i < nb_output_streams; i++) {
 +        ost = output_streams[i];
 +
 +        if (ost->attachment_filename) {
 +            /* an attached file */
 +            av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
 +                   ost->attachment_filename, ost->file_index, ost->index);
 +            continue;
 +        }
 +
 +        if (ost->filter && ost->filter->graph->graph_desc) {
 +            /* output from a complex graph */
 +            av_log(NULL, AV_LOG_INFO, "  %s", ost->filter->name);
 +            if (nb_filtergraphs > 1)
 +                av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
 +
 +            av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
 +                   ost->index, ost->enc ? ost->enc->name : "?");
 +            continue;
 +        }
 +
 +        av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
 +               input_streams[ost->source_index]->file_index,
 +               input_streams[ost->source_index]->st->index,
 +               ost->file_index,
 +               ost->index);
 +        if (ost->sync_ist != input_streams[ost->source_index])
 +            av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
 +                   ost->sync_ist->file_index,
 +                   ost->sync_ist->st->index);
 +        if (ost->stream_copy)
 +            av_log(NULL, AV_LOG_INFO, " (copy)");
 +        else
 +            av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
 +                   input_streams[ost->source_index]->dec->name : "?",
 +                   ost->enc ? ost->enc->name : "?");
 +        av_log(NULL, AV_LOG_INFO, "\n");
 +    }
 +
 +    if (ret) {
 +        av_log(NULL, AV_LOG_ERROR, "%s\n", error);
 +        return ret;
 +    }
 +
 +    if (want_sdp) {
 +        print_sdp();
 +    }
 +
 +    return 0;
 +}
 +
 +/**
 + * @return 1 if there are still streams where more output is wanted,
 + *         0 otherwise
 + */
 +static int need_output(void)
 +{
 +    int i;
 +
 +    for (i = 0; i < nb_output_streams; i++) {
 +        OutputStream *ost    = output_streams[i];
 +        OutputFile *of       = output_files[ost->file_index];
 +        AVFormatContext *os  = output_files[ost->file_index]->ctx;
 +
 +        if (ost->finished ||
 +            (os->pb && avio_tell(os->pb) >= of->limit_filesize))
 +            continue;
 +        if (ost->frame_number >= ost->max_frames) {
 +            int j;
 +            for (j = 0; j < of->ctx->nb_streams; j++)
 +                output_streams[of->ost_index + j]->finished = 1;
 +            continue;
 +        }
 +
 +        return 1;
 +    }
 +
 +    return 0;
 +}
 +
 +static int input_acceptable(InputStream *ist)
 +{
 +    av_assert1(!ist->discard);
 +    return !input_files[ist->file_index]->eagain &&
 +           !input_files[ist->file_index]->eof_reached;
 +}
 +
 +static int find_graph_input(FilterGraph *graph)
 +{
 +    int i, nb_req_max = 0, file_index = -1;
 +
 +    for (i = 0; i < graph->nb_inputs; i++) {
 +        int nb_req = av_buffersrc_get_nb_failed_requests(graph->inputs[i]->filter);
 +        if (nb_req > nb_req_max) {
 +            InputStream *ist = graph->inputs[i]->ist;
 +            if (input_acceptable(ist)) {
 +                nb_req_max = nb_req;
 +                file_index = ist->file_index;
 +            }
 +        }
 +    }
 +
 +    return file_index;
 +}
 +
 +/**
 + * Select the input file to read from.
 + *
 + * @return  >=0 index of the input file to use;
 + *          -1  if no file is acceptable;
 + *          -2  to read from filters without reading from a file
 + */
 +static int select_input_file(void)
 +{
 +    int i, ret, nb_active_out = nb_output_streams, ost_index = -1;
 +    int64_t opts_min;
 +    OutputStream *ost;
 +    AVFilterBufferRef *dummy;
 +
 +    for (i = 0; i < nb_output_streams; i++)
 +        nb_active_out -= output_streams[i]->unavailable =
 +            output_streams[i]->finished;
 +    while (nb_active_out) {
 +        opts_min = INT64_MAX;
 +        ost_index = -1;
 +        for (i = 0; i < nb_output_streams; i++) {
 +            OutputStream *ost = output_streams[i];
 +            int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
 +                                        AV_TIME_BASE_Q);
 +            if (!ost->unavailable && opts < opts_min) {
 +                opts_min  = opts;
 +                ost_index = i;
 +            }
 +        }
 +        if (ost_index < 0)
 +            return -1;
 +
 +        ost = output_streams[ost_index];
 +        if (ost->source_index >= 0) {
 +            /* ost is directly connected to an input */
 +            InputStream *ist = input_streams[ost->source_index];
 +            if (input_acceptable(ist))
 +                return ist->file_index;
 +        } else {
 +            /* ost is connected to a complex filtergraph */
 +            av_assert1(ost->filter);
 +            ret = av_buffersink_get_buffer_ref(ost->filter->filter, &dummy,
 +                                               AV_BUFFERSINK_FLAG_PEEK);
 +            if (ret >= 0)
 +                return -2;
 +            ret = find_graph_input(ost->filter->graph);
 +            if (ret >= 0)
 +                return ret;
 +        }
 +        ost->unavailable = 1;
 +        nb_active_out--;
 +    }
 +    return -1;
 +}
 +
 +static int check_keyboard_interaction(int64_t cur_time)
 +{
 +    int i, ret, key;
 +    static int64_t last_time;
 +    if (received_nb_signals)
 +        return AVERROR_EXIT;
 +    /* 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')
 +        return AVERROR_EXIT;
 +    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++) {
 +            OutputStream *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"
 +        );
 +    }
 +    return 0;
 +}
 +
 +#if HAVE_PTHREADS
 +static void *input_thread(void *arg)
 +{
 +    InputFile *f = arg;
 +    int ret = 0;
 +
 +    while (!transcoding_finished && ret >= 0) {
 +        AVPacket pkt;
 +        ret = av_read_frame(f->ctx, &pkt);
 +
 +        if (ret == AVERROR(EAGAIN)) {
 +            av_usleep(10000);
 +            ret = 0;
 +            continue;
 +        } else if (ret < 0)
 +            break;
 +
 +        pthread_mutex_lock(&f->fifo_lock);
 +        while (!av_fifo_space(f->fifo))
 +            pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
 +
 +        av_dup_packet(&pkt);
 +        av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
 +
 +        pthread_mutex_unlock(&f->fifo_lock);
 +    }
 +
 +    f->finished = 1;
 +    return NULL;
 +}
 +
 +static void free_input_threads(void)
 +{
 +    int i;
 +
 +    if (nb_input_files == 1)
 +        return;
 +
 +    transcoding_finished = 1;
 +
 +    for (i = 0; i < nb_input_files; i++) {
 +        InputFile *f = input_files[i];
 +        AVPacket pkt;
 +
 +        if (!f->fifo || f->joined)
 +            continue;
 +
 +        pthread_mutex_lock(&f->fifo_lock);
 +        while (av_fifo_size(f->fifo)) {
 +            av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
 +            av_free_packet(&pkt);
 +        }
 +        pthread_cond_signal(&f->fifo_cond);
 +        pthread_mutex_unlock(&f->fifo_lock);
 +
 +        pthread_join(f->thread, NULL);
 +        f->joined = 1;
 +
 +        while (av_fifo_size(f->fifo)) {
 +            av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
 +            av_free_packet(&pkt);
 +        }
 +        av_fifo_free(f->fifo);
 +    }
 +}
 +
 +static int init_input_threads(void)
 +{
 +    int i, ret;
 +
 +    if (nb_input_files == 1)
 +        return 0;
 +
 +    for (i = 0; i < nb_input_files; i++) {
 +        InputFile *f = input_files[i];
 +
 +        if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
 +            return AVERROR(ENOMEM);
 +
 +        pthread_mutex_init(&f->fifo_lock, NULL);
 +        pthread_cond_init (&f->fifo_cond, NULL);
 +
 +        if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
 +            return AVERROR(ret);
 +    }
 +    return 0;
 +}
 +
 +static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
 +{
 +    int ret = 0;
 +
 +    pthread_mutex_lock(&f->fifo_lock);
 +
 +    if (av_fifo_size(f->fifo)) {
 +        av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
 +        pthread_cond_signal(&f->fifo_cond);
 +    } else {
 +        if (f->finished)
 +            ret = AVERROR_EOF;
 +        else
 +            ret = AVERROR(EAGAIN);
 +    }
 +
 +    pthread_mutex_unlock(&f->fifo_lock);
 +
 +    return ret;
 +}
 +#endif
 +
 +static int get_input_packet(InputFile *f, AVPacket *pkt)
 +{
 +#if HAVE_PTHREADS
 +    if (nb_input_files > 1)
 +        return get_input_packet_mt(f, pkt);
 +#endif
 +    return av_read_frame(f->ctx, pkt);
 +}
 +
 +static int got_eagain(void)
 +{
 +    int i;
 +    for (i = 0; i < nb_input_files; i++)
 +        if (input_files[i]->eagain)
 +            return 1;
 +    return 0;
 +}
 +
 +static void reset_eagain(void)
 +{
 +    int i;
 +    for (i = 0; i < nb_input_files; i++)
 +        input_files[i]->eagain = 0;
 +}
 +
 +/**
 + * @return
 + * - 0 -- one packet was read and processed
 + * - AVERROR(EAGAIN) -- no packets were available for selected file,
 + *   this function should be called again
 + * - AVERROR_EOF -- this function should not be called again
 + */
 +static int process_input(void)
 +{
 +    InputFile *ifile;
 +    AVFormatContext *is;
 +    InputStream *ist;
 +    AVPacket pkt;
 +    int ret, i, j;
 +    int file_index;
 +
 +    /* select the stream that we must read now */
 +    file_index = select_input_file();
 +    /* if none, if is finished */
 +    if (file_index == -2) {
 +        poll_filters() ;
 +        return AVERROR(EAGAIN);
 +    }
 +    if (file_index < 0) {
 +        if (got_eagain()) {
 +            reset_eagain();
 +            av_usleep(10000);
 +            return AVERROR(EAGAIN);
 +        }
 +        av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
 +        return AVERROR_EOF;
 +    }
 +    ifile = input_files[file_index];
 +
 +    is  = ifile->ctx;
 +    ret = get_input_packet(ifile, &pkt);
 +
 +    if (ret == AVERROR(EAGAIN)) {
 +        ifile->eagain = 1;
 +        return ret;
 +    }
 +    if (ret < 0) {
 +        if (ret != AVERROR_EOF) {
 +            print_error(is->filename, ret);
 +            if (exit_on_error)
 +                exit_program(1);
 +        }
 +        ifile->eof_reached = 1;
 +
 +        for (i = 0; i < ifile->nb_streams; i++) {
 +            ist = input_streams[ifile->ist_index + i];
 +            if (ist->decoding_needed)
 +                output_packet(ist, NULL);
 +            poll_filters();
 +        }
 +
 +        if (opt_shortest)
 +            return AVERROR_EOF;
 +        else
 +            return AVERROR(EAGAIN);
 +    }
 +
 +    reset_eagain();
 +
 +    if (do_pkt_dump) {
 +        av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
 +                         is->streams[pkt.stream_index]);
 +    }
 +    /* the following test is needed in case new streams appear
 +       dynamically in stream : we ignore them */
 +    if (pkt.stream_index >= ifile->nb_streams) {
 +        report_new_stream(file_index, &pkt);
 +        goto discard_packet;
 +    }
 +
 +    ist = input_streams[ifile->ist_index + pkt.stream_index];
 +    if (ist->discard)
 +        goto discard_packet;
 +
 +    if(!ist->wrap_correction_done && input_files[file_index]->ctx->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
 +        uint64_t stime = av_rescale_q(input_files[file_index]->ctx->start_time, AV_TIME_BASE_Q, ist->st->time_base);
 +        uint64_t stime2= stime + (1LL<<ist->st->pts_wrap_bits);
 +        ist->wrap_correction_done = 1;
 +        if(pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime && pkt.dts - stime > stime2 - pkt.dts) {
 +            pkt.dts -= 1LL<<ist->st->pts_wrap_bits;
 +            ist->wrap_correction_done = 0;
 +        }
 +        if(pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime && pkt.pts - stime > stime2 - pkt.pts) {
 +            pkt.pts -= 1LL<<ist->st->pts_wrap_bits;
 +            ist->wrap_correction_done = 0;
 +        }
 +    }
 +
 +    if (pkt.dts != AV_NOPTS_VALUE)
 +        pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
 +    if (pkt.pts != AV_NOPTS_VALUE)
 +        pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
 +
 +    if (pkt.pts != AV_NOPTS_VALUE)
 +        pkt.pts *= ist->ts_scale;
 +    if (pkt.dts != AV_NOPTS_VALUE)
 +        pkt.dts *= ist->ts_scale;
 +
 +    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",
 +                ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
 +                av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
 +                av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
 +                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 (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){
 +            ifile->ts_offset -= delta;
 +            av_log(NULL, AV_LOG_DEBUG,
 +                   "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
 +                   delta, ifile->ts_offset);
 +            pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
 +            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)
 +               ) {
 +                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)
 +                   ) {
 +                    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;
 +                }
 +            }
 +        }
 +    }
 +
 +    sub2video_heartbeat(ist, pkt.pts);
 +
 +    if ((ret = output_packet(ist, &pkt)) < 0 ||
 +        ((ret = poll_filters()) < 0 && ret != AVERROR_EOF)) {
 +        char buf[128];
 +        av_strerror(ret, buf, sizeof(buf));
 +        av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
 +                ist->file_index, ist->st->index, buf);
 +        if (exit_on_error)
 +            exit_program(1);
 +        av_free_packet(&pkt);
 +        return AVERROR(EAGAIN);
 +    }
 +
 +discard_packet:
 +    av_free_packet(&pkt);
 +
 +    return 0;
 +}
 +
 +/*
 + * The following code is the main loop of the file converter
 + */
 +static int transcode(void)
 +{
 +    int ret, i;
 +    AVFormatContext *os;
 +    OutputStream *ost;
 +    InputStream *ist;
 +    int64_t timer_start;
 +
 +    ret = transcode_init();
 +    if (ret < 0)
 +        goto fail;
 +
 +    if (stdin_interaction) {
 +        av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
 +    }
 +
 +    timer_start = av_gettime();
 +
 +#if HAVE_PTHREADS
 +    if ((ret = init_input_threads()) < 0)
 +        goto fail;
 +#endif
 +
 +    while (!received_sigterm) {
 +        int64_t cur_time= av_gettime();
 +
 +        /* if 'q' pressed, exits */
 +        if (stdin_interaction)
 +            if (check_keyboard_interaction(cur_time) < 0)
 +                break;
 +
 +        /* check if there's any stream where output is still needed */
 +        if (!need_output()) {
 +            av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
 +            break;
 +        }
 +
 +        ret = process_input();
 +        if (ret < 0) {
 +            if (ret == AVERROR(EAGAIN))
 +                continue;
 +            if (ret == AVERROR_EOF)
 +                break;
 +            av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
 +            break;
 +        }
 +
 +        /* dump report by using the output first video and audio streams */
 +        print_report(0, timer_start, cur_time);
 +    }
 +#if HAVE_PTHREADS
 +    free_input_threads();
 +#endif
 +
 +    /* at the end of stream, we must flush the decoder buffers */
 +    for (i = 0; i < nb_input_streams; i++) {
 +        ist = input_streams[i];
 +        if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
 +            output_packet(ist, NULL);
 +        }
 +    }
 +    poll_filters();
 +    flush_encoders();
 +
 +    term_exit();
 +
 +    /* write the trailer if needed and close file */
 +    for (i = 0; i < nb_output_files; i++) {
 +        os = output_files[i]->ctx;
 +        av_write_trailer(os);
 +    }
 +
 +    /* dump report by using the first video and audio streams */
 +    print_report(1, timer_start, av_gettime());
 +
 +    /* close each encoder */
 +    for (i = 0; i < nb_output_streams; i++) {
 +        ost = output_streams[i];
 +        if (ost->encoding_needed) {
 +            av_freep(&ost->st->codec->stats_in);
 +            avcodec_close(ost->st->codec);
 +        }
 +    }
 +
 +    /* close each decoder */
 +    for (i = 0; i < nb_input_streams; i++) {
 +        ist = input_streams[i];
 +        if (ist->decoding_needed) {
 +            avcodec_close(ist->st->codec);
 +        }
 +    }
 +
 +    /* finished ! */
 +    ret = 0;
 +
 + fail:
 +#if HAVE_PTHREADS
 +    free_input_threads();
 +#endif
 +
 +    if (output_streams) {
 +        for (i = 0; i < nb_output_streams; i++) {
 +            ost = output_streams[i];
 +            if (ost) {
 +                if (ost->stream_copy)
 +                    av_freep(&ost->st->codec->extradata);
 +                if (ost->logfile) {
 +                    fclose(ost->logfile);
 +                    ost->logfile = NULL;
 +                }
 +                av_freep(&ost->st->codec->subtitle_header);
 +                av_free(ost->forced_kf_pts);
 +                av_dict_free(&ost->opts);
 +            }
 +        }
 +    }
 +    return ret;
 +}
 +
 +
 +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
 +    struct rusage rusage;
 +    getrusage(RUSAGE_SELF, &rusage);
 +    return (int64_t)rusage.ru_maxrss * 1024;
 +#elif HAVE_GETPROCESSMEMORYINFO
 +    HANDLE proc;
 +    PROCESS_MEMORY_COUNTERS memcounters;
 +    proc = GetCurrentProcess();
 +    memcounters.cb = sizeof(memcounters);
 +    GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
 +    return memcounters.PeakPagefileUsage;
 +#else
 +    return 0;
 +#endif
 +}
 +
 +static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
 +{
 +}
 +
 +static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
 +{
 +    int idx = locate_option(argc, argv, options, "cpuflags");
 +    if (idx && argv[idx + 1])
 +        opt_cpuflags("cpuflags", argv[idx + 1]);
 +}
 +
 +int main(int argc, char **argv)
 +{
 +    OptionsContext o = { 0 };
 +    int64_t ti;
 +
 +    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();
 +#endif
 +    avfilter_register_all();
 +    av_register_all();
 +    avformat_network_init();
 +
 +    show_banner(argc, argv, options);
 +
 +    term_init();
 +
 +    parse_cpuflags(argc, argv, options);
 +
 +    /* parse options */
 +    parse_options(&o, argc, argv, options, opt_output_file);
 +
 +    if (nb_output_files <= 0 && nb_input_files == 0) {
 +        show_usage();
 +        av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
 +        exit_program(1);
 +    }
 +
 +    /* file converter / grab */
 +    if (nb_output_files <= 0) {
 +        av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
 +        exit_program(1);
 +    }
 +
 +//     if (nb_input_files == 0) {
 +//         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
 +//         exit_program(1);
 +//     }
 +
 +    current_time = ti = getutime();
 +    if (transcode() < 0)
 +        exit_program(1);
 +    ti = getutime() - ti;
 +    if (do_benchmark) {
 +        int maxrss = getmaxrss() / 1024;
 +        printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
 +    }
 +
 +    exit_program(0);
 +    return 0;
 +}
diff --cc ffprobe.c
index 6de9eb3,0000000..a40f756
mode 100644,000000..100644
--- /dev/null
+++ b/ffprobe.c
@@@ -1,2205 -1,0 +1,2206 @@@
-                 index = (long long int) (log(vald)/log(2)) / 10;
 +/*
 + * Copyright (c) 2007-2010 Stefano Sabatini
 + *
 + * This file is part of FFmpeg.
 + *
 + * 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.
 + *
 + * 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 FFmpeg; if not, write to the Free Software
 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 + */
 +
 +/**
 + * @file
 + * simple media prober based on the FFmpeg libraries
 + */
 +
 +#include "config.h"
 +#include "version.h"
 +
 +#include "libavformat/avformat.h"
 +#include "libavcodec/avcodec.h"
 +#include "libavutil/avstring.h"
 +#include "libavutil/bprint.h"
 +#include "libavutil/opt.h"
 +#include "libavutil/pixdesc.h"
 +#include "libavutil/dict.h"
++#include "libavutil/libm.h"
 +#include "libavutil/timecode.h"
 +#include "libavdevice/avdevice.h"
 +#include "libswscale/swscale.h"
 +#include "libswresample/swresample.h"
 +#include "libpostproc/postprocess.h"
 +#include "cmdutils.h"
 +
 +const char program_name[] = "ffprobe";
 +const int program_birth_year = 2007;
 +
 +static int do_count_frames = 0;
 +static int do_count_packets = 0;
 +static int do_read_frames  = 0;
 +static int do_read_packets = 0;
 +static int do_show_error   = 0;
 +static int do_show_format  = 0;
 +static int do_show_frames  = 0;
 +static AVDictionary *fmt_entries_to_show = NULL;
 +static int do_show_packets = 0;
 +static int do_show_streams = 0;
 +static int do_show_data    = 0;
 +static int do_show_program_version  = 0;
 +static int do_show_library_versions = 0;
 +
 +static int show_value_unit              = 0;
 +static int use_value_prefix             = 0;
 +static int use_byte_value_binary_prefix = 0;
 +static int use_value_sexagesimal_format = 0;
 +static int show_private_data            = 1;
 +
 +static char *print_format;
 +
 +static const OptionDef *options;
 +
 +/* FFprobe context */
 +static const char *input_filename;
 +static AVInputFormat *iformat = NULL;
 +
 +static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
 +static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
 +
 +static const char unit_second_str[]         = "s"    ;
 +static const char unit_hertz_str[]          = "Hz"   ;
 +static const char unit_byte_str[]           = "byte" ;
 +static const char unit_bit_per_second_str[] = "bit/s";
 +static uint64_t *nb_streams_packets;
 +static uint64_t *nb_streams_frames;
 +
 +void av_noreturn exit_program(int ret)
 +{
 +    av_dict_free(&fmt_entries_to_show);
 +    exit(ret);
 +}
 +
 +struct unit_value {
 +    union { double d; long long int i; } val;
 +    const char *unit;
 +};
 +
 +static char *value_string(char *buf, int buf_size, struct unit_value uv)
 +{
 +    double vald;
 +    int show_float = 0;
 +
 +    if (uv.unit == unit_second_str) {
 +        vald = uv.val.d;
 +        show_float = 1;
 +    } else {
 +        vald = uv.val.i;
 +    }
 +
 +    if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
 +        double secs;
 +        int hours, mins;
 +        secs  = vald;
 +        mins  = (int)secs / 60;
 +        secs  = secs - mins * 60;
 +        hours = mins / 60;
 +        mins %= 60;
 +        snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
 +    } else {
 +        const char *prefix_string = "";
 +        int l;
 +
 +        if (use_value_prefix && vald > 1) {
 +            long long int index;
 +
 +            if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
++                index = (long long int) (log2(vald)) / 10;
 +                index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
 +                vald /= pow(2, index * 10);
 +                prefix_string = binary_unit_prefixes[index];
 +            } else {
 +                index = (long long int) (log10(vald)) / 3;
 +                index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
 +                vald /= pow(10, index * 3);
 +                prefix_string = decimal_unit_prefixes[index];
 +            }
 +        }
 +
 +        if (show_float || (use_value_prefix && vald != (long long int)vald))
 +            l = snprintf(buf, buf_size, "%f", vald);
 +        else
 +            l = snprintf(buf, buf_size, "%lld", (long long int)vald);
 +        snprintf(buf+l, buf_size-l, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
 +                 prefix_string, show_value_unit ? uv.unit : "");
 +    }
 +
 +    return buf;
 +}
 +
 +/* WRITERS API */
 +
 +typedef struct WriterContext WriterContext;
 +
 +#define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
 +#define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
 +
 +typedef struct Writer {
 +    int priv_size;                  ///< private size for the writer context
 +    const char *name;
 +
 +    int  (*init)  (WriterContext *wctx, const char *args, void *opaque);
 +    void (*uninit)(WriterContext *wctx);
 +
 +    void (*print_header)(WriterContext *ctx);
 +    void (*print_footer)(WriterContext *ctx);
 +
 +    void (*print_chapter_header)(WriterContext *wctx, const char *);
 +    void (*print_chapter_footer)(WriterContext *wctx, const char *);
 +    void (*print_section_header)(WriterContext *wctx, const char *);
 +    void (*print_section_footer)(WriterContext *wctx, const char *);
 +    void (*print_integer)       (WriterContext *wctx, const char *, long long int);
 +    void (*print_rational)      (WriterContext *wctx, AVRational *q, char *sep);
 +    void (*print_string)        (WriterContext *wctx, const char *, const char *);
 +    void (*show_tags)           (WriterContext *wctx, AVDictionary *dict);
 +    int flags;                  ///< a combination or WRITER_FLAG_*
 +} Writer;
 +
 +struct WriterContext {
 +    const AVClass *class;           ///< class of the writer
 +    const Writer *writer;           ///< the Writer of which this is an instance
 +    char *name;                     ///< name of this writer instance
 +    void *priv;                     ///< private data for use by the filter
 +    unsigned int nb_item;           ///< number of the item printed in the given section, starting at 0
 +    unsigned int nb_section;        ///< number of the section printed in the given section sequence, starting at 0
 +    unsigned int nb_section_packet; ///< number of the packet section in case we are in "packets_and_frames" section
 +    unsigned int nb_section_frame;  ///< number of the frame  section in case we are in "packets_and_frames" section
 +    unsigned int nb_section_packet_frame; ///< nb_section_packet or nb_section_frame according if is_packets_and_frames
 +    unsigned int nb_chapter;        ///< number of the chapter, starting at 0
 +
 +    int multiple_sections;          ///< tells if the current chapter can contain multiple sections
 +    int is_fmt_chapter;             ///< tells if the current chapter is "format", required by the print_format_entry option
 +    int is_packets_and_frames;      ///< tells if the current section is "packets_and_frames"
 +};
 +
 +static const char *writer_get_name(void *p)
 +{
 +    WriterContext *wctx = p;
 +    return wctx->writer->name;
 +}
 +
 +static const AVClass writer_class = {
 +    "Writer",
 +    writer_get_name,
 +    NULL,
 +    LIBAVUTIL_VERSION_INT,
 +};
 +
 +static void writer_close(WriterContext **wctx)
 +{
 +    if (!*wctx)
 +        return;
 +
 +    if ((*wctx)->writer->uninit)
 +        (*wctx)->writer->uninit(*wctx);
 +    av_freep(&((*wctx)->priv));
 +    av_freep(wctx);
 +}
 +
 +static int writer_open(WriterContext **wctx, const Writer *writer,
 +                       const char *args, void *opaque)
 +{
 +    int ret = 0;
 +
 +    if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
 +        ret = AVERROR(ENOMEM);
 +        goto fail;
 +    }
 +
 +    if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
 +        ret = AVERROR(ENOMEM);
 +        goto fail;
 +    }
 +
 +    (*wctx)->class = &writer_class;
 +    (*wctx)->writer = writer;
 +    if ((*wctx)->writer->init)
 +        ret = (*wctx)->writer->init(*wctx, args, opaque);
 +    if (ret < 0)
 +        goto fail;
 +
 +    return 0;
 +
 +fail:
 +    writer_close(wctx);
 +    return ret;
 +}
 +
 +static inline void writer_print_header(WriterContext *wctx)
 +{
 +    if (wctx->writer->print_header)
 +        wctx->writer->print_header(wctx);
 +    wctx->nb_chapter = 0;
 +}
 +
 +static inline void writer_print_footer(WriterContext *wctx)
 +{
 +    if (wctx->writer->print_footer)
 +        wctx->writer->print_footer(wctx);
 +}
 +
 +static inline void writer_print_chapter_header(WriterContext *wctx,
 +                                               const char *chapter)
 +{
 +    wctx->nb_section =
 +    wctx->nb_section_packet = wctx->nb_section_frame =
 +    wctx->nb_section_packet_frame = 0;
 +    wctx->is_packets_and_frames = !strcmp(chapter, "packets_and_frames");
 +    wctx->multiple_sections = !strcmp(chapter, "packets") || !strcmp(chapter, "frames" ) ||
 +                              wctx->is_packets_and_frames ||
 +                              !strcmp(chapter, "streams") || !strcmp(chapter, "library_versions");
 +    wctx->is_fmt_chapter = !strcmp(chapter, "format");
 +
 +    if (wctx->writer->print_chapter_header)
 +        wctx->writer->print_chapter_header(wctx, chapter);
 +}
 +
 +static inline void writer_print_chapter_footer(WriterContext *wctx,
 +                                               const char *chapter)
 +{
 +    if (wctx->writer->print_chapter_footer)
 +        wctx->writer->print_chapter_footer(wctx, chapter);
 +    wctx->nb_chapter++;
 +}
 +
 +static inline void writer_print_section_header(WriterContext *wctx,
 +                                               const char *section)
 +{
 +    if (wctx->is_packets_and_frames)
 +        wctx->nb_section_packet_frame = !strcmp(section, "packet") ? wctx->nb_section_packet
 +                                                                   : wctx->nb_section_frame;
 +    if (wctx->writer->print_section_header)
 +        wctx->writer->print_section_header(wctx, section);
 +    wctx->nb_item = 0;
 +}
 +
 +static inline void writer_print_section_footer(WriterContext *wctx,
 +                                               const char *section)
 +{
 +    if (wctx->writer->print_section_footer)
 +        wctx->writer->print_section_footer(wctx, section);
 +    if (wctx->is_packets_and_frames) {
 +        if (!strcmp(section, "packet")) wctx->nb_section_packet++;
 +        else                            wctx->nb_section_frame++;
 +    }
 +    wctx->nb_section++;
 +}
 +
 +static inline void writer_print_integer(WriterContext *wctx,
 +                                        const char *key, long long int val)
 +{
 +    if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
 +        wctx->writer->print_integer(wctx, key, val);
 +        wctx->nb_item++;
 +    }
 +}
 +
 +static inline void writer_print_rational(WriterContext *wctx,
 +                                         const char *key, AVRational q, char sep)
 +{
 +    AVBPrint buf;
 +    av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
 +    av_bprintf(&buf, "%d%c%d", q.num, sep, q.den);
 +    wctx->writer->print_string(wctx, key, buf.str);
 +    wctx->nb_item++;
 +}
 +
 +static inline void writer_print_string(WriterContext *wctx,
 +                                       const char *key, const char *val, int opt)
 +{
 +    if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
 +        return;
 +    if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
 +        wctx->writer->print_string(wctx, key, val);
 +        wctx->nb_item++;
 +    }
 +}
 +
 +static void writer_print_time(WriterContext *wctx, const char *key,
 +                              int64_t ts, const AVRational *time_base, int is_duration)
 +{
 +    char buf[128];
 +
 +    if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
 +        if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
 +            writer_print_string(wctx, key, "N/A", 1);
 +        } else {
 +            double d = ts * av_q2d(*time_base);
 +            value_string(buf, sizeof(buf), (struct unit_value){.val.d=d, .unit=unit_second_str});
 +            writer_print_string(wctx, key, buf, 0);
 +        }
 +    }
 +}
 +
 +static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts, int is_duration)
 +{
 +    if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
 +        writer_print_string(wctx, key, "N/A", 1);
 +    } else {
 +        writer_print_integer(wctx, key, ts);
 +    }
 +}
 +
 +static inline void writer_show_tags(WriterContext *wctx, AVDictionary *dict)
 +{
 +    wctx->writer->show_tags(wctx, dict);
 +}
 +
 +static void writer_print_data(WriterContext *wctx, const char *name,
 +                              uint8_t *data, int size)
 +{
 +    AVBPrint bp;
 +    int offset = 0, l, i;
 +
 +    av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
 +    av_bprintf(&bp, "\n");
 +    while (size) {
 +        av_bprintf(&bp, "%08x: ", offset);
 +        l = FFMIN(size, 16);
 +        for (i = 0; i < l; i++) {
 +            av_bprintf(&bp, "%02x", data[i]);
 +            if (i & 1)
 +                av_bprintf(&bp, " ");
 +        }
 +        av_bprint_chars(&bp, ' ', 41 - 2 * i - i / 2);
 +        for (i = 0; i < l; i++)
 +            av_bprint_chars(&bp, data[i] - 32U < 95 ? data[i] : '.', 1);
 +        av_bprintf(&bp, "\n");
 +        offset += l;
 +        data   += l;
 +        size   -= l;
 +    }
 +    writer_print_string(wctx, name, bp.str, 0);
 +    av_bprint_finalize(&bp, NULL);
 +}
 +
 +#define MAX_REGISTERED_WRITERS_NB 64
 +
 +static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
 +
 +static int writer_register(const Writer *writer)
 +{
 +    static int next_registered_writer_idx = 0;
 +
 +    if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
 +        return AVERROR(ENOMEM);
 +
 +    registered_writers[next_registered_writer_idx++] = writer;
 +    return 0;
 +}
 +
 +static const Writer *writer_get_by_name(const char *name)
 +{
 +    int i;
 +
 +    for (i = 0; registered_writers[i]; i++)
 +        if (!strcmp(registered_writers[i]->name, name))
 +            return registered_writers[i];
 +
 +    return NULL;
 +}
 +
 +
 +/* WRITERS */
 +
 +/* Default output */
 +
 +typedef struct DefaultContext {
 +    const AVClass *class;
 +    int nokey;
 +    int noprint_wrappers;
 +} DefaultContext;
 +
 +#define OFFSET(x) offsetof(DefaultContext, x)
 +
 +static const AVOption default_options[] = {
 +    { "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
 +    { "nw",               "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
 +    { "nokey",          "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
 +    { "nk",             "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
 +    {NULL},
 +};
 +
 +static const char *default_get_name(void *ctx)
 +{
 +    return "default";
 +}
 +
 +static const AVClass default_class = {
 +    "DefaultContext",
 +    default_get_name,
 +    default_options
 +};
 +
 +static av_cold int default_init(WriterContext *wctx, const char *args, void *opaque)
 +{
 +    DefaultContext *def = wctx->priv;
 +    int err;
 +
 +    def->class = &default_class;
 +    av_opt_set_defaults(def);
 +
 +    if (args &&
 +        (err = (av_set_options_string(def, args, "=", ":"))) < 0)
 +        return err;
 +
 +    return 0;
 +}
 +
 +static void default_print_footer(WriterContext *wctx)
 +{
 +    DefaultContext *def = wctx->priv;
 +
 +    if (!def->noprint_wrappers)
 +        printf("\n");
 +}
 +
 +static void default_print_chapter_header(WriterContext *wctx, const char *chapter)
 +{
 +    DefaultContext *def = wctx->priv;
 +
 +    if (!def->noprint_wrappers && wctx->nb_chapter)
 +        printf("\n");
 +}
 +
 +/* lame uppercasing routine, assumes the string is lower case ASCII */
 +static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
 +{
 +    int i;
 +    for (i = 0; src[i] && i < dst_size-1; i++)
 +        dst[i] = av_toupper(src[i]);
 +    dst[i] = 0;
 +    return dst;
 +}
 +
 +static void default_print_section_header(WriterContext *wctx, const char *section)
 +{
 +    DefaultContext *def = wctx->priv;
 +    char buf[32];
 +
 +    if (wctx->nb_section)
 +        printf("\n");
 +    if (!def->noprint_wrappers)
 +        printf("[%s]\n", upcase_string(buf, sizeof(buf), section));
 +}
 +
 +static void default_print_section_footer(WriterContext *wctx, const char *section)
 +{
 +    DefaultContext *def = wctx->priv;
 +    char buf[32];
 +
 +    if (!def->noprint_wrappers)
 +        printf("[/%s]", upcase_string(buf, sizeof(buf), section));
 +}
 +
 +static void default_print_str(WriterContext *wctx, const char *key, const char *value)
 +{
 +    DefaultContext *def = wctx->priv;
 +    if (!def->nokey)
 +        printf("%s=", key);
 +    printf("%s\n", value);
 +}
 +
 +static void default_print_int(WriterContext *wctx, const char *key, long long int value)
 +{
 +    DefaultContext *def = wctx->priv;
 +
 +    if (!def->nokey)
 +        printf("%s=", key);
 +    printf("%lld\n", value);
 +}
 +
 +static void default_show_tags(WriterContext *wctx, AVDictionary *dict)
 +{
 +    AVDictionaryEntry *tag = NULL;
 +    while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
 +        if (!fmt_entries_to_show || (tag->key && av_dict_get(fmt_entries_to_show, tag->key, NULL, 0)))
 +            printf("TAG:");
 +        writer_print_string(wctx, tag->key, tag->value, 0);
 +    }
 +}
 +
 +static const Writer default_writer = {
 +    .name                  = "default",
 +    .priv_size             = sizeof(DefaultContext),
 +    .init                  = default_init,
 +    .print_footer          = default_print_footer,
 +    .print_chapter_header  = default_print_chapter_header,
 +    .print_section_header  = default_print_section_header,
 +    .print_section_footer  = default_print_section_footer,
 +    .print_integer         = default_print_int,
 +    .print_string          = default_print_str,
 +    .show_tags             = default_show_tags,
 +    .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
 +};
 +
 +/* Compact output */
 +
 +/**
 + * Apply C-language-like string escaping.
 + */
 +static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
 +{
 +    const char *p;
 +
 +    for (p = src; *p; p++) {
 +        switch (*p) {
 +        case '\b': av_bprintf(dst, "%s", "\\b");  break;
 +        case '\f': av_bprintf(dst, "%s", "\\f");  break;
 +        case '\n': av_bprintf(dst, "%s", "\\n");  break;
 +        case '\r': av_bprintf(dst, "%s", "\\r");  break;
 +        case '\\': av_bprintf(dst, "%s", "\\\\"); break;
 +        default:
 +            if (*p == sep)
 +                av_bprint_chars(dst, '\\', 1);
 +            av_bprint_chars(dst, *p, 1);
 +        }
 +    }
 +    return dst->str;
 +}
 +
 +/**
 + * Quote fields containing special characters, check RFC4180.
 + */
 +static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
 +{
 +    const char *p;
 +    int quote = 0;
 +
 +    /* check if input needs quoting */
 +    for (p = src; *p; p++)
 +        if (*p == '"' || *p == sep || *p == '\n' || *p == '\r')
 +            quote = 1;
 +
 +    if (quote)
 +        av_bprint_chars(dst, '\"', 1);
 +
 +    for (p = src; *p; p++) {
 +        if (*p == '"')
 +            av_bprint_chars(dst, '\"', 1);
 +        av_bprint_chars(dst, *p, 1);
 +    }
 +    if (quote)
 +        av_bprint_chars(dst, '\"', 1);
 +    return dst->str;
 +}
 +
 +static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
 +{
 +    return src;
 +}
 +
 +typedef struct CompactContext {
 +    const AVClass *class;
 +    char *item_sep_str;
 +    char item_sep;
 +    int nokey;
 +    char *escape_mode_str;
 +    const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
 +} CompactContext;
 +
 +#undef OFFSET
 +#define OFFSET(x) offsetof(CompactContext, x)
 +
 +static const AVOption compact_options[]= {
 +    {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
 +    {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
 +    {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
 +    {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
 +    {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
 +    {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
 +    {NULL},
 +};
 +
 +static const char *compact_get_name(void *ctx)
 +{
 +    return "compact";
 +}
 +
 +static const AVClass compact_class = {
 +    "CompactContext",
 +    compact_get_name,
 +    compact_options
 +};
 +
 +static av_cold int compact_init(WriterContext *wctx, const char *args, void *opaque)
 +{
 +    CompactContext *compact = wctx->priv;
 +    int err;
 +
 +    compact->class = &compact_class;
 +    av_opt_set_defaults(compact);
 +
 +    if (args &&
 +        (err = (av_set_options_string(compact, args, "=", ":"))) < 0)
 +        return err;
 +    if (strlen(compact->item_sep_str) != 1) {
 +        av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
 +               compact->item_sep_str);
 +        return AVERROR(EINVAL);
 +    }
 +    compact->item_sep = compact->item_sep_str[0];
 +
 +    if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
 +    else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
 +    else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
 +    else {
 +        av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
 +        return AVERROR(EINVAL);
 +    }
 +
 +    return 0;
 +}
 +
 +static av_cold void compact_uninit(WriterContext *wctx)
 +{
 +    CompactContext *compact = wctx->priv;
 +
 +    av_freep(&compact->item_sep_str);
 +    av_freep(&compact->escape_mode_str);
 +}
 +
 +static void compact_print_section_header(WriterContext *wctx, const char *section)
 +{
 +    CompactContext *compact = wctx->priv;
 +
 +    printf("%s%c", section, compact->item_sep);
 +}
 +
 +static void compact_print_section_footer(WriterContext *wctx, const char *section)
 +{
 +    printf("\n");
 +}
 +
 +static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
 +{
 +    CompactContext *compact = wctx->priv;
 +    AVBPrint buf;
 +
 +    if (wctx->nb_item) printf("%c", compact->item_sep);
 +    if (!compact->nokey)
 +        printf("%s=", key);
 +    av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +    printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
 +    av_bprint_finalize(&buf, NULL);
 +}
 +
 +static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
 +{
 +    CompactContext *compact = wctx->priv;
 +
 +    if (wctx->nb_item) printf("%c", compact->item_sep);
 +    if (!compact->nokey)
 +        printf("%s=", key);
 +    printf("%lld", value);
 +}
 +
 +static void compact_show_tags(WriterContext *wctx, AVDictionary *dict)
 +{
 +    CompactContext *compact = wctx->priv;
 +    AVDictionaryEntry *tag = NULL;
 +    AVBPrint buf;
 +
 +    av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +    while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
 +        if (wctx->nb_item) printf("%c", compact->item_sep);
 +        if (!compact->nokey) {
 +            av_bprint_clear(&buf);
 +            printf("tag:%s=", compact->escape_str(&buf, tag->key, compact->item_sep, wctx));
 +        }
 +        av_bprint_clear(&buf);
 +        printf("%s", compact->escape_str(&buf, tag->value, compact->item_sep, wctx));
 +    }
 +    av_bprint_finalize(&buf, NULL);
 +}
 +
 +static const Writer compact_writer = {
 +    .name                 = "compact",
 +    .priv_size            = sizeof(CompactContext),
 +    .init                 = compact_init,
 +    .uninit               = compact_uninit,
 +    .print_section_header = compact_print_section_header,
 +    .print_section_footer = compact_print_section_footer,
 +    .print_integer        = compact_print_int,
 +    .print_string         = compact_print_str,
 +    .show_tags            = compact_show_tags,
 +    .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
 +};
 +
 +/* CSV output */
 +
 +static av_cold int csv_init(WriterContext *wctx, const char *args, void *opaque)
 +{
 +    return compact_init(wctx, "item_sep=,:nokey=1:escape=csv", opaque);
 +}
 +
 +static const Writer csv_writer = {
 +    .name                 = "csv",
 +    .priv_size            = sizeof(CompactContext),
 +    .init                 = csv_init,
 +    .uninit               = compact_uninit,
 +    .print_section_header = compact_print_section_header,
 +    .print_section_footer = compact_print_section_footer,
 +    .print_integer        = compact_print_int,
 +    .print_string         = compact_print_str,
 +    .show_tags            = compact_show_tags,
 +    .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
 +};
 +
 +/* Flat output */
 +
 +typedef struct FlatContext {
 +    const AVClass *class;
 +    const char *section, *chapter;
 +    const char *sep_str;
 +    char sep;
 +    int hierarchical;
 +} FlatContext;
 +
 +#undef OFFSET
 +#define OFFSET(x) offsetof(FlatContext, x)
 +
 +static const AVOption flat_options[]= {
 +    {"sep_char", "set separator",    OFFSET(sep_str),    AV_OPT_TYPE_STRING, {.str="."},  CHAR_MIN, CHAR_MAX },
 +    {"s",        "set separator",    OFFSET(sep_str),    AV_OPT_TYPE_STRING, {.str="."},  CHAR_MIN, CHAR_MAX },
 +    {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.dbl=1}, 0, 1 },
 +    {"h",           "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.dbl=1}, 0, 1 },
 +    {NULL},
 +};
 +
 +static const char *flat_get_name(void *ctx)
 +{
 +    return "flat";
 +}
 +
 +static const AVClass flat_class = {
 +    "FlatContext",
 +    flat_get_name,
 +    flat_options
 +};
 +
 +static av_cold int flat_init(WriterContext *wctx, const char *args, void *opaque)
 +{
 +    FlatContext *flat = wctx->priv;
 +    int err;
 +
 +    flat->class = &flat_class;
 +    av_opt_set_defaults(flat);
 +
 +    if (args &&
 +        (err = (av_set_options_string(flat, args, "=", ":"))) < 0)
 +        return err;
 +    if (strlen(flat->sep_str) != 1) {
 +        av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
 +               flat->sep_str);
 +        return AVERROR(EINVAL);
 +    }
 +    flat->sep = flat->sep_str[0];
 +    return 0;
 +}
 +
 +static const char *flat_escape_key_str(AVBPrint *dst, const char *src, const char sep)
 +{
 +    const char *p;
 +
 +    for (p = src; *p; p++) {
 +        if (!((*p >= '0' && *p <= '9') ||
 +              (*p >= 'a' && *p <= 'z') ||
 +              (*p >= 'A' && *p <= 'Z')))
 +            av_bprint_chars(dst, '_', 1);
 +        else
 +            av_bprint_chars(dst, *p, 1);
 +    }
 +    return dst->str;
 +}
 +
 +static const char *flat_escape_value_str(AVBPrint *dst, const char *src)
 +{
 +    const char *p;
 +
 +    for (p = src; *p; p++) {
 +        switch (*p) {
 +        case '\n': av_bprintf(dst, "%s", "\\n");  break;
 +        case '\r': av_bprintf(dst, "%s", "\\r");  break;
 +        case '\\': av_bprintf(dst, "%s", "\\\\"); break;
 +        case '"':  av_bprintf(dst, "%s", "\\\""); break;
 +        case '`':  av_bprintf(dst, "%s", "\\`");  break;
 +        case '$':  av_bprintf(dst, "%s", "\\$");  break;
 +        default:   av_bprint_chars(dst, *p, 1);   break;
 +        }
 +    }
 +    return dst->str;
 +}
 +
 +static void flat_print_chapter_header(WriterContext *wctx, const char *chapter)
 +{
 +    FlatContext *flat = wctx->priv;
 +    flat->chapter = chapter;
 +}
 +
 +static void flat_print_section_header(WriterContext *wctx, const char *section)
 +{
 +    FlatContext *flat = wctx->priv;
 +    flat->section = section;
 +}
 +
 +static void flat_print_section(WriterContext *wctx)
 +{
 +    FlatContext *flat = wctx->priv;
 +    int n = wctx->is_packets_and_frames ? wctx->nb_section_packet_frame
 +                                        : wctx->nb_section;
 +
 +    if (flat->hierarchical && wctx->multiple_sections)
 +        printf("%s%c", flat->chapter, flat->sep);
 +    printf("%s%c", flat->section, flat->sep);
 +    if (wctx->multiple_sections)
 +        printf("%d%c", n, flat->sep);
 +}
 +
 +static void flat_print_int(WriterContext *wctx, const char *key, long long int value)
 +{
 +    flat_print_section(wctx);
 +    printf("%s=%lld\n", key, value);
 +}
 +
 +static void flat_print_str(WriterContext *wctx, const char *key, const char *value)
 +{
 +    FlatContext *flat = wctx->priv;
 +    AVBPrint buf;
 +
 +    flat_print_section(wctx);
 +    av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +    printf("%s=", flat_escape_key_str(&buf, key, flat->sep));
 +    av_bprint_clear(&buf);
 +    printf("\"%s\"\n", flat_escape_value_str(&buf, value));
 +    av_bprint_finalize(&buf, NULL);
 +}
 +
 +static void flat_show_tags(WriterContext *wctx, AVDictionary *dict)
 +{
 +    FlatContext *flat = wctx->priv;
 +    AVBPrint buf;
 +    AVDictionaryEntry *tag = NULL;
 +
 +    av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +    while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
 +        flat_print_section(wctx);
 +        av_bprint_clear(&buf);
 +        printf("tags%c%s=", flat->sep, flat_escape_key_str(&buf, tag->key, flat->sep));
 +        av_bprint_clear(&buf);
 +        printf("\"%s\"\n", flat_escape_value_str(&buf, tag->value));
 +    }
 +    av_bprint_finalize(&buf, NULL);
 +}
 +
 +static const Writer flat_writer = {
 +    .name                  = "flat",
 +    .priv_size             = sizeof(FlatContext),
 +    .init                  = flat_init,
 +    .print_chapter_header  = flat_print_chapter_header,
 +    .print_section_header  = flat_print_section_header,
 +    .print_integer         = flat_print_int,
 +    .print_string          = flat_print_str,
 +    .show_tags             = flat_show_tags,
 +    .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
 +};
 +
 +/* INI format output */
 +
 +typedef struct {
 +    const AVClass *class;
 +    AVBPrint chapter_name, section_name;
 +    int hierarchical;
 +} INIContext;
 +
 +#undef OFFSET
 +#define OFFSET(x) offsetof(INIContext, x)
 +
 +static const AVOption ini_options[] = {
 +    {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.dbl=1}, 0, 1 },
 +    {"h",           "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.dbl=1}, 0, 1 },
 +    {NULL},
 +};
 +
 +static const char *ini_get_name(void *ctx)
 +{
 +    return "ini";
 +}
 +
 +static const AVClass ini_class = {
 +    "INIContext",
 +    ini_get_name,
 +    ini_options
 +};
 +
 +static av_cold int ini_init(WriterContext *wctx, const char *args, void *opaque)
 +{
 +    INIContext *ini = wctx->priv;
 +    int err;
 +
 +    av_bprint_init(&ini->chapter_name, 1, AV_BPRINT_SIZE_UNLIMITED);
 +    av_bprint_init(&ini->section_name, 1, AV_BPRINT_SIZE_UNLIMITED);
 +
 +    ini->class = &ini_class;
 +    av_opt_set_defaults(ini);
 +
 +    if (args && (err = av_set_options_string(ini, args, "=", ":")) < 0)
 +        return err;
 +
 +    return 0;
 +}
 +
 +static av_cold void ini_uninit(WriterContext *wctx)
 +{
 +    INIContext *ini = wctx->priv;
 +    av_bprint_finalize(&ini->chapter_name, NULL);
 +    av_bprint_finalize(&ini->section_name, NULL);
 +}
 +
 +static void ini_print_header(WriterContext *wctx)
 +{
 +    printf("# ffprobe output\n\n");
 +}
 +
 +static char *ini_escape_str(AVBPrint *dst, const char *src)
 +{
 +    int i = 0;
 +    char c = 0;
 +
 +    while (c = src[i++]) {
 +        switch (c) {
 +        case '\b': av_bprintf(dst, "%s", "\\b"); break;
 +        case '\f': av_bprintf(dst, "%s", "\\f"); break;
 +        case '\n': av_bprintf(dst, "%s", "\\n"); break;
 +        case '\r': av_bprintf(dst, "%s", "\\r"); break;
 +        case '\t': av_bprintf(dst, "%s", "\\t"); break;
 +        case '\\':
 +        case '#' :
 +        case '=' :
 +        case ':' : av_bprint_chars(dst, '\\', 1);
 +        default:
 +            if ((unsigned char)c < 32)
 +                av_bprintf(dst, "\\x00%02x", c & 0xff);
 +            else
 +                av_bprint_chars(dst, c, 1);
 +            break;
 +        }
 +    }
 +    return dst->str;
 +}
 +
 +static void ini_print_chapter_header(WriterContext *wctx, const char *chapter)
 +{
 +    INIContext *ini = wctx->priv;
 +
 +    av_bprint_clear(&ini->chapter_name);
 +    av_bprintf(&ini->chapter_name, "%s", chapter);
 +
 +    if (wctx->nb_chapter)
 +        printf("\n");
 +}
 +
 +static void ini_print_section_header(WriterContext *wctx, const char *section)
 +{
 +    INIContext *ini = wctx->priv;
 +    int n = wctx->is_packets_and_frames ? wctx->nb_section_packet_frame
 +                                        : wctx->nb_section;
 +    if (wctx->nb_section)
 +        printf("\n");
 +    av_bprint_clear(&ini->section_name);
 +
 +    if (ini->hierarchical && wctx->multiple_sections)
 +        av_bprintf(&ini->section_name, "%s.", ini->chapter_name.str);
 +    av_bprintf(&ini->section_name, "%s", section);
 +
 +    if (wctx->multiple_sections)
 +        av_bprintf(&ini->section_name, ".%d", n);
 +    printf("[%s]\n", ini->section_name.str);
 +}
 +
 +static void ini_print_str(WriterContext *wctx, const char *key, const char *value)
 +{
 +    AVBPrint buf;
 +
 +    av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +    printf("%s=", ini_escape_str(&buf, key));
 +    av_bprint_clear(&buf);
 +    printf("%s\n", ini_escape_str(&buf, value));
 +    av_bprint_finalize(&buf, NULL);
 +}
 +
 +static void ini_print_int(WriterContext *wctx, const char *key, long long int value)
 +{
 +    printf("%s=%lld\n", key, value);
 +}
 +
 +static void ini_show_tags(WriterContext *wctx, AVDictionary *dict)
 +{
 +    INIContext *ini = wctx->priv;
 +    AVDictionaryEntry *tag = NULL;
 +    int is_first = 1;
 +
 +    while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
 +        if (is_first) {
 +            printf("\n[%s.tags]\n", ini->section_name.str);
 +            is_first = 0;
 +        }
 +        writer_print_string(wctx, tag->key, tag->value, 0);
 +    }
 +}
 +
 +static const Writer ini_writer = {
 +    .name                  = "ini",
 +    .priv_size             = sizeof(INIContext),
 +    .init                  = ini_init,
 +    .uninit                = ini_uninit,
 +    .print_header          = ini_print_header,
 +    .print_chapter_header  = ini_print_chapter_header,
 +    .print_section_header  = ini_print_section_header,
 +    .print_integer         = ini_print_int,
 +    .print_string          = ini_print_str,
 +    .show_tags             = ini_show_tags,
 +    .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
 +};
 +
 +/* JSON output */
 +
 +typedef struct {
 +    const AVClass *class;
 +    int indent_level;
 +    int compact;
 +    const char *item_sep, *item_start_end;
 +} JSONContext;
 +
 +#undef OFFSET
 +#define OFFSET(x) offsetof(JSONContext, x)
 +
 +static const AVOption json_options[]= {
 +    { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
 +    { "c",       "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
 +    { NULL }
 +};
 +
 +static const char *json_get_name(void *ctx)
 +{
 +    return "json";
 +}
 +
 +static const AVClass json_class = {
 +    "JSONContext",
 +    json_get_name,
 +    json_options
 +};
 +
 +static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
 +{
 +    JSONContext *json = wctx->priv;
 +    int err;
 +
 +    json->class = &json_class;
 +    av_opt_set_defaults(json);
 +
 +    if (args &&
 +        (err = (av_set_options_string(json, args, "=", ":"))) < 0)
 +        return err;
 +
 +    json->item_sep       = json->compact ? ", " : ",\n";
 +    json->item_start_end = json->compact ? " "  : "\n";
 +
 +    return 0;
 +}
 +
 +static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
 +{
 +    static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
 +    static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
 +    const char *p;
 +
 +    for (p = src; *p; p++) {
 +        char *s = strchr(json_escape, *p);
 +        if (s) {
 +            av_bprint_chars(dst, '\\', 1);
 +            av_bprint_chars(dst, json_subst[s - json_escape], 1);
 +        } else if ((unsigned char)*p < 32) {
 +            av_bprintf(dst, "\\u00%02x", *p & 0xff);
 +        } else {
 +            av_bprint_chars(dst, *p, 1);
 +        }
 +    }
 +    return dst->str;
 +}
 +
 +static void json_print_header(WriterContext *wctx)
 +{
 +    JSONContext *json = wctx->priv;
 +    printf("{");
 +    json->indent_level++;
 +}
 +
 +static void json_print_footer(WriterContext *wctx)
 +{
 +    JSONContext *json = wctx->priv;
 +    json->indent_level--;
 +    printf("\n}\n");
 +}
 +
 +#define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
 +
 +static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
 +{
 +    JSONContext *json = wctx->priv;
 +    AVBPrint buf;
 +
 +    if (wctx->nb_chapter)
 +        printf(",");
 +    printf("\n");
 +    if (wctx->multiple_sections) {
 +        JSON_INDENT();
 +        av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +        printf("\"%s\": [\n", json_escape_str(&buf, chapter, wctx));
 +        av_bprint_finalize(&buf, NULL);
 +        json->indent_level++;
 +    }
 +}
 +
 +static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
 +{
 +    JSONContext *json = wctx->priv;
 +
 +    if (wctx->multiple_sections) {
 +        printf("\n");
 +        json->indent_level--;
 +        JSON_INDENT();
 +        printf("]");
 +    }
 +}
 +
 +static void json_print_section_header(WriterContext *wctx, const char *section)
 +{
 +    JSONContext *json = wctx->priv;
 +
 +    if (wctx->nb_section)
 +        printf(",\n");
 +    JSON_INDENT();
 +    if (!wctx->multiple_sections)
 +        printf("\"%s\": ", section);
 +    printf("{%s", json->item_start_end);
 +    json->indent_level++;
 +    /* this is required so the parser can distinguish between packets and frames */
 +    if (wctx->is_packets_and_frames) {
 +        if (!json->compact)
 +            JSON_INDENT();
 +        printf("\"type\": \"%s\"%s", section, json->item_sep);
 +    }
 +}
 +
 +static void json_print_section_footer(WriterContext *wctx, const char *section)
 +{
 +    JSONContext *json = wctx->priv;
 +
 +    printf("%s", json->item_start_end);
 +    json->indent_level--;
 +    if (!json->compact)
 +        JSON_INDENT();
 +    printf("}");
 +}
 +
 +static inline void json_print_item_str(WriterContext *wctx,
 +                                       const char *key, const char *value)
 +{
 +    AVBPrint buf;
 +
 +    av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +    printf("\"%s\":", json_escape_str(&buf, key,   wctx));
 +    av_bprint_clear(&buf);
 +    printf(" \"%s\"", json_escape_str(&buf, value, wctx));
 +    av_bprint_finalize(&buf, NULL);
 +}
 +
 +static void json_print_str(WriterContext *wctx, const char *key, const char *value)
 +{
 +    JSONContext *json = wctx->priv;
 +
 +    if (wctx->nb_item) printf("%s", json->item_sep);
 +    if (!json->compact)
 +        JSON_INDENT();
 +    json_print_item_str(wctx, key, value);
 +}
 +
 +static void json_print_int(WriterContext *wctx, const char *key, long long int value)
 +{
 +    JSONContext *json = wctx->priv;
 +    AVBPrint buf;
 +
 +    if (wctx->nb_item) printf("%s", json->item_sep);
 +    if (!json->compact)
 +        JSON_INDENT();
 +
 +    av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +    printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
 +    av_bprint_finalize(&buf, NULL);
 +}
 +
 +static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
 +{
 +    JSONContext *json = wctx->priv;
 +    AVDictionaryEntry *tag = NULL;
 +    int is_first = 1;
 +    if (!dict)
 +        return;
 +    printf("%s", json->item_sep);
 +    if (!json->compact)
 +        JSON_INDENT();
 +    printf("\"tags\": {%s", json->item_start_end);
 +    json->indent_level++;
 +    while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
 +        if (is_first) is_first = 0;
 +        else          printf("%s", json->item_sep);
 +        if (!json->compact)
 +            JSON_INDENT();
 +        json_print_item_str(wctx, tag->key, tag->value);
 +    }
 +    json->indent_level--;
 +    printf("%s", json->item_start_end);
 +    if (!json->compact)
 +        JSON_INDENT();
 +    printf("}");
 +}
 +
 +static const Writer json_writer = {
 +    .name                 = "json",
 +    .priv_size            = sizeof(JSONContext),
 +    .init                 = json_init,
 +    .print_header         = json_print_header,
 +    .print_footer         = json_print_footer,
 +    .print_chapter_header = json_print_chapter_header,
 +    .print_chapter_footer = json_print_chapter_footer,
 +    .print_section_header = json_print_section_header,
 +    .print_section_footer = json_print_section_footer,
 +    .print_integer        = json_print_int,
 +    .print_string         = json_print_str,
 +    .show_tags            = json_show_tags,
 +    .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
 +};
 +
 +/* XML output */
 +
 +typedef struct {
 +    const AVClass *class;
 +    int within_tag;
 +    int indent_level;
 +    int fully_qualified;
 +    int xsd_strict;
 +} XMLContext;
 +
 +#undef OFFSET
 +#define OFFSET(x) offsetof(XMLContext, x)
 +
 +static const AVOption xml_options[] = {
 +    {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
 +    {"q",               "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
 +    {"xsd_strict",      "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
 +    {"x",               "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
 +    {NULL},
 +};
 +
 +static const char *xml_get_name(void *ctx)
 +{
 +    return "xml";
 +}
 +
 +static const AVClass xml_class = {
 +    "XMLContext",
 +    xml_get_name,
 +    xml_options
 +};
 +
 +static av_cold int xml_init(WriterContext *wctx, const char *args, void *opaque)
 +{
 +    XMLContext *xml = wctx->priv;
 +    int err;
 +
 +    xml->class = &xml_class;
 +    av_opt_set_defaults(xml);
 +
 +    if (args &&
 +        (err = (av_set_options_string(xml, args, "=", ":"))) < 0)
 +        return err;
 +
 +    if (xml->xsd_strict) {
 +        xml->fully_qualified = 1;
 +#define CHECK_COMPLIANCE(opt, opt_name)                                 \
 +        if (opt) {                                                      \
 +            av_log(wctx, AV_LOG_ERROR,                                  \
 +                   "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
 +                   "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
 +            return AVERROR(EINVAL);                                     \
 +        }
 +        CHECK_COMPLIANCE(show_private_data, "private");
 +        CHECK_COMPLIANCE(show_value_unit,   "unit");
 +        CHECK_COMPLIANCE(use_value_prefix,  "prefix");
 +
 +        if (do_show_frames && do_show_packets) {
 +            av_log(wctx, AV_LOG_ERROR,
 +                   "Interleaved frames and packets are not allowed in XSD. "
 +                   "Select only one between the -show_frames and the -show_packets options.\n");
 +            return AVERROR(EINVAL);
 +        }
 +    }
 +
 +    return 0;
 +}
 +
 +static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
 +{
 +    const char *p;
 +
 +    for (p = src; *p; p++) {
 +        switch (*p) {
 +        case '&' : av_bprintf(dst, "%s", "&amp;");  break;
 +        case '<' : av_bprintf(dst, "%s", "&lt;");   break;
 +        case '>' : av_bprintf(dst, "%s", "&gt;");   break;
 +        case '\"': av_bprintf(dst, "%s", "&quot;"); break;
 +        case '\'': av_bprintf(dst, "%s", "&apos;"); break;
 +        default: av_bprint_chars(dst, *p, 1);
 +        }
 +    }
 +
 +    return dst->str;
 +}
 +
 +static void xml_print_header(WriterContext *wctx)
 +{
 +    XMLContext *xml = wctx->priv;
 +    const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
 +        "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
 +        "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
 +
 +    printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
 +    printf("<%sffprobe%s>\n",
 +           xml->fully_qualified ? "ffprobe:" : "",
 +           xml->fully_qualified ? qual : "");
 +
 +    xml->indent_level++;
 +}
 +
 +static void xml_print_footer(WriterContext *wctx)
 +{
 +    XMLContext *xml = wctx->priv;
 +
 +    xml->indent_level--;
 +    printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
 +}
 +
 +#define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
 +
 +static void xml_print_chapter_header(WriterContext *wctx, const char *chapter)
 +{
 +    XMLContext *xml = wctx->priv;
 +
 +    if (wctx->nb_chapter)
 +        printf("\n");
 +    if (wctx->multiple_sections) {
 +        XML_INDENT(); printf("<%s>\n", chapter);
 +        xml->indent_level++;
 +    }
 +}
 +
 +static void xml_print_chapter_footer(WriterContext *wctx, const char *chapter)
 +{
 +    XMLContext *xml = wctx->priv;
 +
 +    if (wctx->multiple_sections) {
 +        xml->indent_level--;
 +        XML_INDENT(); printf("</%s>\n", chapter);
 +    }
 +}
 +
 +static void xml_print_section_header(WriterContext *wctx, const char *section)
 +{
 +    XMLContext *xml = wctx->priv;
 +
 +    XML_INDENT(); printf("<%s ", section);
 +    xml->within_tag = 1;
 +}
 +
 +static void xml_print_section_footer(WriterContext *wctx, const char *section)
 +{
 +    XMLContext *xml = wctx->priv;
 +
 +    if (xml->within_tag)
 +        printf("/>\n");
 +    else {
 +        XML_INDENT(); printf("</%s>\n", section);
 +    }
 +}
 +
 +static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
 +{
 +    AVBPrint buf;
 +
 +    if (wctx->nb_item)
 +        printf(" ");
 +    av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +    printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
 +    av_bprint_finalize(&buf, NULL);
 +}
 +
 +static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
 +{
 +    if (wctx->nb_item)
 +        printf(" ");
 +    printf("%s=\"%lld\"", key, value);
 +}
 +
 +static void xml_show_tags(WriterContext *wctx, AVDictionary *dict)
 +{
 +    XMLContext *xml = wctx->priv;
 +    AVDictionaryEntry *tag = NULL;
 +    int is_first = 1;
 +    AVBPrint buf;
 +
 +    av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +    xml->indent_level++;
 +    while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
 +        if (is_first) {
 +            /* close section tag */
 +            printf(">\n");
 +            xml->within_tag = 0;
 +            is_first = 0;
 +        }
 +        XML_INDENT();
 +
 +        av_bprint_clear(&buf);
 +        printf("<tag key=\"%s\"", xml_escape_str(&buf, tag->key, wctx));
 +        av_bprint_clear(&buf);
 +        printf(" value=\"%s\"/>\n", xml_escape_str(&buf, tag->value, wctx));
 +    }
 +    av_bprint_finalize(&buf, NULL);
 +    xml->indent_level--;
 +}
 +
 +static Writer xml_writer = {
 +    .name                 = "xml",
 +    .priv_size            = sizeof(XMLContext),
 +    .init                 = xml_init,
 +    .print_header         = xml_print_header,
 +    .print_footer         = xml_print_footer,
 +    .print_chapter_header = xml_print_chapter_header,
 +    .print_chapter_footer = xml_print_chapter_footer,
 +    .print_section_header = xml_print_section_header,
 +    .print_section_footer = xml_print_section_footer,
 +    .print_integer        = xml_print_int,
 +    .print_string         = xml_print_str,
 +    .show_tags            = xml_show_tags,
 +    .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
 +};
 +
 +static void writer_register_all(void)
 +{
 +    static int initialized;
 +
 +    if (initialized)
 +        return;
 +    initialized = 1;
 +
 +    writer_register(&default_writer);
 +    writer_register(&compact_writer);
 +    writer_register(&csv_writer);
 +    writer_register(&flat_writer);
 +    writer_register(&ini_writer);
 +    writer_register(&json_writer);
 +    writer_register(&xml_writer);
 +}
 +
 +#define print_fmt(k, f, ...) do {              \
 +    av_bprint_clear(&pbuf);                    \
 +    av_bprintf(&pbuf, f, __VA_ARGS__);         \
 +    writer_print_string(w, k, pbuf.str, 0);    \
 +} while (0)
 +
 +#define print_int(k, v)         writer_print_integer(w, k, v)
 +#define print_q(k, v, s)        writer_print_rational(w, k, v, s)
 +#define print_str(k, v)         writer_print_string(w, k, v, 0)
 +#define print_str_opt(k, v)     writer_print_string(w, k, v, 1)
 +#define print_time(k, v, tb)    writer_print_time(w, k, v, tb, 0)
 +#define print_ts(k, v)          writer_print_ts(w, k, v, 0)
 +#define print_duration_time(k, v, tb) writer_print_time(w, k, v, tb, 1)
 +#define print_duration_ts(k, v)       writer_print_ts(w, k, v, 1)
 +#define print_val(k, v, u)      writer_print_string(w, k, \
 +    value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 0)
 +#define print_section_header(s) writer_print_section_header(w, s)
 +#define print_section_footer(s) writer_print_section_footer(w, s)
 +#define show_tags(metadata)     writer_show_tags(w, metadata)
 +
 +static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
 +{
 +    char val_str[128];
 +    AVStream *st = fmt_ctx->streams[pkt->stream_index];
 +    AVBPrint pbuf;
 +    const char *s;
 +
 +    av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +
 +    print_section_header("packet");
 +    s = av_get_media_type_string(st->codec->codec_type);
 +    if (s) print_str    ("codec_type", s);
 +    else   print_str_opt("codec_type", "unknown");
 +    print_int("stream_index",     pkt->stream_index);
 +    print_ts  ("pts",             pkt->pts);
 +    print_time("pts_time",        pkt->pts, &st->time_base);
 +    print_ts  ("dts",             pkt->dts);
 +    print_time("dts_time",        pkt->dts, &st->time_base);
 +    print_duration_ts("duration",        pkt->duration);
 +    print_duration_time("duration_time", pkt->duration, &st->time_base);
 +    print_duration_ts("convergence_duration", pkt->convergence_duration);
 +    print_duration_time("convergence_duration_time", pkt->convergence_duration, &st->time_base);
 +    print_val("size",             pkt->size, unit_byte_str);
 +    if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
 +    else                print_str_opt("pos", "N/A");
 +    print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
 +    if (do_show_data)
 +        writer_print_data(w, "data", pkt->data, pkt->size);
 +    print_section_footer("packet");
 +
 +    av_bprint_finalize(&pbuf, NULL);
 +    fflush(stdout);
 +}
 +
 +static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream,
 +                       AVFormatContext *fmt_ctx)
 +{
 +    AVBPrint pbuf;
 +    const char *s;
 +
 +    av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +
 +    print_section_header("frame");
 +
 +    s = av_get_media_type_string(stream->codec->codec_type);
 +    if (s) print_str    ("media_type", s);
 +    else   print_str_opt("media_type", "unknown");
 +    print_int("key_frame",              frame->key_frame);
 +    print_ts  ("pkt_pts",               frame->pkt_pts);
 +    print_time("pkt_pts_time",          frame->pkt_pts, &stream->time_base);
 +    print_ts  ("pkt_dts",               frame->pkt_dts);
 +    print_time("pkt_dts_time",          frame->pkt_dts, &stream->time_base);
 +    print_duration_ts  ("pkt_duration",      frame->pkt_duration);
 +    print_duration_time("pkt_duration_time", frame->pkt_duration, &stream->time_base);
 +    if (frame->pkt_pos != -1) print_fmt    ("pkt_pos", "%"PRId64, frame->pkt_pos);
 +    else                      print_str_opt("pkt_pos", "N/A");
 +
 +    switch (stream->codec->codec_type) {
 +        AVRational sar;
 +
 +    case AVMEDIA_TYPE_VIDEO:
 +        print_int("width",                  frame->width);
 +        print_int("height",                 frame->height);
 +        s = av_get_pix_fmt_name(frame->format);
 +        if (s) print_str    ("pix_fmt", s);
 +        else   print_str_opt("pix_fmt", "unknown");
 +        sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, frame);
 +        if (sar.num) {
 +            print_q("sample_aspect_ratio", sar, ':');
 +        } else {
 +            print_str_opt("sample_aspect_ratio", "N/A");
 +        }
 +        print_fmt("pict_type",              "%c", av_get_picture_type_char(frame->pict_type));
 +        print_int("coded_picture_number",   frame->coded_picture_number);
 +        print_int("display_picture_number", frame->display_picture_number);
 +        print_int("interlaced_frame",       frame->interlaced_frame);
 +        print_int("top_field_first",        frame->top_field_first);
 +        print_int("repeat_pict",            frame->repeat_pict);
 +        print_int("reference",              frame->reference);
 +        break;
 +
 +    case AVMEDIA_TYPE_AUDIO:
 +        s = av_get_sample_fmt_name(frame->format);
 +        if (s) print_str    ("sample_fmt", s);
 +        else   print_str_opt("sample_fmt", "unknown");
 +        print_int("nb_samples",         frame->nb_samples);
 +        print_int("channels", av_frame_get_channels(frame));
 +        if (av_frame_get_channel_layout(frame)) {
 +            av_bprint_clear(&pbuf);
 +            av_bprint_channel_layout(&pbuf, av_frame_get_channels(frame),
 +                                     av_frame_get_channel_layout(frame));
 +            print_str    ("channel_layout", pbuf.str);
 +        } else
 +            print_str_opt("channel_layout", "unknown");
 +        break;
 +    }
 +    show_tags(av_frame_get_metadata(frame));
 +
 +    print_section_footer("frame");
 +
 +    av_bprint_finalize(&pbuf, NULL);
 +    fflush(stdout);
 +}
 +
 +static av_always_inline int process_frame(WriterContext *w,
 +                                          AVFormatContext *fmt_ctx,
 +                                          AVFrame *frame, AVPacket *pkt)
 +{
 +    AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
 +    int ret = 0, got_frame = 0;
 +
 +    avcodec_get_frame_defaults(frame);
 +    if (dec_ctx->codec) {
 +        switch (dec_ctx->codec_type) {
 +        case AVMEDIA_TYPE_VIDEO:
 +            ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, pkt);
 +            break;
 +
 +        case AVMEDIA_TYPE_AUDIO:
 +            ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, pkt);
 +            break;
 +        }
 +    }
 +
 +    if (ret < 0)
 +        return ret;
 +    ret = FFMIN(ret, pkt->size); /* guard against bogus return values */
 +    pkt->data += ret;
 +    pkt->size -= ret;
 +    if (got_frame) {
 +        nb_streams_frames[pkt->stream_index]++;
 +        if (do_show_frames)
 +            show_frame(w, frame, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
 +    }
 +    return got_frame;
 +}
 +
 +static void read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
 +{
 +    AVPacket pkt, pkt1;
 +    AVFrame frame;
 +    int i = 0;
 +
 +    av_init_packet(&pkt);
 +
 +    while (!av_read_frame(fmt_ctx, &pkt)) {
 +        if (do_read_packets) {
 +            if (do_show_packets)
 +                show_packet(w, fmt_ctx, &pkt, i++);
 +            nb_streams_packets[pkt.stream_index]++;
 +        }
 +        if (do_read_frames) {
 +            pkt1 = pkt;
 +            while (pkt1.size && process_frame(w, fmt_ctx, &frame, &pkt1) > 0);
 +        }
 +        av_free_packet(&pkt);
 +    }
 +    av_init_packet(&pkt);
 +    pkt.data = NULL;
 +    pkt.size = 0;
 +    //Flush remaining frames that are cached in the decoder
 +    for (i = 0; i < fmt_ctx->nb_streams; i++) {
 +        pkt.stream_index = i;
 +        if (do_read_frames)
 +            while (process_frame(w, fmt_ctx, &frame, &pkt) > 0);
 +    }
 +}
 +
 +static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
 +{
 +    AVStream *stream = fmt_ctx->streams[stream_idx];
 +    AVCodecContext *dec_ctx;
 +    AVCodec *dec;
 +    char val_str[128];
 +    const char *s;
 +    AVRational sar, dar;
 +    AVBPrint pbuf;
 +
 +    av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +
 +    print_section_header("stream");
 +
 +    print_int("index", stream->index);
 +
 +    if ((dec_ctx = stream->codec)) {
 +        const char *profile = NULL;
 +        if ((dec = dec_ctx->codec)) {
 +            print_str("codec_name",      dec->name);
 +            print_str("codec_long_name", dec->long_name);
 +        } else {
 +            print_str_opt("codec_name",      "unknown");
 +            print_str_opt("codec_long_name", "unknown");
 +        }
 +
 +        if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
 +            print_str("profile", profile);
 +        else
 +            print_str_opt("profile", "unknown");
 +
 +        s = av_get_media_type_string(dec_ctx->codec_type);
 +        if (s) print_str    ("codec_type", s);
 +        else   print_str_opt("codec_type", "unknown");
 +        print_q("codec_time_base", dec_ctx->time_base, '/');
 +
 +        /* print AVI/FourCC tag */
 +        av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
 +        print_str("codec_tag_string",    val_str);
 +        print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
 +
 +        switch (dec_ctx->codec_type) {
 +        case AVMEDIA_TYPE_VIDEO:
 +            print_int("width",        dec_ctx->width);
 +            print_int("height",       dec_ctx->height);
 +            print_int("has_b_frames", dec_ctx->has_b_frames);
 +            sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);
 +            if (sar.den) {
 +                print_q("sample_aspect_ratio", sar, ':');
 +                av_reduce(&dar.num, &dar.den,
 +                          dec_ctx->width  * sar.num,
 +                          dec_ctx->height * sar.den,
 +                          1024*1024);
 +                print_q("display_aspect_ratio", dar, ':');
 +            } else {
 +                print_str_opt("sample_aspect_ratio", "N/A");
 +                print_str_opt("display_aspect_ratio", "N/A");
 +            }
 +            s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
 +            if (s) print_str    ("pix_fmt", s);
 +            else   print_str_opt("pix_fmt", "unknown");
 +            print_int("level",   dec_ctx->level);
 +            if (dec_ctx->timecode_frame_start >= 0) {
 +                char tcbuf[AV_TIMECODE_STR_SIZE];
 +                av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
 +                print_str("timecode", tcbuf);
 +            } else {
 +                print_str_opt("timecode", "N/A");
 +            }
 +            break;
 +
 +        case AVMEDIA_TYPE_AUDIO:
 +            s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
 +            if (s) print_str    ("sample_fmt", s);
 +            else   print_str_opt("sample_fmt", "unknown");
 +            print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
 +            print_int("channels",        dec_ctx->channels);
 +            print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
 +            break;
 +        }
 +    } else {
 +        print_str_opt("codec_type", "unknown");
 +    }
 +    if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
 +        const AVOption *opt = NULL;
 +        while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
 +            uint8_t *str;
 +            if (opt->flags) continue;
 +            if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
 +                print_str(opt->name, str);
 +                av_free(str);
 +            }
 +        }
 +    }
 +
 +    if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
 +    else                                          print_str_opt("id", "N/A");
 +    print_q("r_frame_rate",   stream->r_frame_rate,   '/');
 +    print_q("avg_frame_rate", stream->avg_frame_rate, '/');
 +    print_q("time_base",      stream->time_base,      '/');
 +    print_time("start_time",    stream->start_time, &stream->time_base);
 +    print_time("duration",      stream->duration,   &stream->time_base);
 +    if (dec_ctx->bit_rate > 0) print_val    ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
 +    else                       print_str_opt("bit_rate", "N/A");
 +    if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
 +    else                   print_str_opt("nb_frames", "N/A");
 +    if (nb_streams_frames[stream_idx])  print_fmt    ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
 +    else                                print_str_opt("nb_read_frames", "N/A");
 +    if (nb_streams_packets[stream_idx]) print_fmt    ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
 +    else                                print_str_opt("nb_read_packets", "N/A");
 +    if (do_show_data)
 +        writer_print_data(w, "extradata", dec_ctx->extradata,
 +                                          dec_ctx->extradata_size);
 +    show_tags(stream->metadata);
 +
 +    print_section_footer("stream");
 +    av_bprint_finalize(&pbuf, NULL);
 +    fflush(stdout);
 +}
 +
 +static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
 +{
 +    int i;
 +    for (i = 0; i < fmt_ctx->nb_streams; i++)
 +        show_stream(w, fmt_ctx, i);
 +}
 +
 +static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
 +{
 +    char val_str[128];
 +    int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
 +
 +    print_section_header("format");
 +    print_str("filename",         fmt_ctx->filename);
 +    print_int("nb_streams",       fmt_ctx->nb_streams);
 +    print_str("format_name",      fmt_ctx->iformat->name);
 +    print_str("format_long_name", fmt_ctx->iformat->long_name);
 +    print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
 +    print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
 +    if (size >= 0) print_val    ("size", size, unit_byte_str);
 +    else           print_str_opt("size", "N/A");
 +    if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
 +    else                       print_str_opt("bit_rate", "N/A");
 +    show_tags(fmt_ctx->metadata);
 +    print_section_footer("format");
 +    fflush(stdout);
 +}
 +
 +static void show_error(WriterContext *w, int err)
 +{
 +    char errbuf[128];
 +    const char *errbuf_ptr = errbuf;
 +
 +    if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
 +        errbuf_ptr = strerror(AVUNERROR(err));
 +
 +    writer_print_chapter_header(w, "error");
 +    print_section_header("error");
 +    print_int("code", err);
 +    print_str("string", errbuf_ptr);
 +    print_section_footer("error");
 +    writer_print_chapter_footer(w, "error");
 +}
 +
 +static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
 +{
 +    int err, i;
 +    AVFormatContext *fmt_ctx = NULL;
 +    AVDictionaryEntry *t;
 +
 +    if ((err = avformat_open_input(&fmt_ctx, filename,
 +                                   iformat, &format_opts)) < 0) {
 +        print_error(filename, err);
 +        return err;
 +    }
 +    if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
 +        av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
 +        return AVERROR_OPTION_NOT_FOUND;
 +    }
 +
 +
 +    /* fill the streams in the format context */
 +    if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
 +        print_error(filename, err);
 +        return err;
 +    }
 +
 +    av_dump_format(fmt_ctx, 0, filename, 0);
 +
 +    /* bind a decoder to each input stream */
 +    for (i = 0; i < fmt_ctx->nb_streams; i++) {
 +        AVStream *stream = fmt_ctx->streams[i];
 +        AVCodec *codec;
 +
 +        if (stream->codec->codec_id == AV_CODEC_ID_PROBE) {
 +            av_log(NULL, AV_LOG_ERROR,
 +                   "Failed to probe codec for input stream %d\n",
 +                    stream->index);
 +        } else if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
 +            av_log(NULL, AV_LOG_ERROR,
 +                    "Unsupported codec with id %d for input stream %d\n",
 +                    stream->codec->codec_id, stream->index);
 +        } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
 +            av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
 +                   stream->index);
 +        }
 +    }
 +
 +    *fmt_ctx_ptr = fmt_ctx;
 +    return 0;
 +}
 +
 +static void close_input_file(AVFormatContext **ctx_ptr)
 +{
 +    int i;
 +    AVFormatContext *fmt_ctx = *ctx_ptr;
 +
 +    /* close decoder for each stream */
 +    for (i = 0; i < fmt_ctx->nb_streams; i++)
 +        if (fmt_ctx->streams[i]->codec->codec_id != AV_CODEC_ID_NONE)
 +            avcodec_close(fmt_ctx->streams[i]->codec);
 +
 +    avformat_close_input(ctx_ptr);
 +}
 +
 +#define PRINT_CHAPTER(name) do {                                        \
 +    if (do_show_ ## name) {                                             \
 +        writer_print_chapter_header(wctx, #name);                       \
 +        show_ ## name (wctx, fmt_ctx);                                  \
 +        writer_print_chapter_footer(wctx, #name);                       \
 +    }                                                                   \
 +} while (0)
 +
 +static int probe_file(WriterContext *wctx, const char *filename)
 +{
 +    AVFormatContext *fmt_ctx;
 +    int ret;
 +
 +    do_read_frames = do_show_frames || do_count_frames;
 +    do_read_packets = do_show_packets || do_count_packets;
 +
 +    ret = open_input_file(&fmt_ctx, filename);
 +    if (ret >= 0) {
 +        nb_streams_frames  = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
 +        nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
 +        if (do_read_frames || do_read_packets) {
 +            const char *chapter;
 +            if (do_show_frames && do_show_packets &&
 +                wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
 +                chapter = "packets_and_frames";
 +            else if (do_show_packets && !do_show_frames)
 +                chapter = "packets";
 +            else // (!do_show_packets && do_show_frames)
 +                chapter = "frames";
 +            if (do_show_frames || do_show_packets)
 +                writer_print_chapter_header(wctx, chapter);
 +            read_packets(wctx, fmt_ctx);
 +            if (do_show_frames || do_show_packets)
 +                writer_print_chapter_footer(wctx, chapter);
 +        }
 +        PRINT_CHAPTER(streams);
 +        PRINT_CHAPTER(format);
 +        close_input_file(&fmt_ctx);
 +        av_freep(&nb_streams_frames);
 +        av_freep(&nb_streams_packets);
 +    }
 +    return ret;
 +}
 +
 +static void show_usage(void)
 +{
 +    av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
 +    av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
 +    av_log(NULL, AV_LOG_INFO, "\n");
 +}
 +
 +static void ffprobe_show_program_version(WriterContext *w)
 +{
 +    AVBPrint pbuf;
 +    av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
 +
 +    writer_print_chapter_header(w, "program_version");
 +    print_section_header("program_version");
 +    print_str("version", FFMPEG_VERSION);
 +    print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
 +              program_birth_year, this_year);
 +    print_str("build_date", __DATE__);
 +    print_str("build_time", __TIME__);
 +    print_str("compiler_ident", CC_IDENT);
 +    print_str("configuration", FFMPEG_CONFIGURATION);
 +    print_section_footer("program_version");
 +    writer_print_chapter_footer(w, "program_version");
 +
 +    av_bprint_finalize(&pbuf, NULL);
 +}
 +
 +#define SHOW_LIB_VERSION(libname, LIBNAME)                              \
 +    do {                                                                \
 +        if (CONFIG_##LIBNAME) {                                         \
 +            unsigned int version = libname##_version();                 \
 +            print_section_header("library_version");                    \
 +            print_str("name",    "lib" #libname);                       \
 +            print_int("major",   LIB##LIBNAME##_VERSION_MAJOR);         \
 +            print_int("minor",   LIB##LIBNAME##_VERSION_MINOR);         \
 +            print_int("micro",   LIB##LIBNAME##_VERSION_MICRO);         \
 +            print_int("version", version);                              \
 +            print_section_footer("library_version");                    \
 +        }                                                               \
 +    } while (0)
 +
 +static void ffprobe_show_library_versions(WriterContext *w)
 +{
 +    writer_print_chapter_header(w, "library_versions");
 +    SHOW_LIB_VERSION(avutil,     AVUTIL);
 +    SHOW_LIB_VERSION(avcodec,    AVCODEC);
 +    SHOW_LIB_VERSION(avformat,   AVFORMAT);
 +    SHOW_LIB_VERSION(avdevice,   AVDEVICE);
 +    SHOW_LIB_VERSION(avfilter,   AVFILTER);
 +    SHOW_LIB_VERSION(swscale,    SWSCALE);
 +    SHOW_LIB_VERSION(swresample, SWRESAMPLE);
 +    SHOW_LIB_VERSION(postproc,   POSTPROC);
 +    writer_print_chapter_footer(w, "library_versions");
 +}
 +
 +static int opt_format(const char *opt, const char *arg)
 +{
 +    iformat = av_find_input_format(arg);
 +    if (!iformat) {
 +        av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
 +        return AVERROR(EINVAL);
 +    }
 +    return 0;
 +}
 +
 +static int opt_show_format_entry(const char *opt, const char *arg)
 +{
 +    do_show_format = 1;
 +    av_dict_set(&fmt_entries_to_show, arg, "", 0);
 +    return 0;
 +}
 +
 +static void opt_input_file(void *optctx, const char *arg)
 +{
 +    if (input_filename) {
 +        av_log(NULL, AV_LOG_ERROR,
 +                "Argument '%s' provided as input filename, but '%s' was already specified.\n",
 +                arg, input_filename);
 +        exit(1);
 +    }
 +    if (!strcmp(arg, "-"))
 +        arg = "pipe:";
 +    input_filename = arg;
 +}
 +
 +static int opt_help(const char *opt, const char *arg)
 +{
 +    av_log_set_callback(log_callback_help);
 +    show_usage();
 +    show_help_options(options, "Main options:\n", 0, 0);
 +    printf("\n");
 +
 +    show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
 +
 +    return 0;
 +}
 +
 +static int opt_pretty(const char *opt, const char *arg)
 +{
 +    show_value_unit              = 1;
 +    use_value_prefix             = 1;
 +    use_byte_value_binary_prefix = 1;
 +    use_value_sexagesimal_format = 1;
 +    return 0;
 +}
 +
 +static int opt_show_versions(const char *opt, const char *arg)
 +{
 +    do_show_program_version  = 1;
 +    do_show_library_versions = 1;
 +    return 0;
 +}
 +
 +static const OptionDef real_options[] = {
 +#include "cmdutils_common_opts.h"
 +    { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
 +    { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
 +    { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
 +    { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
 +      "use binary prefixes for byte units" },
 +    { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
 +      "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
 +    { "pretty", 0, {(void*)&opt_pretty},
 +      "prettify the format of displayed values, make it more human readable" },
 +    { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
 +      "set the output printing format (available formats are: default, compact, csv, flat, ini, json, xml)", "format" },
 +    { "of", OPT_STRING | HAS_ARG, {(void*)&print_format}, "alias for -print_format", "format" },
 +    { "show_data",    OPT_BOOL, {(void*)&do_show_data}, "show packets data" },
 +    { "show_error",   OPT_BOOL, {(void*)&do_show_error} ,  "show probing error" },
 +    { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
 +    { "show_frames",  OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
 +    { "show_format_entry", HAS_ARG, {(void*)opt_show_format_entry},
 +      "show a particular entry from the format/container info", "entry" },
 +    { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
 +    { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
 +    { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
 +    { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
 +    { "show_program_version",  OPT_BOOL, {(void*)&do_show_program_version},  "show ffprobe version" },
 +    { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
 +    { "show_versions",         0, {(void*)&opt_show_versions}, "show program and library versions" },
 +    { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
 +    { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
 +    { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
 +    { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
 +    { NULL, },
 +};
 +
 +int main(int argc, char **argv)
 +{
 +    const Writer *w;
 +    WriterContext *wctx;
 +    char *buf;
 +    char *w_name = NULL, *w_args = NULL;
 +    int ret;
 +
 +    av_log_set_flags(AV_LOG_SKIP_REPEATED);
 +    options = real_options;
 +    parse_loglevel(argc, argv, options);
 +    av_register_all();
 +    avformat_network_init();
 +    init_opts();
 +#if CONFIG_AVDEVICE
 +    avdevice_register_all();
 +#endif
 +
 +    show_banner(argc, argv, options);
 +    parse_options(NULL, argc, argv, options, opt_input_file);
 +
 +    writer_register_all();
 +
 +    if (!print_format)
 +        print_format = av_strdup("default");
 +    w_name = av_strtok(print_format, "=", &buf);
 +    w_args = buf;
 +
 +    w = writer_get_by_name(w_name);
 +    if (!w) {
 +        av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
 +        ret = AVERROR(EINVAL);
 +        goto end;
 +    }
 +
 +    if ((ret = writer_open(&wctx, w, w_args, NULL)) >= 0) {
 +        writer_print_header(wctx);
 +
 +        if (do_show_program_version)
 +            ffprobe_show_program_version(wctx);
 +        if (do_show_library_versions)
 +            ffprobe_show_library_versions(wctx);
 +
 +        if (!input_filename &&
 +            ((do_show_format || do_show_streams || do_show_packets || do_show_error) ||
 +             (!do_show_program_version && !do_show_library_versions))) {
 +            show_usage();
 +            av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
 +            av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
 +            ret = AVERROR(EINVAL);
 +        } else if (input_filename) {
 +            ret = probe_file(wctx, input_filename);
 +            if (ret < 0 && do_show_error)
 +                show_error(wctx, ret);
 +        }
 +
 +        writer_print_footer(wctx);
 +        writer_close(&wctx);
 +    }
 +
 +end:
 +    av_freep(&print_format);
 +
 +    uninit_opts();
 +    av_dict_free(&fmt_entries_to_show);
 +
 +    avformat_network_deinit();
 +
 +    return ret;
 +}
@@@ -139,14 -126,9 +141,12 @@@ OBJS-$(CONFIG_CSCD_DECODER)            
  OBJS-$(CONFIG_CYUV_DECODER)            += cyuv.o
  OBJS-$(CONFIG_DCA_DECODER)             += dcadec.o dca.o dcadsp.o      \
                                            dca_parser.o synth_filter.o
 +OBJS-$(CONFIG_DCA_ENCODER)             += dcaenc.o
 +OBJS-$(CONFIG_DIRAC_DECODER)           += diracdec.o dirac.o diracdsp.o \
 +                                          dirac_arith.o mpeg12data.o dwt.o
  OBJS-$(CONFIG_DFA_DECODER)             += dfa.o
  OBJS-$(CONFIG_DNXHD_DECODER)           += dnxhddec.o dnxhddata.o
- OBJS-$(CONFIG_DNXHD_ENCODER)           += dnxhdenc.o dnxhddata.o       \
-                                           mpegvideo_enc.o motion_est.o \
-                                           ratecontrol.o mpeg12data.o
+ OBJS-$(CONFIG_DNXHD_ENCODER)           += dnxhdenc.o dnxhddata.o
  OBJS-$(CONFIG_DPX_DECODER)             += dpx.o
  OBJS-$(CONFIG_DPX_ENCODER)             += dpxenc.o
  OBJS-$(CONFIG_DSICINAUDIO_DECODER)     += dsicinav.o
@@@ -198,10 -174,8 +198,8 @@@ OBJS-$(CONFIG_GIF_DECODER)             
  OBJS-$(CONFIG_GIF_ENCODER)             += gif.o lzwenc.o
  OBJS-$(CONFIG_GSM_DECODER)             += gsmdec.o gsmdec_data.o msgsmdec.o
  OBJS-$(CONFIG_GSM_MS_DECODER)          += gsmdec.o gsmdec_data.o msgsmdec.o
 -OBJS-$(CONFIG_H261_DECODER)            += h261dec.o h261.o error_resilience.o
 -OBJS-$(CONFIG_H261_ENCODER)            += h261enc.o h261.o
 +OBJS-$(CONFIG_H261_DECODER)            += h261dec.o h261.o h261data.o error_resilience.o
- OBJS-$(CONFIG_H261_ENCODER)            += h261enc.o h261.o h261data.o  \
-                                           mpegvideo_enc.o motion_est.o \
-                                           ratecontrol.o mpeg12data.o
++OBJS-$(CONFIG_H261_ENCODER)            += h261enc.o h261.o h261data.o
  OBJS-$(CONFIG_H263_DECODER)            += h263dec.o h263.o ituh263dec.o        \
                                            mpeg4video.o mpeg4videodec.o flvdec.o\
                                            intelh263dec.o  error_resilience.o
@@@ -251,12 -217,9 +245,10 @@@ OBJS-$(CONFIG_MACE3_DECODER)           
  OBJS-$(CONFIG_MACE6_DECODER)           += mace.o
  OBJS-$(CONFIG_MDEC_DECODER)            += mdec.o mpeg12.o mpeg12data.o \
                                            error_resilience.o
 +OBJS-$(CONFIG_MICRODVD_DECODER)        += microdvddec.o ass.o
  OBJS-$(CONFIG_MIMIC_DECODER)           += mimic.o
  OBJS-$(CONFIG_MJPEG_DECODER)           += mjpegdec.o mjpeg.o
- OBJS-$(CONFIG_MJPEG_ENCODER)           += mjpegenc.o mjpeg.o           \
-                                           mpegvideo_enc.o motion_est.o \
-                                           ratecontrol.o mpeg12data.o
+ OBJS-$(CONFIG_MJPEG_ENCODER)           += mjpegenc.o mjpeg.o
  OBJS-$(CONFIG_MJPEGB_DECODER)          += mjpegbdec.o mjpegdec.o mjpeg.o
  OBJS-$(CONFIG_MLP_DECODER)             += mlpdec.o mlpdsp.o
  OBJS-$(CONFIG_MMVIDEO_DECODER)         += mmvideo.o
@@@ -298,19 -257,13 +290,15 @@@ OBJS-$(CONFIG_MPEGVIDEO_DECODER)       
  OBJS-$(CONFIG_MPEG_XVMC_DECODER)       += mpegvideo_xvmc.o
  OBJS-$(CONFIG_MPEG1VIDEO_DECODER)      += mpeg12.o mpeg12data.o \
                                            error_resilience.o
- OBJS-$(CONFIG_MPEG1VIDEO_ENCODER)      += mpeg12enc.o mpegvideo_enc.o \
+ OBJS-$(CONFIG_MPEG1VIDEO_ENCODER)      += mpeg12enc.o mpeg12.o          \
 +                                          timecode.o                  \
-                                           motion_est.o ratecontrol.o  \
-                                           mpeg12.o mpeg12data.o       \
                                            error_resilience.o
  OBJS-$(CONFIG_MPEG2_DXVA2_HWACCEL)     += dxva2_mpeg2.o
  OBJS-$(CONFIG_MPEG2_VAAPI_HWACCEL)     += vaapi_mpeg2.o
  OBJS-$(CONFIG_MPEG2VIDEO_DECODER)      += mpeg12.o mpeg12data.o \
                                            error_resilience.o
- OBJS-$(CONFIG_MPEG2VIDEO_ENCODER)      += mpeg12enc.o mpegvideo_enc.o \
+ OBJS-$(CONFIG_MPEG2VIDEO_ENCODER)      += mpeg12enc.o mpeg12.o          \
 +                                          timecode.o                  \
-                                           motion_est.o ratecontrol.o  \
-                                           mpeg12.o mpeg12data.o       \
                                            error_resilience.o
  OBJS-$(CONFIG_MPEG4_VAAPI_HWACCEL)     += vaapi_mpeg4.o
  OBJS-$(CONFIG_MSMPEG4V1_DECODER)       += msmpeg4.o msmpeg4data.o
@@@ -411,18 -353,11 +399,16 @@@ OBJS-$(CONFIG_SMACKER_DECODER)         
  OBJS-$(CONFIG_SMC_DECODER)             += smc.o
  OBJS-$(CONFIG_SNOW_DECODER)            += snowdec.o snow.o rangecoder.o
  OBJS-$(CONFIG_SNOW_ENCODER)            += snowenc.o snow.o rangecoder.o    \
-                                           motion_est.o ratecontrol.o       \
-                                           h263.o                           \
-                                           error_resilience.o ituh263enc.o  \
-                                           mpegvideo_enc.o mpeg12data.o
+                                           h263.o ituh263enc.o          \
+                                           error_resilience.o
  OBJS-$(CONFIG_SOL_DPCM_DECODER)        += dpcm.o
 +OBJS-$(CONFIG_SONIC_DECODER)           += sonic.o
 +OBJS-$(CONFIG_SONIC_ENCODER)           += sonic.o
 +OBJS-$(CONFIG_SONIC_LS_ENCODER)        += sonic.o
  OBJS-$(CONFIG_SP5X_DECODER)            += sp5xdec.o mjpegdec.o mjpeg.o
  OBJS-$(CONFIG_SRT_DECODER)             += srtdec.o ass.o
 +OBJS-$(CONFIG_SRT_ENCODER)             += srtenc.o ass_split.o
 +OBJS-$(CONFIG_SUBVIEWER_DECODER)       += subviewerdec.o ass.o
  OBJS-$(CONFIG_SUNRAST_DECODER)         += sunrast.o
  OBJS-$(CONFIG_SUNRAST_ENCODER)         += sunrastenc.o
  OBJS-$(CONFIG_SVQ1_DECODER)            += svq1dec.o svq1.o h263.o \
@@@ -230,22 -265,9 +230,12 @@@ static int16_t square_root(int val
   */
  static int normalize_bits(int num, int width)
  {
-     int i = 0;
-     if (num) {
-         if (num == -1)
-             return width;
-         if (num < 0)
-             num = ~num;
-         i= width - av_log2(num) - 1;
-         i= FFMAX(i, 0);
-     }
-     return i;
+     return width - av_log2(num) - 1;
  }
  
 +#define normalize_bits_int16(num) normalize_bits(num, 15)
 +#define normalize_bits_int32(num) normalize_bits(num, 31)
 +
  /**
   * Scale vector contents based on the largest of their absolutes.
   */
Simple merge
Simple merge
  
  #if FF_API_VDA_ASYNC
  /**
-  * This structure is used to store decoded frame information and data.
+  * This structure is used to store decoded frame information and data.
   *
   * @deprecated Use synchronous decoding mode.
-  *
   */
 -typedef struct vda_frame {
 +typedef struct {
      /**
-     * The PTS of the frame.
-     *
-     * - encoding: unused
-     * - decoding: Set/Unset by libavcodec.
-     */
+      * The PTS of the frame.
+      *
+      * - encoding: unused
+      * - decoding: Set/Unset by libavcodec.
+      */
      int64_t             pts;
  
      /**
@@@ -171,28 -171,19 +171,28 @@@ struct vda_context 
      OSType              cv_pix_fmt_type;
  
      /**
-     * The current bitstream buffer.
-     *
-     * - encoding: unused
-     * - decoding: Set/Unset by libavcodec.
-     */
-     uint8_t             *bitstream;
+      * The current bitstream buffer.
++     *
++     * - encoding: unused
++     * - decoding: Set/Unset by libavcodec.
+      */
+     uint8_t             *priv_bitstream;
  
      /**
-     * The current size of the bitstream.
-     *
-     * - encoding: unused
-     * - decoding: Set/Unset by libavcodec.
-     */
-     int                 bitstream_size;
+      * The current size of the bitstream.
++     *
++     * - encoding: unused
++     * - decoding: Set/Unset by libavcodec.
+      */
+     int                 priv_bitstream_size;
  
      /**
-     * The reference size used for fast reallocation.
-     *
-     * - encoding: unused
-     * - decoding: Set/Unset by libavcodec.
-     */
-     int                 ref_size;
+      * The reference size used for fast reallocation.
++     *
++     * - encoding: unused
++     * - decoding: Set/Unset by libavcodec.
+      */
+     int                 priv_allocated_size;
  };
  
  /** Create the video decoder. */
@@@ -123,14 -123,14 +123,14 @@@ void ff_vda_release_vda_frame(vda_fram
  }
  #endif
  
 -/* Decoder callback that adds the VDA frame to the queue in display order. */
 -static void vda_decoder_callback(void *vda_hw_ctx,
 -                                 CFDictionaryRef user_info,
 -                                 OSStatus status,
 -                                 uint32_t infoFlags,
 -                                 CVImageBufferRef image_buffer)
 +/* Decoder callback that adds the vda frame to the queue in display order. */
 +static void vda_decoder_callback (void *vda_hw_ctx,
 +                                  CFDictionaryRef user_info,
 +                                  OSStatus status,
 +                                  uint32_t infoFlags,
 +                                  CVImageBufferRef image_buffer)
  {
-     struct vda_context *vda_ctx = (struct vda_context*)vda_hw_ctx;
+     struct vda_context *vda_ctx = vda_hw_ctx;
  
      if (!image_buffer)
          return;
@@@ -280,9 -276,6 +279,9 @@@ int ff_vda_create_decoder(struct vda_co
      CFMutableDictionaryRef io_surface_properties;
      CFNumberRef cv_pix_fmt;
  
-     vda_ctx->bitstream = NULL;
-     vda_ctx->ref_size = 0;
++    vda_ctx->priv_bitstream = NULL;
++    vda_ctx->priv_allocated_size = 0;
 +
  #if FF_API_VDA_ASYNC
      pthread_mutex_init(&vda_ctx->queue_mutex, NULL);
  #endif
@@@ -368,8 -361,8 +367,7 @@@ int ff_vda_destroy_decoder(struct vda_c
      vda_clear_queue(vda_ctx);
      pthread_mutex_destroy(&vda_ctx->queue_mutex);
  #endif
-     if (vda_ctx->bitstream)
-         av_freep(&vda_ctx->bitstream);
 -
+     av_freep(&vda_ctx->priv_bitstream);
  
      return status;
  }
  #ifndef FF_API_CODEC_ID
  #define FF_API_CODEC_ID          (LIBAVCODEC_VERSION_MAJOR < 55)
  #endif
+ #ifndef FF_API_VDA_ASYNC
+ #define FF_API_VDA_ASYNC         (LIBAVCODEC_VERSION_MAJOR < 55)
+ #endif
  
 +#ifndef FF_API_VDA_ASYNC
 +#define FF_API_VDA_ASYNC         (LIBAVCODEC_VERSION_MAJOR < 55)
 +#endif
 +
  #endif /* AVCODEC_VERSION_H */
@@@ -205,11 -211,12 +207,11 @@@ static av_always_inline int get_cabac_b
          "movzwl         (%1), %%edx     \n\t"
          "bswap         %%edx            \n\t"
          "shrl            $15, %%edx     \n\t"
 +        "add              $2, %1        \n\t"
          "addl          %%edx, %%eax     \n\t"
-         "mov              %1, %a4(%2)   \n\t"
 -        "cmp         %c5(%2), %1        \n\t"
 -        "jge              1f            \n\t"
 -        "add"OPSIZE"      $2, %c4(%2)   \n\t"
++        "mov              %1, %c4(%2)   \n\t"
          "1:                             \n\t"
-         "movl          %%eax, %a3(%2)   \n\t"
+         "movl          %%eax, %c3(%2)   \n\t"
  
          : "+c"(val), "=&r"(tmp)
          : "r"(c),
Simple merge
Simple merge
@@@ -107,8 -107,7 +107,8 @@@ static void RENAME(yadif_filter_line)(u
                                        uint8_t *next, int w, int prefs,
                                        int mrefs, int parity, int mode)
  {
-     uint8_t tmp[5*16];
-     uint8_t *tmpA= (uint8_t*)(((uint64_t)(tmp+15)) & ~15);
 -    DECLARE_ALIGNED(16, uint8_t, tmp)[16*4];
++    uint8_t tmpU[5*16];
++    uint8_t *tmp= (uint8_t*)(((uint64_t)(tmpU+15)) & ~15);
      int x;
  
  #define FILTER\
Simple merge
Simple merge
@@@ -1051,13 -976,11 +961,12 @@@ static inline void RENAME(rgb15to32)(co
              "pand          %2, %%mm0    \n\t"
              "pand          %3, %%mm1    \n\t"
              "pand          %4, %%mm2    \n\t"
 -            "psllq         $3, %%mm0    \n\t"
 -            "psrlq         $2, %%mm1    \n\t"
 -            "psrlq         $7, %%mm2    \n\t"
 +            "psllq         $5, %%mm0    \n\t"
 +            "pmulhw        %5, %%mm0    \n\t"
 +            "pmulhw        %5, %%mm1    \n\t"
 +            "pmulhw        "MANGLE(mul15_hi)", %%mm2    \n\t"
              PACK_RGB32
-             :"=m"(*d)
-             :"m"(*s),"m"(mask15b),"m"(mask15g),"m"(mask15r),"m"(mul15_mid)
 -            ::"r"(d),"r"(s),"m"(mask15b),"m"(mask15g),"m"(mask15r)
++            ::"r"(d),"r"(s),"m"(mask15b),"m"(mask15g),"m"(mask15r) ,"m"(mul15_mid)
              :"memory");
          d += 16;
          s += 4;
@@@ -1094,14 -1017,11 +1003,13 @@@ static inline void RENAME(rgb16to32)(co
              "pand          %2, %%mm0    \n\t"
              "pand          %3, %%mm1    \n\t"
              "pand          %4, %%mm2    \n\t"
 -            "psllq         $3, %%mm0    \n\t"
 -            "psrlq         $3, %%mm1    \n\t"
 -            "psrlq         $8, %%mm2    \n\t"
 +            "psllq         $5, %%mm0    \n\t"
 +            "psrlq         $1, %%mm2    \n\t"
 +            "pmulhw        %5, %%mm0    \n\t"
 +            "pmulhw        "MANGLE(mul16_mid)", %%mm1    \n\t"
 +            "pmulhw        "MANGLE(mul15_hi)", %%mm2    \n\t"
              PACK_RGB32
-             :"=m"(*d)
-             :"m"(*s),"m"(mask16b),"m"(mask16g),"m"(mask16r),"m"(mul15_mid)
 -            ::"r"(d),"r"(s),"m"(mask16b),"m"(mask16g),"m"(mask16r)
++            ::"r"(d),"r"(s),"m"(mask16b),"m"(mask16g),"m"(mask16r),"m"(mul15_mid)
              :"memory");
          d += 16;
          s += 4;