LCOV - code coverage report
Current view: top level - fftools - ffmpeg.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 1927 2733 70.5 %
Date: 2018-05-20 11:54:08 Functions: 71 84 84.5 %

          Line data    Source code
       1             : /*
       2             :  * Copyright (c) 2000-2003 Fabrice Bellard
       3             :  *
       4             :  * This file is part of FFmpeg.
       5             :  *
       6             :  * FFmpeg is free software; you can redistribute it and/or
       7             :  * modify it under the terms of the GNU Lesser General Public
       8             :  * License as published by the Free Software Foundation; either
       9             :  * version 2.1 of the License, or (at your option) any later version.
      10             :  *
      11             :  * FFmpeg is distributed in the hope that it will be useful,
      12             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      13             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      14             :  * Lesser General Public License for more details.
      15             :  *
      16             :  * You should have received a copy of the GNU Lesser General Public
      17             :  * License along with FFmpeg; if not, write to the Free Software
      18             :  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
      19             :  */
      20             : 
      21             : /**
      22             :  * @file
      23             :  * multimedia converter based on the FFmpeg libraries
      24             :  */
      25             : 
      26             : #include "config.h"
      27             : #include <ctype.h>
      28             : #include <string.h>
      29             : #include <math.h>
      30             : #include <stdlib.h>
      31             : #include <errno.h>
      32             : #include <limits.h>
      33             : #include <stdatomic.h>
      34             : #include <stdint.h>
      35             : 
      36             : #if HAVE_IO_H
      37             : #include <io.h>
      38             : #endif
      39             : #if HAVE_UNISTD_H
      40             : #include <unistd.h>
      41             : #endif
      42             : 
      43             : #include "libavformat/avformat.h"
      44             : #include "libavdevice/avdevice.h"
      45             : #include "libswresample/swresample.h"
      46             : #include "libavutil/opt.h"
      47             : #include "libavutil/channel_layout.h"
      48             : #include "libavutil/parseutils.h"
      49             : #include "libavutil/samplefmt.h"
      50             : #include "libavutil/fifo.h"
      51             : #include "libavutil/hwcontext.h"
      52             : #include "libavutil/internal.h"
      53             : #include "libavutil/intreadwrite.h"
      54             : #include "libavutil/dict.h"
      55             : #include "libavutil/display.h"
      56             : #include "libavutil/mathematics.h"
      57             : #include "libavutil/pixdesc.h"
      58             : #include "libavutil/avstring.h"
      59             : #include "libavutil/libm.h"
      60             : #include "libavutil/imgutils.h"
      61             : #include "libavutil/timestamp.h"
      62             : #include "libavutil/bprint.h"
      63             : #include "libavutil/time.h"
      64             : #include "libavutil/thread.h"
      65             : #include "libavutil/threadmessage.h"
      66             : #include "libavcodec/mathops.h"
      67             : #include "libavformat/os_support.h"
      68             : 
      69             : # include "libavfilter/avfilter.h"
      70             : # include "libavfilter/buffersrc.h"
      71             : # include "libavfilter/buffersink.h"
      72             : 
      73             : #if HAVE_SYS_RESOURCE_H
      74             : #include <sys/time.h>
      75             : #include <sys/types.h>
      76             : #include <sys/resource.h>
      77             : #elif HAVE_GETPROCESSTIMES
      78             : #include <windows.h>
      79             : #endif
      80             : #if HAVE_GETPROCESSMEMORYINFO
      81             : #include <windows.h>
      82             : #include <psapi.h>
      83             : #endif
      84             : #if HAVE_SETCONSOLECTRLHANDLER
      85             : #include <windows.h>
      86             : #endif
      87             : 
      88             : 
      89             : #if HAVE_SYS_SELECT_H
      90             : #include <sys/select.h>
      91             : #endif
      92             : 
      93             : #if HAVE_TERMIOS_H
      94             : #include <fcntl.h>
      95             : #include <sys/ioctl.h>
      96             : #include <sys/time.h>
      97             : #include <termios.h>
      98             : #elif HAVE_KBHIT
      99             : #include <conio.h>
     100             : #endif
     101             : 
     102             : #include <time.h>
     103             : 
     104             : #include "ffmpeg.h"
     105             : #include "cmdutils.h"
     106             : 
     107             : #include "libavutil/avassert.h"
     108             : 
     109             : const char program_name[] = "ffmpeg";
     110             : const int program_birth_year = 2000;
     111             : 
     112             : static FILE *vstats_file;
     113             : 
     114             : const char *const forced_keyframes_const_names[] = {
     115             :     "n",
     116             :     "n_forced",
     117             :     "prev_forced_n",
     118             :     "prev_forced_t",
     119             :     "t",
     120             :     NULL
     121             : };
     122             : 
     123             : typedef struct BenchmarkTimeStamps {
     124             :     int64_t real_usec;
     125             :     int64_t user_usec;
     126             :     int64_t sys_usec;
     127             : } BenchmarkTimeStamps;
     128             : 
     129             : static void do_video_stats(OutputStream *ost, int frame_size);
     130             : static BenchmarkTimeStamps get_benchmark_time_stamps(void);
     131             : static int64_t getmaxrss(void);
     132             : static int ifilter_has_all_input_formats(FilterGraph *fg);
     133             : 
     134             : static int run_as_daemon  = 0;
     135             : static int nb_frames_dup = 0;
     136             : static unsigned dup_warning = 1000;
     137             : static int nb_frames_drop = 0;
     138             : static int64_t decode_error_stat[2];
     139             : 
     140             : static int want_sdp = 1;
     141             : 
     142             : static BenchmarkTimeStamps current_time;
     143             : AVIOContext *progress_avio = NULL;
     144             : 
     145             : static uint8_t *subtitle_out;
     146             : 
     147             : InputStream **input_streams = NULL;
     148             : int        nb_input_streams = 0;
     149             : InputFile   **input_files   = NULL;
     150             : int        nb_input_files   = 0;
     151             : 
     152             : OutputStream **output_streams = NULL;
     153             : int         nb_output_streams = 0;
     154             : OutputFile   **output_files   = NULL;
     155             : int         nb_output_files   = 0;
     156             : 
     157             : FilterGraph **filtergraphs;
     158             : int        nb_filtergraphs;
     159             : 
     160             : #if HAVE_TERMIOS_H
     161             : 
     162             : /* init terminal so that we can grab keys */
     163             : static struct termios oldtty;
     164             : static int restore_tty;
     165             : #endif
     166             : 
     167             : #if HAVE_THREADS
     168             : static void free_input_threads(void);
     169             : #endif
     170             : 
     171             : /* sub2video hack:
     172             :    Convert subtitles to video with alpha to insert them in filter graphs.
     173             :    This is a temporary solution until libavfilter gets real subtitles support.
     174             :  */
     175             : 
     176          90 : static int sub2video_get_blank_frame(InputStream *ist)
     177             : {
     178             :     int ret;
     179          90 :     AVFrame *frame = ist->sub2video.frame;
     180             : 
     181          90 :     av_frame_unref(frame);
     182          90 :     ist->sub2video.frame->width  = ist->dec_ctx->width  ? ist->dec_ctx->width  : ist->sub2video.w;
     183          90 :     ist->sub2video.frame->height = ist->dec_ctx->height ? ist->dec_ctx->height : ist->sub2video.h;
     184          90 :     ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
     185          90 :     if ((ret = av_frame_get_buffer(frame, 32)) < 0)
     186           0 :         return ret;
     187          90 :     memset(frame->data[0], 0, frame->height * frame->linesize[0]);
     188          90 :     return 0;
     189             : }
     190             : 
     191          44 : static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
     192             :                                 AVSubtitleRect *r)
     193             : {
     194             :     uint32_t *pal, *dst2;
     195             :     uint8_t *src, *src2;
     196             :     int x, y;
     197             : 
     198          44 :     if (r->type != SUBTITLE_BITMAP) {
     199           0 :         av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
     200           0 :         return;
     201             :     }
     202          44 :     if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
     203           0 :         av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle (%d %d %d %d) overflowing %d %d\n",
     204             :             r->x, r->y, r->w, r->h, w, h
     205             :         );
     206           0 :         return;
     207             :     }
     208             : 
     209          44 :     dst += r->y * dst_linesize + r->x * 4;
     210          44 :     src = r->data[0];
     211          44 :     pal = (uint32_t *)r->data[1];
     212        1642 :     for (y = 0; y < r->h; y++) {
     213        1598 :         dst2 = (uint32_t *)dst;
     214        1598 :         src2 = src;
     215      480325 :         for (x = 0; x < r->w; x++)
     216      478727 :             *(dst2++) = pal[*(src2++)];
     217        1598 :         dst += dst_linesize;
     218        1598 :         src += r->linesize[0];
     219             :     }
     220             : }
     221             : 
     222         335 : static void sub2video_push_ref(InputStream *ist, int64_t pts)
     223             : {
     224         335 :     AVFrame *frame = ist->sub2video.frame;
     225             :     int i;
     226             :     int ret;
     227             : 
     228             :     av_assert1(frame->data[0]);
     229         335 :     ist->sub2video.last_pts = frame->pts = pts;
     230         670 :     for (i = 0; i < ist->nb_filters; i++) {
     231         335 :         ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
     232             :                                            AV_BUFFERSRC_FLAG_KEEP_REF |
     233             :                                            AV_BUFFERSRC_FLAG_PUSH);
     234         335 :         if (ret != AVERROR_EOF && ret < 0)
     235           0 :             av_log(NULL, AV_LOG_WARNING, "Error while add the frame to buffer source(%s).\n",
     236           0 :                    av_err2str(ret));
     237             :     }
     238         335 : }
     239             : 
     240         119 : void sub2video_update(InputStream *ist, AVSubtitle *sub)
     241             : {
     242         119 :     AVFrame *frame = ist->sub2video.frame;
     243             :     int8_t *dst;
     244             :     int     dst_linesize;
     245             :     int num_rects, i;
     246             :     int64_t pts, end_pts;
     247             : 
     248         119 :     if (!frame)
     249          29 :         return;
     250          90 :     if (sub) {
     251          44 :         pts       = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
     252          44 :                                  AV_TIME_BASE_Q, ist->st->time_base);
     253          44 :         end_pts   = av_rescale_q(sub->pts + sub->end_display_time   * 1000LL,
     254          44 :                                  AV_TIME_BASE_Q, ist->st->time_base);
     255          44 :         num_rects = sub->num_rects;
     256             :     } else {
     257          46 :         pts       = ist->sub2video.end_pts;
     258          46 :         end_pts   = INT64_MAX;
     259          46 :         num_rects = 0;
     260             :     }
     261          90 :     if (sub2video_get_blank_frame(ist) < 0) {
     262           0 :         av_log(ist->dec_ctx, AV_LOG_ERROR,
     263             :                "Impossible to get a blank canvas.\n");
     264           0 :         return;
     265             :     }
     266          90 :     dst          = frame->data    [0];
     267          90 :     dst_linesize = frame->linesize[0];
     268         134 :     for (i = 0; i < num_rects; i++)
     269          44 :         sub2video_copy_rect(dst, dst_linesize, frame->width, frame->height, sub->rects[i]);
     270          90 :     sub2video_push_ref(ist, pts);
     271          90 :     ist->sub2video.end_pts = end_pts;
     272             : }
     273             : 
     274      389220 : static void sub2video_heartbeat(InputStream *ist, int64_t pts)
     275             : {
     276      389220 :     InputFile *infile = input_files[ist->file_index];
     277             :     int i, j, nb_reqs;
     278             :     int64_t pts2;
     279             : 
     280             :     /* When a frame is read from a file, examine all sub2video streams in
     281             :        the same file and send the sub2video frame again. Otherwise, decoded
     282             :        video frames could be accumulating in the filter graph while a filter
     283             :        (possibly overlay) is desperately waiting for a subtitle frame. */
     284      817012 :     for (i = 0; i < infile->nb_streams; i++) {
     285      427792 :         InputStream *ist2 = input_streams[infile->ist_index + i];
     286      427792 :         if (!ist2->sub2video.frame)
     287      426903 :             continue;
     288             :         /* subtitles seem to be usually muxed ahead of other streams;
     289             :            if not, subtracting a larger time here is necessary */
     290         889 :         pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
     291             :         /* do not send the heartbeat frame if the subtitle is already ahead */
     292         889 :         if (pts2 <= ist2->sub2video.last_pts)
     293           0 :             continue;
     294        1734 :         if (pts2 >= ist2->sub2video.end_pts ||
     295         845 :             (!ist2->sub2video.frame->data[0] && ist2->sub2video.end_pts < INT64_MAX))
     296          44 :             sub2video_update(ist2, NULL);
     297        1778 :         for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
     298         889 :             nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
     299         889 :         if (nb_reqs)
     300         245 :             sub2video_push_ref(ist2, pts2);
     301             :     }
     302      389220 : }
     303             : 
     304          31 : static void sub2video_flush(InputStream *ist)
     305             : {
     306             :     int i;
     307             :     int ret;
     308             : 
     309          31 :     if (ist->sub2video.end_pts < INT64_MAX)
     310          31 :         sub2video_update(ist, NULL);
     311          33 :     for (i = 0; i < ist->nb_filters; i++) {
     312           2 :         ret = av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
     313           2 :         if (ret != AVERROR_EOF && ret < 0)
     314           0 :             av_log(NULL, AV_LOG_WARNING, "Flush the frame error.\n");
     315             :     }
     316          31 : }
     317             : 
     318             : /* end of sub2video hack */
     319             : 
     320       11235 : static void term_exit_sigsafe(void)
     321             : {
     322             : #if HAVE_TERMIOS_H
     323       11235 :     if(restore_tty)
     324           4 :         tcsetattr (0, TCSANOW, &oldtty);
     325             : #endif
     326       11235 : }
     327             : 
     328       11235 : void term_exit(void)
     329             : {
     330       11235 :     av_log(NULL, AV_LOG_QUIET, "%s", "");
     331       11235 :     term_exit_sigsafe();
     332       11235 : }
     333             : 
     334             : static volatile int received_sigterm = 0;
     335             : static volatile int received_nb_signals = 0;
     336             : static atomic_int transcode_init_done = ATOMIC_VAR_INIT(0);
     337             : static volatile int ffmpeg_exited = 0;
     338             : static int main_return_code = 0;
     339             : 
     340             : static void
     341           0 : sigterm_handler(int sig)
     342             : {
     343             :     int ret;
     344           0 :     received_sigterm = sig;
     345           0 :     received_nb_signals++;
     346           0 :     term_exit_sigsafe();
     347           0 :     if(received_nb_signals > 3) {
     348           0 :         ret = write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
     349             :                     strlen("Received > 3 system signals, hard exiting\n"));
     350             :         if (ret < 0) { /* Do nothing */ };
     351           0 :         exit(123);
     352             :     }
     353           0 : }
     354             : 
     355             : #if HAVE_SETCONSOLECTRLHANDLER
     356             : static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
     357             : {
     358             :     av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
     359             : 
     360             :     switch (fdwCtrlType)
     361             :     {
     362             :     case CTRL_C_EVENT:
     363             :     case CTRL_BREAK_EVENT:
     364             :         sigterm_handler(SIGINT);
     365             :         return TRUE;
     366             : 
     367             :     case CTRL_CLOSE_EVENT:
     368             :     case CTRL_LOGOFF_EVENT:
     369             :     case CTRL_SHUTDOWN_EVENT:
     370             :         sigterm_handler(SIGTERM);
     371             :         /* Basically, with these 3 events, when we return from this method the
     372             :            process is hard terminated, so stall as long as we need to
     373             :            to try and let the main thread(s) clean up and gracefully terminate
     374             :            (we have at most 5 seconds, but should be done far before that). */
     375             :         while (!ffmpeg_exited) {
     376             :             Sleep(0);
     377             :         }
     378             :         return TRUE;
     379             : 
     380             :     default:
     381             :         av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
     382             :         return FALSE;
     383             :     }
     384             : }
     385             : #endif
     386             : 
     387        5617 : void term_init(void)
     388             : {
     389             : #if HAVE_TERMIOS_H
     390        5617 :     if (!run_as_daemon && stdin_interaction) {
     391             :         struct termios tty;
     392          15 :         if (tcgetattr (0, &tty) == 0) {
     393           2 :             oldtty = tty;
     394           2 :             restore_tty = 1;
     395             : 
     396           2 :             tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
     397             :                              |INLCR|IGNCR|ICRNL|IXON);
     398           2 :             tty.c_oflag |= OPOST;
     399           2 :             tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
     400           2 :             tty.c_cflag &= ~(CSIZE|PARENB);
     401           2 :             tty.c_cflag |= CS8;
     402           2 :             tty.c_cc[VMIN] = 1;
     403           2 :             tty.c_cc[VTIME] = 0;
     404             : 
     405           2 :             tcsetattr (0, TCSANOW, &tty);
     406             :         }
     407          15 :         signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
     408             :     }
     409             : #endif
     410             : 
     411        5617 :     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
     412        5617 :     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
     413             : #ifdef SIGXCPU
     414        5617 :     signal(SIGXCPU, sigterm_handler);
     415             : #endif
     416             : #ifdef SIGPIPE
     417        5617 :     signal(SIGPIPE, SIG_IGN); /* Broken pipe (POSIX). */
     418             : #endif
     419             : #if HAVE_SETCONSOLECTRLHANDLER
     420             :     SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
     421             : #endif
     422        5617 : }
     423             : 
     424             : /* read a key without blocking */
     425          42 : static int read_key(void)
     426             : {
     427             :     unsigned char ch;
     428             : #if HAVE_TERMIOS_H
     429          42 :     int n = 1;
     430             :     struct timeval tv;
     431             :     fd_set rfds;
     432             : 
     433          42 :     FD_ZERO(&rfds);
     434          42 :     FD_SET(0, &rfds);
     435          42 :     tv.tv_sec = 0;
     436          42 :     tv.tv_usec = 0;
     437          42 :     n = select(1, &rfds, NULL, NULL, &tv);
     438          42 :     if (n > 0) {
     439          28 :         n = read(0, &ch, 1);
     440          28 :         if (n == 1)
     441           0 :             return ch;
     442             : 
     443          28 :         return n;
     444             :     }
     445             : #elif HAVE_KBHIT
     446             : #    if HAVE_PEEKNAMEDPIPE
     447             :     static int is_pipe;
     448             :     static HANDLE input_handle;
     449             :     DWORD dw, nchars;
     450             :     if(!input_handle){
     451             :         input_handle = GetStdHandle(STD_INPUT_HANDLE);
     452             :         is_pipe = !GetConsoleMode(input_handle, &dw);
     453             :     }
     454             : 
     455             :     if (is_pipe) {
     456             :         /* When running under a GUI, you will end here. */
     457             :         if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
     458             :             // input pipe may have been closed by the program that ran ffmpeg
     459             :             return -1;
     460             :         }
     461             :         //Read it
     462             :         if(nchars != 0) {
     463             :             read(0, &ch, 1);
     464             :             return ch;
     465             :         }else{
     466             :             return -1;
     467             :         }
     468             :     }
     469             : #    endif
     470             :     if(kbhit())
     471             :         return(getch());
     472             : #endif
     473          14 :     return -1;
     474             : }
     475             : 
     476      562410 : static int decode_interrupt_cb(void *ctx)
     477             : {
     478      562410 :     return received_nb_signals > atomic_load(&transcode_init_done);
     479             : }
     480             : 
     481             : const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
     482             : 
     483        5618 : static void ffmpeg_cleanup(int ret)
     484             : {
     485             :     int i, j;
     486             : 
     487        5618 :     if (do_benchmark) {
     488           0 :         int maxrss = getmaxrss() / 1024;
     489           0 :         av_log(NULL, AV_LOG_INFO, "bench: maxrss=%ikB\n", maxrss);
     490             :     }
     491             : 
     492       11092 :     for (i = 0; i < nb_filtergraphs; i++) {
     493        5474 :         FilterGraph *fg = filtergraphs[i];
     494        5474 :         avfilter_graph_free(&fg->graph);
     495       10933 :         for (j = 0; j < fg->nb_inputs; j++) {
     496       10918 :             while (av_fifo_size(fg->inputs[j]->frame_queue)) {
     497             :                 AVFrame *frame;
     498           0 :                 av_fifo_generic_read(fg->inputs[j]->frame_queue, &frame,
     499             :                                      sizeof(frame), NULL);
     500           0 :                 av_frame_free(&frame);
     501             :             }
     502        5459 :             av_fifo_freep(&fg->inputs[j]->frame_queue);
     503        5459 :             if (fg->inputs[j]->ist->sub2video.sub_queue) {
     504           0 :                 while (av_fifo_size(fg->inputs[j]->ist->sub2video.sub_queue)) {
     505             :                     AVSubtitle sub;
     506           0 :                     av_fifo_generic_read(fg->inputs[j]->ist->sub2video.sub_queue,
     507             :                                          &sub, sizeof(sub), NULL);
     508           0 :                     avsubtitle_free(&sub);
     509             :                 }
     510           0 :                 av_fifo_freep(&fg->inputs[j]->ist->sub2video.sub_queue);
     511             :             }
     512        5459 :             av_buffer_unref(&fg->inputs[j]->hw_frames_ctx);
     513        5459 :             av_freep(&fg->inputs[j]->name);
     514        5459 :             av_freep(&fg->inputs[j]);
     515             :         }
     516        5474 :         av_freep(&fg->inputs);
     517       10950 :         for (j = 0; j < fg->nb_outputs; j++) {
     518        5476 :             av_freep(&fg->outputs[j]->name);
     519        5476 :             av_freep(&fg->outputs[j]->formats);
     520        5476 :             av_freep(&fg->outputs[j]->channel_layouts);
     521        5476 :             av_freep(&fg->outputs[j]->sample_rates);
     522        5476 :             av_freep(&fg->outputs[j]);
     523             :         }
     524        5474 :         av_freep(&fg->outputs);
     525        5474 :         av_freep(&fg->graph_desc);
     526             : 
     527        5474 :         av_freep(&filtergraphs[i]);
     528             :     }
     529        5618 :     av_freep(&filtergraphs);
     530             : 
     531        5618 :     av_freep(&subtitle_out);
     532             : 
     533             :     /* close files */
     534       11236 :     for (i = 0; i < nb_output_files; i++) {
     535        5618 :         OutputFile *of = output_files[i];
     536             :         AVFormatContext *s;
     537        5618 :         if (!of)
     538           0 :             continue;
     539        5618 :         s = of->ctx;
     540        5618 :         if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
     541        5573 :             avio_closep(&s->pb);
     542        5618 :         avformat_free_context(s);
     543        5618 :         av_dict_free(&of->opts);
     544             : 
     545        5618 :         av_freep(&output_files[i]);
     546             :     }
     547       11374 :     for (i = 0; i < nb_output_streams; i++) {
     548        5756 :         OutputStream *ost = output_streams[i];
     549             : 
     550        5756 :         if (!ost)
     551           0 :             continue;
     552             : 
     553        5822 :         for (j = 0; j < ost->nb_bitstream_filters; j++)
     554          66 :             av_bsf_free(&ost->bsf_ctx[j]);
     555        5756 :         av_freep(&ost->bsf_ctx);
     556             : 
     557        5756 :         av_frame_free(&ost->filtered_frame);
     558        5756 :         av_frame_free(&ost->last_frame);
     559        5756 :         av_dict_free(&ost->encoder_opts);
     560             : 
     561        5756 :         av_freep(&ost->forced_keyframes);
     562        5756 :         av_expr_free(ost->forced_keyframes_pexpr);
     563        5756 :         av_freep(&ost->avfilter);
     564        5756 :         av_freep(&ost->logfile_prefix);
     565             : 
     566        5756 :         av_freep(&ost->audio_channels_map);
     567        5756 :         ost->audio_channels_mapped = 0;
     568             : 
     569        5756 :         av_dict_free(&ost->sws_dict);
     570             : 
     571        5756 :         avcodec_free_context(&ost->enc_ctx);
     572        5756 :         avcodec_parameters_free(&ost->ref_par);
     573             : 
     574        5756 :         if (ost->muxing_queue) {
     575       11512 :             while (av_fifo_size(ost->muxing_queue)) {
     576             :                 AVPacket pkt;
     577           0 :                 av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
     578           0 :                 av_packet_unref(&pkt);
     579             :             }
     580        5756 :             av_fifo_freep(&ost->muxing_queue);
     581             :         }
     582             : 
     583        5756 :         av_freep(&output_streams[i]);
     584             :     }
     585             : #if HAVE_THREADS
     586        5618 :     free_input_threads();
     587             : #endif
     588       11268 :     for (i = 0; i < nb_input_files; i++) {
     589        5650 :         avformat_close_input(&input_files[i]->ctx);
     590        5650 :         av_freep(&input_files[i]);
     591             :     }
     592       11576 :     for (i = 0; i < nb_input_streams; i++) {
     593        5958 :         InputStream *ist = input_streams[i];
     594             : 
     595        5958 :         av_frame_free(&ist->decoded_frame);
     596        5958 :         av_frame_free(&ist->filter_frame);
     597        5958 :         av_dict_free(&ist->decoder_opts);
     598        5958 :         avsubtitle_free(&ist->prev_sub.subtitle);
     599        5958 :         av_frame_free(&ist->sub2video.frame);
     600        5958 :         av_freep(&ist->filters);
     601        5958 :         av_freep(&ist->hwaccel_device);
     602        5958 :         av_freep(&ist->dts_buffer);
     603             : 
     604        5958 :         avcodec_free_context(&ist->dec_ctx);
     605             : 
     606        5958 :         av_freep(&input_streams[i]);
     607             :     }
     608             : 
     609        5618 :     if (vstats_file) {
     610           0 :         if (fclose(vstats_file))
     611           0 :             av_log(NULL, AV_LOG_ERROR,
     612             :                    "Error closing vstats file, loss of information possible: %s\n",
     613           0 :                    av_err2str(AVERROR(errno)));
     614             :     }
     615        5618 :     av_freep(&vstats_filename);
     616             : 
     617        5618 :     av_freep(&input_streams);
     618        5618 :     av_freep(&input_files);
     619        5618 :     av_freep(&output_streams);
     620        5618 :     av_freep(&output_files);
     621             : 
     622        5618 :     uninit_opts();
     623             : 
     624        5618 :     avformat_network_deinit();
     625             : 
     626        5618 :     if (received_sigterm) {
     627           0 :         av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
     628             :                (int) received_sigterm);
     629        5618 :     } else if (ret && atomic_load(&transcode_init_done)) {
     630           0 :         av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
     631             :     }
     632        5618 :     term_exit();
     633        5618 :     ffmpeg_exited = 1;
     634        5618 : }
     635             : 
     636        5650 : void remove_avoptions(AVDictionary **a, AVDictionary *b)
     637             : {
     638        5650 :     AVDictionaryEntry *t = NULL;
     639             : 
     640       29065 :     while ((t = av_dict_get(b, "", t, AV_DICT_IGNORE_SUFFIX))) {
     641       17765 :         av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
     642             :     }
     643        5650 : }
     644             : 
     645       16643 : void assert_avoptions(AVDictionary *m)
     646             : {
     647             :     AVDictionaryEntry *t;
     648       16643 :     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
     649           0 :         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
     650           0 :         exit_program(1);
     651             :     }
     652       16643 : }
     653             : 
     654           0 : static void abort_codec_experimental(AVCodec *c, int encoder)
     655             : {
     656           0 :     exit_program(1);
     657             : }
     658             : 
     659     2374222 : static void update_benchmark(const char *fmt, ...)
     660             : {
     661     2374222 :     if (do_benchmark_all) {
     662           0 :         BenchmarkTimeStamps t = get_benchmark_time_stamps();
     663             :         va_list va;
     664             :         char buf[1024];
     665             : 
     666           0 :         if (fmt) {
     667           0 :             va_start(va, fmt);
     668           0 :             vsnprintf(buf, sizeof(buf), fmt, va);
     669           0 :             va_end(va);
     670           0 :             av_log(NULL, AV_LOG_INFO,
     671             :                    "bench: %8" PRIu64 " user %8" PRIu64 " sys %8" PRIu64 " real %s \n",
     672           0 :                    t.user_usec - current_time.user_usec,
     673           0 :                    t.sys_usec - current_time.sys_usec,
     674           0 :                    t.real_usec - current_time.real_usec, buf);
     675             :         }
     676           0 :         current_time = t;
     677             :     }
     678     2374222 : }
     679             : 
     680           0 : static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
     681             : {
     682             :     int i;
     683           0 :     for (i = 0; i < nb_output_streams; i++) {
     684           0 :         OutputStream *ost2 = output_streams[i];
     685           0 :         ost2->finished |= ost == ost2 ? this_stream : others;
     686             :     }
     687           0 : }
     688             : 
     689      418068 : static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
     690             : {
     691      418068 :     AVFormatContext *s = of->ctx;
     692      418068 :     AVStream *st = ost->st;
     693             :     int ret;
     694             : 
     695             :     /*
     696             :      * Audio encoders may split the packets --  #frames in != #packets out.
     697             :      * But there is no reordering, so we can limit the number of output packets
     698             :      * by simply dropping them here.
     699             :      * Counting encoded video frames needs to be done separately because of
     700             :      * reordering, see do_video_out().
     701             :      * Do not count the packet when unqueued because it has been counted when queued.
     702             :      */
     703      418068 :     if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed) && !unqueue) {
     704      321001 :         if (ost->frame_number >= ost->max_frames) {
     705         313 :             av_packet_unref(pkt);
     706         313 :             return;
     707             :         }
     708      320688 :         ost->frame_number++;
     709             :     }
     710             : 
     711      417755 :     if (!of->header_written) {
     712         276 :         AVPacket tmp_pkt = {0};
     713             :         /* the muxer is not initialized yet, buffer the packet */
     714         276 :         if (!av_fifo_space(ost->muxing_queue)) {
     715          16 :             int new_size = FFMIN(2 * av_fifo_size(ost->muxing_queue),
     716             :                                  ost->max_muxing_queue_size);
     717          16 :             if (new_size <= av_fifo_size(ost->muxing_queue)) {
     718           0 :                 av_log(NULL, AV_LOG_ERROR,
     719             :                        "Too many packets buffered for output stream %d:%d.\n",
     720           0 :                        ost->file_index, ost->st->index);
     721           0 :                 exit_program(1);
     722             :             }
     723          16 :             ret = av_fifo_realloc2(ost->muxing_queue, new_size);
     724          16 :             if (ret < 0)
     725           0 :                 exit_program(1);
     726             :         }
     727         276 :         ret = av_packet_ref(&tmp_pkt, pkt);
     728         276 :         if (ret < 0)
     729           0 :             exit_program(1);
     730         276 :         av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);
     731         276 :         av_packet_unref(pkt);
     732         276 :         return;
     733             :     }
     734             : 
     735      811630 :     if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
     736      705233 :         (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
     737       23328 :         pkt->pts = pkt->dts = AV_NOPTS_VALUE;
     738             : 
     739      417479 :     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
     740             :         int i;
     741      105272 :         uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,
     742             :                                               NULL);
     743      105272 :         ost->quality = sd ? AV_RL32(sd) : -1;
     744      105272 :         ost->pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;
     745             : 
     746      526360 :         for (i = 0; i<FF_ARRAY_ELEMS(ost->error); i++) {
     747      421088 :             if (sd && i < sd[5])
     748           0 :                 ost->error[i] = AV_RL64(sd + 8 + 8*i);
     749             :             else
     750      421088 :                 ost->error[i] = -1;
     751             :         }
     752             : 
     753      105272 :         if (ost->frame_rate.num && ost->is_cfr) {
     754        9059 :             if (pkt->duration > 0)
     755           0 :                 av_log(NULL, AV_LOG_WARNING, "Overriding packet duration by frame rate, this should not happen\n");
     756        9059 :             pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
     757             :                                          ost->mux_timebase);
     758             :         }
     759             :     }
     760             : 
     761      417479 :     av_packet_rescale_ts(pkt, ost->mux_timebase, ost->st->time_base);
     762             : 
     763      417479 :     if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
     764      337142 :         if (pkt->dts != AV_NOPTS_VALUE &&
     765      313295 :             pkt->pts != AV_NOPTS_VALUE &&
     766      156388 :             pkt->dts > pkt->pts) {
     767           0 :             av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
     768             :                    pkt->dts, pkt->pts,
     769           0 :                    ost->file_index, ost->st->index);
     770           0 :             pkt->pts =
     771           0 :             pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1
     772           0 :                      - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)
     773           0 :                      - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);
     774             :         }
     775      359862 :         if ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
     776      335926 :             pkt->dts != AV_NOPTS_VALUE &&
     777      312598 :             !(st->codecpar->codec_id == AV_CODEC_ID_VP9 && ost->stream_copy) &&
     778      156066 :             ost->last_mux_dts != AV_NOPTS_VALUE) {
     779      151849 :             int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
     780      151849 :             if (pkt->dts < max) {
     781           0 :                 int loglevel = max - pkt->dts > 2 || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
     782           0 :                 av_log(s, loglevel, "Non-monotonous DTS in output stream "
     783             :                        "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
     784           0 :                        ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
     785           0 :                 if (exit_on_error) {
     786           0 :                     av_log(NULL, AV_LOG_FATAL, "aborting.\n");
     787           0 :                     exit_program(1);
     788             :                 }
     789           0 :                 av_log(s, loglevel, "changing to %"PRId64". This may result "
     790             :                        "in incorrect timestamps in the output file.\n",
     791             :                        max);
     792           0 :                 if (pkt->pts >= pkt->dts)
     793           0 :                     pkt->pts = FFMAX(pkt->pts, max);
     794           0 :                 pkt->dts = max;
     795             :             }
     796             :         }
     797             :     }
     798      417479 :     ost->last_mux_dts = pkt->dts;
     799             : 
     800      417479 :     ost->data_size += pkt->size;
     801      417479 :     ost->packets_written++;
     802             : 
     803      417479 :     pkt->stream_index = ost->index;
     804             : 
     805      417479 :     if (debug_ts) {
     806           0 :         av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
     807             :                 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
     808           0 :                 av_get_media_type_string(ost->enc_ctx->codec_type),
     809           0 :                 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
     810           0 :                 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
     811             :                 pkt->size
     812             :               );
     813             :     }
     814             : 
     815      417479 :     ret = av_interleaved_write_frame(s, pkt);
     816      417479 :     if (ret < 0) {
     817           0 :         print_error("av_interleaved_write_frame()", ret);
     818           0 :         main_return_code = 1;
     819           0 :         close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);
     820             :     }
     821      417479 :     av_packet_unref(pkt);
     822             : }
     823             : 
     824        5488 : static void close_output_stream(OutputStream *ost)
     825             : {
     826        5488 :     OutputFile *of = output_files[ost->file_index];
     827             : 
     828        5488 :     ost->finished |= ENCODER_FINISHED;
     829        5488 :     if (of->shortest) {
     830           0 :         int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, AV_TIME_BASE_Q);
     831           0 :         of->recording_time = FFMIN(of->recording_time, end);
     832             :     }
     833        5488 : }
     834             : 
     835             : /*
     836             :  * Send a single packet to the output, applying any bitstream filters
     837             :  * associated with the output stream.  This may result in any number
     838             :  * of packets actually being written, depending on what bitstream
     839             :  * filters are applied.  The supplied packet is consumed and will be
     840             :  * blank (as if newly-allocated) when this function returns.
     841             :  *
     842             :  * If eof is set, instead indicate EOF to all bitstream filters and
     843             :  * therefore flush any delayed packets to the output.  A blank packet
     844             :  * must be supplied in this case.
     845             :  */
     846      422286 : static void output_packet(OutputFile *of, AVPacket *pkt,
     847             :                           OutputStream *ost, int eof)
     848             : {
     849      422286 :     int ret = 0;
     850             : 
     851             :     /* apply the output bitstream filters, if any */
     852      422286 :     if (ost->nb_bitstream_filters) {
     853             :         int idx;
     854             : 
     855        6279 :         ret = av_bsf_send_packet(ost->bsf_ctx[0], eof ? NULL : pkt);
     856        6279 :         if (ret < 0)
     857           0 :             goto finish;
     858             : 
     859        6279 :         eof = 0;
     860        6279 :         idx = 1;
     861       25108 :         while (idx) {
     862             :             /* get a packet from the previous filter up the chain */
     863       12554 :             ret = av_bsf_receive_packet(ost->bsf_ctx[idx - 1], pkt);
     864       12554 :             if (ret == AVERROR(EAGAIN)) {
     865        6275 :                 ret = 0;
     866        6275 :                 idx--;
     867        6275 :                 continue;
     868        6279 :             } else if (ret == AVERROR_EOF) {
     869           3 :                 eof = 1;
     870        6276 :             } else if (ret < 0)
     871           1 :                 goto finish;
     872             : 
     873             :             /* send it to the next filter down the chain or to the muxer */
     874        6278 :             if (idx < ost->nb_bitstream_filters) {
     875           0 :                 ret = av_bsf_send_packet(ost->bsf_ctx[idx], eof ? NULL : pkt);
     876           0 :                 if (ret < 0)
     877           0 :                     goto finish;
     878           0 :                 idx++;
     879           0 :                 eof = 0;
     880        6278 :             } else if (eof)
     881           3 :                 goto finish;
     882             :             else
     883        6275 :                 write_packet(of, pkt, ost, 0);
     884             :         }
     885      416007 :     } else if (!eof)
     886      411517 :         write_packet(of, pkt, ost, 0);
     887             : 
     888      426776 : finish:
     889      422286 :     if (ret < 0 && ret != AVERROR_EOF) {
     890           1 :         av_log(NULL, AV_LOG_ERROR, "Error applying bitstream filters to an output "
     891             :                "packet for stream #%d:%d.\n", ost->file_index, ost->index);
     892           1 :         if(exit_on_error)
     893           0 :             exit_program(1);
     894             :     }
     895      422286 : }
     896             : 
     897      394748 : static int check_recording_time(OutputStream *ost)
     898             : {
     899      394748 :     OutputFile *of = output_files[ost->file_index];
     900             : 
     901      400939 :     if (of->recording_time != INT64_MAX &&
     902        6191 :         av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
     903        6191 :                       AV_TIME_BASE_Q) >= 0) {
     904           1 :         close_output_stream(ost);
     905           1 :         return 0;
     906             :     }
     907      394747 :     return 1;
     908             : }
     909             : 
     910      297361 : static void do_audio_out(OutputFile *of, OutputStream *ost,
     911             :                          AVFrame *frame)
     912             : {
     913      297361 :     AVCodecContext *enc = ost->enc_ctx;
     914             :     AVPacket pkt;
     915             :     int ret;
     916             : 
     917      297361 :     av_init_packet(&pkt);
     918      297361 :     pkt.data = NULL;
     919      297361 :     pkt.size = 0;
     920             : 
     921      297361 :     if (!check_recording_time(ost))
     922           0 :         return;
     923             : 
     924      297361 :     if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
     925           0 :         frame->pts = ost->sync_opts;
     926      297361 :     ost->sync_opts = frame->pts + frame->nb_samples;
     927      297361 :     ost->samples_encoded += frame->nb_samples;
     928      297361 :     ost->frames_encoded++;
     929             : 
     930      297361 :     av_assert0(pkt.size || !pkt.data);
     931      297361 :     update_benchmark(NULL);
     932      297361 :     if (debug_ts) {
     933           0 :         av_log(NULL, AV_LOG_INFO, "encoder <- type:audio "
     934             :                "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
     935           0 :                av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
     936             :                enc->time_base.num, enc->time_base.den);
     937             :     }
     938             : 
     939      297361 :     ret = avcodec_send_frame(enc, frame);
     940      297361 :     if (ret < 0)
     941           0 :         goto error;
     942             : 
     943             :     while (1) {
     944      291205 :         ret = avcodec_receive_packet(enc, &pkt);
     945      588566 :         if (ret == AVERROR(EAGAIN))
     946      297361 :             break;
     947      291205 :         if (ret < 0)
     948           0 :             goto error;
     949             : 
     950      291205 :         update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
     951             : 
     952      291205 :         av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
     953             : 
     954      291205 :         if (debug_ts) {
     955           0 :             av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
     956             :                    "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
     957           0 :                    av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
     958           0 :                    av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
     959             :         }
     960             : 
     961      291205 :         output_packet(of, &pkt, ost, 0);
     962             :     }
     963             : 
     964      297361 :     return;
     965           0 : error:
     966           0 :     av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
     967           0 :     exit_program(1);
     968             : }
     969             : 
     970         595 : static void do_subtitle_out(OutputFile *of,
     971             :                             OutputStream *ost,
     972             :                             AVSubtitle *sub)
     973             : {
     974         595 :     int subtitle_out_max_size = 1024 * 1024;
     975             :     int subtitle_out_size, nb, i;
     976             :     AVCodecContext *enc;
     977             :     AVPacket pkt;
     978             :     int64_t pts;
     979             : 
     980         595 :     if (sub->pts == AV_NOPTS_VALUE) {
     981           0 :         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
     982           0 :         if (exit_on_error)
     983           0 :             exit_program(1);
     984           0 :         return;
     985             :     }
     986             : 
     987         595 :     enc = ost->enc_ctx;
     988             : 
     989         595 :     if (!subtitle_out) {
     990          30 :         subtitle_out = av_malloc(subtitle_out_max_size);
     991          30 :         if (!subtitle_out) {
     992           0 :             av_log(NULL, AV_LOG_FATAL, "Failed to allocate subtitle_out\n");
     993           0 :             exit_program(1);
     994             :         }
     995             :     }
     996             : 
     997             :     /* Note: DVB subtitle need one packet to draw them and one other
     998             :        packet to clear them */
     999             :     /* XXX: signal it in the codec context ? */
    1000         595 :     if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
    1001           0 :         nb = 2;
    1002             :     else
    1003         595 :         nb = 1;
    1004             : 
    1005             :     /* shift timestamp to honor -ss and make check_recording_time() work with -t */
    1006         595 :     pts = sub->pts;
    1007         595 :     if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
    1008           0 :         pts -= output_files[ost->file_index]->start_time;
    1009        1190 :     for (i = 0; i < nb; i++) {
    1010         595 :         unsigned save_num_rects = sub->num_rects;
    1011             : 
    1012         595 :         ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
    1013         595 :         if (!check_recording_time(ost))
    1014           0 :             return;
    1015             : 
    1016         595 :         sub->pts = pts;
    1017             :         // start_display_time is required to be 0
    1018         595 :         sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
    1019         595 :         sub->end_display_time  -= sub->start_display_time;
    1020         595 :         sub->start_display_time = 0;
    1021         595 :         if (i == 1)
    1022           0 :             sub->num_rects = 0;
    1023             : 
    1024         595 :         ost->frames_encoded++;
    1025             : 
    1026         595 :         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
    1027             :                                                     subtitle_out_max_size, sub);
    1028         595 :         if (i == 1)
    1029           0 :             sub->num_rects = save_num_rects;
    1030         595 :         if (subtitle_out_size < 0) {
    1031           0 :             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
    1032           0 :             exit_program(1);
    1033             :         }
    1034             : 
    1035         595 :         av_init_packet(&pkt);
    1036         595 :         pkt.data = subtitle_out;
    1037         595 :         pkt.size = subtitle_out_size;
    1038         595 :         pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->mux_timebase);
    1039         595 :         pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
    1040         595 :         if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
    1041             :             /* XXX: the pts correction is handled here. Maybe handling
    1042             :                it in the codec would be better */
    1043           0 :             if (i == 0)
    1044           0 :                 pkt.pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
    1045             :             else
    1046           0 :                 pkt.pts += av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
    1047             :         }
    1048         595 :         pkt.dts = pkt.pts;
    1049         595 :         output_packet(of, &pkt, ost, 0);
    1050             :     }
    1051             : }
    1052             : 
    1053       99104 : static void do_video_out(OutputFile *of,
    1054             :                          OutputStream *ost,
    1055             :                          AVFrame *next_picture,
    1056             :                          double sync_ipts)
    1057             : {
    1058             :     int ret, format_video_sync;
    1059             :     AVPacket pkt;
    1060       99104 :     AVCodecContext *enc = ost->enc_ctx;
    1061       99104 :     AVCodecParameters *mux_par = ost->st->codecpar;
    1062             :     AVRational frame_rate;
    1063             :     int nb_frames, nb0_frames, i;
    1064             :     double delta, delta0;
    1065       99104 :     double duration = 0;
    1066       99104 :     int frame_size = 0;
    1067       99104 :     InputStream *ist = NULL;
    1068       99104 :     AVFilterContext *filter = ost->filter->filter;
    1069             : 
    1070       99104 :     if (ost->source_index >= 0)
    1071       97662 :         ist = input_streams[ost->source_index];
    1072             : 
    1073       99104 :     frame_rate = av_buffersink_get_frame_rate(filter);
    1074       99104 :     if (frame_rate.num > 0 && frame_rate.den > 0)
    1075       99104 :         duration = 1/(av_q2d(frame_rate) * av_q2d(enc->time_base));
    1076             : 
    1077       99104 :     if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
    1078       63178 :         duration = FFMIN(duration, 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base)));
    1079             : 
    1080      198111 :     if (!ost->filters_script &&
    1081      191815 :         !ost->filters &&
    1082       90520 :         next_picture &&
    1083       89120 :         ist &&
    1084       89120 :         lrintf(next_picture->pkt_duration * av_q2d(ist->st->time_base) / av_q2d(enc->time_base)) > 0) {
    1085       84301 :         duration = lrintf(next_picture->pkt_duration * av_q2d(ist->st->time_base) / av_q2d(enc->time_base));
    1086             :     }
    1087             : 
    1088       99104 :     if (!next_picture) {
    1089             :         //end, flushing
    1090        2350 :         nb0_frames = nb_frames = mid_pred(ost->last_nb0_frames[0],
    1091             :                                           ost->last_nb0_frames[1],
    1092             :                                           ost->last_nb0_frames[2]);
    1093             :     } else {
    1094       96754 :         delta0 = sync_ipts - ost->sync_opts; // delta0 is the "drift" between the input frame (next_picture) and where it would fall in the output.
    1095       96754 :         delta  = delta0 + duration;
    1096             : 
    1097             :         /* by default, we output a single frame */
    1098       96754 :         nb0_frames = 0; // tracks the number of times the PREVIOUS frame should be duplicated, mostly for variable framerate (VFR)
    1099       96754 :         nb_frames = 1;
    1100             : 
    1101       96754 :         format_video_sync = video_sync_method;
    1102       96754 :         if (format_video_sync == VSYNC_AUTO) {
    1103       54850 :             if(!strcmp(of->ctx->oformat->name, "avi")) {
    1104       12650 :                 format_video_sync = VSYNC_VFR;
    1105             :             } else
    1106       42200 :                 format_video_sync = (of->ctx->oformat->flags & AVFMT_VARIABLE_FPS) ? ((of->ctx->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
    1107       54850 :             if (   ist
    1108       53450 :                 && format_video_sync == VSYNC_CFR
    1109        8694 :                 && input_files[ist->file_index]->ctx->nb_streams == 1
    1110        7674 :                 && input_files[ist->file_index]->input_ts_offset == 0) {
    1111        7674 :                 format_video_sync = VSYNC_VSCFR;
    1112             :             }
    1113       54850 :             if (format_video_sync == VSYNC_CFR && copy_ts) {
    1114           0 :                 format_video_sync = VSYNC_VSCFR;
    1115             :             }
    1116             :         }
    1117       96754 :         ost->is_cfr = (format_video_sync == VSYNC_CFR || format_video_sync == VSYNC_VSCFR);
    1118             : 
    1119       96754 :         if (delta0 < 0 &&
    1120       10944 :             delta > 0 &&
    1121       10542 :             format_video_sync != VSYNC_PASSTHROUGH &&
    1122             :             format_video_sync != VSYNC_DROP) {
    1123        7773 :             if (delta0 < -0.6) {
    1124         437 :                 av_log(NULL, AV_LOG_WARNING, "Past duration %f too large\n", -delta0);
    1125             :             } else
    1126        7336 :                 av_log(NULL, AV_LOG_DEBUG, "Clipping frame in rate conversion by %f\n", -delta0);
    1127        7773 :             sync_ipts = ost->sync_opts;
    1128        7773 :             duration += delta0;
    1129        7773 :             delta0 = 0;
    1130             :         }
    1131             : 
    1132       96754 :         switch (format_video_sync) {
    1133        7674 :         case VSYNC_VSCFR:
    1134        7674 :             if (ost->frame_number == 0 && delta0 >= 0.5) {
    1135           0 :                 av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta0));
    1136           0 :                 delta = duration;
    1137           0 :                 delta0 = 0;
    1138           0 :                 ost->sync_opts = lrint(sync_ipts);
    1139             :             }
    1140             :         case VSYNC_CFR:
    1141             :             // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
    1142        8848 :             if (frame_drop_threshold && delta < frame_drop_threshold && ost->frame_number) {
    1143           0 :                 nb_frames = 0;
    1144        8848 :             } else if (delta < -1.1)
    1145           0 :                 nb_frames = 0;
    1146        8848 :             else if (delta > 1.1) {
    1147         350 :                 nb_frames = lrintf(delta);
    1148         350 :                 if (delta0 > 1.1)
    1149           2 :                     nb0_frames = lrintf(delta0 - 0.6);
    1150             :             }
    1151        8848 :             break;
    1152       46139 :         case VSYNC_VFR:
    1153       46139 :             if (delta <= -0.6)
    1154         171 :                 nb_frames = 0;
    1155       45968 :             else if (delta > 0.6)
    1156       45380 :                 ost->sync_opts = lrint(sync_ipts);
    1157       46139 :             break;
    1158       41767 :         case VSYNC_DROP:
    1159             :         case VSYNC_PASSTHROUGH:
    1160       41767 :             ost->sync_opts = lrint(sync_ipts);
    1161       41767 :             break;
    1162           0 :         default:
    1163           0 :             av_assert0(0);
    1164             :         }
    1165             :     }
    1166             : 
    1167       99104 :     nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
    1168       99104 :     nb0_frames = FFMIN(nb0_frames, nb_frames);
    1169             : 
    1170       99104 :     memmove(ost->last_nb0_frames + 1,
    1171       99104 :             ost->last_nb0_frames,
    1172             :             sizeof(ost->last_nb0_frames[0]) * (FF_ARRAY_ELEMS(ost->last_nb0_frames) - 1));
    1173       99104 :     ost->last_nb0_frames[0] = nb0_frames;
    1174             : 
    1175       99104 :     if (nb0_frames == 0 && ost->last_dropped) {
    1176         171 :         nb_frames_drop++;
    1177         342 :         av_log(NULL, AV_LOG_VERBOSE,
    1178             :                "*** dropping frame %d from stream %d at ts %"PRId64"\n",
    1179         342 :                ost->frame_number, ost->st->index, ost->last_frame->pts);
    1180             :     }
    1181       99104 :     if (nb_frames > (nb0_frames && ost->last_dropped) + (nb_frames > nb0_frames)) {
    1182          49 :         if (nb_frames > dts_error_threshold * 30) {
    1183           0 :             av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
    1184           0 :             nb_frames_drop++;
    1185           0 :             return;
    1186             :         }
    1187          49 :         nb_frames_dup += nb_frames - (nb0_frames && ost->last_dropped) - (nb_frames > nb0_frames);
    1188          49 :         av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
    1189          49 :         if (nb_frames_dup > dup_warning) {
    1190           0 :             av_log(NULL, AV_LOG_WARNING, "More than %d frames duplicated\n", dup_warning);
    1191           0 :             dup_warning *= 10;
    1192             :         }
    1193             :     }
    1194       99104 :     ost->last_dropped = nb_frames == nb0_frames && next_picture;
    1195             : 
    1196             :   /* duplicates frame if needed */
    1197      195895 :   for (i = 0; i < nb_frames; i++) {
    1198             :     AVFrame *in_picture;
    1199       96792 :     av_init_packet(&pkt);
    1200       96792 :     pkt.data = NULL;
    1201       96792 :     pkt.size = 0;
    1202             : 
    1203       96792 :     if (i < nb0_frames && ost->last_frame) {
    1204          69 :         in_picture = ost->last_frame;
    1205             :     } else
    1206       96723 :         in_picture = next_picture;
    1207             : 
    1208       96792 :     if (!in_picture)
    1209           0 :         return;
    1210             : 
    1211       96792 :     in_picture->pts = ost->sync_opts;
    1212             : 
    1213             : #if 1
    1214       96792 :     if (!check_recording_time(ost))
    1215             : #else
    1216             :     if (ost->frame_number >= ost->max_frames)
    1217             : #endif
    1218           1 :         return;
    1219             : 
    1220             :     {
    1221       96791 :         int forced_keyframe = 0;
    1222             :         double pts_time;
    1223             : 
    1224       97671 :         if (enc->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
    1225         880 :             ost->top_field_first >= 0)
    1226          25 :             in_picture->top_field_first = !!ost->top_field_first;
    1227             : 
    1228       96791 :         if (in_picture->interlaced_frame) {
    1229        6351 :             if (enc->codec->id == AV_CODEC_ID_MJPEG)
    1230           0 :                 mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
    1231             :             else
    1232        6351 :                 mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
    1233             :         } else
    1234       90440 :             mux_par->field_order = AV_FIELD_PROGRESSIVE;
    1235             : 
    1236       96791 :         in_picture->quality = enc->global_quality;
    1237       96791 :         in_picture->pict_type = 0;
    1238             : 
    1239      193582 :         pts_time = in_picture->pts != AV_NOPTS_VALUE ?
    1240       96791 :             in_picture->pts * av_q2d(enc->time_base) : NAN;
    1241       96830 :         if (ost->forced_kf_index < ost->forced_kf_count &&
    1242          39 :             in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
    1243           2 :             ost->forced_kf_index++;
    1244           2 :             forced_keyframe = 1;
    1245       96789 :         } else if (ost->forced_keyframes_pexpr) {
    1246             :             double res;
    1247           0 :             ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
    1248           0 :             res = av_expr_eval(ost->forced_keyframes_pexpr,
    1249           0 :                                ost->forced_keyframes_expr_const_values, NULL);
    1250             :             ff_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
    1251             :                     ost->forced_keyframes_expr_const_values[FKF_N],
    1252             :                     ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
    1253             :                     ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
    1254             :                     ost->forced_keyframes_expr_const_values[FKF_T],
    1255             :                     ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
    1256             :                     res);
    1257           0 :             if (res) {
    1258           0 :                 forced_keyframe = 1;
    1259           0 :                 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
    1260           0 :                     ost->forced_keyframes_expr_const_values[FKF_N];
    1261           0 :                 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
    1262           0 :                     ost->forced_keyframes_expr_const_values[FKF_T];
    1263           0 :                 ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
    1264             :             }
    1265             : 
    1266           0 :             ost->forced_keyframes_expr_const_values[FKF_N] += 1;
    1267       96789 :         } else if (   ost->forced_keyframes
    1268          48 :                    && !strncmp(ost->forced_keyframes, "source", 6)
    1269           0 :                    && in_picture->key_frame==1) {
    1270           0 :             forced_keyframe = 1;
    1271             :         }
    1272             : 
    1273       96791 :         if (forced_keyframe) {
    1274           2 :             in_picture->pict_type = AV_PICTURE_TYPE_I;
    1275           2 :             av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
    1276             :         }
    1277             : 
    1278       96791 :         update_benchmark(NULL);
    1279       96791 :         if (debug_ts) {
    1280           0 :             av_log(NULL, AV_LOG_INFO, "encoder <- type:video "
    1281             :                    "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
    1282           0 :                    av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
    1283             :                    enc->time_base.num, enc->time_base.den);
    1284             :         }
    1285             : 
    1286       96791 :         ost->frames_encoded++;
    1287             : 
    1288       96791 :         ret = avcodec_send_frame(enc, in_picture);
    1289       96791 :         if (ret < 0)
    1290           0 :             goto error;
    1291             : 
    1292             :         while (1) {
    1293      289987 :             ret = avcodec_receive_packet(enc, &pkt);
    1294      193389 :             update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
    1295      193389 :             if (ret == AVERROR(EAGAIN))
    1296       96791 :                 break;
    1297       96598 :             if (ret < 0)
    1298           0 :                 goto error;
    1299             : 
    1300       96598 :             if (debug_ts) {
    1301           0 :                 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
    1302             :                        "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
    1303           0 :                        av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
    1304           0 :                        av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
    1305             :             }
    1306             : 
    1307       96598 :             if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & AV_CODEC_CAP_DELAY))
    1308           0 :                 pkt.pts = ost->sync_opts;
    1309             : 
    1310       96598 :             av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
    1311             : 
    1312       96598 :             if (debug_ts) {
    1313           0 :                 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
    1314             :                     "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
    1315           0 :                     av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->mux_timebase),
    1316           0 :                     av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->mux_timebase));
    1317             :             }
    1318             : 
    1319       96598 :             frame_size = pkt.size;
    1320       96598 :             output_packet(of, &pkt, ost, 0);
    1321             : 
    1322             :             /* if two pass, output log */
    1323       96598 :             if (ost->logfile && enc->stats_out) {
    1324           0 :                 fprintf(ost->logfile, "%s", enc->stats_out);
    1325             :             }
    1326             :         }
    1327             :     }
    1328       96791 :     ost->sync_opts++;
    1329             :     /*
    1330             :      * For video, number of frames in == number of packets out.
    1331             :      * But there may be reordering, so we can't throw away frames on encoder
    1332             :      * flush, we need to limit them here, before they go into encoder.
    1333             :      */
    1334       96791 :     ost->frame_number++;
    1335             : 
    1336       96791 :     if (vstats_filename && frame_size)
    1337           0 :         do_video_stats(ost, frame_size);
    1338             :   }
    1339             : 
    1340       99103 :     if (!ost->last_frame)
    1341        4491 :         ost->last_frame = av_frame_alloc();
    1342       99103 :     av_frame_unref(ost->last_frame);
    1343       99103 :     if (next_picture && ost->last_frame)
    1344       96753 :         av_frame_ref(ost->last_frame, next_picture);
    1345             :     else
    1346        2350 :         av_frame_free(&ost->last_frame);
    1347             : 
    1348       99103 :     return;
    1349           0 : error:
    1350           0 :     av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
    1351           0 :     exit_program(1);
    1352             : }
    1353             : 
    1354           0 : static double psnr(double d)
    1355             : {
    1356           0 :     return -10.0 * log10(d);
    1357             : }
    1358             : 
    1359           0 : static void do_video_stats(OutputStream *ost, int frame_size)
    1360             : {
    1361             :     AVCodecContext *enc;
    1362             :     int frame_number;
    1363             :     double ti1, bitrate, avg_bitrate;
    1364             : 
    1365             :     /* this is executed just the first time do_video_stats is called */
    1366           0 :     if (!vstats_file) {
    1367           0 :         vstats_file = fopen(vstats_filename, "w");
    1368           0 :         if (!vstats_file) {
    1369           0 :             perror("fopen");
    1370           0 :             exit_program(1);
    1371             :         }
    1372             :     }
    1373             : 
    1374           0 :     enc = ost->enc_ctx;
    1375           0 :     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
    1376           0 :         frame_number = ost->st->nb_frames;
    1377           0 :         if (vstats_version <= 1) {
    1378           0 :             fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
    1379           0 :                     ost->quality / (float)FF_QP2LAMBDA);
    1380             :         } else  {
    1381           0 :             fprintf(vstats_file, "out= %2d st= %2d frame= %5d q= %2.1f ", ost->file_index, ost->index, frame_number,
    1382           0 :                     ost->quality / (float)FF_QP2LAMBDA);
    1383             :         }
    1384             : 
    1385           0 :         if (ost->error[0]>=0 && (enc->flags & AV_CODEC_FLAG_PSNR))
    1386           0 :             fprintf(vstats_file, "PSNR= %6.2f ", psnr(ost->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
    1387             : 
    1388           0 :         fprintf(vstats_file,"f_size= %6d ", frame_size);
    1389             :         /* compute pts value */
    1390           0 :         ti1 = av_stream_get_end_pts(ost->st) * av_q2d(ost->st->time_base);
    1391           0 :         if (ti1 < 0.01)
    1392           0 :             ti1 = 0.01;
    1393             : 
    1394           0 :         bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
    1395           0 :         avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
    1396           0 :         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
    1397           0 :                (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
    1398           0 :         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(ost->pict_type));
    1399             :     }
    1400           0 : }
    1401             : 
    1402             : static int init_output_stream(OutputStream *ost, char *error, int error_len);
    1403             : 
    1404         267 : static void finish_output_stream(OutputStream *ost)
    1405             : {
    1406         267 :     OutputFile *of = output_files[ost->file_index];
    1407             :     int i;
    1408             : 
    1409         267 :     ost->finished = ENCODER_FINISHED | MUXER_FINISHED;
    1410             : 
    1411         267 :     if (of->shortest) {
    1412           0 :         for (i = 0; i < of->ctx->nb_streams; i++)
    1413           0 :             output_streams[of->ost_index + i]->finished = ENCODER_FINISHED | MUXER_FINISHED;
    1414             :     }
    1415         267 : }
    1416             : 
    1417             : /**
    1418             :  * Get and encode new output from any of the filtergraphs, without causing
    1419             :  * activity.
    1420             :  *
    1421             :  * @return  0 for success, <0 for severe errors
    1422             :  */
    1423      407676 : static int reap_filters(int flush)
    1424             : {
    1425      407676 :     AVFrame *filtered_frame = NULL;
    1426             :     int i;
    1427             : 
    1428             :     /* Reap all buffers present in the buffer sinks */
    1429      829795 :     for (i = 0; i < nb_output_streams; i++) {
    1430      422119 :         OutputStream *ost = output_streams[i];
    1431      422119 :         OutputFile    *of = output_files[ost->file_index];
    1432             :         AVFilterContext *filter;
    1433      422119 :         AVCodecContext *enc = ost->enc_ctx;
    1434      422119 :         int ret = 0;
    1435             : 
    1436      422119 :         if (!ost->filter || !ost->filter->graph->graph)
    1437       45477 :             continue;
    1438      376642 :         filter = ost->filter->filter;
    1439             : 
    1440      376642 :         if (!ost->initialized) {
    1441        5440 :             char error[1024] = "";
    1442        5440 :             ret = init_output_stream(ost, error, sizeof(error));
    1443        5440 :             if (ret < 0) {
    1444           0 :                 av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
    1445             :                        ost->file_index, ost->index, error);
    1446           0 :                 exit_program(1);
    1447             :             }
    1448             :         }
    1449             : 
    1450      376642 :         if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
    1451           0 :             return AVERROR(ENOMEM);
    1452             :         }
    1453      376642 :         filtered_frame = ost->filtered_frame;
    1454             : 
    1455      394115 :         while (1) {
    1456      770757 :             double float_pts = AV_NOPTS_VALUE; // this is identical to filtered_frame.pts but with higher precision
    1457      770757 :             ret = av_buffersink_get_frame_flags(filter, filtered_frame,
    1458             :                                                AV_BUFFERSINK_FLAG_NO_REQUEST);
    1459      770757 :             if (ret < 0) {
    1460      376642 :                 if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
    1461           0 :                     av_log(NULL, AV_LOG_WARNING,
    1462           0 :                            "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
    1463      376642 :                 } else if (flush && ret == AVERROR_EOF) {
    1464        3456 :                     if (av_buffersink_get_type(filter) == AVMEDIA_TYPE_VIDEO)
    1465        2350 :                         do_video_out(of, ost, NULL, AV_NOPTS_VALUE);
    1466             :                 }
    1467      376642 :                 break;
    1468             :             }
    1469      394115 :             if (ost->finished) {
    1470           0 :                 av_frame_unref(filtered_frame);
    1471           0 :                 continue;
    1472             :             }
    1473      394115 :             if (filtered_frame->pts != AV_NOPTS_VALUE) {
    1474      394115 :                 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
    1475      394115 :                 AVRational filter_tb = av_buffersink_get_time_base(filter);
    1476      394115 :                 AVRational tb = enc->time_base;
    1477      394115 :                 int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
    1478             : 
    1479      394115 :                 tb.den <<= extra_bits;
    1480      394115 :                 float_pts =
    1481      788230 :                     av_rescale_q(filtered_frame->pts, filter_tb, tb) -
    1482      394115 :                     av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
    1483      394115 :                 float_pts /= 1 << extra_bits;
    1484             :                 // avoid exact midoints to reduce the chance of rounding differences, this can be removed in case the fps code is changed to work with integers
    1485      394115 :                 float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
    1486             : 
    1487      394115 :                 filtered_frame->pts =
    1488      788230 :                     av_rescale_q(filtered_frame->pts, filter_tb, enc->time_base) -
    1489      394115 :                     av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
    1490             :             }
    1491             :             //if (ost->source_index >= 0)
    1492             :             //    *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
    1493             : 
    1494      394115 :             switch (av_buffersink_get_type(filter)) {
    1495       96754 :             case AVMEDIA_TYPE_VIDEO:
    1496       96754 :                 if (!ost->frame_aspect_ratio.num)
    1497       96754 :                     enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
    1498             : 
    1499       96754 :                 if (debug_ts) {
    1500           0 :                     av_log(NULL, AV_LOG_INFO, "filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
    1501           0 :                             av_ts2str(filtered_frame->pts), av_ts2timestr(filtered_frame->pts, &enc->time_base),
    1502             :                             float_pts,
    1503             :                             enc->time_base.num, enc->time_base.den);
    1504             :                 }
    1505             : 
    1506       96754 :                 do_video_out(of, ost, filtered_frame, float_pts);
    1507       96754 :                 break;
    1508      297361 :             case AVMEDIA_TYPE_AUDIO:
    1509      594722 :                 if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&
    1510      297361 :                     enc->channels != filtered_frame->channels) {
    1511           0 :                     av_log(NULL, AV_LOG_ERROR,
    1512             :                            "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
    1513           0 :                     break;
    1514             :                 }
    1515      297361 :                 do_audio_out(of, ost, filtered_frame);
    1516      297361 :                 break;
    1517           0 :             default:
    1518             :                 // TODO support subtitle filters
    1519           0 :                 av_assert0(0);
    1520             :             }
    1521             : 
    1522      394115 :             av_frame_unref(filtered_frame);
    1523             :         }
    1524             :     }
    1525             : 
    1526      407676 :     return 0;
    1527             : }
    1528             : 
    1529        5617 : static void print_final_stats(int64_t total_size)
    1530             : {
    1531        5617 :     uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
    1532        5617 :     uint64_t subtitle_size = 0;
    1533        5617 :     uint64_t data_size = 0;
    1534        5617 :     float percent = -1.0;
    1535             :     int i, j;
    1536        5617 :     int pass1_used = 1;
    1537             : 
    1538       11373 :     for (i = 0; i < nb_output_streams; i++) {
    1539        5756 :         OutputStream *ost = output_streams[i];
    1540        5756 :         switch (ost->enc_ctx->codec_type) {
    1541        4546 :             case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
    1542        1163 :             case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
    1543          36 :             case AVMEDIA_TYPE_SUBTITLE: subtitle_size += ost->data_size; break;
    1544          11 :             default:                 other_size += ost->data_size; break;
    1545             :         }
    1546        5756 :         extra_size += ost->enc_ctx->extradata_size;
    1547        5756 :         data_size  += ost->data_size;
    1548        5756 :         if (   (ost->enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
    1549             :             != AV_CODEC_FLAG_PASS1)
    1550        5756 :             pass1_used = 0;
    1551             :     }
    1552             : 
    1553        5617 :     if (data_size && total_size>0 && total_size >= data_size)
    1554        3851 :         percent = 100.0 * (total_size - data_size) / data_size;
    1555             : 
    1556        5617 :     av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0fkB other streams:%1.0fkB global headers:%1.0fkB muxing overhead: ",
    1557             :            video_size / 1024.0,
    1558             :            audio_size / 1024.0,
    1559             :            subtitle_size / 1024.0,
    1560             :            other_size / 1024.0,
    1561             :            extra_size / 1024.0);
    1562        5617 :     if (percent >= 0.0)
    1563        3851 :         av_log(NULL, AV_LOG_INFO, "%f%%", percent);
    1564             :     else
    1565        1766 :         av_log(NULL, AV_LOG_INFO, "unknown");
    1566        5617 :     av_log(NULL, AV_LOG_INFO, "\n");
    1567             : 
    1568             :     /* print verbose per-stream stats */
    1569       11267 :     for (i = 0; i < nb_input_files; i++) {
    1570        5650 :         InputFile *f = input_files[i];
    1571        5650 :         uint64_t total_packets = 0, total_size = 0;
    1572             : 
    1573        5650 :         av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
    1574        5650 :                i, f->ctx->url);
    1575             : 
    1576       11608 :         for (j = 0; j < f->nb_streams; j++) {
    1577        5958 :             InputStream *ist = input_streams[f->ist_index + j];
    1578        5958 :             enum AVMediaType type = ist->dec_ctx->codec_type;
    1579             : 
    1580        5958 :             total_size    += ist->data_size;
    1581        5958 :             total_packets += ist->nb_packets;
    1582             : 
    1583        5958 :             av_log(NULL, AV_LOG_VERBOSE, "  Input stream #%d:%d (%s): ",
    1584             :                    i, j, media_type_string(type));
    1585        5958 :             av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
    1586             :                    ist->nb_packets, ist->data_size);
    1587             : 
    1588        5958 :             if (ist->decoding_needed) {
    1589        5487 :                 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
    1590             :                        ist->frames_decoded);
    1591        5487 :                 if (type == AVMEDIA_TYPE_AUDIO)
    1592        1071 :                     av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
    1593        5487 :                 av_log(NULL, AV_LOG_VERBOSE, "; ");
    1594             :             }
    1595             : 
    1596        5958 :             av_log(NULL, AV_LOG_VERBOSE, "\n");
    1597             :         }
    1598             : 
    1599        5650 :         av_log(NULL, AV_LOG_VERBOSE, "  Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
    1600             :                total_packets, total_size);
    1601             :     }
    1602             : 
    1603       11235 :     for (i = 0; i < nb_output_files; i++) {
    1604        5618 :         OutputFile *of = output_files[i];
    1605        5618 :         uint64_t total_packets = 0, total_size = 0;
    1606             : 
    1607        5618 :         av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
    1608        5618 :                i, of->ctx->url);
    1609             : 
    1610       11374 :         for (j = 0; j < of->ctx->nb_streams; j++) {
    1611        5756 :             OutputStream *ost = output_streams[of->ost_index + j];
    1612        5756 :             enum AVMediaType type = ost->enc_ctx->codec_type;
    1613             : 
    1614        5756 :             total_size    += ost->data_size;
    1615        5756 :             total_packets += ost->packets_written;
    1616             : 
    1617        5756 :             av_log(NULL, AV_LOG_VERBOSE, "  Output stream #%d:%d (%s): ",
    1618             :                    i, j, media_type_string(type));
    1619        5756 :             if (ost->encoding_needed) {
    1620        5506 :                 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
    1621             :                        ost->frames_encoded);
    1622        5506 :                 if (type == AVMEDIA_TYPE_AUDIO)
    1623        1068 :                     av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
    1624        5506 :                 av_log(NULL, AV_LOG_VERBOSE, "; ");
    1625             :             }
    1626             : 
    1627        5756 :             av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
    1628             :                    ost->packets_written, ost->data_size);
    1629             : 
    1630        5756 :             av_log(NULL, AV_LOG_VERBOSE, "\n");
    1631             :         }
    1632             : 
    1633        5618 :         av_log(NULL, AV_LOG_VERBOSE, "  Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
    1634             :                total_packets, total_size);
    1635             :     }
    1636        5617 :     if(video_size + data_size + audio_size + subtitle_size + extra_size == 0){
    1637           5 :         av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded ");
    1638           5 :         if (pass1_used) {
    1639           1 :             av_log(NULL, AV_LOG_WARNING, "\n");
    1640             :         } else {
    1641           4 :             av_log(NULL, AV_LOG_WARNING, "(check -ss / -t / -frames parameters if used)\n");
    1642             :         }
    1643             :     }
    1644        5617 : }
    1645             : 
    1646     1473893 : static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
    1647             : {
    1648             :     AVBPrint buf, buf_script;
    1649             :     OutputStream *ost;
    1650             :     AVFormatContext *oc;
    1651             :     int64_t total_size;
    1652             :     AVCodecContext *enc;
    1653             :     int frame_number, vid, i;
    1654             :     double bitrate;
    1655             :     double speed;
    1656     1473893 :     int64_t pts = INT64_MIN + 1;
    1657             :     static int64_t last_time = -1;
    1658             :     static int qp_histogram[52];
    1659             :     int hours, mins, secs, us;
    1660             :     const char *hours_sign;
    1661             :     int ret;
    1662             :     float t;
    1663             : 
    1664     1473893 :     if (!print_stats && !is_last_report && !progress_avio)
    1665     2933248 :         return;
    1666             : 
    1667        8917 :     if (!is_last_report) {
    1668        3300 :         if (last_time == -1) {
    1669          23 :             last_time = cur_time;
    1670          23 :             return;
    1671             :         }
    1672        3277 :         if ((cur_time - last_time) < 500000)
    1673        3273 :             return;
    1674           4 :         last_time = cur_time;
    1675             :     }
    1676             : 
    1677        5621 :     t = (cur_time-timer_start) / 1000000.0;
    1678             : 
    1679             : 
    1680        5621 :     oc = output_files[0]->ctx;
    1681             : 
    1682        5621 :     total_size = avio_size(oc->pb);
    1683        5621 :     if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
    1684          48 :         total_size = avio_tell(oc->pb);
    1685             : 
    1686        5621 :     vid = 0;
    1687        5621 :     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
    1688        5621 :     av_bprint_init(&buf_script, 0, 1);
    1689       11381 :     for (i = 0; i < nb_output_streams; i++) {
    1690        5760 :         float q = -1;
    1691        5760 :         ost = output_streams[i];
    1692        5760 :         enc = ost->enc_ctx;
    1693        5760 :         if (!ost->stream_copy)
    1694        5511 :             q = ost->quality / (float) FF_QP2LAMBDA;
    1695             : 
    1696        5760 :         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
    1697           7 :             av_bprintf(&buf, "q=%2.1f ", q);
    1698           7 :             av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
    1699             :                        ost->file_index, ost->index, q);
    1700             :         }
    1701        5760 :         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
    1702             :             float fps;
    1703             : 
    1704        4540 :             frame_number = ost->frame_number;
    1705        4540 :             fps = t > 1 ? frame_number / t : 0;
    1706        4540 :             av_bprintf(&buf, "frame=%5d fps=%3.*f q=%3.1f ",
    1707             :                      frame_number, fps < 9.95, fps, q);
    1708        4540 :             av_bprintf(&buf_script, "frame=%d\n", frame_number);
    1709        4540 :             av_bprintf(&buf_script, "fps=%.2f\n", fps);
    1710        4540 :             av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
    1711             :                        ost->file_index, ost->index, q);
    1712        4540 :             if (is_last_report)
    1713        4539 :                 av_bprintf(&buf, "L");
    1714        4540 :             if (qp_hist) {
    1715             :                 int j;
    1716           0 :                 int qp = lrintf(q);
    1717           0 :                 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
    1718           0 :                     qp_histogram[qp]++;
    1719           0 :                 for (j = 0; j < 32; j++)
    1720           0 :                     av_bprintf(&buf, "%X", av_log2(qp_histogram[j] + 1));
    1721             :             }
    1722             : 
    1723        4540 :             if ((enc->flags & AV_CODEC_FLAG_PSNR) && (ost->pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {
    1724             :                 int j;
    1725           0 :                 double error, error_sum = 0;
    1726           0 :                 double scale, scale_sum = 0;
    1727             :                 double p;
    1728           0 :                 char type[3] = { 'Y','U','V' };
    1729           0 :                 av_bprintf(&buf, "PSNR=");
    1730           0 :                 for (j = 0; j < 3; j++) {
    1731           0 :                     if (is_last_report) {
    1732           0 :                         error = enc->error[j];
    1733           0 :                         scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
    1734             :                     } else {
    1735           0 :                         error = ost->error[j];
    1736           0 :                         scale = enc->width * enc->height * 255.0 * 255.0;
    1737             :                     }
    1738           0 :                     if (j)
    1739           0 :                         scale /= 4;
    1740           0 :                     error_sum += error;
    1741           0 :                     scale_sum += scale;
    1742           0 :                     p = psnr(error / scale);
    1743           0 :                     av_bprintf(&buf, "%c:%2.2f ", type[j], p);
    1744           0 :                     av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
    1745           0 :                                ost->file_index, ost->index, type[j] | 32, p);
    1746             :                 }
    1747           0 :                 p = psnr(error_sum / scale_sum);
    1748           0 :                 av_bprintf(&buf, "*:%2.2f ", psnr(error_sum / scale_sum));
    1749           0 :                 av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
    1750             :                            ost->file_index, ost->index, p);
    1751             :             }
    1752        4540 :             vid = 1;
    1753             :         }
    1754             :         /* compute min output value */
    1755        5760 :         if (av_stream_get_end_pts(ost->st) != AV_NOPTS_VALUE)
    1756        5760 :             pts = FFMAX(pts, av_rescale_q(av_stream_get_end_pts(ost->st),
    1757             :                                           ost->st->time_base, AV_TIME_BASE_Q));
    1758        5760 :         if (is_last_report)
    1759        5756 :             nb_frames_drop += ost->last_dropped;
    1760             :     }
    1761             : 
    1762        5621 :     secs = FFABS(pts) / AV_TIME_BASE;
    1763        5621 :     us = FFABS(pts) % AV_TIME_BASE;
    1764        5621 :     mins = secs / 60;
    1765        5621 :     secs %= 60;
    1766        5621 :     hours = mins / 60;
    1767        5621 :     mins %= 60;
    1768        5621 :     hours_sign = (pts < 0) ? "-" : "";
    1769             : 
    1770        5621 :     bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
    1771        5621 :     speed = t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
    1772             : 
    1773        5621 :     if (total_size < 0) av_bprintf(&buf, "size=N/A time=");
    1774        5573 :     else                av_bprintf(&buf, "size=%8.0fkB time=", total_size / 1024.0);
    1775        5621 :     if (pts == AV_NOPTS_VALUE) {
    1776           0 :         av_bprintf(&buf, "N/A ");
    1777             :     } else {
    1778        5621 :         av_bprintf(&buf, "%s%02d:%02d:%02d.%02d ",
    1779        5621 :                    hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
    1780             :     }
    1781             : 
    1782        5621 :     if (bitrate < 0) {
    1783          59 :         av_bprintf(&buf, "bitrate=N/A");
    1784          59 :         av_bprintf(&buf_script, "bitrate=N/A\n");
    1785             :     }else{
    1786        5562 :         av_bprintf(&buf, "bitrate=%6.1fkbits/s", bitrate);
    1787        5562 :         av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
    1788             :     }
    1789             : 
    1790        5621 :     if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
    1791        5573 :     else                av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
    1792        5621 :     if (pts == AV_NOPTS_VALUE) {
    1793           0 :         av_bprintf(&buf_script, "out_time_ms=N/A\n");
    1794           0 :         av_bprintf(&buf_script, "out_time=N/A\n");
    1795             :     } else {
    1796        5621 :         av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
    1797        5621 :         av_bprintf(&buf_script, "out_time=%s%02d:%02d:%02d.%06d\n",
    1798             :                    hours_sign, hours, mins, secs, us);
    1799             :     }
    1800             : 
    1801        5621 :     if (nb_frames_dup || nb_frames_drop)
    1802          27 :         av_bprintf(&buf, " dup=%d drop=%d", nb_frames_dup, nb_frames_drop);
    1803        5621 :     av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
    1804        5621 :     av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
    1805             : 
    1806        5621 :     if (speed < 0) {
    1807           1 :         av_bprintf(&buf, " speed=N/A");
    1808           1 :         av_bprintf(&buf_script, "speed=N/A\n");
    1809             :     } else {
    1810        5620 :         av_bprintf(&buf, " speed=%4.3gx", speed);
    1811        5620 :         av_bprintf(&buf_script, "speed=%4.3gx\n", speed);
    1812             :     }
    1813             : 
    1814        5621 :     if (print_stats || is_last_report) {
    1815        5621 :         const char end = is_last_report ? '\n' : '\r';
    1816        5621 :         if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
    1817           0 :             fprintf(stderr, "%s    %c", buf.str, end);
    1818             :         } else
    1819        5621 :             av_log(NULL, AV_LOG_INFO, "%s    %c", buf.str, end);
    1820             : 
    1821        5621 :     fflush(stderr);
    1822             :     }
    1823        5621 :     av_bprint_finalize(&buf, NULL);
    1824             : 
    1825        5621 :     if (progress_avio) {
    1826           0 :         av_bprintf(&buf_script, "progress=%s\n",
    1827             :                    is_last_report ? "end" : "continue");
    1828           0 :         avio_write(progress_avio, buf_script.str,
    1829           0 :                    FFMIN(buf_script.len, buf_script.size - 1));
    1830           0 :         avio_flush(progress_avio);
    1831           0 :         av_bprint_finalize(&buf_script, NULL);
    1832           0 :         if (is_last_report) {
    1833           0 :             if ((ret = avio_closep(&progress_avio)) < 0)
    1834           0 :                 av_log(NULL, AV_LOG_ERROR,
    1835           0 :                        "Error closing progress log, loss of information possible: %s\n", av_err2str(ret));
    1836             :         }
    1837             :     }
    1838             : 
    1839        5621 :     if (is_last_report)
    1840        5617 :         print_final_stats(total_size);
    1841             : }
    1842             : 
    1843           0 : static void ifilter_parameters_from_codecpar(InputFilter *ifilter, AVCodecParameters *par)
    1844             : {
    1845             :     // We never got any input. Set a fake format, which will
    1846             :     // come from libavformat.
    1847           0 :     ifilter->format                 = par->format;
    1848           0 :     ifilter->sample_rate            = par->sample_rate;
    1849           0 :     ifilter->channels               = par->channels;
    1850           0 :     ifilter->channel_layout         = par->channel_layout;
    1851           0 :     ifilter->width                  = par->width;
    1852           0 :     ifilter->height                 = par->height;
    1853           0 :     ifilter->sample_aspect_ratio    = par->sample_aspect_ratio;
    1854           0 : }
    1855             : 
    1856        5617 : static void flush_encoders(void)
    1857             : {
    1858             :     int i, ret;
    1859             : 
    1860       11373 :     for (i = 0; i < nb_output_streams; i++) {
    1861        5756 :         OutputStream   *ost = output_streams[i];
    1862        5756 :         AVCodecContext *enc = ost->enc_ctx;
    1863        5756 :         OutputFile      *of = output_files[ost->file_index];
    1864             : 
    1865        5756 :         if (!ost->encoding_needed)
    1866         250 :             continue;
    1867             : 
    1868             :         // Try to enable encoding with no input frames.
    1869             :         // Maybe we should just let encoding fail instead.
    1870        5506 :         if (!ost->initialized) {
    1871           0 :             FilterGraph *fg = ost->filter->graph;
    1872           0 :             char error[1024] = "";
    1873             : 
    1874           0 :             av_log(NULL, AV_LOG_WARNING,
    1875             :                    "Finishing stream %d:%d without any data written to it.\n",
    1876           0 :                    ost->file_index, ost->st->index);
    1877             : 
    1878           0 :             if (ost->filter && !fg->graph) {
    1879             :                 int x;
    1880           0 :                 for (x = 0; x < fg->nb_inputs; x++) {
    1881           0 :                     InputFilter *ifilter = fg->inputs[x];
    1882           0 :                     if (ifilter->format < 0)
    1883           0 :                         ifilter_parameters_from_codecpar(ifilter, ifilter->ist->st->codecpar);
    1884             :                 }
    1885             : 
    1886           0 :                 if (!ifilter_has_all_input_formats(fg))
    1887           0 :                     continue;
    1888             : 
    1889           0 :                 ret = configure_filtergraph(fg);
    1890           0 :                 if (ret < 0) {
    1891           0 :                     av_log(NULL, AV_LOG_ERROR, "Error configuring filter graph\n");
    1892           0 :                     exit_program(1);
    1893             :                 }
    1894             : 
    1895           0 :                 finish_output_stream(ost);
    1896             :             }
    1897             : 
    1898           0 :             ret = init_output_stream(ost, error, sizeof(error));
    1899           0 :             if (ret < 0) {
    1900           0 :                 av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
    1901             :                        ost->file_index, ost->index, error);
    1902           0 :                 exit_program(1);
    1903             :             }
    1904             :         }
    1905             : 
    1906        5506 :         if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
    1907         983 :             continue;
    1908             : 
    1909        4523 :         if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
    1910          30 :             continue;
    1911             : 
    1912         230 :         for (;;) {
    1913        4723 :             const char *desc = NULL;
    1914             :             AVPacket pkt;
    1915             :             int pkt_size;
    1916             : 
    1917        4723 :             switch (enc->codec_type) {
    1918         122 :             case AVMEDIA_TYPE_AUDIO:
    1919         122 :                 desc   = "audio";
    1920         122 :                 break;
    1921        4601 :             case AVMEDIA_TYPE_VIDEO:
    1922        4601 :                 desc   = "video";
    1923        4601 :                 break;
    1924           0 :             default:
    1925           0 :                 av_assert0(0);
    1926             :             }
    1927             : 
    1928        4723 :                 av_init_packet(&pkt);
    1929        4723 :                 pkt.data = NULL;
    1930        4723 :                 pkt.size = 0;
    1931             : 
    1932        4723 :                 update_benchmark(NULL);
    1933             : 
    1934        4723 :                 while ((ret = avcodec_receive_packet(enc, &pkt)) == AVERROR(EAGAIN)) {
    1935        4493 :                     ret = avcodec_send_frame(enc, NULL);
    1936        4493 :                     if (ret < 0) {
    1937           0 :                         av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
    1938             :                                desc,
    1939           0 :                                av_err2str(ret));
    1940           0 :                         exit_program(1);
    1941             :                     }
    1942             :                 }
    1943             : 
    1944        4723 :                 update_benchmark("flush_%s %d.%d", desc, ost->file_index, ost->index);
    1945        4723 :                 if (ret < 0 && ret != AVERROR_EOF) {
    1946           0 :                     av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
    1947             :                            desc,
    1948           0 :                            av_err2str(ret));
    1949           0 :                     exit_program(1);
    1950             :                 }
    1951        4723 :                 if (ost->logfile && enc->stats_out) {
    1952           0 :                     fprintf(ost->logfile, "%s", enc->stats_out);
    1953             :                 }
    1954        4723 :                 if (ret == AVERROR_EOF) {
    1955        4493 :                     output_packet(of, &pkt, ost, 1);
    1956        4493 :                     break;
    1957             :                 }
    1958         230 :                 if (ost->finished & MUXER_FINISHED) {
    1959           0 :                     av_packet_unref(&pkt);
    1960           0 :                     continue;
    1961             :                 }
    1962         230 :                 av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
    1963         230 :                 pkt_size = pkt.size;
    1964         230 :                 output_packet(of, &pkt, ost, 0);
    1965         230 :                 if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
    1966           0 :                     do_video_stats(ost, pkt_size);
    1967             :                 }
    1968             :         }
    1969             :     }
    1970        5617 : }
    1971             : 
    1972             : /*
    1973             :  * Check whether a packet from ist should be written into ost at this time
    1974             :  */
    1975      409950 : static int check_output_constraints(InputStream *ist, OutputStream *ost)
    1976             : {
    1977      409950 :     OutputFile *of = output_files[ost->file_index];
    1978      409950 :     int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
    1979             : 
    1980      409950 :     if (ost->source_index != ist_index)
    1981       16943 :         return 0;
    1982             : 
    1983      393007 :     if (ost->finished)
    1984        2674 :         return 0;
    1985             : 
    1986      390333 :     if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
    1987           0 :         return 0;
    1988             : 
    1989      390333 :     return 1;
    1990             : }
    1991             : 
    1992       29183 : static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
    1993             : {
    1994       29183 :     OutputFile *of = output_files[ost->file_index];
    1995       29183 :     InputFile   *f = input_files [ist->file_index];
    1996       29183 :     int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
    1997       29183 :     int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->mux_timebase);
    1998       29183 :     AVPacket opkt = { 0 };
    1999             : 
    2000       29183 :     av_init_packet(&opkt);
    2001             : 
    2002             :     // EOF: flush output bitstream filters.
    2003       29183 :     if (!pkt) {
    2004           0 :         output_packet(of, &opkt, ost, 1);
    2005           0 :         return;
    2006             :     }
    2007             : 
    2008       29194 :     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
    2009          11 :         !ost->copy_initial_nonkeyframes)
    2010          11 :         return;
    2011             : 
    2012       29172 :     if (!ost->frame_number && !ost->copy_prior_start) {
    2013           0 :         int64_t comp_start = start_time;
    2014           0 :         if (copy_ts && f->start_time != AV_NOPTS_VALUE)
    2015           0 :             comp_start = FFMAX(start_time, f->start_time + f->ts_offset);
    2016           0 :         if (pkt->pts == AV_NOPTS_VALUE ?
    2017           0 :             ist->pts < comp_start :
    2018           0 :             pkt->pts < av_rescale_q(comp_start, AV_TIME_BASE_Q, ist->st->time_base))
    2019           0 :             return;
    2020             :     }
    2021             : 
    2022       29588 :     if (of->recording_time != INT64_MAX &&
    2023         416 :         ist->pts >= of->recording_time + start_time) {
    2024           5 :         close_output_stream(ost);
    2025           5 :         return;
    2026             :     }
    2027             : 
    2028       29167 :     if (f->recording_time != INT64_MAX) {
    2029         148 :         start_time = f->ctx->start_time;
    2030         148 :         if (f->start_time != AV_NOPTS_VALUE && copy_ts)
    2031          74 :             start_time += f->start_time;
    2032         148 :         if (ist->pts >= f->recording_time + start_time) {
    2033           2 :             close_output_stream(ost);
    2034           2 :             return;
    2035             :         }
    2036             :     }
    2037             : 
    2038             :     /* force the input stream PTS */
    2039       29165 :     if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
    2040        8482 :         ost->sync_opts++;
    2041             : 
    2042       29165 :     if (pkt->pts != AV_NOPTS_VALUE)
    2043       24194 :         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->mux_timebase) - ost_tb_start_time;
    2044             :     else
    2045        4971 :         opkt.pts = AV_NOPTS_VALUE;
    2046             : 
    2047       29165 :     if (pkt->dts == AV_NOPTS_VALUE)
    2048        4719 :         opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->mux_timebase);
    2049             :     else
    2050       24446 :         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->mux_timebase);
    2051       29165 :     opkt.dts -= ost_tb_start_time;
    2052             : 
    2053       29165 :     if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
    2054       20153 :         int duration = av_get_audio_frame_duration(ist->dec_ctx, pkt->size);
    2055       20153 :         if(!duration)
    2056        7408 :             duration = ist->dec_ctx->frame_size;
    2057       60459 :         opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
    2058       20153 :                                                (AVRational){1, ist->dec_ctx->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
    2059       20153 :                                                ost->mux_timebase) - ost_tb_start_time;
    2060             :     }
    2061             : 
    2062       29165 :     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->mux_timebase);
    2063             : 
    2064       29165 :     opkt.flags    = pkt->flags;
    2065             : 
    2066       29165 :     if (pkt->buf) {
    2067       29165 :         opkt.buf = av_buffer_ref(pkt->buf);
    2068       29165 :         if (!opkt.buf)
    2069           0 :             exit_program(1);
    2070             :     }
    2071       29165 :     opkt.data = pkt->data;
    2072       29165 :     opkt.size = pkt->size;
    2073             : 
    2074       29165 :     av_copy_packet_side_data(&opkt, pkt);
    2075             : 
    2076       29165 :     output_packet(of, &opkt, ost, 0);
    2077             : }
    2078             : 
    2079        1300 : int guess_input_channel_layout(InputStream *ist)
    2080             : {
    2081        1300 :     AVCodecContext *dec = ist->dec_ctx;
    2082             : 
    2083        1300 :     if (!dec->channel_layout) {
    2084             :         char layout_name[256];
    2085             : 
    2086         732 :         if (dec->channels > ist->guess_layout_max)
    2087           6 :             return 0;
    2088         729 :         dec->channel_layout = av_get_default_channel_layout(dec->channels);
    2089         729 :         if (!dec->channel_layout)
    2090           0 :             return 0;
    2091         729 :         av_get_channel_layout_string(layout_name, sizeof(layout_name),
    2092             :                                      dec->channels, dec->channel_layout);
    2093         729 :         av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
    2094         729 :                "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
    2095             :     }
    2096        1297 :     return 1;
    2097             : }
    2098             : 
    2099      738737 : static void check_decode_result(InputStream *ist, int *got_output, int ret)
    2100             : {
    2101      738737 :     if (*got_output || ret<0)
    2102      381295 :         decode_error_stat[ret<0] ++;
    2103             : 
    2104      738737 :     if (ret < 0 && exit_on_error)
    2105           0 :         exit_program(1);
    2106             : 
    2107      738737 :     if (exit_on_error && *got_output && ist) {
    2108           0 :         if (ist->decoded_frame->decode_error_flags || (ist->decoded_frame->flags & AV_FRAME_FLAG_CORRUPT)) {
    2109           0 :             av_log(NULL, AV_LOG_FATAL, "%s: corrupt decoded frame in stream %d\n", input_files[ist->file_index]->ctx->url, ist->st->index);
    2110           0 :             exit_program(1);
    2111             :         }
    2112             :     }
    2113      738737 : }
    2114             : 
    2115             : // Filters can be configured only if the formats of all inputs are known.
    2116     1076969 : static int ifilter_has_all_input_formats(FilterGraph *fg)
    2117             : {
    2118             :     int i;
    2119     1110941 :     for (i = 0; i < fg->nb_inputs; i++) {
    2120     2176825 :         if (fg->inputs[i]->format < 0 && (fg->inputs[i]->type == AVMEDIA_TYPE_AUDIO ||
    2121     1071416 :                                           fg->inputs[i]->type == AVMEDIA_TYPE_VIDEO))
    2122     1071437 :             return 0;
    2123             :     }
    2124        5532 :     return 1;
    2125             : }
    2126             : 
    2127      380624 : static int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame)
    2128             : {
    2129      380624 :     FilterGraph *fg = ifilter->graph;
    2130             :     int need_reinit, ret, i;
    2131             : 
    2132             :     /* determine if the parameters for this input changed */
    2133      380624 :     need_reinit = ifilter->format != frame->format;
    2134      761248 :     if (!!ifilter->hw_frames_ctx != !!frame->hw_frames_ctx ||
    2135      380624 :         (ifilter->hw_frames_ctx && ifilter->hw_frames_ctx->data != frame->hw_frames_ctx->data))
    2136           0 :         need_reinit = 1;
    2137             : 
    2138      380624 :     switch (ifilter->ist->st->codecpar->codec_type) {
    2139      284003 :     case AVMEDIA_TYPE_AUDIO:
    2140      850937 :         need_reinit |= ifilter->sample_rate    != frame->sample_rate ||
    2141      566933 :                        ifilter->channels       != frame->channels ||
    2142      282930 :                        ifilter->channel_layout != frame->channel_layout;
    2143      284003 :         break;
    2144       96621 :     case AVMEDIA_TYPE_VIDEO:
    2145      188834 :         need_reinit |= ifilter->width  != frame->width ||
    2146       92213 :                        ifilter->height != frame->height;
    2147       96621 :         break;
    2148             :     }
    2149             : 
    2150      380624 :     if (need_reinit) {
    2151        5494 :         ret = ifilter_parameters_from_frame(ifilter, frame);
    2152        5494 :         if (ret < 0)
    2153           0 :             return ret;
    2154             :     }
    2155             : 
    2156             :     /* (re)init the graph if possible, otherwise buffer the frame and return */
    2157      380624 :     if (need_reinit || !fg->graph) {
    2158       10990 :         for (i = 0; i < fg->nb_inputs; i++) {
    2159        5515 :             if (!ifilter_has_all_input_formats(fg)) {
    2160          19 :                 AVFrame *tmp = av_frame_clone(frame);
    2161          19 :                 if (!tmp)
    2162           0 :                     return AVERROR(ENOMEM);
    2163          19 :                 av_frame_unref(frame);
    2164             : 
    2165          19 :                 if (!av_fifo_space(ifilter->frame_queue)) {
    2166           0 :                     ret = av_fifo_realloc2(ifilter->frame_queue, 2 * av_fifo_size(ifilter->frame_queue));
    2167           0 :                     if (ret < 0) {
    2168           0 :                         av_frame_free(&tmp);
    2169           0 :                         return ret;
    2170             :                     }
    2171             :                 }
    2172          19 :                 av_fifo_generic_write(ifilter->frame_queue, &tmp, sizeof(tmp), NULL);
    2173          19 :                 return 0;
    2174             :             }
    2175             :         }
    2176             : 
    2177        5475 :         ret = reap_filters(1);
    2178        5475 :         if (ret < 0 && ret != AVERROR_EOF) {
    2179           0 :             av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
    2180           0 :             return ret;
    2181             :         }
    2182             : 
    2183        5475 :         ret = configure_filtergraph(fg);
    2184        5475 :         if (ret < 0) {
    2185           0 :             av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
    2186           0 :             return ret;
    2187             :         }
    2188             :     }
    2189             : 
    2190      380605 :     ret = av_buffersrc_add_frame_flags(ifilter->filter, frame, AV_BUFFERSRC_FLAG_PUSH);
    2191      380605 :     if (ret < 0) {
    2192           0 :         if (ret != AVERROR_EOF)
    2193           0 :             av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
    2194           0 :         return ret;
    2195             :     }
    2196             : 
    2197      380605 :     return 0;
    2198             : }
    2199             : 
    2200        5448 : static int ifilter_send_eof(InputFilter *ifilter, int64_t pts)
    2201             : {
    2202             :     int ret;
    2203             : 
    2204        5448 :     ifilter->eof = 1;
    2205             : 
    2206        5448 :     if (ifilter->filter) {
    2207        5448 :         ret = av_buffersrc_close(ifilter->filter, pts, AV_BUFFERSRC_FLAG_PUSH);
    2208        5448 :         if (ret < 0)
    2209           0 :             return ret;
    2210             :     } else {
    2211             :         // the filtergraph was never configured
    2212           0 :         if (ifilter->format < 0)
    2213           0 :             ifilter_parameters_from_codecpar(ifilter, ifilter->ist->st->codecpar);
    2214           0 :         if (ifilter->format < 0 && (ifilter->type == AVMEDIA_TYPE_AUDIO || ifilter->type == AVMEDIA_TYPE_VIDEO)) {
    2215           0 :             av_log(NULL, AV_LOG_ERROR, "Cannot determine format of input stream %d:%d after EOF\n", ifilter->ist->file_index, ifilter->ist->st->index);
    2216           0 :             return AVERROR_INVALIDDATA;
    2217             :         }
    2218             :     }
    2219             : 
    2220        5448 :     return 0;
    2221             : }
    2222             : 
    2223             : // This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
    2224             : // There is the following difference: if you got a frame, you must call
    2225             : // it again with pkt=NULL. pkt==NULL is treated differently from pkt->size==0
    2226             : // (pkt==NULL means get more output, pkt->size==0 is a flush/drain packet)
    2227      743015 : static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
    2228             : {
    2229             :     int ret;
    2230             : 
    2231      743015 :     *got_frame = 0;
    2232             : 
    2233      743015 :     if (pkt) {
    2234      363455 :         ret = avcodec_send_packet(avctx, pkt);
    2235             :         // In particular, we don't expect AVERROR(EAGAIN), because we read all
    2236             :         // decoded frames with avcodec_receive_frame() until done.
    2237      363455 :         if (ret < 0 && ret != AVERROR_EOF)
    2238         379 :             return ret;
    2239             :     }
    2240             : 
    2241      742636 :     ret = avcodec_receive_frame(avctx, frame);
    2242      742636 :     if (ret < 0 && ret != AVERROR(EAGAIN))
    2243        5450 :         return ret;
    2244      737186 :     if (ret >= 0)
    2245      380236 :         *got_frame = 1;
    2246             : 
    2247      737186 :     return 0;
    2248             : }
    2249             : 
    2250      380236 : static int send_frame_to_filters(InputStream *ist, AVFrame *decoded_frame)
    2251             : {
    2252             :     int i, ret;
    2253             :     AVFrame *f;
    2254             : 
    2255             :     av_assert1(ist->nb_filters > 0); /* ensure ret is initialized */
    2256      760860 :     for (i = 0; i < ist->nb_filters; i++) {
    2257      380624 :         if (i < ist->nb_filters - 1) {
    2258         388 :             f = ist->filter_frame;
    2259         388 :             ret = av_frame_ref(f, decoded_frame);
    2260         388 :             if (ret < 0)
    2261           0 :                 break;
    2262             :         } else
    2263      380236 :             f = decoded_frame;
    2264      380624 :         ret = ifilter_send_frame(ist->filters[i], f);
    2265      380624 :         if (ret == AVERROR_EOF)
    2266           0 :             ret = 0; /* ignore */
    2267      380624 :         if (ret < 0) {
    2268           0 :             av_log(NULL, AV_LOG_ERROR,
    2269           0 :                    "Failed to inject frame into filter network: %s\n", av_err2str(ret));
    2270           0 :             break;
    2271             :         }
    2272             :     }
    2273      380236 :     return ret;
    2274             : }
    2275             : 
    2276      541525 : static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output,
    2277             :                         int *decode_failed)
    2278             : {
    2279             :     AVFrame *decoded_frame;
    2280      541525 :     AVCodecContext *avctx = ist->dec_ctx;
    2281      541525 :     int ret, err = 0;
    2282             :     AVRational decoded_frame_tb;
    2283             : 
    2284      541525 :     if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
    2285           0 :         return AVERROR(ENOMEM);
    2286      541525 :     if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
    2287           0 :         return AVERROR(ENOMEM);
    2288      541525 :     decoded_frame = ist->decoded_frame;
    2289             : 
    2290      541525 :     update_benchmark(NULL);
    2291      541525 :     ret = decode(avctx, decoded_frame, got_output, pkt);
    2292      541525 :     update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
    2293      541525 :     if (ret < 0)
    2294        1080 :         *decode_failed = 1;
    2295             : 
    2296      541525 :     if (ret >= 0 && avctx->sample_rate <= 0) {
    2297           0 :         av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
    2298           0 :         ret = AVERROR_INVALIDDATA;
    2299             :     }
    2300             : 
    2301      541525 :     if (ret != AVERROR_EOF)
    2302      540455 :         check_decode_result(ist, got_output, ret);
    2303             : 
    2304      541525 :     if (!*got_output || ret < 0)
    2305      257910 :         return ret;
    2306             : 
    2307      283615 :     ist->samples_decoded += decoded_frame->nb_samples;
    2308      283615 :     ist->frames_decoded++;
    2309             : 
    2310             : #if 1
    2311             :     /* increment next_dts to use for the case where the input stream does not
    2312             :        have timestamps or there are multiple frames in the packet */
    2313      567230 :     ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
    2314      283615 :                      avctx->sample_rate;
    2315      567230 :     ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
    2316      283615 :                      avctx->sample_rate;
    2317             : #endif
    2318             : 
    2319      283615 :     if (decoded_frame->pts != AV_NOPTS_VALUE) {
    2320      255711 :         decoded_frame_tb   = ist->st->time_base;
    2321       27904 :     } else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
    2322           3 :         decoded_frame->pts = pkt->pts;
    2323           3 :         decoded_frame_tb   = ist->st->time_base;
    2324             :     }else {
    2325       27901 :         decoded_frame->pts = ist->dts;
    2326       27901 :         decoded_frame_tb   = AV_TIME_BASE_Q;
    2327             :     }
    2328      283615 :     if (decoded_frame->pts != AV_NOPTS_VALUE)
    2329      567230 :         decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
    2330      283615 :                                               (AVRational){1, avctx->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
    2331      283615 :                                               (AVRational){1, avctx->sample_rate});
    2332      283615 :     ist->nb_samples = decoded_frame->nb_samples;
    2333      283615 :     err = send_frame_to_filters(ist, decoded_frame);
    2334             : 
    2335      283615 :     av_frame_unref(ist->filter_frame);
    2336      283615 :     av_frame_unref(decoded_frame);
    2337      283615 :     return err < 0 ? err : ret;
    2338             : }
    2339             : 
    2340      203035 : static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *duration_pts, int eof,
    2341             :                         int *decode_failed)
    2342             : {
    2343             :     AVFrame *decoded_frame;
    2344      203035 :     int i, ret = 0, err = 0;
    2345             :     int64_t best_effort_timestamp;
    2346      203035 :     int64_t dts = AV_NOPTS_VALUE;
    2347             :     AVPacket avpkt;
    2348             : 
    2349             :     // With fate-indeo3-2, we're getting 0-sized packets before EOF for some
    2350             :     // reason. This seems like a semi-critical bug. Don't trigger EOF, and
    2351             :     // skip the packet.
    2352      203035 :     if (!eof && pkt && pkt->size == 0)
    2353        1545 :         return 0;
    2354             : 
    2355      201490 :     if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
    2356           0 :         return AVERROR(ENOMEM);
    2357      201490 :     if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
    2358           0 :         return AVERROR(ENOMEM);
    2359      201490 :     decoded_frame = ist->decoded_frame;
    2360      201490 :     if (ist->dts != AV_NOPTS_VALUE)
    2361      201079 :         dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
    2362      201490 :     if (pkt) {
    2363      105517 :         avpkt = *pkt;
    2364      105517 :         avpkt.dts = dts; // ffmpeg.c probably shouldn't do this
    2365             :     }
    2366             : 
    2367             :     // The old code used to set dts on the drain packet, which does not work
    2368             :     // with the new API anymore.
    2369      201490 :     if (eof) {
    2370        5023 :         void *new = av_realloc_array(ist->dts_buffer, ist->nb_dts_buffer + 1, sizeof(ist->dts_buffer[0]));
    2371        5023 :         if (!new)
    2372           0 :             return AVERROR(ENOMEM);
    2373        5023 :         ist->dts_buffer = new;
    2374        5023 :         ist->dts_buffer[ist->nb_dts_buffer++] = dts;
    2375             :     }
    2376             : 
    2377      201490 :     update_benchmark(NULL);
    2378      201490 :     ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt ? &avpkt : NULL);
    2379      201490 :     update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
    2380      201490 :     if (ret < 0)
    2381        4749 :         *decode_failed = 1;
    2382             : 
    2383             :     // The following line may be required in some cases where there is no parser
    2384             :     // or the parser does not has_b_frames correctly
    2385      201490 :     if (ist->st->codecpar->video_delay < ist->dec_ctx->has_b_frames) {
    2386           2 :         if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
    2387           2 :             ist->st->codecpar->video_delay = ist->dec_ctx->has_b_frames;
    2388             :         } else
    2389           0 :             av_log(ist->dec_ctx, AV_LOG_WARNING,
    2390             :                    "video_delay is larger in decoder than demuxer %d > %d.\n"
    2391             :                    "If you want to help, upload a sample "
    2392             :                    "of this file to ftp://upload.ffmpeg.org/incoming/ "
    2393             :                    "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n",
    2394           0 :                    ist->dec_ctx->has_b_frames,
    2395           0 :                    ist->st->codecpar->video_delay);
    2396             :     }
    2397             : 
    2398      201490 :     if (ret != AVERROR_EOF)
    2399      197115 :         check_decode_result(ist, got_output, ret);
    2400             : 
    2401      201490 :     if (*got_output && ret >= 0) {
    2402      193233 :         if (ist->dec_ctx->width  != decoded_frame->width ||
    2403      193222 :             ist->dec_ctx->height != decoded_frame->height ||
    2404       96610 :             ist->dec_ctx->pix_fmt != decoded_frame->format) {
    2405          30 :             av_log(NULL, AV_LOG_DEBUG, "Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
    2406             :                 decoded_frame->width,
    2407             :                 decoded_frame->height,
    2408             :                 decoded_frame->format,
    2409          15 :                 ist->dec_ctx->width,
    2410          15 :                 ist->dec_ctx->height,
    2411          15 :                 ist->dec_ctx->pix_fmt);
    2412             :         }
    2413             :     }
    2414             : 
    2415      201490 :     if (!*got_output || ret < 0)
    2416      104869 :         return ret;
    2417             : 
    2418       96621 :     if(ist->top_field_first>=0)
    2419           0 :         decoded_frame->top_field_first = ist->top_field_first;
    2420             : 
    2421       96621 :     ist->frames_decoded++;
    2422             : 
    2423       96621 :     if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
    2424           0 :         err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
    2425           0 :         if (err < 0)
    2426           0 :             goto fail;
    2427             :     }
    2428       96621 :     ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
    2429             : 
    2430       96621 :     best_effort_timestamp= decoded_frame->best_effort_timestamp;
    2431       96621 :     *duration_pts = decoded_frame->pkt_duration;
    2432             : 
    2433       96621 :     if (ist->framerate.num)
    2434         103 :         best_effort_timestamp = ist->cfr_next_pts++;
    2435             : 
    2436       96621 :     if (eof && best_effort_timestamp == AV_NOPTS_VALUE && ist->nb_dts_buffer > 0) {
    2437         521 :         best_effort_timestamp = ist->dts_buffer[0];
    2438             : 
    2439         521 :         for (i = 0; i < ist->nb_dts_buffer - 1; i++)
    2440           0 :             ist->dts_buffer[i] = ist->dts_buffer[i + 1];
    2441         521 :         ist->nb_dts_buffer--;
    2442             :     }
    2443             : 
    2444       96621 :     if(best_effort_timestamp != AV_NOPTS_VALUE) {
    2445       96621 :         int64_t ts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
    2446             : 
    2447       96621 :         if (ts != AV_NOPTS_VALUE)
    2448       96621 :             ist->next_pts = ist->pts = ts;
    2449             :     }
    2450             : 
    2451       96621 :     if (debug_ts) {
    2452           0 :         av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
    2453             :                "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d time_base:%d/%d\n",
    2454           0 :                ist->st->index, av_ts2str(decoded_frame->pts),
    2455           0 :                av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
    2456             :                best_effort_timestamp,
    2457           0 :                av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
    2458           0 :                decoded_frame->key_frame, decoded_frame->pict_type,
    2459           0 :                ist->st->time_base.num, ist->st->time_base.den);
    2460             :     }
    2461             : 
    2462       96621 :     if (ist->st->sample_aspect_ratio.num)
    2463        4399 :         decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
    2464             : 
    2465       96621 :     err = send_frame_to_filters(ist, decoded_frame);
    2466             : 
    2467       96621 : fail:
    2468       96621 :     av_frame_unref(ist->filter_frame);
    2469       96621 :     av_frame_unref(decoded_frame);
    2470       96621 :     return err < 0 ? err : ret;
    2471             : }
    2472             : 
    2473        1167 : static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output,
    2474             :                                int *decode_failed)
    2475             : {
    2476             :     AVSubtitle subtitle;
    2477        1167 :     int free_sub = 1;
    2478        1167 :     int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
    2479             :                                           &subtitle, got_output, pkt);
    2480             : 
    2481        1167 :     check_decode_result(NULL, got_output, ret);
    2482             : 
    2483        1167 :     if (ret < 0 || !*got_output) {
    2484         571 :         *decode_failed = 1;
    2485         571 :         if (!pkt->size)
    2486          31 :             sub2video_flush(ist);
    2487         571 :         return ret;
    2488             :     }
    2489             : 
    2490         596 :     if (ist->fix_sub_duration) {
    2491           0 :         int end = 1;
    2492           0 :         if (ist->prev_sub.got_output) {
    2493           0 :             end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
    2494             :                              1000, AV_TIME_BASE);
    2495           0 :             if (end < ist->prev_sub.subtitle.end_display_time) {
    2496           0 :                 av_log(ist->dec_ctx, AV_LOG_DEBUG,
    2497             :                        "Subtitle duration reduced from %"PRId32" to %d%s\n",
    2498             :                        ist->prev_sub.subtitle.end_display_time, end,
    2499             :                        end <= 0 ? ", dropping it" : "");
    2500           0 :                 ist->prev_sub.subtitle.end_display_time = end;
    2501             :             }
    2502             :         }
    2503           0 :         FFSWAP(int,        *got_output, ist->prev_sub.got_output);
    2504           0 :         FFSWAP(int,        ret,         ist->prev_sub.ret);
    2505           0 :         FFSWAP(AVSubtitle, subtitle,    ist->prev_sub.subtitle);
    2506           0 :         if (end <= 0)
    2507           0 :             goto out;
    2508             :     }
    2509             : 
    2510         596 :     if (!*got_output)
    2511           0 :         return ret;
    2512             : 
    2513         596 :     if (ist->sub2video.frame) {
    2514          44 :         sub2video_update(ist, &subtitle);
    2515         552 :     } else if (ist->nb_filters) {
    2516           0 :         if (!ist->sub2video.sub_queue)
    2517           0 :             ist->sub2video.sub_queue = av_fifo_alloc(8 * sizeof(AVSubtitle));
    2518           0 :         if (!ist->sub2video.sub_queue)
    2519           0 :             exit_program(1);
    2520           0 :         if (!av_fifo_space(ist->sub2video.sub_queue)) {
    2521           0 :             ret = av_fifo_realloc2(ist->sub2video.sub_queue, 2 * av_fifo_size(ist->sub2video.sub_queue));
    2522           0 :             if (ret < 0)
    2523           0 :                 exit_program(1);
    2524             :         }
    2525           0 :         av_fifo_generic_write(ist->sub2video.sub_queue, &subtitle, sizeof(subtitle), NULL);
    2526           0 :         free_sub = 0;
    2527             :     }
    2528             : 
    2529         596 :     if (!subtitle.num_rects)
    2530           0 :         goto out;
    2531             : 
    2532         596 :     ist->frames_decoded++;
    2533             : 
    2534        1236 :     for (i = 0; i < nb_output_streams; i++) {
    2535         640 :         OutputStream *ost = output_streams[i];
    2536             : 
    2537         640 :         if (!check_output_constraints(ist, ost) || !ost->encoding_needed
    2538         595 :             || ost->enc->type != AVMEDIA_TYPE_SUBTITLE)
    2539          45 :             continue;
    2540             : 
    2541         595 :         do_subtitle_out(output_files[ost->file_index], ost, &subtitle);
    2542             :     }
    2543             : 
    2544         596 : out:
    2545         596 :     if (free_sub)
    2546         596 :         avsubtitle_free(&subtitle);
    2547         596 :     return ret;
    2548             : }
    2549             : 
    2550        5476 : static int send_filter_eof(InputStream *ist)
    2551             : {
    2552             :     int i, ret;
    2553             :     /* TODO keep pts also in stream time base to avoid converting back */
    2554        5476 :     int64_t pts = av_rescale_q_rnd(ist->pts, AV_TIME_BASE_Q, ist->st->time_base,
    2555             :                                    AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
    2556             : 
    2557       10924 :     for (i = 0; i < ist->nb_filters; i++) {
    2558        5448 :         ret = ifilter_send_eof(ist->filters[i], pts);
    2559        5448 :         if (ret < 0)
    2560           0 :             return ret;
    2561             :     }
    2562        5476 :     return 0;
    2563             : }
    2564             : 
    2565             : /* pkt = NULL means EOF (needed to flush decoder buffers) */
    2566      395434 : static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
    2567             : {
    2568      395434 :     int ret = 0, i;
    2569      395434 :     int repeating = 0;
    2570      395434 :     int eof_reached = 0;
    2571             : 
    2572             :     AVPacket avpkt;
    2573      395434 :     if (!ist->saw_first_ts) {
    2574        5765 :         ist->dts = ist->st->avg_frame_rate.num ? - ist->dec_ctx->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
    2575        5765 :         ist->pts = 0;
    2576        5765 :         if (pkt && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
    2577         172 :             ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
    2578         172 :             ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
    2579             :         }
    2580        5765 :         ist->saw_first_ts = 1;
    2581             :     }
    2582             : 
    2583      395434 :     if (ist->next_dts == AV_NOPTS_VALUE)
    2584        6179 :         ist->next_dts = ist->dts;
    2585      395434 :     if (ist->next_pts == AV_NOPTS_VALUE)
    2586        5765 :         ist->next_pts = ist->pts;
    2587             : 
    2588      395434 :     if (!pkt) {
    2589             :         /* EOF handling */
    2590        6214 :         av_init_packet(&avpkt);
    2591        6214 :         avpkt.data = NULL;
    2592        6214 :         avpkt.size = 0;
    2593             :     } else {
    2594      389220 :         avpkt = *pkt;
    2595             :     }
    2596             : 
    2597      395434 :     if (pkt && pkt->dts != AV_NOPTS_VALUE) {
    2598      353568 :         ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
    2599      353568 :         if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
    2600      281382 :             ist->next_pts = ist->pts = ist->dts;
    2601             :     }
    2602             : 
    2603             :     // while we have more to decode or while the decoder did output something on EOF
    2604     1171024 :     while (ist->decoding_needed) {
    2605      746323 :         int64_t duration_dts = 0;
    2606      746323 :         int64_t duration_pts = 0;
    2607      746323 :         int got_output = 0;
    2608      746323 :         int decode_failed = 0;
    2609             : 
    2610      746323 :         ist->pts = ist->next_pts;
    2611      746323 :         ist->dts = ist->next_dts;
    2612             : 
    2613      746323 :         switch (ist->dec_ctx->codec_type) {
    2614      541525 :         case AVMEDIA_TYPE_AUDIO:
    2615      541525 :             ret = decode_audio    (ist, repeating ? NULL : &avpkt, &got_output,
    2616             :                                    &decode_failed);
    2617      541525 :             break;
    2618      203035 :         case AVMEDIA_TYPE_VIDEO:
    2619      203035 :             ret = decode_video    (ist, repeating ? NULL : &avpkt, &got_output, &duration_pts, !pkt,
    2620             :                                    &decode_failed);
    2621      203035 :             if (!repeating || !pkt || got_output) {
    2622      107062 :                 if (pkt && pkt->duration) {
    2623       99749 :                     duration_dts = av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
    2624        7313 :                 } else if(ist->dec_ctx->framerate.num != 0 && ist->dec_ctx->framerate.den != 0) {
    2625        6103 :                     int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict+1 : ist->dec_ctx->ticks_per_frame;
    2626       12206 :                     duration_dts = ((int64_t)AV_TIME_BASE *
    2627       18309 :                                     ist->dec_ctx->framerate.den * ticks) /
    2628       12206 :                                     ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
    2629             :                 }
    2630             : 
    2631      107062 :                 if(ist->dts != AV_NOPTS_VALUE && duration_dts) {
    2632      105852 :                     ist->next_dts += duration_dts;
    2633             :                 }else
    2634        1210 :                     ist->next_dts = AV_NOPTS_VALUE;
    2635             :             }
    2636             : 
    2637      203035 :             if (got_output) {
    2638       96621 :                 if (duration_pts > 0) {
    2639       94333 :                     ist->next_pts += av_rescale_q(duration_pts, ist->st->time_base, AV_TIME_BASE_Q);
    2640             :                 } else {
    2641        2288 :                     ist->next_pts += duration_dts;
    2642             :                 }
    2643             :             }
    2644      203035 :             break;
    2645        1763 :         case AVMEDIA_TYPE_SUBTITLE:
    2646        1763 :             if (repeating)
    2647         596 :                 break;
    2648        1167 :             ret = transcode_subtitles(ist, &avpkt, &got_output, &decode_failed);
    2649        1167 :             if (!pkt && ret >= 0)
    2650          31 :                 ret = AVERROR_EOF;
    2651        1167 :             break;
    2652           0 :         default:
    2653           0 :             return -1;
    2654             :         }
    2655             : 
    2656      746323 :         if (ret == AVERROR_EOF) {
    2657        5476 :             eof_reached = 1;
    2658      371643 :             break;
    2659             :         }
    2660             : 
    2661      740847 :         if (ret < 0) {
    2662         463 :             if (decode_failed) {
    2663         926 :                 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
    2664         926 :                        ist->file_index, ist->st->index, av_err2str(ret));
    2665             :             } else {
    2666           0 :                 av_log(NULL, AV_LOG_FATAL, "Error while processing the decoded "
    2667           0 :                        "data for stream #%d:%d\n", ist->file_index, ist->st->index);
    2668             :             }
    2669         463 :             if (!decode_failed || exit_on_error)
    2670           0 :                 exit_program(1);
    2671         463 :             break;
    2672             :         }
    2673             : 
    2674      740384 :         if (got_output)
    2675      380832 :             ist->got_output = 1;
    2676             : 
    2677      740384 :         if (!got_output)
    2678      359552 :             break;
    2679             : 
    2680             :         // During draining, we might get multiple output frames in this loop.
    2681             :         // ffmpeg.c does not drain the filter chain on configuration changes,
    2682             :         // which means if we send multiple frames at once to the filters, and
    2683             :         // one of those frames changes configuration, the buffered frames will
    2684             :         // be lost. This can upset certain FATE tests.
    2685             :         // Decode only 1 frame per call on EOF to appease these FATE tests.
    2686             :         // The ideal solution would be to rewrite decoding to use the new
    2687             :         // decoding API in a better way.
    2688      380832 :         if (!pkt)
    2689         676 :             break;
    2690             : 
    2691      380156 :         repeating = 1;
    2692             :     }
    2693             : 
    2694             :     /* after flushing, send an EOF on all the filter inputs attached to the stream */
    2695             :     /* except when looping we need to flush but not to send an EOF */
    2696      395434 :     if (!pkt && ist->decoding_needed && eof_reached && !no_eof) {
    2697        5476 :         int ret = send_filter_eof(ist);
    2698        5476 :         if (ret < 0) {
    2699           0 :             av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
    2700           0 :             exit_program(1);
    2701             :         }
    2702             :     }
    2703             : 
    2704             :     /* handle stream copy */
    2705      395434 :     if (!ist->decoding_needed && pkt) {
    2706       29206 :         ist->dts = ist->next_dts;
    2707       29206 :         switch (ist->dec_ctx->codec_type) {
    2708       20181 :         case AVMEDIA_TYPE_AUDIO:
    2709       40362 :             ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
    2710       20181 :                              ist->dec_ctx->sample_rate;
    2711       20181 :             break;
    2712        8495 :         case AVMEDIA_TYPE_VIDEO:
    2713        8495 :             if (ist->framerate.num) {
    2714             :                 // TODO: Remove work-around for c99-to-c89 issue 7
    2715          79 :                 AVRational time_base_q = AV_TIME_BASE_Q;
    2716          79 :                 int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
    2717          79 :                 ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
    2718        8416 :             } else if (pkt->duration) {
    2719        8018 :                 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
    2720         398 :             } else if(ist->dec_ctx->framerate.num != 0) {
    2721         275 :                 int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
    2722         825 :                 ist->next_dts += ((int64_t)AV_TIME_BASE *
    2723         825 :                                   ist->dec_ctx->framerate.den * ticks) /
    2724         550 :                                   ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
    2725             :             }
    2726        8495 :             break;
    2727             :         }
    2728       29206 :         ist->pts = ist->dts;
    2729       29206 :         ist->next_pts = ist->next_dts;
    2730             :     }
    2731      804744 :     for (i = 0; i < nb_output_streams; i++) {
    2732      409310 :         OutputStream *ost = output_streams[i];
    2733             : 
    2734      409310 :         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
    2735      380127 :             continue;
    2736             : 
    2737       29183 :         do_streamcopy(ist, ost, pkt);
    2738             :     }
    2739             : 
    2740      395434 :     return !eof_reached;
    2741             : }
    2742             : 
    2743           0 : static void print_sdp(void)
    2744             : {
    2745             :     char sdp[16384];
    2746             :     int i;
    2747             :     int j;
    2748             :     AVIOContext *sdp_pb;
    2749             :     AVFormatContext **avc;
    2750             : 
    2751           0 :     for (i = 0; i < nb_output_files; i++) {
    2752           0 :         if (!output_files[i]->header_written)
    2753           0 :             return;
    2754             :     }
    2755             : 
    2756           0 :     avc = av_malloc_array(nb_output_files, sizeof(*avc));
    2757           0 :     if (!avc)
    2758           0 :         exit_program(1);
    2759           0 :     for (i = 0, j = 0; i < nb_output_files; i++) {
    2760           0 :         if (!strcmp(output_files[i]->ctx->oformat->name, "rtp")) {
    2761           0 :             avc[j] = output_files[i]->ctx;
    2762           0 :             j++;
    2763             :         }
    2764             :     }
    2765             : 
    2766           0 :     if (!j)
    2767           0 :         goto fail;
    2768             : 
    2769           0 :     av_sdp_create(avc, j, sdp, sizeof(sdp));
    2770             : 
    2771           0 :     if (!sdp_filename) {
    2772           0 :         printf("SDP:\n%s\n", sdp);
    2773           0 :         fflush(stdout);
    2774             :     } else {
    2775           0 :         if (avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL) < 0) {
    2776           0 :             av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
    2777             :         } else {
    2778           0 :             avio_printf(sdp_pb, "SDP:\n%s", sdp);
    2779           0 :             avio_closep(&sdp_pb);
    2780           0 :             av_freep(&sdp_filename);
    2781             :         }
    2782             :     }
    2783             : 
    2784           0 : fail:
    2785           0 :     av_freep(&avc);
    2786             : }
    2787             : 
    2788         915 : static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
    2789             : {
    2790         915 :     InputStream *ist = s->opaque;
    2791             :     const enum AVPixelFormat *p;
    2792             :     int ret;
    2793             : 
    2794         915 :     for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
    2795         915 :         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
    2796         915 :         const AVCodecHWConfig  *config = NULL;
    2797             :         int i;
    2798             : 
    2799         915 :         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
    2800         915 :             break;
    2801             : 
    2802           0 :         if (ist->hwaccel_id == HWACCEL_GENERIC ||
    2803           0 :             ist->hwaccel_id == HWACCEL_AUTO) {
    2804           0 :             for (i = 0;; i++) {
    2805           0 :                 config = avcodec_get_hw_config(s->codec, i);
    2806           0 :                 if (!config)
    2807           0 :                     break;
    2808           0 :                 if (!(config->methods &
    2809             :                       AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
    2810           0 :                     continue;
    2811           0 :                 if (config->pix_fmt == *p)
    2812           0 :                     break;
    2813             :             }
    2814             :         }
    2815           0 :         if (config) {
    2816           0 :             if (config->device_type != ist->hwaccel_device_type) {
    2817             :                 // Different hwaccel offered, ignore.
    2818           0 :                 continue;
    2819             :             }
    2820             : 
    2821           0 :             ret = hwaccel_decode_init(s);
    2822           0 :             if (ret < 0) {
    2823           0 :                 if (ist->hwaccel_id == HWACCEL_GENERIC) {
    2824           0 :                     av_log(NULL, AV_LOG_FATAL,
    2825             :                            "%s hwaccel requested for input stream #%d:%d, "
    2826             :                            "but cannot be initialized.\n",
    2827             :                            av_hwdevice_get_type_name(config->device_type),
    2828           0 :                            ist->file_index, ist->st->index);
    2829           0 :                     return AV_PIX_FMT_NONE;
    2830             :                 }
    2831           0 :                 continue;
    2832             :             }
    2833             :         } else {
    2834           0 :             const HWAccel *hwaccel = NULL;
    2835             :             int i;
    2836           0 :             for (i = 0; hwaccels[i].name; i++) {
    2837           0 :                 if (hwaccels[i].pix_fmt == *p) {
    2838           0 :                     hwaccel = &hwaccels[i];
    2839           0 :                     break;
    2840             :                 }
    2841             :             }
    2842           0 :             if (!hwaccel) {
    2843             :                 // No hwaccel supporting this pixfmt.
    2844           0 :                 continue;
    2845             :             }
    2846           0 :             if (hwaccel->id != ist->hwaccel_id) {
    2847             :                 // Does not match requested hwaccel.
    2848           0 :                 continue;
    2849             :             }
    2850             : 
    2851           0 :             ret = hwaccel->init(s);
    2852           0 :             if (ret < 0) {
    2853           0 :                 av_log(NULL, AV_LOG_FATAL,
    2854             :                        "%s hwaccel requested for input stream #%d:%d, "
    2855             :                        "but cannot be initialized.\n", hwaccel->name,
    2856           0 :                        ist->file_index, ist->st->index);
    2857           0 :                 return AV_PIX_FMT_NONE;
    2858             :             }
    2859             :         }
    2860             : 
    2861           0 :         if (ist->hw_frames_ctx) {
    2862           0 :             s->hw_frames_ctx = av_buffer_ref(ist->hw_frames_ctx);
    2863           0 :             if (!s->hw_frames_ctx)
    2864           0 :                 return AV_PIX_FMT_NONE;
    2865             :         }
    2866             : 
    2867           0 :         ist->hwaccel_pix_fmt = *p;
    2868           0 :         break;
    2869             :     }
    2870             : 
    2871         915 :     return *p;
    2872             : }
    2873             : 
    2874      356006 : static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
    2875             : {
    2876      356006 :     InputStream *ist = s->opaque;
    2877             : 
    2878      356006 :     if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
    2879           0 :         return ist->hwaccel_get_buffer(s, frame, flags);
    2880             : 
    2881      356006 :     return avcodec_default_get_buffer2(s, frame, flags);
    2882             : }
    2883             : 
    2884        5958 : static int init_input_stream(int ist_index, char *error, int error_len)
    2885             : {
    2886             :     int ret;
    2887        5958 :     InputStream *ist = input_streams[ist_index];
    2888             : 
    2889        5958 :     if (ist->decoding_needed) {
    2890        5487 :         AVCodec *codec = ist->dec;
    2891        5487 :         if (!codec) {
    2892           0 :             snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
    2893           0 :                     avcodec_get_name(ist->dec_ctx->codec_id), ist->file_index, ist->st->index);
    2894           0 :             return AVERROR(EINVAL);
    2895             :         }
    2896             : 
    2897        5487 :         ist->dec_ctx->opaque                = ist;
    2898        5487 :         ist->dec_ctx->get_format            = get_format;
    2899        5487 :         ist->dec_ctx->get_buffer2           = get_buffer;
    2900        5487 :         ist->dec_ctx->thread_safe_callbacks = 1;
    2901             : 
    2902        5487 :         av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
    2903        5487 :         if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
    2904           0 :            (ist->decoding_needed & DECODING_FOR_OST)) {
    2905           0 :             av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
    2906           0 :             if (ist->decoding_needed & DECODING_FOR_FILTER)
    2907           0 :                 av_log(NULL, AV_LOG_WARNING, "Warning using DVB subtitles for filtering and output at the same time is not fully supported, also see -compute_edt [0|1]\n");
    2908             :         }
    2909             : 
    2910        5487 :         av_dict_set(&ist->decoder_opts, "sub_text_format", "ass", AV_DICT_DONT_OVERWRITE);
    2911             : 
    2912             :         /* Useful for subtitles retiming by lavf (FIXME), skipping samples in
    2913             :          * audio, and video decoders such as cuvid or mediacodec */
    2914        5487 :         ist->dec_ctx->pkt_timebase = ist->st->time_base;
    2915             : 
    2916        5487 :         if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
    2917          43 :             av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
    2918             :         /* Attached pics are sparse, therefore we would not want to delay their decoding till EOF. */
    2919        5487 :         if (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC)
    2920           1 :             av_dict_set(&ist->decoder_opts, "threads", "1", 0);
    2921             : 
    2922        5487 :         ret = hw_device_setup_for_decode(ist);
    2923        5487 :         if (ret < 0) {
    2924           0 :             snprintf(error, error_len, "Device setup failed for "
    2925             :                      "decoder on input stream #%d:%d : %s",
    2926           0 :                      ist->file_index, ist->st->index, av_err2str(ret));
    2927           0 :             return ret;
    2928             :         }
    2929             : 
    2930        5487 :         if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
    2931           0 :             if (ret == AVERROR_EXPERIMENTAL)
    2932           0 :                 abort_codec_experimental(codec, 0);
    2933             : 
    2934           0 :             snprintf(error, error_len,
    2935             :                      "Error while opening decoder for input stream "
    2936             :                      "#%d:%d : %s",
    2937           0 :                      ist->file_index, ist->st->index, av_err2str(ret));
    2938           0 :             return ret;
    2939             :         }
    2940        5487 :         assert_avoptions(ist->decoder_opts);
    2941             :     }
    2942             : 
    2943        5958 :     ist->next_pts = AV_NOPTS_VALUE;
    2944        5958 :     ist->next_dts = AV_NOPTS_VALUE;
    2945             : 
    2946        5958 :     return 0;
    2947             : }
    2948             : 
    2949       16737 : static InputStream *get_input_stream(OutputStream *ost)
    2950             : {
    2951       16737 :     if (ost->source_index >= 0)
    2952       16566 :         return input_streams[ost->source_index];
    2953         171 :     return NULL;
    2954             : }
    2955             : 
    2956           1 : static int compare_int64(const void *a, const void *b)
    2957             : {
    2958           1 :     return FFDIFFSIGN(*(const int64_t *)a, *(const int64_t *)b);
    2959             : }
    2960             : 
    2961             : /* open the muxer when all the streams are initialized */
    2962        5757 : static int check_init_output_file(OutputFile *of, int file_index)
    2963             : {
    2964             :     int ret, i;
    2965             : 
    2966       11627 :     for (i = 0; i < of->ctx->nb_streams; i++) {
    2967        6009 :         OutputStream *ost = output_streams[of->ost_index + i];
    2968        6009 :         if (!ost->initialized)
    2969         139 :             return 0;
    2970             :     }
    2971             : 
    2972        5618 :     of->ctx->interrupt_callback = int_cb;
    2973             : 
    2974        5618 :     ret = avformat_write_header(of->ctx, &of->opts);
    2975        5618 :     if (ret < 0) {
    2976           0 :         av_log(NULL, AV_LOG_ERROR,
    2977             :                "Could not write header for output file #%d "
    2978             :                "(incorrect codec parameters ?): %s\n",
    2979           0 :                file_index, av_err2str(ret));
    2980           0 :         return ret;
    2981             :     }
    2982             :     //assert_avoptions(of->opts);
    2983        5618 :     of->header_written = 1;
    2984             : 
    2985        5618 :     av_dump_format(of->ctx, file_index, of->ctx->url, 1);
    2986             : 
    2987        5618 :     if (sdp_filename || want_sdp)
    2988           0 :         print_sdp();
    2989             : 
    2990             :     /* flush the muxing queues */
    2991       11374 :     for (i = 0; i < of->ctx->nb_streams; i++) {
    2992        5756 :         OutputStream *ost = output_streams[of->ost_index + i];
    2993             : 
    2994             :         /* try to improve muxing time_base (only possible if nothing has been written yet) */
    2995        5756 :         if (!av_fifo_size(ost->muxing_queue))
    2996        5680 :             ost->mux_timebase = ost->st->time_base;
    2997             : 
    2998       11788 :         while (av_fifo_size(ost->muxing_queue)) {
    2999             :             AVPacket pkt;
    3000         276 :             av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
    3001         276 :             write_packet(of, &pkt, ost, 1);
    3002             :         }
    3003             :     }
    3004             : 
    3005        5618 :     return 0;
    3006             : }
    3007             : 
    3008        5756 : static int init_output_bsfs(OutputStream *ost)
    3009             : {
    3010             :     AVBSFContext *ctx;
    3011             :     int i, ret;
    3012             : 
    3013        5756 :     if (!ost->nb_bitstream_filters)
    3014        5690 :         return 0;
    3015             : 
    3016         132 :     for (i = 0; i < ost->nb_bitstream_filters; i++) {
    3017          66 :         ctx = ost->bsf_ctx[i];
    3018             : 
    3019         132 :         ret = avcodec_parameters_copy(ctx->par_in,
    3020          66 :                                       i ? ost->bsf_ctx[i - 1]->par_out : ost->st->codecpar);
    3021          66 :         if (ret < 0)
    3022           0 :             return ret;
    3023             : 
    3024          66 :         ctx->time_base_in = i ? ost->bsf_ctx[i - 1]->time_base_out : ost->st->time_base;
    3025             : 
    3026          66 :         ret = av_bsf_init(ctx);
    3027          66 :         if (ret < 0) {
    3028           0 :             av_log(NULL, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
    3029           0 :                    ost->bsf_ctx[i]->filter->name);
    3030           0 :             return ret;
    3031             :         }
    3032             :     }
    3033             : 
    3034          66 :     ctx = ost->bsf_ctx[ost->nb_bitstream_filters - 1];
    3035          66 :     ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
    3036          66 :     if (ret < 0)
    3037           0 :         return ret;
    3038             : 
    3039          66 :     ost->st->time_base = ctx->time_base_out;
    3040             : 
    3041          66 :     return 0;
    3042             : }
    3043             : 
    3044         249 : static int init_output_stream_streamcopy(OutputStream *ost)
    3045             : {
    3046         249 :     OutputFile *of = output_files[ost->file_index];
    3047         249 :     InputStream *ist = get_input_stream(ost);
    3048         249 :     AVCodecParameters *par_dst = ost->st->codecpar;
    3049         249 :     AVCodecParameters *par_src = ost->ref_par;
    3050             :     AVRational sar;
    3051             :     int i, ret;
    3052         249 :     uint32_t codec_tag = par_dst->codec_tag;
    3053             : 
    3054         249 :     av_assert0(ist && !ost->filter);
    3055             : 
    3056         249 :     ret = avcodec_parameters_to_context(ost->enc_ctx, ist->st->codecpar);
    3057         249 :     if (ret >= 0)
    3058         249 :         ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
    3059         249 :     if (ret < 0) {
    3060           0 :         av_log(NULL, AV_LOG_FATAL,
    3061             :                "Error setting up codec context options.\n");
    3062           0 :         return ret;
    3063             :     }
    3064         249 :     avcodec_parameters_from_context(par_src, ost->enc_ctx);
    3065             : 
    3066         249 :     if (!codec_tag) {
    3067             :         unsigned int codec_tag_tmp;
    3068         284 :         if (!of->ctx->oformat->codec_tag ||
    3069          66 :             av_codec_get_id (of->ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
    3070          25 :             !av_codec_get_tag2(of->ctx->oformat->codec_tag, par_src->codec_id, &codec_tag_tmp))
    3071         221 :             codec_tag = par_src->codec_tag;
    3072             :     }
    3073             : 
    3074         249 :     ret = avcodec_parameters_copy(par_dst, par_src);
    3075         249 :     if (ret < 0)
    3076           0 :         return ret;
    3077             : 
    3078         249 :     par_dst->codec_tag = codec_tag;
    3079             : 
    3080         249 :     if (!ost->frame_rate.num)
    3081         248 :         ost->frame_rate = ist->framerate;
    3082         249 :     ost->st->avg_frame_rate = ost->frame_rate;
    3083             : 
    3084         249 :     ret = avformat_transfer_internal_stream_timing_info(of->ctx->oformat, ost->st, ist->st, copy_tb);
    3085         249 :     if (ret < 0)
    3086           0 :         return ret;
    3087             : 
    3088             :     // copy timebase while removing common factors
    3089         249 :     if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
    3090         248 :         ost->st->time_base = av_add_q(av_stream_get_codec_timebase(ost->st), (AVRational){0, 1});
    3091             : 
    3092             :     // copy estimated duration as a hint to the muxer
    3093         249 :     if (ost->st->duration <= 0 && ist->st->duration > 0)
    3094         143 :         ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
    3095             : 
    3096             :     // copy disposition
    3097         249 :     ost->st->disposition = ist->st->disposition;
    3098             : 
    3099         249 :     if (ist->st->nb_side_data) {
    3100          22 :         for (i = 0; i < ist->st->nb_side_data; i++) {
    3101          11 :             const AVPacketSideData *sd_src = &ist->st->side_data[i];
    3102             :             uint8_t *dst_data;
    3103             : 
    3104          11 :             dst_data = av_stream_new_side_data(ost->st, sd_src->type, sd_src->size);
    3105          11 :             if (!dst_data)
    3106           0 :                 return AVERROR(ENOMEM);
    3107          11 :             memcpy(dst_data, sd_src->data, sd_src->size);
    3108             :         }
    3109             :     }
    3110             : 
    3111         249 :     if (ost->rotate_overridden) {
    3112           1 :         uint8_t *sd = av_stream_new_side_data(ost->st, AV_PKT_DATA_DISPLAYMATRIX,
    3113             :                                               sizeof(int32_t) * 9);
    3114           1 :         if (sd)
    3115           1 :             av_display_rotation_set((int32_t *)sd, -ost->rotate_override_value);
    3116             :     }
    3117             : 
    3118         249 :     switch (par_dst->codec_type) {
    3119          95 :     case AVMEDIA_TYPE_AUDIO:
    3120          95 :         if (audio_volume != 256) {
    3121           0 :             av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
    3122           0 :             exit_program(1);
    3123             :         }
    3124          95 :         if((par_dst->block_align == 1 || par_dst->block_align == 1152 || par_dst->block_align == 576) && par_dst->codec_id == AV_CODEC_ID_MP3)
    3125           0 :             par_dst->block_align= 0;
    3126          95 :         if(par_dst->codec_id == AV_CODEC_ID_AC3)
    3127           2 :             par_dst->block_align= 0;
    3128          95 :         break;
    3129         138 :     case AVMEDIA_TYPE_VIDEO:
    3130         138 :         if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
    3131           0 :             sar =
    3132             :                 av_mul_q(ost->frame_aspect_ratio,
    3133           0 :                          (AVRational){ par_dst->height, par_dst->width });
    3134           0 :             av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
    3135             :                    "with stream copy may produce invalid files\n");
    3136             :             }
    3137         138 :         else if (ist->st->sample_aspect_ratio.num)
    3138          48 :             sar = ist->st->sample_aspect_ratio;
    3139             :         else
    3140          90 :             sar = par_src->sample_aspect_ratio;
    3141         138 :         ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
    3142         138 :         ost->st->avg_frame_rate = ist->st->avg_frame_rate;
    3143         138 :         ost->st->r_frame_rate = ist->st->r_frame_rate;
    3144         138 :         break;
    3145             :     }
    3146             : 
    3147         249 :     ost->mux_timebase = ist->st->time_base;
    3148             : 
    3149         249 :     return 0;
    3150             : }
    3151             : 
    3152        5506 : static void set_encoder_id(OutputFile *of, OutputStream *ost)
    3153             : {
    3154             :     AVDictionaryEntry *e;
    3155             : 
    3156             :     uint8_t *encoder_string;
    3157             :     int encoder_string_len;
    3158        5506 :     int format_flags = 0;
    3159        5506 :     int codec_flags = ost->enc_ctx->flags;
    3160             : 
    3161        5506 :     if (av_dict_get(ost->st->metadata, "encoder",  NULL, 0))
    3162           0 :         return;
    3163             : 
    3164        5506 :     e = av_dict_get(of->opts, "fflags", NULL, 0);
    3165        5506 :     if (e) {
    3166        3144 :         const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
    3167        3144 :         if (!o)
    3168           0 :             return;
    3169        3144 :         av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
    3170             :     }
    3171        5506 :     e = av_dict_get(ost->encoder_opts, "flags", NULL, 0);
    3172        5506 :     if (e) {
    3173        3133 :         const AVOption *o = av_opt_find(ost->enc_ctx, "flags", NULL, 0, 0);
    3174        3133 :         if (!o)
    3175           0 :             return;
    3176        3133 :         av_opt_eval_flags(ost->enc_ctx, o, e->value, &codec_flags);
    3177             :     }
    3178             : 
    3179        5506 :     encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
    3180        5506 :     encoder_string     = av_mallocz(encoder_string_len);
    3181        5506 :     if (!encoder_string)
    3182           0 :         exit_program(1);
    3183             : 
    3184        5506 :     if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & AV_CODEC_FLAG_BITEXACT))
    3185         802 :         av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
    3186             :     else
    3187        4704 :         av_strlcpy(encoder_string, "Lavc ", encoder_string_len);
    3188        5506 :     av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
    3189        5506 :     av_dict_set(&ost->st->metadata, "encoder",  encoder_string,
    3190             :                 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
    3191             : }
    3192             : 
    3193           1 : static void parse_forced_key_frames(char *kf, OutputStream *ost,
    3194             :                                     AVCodecContext *avctx)
    3195             : {
    3196             :     char *p;
    3197           1 :     int n = 1, i, size, index = 0;
    3198             :     int64_t t, *pts;
    3199             : 
    3200          14 :     for (p = kf; *p; p++)
    3201          13 :         if (*p == ',')
    3202           1 :             n++;
    3203           1 :     size = n;
    3204           1 :     pts = av_malloc_array(size, sizeof(*pts));
    3205           1 :     if (!pts) {
    3206           0 :         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
    3207           0 :         exit_program(1);
    3208             :     }
    3209             : 
    3210           1 :     p = kf;
    3211           3 :     for (i = 0; i < n; i++) {
    3212           2 :         char *next = strchr(p, ',');
    3213             : 
    3214           2 :         if (next)
    3215           1 :             *next++ = 0;
    3216             : 
    3217           2 :         if (!memcmp(p, "chapters", 8)) {
    3218             : 
    3219           0 :             AVFormatContext *avf = output_files[ost->file_index]->ctx;
    3220             :             int j;
    3221             : 
    3222           0 :             if (avf->nb_chapters > INT_MAX - size ||
    3223           0 :                 !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
    3224             :                                      sizeof(*pts)))) {
    3225           0 :                 av_log(NULL, AV_LOG_FATAL,
    3226             :                        "Could not allocate forced key frames array.\n");
    3227           0 :                 exit_program(1);
    3228             :             }
    3229           0 :             t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
    3230           0 :             t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
    3231             : 
    3232           0 :             for (j = 0; j < avf->nb_chapters; j++) {
    3233           0 :                 AVChapter *c = avf->chapters[j];
    3234             :                 av_assert1(index < size);
    3235           0 :                 pts[index++] = av_rescale_q(c->start, c->time_base,
    3236           0 :                                             avctx->time_base) + t;
    3237             :             }
    3238             : 
    3239             :         } else {
    3240             : 
    3241           2 :             t = parse_time_or_die("force_key_frames", p, 1);
    3242             :             av_assert1(index < size);
    3243           2 :             pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
    3244             : 
    3245             :         }
    3246             : 
    3247           2 :         p = next;
    3248             :     }
    3249             : 
    3250           1 :     av_assert0(index == size);
    3251           1 :     qsort(pts, size, sizeof(*pts), compare_int64);
    3252           1 :     ost->forced_kf_count = size;
    3253           1 :     ost->forced_kf_pts   = pts;
    3254           1 : }
    3255             : 
    3256        5476 : static void init_encoder_time_base(OutputStream *ost, AVRational default_time_base)
    3257             : {
    3258        5476 :     InputStream *ist = get_input_stream(ost);
    3259        5476 :     AVCodecContext *enc_ctx = ost->enc_ctx;
    3260             :     AVFormatContext *oc;
    3261             : 
    3262        5476 :     if (ost->enc_timebase.num > 0) {
    3263           0 :         enc_ctx->time_base = ost->enc_timebase;
    3264           0 :         return;
    3265             :     }
    3266             : 
    3267        5476 :     if (ost->enc_timebase.num < 0) {
    3268           0 :         if (ist) {
    3269           0 :             enc_ctx->time_base = ist->st->time_base;
    3270           0 :             return;
    3271             :         }
    3272             : 
    3273           0 :         oc = output_files[ost->file_index]->ctx;
    3274           0 :         av_log(oc, AV_LOG_WARNING, "Input stream data not available, using default time base\n");
    3275             :     }
    3276             : 
    3277        5476 :     enc_ctx->time_base = default_time_base;
    3278             : }
    3279             : 
    3280        5506 : static int init_output_stream_encode(OutputStream *ost)
    3281             : {
    3282        5506 :     InputStream *ist = get_input_stream(ost);
    3283        5506 :     AVCodecContext *enc_ctx = ost->enc_ctx;
    3284        5506 :     AVCodecContext *dec_ctx = NULL;
    3285        5506 :     AVFormatContext *oc = output_files[ost->file_index]->ctx;
    3286             :     int j, ret;
    3287             : 
    3288        5506 :     set_encoder_id(output_files[ost->file_index], ost);
    3289             : 
    3290             :     // Muxers use AV_PKT_DATA_DISPLAYMATRIX to signal rotation. On the other
    3291             :     // hand, the legacy API makes demuxers set "rotate" metadata entries,
    3292             :     // which have to be filtered out to prevent leaking them to output files.
    3293        5506 :     av_dict_set(&ost->st->metadata, "rotate", NULL, 0);
    3294             : 
    3295        5506 :     if (ist) {
    3296        5449 :         ost->st->disposition          = ist->st->disposition;
    3297             : 
    3298        5449 :         dec_ctx = ist->dec_ctx;
    3299             : 
    3300        5449 :         enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
    3301             :     } else {
    3302         118 :         for (j = 0; j < oc->nb_streams; j++) {
    3303          61 :             AVStream *st = oc->streams[j];
    3304          61 :             if (st != ost->st && st->codecpar->codec_type == ost->st->codecpar->codec_type)
    3305           0 :                 break;
    3306             :         }
    3307          57 :         if (j == oc->nb_streams)
    3308         106 :             if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
    3309          49 :                 ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
    3310          57 :                 ost->st->disposition = AV_DISPOSITION_DEFAULT;
    3311             :     }
    3312             : 
    3313        5506 :     if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
    3314        4408 :         if (!ost->frame_rate.num)
    3315        4389 :             ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
    3316        4408 :         if (ist && !ost->frame_rate.num)
    3317           0 :             ost->frame_rate = ist->framerate;
    3318        4408 :         if (ist && !ost->frame_rate.num)
    3319           0 :             ost->frame_rate = ist->st->r_frame_rate;
    3320        4408 :         if (ist && !ost->frame_rate.num) {
    3321           0 :             ost->frame_rate = (AVRational){25, 1};
    3322           0 :             av_log(NULL, AV_LOG_WARNING,
    3323             :                    "No information "
    3324             :                    "about the input framerate is available. Falling "
    3325             :                    "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
    3326             :                    "if you want a different framerate.\n",
    3327             :                    ost->file_index, ost->index);
    3328             :         }
    3329             : //      ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
    3330        4408 :         if (ost->enc->supported_framerates && !ost->force_fps) {
    3331          48 :             int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
    3332          48 :             ost->frame_rate = ost->enc->supported_framerates[idx];
    3333             :         }
    3334             :         // reduce frame rate for mpeg4 to be within the spec limits
    3335        4408 :         if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
    3336         116 :             av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
    3337         116 :                       ost->frame_rate.num, ost->frame_rate.den, 65535);
    3338             :         }
    3339             :     }
    3340             : 
    3341        5506 :     switch (enc_ctx->codec_type) {
    3342        1068 :     case AVMEDIA_TYPE_AUDIO:
    3343        1068 :         enc_ctx->sample_fmt     = av_buffersink_get_format(ost->filter->filter);
    3344        1068 :         if (dec_ctx)
    3345        1060 :             enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,
    3346             :                                                  av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
    3347        1068 :         enc_ctx->sample_rate    = av_buffersink_get_sample_rate(ost->filter->filter);
    3348        1068 :         enc_ctx->channel_layout = av_buffersink_get_channel_layout(ost->filter->filter);
    3349        1068 :         enc_ctx->channels       = av_buffersink_get_channels(ost->filter->filter);
    3350             : 
    3351        1068 :         init_encoder_time_base(ost, av_make_q(1, enc_ctx->sample_rate));
    3352        1068 :         break;
    3353             : 
    3354        4408 :     case AVMEDIA_TYPE_VIDEO:
    3355        4408 :         init_encoder_time_base(ost, av_inv_q(ost->frame_rate));
    3356             : 
    3357        4408 :         if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
    3358           0 :             enc_ctx->time_base = av_buffersink_get_time_base(ost->filter->filter);
    3359        4408 :         if (   av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
    3360           3 :            && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
    3361           0 :             av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
    3362             :                                        "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
    3363             :         }
    3364        4408 :         for (j = 0; j < ost->forced_kf_count; j++)
    3365           0 :             ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
    3366           0 :                                                  AV_TIME_BASE_Q,
    3367             :                                                  enc_ctx->time_base);
    3368             : 
    3369        4408 :         enc_ctx->width  = av_buffersink_get_w(ost->filter->filter);
    3370        4408 :         enc_ctx->height = av_buffersink_get_h(ost->filter->filter);
    3371        8816 :         enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
    3372        4408 :             ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
    3373        8816 :             av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :
    3374        4408 :             av_buffersink_get_sample_aspect_ratio(ost->filter->filter);
    3375             : 
    3376        4408 :         enc_ctx->pix_fmt = av_buffersink_get_format(ost->filter->filter);
    3377        4408 :         if (dec_ctx)
    3378        4359 :             enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,
    3379             :                                                  av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
    3380             : 
    3381        4408 :         enc_ctx->framerate = ost->frame_rate;
    3382             : 
    3383        4408 :         ost->st->avg_frame_rate = ost->frame_rate;
    3384             : 
    3385        8767 :         if (!dec_ctx ||
    3386        8010 :             enc_ctx->width   != dec_ctx->width  ||
    3387        7098 :             enc_ctx->height  != dec_ctx->height ||
    3388        3447 :             enc_ctx->pix_fmt != dec_ctx->pix_fmt) {
    3389        2837 :             enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample;
    3390             :         }
    3391             : 
    3392        4408 :         if (ost->top_field_first == 0) {
    3393           2 :             enc_ctx->field_order = AV_FIELD_BB;
    3394        4406 :         } else if (ost->top_field_first == 1) {
    3395           1 :             enc_ctx->field_order = AV_FIELD_TT;
    3396             :         }
    3397             : 
    3398        4408 :         if (ost->forced_keyframes) {
    3399           1 :             if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
    3400           0 :                 ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
    3401             :                                     forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
    3402           0 :                 if (ret < 0) {
    3403           0 :                     av_log(NULL, AV_LOG_ERROR,
    3404           0 :                            "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
    3405           0 :                     return ret;
    3406             :                 }
    3407           0 :                 ost->forced_keyframes_expr_const_values[FKF_N] = 0;
    3408           0 :                 ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
    3409           0 :                 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
    3410           0 :                 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
    3411             : 
    3412             :             // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
    3413             :             // parse it only for static kf timings
    3414           1 :             } else if(strncmp(ost->forced_keyframes, "source", 6)) {
    3415           1 :                 parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx);
    3416             :             }
    3417             :         }
    3418        4408 :         break;
    3419          30 :     case AVMEDIA_TYPE_SUBTITLE:
    3420          30 :         enc_ctx->time_base = AV_TIME_BASE_Q;
    3421          30 :         if (!enc_ctx->width) {
    3422          30 :             enc_ctx->width     = input_streams[ost->source_index]->st->codecpar->width;
    3423          30 :             enc_ctx->height    = input_streams[ost->source_index]->st->codecpar->height;
    3424             :         }
    3425          30 :         break;
    3426           0 :     case AVMEDIA_TYPE_DATA:
    3427           0 :         break;
    3428           0 :     default:
    3429           0 :         abort();
    3430             :         break;
    3431             :     }
    3432             : 
    3433        5506 :     ost->mux_timebase = enc_ctx->time_base;
    3434             : 
    3435        5506 :     return 0;
    3436             : }
    3437             : 
    3438        5756 : static int init_output_stream(OutputStream *ost, char *error, int error_len)
    3439             : {
    3440        5756 :     int ret = 0;
    3441             : 
    3442        5756 :     if (ost->encoding_needed) {
    3443        5506 :         AVCodec      *codec = ost->enc;
    3444        5506 :         AVCodecContext *dec = NULL;
    3445             :         InputStream *ist;
    3446             : 
    3447        5506 :         ret = init_output_stream_encode(ost);
    3448        5506 :         if (ret < 0)
    3449           0 :             return ret;
    3450             : 
    3451        5506 :         if ((ist = get_input_stream(ost)))
    3452        5449 :             dec = ist->dec_ctx;
    3453        5506 :         if (dec && dec->subtitle_header) {
    3454             :             /* ASS code assumes this buffer is null terminated so add extra byte. */
    3455          29 :             ost->enc_ctx->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
    3456          29 :             if (!ost->enc_ctx->subtitle_header)
    3457           0 :                 return AVERROR(ENOMEM);
    3458          29 :             memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
    3459          29 :             ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
    3460             :         }
    3461        5506 :         if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
    3462        2423 :             av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
    3463        6574 :         if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
    3464        2098 :             !codec->defaults &&
    3465        1995 :             !av_dict_get(ost->encoder_opts, "b", NULL, 0) &&
    3466         965 :             !av_dict_get(ost->encoder_opts, "ab", NULL, 0))
    3467         965 :             av_dict_set(&ost->encoder_opts, "b", "128000", 0);
    3468             : 
    3469        5506 :         if (ost->filter && av_buffersink_get_hw_frames_ctx(ost->filter->filter) &&
    3470           0 :             ((AVHWFramesContext*)av_buffersink_get_hw_frames_ctx(ost->filter->filter)->data)->format ==
    3471           0 :             av_buffersink_get_format(ost->filter->filter)) {
    3472           0 :             ost->enc_ctx->hw_frames_ctx = av_buffer_ref(av_buffersink_get_hw_frames_ctx(ost->filter->filter));
    3473           0 :             if (!ost->enc_ctx->hw_frames_ctx)
    3474           0 :                 return AVERROR(ENOMEM);
    3475             :         } else {
    3476        5506 :             ret = hw_device_setup_for_encode(ost);
    3477        5506 :             if (ret < 0) {
    3478           0 :                 snprintf(error, error_len, "Device setup failed for "
    3479             :                          "encoder on output stream #%d:%d : %s",
    3480           0 :                      ost->file_index, ost->index, av_err2str(ret));
    3481           0 :                 return ret;
    3482             :             }
    3483             :         }
    3484             : 
    3485        5506 :         if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
    3486           0 :             if (ret == AVERROR_EXPERIMENTAL)
    3487           0 :                 abort_codec_experimental(codec, 1);
    3488           0 :             snprintf(error, error_len,
    3489             :                      "Error while opening encoder for output stream #%d:%d - "
    3490             :                      "maybe incorrect parameters such as bit_rate, rate, width or height",
    3491             :                     ost->file_index, ost->index);
    3492           0 :             return ret;
    3493             :         }
    3494        6574 :         if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
    3495        1068 :             !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
    3496          85 :             av_buffersink_set_frame_size(ost->filter->filter,
    3497          85 :                                             ost->enc_ctx->frame_size);
    3498        5506 :         assert_avoptions(ost->encoder_opts);
    3499        5506 :         if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000 &&
    3500           0 :             ost->enc_ctx->codec_id != AV_CODEC_ID_CODEC2 /* don't complain about 700 bit/s modes */)
    3501           0 :             av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
    3502             :                                          " It takes bits/s as argument, not kbits/s\n");
    3503             : 
    3504        5506 :         ret = avcodec_parameters_from_context(ost->st->codecpar, ost->enc_ctx);
    3505        5506 :         if (ret < 0) {
    3506           0 :             av_log(NULL, AV_LOG_FATAL,
    3507             :                    "Error initializing the output stream codec context.\n");
    3508           0 :             exit_program(1);
    3509             :         }
    3510             :         /*
    3511             :          * FIXME: ost->st->codec should't be needed here anymore.
    3512             :          */
    3513        5506 :         ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);
    3514        5506 :         if (ret < 0)
    3515           0 :             return ret;
    3516             : 
    3517        5506 :         if (ost->enc_ctx->nb_coded_side_data) {
    3518             :             int i;
    3519             : 
    3520         364 :             for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
    3521         182 :                 const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
    3522             :                 uint8_t *dst_data;
    3523             : 
    3524         182 :                 dst_data = av_stream_new_side_data(ost->st, sd_src->type, sd_src->size);
    3525         182 :                 if (!dst_data)
    3526           0 :                     return AVERROR(ENOMEM);
    3527         182 :                 memcpy(dst_data, sd_src->data, sd_src->size);
    3528             :             }
    3529             :         }
    3530             : 
    3531             :         /*
    3532             :          * Add global input side data. For now this is naive, and copies it
    3533             :          * from the input stream's global side data. All side data should
    3534             :          * really be funneled over AVFrame and libavfilter, then added back to
    3535             :          * packet side data, and then potentially using the first packet for
    3536             :          * global side data.
    3537             :          */
    3538        5506 :         if (ist) {
    3539             :             int i;
    3540        5658 :             for (i = 0; i < ist->st->nb_side_data; i++) {
    3541         209 :                 AVPacketSideData *sd = &ist->st->side_data[i];
    3542         209 :                 uint8_t *dst = av_stream_new_side_data(ost->st, sd->type, sd->size);
    3543         209 :                 if (!dst)
    3544           0 :                     return AVERROR(ENOMEM);
    3545         209 :                 memcpy(dst, sd->data, sd->size);
    3546         209 :                 if (ist->autorotate && sd->type == AV_PKT_DATA_DISPLAYMATRIX)
    3547           0 :                     av_display_rotation_set((uint32_t *)dst, 0);
    3548             :             }
    3549             :         }
    3550             : 
    3551             :         // copy timebase while removing common factors
    3552        5506 :         if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
    3553        5506 :             ost->st->time_base = av_add_q(ost->enc_ctx->time_base, (AVRational){0, 1});
    3554             : 
    3555             :         // copy estimated duration as a hint to the muxer
    3556        5506 :         if (ost->st->duration <= 0 && ist && ist->st->duration > 0)
    3557        4346 :             ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
    3558             : 
    3559        5506 :         ost->st->codec->codec= ost->enc_ctx->codec;
    3560         250 :     } else if (ost->stream_copy) {
    3561         249 :         ret = init_output_stream_streamcopy(ost);
    3562         249 :         if (ret < 0)
    3563           0 :             return ret;
    3564             :     }
    3565             : 
    3566             :     // parse user provided disposition, and update stream values
    3567        5756 :     if (ost->disposition) {
    3568             :         static const AVOption opts[] = {
    3569             :             { "disposition"         , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
    3570             :             { "default"             , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT           },    .unit = "flags" },
    3571             :             { "dub"                 , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB               },    .unit = "flags" },
    3572             :             { "original"            , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL          },    .unit = "flags" },
    3573             :             { "comment"             , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT           },    .unit = "flags" },
    3574             :             { "lyrics"              , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS            },    .unit = "flags" },
    3575             :             { "karaoke"             , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE           },    .unit = "flags" },
    3576             :             { "forced"              , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED            },    .unit = "flags" },
    3577             :             { "hearing_impaired"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED  },    .unit = "flags" },
    3578             :             { "visual_impaired"     , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED   },    .unit = "flags" },
    3579             :             { "clean_effects"       , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS     },    .unit = "flags" },
    3580             :             { "attached_pic"        , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ATTACHED_PIC      },    .unit = "flags" },
    3581             :             { "captions"            , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS          },    .unit = "flags" },
    3582             :             { "descriptions"        , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS      },    .unit = "flags" },
    3583             :             { "dependent"           , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEPENDENT         },    .unit = "flags" },
    3584             :             { "metadata"            , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA          },    .unit = "flags" },
    3585             :             { NULL },
    3586             :         };
    3587             :         static const AVClass class = {
    3588             :             .class_name = "",
    3589             :             .item_name  = av_default_item_name,
    3590             :             .option     = opts,
    3591             :             .version    = LIBAVUTIL_VERSION_INT,
    3592             :         };
    3593           0 :         const AVClass *pclass = &class;
    3594             : 
    3595           0 :         ret = av_opt_eval_flags(&pclass, &opts[0], ost->disposition, &ost->st->disposition);
    3596           0 :         if (ret < 0)
    3597           0 :             return ret;
    3598             :     }
    3599             : 
    3600             :     /* initialize bitstream filters for the output stream
    3601             :      * needs to be done here, because the codec id for streamcopy is not
    3602             :      * known until now */
    3603        5756 :     ret = init_output_bsfs(ost);
    3604        5756 :     if (ret < 0)
    3605           0 :         return ret;
    3606             : 
    3607        5756 :     ost->initialized = 1;
    3608             : 
    3609        5756 :     ret = check_init_output_file(output_files[ost->file_index], ost->file_index);
    3610        5756 :     if (ret < 0)
    3611           0 :         return ret;
    3612             : 
    3613        5756 :     return ret;
    3614             : }
    3615             : 
    3616           0 : static void report_new_stream(int input_index, AVPacket *pkt)
    3617             : {
    3618           0 :     InputFile *file = input_files[input_index];
    3619           0 :     AVStream *st = file->ctx->streams[pkt->stream_index];
    3620             : 
    3621           0 :     if (pkt->stream_index < file->nb_streams_warn)
    3622           0 :         return;
    3623           0 :     av_log(file->ctx, AV_LOG_WARNING,
    3624             :            "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
    3625           0 :            av_get_media_type_string(st->codecpar->codec_type),
    3626             :            input_index, pkt->stream_index,
    3627           0 :            pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
    3628           0 :     file->nb_streams_warn = pkt->stream_index + 1;
    3629             : }
    3630             : 
    3631        5617 : static int transcode_init(void)
    3632             : {
    3633        5617 :     int ret = 0, i, j, k;
    3634             :     AVFormatContext *oc;
    3635             :     OutputStream *ost;
    3636             :     InputStream *ist;
    3637        5617 :     char error[1024] = {0};
    3638             : 
    3639       11091 :     for (i = 0; i < nb_filtergraphs; i++) {
    3640        5474 :         FilterGraph *fg = filtergraphs[i];
    3641       10950 :         for (j = 0; j < fg->nb_outputs; j++) {
    3642        5476 :             OutputFilter *ofilter = fg->outputs[j];
    3643        5476 :             if (!ofilter->ost || ofilter->ost->source_index >= 0)
    3644        5403 :                 continue;
    3645          73 :             if (fg->nb_inputs != 1)
    3646          57 :                 continue;
    3647          17 :             for (k = nb_input_streams-1; k >= 0 ; k--)
    3648          17 :                 if (fg->inputs[0]->ist == input_streams[k])
    3649          16 :                     break;
    3650          16 :             ofilter->ost->source_index = k;
    3651             :         }
    3652             :     }
    3653             : 
    3654             :     /* init framerate emulation */
    3655       11267 :     for (i = 0; i < nb_input_files; i++) {
    3656        5650 :         InputFile *ifile = input_files[i];
    3657        5650 :         if (ifile->rate_emu)
    3658           0 :             for (j = 0; j < ifile->nb_streams; j++)
    3659           0 :                 input_streams[j + ifile->ist_index]->start = av_gettime_relative();
    3660             :     }
    3661             : 
    3662             :     /* init input streams */
    3663       11575 :     for (i = 0; i < nb_input_streams; i++)
    3664        5958 :         if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
    3665           0 :             for (i = 0; i < nb_output_streams; i++) {
    3666           0 :                 ost = output_streams[i];
    3667           0 :                 avcodec_close(ost->enc_ctx);
    3668             :             }
    3669           0 :             goto dump_format;
    3670             :         }
    3671             : 
    3672             :     /* open each encoder */
    3673       11373 :     for (i = 0; i < nb_output_streams; i++) {
    3674             :         // skip streams fed from filtergraphs until we have a frame for them
    3675        5756 :         if (output_streams[i]->filter)
    3676        5476 :             continue;
    3677             : 
    3678         280 :         ret = init_output_stream(output_streams[i], error, sizeof(error));
    3679         280 :         if (ret < 0)
    3680           0 :             goto dump_format;
    3681             :     }
    3682             : 
    3683             :     /* discard unused programs */
    3684       11267 :     for (i = 0; i < nb_input_files; i++) {
    3685        5650 :         InputFile *ifile = input_files[i];
    3686        5675 :         for (j = 0; j < ifile->ctx->nb_programs; j++) {
    3687          25 :             AVProgram *p = ifile->ctx->programs[j];
    3688          25 :             int discard  = AVDISCARD_ALL;
    3689             : 
    3690          25 :             for (k = 0; k < p->nb_stream_indexes; k++)
    3691          25 :                 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
    3692          25 :                     discard = AVDISCARD_DEFAULT;
    3693          25 :                     break;
    3694             :                 }
    3695          25 :             p->discard = discard;
    3696             :         }
    3697             :     }
    3698             : 
    3699             :     /* write headers for files with no streams */
    3700       11235 :     for (i = 0; i < nb_output_files; i++) {
    3701        5618 :         oc = output_files[i]->ctx;
    3702        5618 :         if (oc->oformat->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
    3703           1 :             ret = check_init_output_file(output_files[i], i);
    3704           1 :             if (ret < 0)
    3705           0 :                 goto dump_format;
    3706             :         }
    3707             :     }
    3708             : 
    3709        5617 :  dump_format:
    3710             :     /* dump the stream mapping */
    3711        5617 :     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
    3712       11575 :     for (i = 0; i < nb_input_streams; i++) {
    3713        5958 :         ist = input_streams[i];
    3714             : 
    3715       11417 :         for (j = 0; j < ist->nb_filters; j++) {
    3716        5459 :             if (!filtergraph_is_simple(ist->filters[j]->graph)) {
    3717         224 :                 av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
    3718         168 :                        ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
    3719          56 :                        ist->filters[j]->name);
    3720          56 :                 if (nb_filtergraphs > 1)
    3721           0 :                     av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
    3722          56 :                 av_log(NULL, AV_LOG_INFO, "\n");
    3723             :             }
    3724             :         }
    3725             :     }
    3726             : 
    3727       11373 :     for (i = 0; i < nb_output_streams; i++) {
    3728        5756 :         ost = output_streams[i];
    3729             : 
    3730        5756 :         if (ost->attachment_filename) {
    3731             :             /* an attached file */
    3732           1 :             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
    3733             :                    ost->attachment_filename, ost->file_index, ost->index);
    3734           1 :             continue;
    3735             :         }
    3736             : 
    3737        5755 :         if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
    3738             :             /* output from a complex graph */
    3739          73 :             av_log(NULL, AV_LOG_INFO, "  %s", ost->filter->name);
    3740          73 :             if (nb_filtergraphs > 1)
    3741           0 :                 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
    3742             : 
    3743         146 :             av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
    3744         146 :                    ost->index, ost->enc ? ost->enc->name : "?");
    3745          73 :             continue;
    3746             :         }
    3747             : 
    3748       17046 :         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
    3749        5682 :                input_streams[ost->source_index]->file_index,
    3750        5682 :                input_streams[ost->source_index]->st->index,
    3751             :                ost->file_index,
    3752             :                ost->index);
    3753        5682 :         if (ost->sync_ist != input_streams[ost->source_index])
    3754           0 :             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
    3755           0 :                    ost->sync_ist->file_index,
    3756           0 :                    ost->sync_ist->st->index);
    3757        5682 :         if (ost->stream_copy)
    3758         249 :             av_log(NULL, AV_LOG_INFO, " (copy)");
    3759             :         else {
    3760        5433 :             const AVCodec *in_codec    = input_streams[ost->source_index]->dec;
    3761        5433 :             const AVCodec *out_codec   = ost->enc;
    3762        5433 :             const char *decoder_name   = "?";
    3763        5433 :             const char *in_codec_name  = "?";
    3764        5433 :             const char *encoder_name   = "?";
    3765        5433 :             const char *out_codec_name = "?";
    3766             :             const AVCodecDescriptor *desc;
    3767             : 
    3768        5433 :             if (in_codec) {
    3769        5433 :                 decoder_name  = in_codec->name;
    3770        5433 :                 desc = avcodec_descriptor_get(in_codec->id);
    3771        5433 :                 if (desc)
    3772        5433 :                     in_codec_name = desc->name;
    3773        5433 :                 if (!strcmp(decoder_name, in_codec_name))
    3774        5278 :                     decoder_name = "native";
    3775             :             }
    3776             : 
    3777        5433 :             if (out_codec) {
    3778        5433 :                 encoder_name   = out_codec->name;
    3779        5433 :                 desc = avcodec_descriptor_get(out_codec->id);
    3780        5433 :                 if (desc)
    3781        5433 :                     out_codec_name = desc->name;
    3782        5433 :                 if (!strcmp(encoder_name, out_codec_name))
    3783        5345 :                     encoder_name = "native";
    3784             :             }
    3785             : 
    3786        5433 :             av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
    3787             :                    in_codec_name, decoder_name,
    3788             :                    out_codec_name, encoder_name);
    3789             :         }
    3790        5682 :         av_log(NULL, AV_LOG_INFO, "\n");
    3791             :     }
    3792             : 
    3793        5617 :     if (ret) {
    3794           0 :         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
    3795           0 :         return ret;
    3796             :     }
    3797             : 
    3798        5617 :     atomic_store(&transcode_init_done, 1);
    3799             : 
    3800        5617 :     return 0;
    3801             : }
    3802             : 
    3803             : /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
    3804     1473893 : static int need_output(void)
    3805             : {
    3806             :     int i;
    3807             : 
    3808     1479814 :     for (i = 0; i < nb_output_streams; i++) {
    3809     1474197 :         OutputStream *ost    = output_streams[i];
    3810     1474197 :         OutputFile *of       = output_files[ost->file_index];
    3811     1474197 :         AVFormatContext *os  = output_files[ost->file_index]->ctx;
    3812             : 
    3813     2944641 :         if (ost->finished ||
    3814     2937481 :             (os->pb && avio_tell(os->pb) >= of->limit_filesize))
    3815        3753 :             continue;
    3816     1470444 :         if (ost->frame_number >= ost->max_frames) {
    3817             :             int j;
    3818        4338 :             for (j = 0; j < of->ctx->nb_streams; j++)
    3819        2170 :                 close_output_stream(output_streams[of->ost_index + j]);
    3820        2168 :             continue;
    3821             :         }
    3822             : 
    3823     1468276 :         return 1;
    3824             :     }
    3825             : 
    3826        5617 :     return 0;
    3827             : }
    3828             : 
    3829             : /**
    3830             :  * Select the output stream to process.
    3831             :  *
    3832             :  * @return  selected output stream, or NULL if none available
    3833             :  */
    3834     1468276 : static OutputStream *choose_output(void)
    3835             : {
    3836             :     int i;
    3837     1468276 :     int64_t opts_min = INT64_MAX;
    3838     1468276 :     OutputStream *ost_min = NULL;
    3839             : 
    3840     1879032 :     for (i = 0; i < nb_output_streams; i++) {
    3841     1482210 :         OutputStream *ost = output_streams[i];
    3842     1890812 :         int64_t opts = ost->st->cur_dts == AV_NOPTS_VALUE ? INT64_MIN :
    3843      408602 :                        av_rescale_q(ost->st->cur_dts, ost->st->time_base,
    3844      408602 :                                     AV_TIME_BASE_Q);
    3845     1482210 :         if (ost->st->cur_dts == AV_NOPTS_VALUE)
    3846     1073608 :             av_log(NULL, AV_LOG_DEBUG, "cur_dts is invalid (this is harmless if it occurs once at the start per stream)\n");
    3847             : 
    3848     1482210 :         if (!ost->initialized && !ost->inputs_done)
    3849     1071454 :             return ost;
    3850             : 
    3851      410756 :         if (!ost->finished && opts < opts_min) {
    3852      401838 :             opts_min = opts;
    3853      401838 :             ost_min  = ost->unavailable ? NULL : ost;
    3854             :         }
    3855             :     }
    3856      396822 :     return ost_min;
    3857             : }
    3858             : 
    3859           0 : static void set_tty_echo(int on)
    3860             : {
    3861             : #if HAVE_TERMIOS_H
    3862             :     struct termios tty;
    3863           0 :     if (tcgetattr(0, &tty) == 0) {
    3864           0 :         if (on) tty.c_lflag |= ECHO;
    3865           0 :         else    tty.c_lflag &= ~ECHO;
    3866           0 :         tcsetattr(0, TCSANOW, &tty);
    3867             :     }
    3868             : #endif
    3869           0 : }
    3870             : 
    3871        3297 : static int check_keyboard_interaction(int64_t cur_time)
    3872             : {
    3873             :     int i, ret, key;
    3874             :     static int64_t last_time;
    3875        3297 :     if (received_nb_signals)
    3876           0 :         return AVERROR_EXIT;
    3877             :     /* read_key() returns 0 on EOF */
    3878        3297 :     if(cur_time - last_time >= 100000 && !run_as_daemon){
    3879          42 :         key =  read_key();
    3880          42 :         last_time = cur_time;
    3881             :     }else
    3882        3255 :         key = -1;
    3883        3297 :     if (key == 'q')
    3884           0 :         return AVERROR_EXIT;
    3885        3297 :     if (key == '+') av_log_set_level(av_log_get_level()+10);
    3886        3297 :     if (key == '-') av_log_set_level(av_log_get_level()-10);
    3887        3297 :     if (key == 's') qp_hist     ^= 1;
    3888        3297 :     if (key == 'h'){
    3889           0 :         if (do_hex_dump){
    3890           0 :             do_hex_dump = do_pkt_dump = 0;
    3891           0 :         } else if(do_pkt_dump){
    3892           0 :             do_hex_dump = 1;
    3893             :         } else
    3894           0 :             do_pkt_dump = 1;
    3895           0 :         av_log_set_level(AV_LOG_DEBUG);
    3896             :     }
    3897        3297 :     if (key == 'c' || key == 'C'){
    3898           0 :         char buf[4096], target[64], command[256], arg[256] = {0};
    3899             :         double time;
    3900           0 :         int k, n = 0;
    3901           0 :         fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
    3902           0 :         i = 0;
    3903           0 :         set_tty_echo(1);
    3904           0 :         while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
    3905           0 :             if (k > 0)
    3906           0 :                 buf[i++] = k;
    3907           0 :         buf[i] = 0;
    3908           0 :         set_tty_echo(0);
    3909           0 :         fprintf(stderr, "\n");
    3910           0 :         if (k > 0 &&
    3911             :             (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
    3912           0 :             av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
    3913             :                    target, time, command, arg);
    3914           0 :             for (i = 0; i < nb_filtergraphs; i++) {
    3915           0 :                 FilterGraph *fg = filtergraphs[i];
    3916           0 :                 if (fg->graph) {
    3917           0 :                     if (time < 0) {
    3918           0 :                         ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
    3919             :                                                           key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
    3920           0 :                         fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
    3921           0 :                     } else if (key == 'c') {
    3922           0 :                         fprintf(stderr, "Queuing commands only on filters supporting the specific command is unsupported\n");
    3923           0 :                         ret = AVERROR_PATCHWELCOME;
    3924             :                     } else {
    3925           0 :                         ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
    3926           0 :                         if (ret < 0)
    3927           0 :                             fprintf(stderr, "Queuing command failed with error %s\n", av_err2str(ret));
    3928             :                     }
    3929             :                 }
    3930             :             }
    3931             :         } else {
    3932           0 :             av_log(NULL, AV_LOG_ERROR,
    3933             :                    "Parse error, at least 3 arguments were expected, "
    3934             :                    "only %d given in string '%s'\n", n, buf);
    3935             :         }
    3936             :     }
    3937        3297 :     if (key == 'd' || key == 'D'){
    3938           0 :         int debug=0;
    3939           0 :         if(key == 'D') {
    3940           0 :             debug = input_streams[0]->st->codec->debug<<1;
    3941           0 :             if(!debug) debug = 1;
    3942           0 :             while(debug & (FF_DEBUG_DCT_COEFF
    3943             : #if FF_API_DEBUG_MV
    3944             :                                              |FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE
    3945             : #endif
    3946             :                                                                                   )) //unsupported, would just crash
    3947           0 :                 debug += debug;
    3948             :         }else{
    3949             :             char buf[32];
    3950           0 :             int k = 0;
    3951           0 :             i = 0;
    3952           0 :             set_tty_echo(1);
    3953           0 :             while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
    3954           0 :                 if (k > 0)
    3955           0 :                     buf[i++] = k;
    3956           0 :             buf[i] = 0;
    3957           0 :             set_tty_echo(0);
    3958           0 :             fprintf(stderr, "\n");
    3959           0 :             if (k <= 0 || sscanf(buf, "%d", &debug)!=1)
    3960           0 :                 fprintf(stderr,"error parsing debug value\n");
    3961             :         }
    3962           0 :         for(i=0;i<nb_input_streams;i++) {
    3963           0 :             input_streams[i]->st->codec->debug = debug;
    3964             :         }
    3965           0 :         for(i=0;i<nb_output_streams;i++) {
    3966           0 :             OutputStream *ost = output_streams[i];
    3967           0 :             ost->enc_ctx->debug = debug;
    3968             :         }
    3969           0 :         if(debug) av_log_set_level(AV_LOG_DEBUG);
    3970           0 :         fprintf(stderr,"debug=%d\n", debug);
    3971             :     }
    3972        3297 :     if (key == '?'){
    3973           0 :         fprintf(stderr, "key    function\n"
    3974             :                         "?      show this help\n"
    3975             :                         "+      increase verbosity\n"
    3976             :                         "-      decrease verbosity\n"
    3977             :                         "c      Send command to first matching filter supporting it\n"
    3978             :                         "C      Send/Queue command to all matching filters\n"
    3979             :                         "D      cycle through available debug modes\n"
    3980             :                         "h      dump packets/hex press to cycle through the 3 states\n"
    3981             :                         "q      quit\n"
    3982             :                         "s      Show QP histogram\n"
    3983             :         );
    3984             :     }
    3985        3297 :     return 0;
    3986             : }
    3987             : 
    3988             : #if HAVE_THREADS
    3989         135 : static void *input_thread(void *arg)
    3990             : {
    3991         135 :     InputFile *f = arg;
    3992         135 :     unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
    3993         135 :     int ret = 0;
    3994             : 
    3995        6516 :     while (1) {
    3996             :         AVPacket pkt;
    3997        6651 :         ret = av_read_frame(f->ctx, &pkt);
    3998             : 
    3999        6651 :         if (ret == AVERROR(EAGAIN)) {
    4000           0 :             av_usleep(10000);
    4001           0 :             continue;
    4002             :         }
    4003        6651 :         if (ret < 0) {
    4004          44 :             av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
    4005          44 :             break;
    4006             :         }
    4007        6607 :         ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
    4008        6607 :         if (flags && ret == AVERROR(EAGAIN)) {
    4009          57 :             flags = 0;
    4010          57 :             ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
    4011          57 :             av_log(f->ctx, AV_LOG_WARNING,
    4012             :                    "Thread message queue blocking; consider raising the "
    4013             :                    "thread_queue_size option (current value: %d)\n",
    4014             :                    f->thread_queue_size);
    4015             :         }
    4016        6607 :         if (ret < 0) {
    4017          91 :             if (ret != AVERROR_EOF)
    4018           0 :                 av_log(f->ctx, AV_LOG_ERROR,
    4019             :                        "Unable to send packet to main thread: %s\n",
    4020           0 :                        av_err2str(ret));
    4021          91 :             av_packet_unref(&pkt);
    4022          91 :             av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
    4023          91 :             break;
    4024             :         }
    4025             :     }
    4026             : 
    4027         270 :     return NULL;
    4028             : }
    4029             : 
    4030       16852 : static void free_input_threads(void)
    4031             : {
    4032             :     int i;
    4033             : 
    4034       33802 :     for (i = 0; i < nb_input_files; i++) {
    4035       16950 :         InputFile *f = input_files[i];
    4036             :         AVPacket pkt;
    4037             : 
    4038       16950 :         if (!f || !f->in_thread_queue)
    4039       16815 :             continue;
    4040         135 :         av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
    4041         993 :         while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
    4042         723 :             av_packet_unref(&pkt);
    4043             : 
    4044         135 :         pthread_join(f->thread, NULL);
    4045         135 :         f->joined = 1;
    4046         135 :         av_thread_message_queue_free(&f->in_thread_queue);
    4047             :     }
    4048       16852 : }
    4049             : 
    4050        5617 : static int init_input_threads(void)
    4051             : {
    4052             :     int i, ret;
    4053             : 
    4054        5617 :     if (nb_input_files == 1)
    4055        5515 :         return 0;
    4056             : 
    4057         237 :     for (i = 0; i < nb_input_files; i++) {
    4058         135 :         InputFile *f = input_files[i];
    4059             : 
    4060         193 :         if (f->ctx->pb ? !f->ctx->pb->seekable :
    4061          58 :             strcmp(f->ctx->iformat->name, "lavfi"))
    4062          57 :             f->non_blocking = 1;
    4063         135 :         ret = av_thread_message_queue_alloc(&f->in_thread_queue,
    4064         135 :                                             f->thread_queue_size, sizeof(AVPacket));
    4065         135 :         if (ret < 0)
    4066           0 :             return ret;
    4067             : 
    4068         135 :         if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
    4069           0 :             av_log(NULL, AV_LOG_ERROR, "pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
    4070           0 :             av_thread_message_queue_free(&f->in_thread_queue);
    4071           0 :             return AVERROR(ret);
    4072             :         }
    4073             :     }
    4074         102 :     return 0;
    4075             : }
    4076             : 
    4077     1068926 : static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
    4078             : {
    4079     1068926 :     return av_thread_message_queue_recv(f->in_thread_queue, pkt,
    4080     1068926 :                                         f->non_blocking ?
    4081             :                                         AV_THREAD_MESSAGE_NONBLOCK : 0);
    4082             : }
    4083             : #endif
    4084             : 
    4085     1463505 : static int get_input_packet(InputFile *f, AVPacket *pkt)
    4086             : {
    4087     1463505 :     if (f->rate_emu) {
    4088             :         int i;
    4089           0 :         for (i = 0; i < f->nb_streams; i++) {
    4090           0 :             InputStream *ist = input_streams[f->ist_index + i];
    4091           0 :             int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
    4092           0 :             int64_t now = av_gettime_relative() - ist->start;
    4093           0 :             if (pts > now)
    4094           0 :                 return AVERROR(EAGAIN);
    4095             :         }
    4096             :     }
    4097             : 
    4098             : #if HAVE_THREADS
    4099     1463505 :     if (nb_input_files > 1)
    4100     1068926 :         return get_input_packet_mt(f, pkt);
    4101             : #endif
    4102      394579 :     return av_read_frame(f->ctx, pkt);
    4103             : }
    4104             : 
    4105           2 : static int got_eagain(void)
    4106             : {
    4107             :     int i;
    4108           2 :     for (i = 0; i < nb_output_streams; i++)
    4109           2 :         if (output_streams[i]->unavailable)
    4110           2 :             return 1;
    4111           0 :     return 0;
    4112             : }
    4113             : 
    4114      396768 : static void reset_eagain(void)
    4115             : {
    4116             :     int i;
    4117      799849 :     for (i = 0; i < nb_input_files; i++)
    4118      403081 :         input_files[i]->eagain = 0;
    4119      807457 :     for (i = 0; i < nb_output_streams; i++)
    4120      410689 :         output_streams[i]->unavailable = 0;
    4121      396768 : }
    4122             : 
    4123             : // set duration to max(tmp, duration) in a proper time base and return duration's time_base
    4124           0 : static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
    4125             :                                 AVRational time_base)
    4126             : {
    4127             :     int ret;
    4128             : 
    4129           0 :     if (!*duration) {
    4130           0 :         *duration = tmp;
    4131           0 :         return tmp_time_base;
    4132             :     }
    4133             : 
    4134           0 :     ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
    4135           0 :     if (ret < 0) {
    4136           0 :         *duration = tmp;
    4137           0 :         return tmp_time_base;
    4138             :     }
    4139             : 
    4140           0 :     return time_base;
    4141             : }
    4142             : 
    4143           0 : static int seek_to_start(InputFile *ifile, AVFormatContext *is)
    4144             : {
    4145             :     InputStream *ist;
    4146             :     AVCodecContext *avctx;
    4147           0 :     int i, ret, has_audio = 0;
    4148           0 :     int64_t duration = 0;
    4149             : 
    4150           0 :     ret = av_seek_frame(is, -1, is->start_time, 0);
    4151           0 :     if (ret < 0)
    4152           0 :         return ret;
    4153             : 
    4154           0 :     for (i = 0; i < ifile->nb_streams; i++) {
    4155           0 :         ist   = input_streams[ifile->ist_index + i];
    4156           0 :         avctx = ist->dec_ctx;
    4157             : 
    4158             :         /* duration is the length of the last frame in a stream
    4159             :          * when audio stream is present we don't care about
    4160             :          * last video frame length because it's not defined exactly */
    4161           0 :         if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
    4162           0 :             has_audio = 1;
    4163             :     }
    4164             : 
    4165           0 :     for (i = 0; i < ifile->nb_streams; i++) {
    4166           0 :         ist   = input_streams[ifile->ist_index + i];
    4167           0 :         avctx = ist->dec_ctx;
    4168             : 
    4169           0 :         if (has_audio) {
    4170           0 :             if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
    4171           0 :                 AVRational sample_rate = {1, avctx->sample_rate};
    4172             : 
    4173           0 :                 duration = av_rescale_q(ist->nb_samples, sample_rate, ist->st->time_base);
    4174             :             } else {
    4175           0 :                 continue;
    4176             :             }
    4177             :         } else {
    4178           0 :             if (ist->framerate.num) {
    4179           0 :                 duration = av_rescale_q(1, av_inv_q(ist->framerate), ist->st->time_base);
    4180           0 :             } else if (ist->st->avg_frame_rate.num) {
    4181           0 :                 duration = av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate), ist->st->time_base);
    4182             :             } else {
    4183           0 :                 duration = 1;
    4184             :             }
    4185             :         }
    4186           0 :         if (!ifile->duration)
    4187           0 :             ifile->time_base = ist->st->time_base;
    4188             :         /* the total duration of the stream, max_pts - min_pts is
    4189             :          * the duration of the stream without the last frame */
    4190           0 :         duration += ist->max_pts - ist->min_pts;
    4191           0 :         ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
    4192             :                                         ifile->time_base);
    4193             :     }
    4194             : 
    4195           0 :     if (ifile->loop > 0)
    4196           0 :         ifile->loop--;
    4197             : 
    4198           0 :     return ret;
    4199             : }
    4200             : 
    4201             : /*
    4202             :  * Return
    4203             :  * - 0 -- one packet was read and processed
    4204             :  * - AVERROR(EAGAIN) -- no packets were available for selected file,
    4205             :  *   this function should be called again
    4206             :  * - AVERROR_EOF -- this function should not be called again
    4207             :  */
    4208     1463505 : static int process_input(int file_index)
    4209             : {
    4210     1463505 :     InputFile *ifile = input_files[file_index];
    4211             :     AVFormatContext *is;
    4212             :     InputStream *ist;
    4213             :     AVPacket pkt;
    4214             :     int ret, i, j;
    4215             :     int64_t duration;
    4216             :     int64_t pkt_dts;
    4217             : 
    4218     1463505 :     is  = ifile->ctx;
    4219     1463505 :     ret = get_input_packet(ifile, &pkt);
    4220             : 
    4221     1463505 :     if (ret == AVERROR(EAGAIN)) {
    4222     1063093 :         ifile->eagain = 1;
    4223     1063093 :         return ret;
    4224             :     }
    4225      400412 :     if (ret < 0 && ifile->loop) {
    4226             :         AVCodecContext *avctx;
    4227           0 :         for (i = 0; i < ifile->nb_streams; i++) {
    4228           0 :             ist = input_streams[ifile->ist_index + i];
    4229           0 :             avctx = ist->dec_ctx;
    4230           0 :             if (ist->decoding_needed) {
    4231           0 :                 ret = process_input_packet(ist, NULL, 1);
    4232           0 :                 if (ret>0)
    4233           0 :                     return 0;
    4234           0 :                 avcodec_flush_buffers(avctx);
    4235             :             }
    4236             :         }
    4237           0 :         ret = seek_to_start(ifile, is);
    4238           0 :         if (ret < 0)
    4239           0 :             av_log(NULL, AV_LOG_WARNING, "Seek to start failed.\n");
    4240             :         else
    4241           0 :             ret = get_input_packet(ifile, &pkt);
    4242           0 :         if (ret == AVERROR(EAGAIN)) {
    4243           0 :             ifile->eagain = 1;
    4244           0 :             return ret;
    4245             :         }
    4246             :     }
    4247      400412 :     if (ret < 0) {
    4248        3646 :         if (ret != AVERROR_EOF) {
    4249          75 :             print_error(is->url, ret);
    4250          75 :             if (exit_on_error)
    4251           0 :                 exit_program(1);
    4252             :         }
    4253             : 
    4254        6895 :         for (i = 0; i < ifile->nb_streams; i++) {
    4255        3915 :             ist = input_streams[ifile->ist_index + i];
    4256        3915 :             if (ist->decoding_needed) {
    4257        3501 :                 ret = process_input_packet(ist, NULL, 0);
    4258        3501 :                 if (ret>0)
    4259         666 :                     return 0;
    4260             :             }
    4261             : 
    4262             :             /* mark all outputs that don't go through lavfi as finished */
    4263        6761 :             for (j = 0; j < nb_output_streams; j++) {
    4264        3512 :                 OutputStream *ost = output_streams[j];
    4265             : 
    4266        6560 :                 if (ost->source_index == ifile->ist_index + i &&
    4267        5859 :                     (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
    4268         267 :                     finish_output_stream(ost);
    4269             :             }
    4270             :         }
    4271             : 
    4272        2980 :         ifile->eof_reached = 1;
    4273        2980 :         return AVERROR(EAGAIN);
    4274             :     }
    4275             : 
    4276      396766 :     reset_eagain();
    4277             : 
    4278      396766 :     if (do_pkt_dump) {
    4279           0 :         av_pkt_dump_log2(NULL, AV_LOG_INFO, &pkt, do_hex_dump,
    4280           0 :                          is->streams[pkt.stream_index]);
    4281             :     }
    4282             :     /* the following test is needed in case new streams appear
    4283             :        dynamically in stream : we ignore them */
    4284      396766 :     if (pkt.stream_index >= ifile->nb_streams) {
    4285           0 :         report_new_stream(file_index, &pkt);
    4286           0 :         goto discard_packet;
    4287             :     }
    4288             : 
    4289      396766 :     ist = input_streams[ifile->ist_index + pkt.stream_index];
    4290             : 
    4291      396766 :     ist->data_size += pkt.size;
    4292      396766 :     ist->nb_packets++;
    4293             : 
    4294      396766 :     if (ist->discard)
    4295        7546 :         goto discard_packet;
    4296             : 
    4297      389220 :     if (exit_on_error && (pkt.flags & AV_PKT_FLAG_CORRUPT)) {
    4298           0 :         av_log(NULL, AV_LOG_FATAL, "%s: corrupt input packet in stream %d\n", is->url, pkt.stream_index);
    4299           0 :         exit_program(1);
    4300             :     }
    4301             : 
    4302      389220 :     if (debug_ts) {
    4303           0 :         av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
    4304             :                "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:%s off_time:%s\n",
    4305           0 :                ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
    4306           0 :                av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
    4307           0 :                av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
    4308           0 :                av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
    4309           0 :                av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
    4310           0 :                av_ts2str(input_files[ist->file_index]->ts_offset),
    4311           0 :                av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
    4312             :     }
    4313             : 
    4314      389220 :     if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
    4315             :         int64_t stime, stime2;
    4316             :         // Correcting starttime based on the enabled streams
    4317             :         // FIXME this ideally should be done before the first use of starttime but we do not know which are the enabled streams at that point.
    4318             :         //       so we instead do it here as part of discontinuity handling
    4319         234 :         if (   ist->next_dts == AV_NOPTS_VALUE
    4320         234 :             && ifile->ts_offset == -is->start_time
    4321         232 :             && (is->iformat->flags & AVFMT_TS_DISCONT)) {
    4322          43 :             int64_t new_start_time = INT64_MAX;
    4323         119 :             for (i=0; i<is->nb_streams; i++) {
    4324          76 :                 AVStream *st = is->streams[i];
    4325          76 :                 if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
    4326          15 :                     continue;
    4327          61 :                 new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
    4328             :             }
    4329          43 :             if (new_start_time > is->start_time) {
    4330           3 :                 av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
    4331           3 :                 ifile->ts_offset = -new_start_time;
    4332             :             }
    4333             :         }
    4334             : 
    4335         234 :         stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
    4336         234 :         stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
    4337         234 :         ist->wrap_correction_done = 1;
    4338             : 
    4339         234 :         if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
    4340           0 :             pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
    4341           0 :             ist->wrap_correction_done = 0;
    4342             :         }
    4343         234 :         if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
    4344           0 :             pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
    4345           0 :             ist->wrap_correction_done = 0;
    4346             :         }
    4347             :     }
    4348             : 
    4349             :     /* add the stream-global side data to the first packet */
    4350      389220 :     if (ist->nb_packets == 1) {
    4351        5936 :         for (i = 0; i < ist->st->nb_side_data; i++) {
    4352         220 :             AVPacketSideData *src_sd = &ist->st->side_data[i];
    4353             :             uint8_t *dst_data;
    4354             : 
    4355         220 :             if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
    4356           1 :                 continue;
    4357             : 
    4358         219 :             if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
    4359           0 :                 continue;
    4360             : 
    4361         219 :             dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
    4362         219 :             if (!dst_data)
    4363           0 :                 exit_program(1);
    4364             : 
    4365         219 :             memcpy(dst_data, src_sd->data, src_sd->size);
    4366             :         }
    4367             :     }
    4368             : 
    4369      389220 :     if (pkt.dts != AV_NOPTS_VALUE)
    4370      353568 :         pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
    4371      389220 :     if (pkt.pts != AV_NOPTS_VALUE)
    4372      351474 :         pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
    4373             : 
    4374      389220 :     if (pkt.pts != AV_NOPTS_VALUE)
    4375      351474 :         pkt.pts *= ist->ts_scale;
    4376      389220 :     if (pkt.dts != AV_NOPTS_VALUE)
    4377      353568 :         pkt.dts *= ist->ts_scale;
    4378             : 
    4379      389220 :     pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
    4380      667906 :     if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
    4381      666240 :          ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
    4382      351904 :         pkt_dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
    4383        5647 :         && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
    4384          80 :         int64_t delta   = pkt_dts - ifile->last_ts;
    4385         160 :         if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
    4386          80 :             delta >  1LL*dts_delta_threshold*AV_TIME_BASE){
    4387           0 :             ifile->ts_offset -= delta;
    4388           0 :             av_log(NULL, AV_LOG_DEBUG,
    4389             :                    "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
    4390             :                    delta, ifile->ts_offset);
    4391           0 :             pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
    4392           0 :             if (pkt.pts != AV_NOPTS_VALUE)
    4393           0 :                 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
    4394             :         }
    4395             :     }
    4396             : 
    4397      389220 :     duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
    4398      389220 :     if (pkt.pts != AV_NOPTS_VALUE) {
    4399      351474 :         pkt.pts += duration;
    4400      351474 :         ist->max_pts = FFMAX(pkt.pts, ist->max_pts);
    4401      351474 :         ist->min_pts = FFMIN(pkt.pts, ist->min_pts);
    4402             :     }
    4403             : 
    4404      389220 :     if (pkt.dts != AV_NOPTS_VALUE)
    4405      353568 :         pkt.dts += duration;
    4406             : 
    4407      389220 :     pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
    4408      667906 :     if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
    4409      666240 :          ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
    4410      698160 :          pkt_dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
    4411      346256 :         !copy_ts) {
    4412      346183 :         int64_t delta   = pkt_dts - ist->next_dts;
    4413      346183 :         if (is->iformat->flags & AVFMT_TS_DISCONT) {
    4414       27456 :             if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
    4415       27456 :                 delta >  1LL*dts_delta_threshold*AV_TIME_BASE ||
    4416       13728 :                 pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {
    4417           8 :                 ifile->ts_offset -= delta;
    4418           8 :                 av_log(NULL, AV_LOG_DEBUG,
    4419             :                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
    4420             :                        delta, ifile->ts_offset);
    4421           8 :                 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
    4422           8 :                 if (pkt.pts != AV_NOPTS_VALUE)
    4423           8 :                     pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
    4424             :             }
    4425             :         } else {
    4426      664910 :             if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
    4427      332455 :                  delta >  1LL*dts_error_threshold*AV_TIME_BASE) {
    4428           0 :                 av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
    4429           0 :                 pkt.dts = AV_NOPTS_VALUE;
    4430             :             }
    4431      332455 :             if (pkt.pts != AV_NOPTS_VALUE){
    4432      330424 :                 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
    4433      330424 :                 delta   = pkt_pts - ist->next_dts;
    4434      660848 :                 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
    4435      330424 :                      delta >  1LL*dts_error_threshold*AV_TIME_BASE) {
    4436           0 :                     av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
    4437           0 :                     pkt.pts = AV_NOPTS_VALUE;
    4438             :                 }
    4439             :             }
    4440             :         }
    4441             :     }
    4442             : 
    4443      389220 :     if (pkt.dts != AV_NOPTS_VALUE)
    4444      353568 :         ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
    4445             : 
    4446      389220 :     if (debug_ts) {
    4447           0 :         av_log(NULL, AV_LOG_INFO, "demuxer+ffmpeg -> ist_index:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
    4448           0 :                ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
    4449           0 :                av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
    4450           0 :                av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
    4451           0 :                av_ts2str(input_files[ist->file_index]->ts_offset),
    4452           0 :                av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
    4453             :     }
    4454             : 
    4455      389220 :     sub2video_heartbeat(ist, pkt.pts);
    4456             : 
    4457      389220 :     process_input_packet(ist, &pkt, 0);
    4458             : 
    4459      396766 : discard_packet:
    4460      396766 :     av_packet_unref(&pkt);
    4461             : 
    4462      396766 :     return 0;
    4463             : }
    4464             : 
    4465             : /**
    4466             :  * Perform a step of transcoding for the specified filter graph.
    4467             :  *
    4468             :  * @param[in]  graph     filter graph to consider
    4469             :  * @param[out] best_ist  input stream where a frame would allow to continue
    4470             :  * @return  0 for success, <0 for error
    4471             :  */
    4472      366446 : static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
    4473             : {
    4474             :     int i, ret;
    4475      366446 :     int nb_requests, nb_requests_max = 0;
    4476             :     InputFilter *ifilter;
    4477             :     InputStream *ist;
    4478             : 
    4479      366446 :     *best_ist = NULL;
    4480      366446 :     ret = avfilter_graph_request_oldest(graph->graph);
    4481      366446 :     if (ret >= 0)
    4482        1461 :         return reap_filters(0);
    4483             : 
    4484      364985 :     if (ret == AVERROR_EOF) {
    4485        3308 :         ret = reap_filters(1);
    4486        6618 :         for (i = 0; i < graph->nb_outputs; i++)
    4487        3310 :             close_output_stream(graph->outputs[i]->ost);
    4488        3308 :         return ret;
    4489             :     }
    4490      361677 :     if (ret != AVERROR(EAGAIN))
    4491           0 :         return ret;
    4492             : 
    4493      728084 :     for (i = 0; i < graph->nb_inputs; i++) {
    4494      366407 :         ifilter = graph->inputs[i];
    4495      366407 :         ist = ifilter->ist;
    4496      732814 :         if (input_files[ist->file_index]->eagain ||
    4497      366407 :             input_files[ist->file_index]->eof_reached)
    4498        1114 :             continue;
    4499      365293 :         nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
    4500      365293 :         if (nb_requests > nb_requests_max) {
    4501      361677 :             nb_requests_max = nb_requests;
    4502      361677 :             *best_ist = ist;
    4503             :         }
    4504             :     }
    4505             : 
    4506      361677 :     if (!*best_ist)
    4507           0 :         for (i = 0; i < graph->nb_outputs; i++)
    4508           0 :             graph->outputs[i]->ost->unavailable = 1;
    4509             : 
    4510      361677 :     return 0;
    4511             : }
    4512             : 
    4513             : /**
    4514             :  * Run a single step of transcoding.
    4515             :  *
    4516             :  * @return  0 for success, <0 for error
    4517             :  */
    4518     1468276 : static int transcode_step(void)
    4519             : {
    4520             :     OutputStream *ost;
    4521     1468276 :     InputStream  *ist = NULL;
    4522             :     int ret;
    4523             : 
    4524     1468276 :     ost = choose_output();
    4525     1468276 :     if (!ost) {
    4526           2 :         if (got_eagain()) {
    4527           2 :             reset_eagain();
    4528           2 :             av_usleep(10000);
    4529           2 :             return 0;
    4530             :         }
    4531           0 :         av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
    4532           0 :         return AVERROR_EOF;
    4533             :     }
    4534             : 
    4535     1468274 :     if (ost->filter && !ost->filter->graph->graph) {
    4536     1071454 :         if (ifilter_has_all_input_formats(ost->filter->graph)) {
    4537          36 :             ret = configure_filtergraph(ost->filter->graph);
    4538          36 :             if (ret < 0) {
    4539           0 :                 av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
    4540           0 :                 return ret;
    4541             :             }
    4542             :         }
    4543             :     }
    4544             : 
    4545     1468274 :     if (ost->filter && ost->filter->graph->graph) {
    4546      366446 :         if (!ost->initialized) {
    4547          36 :             char error[1024] = {0};
    4548          36 :             ret = init_output_stream(ost, error, sizeof(error));
    4549          36 :             if (ret < 0) {
    4550           0 :                 av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
    4551             :                        ost->file_index, ost->index, error);
    4552           0 :                 exit_program(1);
    4553             :             }
    4554             :         }
    4555      366446 :         if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
    4556           0 :             return ret;
    4557      728123 :         if (!ist)
    4558        4769 :             return 0;
    4559     1101828 :     } else if (ost->filter) {
    4560             :         int i;
    4561     1099830 :         for (i = 0; i < ost->filter->graph->nb_inputs; i++) {
    4562     1099830 :             InputFilter *ifilter = ost->filter->graph->inputs[i];
    4563     1099830 :             if (!ifilter->ist->got_output && !input_files[ifilter->ist->file_index]->eof_reached) {
    4564     1071418 :                 ist = ifilter->ist;
    4565     1071418 :                 break;
    4566             :             }
    4567             :         }
    4568     1071418 :         if (!ist) {
    4569           0 :             ost->inputs_done = 1;
    4570           0 :             return 0;
    4571             :         }
    4572             :     } else {
    4573       30410 :         av_assert0(ost->source_index >= 0);
    4574       30410 :         ist = input_streams[ost->source_index];
    4575             :     }
    4576             : 
    4577     1463505 :     ret = process_input(ist->file_index);
    4578     1463505 :     if (ret == AVERROR(EAGAIN)) {
    4579     1066073 :         if (input_files[ist->file_index]->eagain)
    4580     1063093 :             ost->unavailable = 1;
    4581     1066073 :         return 0;
    4582             :     }
    4583             : 
    4584      397432 :     if (ret < 0)
    4585           0 :         return ret == AVERROR_EOF ? 0 : ret;
    4586             : 
    4587      397432 :     return reap_filters(0);
    4588             : }
    4589             : 
    4590             : /*
    4591             :  * The following code is the main loop of the file converter
    4592             :  */
    4593        5617 : static int transcode(void)
    4594             : {
    4595             :     int ret, i;
    4596             :     AVFormatContext *os;
    4597             :     OutputStream *ost;
    4598             :     InputStream *ist;
    4599             :     int64_t timer_start;
    4600        5617 :     int64_t total_packets_written = 0;
    4601             : 
    4602        5617 :     ret = transcode_init();
    4603        5617 :     if (ret < 0)
    4604           0 :         goto fail;
    4605             : 
    4606        5617 :     if (stdin_interaction) {
    4607          15 :         av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
    4608             :     }
    4609             : 
    4610        5617 :     timer_start = av_gettime_relative();
    4611             : 
    4612             : #if HAVE_THREADS
    4613        5617 :     if ((ret = init_input_threads()) < 0)
    4614           0 :         goto fail;
    4615             : #endif
    4616             : 
    4617     1479510 :     while (!received_sigterm) {
    4618     1473893 :         int64_t cur_time= av_gettime_relative();
    4619             : 
    4620             :         /* if 'q' pressed, exits */
    4621     1473893 :         if (stdin_interaction)
    4622        3297 :             if (check_keyboard_interaction(cur_time) < 0)
    4623           0 :                 break;
    4624             : 
    4625             :         /* check if there's any stream where output is still needed */
    4626     1473893 :         if (!need_output()) {
    4627        5617 :             av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
    4628        5617 :             break;
    4629             :         }
    4630             : 
    4631     1468276 :         ret = transcode_step();
    4632     1468276 :         if (ret < 0 && ret != AVERROR_EOF) {
    4633           0 :             av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
    4634           0 :             break;
    4635             :         }
    4636             : 
    4637             :         /* dump report by using the output first video and audio streams */
    4638     1468276 :         print_report(0, timer_start, cur_time);
    4639             :     }
    4640             : #if HAVE_THREADS
    4641        5617 :     free_input_threads();
    4642             : #endif
    4643             : 
    4644             :     /* at the end of stream, we must flush the decoder buffers */
    4645       11575 :     for (i = 0; i < nb_input_streams; i++) {
    4646        5958 :         ist = input_streams[i];
    4647        5958 :         if (!input_files[ist->file_index]->eof_reached) {
    4648        2713 :             process_input_packet(ist, NULL, 0);
    4649             :         }
    4650             :     }
    4651        5617 :     flush_encoders();
    4652             : 
    4653        5617 :     term_exit();
    4654             : 
    4655             :     /* write the trailer if needed and close file */
    4656       11235 :     for (i = 0; i < nb_output_files; i++) {
    4657        5618 :         os = output_files[i]->ctx;
    4658        5618 :         if (!output_files[i]->header_written) {
    4659           0 :             av_log(NULL, AV_LOG_ERROR,
    4660             :                    "Nothing was written into output file %d (%s), because "
    4661             :                    "at least one of its streams received no packets.\n",
    4662             :                    i, os->url);
    4663           0 :             continue;
    4664             :         }
    4665        5618 :         if ((ret = av_write_trailer(os)) < 0) {
    4666           0 :             av_log(NULL, AV_LOG_ERROR, "Error writing trailer of %s: %s\n", os->url, av_err2str(ret));
    4667           0 :             if (exit_on_error)
    4668           0 :                 exit_program(1);
    4669             :         }
    4670             :     }
    4671             : 
    4672             :     /* dump report by using the first video and audio streams */
    4673        5617 :     print_report(1, timer_start, av_gettime_relative());
    4674             : 
    4675             :     /* close each encoder */
    4676       11373 :     for (i = 0; i < nb_output_streams; i++) {
    4677        5756 :         ost = output_streams[i];
    4678        5756 :         if (ost->encoding_needed) {
    4679        5506 :             av_freep(&ost->enc_ctx->stats_in);
    4680             :         }
    4681        5756 :         total_packets_written += ost->packets_written;
    4682             :     }
    4683             : 
    4684        5617 :     if (!total_packets_written && (abort_on_flags & ABORT_ON_FLAG_EMPTY_OUTPUT)) {
    4685           0 :         av_log(NULL, AV_LOG_FATAL, "Empty output\n");
    4686           0 :         exit_program(1);
    4687             :     }
    4688             : 
    4689             :     /* close each decoder */
    4690       11575 :     for (i = 0; i < nb_input_streams; i++) {
    4691        5958 :         ist = input_streams[i];
    4692        5958 :         if (ist->decoding_needed) {
    4693        5487 :             avcodec_close(ist->dec_ctx);
    4694        5487 :             if (ist->hwaccel_uninit)
    4695           0 :                 ist->hwaccel_uninit(ist->dec_ctx);
    4696             :         }
    4697             :     }
    4698             : 
    4699        5617 :     av_buffer_unref(&hw_device_ctx);
    4700        5617 :     hw_device_free_all();
    4701             : 
    4702             :     /* finished ! */
    4703        5617 :     ret = 0;
    4704             : 
    4705        5617 :  fail:
    4706             : #if HAVE_THREADS
    4707        5617 :     free_input_threads();
    4708             : #endif
    4709             : 
    4710        5617 :     if (output_streams) {
    4711       11372 :         for (i = 0; i < nb_output_streams; i++) {
    4712        5756 :             ost = output_streams[i];
    4713        5756 :             if (ost) {
    4714        5756 :                 if (ost->logfile) {
    4715           0 :                     if (fclose(ost->logfile))
    4716           0 :                         av_log(NULL, AV_LOG_ERROR,
    4717             :                                "Error closing logfile, loss of information possible: %s\n",
    4718           0 :                                av_err2str(AVERROR(errno)));
    4719           0 :                     ost->logfile = NULL;
    4720             :                 }
    4721        5756 :                 av_freep(&ost->forced_kf_pts);
    4722        5756 :                 av_freep(&ost->apad);
    4723        5756 :                 av_freep(&ost->disposition);
    4724        5756 :                 av_dict_free(&ost->encoder_opts);
    4725        5756 :                 av_dict_free(&ost->sws_dict);
    4726        5756 :                 av_dict_free(&ost->swr_opts);
    4727        5756 :                 av_dict_free(&ost->resample_opts);
    4728             :             }
    4729             :         }
    4730             :     }
    4731        5617 :     return ret;
    4732             : }
    4733             : 
    4734        5617 : static BenchmarkTimeStamps get_benchmark_time_stamps(void)
    4735             : {
    4736        5617 :     BenchmarkTimeStamps time_stamps = { av_gettime_relative() };
    4737             : #if HAVE_GETRUSAGE
    4738             :     struct rusage rusage;
    4739             : 
    4740        5617 :     getrusage(RUSAGE_SELF, &rusage);
    4741        5617 :     time_stamps.user_usec =
    4742        5617 :         (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
    4743        5617 :     time_stamps.sys_usec =
    4744        5617 :         (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
    4745             : #elif HAVE_GETPROCESSTIMES
    4746             :     HANDLE proc;
    4747             :     FILETIME c, e, k, u;
    4748             :     proc = GetCurrentProcess();
    4749             :     GetProcessTimes(proc, &c, &e, &k, &u);
    4750             :     time_stamps.user_usec =
    4751             :         ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
    4752             :     time_stamps.sys_usec =
    4753             :         ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
    4754             : #else
    4755             :     time_stamps.user_usec = time_stamps.sys_usec = 0;
    4756             : #endif
    4757        5617 :     return time_stamps;
    4758             : }
    4759             : 
    4760           0 : static int64_t getmaxrss(void)
    4761             : {
    4762             : #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
    4763             :     struct rusage rusage;
    4764           0 :     getrusage(RUSAGE_SELF, &rusage);
    4765           0 :     return (int64_t)rusage.ru_maxrss * 1024;
    4766             : #elif HAVE_GETPROCESSMEMORYINFO
    4767             :     HANDLE proc;
    4768             :     PROCESS_MEMORY_COUNTERS memcounters;
    4769             :     proc = GetCurrentProcess();
    4770             :     memcounters.cb = sizeof(memcounters);
    4771             :     GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
    4772             :     return memcounters.PeakPagefileUsage;
    4773             : #else
    4774             :     return 0;
    4775             : #endif
    4776             : }
    4777             : 
    4778           0 : static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
    4779             : {
    4780           0 : }
    4781             : 
    4782        5618 : int main(int argc, char **argv)
    4783             : {
    4784             :     int i, ret;
    4785             :     BenchmarkTimeStamps ti;
    4786             : 
    4787        5618 :     init_dynload();
    4788             : 
    4789        5618 :     register_exit(ffmpeg_cleanup);
    4790             : 
    4791        5618 :     setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
    4792             : 
    4793        5618 :     av_log_set_flags(AV_LOG_SKIP_REPEATED);
    4794        5618 :     parse_loglevel(argc, argv, options);
    4795             : 
    4796        5618 :     if(argc>1 && !strcmp(argv[1], "-d")){
    4797           0 :         run_as_daemon=1;
    4798           0 :         av_log_set_callback(log_callback_null);
    4799           0 :         argc--;
    4800           0 :         argv++;
    4801             :     }
    4802             : 
    4803             : #if CONFIG_AVDEVICE
    4804        5618 :     avdevice_register_all();
    4805             : #endif
    4806        5618 :     avformat_network_init();
    4807             : 
    4808        5618 :     show_banner(argc, argv, options);
    4809             : 
    4810             :     /* parse options and open all input/output files */
    4811        5618 :     ret = ffmpeg_parse_options(argc, argv);
    4812        5617 :     if (ret < 0)
    4813           0 :         exit_program(1);
    4814             : 
    4815        5617 :     if (nb_output_files <= 0 && nb_input_files == 0) {
    4816           0 :         show_usage();
    4817           0 :         av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
    4818           0 :         exit_program(1);
    4819             :     }
    4820             : 
    4821             :     /* file converter / grab */
    4822        5617 :     if (nb_output_files <= 0) {
    4823           0 :         av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
    4824           0 :         exit_program(1);
    4825             :     }
    4826             : 
    4827             : //     if (nb_input_files == 0) {
    4828             : //         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
    4829             : //         exit_program(1);
    4830             : //     }
    4831             : 
    4832       11235 :     for (i = 0; i < nb_output_files; i++) {
    4833        5618 :         if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
    4834        5618 :             want_sdp = 0;
    4835             :     }
    4836             : 
    4837        5617 :     current_time = ti = get_benchmark_time_stamps();
    4838        5617 :     if (transcode() < 0)
    4839           0 :         exit_program(1);
    4840        5617 :     if (do_benchmark) {
    4841             :         int64_t utime, stime, rtime;
    4842           0 :         current_time = get_benchmark_time_stamps();
    4843           0 :         utime = current_time.user_usec - ti.user_usec;
    4844           0 :         stime = current_time.sys_usec  - ti.sys_usec;
    4845           0 :         rtime = current_time.real_usec - ti.real_usec;
    4846           0 :         av_log(NULL, AV_LOG_INFO,
    4847             :                "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
    4848             :                utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
    4849             :     }
    4850        5617 :     av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
    4851             :            decode_error_stat[0], decode_error_stat[1]);
    4852        5617 :     if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
    4853           0 :         exit_program(69);
    4854             : 
    4855        5617 :     exit_program(received_nb_signals ? 255 : main_return_code);
    4856             :     return main_return_code;
    4857             : }

Generated by: LCOV version 1.13