patch_ffmpeg_ffmpeg.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (c) 2000-2003 Fabrice Bellard
00003  *
00004  * This file is part of FFmpeg.
00005  *
00006  * FFmpeg is free software; you can redistribute it and/or
00007  * modify it under the terms of the GNU Lesser General Public
00008  * License as published by the Free Software Foundation; either
00009  * version 2.1 of the License, or (at your option) any later version.
00010  *
00011  * FFmpeg is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014  * Lesser General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU Lesser General Public
00017  * License along with FFmpeg; if not, write to the Free Software
00018  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00019  */
00020 
00026 #include "config.h"
00027 #include <ctype.h>
00028 #include <string.h>
00029 #include <math.h>
00030 #include <stdlib.h>
00031 #include <errno.h>
00032 #include <limits.h>
00033 #include <stdint.h>
00034 
00035 #if HAVE_ISATTY
00036 #if HAVE_IO_H
00037 #include <io.h>
00038 #endif
00039 #if HAVE_UNISTD_H
00040 #include <unistd.h>
00041 #endif
00042 #endif
00043 
00044 #include "libavformat/avformat.h"
00045 #include "libavdevice/avdevice.h"
00046 #include "libswresample/swresample.h"
00047 #include "libavutil/opt.h"
00048 #include "libavutil/channel_layout.h"
00049 #include "libavutil/parseutils.h"
00050 #include "libavutil/samplefmt.h"
00051 #include "libavutil/fifo.h"
00052 #include "libavutil/intreadwrite.h"
00053 #include "libavutil/dict.h"
00054 #include "libavutil/mathematics.h"
00055 #include "libavutil/pixdesc.h"
00056 #include "libavutil/avstring.h"
00057 #include "libavutil/libm.h"
00058 #include "libavutil/imgutils.h"
00059 #include "libavutil/timestamp.h"
00060 #include "libavutil/bprint.h"
00061 #include "libavutil/time.h"
00062 #include "libavutil/threadmessage.h"
00063 #include "libavformat/os_support.h"
00064 
00065 #include "libavformat/ffm.h" // not public API
00066 
00067 # include "libavfilter/avcodec.h"
00068 # include "libavfilter/avfilter.h"
00069 # include "libavfilter/buffersrc.h"
00070 # include "libavfilter/buffersink.h"
00071 
00072 #if HAVE_SYS_RESOURCE_H
00073 #include <sys/time.h>
00074 #include <sys/types.h>
00075 #include <sys/resource.h>
00076 #elif HAVE_GETPROCESSTIMES
00077 #include <windows.h>
00078 #endif
00079 #if HAVE_GETPROCESSMEMORYINFO
00080 #include <windows.h>
00081 #include <psapi.h>
00082 #endif
00083 
00084 #if HAVE_SYS_SELECT_H
00085 #include <sys/select.h>
00086 #endif
00087 
00088 #if HAVE_TERMIOS_H
00089 #include <fcntl.h>
00090 #include <sys/ioctl.h>
00091 #include <sys/time.h>
00092 #include <termios.h>
00093 #elif HAVE_KBHIT
00094 #include <conio.h>
00095 #endif
00096 
00097 #if HAVE_PTHREADS
00098 #include <pthread.h>
00099 #endif
00100 
00101 #include <time.h>
00102 
00103 #include "ffmpeg.h"
00104 #include "cmdutils.h"
00105 
00106 #include "libavutil/avassert.h"
00107 
00108 const char program_name[] = "ffmpeg";
00109 const int program_birth_year = 2000;
00110 
00111 static FILE *vstats_file;
00112 
00113 const char *const forced_keyframes_const_names[] = {
00114     "n",
00115     "n_forced",
00116     "prev_forced_n",
00117     "prev_forced_t",
00118     "t",
00119     NULL
00120 };
00121 
00122 static void do_video_stats(OutputStream *ost, int frame_size);
00123 static int64_t getutime(void);
00124 static int64_t getmaxrss(void);
00125 
00126 static int run_as_daemon  = 0;
00127 static int nb_frames_dup = 0;
00128 static int nb_frames_drop = 0;
00129 static int64_t decode_error_stat[2];
00130 
00131 static int current_time;
00132 AVIOContext *progress_avio = NULL;
00133 
00134 static uint8_t *subtitle_out;
00135 
00136 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
00137 
00138 InputStream **input_streams = NULL;
00139 int        nb_input_streams = 0;
00140 InputFile   **input_files   = NULL;
00141 int        nb_input_files   = 0;
00142 
00143 OutputStream **output_streams = NULL;
00144 int         nb_output_streams = 0;
00145 OutputFile   **output_files   = NULL;
00146 int         nb_output_files   = 0;
00147 
00148 FilterGraph **filtergraphs;
00149 int        nb_filtergraphs;
00150 
00151 #if HAVE_TERMIOS_H
00152 
00153 /* init terminal so that we can grab keys */
00154 static struct termios oldtty;
00155 static int restore_tty;
00156 #endif
00157 
00158 static void free_input_threads(void);
00159 
00160 
00161 /* sub2video hack:
00162    Convert subtitles to video with alpha to insert them in filter graphs.
00163    This is a temporary solution until libavfilter gets real subtitles support.
00164  */
00165 
00166 static int sub2video_get_blank_frame(InputStream *ist)
00167 {
00168     int ret;
00169     AVFrame *frame = ist->sub2video.frame;
00170 
00171     av_frame_unref(frame);
00172     ist->sub2video.frame->width  = ist->sub2video.w;
00173     ist->sub2video.frame->height = ist->sub2video.h;
00174     ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
00175     if ((ret = av_frame_get_buffer(frame, 32)) < 0)
00176         return ret;
00177     memset(frame->data[0], 0, frame->height * frame->linesize[0]);
00178     return 0;
00179 }
00180 
00181 static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
00182                                 AVSubtitleRect *r)
00183 {
00184     uint32_t *pal, *dst2;
00185     uint8_t *src, *src2;
00186     int x, y;
00187 
00188     if (r->type != SUBTITLE_BITMAP) {
00189         av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
00190         return;
00191     }
00192     if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
00193         av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");
00194         return;
00195     }
00196 
00197     dst += r->y * dst_linesize + r->x * 4;
00198     src = r->pict.data[0];
00199     pal = (uint32_t *)r->pict.data[1];
00200     for (y = 0; y < r->h; y++) {
00201         dst2 = (uint32_t *)dst;
00202         src2 = src;
00203         for (x = 0; x < r->w; x++)
00204             *(dst2++) = pal[*(src2++)];
00205         dst += dst_linesize;
00206         src += r->pict.linesize[0];
00207     }
00208 }
00209 
00210 static void sub2video_push_ref(InputStream *ist, int64_t pts)
00211 {
00212     AVFrame *frame = ist->sub2video.frame;
00213     int i;
00214 
00215     av_assert1(frame->data[0]);
00216     ist->sub2video.last_pts = frame->pts = pts;
00217     for (i = 0; i < ist->nb_filters; i++)
00218         av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
00219                                      AV_BUFFERSRC_FLAG_KEEP_REF |
00220                                      AV_BUFFERSRC_FLAG_PUSH);
00221 }
00222 
00223 static void sub2video_update(InputStream *ist, AVSubtitle *sub)
00224 {
00225     int w = ist->sub2video.w, h = ist->sub2video.h;
00226     AVFrame *frame = ist->sub2video.frame;
00227     int8_t *dst;
00228     int     dst_linesize;
00229     int num_rects, i;
00230     int64_t pts, end_pts;
00231 
00232     if (!frame)
00233         return;
00234     if (sub) {
00235         pts       = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
00236                                  AV_TIME_BASE_Q, ist->st->time_base);
00237         end_pts   = av_rescale_q(sub->pts + sub->end_display_time   * 1000LL,
00238                                  AV_TIME_BASE_Q, ist->st->time_base);
00239         num_rects = sub->num_rects;
00240     } else {
00241         pts       = ist->sub2video.end_pts;
00242         end_pts   = INT64_MAX;
00243         num_rects = 0;
00244     }
00245     if (sub2video_get_blank_frame(ist) < 0) {
00246         av_log(ist->dec_ctx, AV_LOG_ERROR,
00247                "Impossible to get a blank canvas.\n");
00248         return;
00249     }
00250     dst          = frame->data    [0];
00251     dst_linesize = frame->linesize[0];
00252     for (i = 0; i < num_rects; i++)
00253         sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);
00254     sub2video_push_ref(ist, pts);
00255     ist->sub2video.end_pts = end_pts;
00256 }
00257 
00258 static void sub2video_heartbeat(InputStream *ist, int64_t pts)
00259 {
00260     InputFile *infile = input_files[ist->file_index];
00261     int i, j, nb_reqs;
00262     int64_t pts2;
00263 
00264     /* When a frame is read from a file, examine all sub2video streams in
00265        the same file and send the sub2video frame again. Otherwise, decoded
00266        video frames could be accumulating in the filter graph while a filter
00267        (possibly overlay) is desperately waiting for a subtitle frame. */
00268     for (i = 0; i < infile->nb_streams; i++) {
00269         InputStream *ist2 = input_streams[infile->ist_index + i];
00270         if (!ist2->sub2video.frame)
00271             continue;
00272         /* subtitles seem to be usually muxed ahead of other streams;
00273            if not, subtracting a larger time here is necessary */
00274         pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
00275         /* do not send the heartbeat frame if the subtitle is already ahead */
00276         if (pts2 <= ist2->sub2video.last_pts)
00277             continue;
00278         if (pts2 >= ist2->sub2video.end_pts || !ist2->sub2video.frame->data[0])
00279             sub2video_update(ist2, NULL);
00280         for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
00281             nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
00282         if (nb_reqs)
00283             sub2video_push_ref(ist2, pts2);
00284     }
00285 }
00286 
00287 static void sub2video_flush(InputStream *ist)
00288 {
00289     int i;
00290 
00291     if (ist->sub2video.end_pts < INT64_MAX)
00292         sub2video_update(ist, NULL);
00293     for (i = 0; i < ist->nb_filters; i++)
00294         av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
00295 }
00296 
00297 /* end of sub2video hack */
00298 
00299 static void term_exit_sigsafe(void)
00300 {
00301 #if HAVE_TERMIOS_H
00302     if(restore_tty)
00303         tcsetattr (0, TCSANOW, &oldtty);
00304 #endif
00305 }
00306 
00307 void term_exit(void)
00308 {
00309     av_log(NULL, AV_LOG_QUIET, "%s", "");
00310     term_exit_sigsafe();
00311 }
00312 
00313 static volatile int received_sigterm = 0;
00314 static volatile int received_nb_signals = 0;
00315 static volatile int transcode_init_done = 0;
00316 static int main_return_code = 0;
00317 static int mainThreadId = 0;
00318 
00319 static void
00320 sigterm_handler(int sig)
00321 {
00322     if (gettid() != mainThreadId) return;
00323     received_sigterm = sig;
00324     received_nb_signals++;
00325     term_exit_sigsafe();
00326     if(received_nb_signals > 3)
00327         exit(123);
00328 }
00329 
00330 void term_init(void)
00331 {
00332 #if HAVE_TERMIOS_H
00333     if(!run_as_daemon){
00334         struct termios tty;
00335         int istty = 1;
00336 #if HAVE_ISATTY
00337         istty = isatty(0) && isatty(2);
00338 #endif
00339         if (istty && tcgetattr (0, &tty) == 0) {
00340             oldtty = tty;
00341             restore_tty = 1;
00342 
00343             tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
00344                              |INLCR|IGNCR|ICRNL|IXON);
00345             tty.c_oflag |= OPOST;
00346             tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
00347             tty.c_cflag &= ~(CSIZE|PARENB);
00348             tty.c_cflag |= CS8;
00349             tty.c_cc[VMIN] = 1;
00350             tty.c_cc[VTIME] = 0;
00351 
00352             tcsetattr (0, TCSANOW, &tty);
00353         }
00354         signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
00355     }
00356 #endif
00357     avformat_network_deinit();
00358 
00359     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
00360     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
00361     signal(SIGHUP, sigterm_handler); /* Session Exit (ANSI).  */
00362 #ifdef SIGXCPU
00363     signal(SIGXCPU, sigterm_handler);
00364 #endif
00365 }
00366 
00367 /* read a key without blocking */
00368 static int read_key(void)
00369 {
00370     unsigned char ch;
00371 #if HAVE_TERMIOS_H
00372     int n = 1;
00373     struct timeval tv;
00374     fd_set rfds;
00375 
00376     FD_ZERO(&rfds);
00377     FD_SET(0, &rfds);
00378     tv.tv_sec = 0;
00379     tv.tv_usec = 0;
00380     n = select(1, &rfds, NULL, NULL, &tv);
00381     if (n > 0) {
00382         n = read(0, &ch, 1);
00383         if (n == 1)
00384             return ch;
00385 
00386         return n;
00387     }
00388 #elif HAVE_KBHIT
00389 #    if HAVE_PEEKNAMEDPIPE
00390     static int is_pipe;
00391     static HANDLE input_handle;
00392     DWORD dw, nchars;
00393     if(!input_handle){
00394         input_handle = GetStdHandle(STD_INPUT_HANDLE);
00395         is_pipe = !GetConsoleMode(input_handle, &dw);
00396     }
00397 
00398     if (stdin->_cnt > 0) {
00399         read(0, &ch, 1);
00400         return ch;
00401     }
00402     if (is_pipe) {
00403         /* When running under a GUI, you will end here. */
00404         if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
00405             // input pipe may have been closed by the program that ran ffmpeg
00406             return -1;
00407         }
00408         //Read it
00409         if(nchars != 0) {
00410             read(0, &ch, 1);
00411             return ch;
00412         }else{
00413             return -1;
00414         }
00415     }
00416 #    endif
00417     if(kbhit())
00418         return(getch());
00419 #endif
00420     return -1;
00421 }
00422 
00423 static int decode_interrupt_cb(void *ctx)
00424 {
00425     return received_nb_signals > transcode_init_done;
00426 }
00427 
00428 const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
00429 
00430 static void ffmpeg_cleanup(int ret)
00431 {
00432     int i, j;
00433 
00434     if (do_benchmark) {
00435         int maxrss = getmaxrss() / 1024;
00436         printf("bench: maxrss=%ikB\n", maxrss);
00437     }
00438 
00439     for (i = 0; i < nb_filtergraphs; i++) {
00440         FilterGraph *fg = filtergraphs[i];
00441         avfilter_graph_free(&fg->graph);
00442         for (j = 0; j < fg->nb_inputs; j++) {
00443             av_freep(&fg->inputs[j]->name);
00444             av_freep(&fg->inputs[j]);
00445         }
00446         av_freep(&fg->inputs);
00447         for (j = 0; j < fg->nb_outputs; j++) {
00448             av_freep(&fg->outputs[j]->name);
00449             av_freep(&fg->outputs[j]);
00450         }
00451         av_freep(&fg->outputs);
00452         av_freep(&fg->graph_desc);
00453 
00454         av_freep(&filtergraphs[i]);
00455     }
00456     av_freep(&filtergraphs);
00457 
00458     av_freep(&subtitle_out);
00459 
00460     /* close files */
00461     for (i = 0; i < nb_output_files; i++) {
00462         OutputFile *of = output_files[i];
00463         AVFormatContext *s = of->ctx;
00464         if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE) && s->pb)
00465             avio_close(s->pb);
00466         avformat_free_context(s);
00467         av_dict_free(&of->opts);
00468 
00469         av_freep(&output_files[i]);
00470     }
00471     for (i = 0; i < nb_output_streams; i++) {
00472         OutputStream *ost = output_streams[i];
00473         AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
00474         while (bsfc) {
00475             AVBitStreamFilterContext *next = bsfc->next;
00476             av_bitstream_filter_close(bsfc);
00477             bsfc = next;
00478         }
00479         ost->bitstream_filters = NULL;
00480         av_frame_free(&ost->filtered_frame);
00481 
00482         av_parser_close(ost->parser);
00483 
00484         av_freep(&ost->forced_keyframes);
00485         av_expr_free(ost->forced_keyframes_pexpr);
00486         av_freep(&ost->avfilter);
00487         av_freep(&ost->logfile_prefix);
00488 
00489         av_freep(&ost->audio_channels_map);
00490         ost->audio_channels_mapped = 0;
00491 
00492         avcodec_free_context(&ost->enc_ctx);
00493 
00494         av_freep(&output_streams[i]);
00495     }
00496 #if HAVE_PTHREADS
00497     free_input_threads();
00498 #endif
00499     for (i = 0; i < nb_input_files; i++) {
00500         avformat_close_input(&input_files[i]->ctx);
00501         av_freep(&input_files[i]);
00502     }
00503     for (i = 0; i < nb_input_streams; i++) {
00504         InputStream *ist = input_streams[i];
00505 
00506         av_frame_free(&ist->decoded_frame);
00507         av_frame_free(&ist->filter_frame);
00508         av_dict_free(&ist->decoder_opts);
00509         avsubtitle_free(&ist->prev_sub.subtitle);
00510         av_frame_free(&ist->sub2video.frame);
00511         av_freep(&ist->filters);
00512         av_freep(&ist->hwaccel_device);
00513 
00514         avcodec_free_context(&ist->dec_ctx);
00515 
00516         av_freep(&input_streams[i]);
00517     }
00518 
00519     if (vstats_file)
00520         fclose(vstats_file);
00521     av_free(vstats_filename);
00522 
00523     av_freep(&input_streams);
00524     av_freep(&input_files);
00525     av_freep(&output_streams);
00526     av_freep(&output_files);
00527 
00528     uninit_opts();
00529 
00530     avformat_network_deinit();
00531 
00532     if (received_sigterm) {
00533         av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
00534                (int) received_sigterm);
00535     } else if (ret && transcode_init_done) {
00536         av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
00537     }
00538     term_exit();
00539 }
00540 
00541 void remove_avoptions(AVDictionary **a, AVDictionary *b)
00542 {
00543     AVDictionaryEntry *t = NULL;
00544 
00545     while ((t = av_dict_get(b, "", t, AV_DICT_IGNORE_SUFFIX))) {
00546         av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
00547     }
00548 }
00549 
00550 void assert_avoptions(AVDictionary *m)
00551 {
00552     AVDictionaryEntry *t;
00553     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
00554         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
00555         exit_program(1);
00556     }
00557 }
00558 
00559 static void abort_codec_experimental(AVCodec *c, int encoder)
00560 {
00561     exit_program(1);
00562 }
00563 
00564 static void update_benchmark(const char *fmt, ...)
00565 {
00566     if (do_benchmark_all) {
00567         int64_t t = getutime();
00568         va_list va;
00569         char buf[1024];
00570 
00571         if (fmt) {
00572             va_start(va, fmt);
00573             vsnprintf(buf, sizeof(buf), fmt, va);
00574             va_end(va);
00575             printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
00576         }
00577         current_time = t;
00578     }
00579 }
00580 
00581 static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
00582 {
00583     int i;
00584     for (i = 0; i < nb_output_streams; i++) {
00585         OutputStream *ost2 = output_streams[i];
00586         ost2->finished |= ost == ost2 ? this_stream : others;
00587     }
00588 }
00589 
00590 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
00591 {
00592     AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
00593     AVCodecContext          *avctx = ost->st->codec;
00594     int ret;
00595 
00596     if (!ost->st->codec->extradata_size && ost->enc_ctx->extradata_size) {
00597         ost->st->codec->extradata = av_mallocz(ost->enc_ctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
00598         if (ost->st->codec->extradata) {
00599             memcpy(ost->st->codec->extradata, ost->enc_ctx->extradata, ost->enc_ctx->extradata_size);
00600             ost->st->codec->extradata_size = ost->enc_ctx->extradata_size;
00601         }
00602     }
00603 
00604     if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
00605         (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
00606         pkt->pts = pkt->dts = AV_NOPTS_VALUE;
00607 
00608     /*
00609      * Audio encoders may split the packets --  #frames in != #packets out.
00610      * But there is no reordering, so we can limit the number of output packets
00611      * by simply dropping them here.
00612      * Counting encoded video frames needs to be done separately because of
00613      * reordering, see do_video_out()
00614      */
00615     if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
00616         if (ost->frame_number >= ost->max_frames) {
00617             av_free_packet(pkt);
00618             return;
00619         }
00620         ost->frame_number++;
00621     }
00622 
00623     if (bsfc)
00624         av_packet_split_side_data(pkt);
00625 
00626     while (bsfc) {
00627         AVPacket new_pkt = *pkt;
00628         int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
00629                                            &new_pkt.data, &new_pkt.size,
00630                                            pkt->data, pkt->size,
00631                                            pkt->flags & AV_PKT_FLAG_KEY);
00632         if(a == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
00633             uint8_t *t = av_malloc(new_pkt.size + FF_INPUT_BUFFER_PADDING_SIZE); //the new should be a subset of the old so cannot overflow
00634             if(t) {
00635                 memcpy(t, new_pkt.data, new_pkt.size);
00636                 memset(t + new_pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
00637                 new_pkt.data = t;
00638                 new_pkt.buf = NULL;
00639                 a = 1;
00640             } else
00641                 a = AVERROR(ENOMEM);
00642         }
00643         if (a > 0) {
00644             pkt->side_data = NULL;
00645             pkt->side_data_elems = 0;
00646             av_free_packet(pkt);
00647             new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
00648                                            av_buffer_default_free, NULL, 0);
00649             if (!new_pkt.buf)
00650                 exit_program(1);
00651         } else if (a < 0) {
00652             av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
00653                    bsfc->filter->name, pkt->stream_index,
00654                    avctx->codec ? avctx->codec->name : "copy");
00655             print_error("", a);
00656             if (exit_on_error)
00657                 exit_program(1);
00658         }
00659         *pkt = new_pkt;
00660 
00661         bsfc = bsfc->next;
00662     }
00663 
00664     if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
00665      if(
00666         (avctx->codec_type == AVMEDIA_TYPE_AUDIO || avctx->codec_type == AVMEDIA_TYPE_VIDEO) &&
00667         pkt->dts != AV_NOPTS_VALUE &&
00668         ost->last_mux_dts != AV_NOPTS_VALUE) {
00669       int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
00670       if (pkt->dts < max) {
00671         int loglevel = max - pkt->dts > 2 || avctx->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
00672         av_log(s, loglevel, "Non-monotonous DTS in output stream "
00673                "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
00674                ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
00675         if (exit_on_error) {
00676             av_log(NULL, AV_LOG_FATAL, "aborting.\n");
00677             exit_program(1);
00678         }
00679         av_log(s, loglevel, "changing to %"PRId64". This may result "
00680                "in incorrect timestamps in the output file.\n",
00681                max);
00682         if(pkt->pts >= pkt->dts)
00683             pkt->pts = FFMAX(pkt->pts, max);
00684         pkt->dts = max;
00685       }
00686      }
00687         if (pkt->dts != AV_NOPTS_VALUE &&
00688             pkt->pts != AV_NOPTS_VALUE &&
00689             pkt->dts > pkt->pts) {
00690             av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d\n",
00691                    pkt->dts, pkt->pts,
00692                    ost->file_index, ost->st->index);
00693             pkt->pts = AV_NOPTS_VALUE;
00694             pkt->dts = AV_NOPTS_VALUE;
00695         }
00696     }
00697     ost->last_mux_dts = pkt->dts;
00698 
00699     ost->data_size += pkt->size;
00700     ost->packets_written++;
00701 
00702     pkt->stream_index = ost->index;
00703 
00704     if (debug_ts) {
00705         av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
00706                 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
00707                 av_get_media_type_string(ost->enc_ctx->codec_type),
00708                 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
00709                 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
00710                 pkt->size
00711               );
00712     }
00713 
00714     ret = av_interleaved_write_frame(s, pkt);
00715     if (ret < 0) {
00716         print_error("av_interleaved_write_frame()", ret);
00717         main_return_code = 1;
00718         close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);
00719     }
00720     av_free_packet(pkt);
00721 }
00722 
00723 static void close_output_stream(OutputStream *ost)
00724 {
00725     OutputFile *of = output_files[ost->file_index];
00726 
00727     ost->finished |= ENCODER_FINISHED;
00728     if (of->shortest) {
00729         int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, AV_TIME_BASE_Q);
00730         of->recording_time = FFMIN(of->recording_time, end);
00731     }
00732 }
00733 
00734 static int check_recording_time(OutputStream *ost)
00735 {
00736     OutputFile *of = output_files[ost->file_index];
00737 
00738     if (of->recording_time != INT64_MAX &&
00739         av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
00740                       AV_TIME_BASE_Q) >= 0) {
00741         close_output_stream(ost);
00742         return 0;
00743     }
00744     return 1;
00745 }
00746 
00747 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
00748                          AVFrame *frame)
00749 {
00750     AVCodecContext *enc = ost->enc_ctx;
00751     AVPacket pkt;
00752     int got_packet = 0;
00753 
00754     av_init_packet(&pkt);
00755     pkt.data = NULL;
00756     pkt.size = 0;
00757 
00758     if (!check_recording_time(ost))
00759         return;
00760 
00761     if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
00762         frame->pts = ost->sync_opts;
00763     ost->sync_opts = frame->pts + frame->nb_samples;
00764     ost->samples_encoded += frame->nb_samples;
00765     ost->frames_encoded++;
00766 
00767     av_assert0(pkt.size || !pkt.data);
00768     update_benchmark(NULL);
00769     if (debug_ts) {
00770         av_log(NULL, AV_LOG_INFO, "encoder <- type:audio "
00771                "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
00772                av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
00773                enc->time_base.num, enc->time_base.den);
00774     }
00775 
00776     if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
00777         av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
00778         exit_program(1);
00779     }
00780     update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
00781 
00782     if (got_packet) {
00783         av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
00784 
00785         if (debug_ts) {
00786             av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
00787                    "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
00788                    av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
00789                    av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
00790         }
00791 
00792         write_frame(s, &pkt, ost);
00793     }
00794 }
00795 
00796 static void do_subtitle_out(AVFormatContext *s,
00797                             OutputStream *ost,
00798                             InputStream *ist,
00799                             AVSubtitle *sub)
00800 {
00801     int subtitle_out_max_size = 1024 * 1024;
00802     int subtitle_out_size, nb, i;
00803     AVCodecContext *enc;
00804     AVPacket pkt;
00805     int64_t pts;
00806 
00807     if (sub->pts == AV_NOPTS_VALUE) {
00808         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
00809         if (exit_on_error)
00810             exit_program(1);
00811         return;
00812     }
00813 
00814     enc = ost->enc_ctx;
00815 
00816     if (!subtitle_out) {
00817         subtitle_out = av_malloc(subtitle_out_max_size);
00818     }
00819 
00820     /* Note: DVB subtitle need one packet to draw them and one other
00821        packet to clear them */
00822     /* XXX: signal it in the codec context ? */
00823     if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
00824         nb = 2;
00825     else
00826         nb = 1;
00827 
00828     /* shift timestamp to honor -ss and make check_recording_time() work with -t */
00829     pts = sub->pts;
00830     if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
00831         pts -= output_files[ost->file_index]->start_time;
00832     for (i = 0; i < nb; i++) {
00833         unsigned save_num_rects = sub->num_rects;
00834 
00835         ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
00836         if (!check_recording_time(ost))
00837             return;
00838 
00839         sub->pts = pts;
00840         // start_display_time is required to be 0
00841         sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
00842         sub->end_display_time  -= sub->start_display_time;
00843         sub->start_display_time = 0;
00844         if (i == 1)
00845             sub->num_rects = 0;
00846 
00847         ost->frames_encoded++;
00848 
00849         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
00850                                                     subtitle_out_max_size, sub);
00851         if (i == 1)
00852             sub->num_rects = save_num_rects;
00853         if (subtitle_out_size < 0) {
00854             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
00855             exit_program(1);
00856         }
00857 
00858         av_init_packet(&pkt);
00859         pkt.data = subtitle_out;
00860         pkt.size = subtitle_out_size;
00861         pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
00862         pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
00863         if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
00864             /* XXX: the pts correction is handled here. Maybe handling
00865                it in the codec would be better */
00866             if (i == 0)
00867                 pkt.pts += 90 * sub->start_display_time;
00868             else
00869                 pkt.pts += 90 * sub->end_display_time;
00870         }
00871         pkt.dts = pkt.pts;
00872         write_frame(s, &pkt, ost);
00873     }
00874 }
00875 
00876 static void do_video_out(AVFormatContext *s,
00877                          OutputStream *ost,
00878                          AVFrame *in_picture)
00879 {
00880     int ret, format_video_sync;
00881     AVPacket pkt;
00882     AVCodecContext *enc = ost->enc_ctx;
00883     AVCodecContext *mux_enc = ost->st->codec;
00884     int nb_frames, i;
00885     double sync_ipts, delta;
00886     double duration = 0;
00887     int frame_size = 0;
00888     InputStream *ist = NULL;
00889 
00890     if (ost->source_index >= 0)
00891         ist = input_streams[ost->source_index];
00892 
00893     if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
00894         duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
00895 
00896     sync_ipts = in_picture->pts;
00897     delta = sync_ipts - ost->sync_opts + duration;
00898 
00899     /* by default, we output a single frame */
00900     nb_frames = 1;
00901 
00902     format_video_sync = video_sync_method;
00903     if (format_video_sync == VSYNC_AUTO) {
00904         if(!strcmp(s->oformat->name, "avi")) {
00905             format_video_sync = VSYNC_VFR;
00906         } else
00907             format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
00908         if (   ist
00909             && format_video_sync == VSYNC_CFR
00910             && input_files[ist->file_index]->ctx->nb_streams == 1
00911             && input_files[ist->file_index]->input_ts_offset == 0) {
00912             format_video_sync = VSYNC_VSCFR;
00913         }
00914         if (format_video_sync == VSYNC_CFR && copy_ts) {
00915             format_video_sync = VSYNC_VSCFR;
00916         }
00917     }
00918 
00919     switch (format_video_sync) {
00920     case VSYNC_VSCFR:
00921         if (ost->frame_number == 0 && delta - duration >= 0.5) {
00922             av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta - duration));
00923             delta = duration;
00924             ost->sync_opts = lrint(sync_ipts);
00925         }
00926     case VSYNC_CFR:
00927         // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
00928         if (delta < -1.1)
00929             nb_frames = 0;
00930         else if (delta > 1.1)
00931             nb_frames = lrintf(delta);
00932         break;
00933     case VSYNC_VFR:
00934         if (delta <= -0.6)
00935             nb_frames = 0;
00936         else if (delta > 0.6)
00937             ost->sync_opts = lrint(sync_ipts);
00938         break;
00939     case VSYNC_DROP:
00940     case VSYNC_PASSTHROUGH:
00941         ost->sync_opts = lrint(sync_ipts);
00942         break;
00943     default:
00944         av_assert0(0);
00945     }
00946 
00947     nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
00948     if (nb_frames == 0) {
00949         nb_frames_drop++;
00950         av_log(NULL, AV_LOG_VERBOSE,
00951                "*** dropping frame %d from stream %d at ts %"PRId64"\n",
00952                ost->frame_number, ost->st->index, in_picture->pts);
00953         return;
00954     } else if (nb_frames > 1) {
00955         if (nb_frames > dts_error_threshold * 30) {
00956             av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
00957             nb_frames_drop++;
00958             return;
00959         }
00960         nb_frames_dup += nb_frames - 1;
00961         av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
00962     }
00963 
00964   /* duplicates frame if needed */
00965   for (i = 0; i < nb_frames; i++) {
00966     av_init_packet(&pkt);
00967     pkt.data = NULL;
00968     pkt.size = 0;
00969 
00970     in_picture->pts = ost->sync_opts;
00971 
00972 #if 1
00973     if (!check_recording_time(ost))
00974 #else
00975     if (ost->frame_number >= ost->max_frames)
00976 #endif
00977         return;
00978 
00979     if (s->oformat->flags & AVFMT_RAWPICTURE &&
00980         enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
00981         /* raw pictures are written as AVPicture structure to
00982            avoid any copies. We support temporarily the older
00983            method. */
00984         mux_enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
00985         mux_enc->coded_frame->top_field_first  = in_picture->top_field_first;
00986         if (mux_enc->coded_frame->interlaced_frame)
00987             mux_enc->field_order = mux_enc->coded_frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
00988         else
00989             mux_enc->field_order = AV_FIELD_PROGRESSIVE;
00990         pkt.data   = (uint8_t *)in_picture;
00991         pkt.size   =  sizeof(AVPicture);
00992         pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
00993         pkt.flags |= AV_PKT_FLAG_KEY;
00994 
00995         write_frame(s, &pkt, ost);
00996     } else {
00997         int got_packet, forced_keyframe = 0;
00998         double pts_time;
00999 
01000         if (enc->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME) &&
01001             ost->top_field_first >= 0)
01002             in_picture->top_field_first = !!ost->top_field_first;
01003 
01004         if (in_picture->interlaced_frame) {
01005             if (enc->codec->id == AV_CODEC_ID_MJPEG)
01006                 mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
01007             else
01008                 mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
01009         } else
01010             mux_enc->field_order = AV_FIELD_PROGRESSIVE;
01011 
01012         in_picture->quality = enc->global_quality;
01013         if (!enc->me_threshold)
01014             in_picture->pict_type = 0;
01015 
01016         pts_time = in_picture->pts != AV_NOPTS_VALUE ?
01017             in_picture->pts * av_q2d(enc->time_base) : NAN;
01018         if (ost->forced_kf_index < ost->forced_kf_count &&
01019             in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
01020             ost->forced_kf_index++;
01021             forced_keyframe = 1;
01022         } else if (ost->forced_keyframes_pexpr) {
01023             double res;
01024             ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
01025             res = av_expr_eval(ost->forced_keyframes_pexpr,
01026                                ost->forced_keyframes_expr_const_values, NULL);
01027             av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
01028                     ost->forced_keyframes_expr_const_values[FKF_N],
01029                     ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
01030                     ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
01031                     ost->forced_keyframes_expr_const_values[FKF_T],
01032                     ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
01033                     res);
01034             if (res) {
01035                 forced_keyframe = 1;
01036                 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
01037                     ost->forced_keyframes_expr_const_values[FKF_N];
01038                 ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
01039                     ost->forced_keyframes_expr_const_values[FKF_T];
01040                 ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
01041             }
01042 
01043             ost->forced_keyframes_expr_const_values[FKF_N] += 1;
01044         }
01045 
01046         if (forced_keyframe) {
01047             in_picture->pict_type = AV_PICTURE_TYPE_I;
01048             av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
01049         }
01050 
01051         update_benchmark(NULL);
01052         if (debug_ts) {
01053             av_log(NULL, AV_LOG_INFO, "encoder <- type:video "
01054                    "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
01055                    av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
01056                    enc->time_base.num, enc->time_base.den);
01057         }
01058 
01059         ost->frames_encoded++;
01060 
01061         ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);
01062         update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
01063         if (ret < 0) {
01064             av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
01065             exit_program(1);
01066         }
01067 
01068         if (got_packet) {
01069             if (debug_ts) {
01070                 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
01071                        "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
01072                        av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
01073                        av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
01074             }
01075 
01076             if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
01077                 pkt.pts = ost->sync_opts;
01078 
01079             av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
01080 
01081             if (debug_ts) {
01082                 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
01083                     "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
01084                     av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
01085                     av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
01086             }
01087 
01088             frame_size = pkt.size;
01089             write_frame(s, &pkt, ost);
01090 
01091             /* if two pass, output log */
01092             if (ost->logfile && enc->stats_out) {
01093                 fprintf(ost->logfile, "%s", enc->stats_out);
01094             }
01095         }
01096     }
01097     ost->sync_opts++;
01098     /*
01099      * For video, number of frames in == number of packets out.
01100      * But there may be reordering, so we can't throw away frames on encoder
01101      * flush, we need to limit them here, before they go into encoder.
01102      */
01103     ost->frame_number++;
01104 
01105     if (vstats_filename && frame_size)
01106         do_video_stats(ost, frame_size);
01107   }
01108 }
01109 
01110 static double psnr(double d)
01111 {
01112     return -10.0 * log(d) / log(10.0);
01113 }
01114 
01115 static void do_video_stats(OutputStream *ost, int frame_size)
01116 {
01117     AVCodecContext *enc;
01118     int frame_number;
01119     double ti1, bitrate, avg_bitrate;
01120 
01121     /* this is executed just the first time do_video_stats is called */
01122     if (!vstats_file) {
01123         vstats_file = fopen(vstats_filename, "w");
01124         if (!vstats_file) {
01125             perror("fopen");
01126             exit_program(1);
01127         }
01128     }
01129 
01130     enc = ost->enc_ctx;
01131     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
01132         frame_number = ost->st->nb_frames;
01133         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
01134         if (enc->flags&CODEC_FLAG_PSNR)
01135             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
01136 
01137         fprintf(vstats_file,"f_size= %6d ", frame_size);
01138         /* compute pts value */
01139         ti1 = av_stream_get_end_pts(ost->st) * av_q2d(ost->st->time_base);
01140         if (ti1 < 0.01)
01141             ti1 = 0.01;
01142 
01143         bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
01144         avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
01145         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
01146                (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
01147         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
01148     }
01149 }
01150 
01151 static void finish_output_stream(OutputStream *ost)
01152 {
01153     OutputFile *of = output_files[ost->file_index];
01154     int i;
01155 
01156     ost->finished = ENCODER_FINISHED | MUXER_FINISHED;
01157 
01158     if (of->shortest) {
01159         for (i = 0; i < of->ctx->nb_streams; i++)
01160             output_streams[of->ost_index + i]->finished = ENCODER_FINISHED | MUXER_FINISHED;
01161     }
01162 }
01163 
01170 static int reap_filters(void)
01171 {
01172     AVFrame *filtered_frame = NULL;
01173     int i;
01174     int64_t frame_pts;
01175 
01176     /* Reap all buffers present in the buffer sinks */
01177     for (i = 0; i < nb_output_streams; i++) {
01178         OutputStream *ost = output_streams[i];
01179         OutputFile    *of = output_files[ost->file_index];
01180         AVFilterContext *filter;
01181         AVCodecContext *enc = ost->enc_ctx;
01182         int ret = 0;
01183 
01184         if (!ost->filter)
01185             continue;
01186         filter = ost->filter->filter;
01187 
01188         if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
01189             return AVERROR(ENOMEM);
01190         }
01191         filtered_frame = ost->filtered_frame;
01192 
01193         while (1) {
01194             ret = av_buffersink_get_frame_flags(filter, filtered_frame,
01195                                                AV_BUFFERSINK_FLAG_NO_REQUEST);
01196             if (ret < 0) {
01197                 if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
01198                     av_log(NULL, AV_LOG_WARNING,
01199                            "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
01200                 }
01201                 break;
01202             }
01203             if (ost->finished) {
01204                 av_frame_unref(filtered_frame);
01205                 continue;
01206             }
01207             frame_pts = AV_NOPTS_VALUE;
01208             if (filtered_frame->pts != AV_NOPTS_VALUE) {
01209                 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
01210                 filtered_frame->pts = frame_pts =
01211                     av_rescale_q(filtered_frame->pts, filter->inputs[0]->time_base, enc->time_base) -
01212                     av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
01213             }
01214             //if (ost->source_index >= 0)
01215             //    *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
01216 
01217             switch (filter->inputs[0]->type) {
01218             case AVMEDIA_TYPE_VIDEO:
01219                 filtered_frame->pts = frame_pts;
01220                 if (!ost->frame_aspect_ratio.num)
01221                     enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
01222 
01223                 if (debug_ts) {
01224                     av_log(NULL, AV_LOG_INFO, "filter -> pts:%s pts_time:%s time_base:%d/%d\n",
01225                             av_ts2str(filtered_frame->pts), av_ts2timestr(filtered_frame->pts, &enc->time_base),
01226                             enc->time_base.num, enc->time_base.den);
01227                 }
01228 
01229                 do_video_out(of->ctx, ost, filtered_frame);
01230                 break;
01231             case AVMEDIA_TYPE_AUDIO:
01232                 filtered_frame->pts = frame_pts;
01233                 if (!(enc->codec->capabilities & CODEC_CAP_PARAM_CHANGE) &&
01234                     enc->channels != av_frame_get_channels(filtered_frame)) {
01235                     av_log(NULL, AV_LOG_ERROR,
01236                            "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
01237                     break;
01238                 }
01239                 do_audio_out(of->ctx, ost, filtered_frame);
01240                 break;
01241             default:
01242                 // TODO support subtitle filters
01243                 av_assert0(0);
01244             }
01245 
01246             av_frame_unref(filtered_frame);
01247         }
01248     }
01249 
01250     return 0;
01251 }
01252 
01253 static void print_final_stats(int64_t total_size)
01254 {
01255     uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
01256     uint64_t subtitle_size = 0;
01257     uint64_t data_size = 0;
01258     float percent = -1.0;
01259     int i, j;
01260 
01261     for (i = 0; i < nb_output_streams; i++) {
01262         OutputStream *ost = output_streams[i];
01263         switch (ost->enc_ctx->codec_type) {
01264             case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
01265             case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
01266             case AVMEDIA_TYPE_SUBTITLE: subtitle_size += ost->data_size; break;
01267             default:                 other_size += ost->data_size; break;
01268         }
01269         extra_size += ost->enc_ctx->extradata_size;
01270         data_size  += ost->data_size;
01271     }
01272 
01273     if (data_size && total_size>0 && total_size >= data_size)
01274         percent = 100.0 * (total_size - data_size) / data_size;
01275 
01276     av_log(NULL, AV_LOG_INFO, "\n");
01277     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: ",
01278            video_size / 1024.0,
01279            audio_size / 1024.0,
01280            subtitle_size / 1024.0,
01281            other_size / 1024.0,
01282            extra_size / 1024.0);
01283     if (percent >= 0.0)
01284         av_log(NULL, AV_LOG_INFO, "%f%%", percent);
01285     else
01286         av_log(NULL, AV_LOG_INFO, "unknown");
01287     av_log(NULL, AV_LOG_INFO, "\n");
01288 
01289     /* print verbose per-stream stats */
01290     for (i = 0; i < nb_input_files; i++) {
01291         InputFile *f = input_files[i];
01292         uint64_t total_packets = 0, total_size = 0;
01293 
01294         av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
01295                i, f->ctx->filename);
01296 
01297         for (j = 0; j < f->nb_streams; j++) {
01298             InputStream *ist = input_streams[f->ist_index + j];
01299             enum AVMediaType type = ist->dec_ctx->codec_type;
01300 
01301             total_size    += ist->data_size;
01302             total_packets += ist->nb_packets;
01303 
01304             av_log(NULL, AV_LOG_VERBOSE, "  Input stream #%d:%d (%s): ",
01305                    i, j, media_type_string(type));
01306             av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
01307                    ist->nb_packets, ist->data_size);
01308 
01309             if (ist->decoding_needed) {
01310                 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
01311                        ist->frames_decoded);
01312                 if (type == AVMEDIA_TYPE_AUDIO)
01313                     av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
01314                 av_log(NULL, AV_LOG_VERBOSE, "; ");
01315             }
01316 
01317             av_log(NULL, AV_LOG_VERBOSE, "\n");
01318         }
01319 
01320         av_log(NULL, AV_LOG_VERBOSE, "  Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
01321                total_packets, total_size);
01322     }
01323 
01324     for (i = 0; i < nb_output_files; i++) {
01325         OutputFile *of = output_files[i];
01326         uint64_t total_packets = 0, total_size = 0;
01327 
01328         av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
01329                i, of->ctx->filename);
01330 
01331         for (j = 0; j < of->ctx->nb_streams; j++) {
01332             OutputStream *ost = output_streams[of->ost_index + j];
01333             enum AVMediaType type = ost->enc_ctx->codec_type;
01334 
01335             total_size    += ost->data_size;
01336             total_packets += ost->packets_written;
01337 
01338             av_log(NULL, AV_LOG_VERBOSE, "  Output stream #%d:%d (%s): ",
01339                    i, j, media_type_string(type));
01340             if (ost->encoding_needed) {
01341                 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
01342                        ost->frames_encoded);
01343                 if (type == AVMEDIA_TYPE_AUDIO)
01344                     av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
01345                 av_log(NULL, AV_LOG_VERBOSE, "; ");
01346             }
01347 
01348             av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
01349                    ost->packets_written, ost->data_size);
01350 
01351             av_log(NULL, AV_LOG_VERBOSE, "\n");
01352         }
01353 
01354         av_log(NULL, AV_LOG_VERBOSE, "  Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
01355                total_packets, total_size);
01356     }
01357     if(video_size + data_size + audio_size + subtitle_size + extra_size == 0){
01358         av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
01359     }
01360 }
01361 
01362 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
01363 {
01364     char buf[1024];
01365     AVBPrint buf_script;
01366     OutputStream *ost;
01367     AVFormatContext *oc;
01368     int64_t total_size;
01369     AVCodecContext *enc;
01370     int frame_number, vid, i;
01371     double bitrate;
01372     int64_t pts = INT64_MIN;
01373     static int64_t last_time = -1;
01374     static int qp_histogram[52];
01375     int hours, mins, secs, us;
01376 
01377     if (!print_stats && !is_last_report && !progress_avio)
01378         return;
01379 
01380     if (!is_last_report) {
01381         if (last_time == -1) {
01382             last_time = cur_time;
01383             return;
01384         }
01385         if ((cur_time - last_time) < 500000)
01386             return;
01387         last_time = cur_time;
01388     }
01389 
01390 
01391     oc = output_files[0]->ctx;
01392 
01393     total_size = avio_size(oc->pb);
01394     if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
01395         total_size = avio_tell(oc->pb);
01396 
01397     buf[0] = '\0';
01398     vid = 0;
01399     av_bprint_init(&buf_script, 0, 1);
01400     for (i = 0; i < nb_output_streams; i++) {
01401         float q = -1;
01402         ost = output_streams[i];
01403         enc = ost->enc_ctx;
01404         if (!ost->stream_copy && enc->coded_frame)
01405             q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
01406         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
01407             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
01408             av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
01409                        ost->file_index, ost->index, q);
01410         }
01411         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
01412             float fps, t = (cur_time-timer_start) / 1000000.0;
01413 
01414             frame_number = ost->frame_number;
01415             fps = t > 1 ? frame_number / t : 0;
01416             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
01417                      frame_number, fps < 9.95, fps, q);
01418             av_bprintf(&buf_script, "frame=%d\n", frame_number);
01419             av_bprintf(&buf_script, "fps=%.1f\n", fps);
01420             av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
01421                        ost->file_index, ost->index, q);
01422             if (is_last_report)
01423                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
01424             if (qp_hist) {
01425                 int j;
01426                 int qp = lrintf(q);
01427                 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
01428                     qp_histogram[qp]++;
01429                 for (j = 0; j < 32; j++)
01430                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
01431             }
01432             if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
01433                 int j;
01434                 double error, error_sum = 0;
01435                 double scale, scale_sum = 0;
01436                 double p;
01437                 char type[3] = { 'Y','U','V' };
01438                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
01439                 for (j = 0; j < 3; j++) {
01440                     if (is_last_report) {
01441                         error = enc->error[j];
01442                         scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
01443                     } else {
01444                         error = enc->coded_frame->error[j];
01445                         scale = enc->width * enc->height * 255.0 * 255.0;
01446                     }
01447                     if (j)
01448                         scale /= 4;
01449                     error_sum += error;
01450                     scale_sum += scale;
01451                     p = psnr(error / scale);
01452                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
01453                     av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
01454                                ost->file_index, ost->index, type[j] | 32, p);
01455                 }
01456                 p = psnr(error_sum / scale_sum);
01457                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
01458                 av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
01459                            ost->file_index, ost->index, p);
01460             }
01461             vid = 1;
01462         }
01463         /* compute min output value */
01464         if (av_stream_get_end_pts(ost->st) != AV_NOPTS_VALUE)
01465             pts = FFMAX(pts, av_rescale_q(av_stream_get_end_pts(ost->st),
01466                                           ost->st->time_base, AV_TIME_BASE_Q));
01467     }
01468 
01469     secs = pts / AV_TIME_BASE;
01470     us = pts % AV_TIME_BASE;
01471     mins = secs / 60;
01472     secs %= 60;
01473     hours = mins / 60;
01474     mins %= 60;
01475 
01476     bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
01477 
01478     if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
01479                                  "size=N/A time=");
01480     else                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
01481                                  "size=%8.0fkB time=", total_size / 1024.0);
01482     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
01483              "%02d:%02d:%02d.%02d ", hours, mins, secs,
01484              (100 * us) / AV_TIME_BASE);
01485     if (bitrate < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
01486                               "bitrate=N/A");
01487     else             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
01488                               "bitrate=%6.1fkbits/s", bitrate);
01489     if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
01490     else                av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
01491     av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
01492     av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
01493                hours, mins, secs, us);
01494 
01495     if (nb_frames_dup || nb_frames_drop)
01496         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
01497                 nb_frames_dup, nb_frames_drop);
01498     av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
01499     av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
01500 
01501     if (print_stats || is_last_report) {
01502         if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
01503             fprintf(stderr, "%s    \r", buf);
01504         } else
01505             av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
01506 
01507     fflush(stderr);
01508     }
01509 
01510     if (progress_avio) {
01511         av_bprintf(&buf_script, "progress=%s\n",
01512                    is_last_report ? "end" : "continue");
01513         avio_write(progress_avio, buf_script.str,
01514                    FFMIN(buf_script.len, buf_script.size - 1));
01515         avio_flush(progress_avio);
01516         av_bprint_finalize(&buf_script, NULL);
01517         if (is_last_report) {
01518             avio_close(progress_avio);
01519             progress_avio = NULL;
01520         }
01521     }
01522 
01523     if (is_last_report)
01524         print_final_stats(total_size);
01525 }
01526 
01527 static void flush_encoders(void)
01528 {
01529     int i, ret;
01530 
01531     for (i = 0; i < nb_output_streams; i++) {
01532         OutputStream   *ost = output_streams[i];
01533         AVCodecContext *enc = ost->enc_ctx;
01534         AVFormatContext *os = output_files[ost->file_index]->ctx;
01535         int stop_encoding = 0;
01536 
01537         if (!ost->encoding_needed)
01538             continue;
01539 
01540         if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
01541             continue;
01542         if (enc->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
01543             continue;
01544 
01545         for (;;) {
01546             int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
01547             const char *desc;
01548 
01549             switch (enc->codec_type) {
01550             case AVMEDIA_TYPE_AUDIO:
01551                 encode = avcodec_encode_audio2;
01552                 desc   = "Audio";
01553                 break;
01554             case AVMEDIA_TYPE_VIDEO:
01555                 encode = avcodec_encode_video2;
01556                 desc   = "Video";
01557                 break;
01558             default:
01559                 stop_encoding = 1;
01560             }
01561 
01562             if (encode) {
01563                 AVPacket pkt;
01564                 int pkt_size;
01565                 int got_packet;
01566                 av_init_packet(&pkt);
01567                 pkt.data = NULL;
01568                 pkt.size = 0;
01569 
01570                 update_benchmark(NULL);
01571                 ret = encode(enc, &pkt, NULL, &got_packet);
01572                 update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
01573                 if (ret < 0) {
01574                     av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
01575                     exit_program(1);
01576                 }
01577                 if (ost->logfile && enc->stats_out) {
01578                     fprintf(ost->logfile, "%s", enc->stats_out);
01579                 }
01580                 if (!got_packet) {
01581                     stop_encoding = 1;
01582                     break;
01583                 }
01584                 if (ost->finished & MUXER_FINISHED) {
01585                     av_free_packet(&pkt);
01586                     continue;
01587                 }
01588                 av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
01589                 pkt_size = pkt.size;
01590                 write_frame(os, &pkt, ost);
01591                 if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
01592                     do_video_stats(ost, pkt_size);
01593                 }
01594             }
01595 
01596             if (stop_encoding)
01597                 break;
01598         }
01599     }
01600 }
01601 
01602 /*
01603  * Check whether a packet from ist should be written into ost at this time
01604  */
01605 static int check_output_constraints(InputStream *ist, OutputStream *ost)
01606 {
01607     OutputFile *of = output_files[ost->file_index];
01608     int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
01609 
01610     if (ost->source_index != ist_index)
01611         return 0;
01612 
01613     if (ost->finished)
01614         return 0;
01615 
01616     if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
01617         return 0;
01618 
01619     return 1;
01620 }
01621 
01622 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
01623 {
01624     OutputFile *of = output_files[ost->file_index];
01625     InputFile   *f = input_files [ist->file_index];
01626     int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
01627     int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
01628     int64_t ist_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ist->st->time_base);
01629     AVPicture pict;
01630     AVPacket opkt;
01631 
01632     av_init_packet(&opkt);
01633 
01634     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
01635         !ost->copy_initial_nonkeyframes)
01636         return;
01637 
01638     if (pkt->pts == AV_NOPTS_VALUE) {
01639         if (!ost->frame_number && ist->pts < start_time &&
01640             !ost->copy_prior_start)
01641             return;
01642     } else {
01643         if (!ost->frame_number && pkt->pts < ist_tb_start_time &&
01644             !ost->copy_prior_start)
01645             return;
01646     }
01647 
01648     if (of->recording_time != INT64_MAX &&
01649         ist->pts >= of->recording_time + start_time) {
01650         close_output_stream(ost);
01651         return;
01652     }
01653 
01654     if (f->recording_time != INT64_MAX) {
01655         start_time = f->ctx->start_time;
01656         if (f->start_time != AV_NOPTS_VALUE)
01657             start_time += f->start_time;
01658         if (ist->pts >= f->recording_time + start_time) {
01659             close_output_stream(ost);
01660             return;
01661         }
01662     }
01663 
01664     /* force the input stream PTS */
01665     if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
01666         ost->sync_opts++;
01667 
01668     if (pkt->pts != AV_NOPTS_VALUE)
01669         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
01670     else
01671         opkt.pts = AV_NOPTS_VALUE;
01672 
01673     if (pkt->dts == AV_NOPTS_VALUE)
01674         opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
01675     else
01676         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
01677     opkt.dts -= ost_tb_start_time;
01678 
01679     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
01680         int duration = av_get_audio_frame_duration(ist->dec_ctx, pkt->size);
01681         if(!duration)
01682             duration = ist->dec_ctx->frame_size;
01683         opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
01684                                                (AVRational){1, ist->dec_ctx->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
01685                                                ost->st->time_base) - ost_tb_start_time;
01686     }
01687 
01688     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
01689     opkt.flags    = pkt->flags;
01690 
01691     // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
01692     if (  ost->enc_ctx->codec_id != AV_CODEC_ID_H264
01693        && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG1VIDEO
01694        && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG2VIDEO
01695        && ost->enc_ctx->codec_id != AV_CODEC_ID_VC1
01696        ) {
01697         if (av_parser_change(ost->parser, ost->st->codec,
01698                              &opkt.data, &opkt.size,
01699                              pkt->data, pkt->size,
01700                              pkt->flags & AV_PKT_FLAG_KEY)) {
01701             opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
01702             if (!opkt.buf)
01703                 exit_program(1);
01704         }
01705     } else {
01706         opkt.data = pkt->data;
01707         opkt.size = pkt->size;
01708     }
01709     av_copy_packet_side_data(&opkt, pkt);
01710 
01711     if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
01712         /* store AVPicture in AVPacket, as expected by the output format */
01713         avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
01714         opkt.data = (uint8_t *)&pict;
01715         opkt.size = sizeof(AVPicture);
01716         opkt.flags |= AV_PKT_FLAG_KEY;
01717     }
01718 
01719     write_frame(of->ctx, &opkt, ost);
01720 }
01721 
01722 int guess_input_channel_layout(InputStream *ist)
01723 {
01724     AVCodecContext *dec = ist->dec_ctx;
01725 
01726     if (!dec->channel_layout) {
01727         char layout_name[256];
01728 
01729         if (dec->channels > ist->guess_layout_max)
01730             return 0;
01731         dec->channel_layout = av_get_default_channel_layout(dec->channels);
01732         if (!dec->channel_layout)
01733             return 0;
01734         av_get_channel_layout_string(layout_name, sizeof(layout_name),
01735                                      dec->channels, dec->channel_layout);
01736         av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for  Input Stream "
01737                "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
01738     }
01739     return 1;
01740 }
01741 
01742 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
01743 {
01744     AVFrame *decoded_frame, *f;
01745     AVCodecContext *avctx = ist->dec_ctx;
01746     int i, ret, err = 0, resample_changed;
01747     AVRational decoded_frame_tb;
01748 
01749     if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
01750         return AVERROR(ENOMEM);
01751     if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
01752         return AVERROR(ENOMEM);
01753     decoded_frame = ist->decoded_frame;
01754 
01755     update_benchmark(NULL);
01756     ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
01757     update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
01758 
01759     if (ret >= 0 && avctx->sample_rate <= 0) {
01760         av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
01761         ret = AVERROR_INVALIDDATA;
01762     }
01763 
01764     if (*got_output || ret<0 || pkt->size)
01765         decode_error_stat[ret<0] ++;
01766 
01767     if (!*got_output || ret < 0) {
01768         if (!pkt->size) {
01769             for (i = 0; i < ist->nb_filters; i++)
01770 #if 1
01771                 av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
01772 #else
01773                 av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
01774 #endif
01775         }
01776         return ret;
01777     }
01778 
01779     ist->samples_decoded += decoded_frame->nb_samples;
01780     ist->frames_decoded++;
01781 
01782 #if 1
01783     /* increment next_dts to use for the case where the input stream does not
01784        have timestamps or there are multiple frames in the packet */
01785     ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
01786                      avctx->sample_rate;
01787     ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
01788                      avctx->sample_rate;
01789 #endif
01790 
01791     resample_changed = ist->resample_sample_fmt     != decoded_frame->format         ||
01792                        ist->resample_channels       != avctx->channels               ||
01793                        ist->resample_channel_layout != decoded_frame->channel_layout ||
01794                        ist->resample_sample_rate    != decoded_frame->sample_rate;
01795     if (resample_changed) {
01796         char layout1[64], layout2[64];
01797 
01798         if (!guess_input_channel_layout(ist)) {
01799             av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
01800                    "layout for Input Stream #%d.%d\n", ist->file_index,
01801                    ist->st->index);
01802             exit_program(1);
01803         }
01804         decoded_frame->channel_layout = avctx->channel_layout;
01805 
01806         av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
01807                                      ist->resample_channel_layout);
01808         av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
01809                                      decoded_frame->channel_layout);
01810 
01811         av_log(NULL, AV_LOG_INFO,
01812                "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",
01813                ist->file_index, ist->st->index,
01814                ist->resample_sample_rate,  av_get_sample_fmt_name(ist->resample_sample_fmt),
01815                ist->resample_channels, layout1,
01816                decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
01817                avctx->channels, layout2);
01818 
01819         ist->resample_sample_fmt     = decoded_frame->format;
01820         ist->resample_sample_rate    = decoded_frame->sample_rate;
01821         ist->resample_channel_layout = decoded_frame->channel_layout;
01822         ist->resample_channels       = avctx->channels;
01823 
01824         for (i = 0; i < nb_filtergraphs; i++)
01825             if (ist_in_filtergraph(filtergraphs[i], ist)) {
01826                 FilterGraph *fg = filtergraphs[i];
01827                 if (configure_filtergraph(fg) < 0) {
01828                     av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
01829                     exit_program(1);
01830                 }
01831             }
01832     }
01833 
01834     /* if the decoder provides a pts, use it instead of the last packet pts.
01835        the decoder could be delaying output by a packet or more. */
01836     if (decoded_frame->pts != AV_NOPTS_VALUE) {
01837         ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
01838         decoded_frame_tb   = avctx->time_base;
01839     } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
01840         decoded_frame->pts = decoded_frame->pkt_pts;
01841         decoded_frame_tb   = ist->st->time_base;
01842     } else if (pkt->pts != AV_NOPTS_VALUE) {
01843         decoded_frame->pts = pkt->pts;
01844         decoded_frame_tb   = ist->st->time_base;
01845     }else {
01846         decoded_frame->pts = ist->dts;
01847         decoded_frame_tb   = AV_TIME_BASE_Q;
01848     }
01849     pkt->pts           = AV_NOPTS_VALUE;
01850     if (decoded_frame->pts != AV_NOPTS_VALUE)
01851         decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
01852                                               (AVRational){1, avctx->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
01853                                               (AVRational){1, avctx->sample_rate});
01854     for (i = 0; i < ist->nb_filters; i++) {
01855         if (i < ist->nb_filters - 1) {
01856             f = ist->filter_frame;
01857             err = av_frame_ref(f, decoded_frame);
01858             if (err < 0)
01859                 break;
01860         } else
01861             f = decoded_frame;
01862         err = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,
01863                                      AV_BUFFERSRC_FLAG_PUSH);
01864         if (err == AVERROR_EOF)
01865             err = 0; /* ignore */
01866         if (err < 0)
01867             break;
01868     }
01869     decoded_frame->pts = AV_NOPTS_VALUE;
01870 
01871     av_frame_unref(ist->filter_frame);
01872     av_frame_unref(decoded_frame);
01873     return err < 0 ? err : ret;
01874 }
01875 
01876 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
01877 {
01878     AVFrame *decoded_frame, *f;
01879     int i, ret = 0, err = 0, resample_changed;
01880     int64_t best_effort_timestamp;
01881     AVRational *frame_sample_aspect;
01882 
01883     if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
01884         return AVERROR(ENOMEM);
01885     if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
01886         return AVERROR(ENOMEM);
01887     decoded_frame = ist->decoded_frame;
01888     pkt->dts  = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
01889 
01890     update_benchmark(NULL);
01891     ret = avcodec_decode_video2(ist->dec_ctx,
01892                                 decoded_frame, got_output, pkt);
01893     update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
01894 
01895     // The following line may be required in some cases where there is no parser
01896     // or the parser does not has_b_frames correctly
01897     if (ist->st->codec->has_b_frames < ist->dec_ctx->has_b_frames) {
01898         if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
01899             ist->st->codec->has_b_frames = ist->dec_ctx->has_b_frames;
01900         } else
01901             av_log_ask_for_sample(
01902                 ist->dec_ctx,
01903                 "has_b_frames is larger in decoder than demuxer %d > %d ",
01904                 ist->dec_ctx->has_b_frames,
01905                 ist->st->codec->has_b_frames
01906             );
01907     }
01908 
01909     if (*got_output || ret<0 || pkt->size)
01910         decode_error_stat[ret<0] ++;
01911 
01912     if (!*got_output || ret < 0) {
01913         if (!pkt->size) {
01914             for (i = 0; i < ist->nb_filters; i++)
01915 #if 1
01916                 av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
01917 #else
01918                 av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
01919 #endif
01920         }
01921         return ret;
01922     }
01923 
01924     if(ist->top_field_first>=0)
01925         decoded_frame->top_field_first = ist->top_field_first;
01926 
01927     ist->frames_decoded++;
01928 
01929     if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
01930         err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
01931         if (err < 0)
01932             goto fail;
01933     }
01934     ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
01935 
01936     best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
01937     if(best_effort_timestamp != AV_NOPTS_VALUE)
01938         ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
01939 
01940     if (debug_ts) {
01941         av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
01942                "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",
01943                ist->st->index, av_ts2str(decoded_frame->pts),
01944                av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
01945                best_effort_timestamp,
01946                av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
01947                decoded_frame->key_frame, decoded_frame->pict_type,
01948                ist->st->time_base.num, ist->st->time_base.den);
01949     }
01950 
01951     pkt->size = 0;
01952 
01953     if (ist->st->sample_aspect_ratio.num)
01954         decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
01955 
01956     resample_changed = ist->resample_width   != decoded_frame->width  ||
01957                        ist->resample_height  != decoded_frame->height ||
01958                        ist->resample_pix_fmt != decoded_frame->format;
01959     if (resample_changed) {
01960         av_log(NULL, AV_LOG_INFO,
01961                "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
01962                ist->file_index, ist->st->index,
01963                ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),
01964                decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
01965 
01966         ist->resample_width   = decoded_frame->width;
01967         ist->resample_height  = decoded_frame->height;
01968         ist->resample_pix_fmt = decoded_frame->format;
01969 
01970         for (i = 0; i < nb_filtergraphs; i++) {
01971             if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
01972                 configure_filtergraph(filtergraphs[i]) < 0) {
01973                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
01974                 exit_program(1);
01975             }
01976         }
01977     }
01978 
01979     frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
01980     for (i = 0; i < ist->nb_filters; i++) {
01981         if (!frame_sample_aspect->num)
01982             *frame_sample_aspect = ist->st->sample_aspect_ratio;
01983 
01984         if (i < ist->nb_filters - 1) {
01985             f = ist->filter_frame;
01986             err = av_frame_ref(f, decoded_frame);
01987             if (err < 0)
01988                 break;
01989         } else
01990             f = decoded_frame;
01991         ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f, AV_BUFFERSRC_FLAG_PUSH);
01992         if (ret == AVERROR_EOF) {
01993             ret = 0; /* ignore */
01994         } else if (ret < 0) {
01995             av_log(NULL, AV_LOG_FATAL,
01996                    "Failed to inject frame into filter network: %s\n", av_err2str(ret));
01997             exit_program(1);
01998         }
01999     }
02000 
02001 fail:
02002     av_frame_unref(ist->filter_frame);
02003     av_frame_unref(decoded_frame);
02004     return err < 0 ? err : ret;
02005 }
02006 
02007 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
02008 {
02009     AVSubtitle subtitle;
02010     int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
02011                                           &subtitle, got_output, pkt);
02012 
02013     if (*got_output || ret<0 || pkt->size)
02014         decode_error_stat[ret<0] ++;
02015 
02016     if (ret < 0 || !*got_output) {
02017         if (!pkt->size)
02018             sub2video_flush(ist);
02019         return ret;
02020     }
02021 
02022     if (ist->fix_sub_duration) {
02023         int end = 1;
02024         if (ist->prev_sub.got_output) {
02025             end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
02026                              1000, AV_TIME_BASE);
02027             if (end < ist->prev_sub.subtitle.end_display_time) {
02028                 av_log(ist->dec_ctx, AV_LOG_DEBUG,
02029                        "Subtitle duration reduced from %d to %d%s\n",
02030                        ist->prev_sub.subtitle.end_display_time, end,
02031                        end <= 0 ? ", dropping it" : "");
02032                 ist->prev_sub.subtitle.end_display_time = end;
02033             }
02034         }
02035         FFSWAP(int,        *got_output, ist->prev_sub.got_output);
02036         FFSWAP(int,        ret,         ist->prev_sub.ret);
02037         FFSWAP(AVSubtitle, subtitle,    ist->prev_sub.subtitle);
02038         if (end <= 0)
02039             goto out;
02040     }
02041 
02042     if (!*got_output)
02043         return ret;
02044 
02045     sub2video_update(ist, &subtitle);
02046 
02047     if (!subtitle.num_rects)
02048         goto out;
02049 
02050     ist->frames_decoded++;
02051 
02052     for (i = 0; i < nb_output_streams; i++) {
02053         OutputStream *ost = output_streams[i];
02054 
02055         if (!check_output_constraints(ist, ost) || !ost->encoding_needed
02056             || ost->enc->type != AVMEDIA_TYPE_SUBTITLE)
02057             continue;
02058 
02059         do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
02060     }
02061 
02062 out:
02063     avsubtitle_free(&subtitle);
02064     return ret;
02065 }
02066 
02067 /* pkt = NULL means EOF (needed to flush decoder buffers) */
02068 static int process_input_packet(InputStream *ist, const AVPacket *pkt)
02069 {
02070     int ret = 0, i;
02071     int got_output = 0;
02072 
02073     AVPacket avpkt;
02074     if (!ist->saw_first_ts) {
02075         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;
02076         ist->pts = 0;
02077         if (pkt && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
02078             ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
02079             ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
02080         }
02081         ist->saw_first_ts = 1;
02082     }
02083 
02084     if (ist->next_dts == AV_NOPTS_VALUE)
02085         ist->next_dts = ist->dts;
02086     if (ist->next_pts == AV_NOPTS_VALUE)
02087         ist->next_pts = ist->pts;
02088 
02089     if (!pkt) {
02090         /* EOF handling */
02091         av_init_packet(&avpkt);
02092         avpkt.data = NULL;
02093         avpkt.size = 0;
02094         goto handle_eof;
02095     } else {
02096         avpkt = *pkt;
02097     }
02098 
02099     if (pkt->dts != AV_NOPTS_VALUE) {
02100         ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
02101         if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
02102             ist->next_pts = ist->pts = ist->dts;
02103     }
02104 
02105     // while we have more to decode or while the decoder did output something on EOF
02106     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
02107         int duration;
02108     handle_eof:
02109 
02110         ist->pts = ist->next_pts;
02111         ist->dts = ist->next_dts;
02112 
02113         if (avpkt.size && avpkt.size != pkt->size &&
02114             !(ist->dec->capabilities & CODEC_CAP_SUBFRAMES)) {
02115             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
02116                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
02117             ist->showed_multi_packet_warning = 1;
02118         }
02119 
02120         switch (ist->dec_ctx->codec_type) {
02121         case AVMEDIA_TYPE_AUDIO:
02122             ret = decode_audio    (ist, &avpkt, &got_output);
02123             break;
02124         case AVMEDIA_TYPE_VIDEO:
02125             ret = decode_video    (ist, &avpkt, &got_output);
02126             if (avpkt.duration) {
02127                 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
02128             } else if(ist->dec_ctx->time_base.num != 0 && ist->dec_ctx->time_base.den != 0) {
02129                 int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict+1 : ist->dec_ctx->ticks_per_frame;
02130                 duration = ((int64_t)AV_TIME_BASE *
02131                                 ist->dec_ctx->time_base.num * ticks) /
02132                                 ist->dec_ctx->time_base.den;
02133             } else
02134                 duration = 0;
02135 
02136             if(ist->dts != AV_NOPTS_VALUE && duration) {
02137                 ist->next_dts += duration;
02138             }else
02139                 ist->next_dts = AV_NOPTS_VALUE;
02140 
02141             if (got_output)
02142                 ist->next_pts += duration; //FIXME the duration is not correct in some cases
02143             break;
02144         case AVMEDIA_TYPE_SUBTITLE:
02145             ret = transcode_subtitles(ist, &avpkt, &got_output);
02146             break;
02147         default:
02148             return -1;
02149         }
02150 
02151         if (ret < 0)
02152             return ret;
02153 
02154         avpkt.dts=
02155         avpkt.pts= AV_NOPTS_VALUE;
02156 
02157         // touch data and size only if not EOF
02158         if (pkt) {
02159             if(ist->dec_ctx->codec_type != AVMEDIA_TYPE_AUDIO)
02160                 ret = avpkt.size;
02161             avpkt.data += ret;
02162             avpkt.size -= ret;
02163         }
02164         if (!got_output) {
02165             continue;
02166         }
02167         if (got_output && !pkt)
02168             break;
02169     }
02170 
02171     /* handle stream copy */
02172     if (!ist->decoding_needed) {
02173         ist->dts = ist->next_dts;
02174         switch (ist->dec_ctx->codec_type) {
02175         case AVMEDIA_TYPE_AUDIO:
02176             ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
02177                              ist->dec_ctx->sample_rate;
02178             break;
02179         case AVMEDIA_TYPE_VIDEO:
02180             if (ist->framerate.num) {
02181                 // TODO: Remove work-around for c99-to-c89 issue 7
02182                 AVRational time_base_q = AV_TIME_BASE_Q;
02183                 int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
02184                 ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
02185             } else if (pkt->duration) {
02186                 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
02187             } else if(ist->dec_ctx->time_base.num != 0) {
02188                 int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
02189                 ist->next_dts += ((int64_t)AV_TIME_BASE *
02190                                   ist->dec_ctx->time_base.num * ticks) /
02191                                   ist->dec_ctx->time_base.den;
02192             }
02193             break;
02194         }
02195         ist->pts = ist->dts;
02196         ist->next_pts = ist->next_dts;
02197     }
02198     for (i = 0; pkt && i < nb_output_streams; i++) {
02199         OutputStream *ost = output_streams[i];
02200 
02201         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
02202             continue;
02203 
02204         do_streamcopy(ist, ost, pkt);
02205     }
02206 
02207     return got_output;
02208 }
02209 
02210 static void print_sdp(void)
02211 {
02212     char sdp[16384];
02213     int i;
02214     AVFormatContext **avc = av_malloc_array(nb_output_files, sizeof(*avc));
02215 
02216     if (!avc)
02217         exit_program(1);
02218     for (i = 0; i < nb_output_files; i++)
02219         avc[i] = output_files[i]->ctx;
02220 
02221     av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
02222     printf("SDP:\n%s\n", sdp);
02223     fflush(stdout);
02224     av_freep(&avc);
02225 }
02226 
02227 static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
02228 {
02229     int i;
02230     for (i = 0; hwaccels[i].name; i++)
02231         if (hwaccels[i].pix_fmt == pix_fmt)
02232             return &hwaccels[i];
02233     return NULL;
02234 }
02235 
02236 static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
02237 {
02238     InputStream *ist = s->opaque;
02239     const enum AVPixelFormat *p;
02240     int ret;
02241 
02242     for (p = pix_fmts; *p != -1; p++) {
02243         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
02244         const HWAccel *hwaccel;
02245 
02246         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
02247             break;
02248 
02249         hwaccel = get_hwaccel(*p);
02250         if (!hwaccel ||
02251             (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
02252             (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
02253             continue;
02254 
02255         ret = hwaccel->init(s);
02256         if (ret < 0) {
02257             if (ist->hwaccel_id == hwaccel->id) {
02258                 av_log(NULL, AV_LOG_FATAL,
02259                        "%s hwaccel requested for input stream #%d:%d, "
02260                        "but cannot be initialized.\n", hwaccel->name,
02261                        ist->file_index, ist->st->index);
02262                 exit_program(1);
02263             }
02264             continue;
02265         }
02266         ist->active_hwaccel_id = hwaccel->id;
02267         ist->hwaccel_pix_fmt   = *p;
02268         break;
02269     }
02270 
02271     return *p;
02272 }
02273 
02274 static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
02275 {
02276     InputStream *ist = s->opaque;
02277 
02278     if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
02279         return ist->hwaccel_get_buffer(s, frame, flags);
02280 
02281     return avcodec_default_get_buffer2(s, frame, flags);
02282 }
02283 
02284 static int init_input_stream(int ist_index, char *error, int error_len)
02285 {
02286     int ret;
02287     InputStream *ist = input_streams[ist_index];
02288 
02289     if (ist->decoding_needed) {
02290         AVCodec *codec = ist->dec;
02291         if (!codec) {
02292             snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
02293                     avcodec_get_name(ist->dec_ctx->codec_id), ist->file_index, ist->st->index);
02294             return AVERROR(EINVAL);
02295         }
02296 
02297         ist->dec_ctx->opaque                = ist;
02298         ist->dec_ctx->get_format            = get_format;
02299         ist->dec_ctx->get_buffer2           = get_buffer;
02300         ist->dec_ctx->thread_safe_callbacks = 1;
02301 
02302         av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
02303         if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
02304            (ist->decoding_needed & DECODING_FOR_OST)) {
02305             av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
02306             if (ist->decoding_needed & DECODING_FOR_FILTER)
02307                 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");
02308         }
02309 
02310         if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
02311             av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
02312         if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
02313             if (ret == AVERROR_EXPERIMENTAL)
02314                 abort_codec_experimental(codec, 0);
02315 
02316             snprintf(error, error_len,
02317                      "Error while opening decoder for input stream "
02318                      "#%d:%d : %s",
02319                      ist->file_index, ist->st->index, av_err2str(ret));
02320             return ret;
02321         }
02322         assert_avoptions(ist->decoder_opts);
02323     }
02324 
02325     ist->next_pts = AV_NOPTS_VALUE;
02326     ist->next_dts = AV_NOPTS_VALUE;
02327 
02328     return 0;
02329 }
02330 
02331 static InputStream *get_input_stream(OutputStream *ost)
02332 {
02333     if (ost->source_index >= 0)
02334         return input_streams[ost->source_index];
02335     return NULL;
02336 }
02337 
02338 static int compare_int64(const void *a, const void *b)
02339 {
02340     int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
02341     return va < vb ? -1 : va > vb ? +1 : 0;
02342 }
02343 
02344 static void parse_forced_key_frames(char *kf, OutputStream *ost,
02345                                     AVCodecContext *avctx)
02346 {
02347     char *p;
02348     int n = 1, i, size, index = 0;
02349     int64_t t, *pts;
02350 
02351     for (p = kf; *p; p++)
02352         if (*p == ',')
02353             n++;
02354     size = n;
02355     pts = av_malloc_array(size, sizeof(*pts));
02356     if (!pts) {
02357         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
02358         exit_program(1);
02359     }
02360 
02361     p = kf;
02362     for (i = 0; i < n; i++) {
02363         char *next = strchr(p, ',');
02364 
02365         if (next)
02366             *next++ = 0;
02367 
02368         if (!memcmp(p, "chapters", 8)) {
02369 
02370             AVFormatContext *avf = output_files[ost->file_index]->ctx;
02371             int j;
02372 
02373             if (avf->nb_chapters > INT_MAX - size ||
02374                 !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
02375                                      sizeof(*pts)))) {
02376                 av_log(NULL, AV_LOG_FATAL,
02377                        "Could not allocate forced key frames array.\n");
02378                 exit_program(1);
02379             }
02380             t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
02381             t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
02382 
02383             for (j = 0; j < avf->nb_chapters; j++) {
02384                 AVChapter *c = avf->chapters[j];
02385                 av_assert1(index < size);
02386                 pts[index++] = av_rescale_q(c->start, c->time_base,
02387                                             avctx->time_base) + t;
02388             }
02389 
02390         } else {
02391 
02392             t = parse_time_or_die("force_key_frames", p, 1);
02393             av_assert1(index < size);
02394             pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
02395 
02396         }
02397 
02398         p = next;
02399     }
02400 
02401     av_assert0(index == size);
02402     qsort(pts, size, sizeof(*pts), compare_int64);
02403     ost->forced_kf_count = size;
02404     ost->forced_kf_pts   = pts;
02405 }
02406 
02407 static void report_new_stream(int input_index, AVPacket *pkt)
02408 {
02409     InputFile *file = input_files[input_index];
02410     AVStream *st = file->ctx->streams[pkt->stream_index];
02411 
02412     if (pkt->stream_index < file->nb_streams_warn)
02413         return;
02414     av_log(file->ctx, AV_LOG_WARNING,
02415            "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
02416            av_get_media_type_string(st->codec->codec_type),
02417            input_index, pkt->stream_index,
02418            pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
02419     file->nb_streams_warn = pkt->stream_index + 1;
02420 }
02421 
02422 static void set_encoder_id(OutputFile *of, OutputStream *ost)
02423 {
02424     AVDictionaryEntry *e;
02425 
02426     uint8_t *encoder_string;
02427     int encoder_string_len;
02428     int format_flags = 0;
02429     int codec_flags = 0;
02430 
02431     if (av_dict_get(ost->st->metadata, "encoder",  NULL, 0))
02432         return;
02433 
02434     e = av_dict_get(of->opts, "fflags", NULL, 0);
02435     if (e) {
02436         const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
02437         if (!o)
02438             return;
02439         av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
02440     }
02441     e = av_dict_get(ost->encoder_opts, "flags", NULL, 0);
02442     if (e) {
02443         const AVOption *o = av_opt_find(ost->enc_ctx, "flags", NULL, 0, 0);
02444         if (!o)
02445             return;
02446         av_opt_eval_flags(ost->enc_ctx, o, e->value, &codec_flags);
02447     }
02448 
02449     encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
02450     encoder_string     = av_mallocz(encoder_string_len);
02451     if (!encoder_string)
02452         exit_program(1);
02453 
02454     if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & CODEC_FLAG_BITEXACT))
02455         av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
02456     else
02457         av_strlcpy(encoder_string, "Lavc ", encoder_string_len);
02458     av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
02459     av_dict_set(&ost->st->metadata, "encoder",  encoder_string,
02460                 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
02461 }
02462 
02463 static int transcode_init(void)
02464 {
02465     int ret = 0, i, j, k;
02466     AVFormatContext *oc;
02467     OutputStream *ost;
02468     InputStream *ist;
02469     char error[1024];
02470     int want_sdp = 1;
02471 
02472     for (i = 0; i < nb_filtergraphs; i++) {
02473         FilterGraph *fg = filtergraphs[i];
02474         for (j = 0; j < fg->nb_outputs; j++) {
02475             OutputFilter *ofilter = fg->outputs[j];
02476             if (!ofilter->ost || ofilter->ost->source_index >= 0)
02477                 continue;
02478             if (fg->nb_inputs != 1)
02479                 continue;
02480             for (k = nb_input_streams-1; k >= 0 ; k--)
02481                 if (fg->inputs[0]->ist == input_streams[k])
02482                     break;
02483             ofilter->ost->source_index = k;
02484         }
02485     }
02486 
02487     /* init framerate emulation */
02488     for (i = 0; i < nb_input_files; i++) {
02489         InputFile *ifile = input_files[i];
02490         if (ifile->rate_emu)
02491             for (j = 0; j < ifile->nb_streams; j++)
02492                 input_streams[j + ifile->ist_index]->start = av_gettime_relative();
02493     }
02494 
02495     /* output stream init */
02496     for (i = 0; i < nb_output_files; i++) {
02497         oc = output_files[i]->ctx;
02498         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
02499             av_dump_format(oc, i, oc->filename, 1);
02500             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
02501             return AVERROR(EINVAL);
02502         }
02503     }
02504 
02505     /* init complex filtergraphs */
02506     for (i = 0; i < nb_filtergraphs; i++)
02507         if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
02508             return ret;
02509 
02510     /* for each output stream, we compute the right encoding parameters */
02511     for (i = 0; i < nb_output_streams; i++) {
02512         AVCodecContext *enc_ctx;
02513         AVCodecContext *dec_ctx = NULL;
02514         ost = output_streams[i];
02515         oc  = output_files[ost->file_index]->ctx;
02516         ist = get_input_stream(ost);
02517 
02518         if (ost->attachment_filename)
02519             continue;
02520 
02521         enc_ctx = ost->enc_ctx;
02522 
02523         if (ist) {
02524             dec_ctx = ist->dec_ctx;
02525 
02526             ost->st->disposition          = ist->st->disposition;
02527             enc_ctx->bits_per_raw_sample    = dec_ctx->bits_per_raw_sample;
02528             enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
02529         } else {
02530             for (j=0; j<oc->nb_streams; j++) {
02531                 AVStream *st = oc->streams[j];
02532                 if (st != ost->st && st->codec->codec_type == enc_ctx->codec_type)
02533                     break;
02534             }
02535             if (j == oc->nb_streams)
02536                 if (enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO || enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
02537                     ost->st->disposition = AV_DISPOSITION_DEFAULT;
02538         }
02539 
02540         if (ost->stream_copy) {
02541             AVRational sar;
02542             uint64_t extra_size;
02543 
02544             av_assert0(ist && !ost->filter);
02545 
02546             extra_size = (uint64_t)dec_ctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
02547 
02548             if (extra_size > INT_MAX) {
02549                 return AVERROR(EINVAL);
02550             }
02551 
02552             /* if stream_copy is selected, no need to decode or encode */
02553             enc_ctx->codec_id   = dec_ctx->codec_id;
02554             enc_ctx->codec_type = dec_ctx->codec_type;
02555 
02556             if (!enc_ctx->codec_tag) {
02557                 unsigned int codec_tag;
02558                 if (!oc->oformat->codec_tag ||
02559                      av_codec_get_id (oc->oformat->codec_tag, dec_ctx->codec_tag) == enc_ctx->codec_id ||
02560                      !av_codec_get_tag2(oc->oformat->codec_tag, dec_ctx->codec_id, &codec_tag))
02561                     enc_ctx->codec_tag = dec_ctx->codec_tag;
02562             }
02563 
02564             enc_ctx->bit_rate       = dec_ctx->bit_rate;
02565             enc_ctx->rc_max_rate    = dec_ctx->rc_max_rate;
02566             enc_ctx->rc_buffer_size = dec_ctx->rc_buffer_size;
02567             enc_ctx->field_order    = dec_ctx->field_order;
02568             enc_ctx->extradata      = av_mallocz(extra_size);
02569             if (!enc_ctx->extradata) {
02570                 return AVERROR(ENOMEM);
02571             }
02572             memcpy(enc_ctx->extradata, dec_ctx->extradata, dec_ctx->extradata_size);
02573             enc_ctx->extradata_size= dec_ctx->extradata_size;
02574             enc_ctx->bits_per_coded_sample  = dec_ctx->bits_per_coded_sample;
02575 
02576             enc_ctx->time_base = ist->st->time_base;
02577             /*
02578              * Avi is a special case here because it supports variable fps but
02579              * having the fps and timebase differe significantly adds quite some
02580              * overhead
02581              */
02582             if(!strcmp(oc->oformat->name, "avi")) {
02583                 if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
02584                                && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
02585                                && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(dec_ctx->time_base)
02586                                && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500
02587                      || copy_tb==2){
02588                     enc_ctx->time_base.num = ist->st->r_frame_rate.den;
02589                     enc_ctx->time_base.den = 2*ist->st->r_frame_rate.num;
02590                     enc_ctx->ticks_per_frame = 2;
02591                 } else if (   copy_tb<0 && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > 2*av_q2d(ist->st->time_base)
02592                                  && av_q2d(ist->st->time_base) < 1.0/500
02593                     || copy_tb==0){
02594                     enc_ctx->time_base = dec_ctx->time_base;
02595                     enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
02596                     enc_ctx->time_base.den *= 2;
02597                     enc_ctx->ticks_per_frame = 2;
02598                 }
02599             } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
02600                       && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
02601                       && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
02602                       && strcmp(oc->oformat->name, "f4v")
02603             ) {
02604                 if(   copy_tb<0 && dec_ctx->time_base.den
02605                                 && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > av_q2d(ist->st->time_base)
02606                                 && av_q2d(ist->st->time_base) < 1.0/500
02607                    || copy_tb==0){
02608                     enc_ctx->time_base = dec_ctx->time_base;
02609                     enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
02610                 }
02611             }
02612             if (   enc_ctx->codec_tag == AV_RL32("tmcd")
02613                 && dec_ctx->time_base.num < dec_ctx->time_base.den
02614                 && dec_ctx->time_base.num > 0
02615                 && 121LL*dec_ctx->time_base.num > dec_ctx->time_base.den) {
02616                 enc_ctx->time_base = dec_ctx->time_base;
02617             }
02618 
02619             if (ist && !ost->frame_rate.num)
02620                 ost->frame_rate = ist->framerate;
02621             if(ost->frame_rate.num)
02622                 enc_ctx->time_base = av_inv_q(ost->frame_rate);
02623 
02624             av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,
02625                         enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);
02626 
02627             ost->parser = av_parser_init(enc_ctx->codec_id);
02628 
02629             switch (enc_ctx->codec_type) {
02630             case AVMEDIA_TYPE_AUDIO:
02631                 if (audio_volume != 256) {
02632                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
02633                     exit_program(1);
02634                 }
02635                 enc_ctx->channel_layout     = dec_ctx->channel_layout;
02636                 enc_ctx->sample_rate        = dec_ctx->sample_rate;
02637                 enc_ctx->channels           = dec_ctx->channels;
02638                 enc_ctx->frame_size         = dec_ctx->frame_size;
02639                 enc_ctx->audio_service_type = dec_ctx->audio_service_type;
02640                 enc_ctx->block_align        = dec_ctx->block_align;
02641                 enc_ctx->delay              = dec_ctx->delay;
02642                 if((enc_ctx->block_align == 1 || enc_ctx->block_align == 1152 || enc_ctx->block_align == 576) && enc_ctx->codec_id == AV_CODEC_ID_MP3)
02643                     enc_ctx->block_align= 0;
02644                 if(enc_ctx->codec_id == AV_CODEC_ID_AC3)
02645                     enc_ctx->block_align= 0;
02646                 break;
02647             case AVMEDIA_TYPE_VIDEO:
02648                 enc_ctx->pix_fmt            = dec_ctx->pix_fmt;
02649                 enc_ctx->width              = dec_ctx->width;
02650                 enc_ctx->height             = dec_ctx->height;
02651                 enc_ctx->has_b_frames       = dec_ctx->has_b_frames;
02652                 if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
02653                     sar =
02654                         av_mul_q(ost->frame_aspect_ratio,
02655                                  (AVRational){ enc_ctx->height, enc_ctx->width });
02656                     av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
02657                            "with stream copy may produce invalid files\n");
02658                 }
02659                 else if (ist->st->sample_aspect_ratio.num)
02660                     sar = ist->st->sample_aspect_ratio;
02661                 else
02662                     sar = dec_ctx->sample_aspect_ratio;
02663                 ost->st->sample_aspect_ratio = enc_ctx->sample_aspect_ratio = sar;
02664                 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
02665                 break;
02666             case AVMEDIA_TYPE_SUBTITLE:
02667                 enc_ctx->width  = dec_ctx->width;
02668                 enc_ctx->height = dec_ctx->height;
02669                 break;
02670             case AVMEDIA_TYPE_DATA:
02671             case AVMEDIA_TYPE_ATTACHMENT:
02672                 break;
02673             default:
02674                 abort();
02675             }
02676         } else {
02677             if (!ost->enc)
02678                 ost->enc = avcodec_find_encoder(enc_ctx->codec_id);
02679             if (!ost->enc) {
02680                 /* should only happen when a default codec is not present. */
02681                 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
02682                          avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
02683                 ret = AVERROR(EINVAL);
02684                 goto dump_format;
02685             }
02686 
02687             if (ist)
02688                 ist->decoding_needed |= DECODING_FOR_OST;
02689             ost->encoding_needed = 1;
02690 
02691             set_encoder_id(output_files[ost->file_index], ost);
02692 
02693             if (!ost->filter &&
02694                 (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
02695                  enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO)) {
02696                     FilterGraph *fg;
02697                     fg = init_simple_filtergraph(ist, ost);
02698                     if (configure_filtergraph(fg)) {
02699                         av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
02700                         exit_program(1);
02701                     }
02702             }
02703 
02704             if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
02705                 if (ost->filter && !ost->frame_rate.num)
02706                     ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
02707                 if (ist && !ost->frame_rate.num)
02708                     ost->frame_rate = ist->framerate;
02709                 if (ist && !ost->frame_rate.num)
02710                     ost->frame_rate = ist->st->r_frame_rate;
02711                 if (ist && !ost->frame_rate.num) {
02712                     ost->frame_rate = (AVRational){25, 1};
02713                     av_log(NULL, AV_LOG_WARNING,
02714                            "No information "
02715                            "about the input framerate is available. Falling "
02716                            "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
02717                            "if you want a different framerate.\n",
02718                            ost->file_index, ost->index);
02719                 }
02720 //                    ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
02721                 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
02722                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
02723                     ost->frame_rate = ost->enc->supported_framerates[idx];
02724                 }
02725                 if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
02726                     av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
02727                               ost->frame_rate.num, ost->frame_rate.den, 65535);
02728                 }
02729             }
02730 
02731             switch (enc_ctx->codec_type) {
02732             case AVMEDIA_TYPE_AUDIO:
02733                 enc_ctx->sample_fmt     = ost->filter->filter->inputs[0]->format;
02734                 enc_ctx->sample_rate    = ost->filter->filter->inputs[0]->sample_rate;
02735                 enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
02736                 enc_ctx->channels       = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
02737                 enc_ctx->time_base      = (AVRational){ 1, enc_ctx->sample_rate };
02738                 break;
02739             case AVMEDIA_TYPE_VIDEO:
02740                 enc_ctx->time_base = av_inv_q(ost->frame_rate);
02741                 if (ost->filter && !(enc_ctx->time_base.num && enc_ctx->time_base.den))
02742                     enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;
02743                 if (   av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
02744                    && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
02745                     av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
02746                                                "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
02747                 }
02748                 for (j = 0; j < ost->forced_kf_count; j++)
02749                     ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
02750                                                          AV_TIME_BASE_Q,
02751                                                          enc_ctx->time_base);
02752 
02753                 enc_ctx->width  = ost->filter->filter->inputs[0]->w;
02754                 enc_ctx->height = ost->filter->filter->inputs[0]->h;
02755                 enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
02756                     ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
02757                     av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :
02758                     ost->filter->filter->inputs[0]->sample_aspect_ratio;
02759                 if (!strncmp(ost->enc->name, "libx264", 7) &&
02760                     enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
02761                     ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
02762                     av_log(NULL, AV_LOG_WARNING,
02763                            "No pixel format specified, %s for H.264 encoding chosen.\n"
02764                            "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
02765                            av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
02766                 if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
02767                     enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
02768                     ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
02769                     av_log(NULL, AV_LOG_WARNING,
02770                            "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
02771                            "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
02772                            av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
02773                 enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;
02774 
02775                 ost->st->avg_frame_rate = ost->frame_rate;
02776 
02777                 if (!dec_ctx ||
02778                     enc_ctx->width   != dec_ctx->width  ||
02779                     enc_ctx->height  != dec_ctx->height ||
02780                     enc_ctx->pix_fmt != dec_ctx->pix_fmt) {
02781                     enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample;
02782                 }
02783 
02784                 if (ost->forced_keyframes) {
02785                     if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
02786                         ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
02787                                             forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
02788                         if (ret < 0) {
02789                             av_log(NULL, AV_LOG_ERROR,
02790                                    "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
02791                             return ret;
02792                         }
02793                         ost->forced_keyframes_expr_const_values[FKF_N] = 0;
02794                         ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
02795                         ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
02796                         ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
02797                     } else {
02798                         parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx);
02799                     }
02800                 }
02801                 break;
02802             case AVMEDIA_TYPE_SUBTITLE:
02803                 enc_ctx->time_base = (AVRational){1, 1000};
02804                 if (!enc_ctx->width) {
02805                     enc_ctx->width     = input_streams[ost->source_index]->st->codec->width;
02806                     enc_ctx->height    = input_streams[ost->source_index]->st->codec->height;
02807                 }
02808                 break;
02809             default:
02810                 abort();
02811                 break;
02812             }
02813             /* two pass mode */
02814             if (enc_ctx->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
02815                 char logfilename[1024];
02816                 FILE *f;
02817 
02818                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
02819                          ost->logfile_prefix ? ost->logfile_prefix :
02820                                                DEFAULT_PASS_LOGFILENAME_PREFIX,
02821                          i);
02822                 if (!strcmp(ost->enc->name, "libx264")) {
02823                     av_dict_set(&ost->encoder_opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
02824                 } else {
02825                     if (enc_ctx->flags & CODEC_FLAG_PASS2) {
02826                         char  *logbuffer;
02827                         size_t logbuffer_size;
02828                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
02829                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
02830                                    logfilename);
02831                             exit_program(1);
02832                         }
02833                         enc_ctx->stats_in = logbuffer;
02834                     }
02835                     if (enc_ctx->flags & CODEC_FLAG_PASS1) {
02836                         f = av_fopen_utf8(logfilename, "wb");
02837                         if (!f) {
02838                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
02839                                 logfilename, strerror(errno));
02840                             exit_program(1);
02841                         }
02842                         ost->logfile = f;
02843                     }
02844                 }
02845             }
02846         }
02847     }
02848 
02849     /* open each encoder */
02850     for (i = 0; i < nb_output_streams; i++) {
02851         ost = output_streams[i];
02852         if (ost->encoding_needed) {
02853             AVCodec      *codec = ost->enc;
02854             AVCodecContext *dec = NULL;
02855 
02856             if ((ist = get_input_stream(ost)))
02857                 dec = ist->dec_ctx;
02858             if (dec && dec->subtitle_header) {
02859                 /* ASS code assumes this buffer is null terminated so add extra byte. */
02860                 ost->enc_ctx->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
02861                 if (!ost->enc_ctx->subtitle_header) {
02862                     ret = AVERROR(ENOMEM);
02863                     goto dump_format;
02864                 }
02865                 memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
02866                 ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
02867             }
02868             if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
02869                 av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
02870             av_dict_set(&ost->encoder_opts, "side_data_only_packets", "1", 0);
02871 
02872             if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
02873                 if (ret == AVERROR_EXPERIMENTAL)
02874                     abort_codec_experimental(codec, 1);
02875                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
02876                         ost->file_index, ost->index);
02877                 goto dump_format;
02878             }
02879             if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
02880                 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
02881                 av_buffersink_set_frame_size(ost->filter->filter,
02882                                              ost->enc_ctx->frame_size);
02883             assert_avoptions(ost->encoder_opts);
02884             if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
02885                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
02886                                              " It takes bits/s as argument, not kbits/s\n");
02887         } else {
02888             if (av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts) < 0) {
02889                 av_log(NULL, AV_LOG_FATAL,
02890                     "Error setting up codec context options.\n");
02891                 exit_program(1);
02892             }
02893         }
02894 
02895         ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);
02896         if (ret < 0) {
02897             av_log(NULL, AV_LOG_FATAL,
02898                    "Error initializing the output stream codec context.\n");
02899             exit_program(1);
02900         }
02901         ost->st->codec->codec= ost->enc_ctx->codec;
02902 
02903         // copy timebase while removing common factors
02904         ost->st->time_base = av_add_q(ost->enc_ctx->time_base, (AVRational){0, 1});
02905     }
02906 
02907     /* init input streams */
02908     for (i = 0; i < nb_input_streams; i++)
02909         if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
02910             for (i = 0; i < nb_output_streams; i++) {
02911                 ost = output_streams[i];
02912                 avcodec_close(ost->enc_ctx);
02913             }
02914             goto dump_format;
02915         }
02916 
02917     /* discard unused programs */
02918     for (i = 0; i < nb_input_files; i++) {
02919         InputFile *ifile = input_files[i];
02920         for (j = 0; j < ifile->ctx->nb_programs; j++) {
02921             AVProgram *p = ifile->ctx->programs[j];
02922             int discard  = AVDISCARD_ALL;
02923 
02924             for (k = 0; k < p->nb_stream_indexes; k++)
02925                 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
02926                     discard = AVDISCARD_DEFAULT;
02927                     break;
02928                 }
02929             p->discard = discard;
02930         }
02931     }
02932 
02933     /* open files and write file headers */
02934     for (i = 0; i < nb_output_files; i++) {
02935         oc = output_files[i]->ctx;
02936         oc->interrupt_callback = int_cb;
02937         if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
02938             snprintf(error, sizeof(error),
02939                      "Could not write header for output file #%d "
02940                      "(incorrect codec parameters ?): %s",
02941                      i, av_err2str(ret));
02942             ret = AVERROR(EINVAL);
02943             goto dump_format;
02944         }
02945 //         assert_avoptions(output_files[i]->opts);
02946         if (strcmp(oc->oformat->name, "rtp")) {
02947             want_sdp = 0;
02948         }
02949     }
02950 
02951  dump_format:
02952     /* dump the file output parameters - cannot be done before in case
02953        of stream copy */
02954     for (i = 0; i < nb_output_files; i++) {
02955         av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
02956     }
02957 
02958     /* dump the stream mapping */
02959     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
02960     for (i = 0; i < nb_input_streams; i++) {
02961         ist = input_streams[i];
02962 
02963         for (j = 0; j < ist->nb_filters; j++) {
02964             if (ist->filters[j]->graph->graph_desc) {
02965                 av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
02966                        ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
02967                        ist->filters[j]->name);
02968                 if (nb_filtergraphs > 1)
02969                     av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
02970                 av_log(NULL, AV_LOG_INFO, "\n");
02971             }
02972         }
02973     }
02974 
02975     for (i = 0; i < nb_output_streams; i++) {
02976         ost = output_streams[i];
02977 
02978         if (ost->attachment_filename) {
02979             /* an attached file */
02980             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
02981                    ost->attachment_filename, ost->file_index, ost->index);
02982             continue;
02983         }
02984 
02985         if (ost->filter && ost->filter->graph->graph_desc) {
02986             /* output from a complex graph */
02987             av_log(NULL, AV_LOG_INFO, "  %s", ost->filter->name);
02988             if (nb_filtergraphs > 1)
02989                 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
02990 
02991             av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
02992                    ost->index, ost->enc ? ost->enc->name : "?");
02993             continue;
02994         }
02995 
02996         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
02997                input_streams[ost->source_index]->file_index,
02998                input_streams[ost->source_index]->st->index,
02999                ost->file_index,
03000                ost->index);
03001         if (ost->sync_ist != input_streams[ost->source_index])
03002             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
03003                    ost->sync_ist->file_index,
03004                    ost->sync_ist->st->index);
03005         if (ost->stream_copy)
03006             av_log(NULL, AV_LOG_INFO, " (copy)");
03007         else {
03008             const AVCodec *in_codec    = input_streams[ost->source_index]->dec;
03009             const AVCodec *out_codec   = ost->enc;
03010             const char *decoder_name   = "?";
03011             const char *in_codec_name  = "?";
03012             const char *encoder_name   = "?";
03013             const char *out_codec_name = "?";
03014 
03015             if (in_codec) {
03016                 decoder_name  = in_codec->name;
03017                 in_codec_name = avcodec_descriptor_get(in_codec->id)->name;
03018                 if (!strcmp(decoder_name, in_codec_name))
03019                     decoder_name = "native";
03020             }
03021 
03022             if (out_codec) {
03023                 encoder_name   = out_codec->name;
03024                 out_codec_name = avcodec_descriptor_get(out_codec->id)->name;
03025                 if (!strcmp(encoder_name, out_codec_name))
03026                     encoder_name = "native";
03027             }
03028 
03029             av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
03030                    in_codec_name, decoder_name,
03031                    out_codec_name, encoder_name);
03032         }
03033         av_log(NULL, AV_LOG_INFO, "\n");
03034     }
03035 
03036     if (ret) {
03037         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
03038         return ret;
03039     }
03040 
03041     if (want_sdp) {
03042         print_sdp();
03043     }
03044 
03045     transcode_init_done = 1;
03046 
03047     return 0;
03048 }
03049 
03050 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
03051 static int need_output(void)
03052 {
03053     int i;
03054 
03055     for (i = 0; i < nb_output_streams; i++) {
03056         OutputStream *ost    = output_streams[i];
03057         OutputFile *of       = output_files[ost->file_index];
03058         AVFormatContext *os  = output_files[ost->file_index]->ctx;
03059 
03060         if (ost->finished ||
03061             (os->pb && avio_tell(os->pb) >= of->limit_filesize))
03062             continue;
03063         if (ost->frame_number >= ost->max_frames) {
03064             int j;
03065             for (j = 0; j < of->ctx->nb_streams; j++)
03066                 close_output_stream(output_streams[of->ost_index + j]);
03067             continue;
03068         }
03069 
03070         return 1;
03071     }
03072 
03073     return 0;
03074 }
03075 
03081 static OutputStream *choose_output(void)
03082 {
03083     int i;
03084     int64_t opts_min = INT64_MAX;
03085     OutputStream *ost_min = NULL;
03086 
03087     for (i = 0; i < nb_output_streams; i++) {
03088         OutputStream *ost = output_streams[i];
03089         int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
03090                                     AV_TIME_BASE_Q);
03091         if (!ost->unavailable && !ost->finished && opts < opts_min) {
03092             opts_min = opts;
03093             ost_min  = ost;
03094         }
03095     }
03096     return ost_min;
03097 }
03098 
03099 static int check_keyboard_interaction(int64_t cur_time)
03100 {
03101     int i, ret, key;
03102     static int64_t last_time;
03103     if (received_nb_signals)
03104         return AVERROR_EXIT;
03105     /* read_key() returns 0 on EOF */
03106     if(cur_time - last_time >= 100000 && !run_as_daemon){
03107         key =  read_key();
03108         last_time = cur_time;
03109     }else
03110         key = -1;
03111     if (key == 'q')
03112         return AVERROR_EXIT;
03113     if (key == '+') av_log_set_level(av_log_get_level()+10);
03114     if (key == '-') av_log_set_level(av_log_get_level()-10);
03115     if (key == 's') qp_hist     ^= 1;
03116     if (key == 'h'){
03117         if (do_hex_dump){
03118             do_hex_dump = do_pkt_dump = 0;
03119         } else if(do_pkt_dump){
03120             do_hex_dump = 1;
03121         } else
03122             do_pkt_dump = 1;
03123         av_log_set_level(AV_LOG_DEBUG);
03124     }
03125     if (key == 'c' || key == 'C'){
03126         char buf[4096], target[64], command[256], arg[256] = {0};
03127         double time;
03128         int k, n = 0;
03129         fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
03130         i = 0;
03131         while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
03132             if (k > 0)
03133                 buf[i++] = k;
03134         buf[i] = 0;
03135         if (k > 0 &&
03136             (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
03137             av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
03138                    target, time, command, arg);
03139             for (i = 0; i < nb_filtergraphs; i++) {
03140                 FilterGraph *fg = filtergraphs[i];
03141                 if (fg->graph) {
03142                     if (time < 0) {
03143                         ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
03144                                                           key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
03145                         fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
03146                     } else if (key == 'c') {
03147                         fprintf(stderr, "Queing commands only on filters supporting the specific command is unsupported\n");
03148                         ret = AVERROR_PATCHWELCOME;
03149                     } else {
03150                         ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
03151                     }
03152                 }
03153             }
03154         } else {
03155             av_log(NULL, AV_LOG_ERROR,
03156                    "Parse error, at least 3 arguments were expected, "
03157                    "only %d given in string '%s'\n", n, buf);
03158         }
03159     }
03160     if (key == 'd' || key == 'D'){
03161         int debug=0;
03162         if(key == 'D') {
03163             debug = input_streams[0]->st->codec->debug<<1;
03164             if(!debug) debug = 1;
03165             while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
03166                 debug += debug;
03167         }else
03168             if(scanf("%d", &debug)!=1)
03169                 fprintf(stderr,"error parsing debug value\n");
03170         for(i=0;i<nb_input_streams;i++) {
03171             input_streams[i]->st->codec->debug = debug;
03172         }
03173         for(i=0;i<nb_output_streams;i++) {
03174             OutputStream *ost = output_streams[i];
03175             ost->enc_ctx->debug = debug;
03176         }
03177         if(debug) av_log_set_level(AV_LOG_DEBUG);
03178         fprintf(stderr,"debug=%d\n", debug);
03179     }
03180     if (key == '?'){
03181         fprintf(stderr, "key    function\n"
03182                         "?      show this help\n"
03183                         "+      increase verbosity\n"
03184                         "-      decrease verbosity\n"
03185                         "c      Send command to first matching filter supporting it\n"
03186                         "C      Send/Que command to all matching filters\n"
03187                         "D      cycle through available debug modes\n"
03188                         "h      dump packets/hex press to cycle through the 3 states\n"
03189                         "q      quit\n"
03190                         "s      Show QP histogram\n"
03191         );
03192     }
03193     return 0;
03194 }
03195 
03196 #if HAVE_PTHREADS
03197 static void *input_thread(void *arg)
03198 {
03199     InputFile *f = arg;
03200     int ret = 0;
03201 
03202     while (1) {
03203         AVPacket pkt;
03204         ret = av_read_frame(f->ctx, &pkt);
03205 
03206         if (ret == AVERROR(EAGAIN)) {
03207             av_usleep(10000);
03208             continue;
03209         }
03210         if (ret < 0) {
03211             av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
03212             break;
03213         }
03214         av_dup_packet(&pkt);
03215         ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, 0);
03216         if (ret < 0) {
03217             if (ret != AVERROR_EOF)
03218                 av_log(f->ctx, AV_LOG_ERROR,
03219                        "Unable to send packet to main thread: %s\n",
03220                        av_err2str(ret));
03221             av_free_packet(&pkt);
03222             av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
03223             break;
03224         }
03225     }
03226 
03227     return NULL;
03228 }
03229 
03230 static void free_input_threads(void)
03231 {
03232     int i;
03233 
03234     for (i = 0; i < nb_input_files; i++) {
03235         InputFile *f = input_files[i];
03236         AVPacket pkt;
03237 
03238         if (!f->in_thread_queue)
03239             continue;
03240         av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
03241         while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
03242             av_free_packet(&pkt);
03243 
03244         pthread_join(f->thread, NULL);
03245         f->joined = 1;
03246         av_thread_message_queue_free(&f->in_thread_queue);
03247     }
03248 }
03249 
03250 static int init_input_threads(void)
03251 {
03252     int i, ret;
03253 
03254     if (nb_input_files == 1)
03255         return 0;
03256 
03257     for (i = 0; i < nb_input_files; i++) {
03258         InputFile *f = input_files[i];
03259 
03260         if (f->ctx->pb ? !f->ctx->pb->seekable :
03261             strcmp(f->ctx->iformat->name, "lavfi"))
03262             f->non_blocking = 1;
03263         ret = av_thread_message_queue_alloc(&f->in_thread_queue,
03264                                             8, sizeof(AVPacket));
03265         if (ret < 0)
03266             return ret;
03267 
03268         if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
03269             av_log(NULL, AV_LOG_ERROR, "pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
03270             av_thread_message_queue_free(&f->in_thread_queue);
03271             return AVERROR(ret);
03272         }
03273     }
03274     return 0;
03275 }
03276 
03277 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
03278 {
03279     return av_thread_message_queue_recv(f->in_thread_queue, pkt,
03280                                         f->non_blocking ?
03281                                         AV_THREAD_MESSAGE_NONBLOCK : 0);
03282 }
03283 #endif
03284 
03285 static int get_input_packet(InputFile *f, AVPacket *pkt)
03286 {
03287     if (f->rate_emu) {
03288         int i;
03289         for (i = 0; i < f->nb_streams; i++) {
03290             InputStream *ist = input_streams[f->ist_index + i];
03291             int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
03292             int64_t now = av_gettime_relative() - ist->start;
03293             if (pts > now)
03294                 return AVERROR(EAGAIN);
03295         }
03296     }
03297 
03298 #if HAVE_PTHREADS
03299     if (nb_input_files > 1)
03300         return get_input_packet_mt(f, pkt);
03301 #endif
03302     return av_read_frame(f->ctx, pkt);
03303 }
03304 
03305 static int got_eagain(void)
03306 {
03307     int i;
03308     for (i = 0; i < nb_output_streams; i++)
03309         if (output_streams[i]->unavailable)
03310             return 1;
03311     return 0;
03312 }
03313 
03314 static void reset_eagain(void)
03315 {
03316     int i;
03317     for (i = 0; i < nb_input_files; i++)
03318         input_files[i]->eagain = 0;
03319     for (i = 0; i < nb_output_streams; i++)
03320         output_streams[i]->unavailable = 0;
03321 }
03322 
03323 /*
03324  * Return
03325  * - 0 -- one packet was read and processed
03326  * - AVERROR(EAGAIN) -- no packets were available for selected file,
03327  *   this function should be called again
03328  * - AVERROR_EOF -- this function should not be called again
03329  */
03330 static int process_input(int file_index)
03331 {
03332     InputFile *ifile = input_files[file_index];
03333     AVFormatContext *is;
03334     InputStream *ist;
03335     AVPacket pkt;
03336     int ret, i, j;
03337 
03338     is  = ifile->ctx;
03339     ret = get_input_packet(ifile, &pkt);
03340 
03341     if (ret == AVERROR(EAGAIN)) {
03342         ifile->eagain = 1;
03343         return ret;
03344     }
03345     if (ret < 0) {
03346         if (ret != AVERROR_EOF) {
03347             print_error(is->filename, ret);
03348             if (exit_on_error)
03349                 exit_program(1);
03350         }
03351 
03352         for (i = 0; i < ifile->nb_streams; i++) {
03353             ist = input_streams[ifile->ist_index + i];
03354             if (ist->decoding_needed) {
03355                 ret = process_input_packet(ist, NULL);
03356                 if (ret>0)
03357                     return 0;
03358             }
03359 
03360             /* mark all outputs that don't go through lavfi as finished */
03361             for (j = 0; j < nb_output_streams; j++) {
03362                 OutputStream *ost = output_streams[j];
03363 
03364                 if (ost->source_index == ifile->ist_index + i &&
03365                     (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
03366                     finish_output_stream(ost);
03367             }
03368         }
03369 
03370         ifile->eof_reached = 1;
03371         return AVERROR(EAGAIN);
03372     }
03373 
03374     reset_eagain();
03375 
03376     if (do_pkt_dump) {
03377         av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
03378                          is->streams[pkt.stream_index]);
03379     }
03380     /* the following test is needed in case new streams appear
03381        dynamically in stream : we ignore them */
03382     if (pkt.stream_index >= ifile->nb_streams) {
03383         report_new_stream(file_index, &pkt);
03384         goto discard_packet;
03385     }
03386 
03387     ist = input_streams[ifile->ist_index + pkt.stream_index];
03388 
03389     ist->data_size += pkt.size;
03390     ist->nb_packets++;
03391 
03392     if (ist->discard)
03393         goto discard_packet;
03394 
03395     if (debug_ts) {
03396         av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
03397                "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",
03398                ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
03399                av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
03400                av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
03401                av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
03402                av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
03403                av_ts2str(input_files[ist->file_index]->ts_offset),
03404                av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
03405     }
03406 
03407     if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
03408         int64_t stime, stime2;
03409         // Correcting starttime based on the enabled streams
03410         // 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.
03411         //       so we instead do it here as part of discontinuity handling
03412         if (   ist->next_dts == AV_NOPTS_VALUE
03413             && ifile->ts_offset == -is->start_time
03414             && (is->iformat->flags & AVFMT_TS_DISCONT)) {
03415             int64_t new_start_time = INT64_MAX;
03416             for (i=0; i<is->nb_streams; i++) {
03417                 AVStream *st = is->streams[i];
03418                 if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
03419                     continue;
03420                 new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
03421             }
03422             if (new_start_time > is->start_time) {
03423                 av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
03424                 ifile->ts_offset = -new_start_time;
03425             }
03426         }
03427 
03428         stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
03429         stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
03430         ist->wrap_correction_done = 1;
03431 
03432         if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
03433             pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
03434             ist->wrap_correction_done = 0;
03435         }
03436         if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
03437             pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
03438             ist->wrap_correction_done = 0;
03439         }
03440     }
03441 
03442     /* add the stream-global side data to the first packet */
03443     if (ist->nb_packets == 1) {
03444         if (ist->st->nb_side_data)
03445             av_packet_split_side_data(&pkt);
03446         for (i = 0; i < ist->st->nb_side_data; i++) {
03447             AVPacketSideData *src_sd = &ist->st->side_data[i];
03448             uint8_t *dst_data;
03449 
03450             if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
03451                 continue;
03452 
03453             dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
03454             if (!dst_data)
03455                 exit_program(1);
03456 
03457             memcpy(dst_data, src_sd->data, src_sd->size);
03458         }
03459     }
03460 
03461     if (pkt.dts != AV_NOPTS_VALUE)
03462         pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
03463     if (pkt.pts != AV_NOPTS_VALUE)
03464         pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
03465 
03466     if (pkt.pts != AV_NOPTS_VALUE)
03467         pkt.pts *= ist->ts_scale;
03468     if (pkt.dts != AV_NOPTS_VALUE)
03469         pkt.dts *= ist->ts_scale;
03470 
03471     if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
03472         && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
03473         int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
03474         int64_t delta   = pkt_dts - ifile->last_ts;
03475         if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
03476             (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
03477                 ist->dec_ctx->codec_type != AVMEDIA_TYPE_SUBTITLE)){
03478             ifile->ts_offset -= delta;
03479             av_log(NULL, AV_LOG_DEBUG,
03480                    "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
03481                    delta, ifile->ts_offset);
03482             pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
03483             if (pkt.pts != AV_NOPTS_VALUE)
03484                 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
03485         }
03486     }
03487 
03488     if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
03489         !copy_ts) {
03490         int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
03491         int64_t delta   = pkt_dts - ist->next_dts;
03492         if (is->iformat->flags & AVFMT_TS_DISCONT) {
03493             if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
03494                 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
03495                  ist->dec_ctx->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
03496                 pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {
03497                 ifile->ts_offset -= delta;
03498                 av_log(NULL, AV_LOG_DEBUG,
03499                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
03500                        delta, ifile->ts_offset);
03501                 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
03502                 if (pkt.pts != AV_NOPTS_VALUE)
03503                     pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
03504             }
03505         } else {
03506             if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
03507                 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->dec_ctx->codec_type != AVMEDIA_TYPE_SUBTITLE)) {
03508                 av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
03509                 pkt.dts = AV_NOPTS_VALUE;
03510             }
03511             if (pkt.pts != AV_NOPTS_VALUE){
03512                 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
03513                 delta   = pkt_pts - ist->next_dts;
03514                 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
03515                     (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->dec_ctx->codec_type != AVMEDIA_TYPE_SUBTITLE)) {
03516                     av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
03517                     pkt.pts = AV_NOPTS_VALUE;
03518                 }
03519             }
03520         }
03521     }
03522 
03523     if (pkt.dts != AV_NOPTS_VALUE)
03524         ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
03525 
03526     if (debug_ts) {
03527         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",
03528                ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
03529                av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
03530                av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
03531                av_ts2str(input_files[ist->file_index]->ts_offset),
03532                av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
03533     }
03534 
03535     sub2video_heartbeat(ist, pkt.pts);
03536 
03537     ret = process_input_packet(ist, &pkt);
03538     if (ret < 0) {
03539         av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
03540                ist->file_index, ist->st->index, av_err2str(ret));
03541         if (exit_on_error)
03542             exit_program(1);
03543     }
03544 
03545 discard_packet:
03546     av_free_packet(&pkt);
03547 
03548     return 0;
03549 }
03550 
03558 static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
03559 {
03560     int i, ret;
03561     int nb_requests, nb_requests_max = 0;
03562     InputFilter *ifilter;
03563     InputStream *ist;
03564 
03565     *best_ist = NULL;
03566     ret = avfilter_graph_request_oldest(graph->graph);
03567     if (ret >= 0)
03568         return reap_filters();
03569 
03570     if (ret == AVERROR_EOF) {
03571         ret = reap_filters();
03572         for (i = 0; i < graph->nb_outputs; i++)
03573             close_output_stream(graph->outputs[i]->ost);
03574         return ret;
03575     }
03576     if (ret != AVERROR(EAGAIN))
03577         return ret;
03578 
03579     for (i = 0; i < graph->nb_inputs; i++) {
03580         ifilter = graph->inputs[i];
03581         ist = ifilter->ist;
03582         if (input_files[ist->file_index]->eagain ||
03583             input_files[ist->file_index]->eof_reached)
03584             continue;
03585         nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
03586         if (nb_requests > nb_requests_max) {
03587             nb_requests_max = nb_requests;
03588             *best_ist = ist;
03589         }
03590     }
03591 
03592     if (!*best_ist)
03593         for (i = 0; i < graph->nb_outputs; i++)
03594             graph->outputs[i]->ost->unavailable = 1;
03595 
03596     return 0;
03597 }
03598 
03604 static int transcode_step(void)
03605 {
03606     OutputStream *ost;
03607     InputStream  *ist;
03608     int ret;
03609 
03610     ost = choose_output();
03611     if (!ost) {
03612         if (got_eagain()) {
03613             reset_eagain();
03614             av_usleep(10000);
03615             return 0;
03616         }
03617         av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
03618         return AVERROR_EOF;
03619     }
03620 
03621     if (ost->filter) {
03622         if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
03623             return ret;
03624         if (!ist)
03625             return 0;
03626     } else {
03627         av_assert0(ost->source_index >= 0);
03628         ist = input_streams[ost->source_index];
03629     }
03630 
03631     ret = process_input(ist->file_index);
03632     if (ret == AVERROR(EAGAIN)) {
03633         if (input_files[ist->file_index]->eagain)
03634             ost->unavailable = 1;
03635         return 0;
03636     }
03637     if (ret < 0)
03638         return ret == AVERROR_EOF ? 0 : ret;
03639 
03640     return reap_filters();
03641 }
03642 
03643 /*
03644  * The following code is the main loop of the file converter
03645  */
03646 static int transcode(void)
03647 {
03648     int ret, i;
03649     AVFormatContext *os;
03650     OutputStream *ost;
03651     InputStream *ist;
03652     int64_t timer_start;
03653 
03654     ret = transcode_init();
03655     if (ret < 0)
03656         goto fail;
03657 
03658     if (stdin_interaction) {
03659         av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
03660     }
03661 
03662     timer_start = av_gettime_relative();
03663 
03664 #if HAVE_PTHREADS
03665     if ((ret = init_input_threads()) < 0)
03666         goto fail;
03667 #endif
03668 
03669     while (!received_sigterm) {
03670         int64_t cur_time= av_gettime_relative();
03671 
03672         /* if 'q' pressed, exits */
03673         if (stdin_interaction)
03674             if (check_keyboard_interaction(cur_time) < 0)
03675                 break;
03676 
03677         /* check if there's any stream where output is still needed */
03678         if (!need_output()) {
03679             av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
03680             break;
03681         }
03682 
03683         ret = transcode_step();
03684         if (ret < 0) {
03685             if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
03686                 continue;
03687 
03688             av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
03689             break;
03690         }
03691 
03692         /* dump report by using the output first video and audio streams */
03693         print_report(0, timer_start, cur_time);
03694     }
03695 #if HAVE_PTHREADS
03696     free_input_threads();
03697 #endif
03698 
03699     /* at the end of stream, we must flush the decoder buffers */
03700     for (i = 0; i < nb_input_streams; i++) {
03701         ist = input_streams[i];
03702         if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
03703             process_input_packet(ist, NULL);
03704         }
03705     }
03706     flush_encoders();
03707 
03708     term_exit();
03709 
03710     /* write the trailer if needed and close file */
03711     for (i = 0; i < nb_output_files; i++) {
03712         os = output_files[i]->ctx;
03713         av_write_trailer(os);
03714     }
03715 
03716     /* dump report by using the first video and audio streams */
03717     print_report(1, timer_start, av_gettime_relative());
03718 
03719     /* close each encoder */
03720     for (i = 0; i < nb_output_streams; i++) {
03721         ost = output_streams[i];
03722         if (ost->encoding_needed) {
03723             av_freep(&ost->enc_ctx->stats_in);
03724         }
03725     }
03726 
03727     /* close each decoder */
03728     for (i = 0; i < nb_input_streams; i++) {
03729         ist = input_streams[i];
03730         if (ist->decoding_needed) {
03731             avcodec_close(ist->dec_ctx);
03732             if (ist->hwaccel_uninit)
03733                 ist->hwaccel_uninit(ist->dec_ctx);
03734         }
03735     }
03736 
03737     /* finished ! */
03738     ret = 0;
03739 
03740  fail:
03741 #if HAVE_PTHREADS
03742     free_input_threads();
03743 #endif
03744 
03745     if (output_streams) {
03746         for (i = 0; i < nb_output_streams; i++) {
03747             ost = output_streams[i];
03748             if (ost) {
03749                 if (ost->logfile) {
03750                     fclose(ost->logfile);
03751                     ost->logfile = NULL;
03752                 }
03753                 av_freep(&ost->forced_kf_pts);
03754                 av_freep(&ost->apad);
03755                 av_dict_free(&ost->encoder_opts);
03756                 av_dict_free(&ost->swr_opts);
03757                 av_dict_free(&ost->resample_opts);
03758             }
03759         }
03760     }
03761     return ret;
03762 }
03763 
03764 
03765 static int64_t getutime(void)
03766 {
03767 #if HAVE_GETRUSAGE
03768     struct rusage rusage;
03769 
03770     getrusage(RUSAGE_SELF, &rusage);
03771     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
03772 #elif HAVE_GETPROCESSTIMES
03773     HANDLE proc;
03774     FILETIME c, e, k, u;
03775     proc = GetCurrentProcess();
03776     GetProcessTimes(proc, &c, &e, &k, &u);
03777     return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
03778 #else
03779     return av_gettime();
03780 #endif
03781 }
03782 
03783 static int64_t getmaxrss(void)
03784 {
03785 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
03786     struct rusage rusage;
03787     getrusage(RUSAGE_SELF, &rusage);
03788     return (int64_t)rusage.ru_maxrss * 1024;
03789 #elif HAVE_GETPROCESSMEMORYINFO
03790     HANDLE proc;
03791     PROCESS_MEMORY_COUNTERS memcounters;
03792     proc = GetCurrentProcess();
03793     memcounters.cb = sizeof(memcounters);
03794     GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
03795     return memcounters.PeakPagefileUsage;
03796 #else
03797     return 0;
03798 #endif
03799 }
03800 
03801 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
03802 {
03803 }
03804 
03805 int main(int argc, char **argv)
03806 {
03807     int ret;
03808     int64_t ti;
03809 
03810     mainThreadId = gettid();
03811     register_exit(ffmpeg_cleanup);
03812 
03813     setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
03814 
03815     av_log_set_flags(AV_LOG_SKIP_REPEATED);
03816     parse_loglevel(argc, argv, options);
03817 
03818     if(argc>1 && !strcmp(argv[1], "-d")){
03819         run_as_daemon=1;
03820         av_log_set_callback(log_callback_null);
03821         argc--;
03822         argv++;
03823     }
03824 
03825     avcodec_register_all();
03826 #if CONFIG_AVDEVICE
03827     avdevice_register_all();
03828 #endif
03829     avfilter_register_all();
03830     av_register_all();
03831     avformat_network_init();
03832 
03833     show_banner(argc, argv, options);
03834 
03835     term_init();
03836 
03837     /* parse options and open all input/output files */
03838     ret = ffmpeg_parse_options(argc, argv);
03839     if (ret < 0)
03840         exit_program(1);
03841 
03842     if (nb_output_files <= 0 && nb_input_files == 0) {
03843         show_usage();
03844         av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
03845         exit_program(1);
03846     }
03847 
03848     /* file converter / grab */
03849     if (nb_output_files <= 0) {
03850         av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
03851         exit_program(1);
03852     }
03853 
03854 //     if (nb_input_files == 0) {
03855 //         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
03856 //         exit_program(1);
03857 //     }
03858 
03859     current_time = ti = getutime();
03860     if (transcode() < 0)
03861         exit_program(1);
03862     ti = getutime() - ti;
03863     if (do_benchmark) {
03864         printf("bench: utime=%0.3fs\n", ti / 1000000.0);
03865     }
03866     av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
03867            decode_error_stat[0], decode_error_stat[1]);
03868     if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
03869         exit_program(69);
03870 
03871     exit_program(received_nb_signals ? 255 : main_return_code);
03872     return main_return_code;
03873 }


dji_ronin
Author(s):
autogenerated on Sat Jun 8 2019 20:15:31