74#include "libavformat/avformat.h"
75#include "libavdevice/avdevice.h"
76#include "libswresample/swresample.h"
77#include "libavutil/opt.h"
78#include "libavutil/channel_layout.h"
79#include "libavutil/parseutils.h"
80#include "libavutil/samplefmt.h"
81#include "libavutil/fifo.h"
82#include "libavutil/hwcontext.h"
83#include "libavutil/internal.h"
84#include "libavutil/intreadwrite.h"
85#include "libavutil/dict.h"
86#include "libavutil/display.h"
87#include "libavutil/mathematics.h"
88#include "libavutil/pixdesc.h"
89#include "libavutil/avstring.h"
90#include "libavutil/libm.h"
91#include "libavutil/imgutils.h"
92#include "libavutil/timestamp.h"
93#include "libavutil/bprint.h"
94#include "libavutil/time.h"
95#include "libavutil/thread.h"
96#include "libavutil/threadmessage.h"
97#include "libavcodec/mathops.h"
98#include "libavformat/os_support.h"
100# include "libavfilter/avfilter.h"
101# include "libavfilter/buffersrc.h"
102# include "libavfilter/buffersink.h"
104#if HAVE_SYS_RESOURCE_H
106#include <sys/types.h>
107#include <sys/resource.h>
108#elif HAVE_GETPROCESSTIMES
111#if HAVE_GETPROCESSMEMORYINFO
115#if HAVE_SETCONSOLECTRLHANDLER
121#include <sys/select.h>
126#include <sys/ioctl.h>
138#include "libavutil/avassert.h"
200extern int opt_map(
void *optctx,
const char *opt,
const char *arg);
201extern int opt_map_channel(
void *optctx,
const char *opt,
const char *arg);
203extern int opt_data_frames(
void *optctx,
const char *opt,
const char *arg);
204extern int opt_progress(
void *optctx,
const char *opt,
const char *arg);
205extern int opt_target(
void *optctx,
const char *opt,
const char *arg);
206extern int opt_vsync(
void *optctx,
const char *opt,
const char *arg);
207extern int opt_abort_on(
void *optctx,
const char *opt,
const char *arg);
209extern int opt_qscale(
void *optctx,
const char *opt,
const char *arg);
210extern int opt_profile(
void *optctx,
const char *opt,
const char *arg);
213extern int opt_attach(
void *optctx,
const char *opt,
const char *arg);
216extern int opt_video_codec(
void *optctx,
const char *opt,
const char *arg);
217extern int opt_sameq(
void *optctx,
const char *opt,
const char *arg);
218extern int opt_timecode(
void *optctx,
const char *opt,
const char *arg);
220extern int opt_vstats_file(
void *optctx,
const char *opt,
const char *arg);
221extern int opt_vstats(
void *optctx,
const char *opt,
const char *arg);
223extern int opt_old2new(
void *optctx,
const char *opt,
const char *arg);
224extern int opt_streamid(
void *optctx,
const char *opt,
const char *arg);
225extern int opt_bitrate(
void *optctx,
const char *opt,
const char *arg);
226extern int show_hwaccels(
void *optctx,
const char *opt,
const char *arg);
230extern int opt_audio_codec(
void *optctx,
const char *opt,
const char *arg);
232extern int opt_preset(
void *optctx,
const char *opt,
const char *arg);
237extern int opt_sdp_file(
void *optctx,
const char *opt,
const char *arg);
238extern int opt_data_codec(
void *optctx,
const char *opt,
const char *arg);
246__thread
struct termios oldtty;
247__thread
int restore_tty;
251static void free_input_threads(
void);
272 AVFrame *frame =
ist->sub2video.frame;
274 av_frame_unref(frame);
275 ist->sub2video.frame->width =
ist->dec_ctx->width ?
ist->dec_ctx->width :
ist->sub2video.w;
276 ist->sub2video.frame->height =
ist->dec_ctx->height ?
ist->dec_ctx->height :
ist->sub2video.h;
277 ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
278 if ((ret = av_frame_get_buffer(frame, 0)) < 0)
280 memset(frame->data[0], 0, frame->height * frame->linesize[0]);
287 uint32_t *pal, *dst2;
291 if (r->type != SUBTITLE_BITMAP) {
292 av_log(NULL, AV_LOG_WARNING,
"sub2video: non-bitmap subtitle\n");
295 if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
296 av_log(NULL, AV_LOG_WARNING,
"sub2video: rectangle (%d %d %d %d) overflowing %d %d\n",
297 r->x, r->y, r->w, r->h, w, h
302 dst += r->y * dst_linesize + r->x * 4;
304 pal = (uint32_t *)r->data[1];
305 for (y = 0; y < r->h; y++) {
306 dst2 = (uint32_t *)dst;
308 for (x = 0; x < r->w; x++)
309 *(dst2++) = pal[*(src2++)];
311 src += r->linesize[0];
317 AVFrame *frame =
ist->sub2video.frame;
321 av_assert1(frame->data[0]);
322 ist->sub2video.last_pts = frame->pts = pts;
323 for (i = 0; i <
ist->nb_filters; i++) {
324 ret = av_buffersrc_add_frame_flags(
ist->filters[i]->filter, frame,
325 AV_BUFFERSRC_FLAG_KEEP_REF |
326 AV_BUFFERSRC_FLAG_PUSH);
327 if (ret != AVERROR_EOF && ret < 0)
328 av_log(NULL, AV_LOG_WARNING,
"Error while add the frame to buffer source(%s).\n",
335 AVFrame *frame =
ist->sub2video.frame;
339 int64_t pts, end_pts;
344 pts = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
345 AV_TIME_BASE_Q,
ist->st->time_base);
346 end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000LL,
347 AV_TIME_BASE_Q,
ist->st->time_base);
348 num_rects = sub->num_rects;
354 pts =
ist->sub2video.initialize ?
355 heartbeat_pts :
ist->sub2video.end_pts;
360 av_log(
ist->dec_ctx, AV_LOG_ERROR,
361 "Impossible to get a blank canvas.\n");
364 dst = frame->data [0];
365 dst_linesize = frame->linesize[0];
366 for (i = 0; i < num_rects; i++)
369 ist->sub2video.end_pts = end_pts;
370 ist->sub2video.initialize = 0;
389 pts2 = av_rescale_q(pts,
ist->st->time_base, ist2->
st->time_base) - 1;
391 if (pts2 <= ist2->sub2video.last_pts)
398 for (j = 0, nb_reqs = 0; j < ist2->
nb_filters; j++)
399 nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->
filters[j]->
filter);
410 if (
ist->sub2video.end_pts < INT64_MAX)
412 for (i = 0; i <
ist->nb_filters; i++) {
413 ret = av_buffersrc_add_frame(
ist->filters[i]->filter, NULL);
414 if (ret != AVERROR_EOF && ret < 0)
415 av_log(NULL, AV_LOG_WARNING,
"Flush the frame error.\n");
425 tcsetattr (0, TCSANOW, &oldtty);
431 av_log(NULL, AV_LOG_QUIET,
"%s",
"");
451#if HAVE_SETCONSOLECTRLHANDLER
452static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
454 av_log(NULL, AV_LOG_DEBUG,
"\nReceived windows signal %ld\n", fdwCtrlType);
459 case CTRL_BREAK_EVENT:
463 case CTRL_CLOSE_EVENT:
464 case CTRL_LOGOFF_EVENT:
465 case CTRL_SHUTDOWN_EVENT:
477 av_log(NULL, AV_LOG_ERROR,
"Received unknown windows signal %ld\n", fdwCtrlType);
484#define SIGNAL(sig, func) \
486 action.sa_handler = func; \
487 sigaction(sig, &action, NULL); \
490#define SIGNAL(sig, func) \
497 #if defined __aarch64__ || defined __amd64__ || defined __x86_64__
498 struct sigaction action = {0};
500 struct sigaction action = {{0}};
506 sigfillset(&action.sa_mask);
509 action.sa_flags = SA_RESTART;
515 if (tcgetattr (0, &tty) == 0) {
519 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
520 |INLCR|IGNCR|ICRNL|IXON);
521 tty.c_oflag |= OPOST;
522 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
523 tty.c_cflag &= ~(CSIZE|PARENB);
528 tcsetattr (0, TCSANOW, &tty);
549 signal(SIGPIPE, SIG_IGN);
552#if HAVE_SETCONSOLECTRLHANDLER
553 SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
570 n = select(1, &rfds, NULL, NULL, &tv);
579# if HAVE_PEEKNAMEDPIPE
581 static HANDLE input_handle;
584 input_handle = GetStdHandle(STD_INPUT_HANDLE);
585 is_pipe = !GetConsoleMode(input_handle, &dw);
590 if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
624 av_log(NULL, AV_LOG_INFO,
"bench: maxrss=%ikB\n", maxrss);
629 avfilter_graph_free(&fg->
graph);
637 sizeof(frame), NULL);
638 av_frame_free(&frame);
641 if (
ist->sub2video.sub_queue) {
642 while (av_fifo_size(
ist->sub2video.sub_queue)) {
644 av_fifo_generic_read(
ist->sub2video.sub_queue,
645 &sub,
sizeof(sub), NULL);
646 avsubtitle_free(&sub);
648 av_fifo_freep(&
ist->sub2video.sub_queue);
651 av_freep(&ifilter->
name);
658 avfilter_inout_free(&ofilter->
out_tmp);
659 av_freep(&ofilter->
name);
681 if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
683 avformat_free_context(s);
684 av_dict_free(&of->
opts);
698 av_packet_free(&
ost->
pkt);
719 av_packet_free(&
pkt);
727 free_input_threads();
737 av_frame_free(&
ist->decoded_frame);
738 av_frame_free(&
ist->filter_frame);
739 av_packet_free(&
ist->pkt);
740 av_dict_free(&
ist->decoder_opts);
741 avsubtitle_free(&
ist->prev_sub.subtitle);
742 av_frame_free(&
ist->sub2video.frame);
743 av_freep(&
ist->filters);
744 av_freep(&
ist->hwaccel_device);
745 av_freep(&
ist->dts_buffer);
747 avcodec_free_context(&
ist->dec_ctx);
754 av_log(NULL, AV_LOG_ERROR,
755 "Error closing vstats file, loss of information possible: %s\n",
756 av_err2str(AVERROR(errno)));
767 avformat_network_deinit();
770 av_log(NULL, AV_LOG_INFO,
"Exiting normally, received signal %d.\n",
773 av_log(NULL, AV_LOG_INFO,
"Exiting normally, received cancel request.\n");
775 av_log(NULL, AV_LOG_INFO,
"Conversion failed!\n");
783 AVDictionaryEntry *t = NULL;
785 while ((t = av_dict_get(b,
"", t, AV_DICT_IGNORE_SUFFIX))) {
786 av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
792 AVDictionaryEntry *t;
793 if ((t = av_dict_get(m,
"", NULL, AV_DICT_IGNORE_SUFFIX))) {
794 av_log(NULL, AV_LOG_FATAL,
"Option %s not found.\n", t->key);
813 vsnprintf(buf,
sizeof(buf), fmt, va);
815 av_log(NULL, AV_LOG_INFO,
816 "bench: %8" PRIu64
" user %8" PRIu64
" sys %8" PRIu64
" real %s \n",
830 ost2->
finished |=
ost == ost2 ? this_stream : others;
836 AVFormatContext *s = of->
ctx;
850 av_packet_unref(
pkt);
860 unsigned int are_we_over_size =
862 int new_size = are_we_over_size ?
868 av_log(NULL, AV_LOG_ERROR,
869 "Too many packets buffered for output stream %d:%d.\n",
877 ret = av_packet_make_refcounted(
pkt);
880 tmp_pkt = av_packet_alloc();
883 av_packet_move_ref(tmp_pkt,
pkt);
885 av_fifo_generic_write(
ost->
muxing_queue, &tmp_pkt,
sizeof(tmp_pkt), NULL);
891 pkt->pts =
pkt->dts = AV_NOPTS_VALUE;
893 if (
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
895 uint8_t *sd = av_packet_get_side_data(
pkt, AV_PKT_DATA_QUALITY_STATS,
900 for (i = 0; i<FF_ARRAY_ELEMS(
ost->
error); i++) {
902 ost->
error[i] = AV_RL64(sd + 8 + 8*i);
908 if (
pkt->duration > 0)
909 av_log(NULL, AV_LOG_WARNING,
"Overriding packet duration by frame rate, this should not happen\n");
917 if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
918 if (
pkt->dts != AV_NOPTS_VALUE &&
919 pkt->pts != AV_NOPTS_VALUE &&
921 av_log(s, AV_LOG_WARNING,
"Invalid DTS: %"PRId64
" PTS: %"PRId64
" in output stream %d:%d, replacing by guess\n",
929 if ((
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) &&
930 pkt->dts != AV_NOPTS_VALUE &&
933 int64_t max =
ost->
last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
934 if (
pkt->dts < max) {
935 int loglevel = max -
pkt->dts > 2 ||
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
937 loglevel = AV_LOG_ERROR;
938 av_log(s, loglevel,
"Non-monotonous DTS in output stream "
939 "%d:%d; previous: %"PRId64
", current: %"PRId64
"; ",
942 av_log(NULL, AV_LOG_FATAL,
"aborting.\n");
945 av_log(s, loglevel,
"changing to %"PRId64
". This may result "
946 "in incorrect timestamps in the output file.\n",
949 pkt->pts = FFMAX(
pkt->pts, max);
962 av_log(NULL, AV_LOG_INFO,
"muxer <- type:%s "
963 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
964 av_get_media_type_string(
ost->
enc_ctx->codec_type),
965 av_ts2str(
pkt->pts), av_ts2timestr(
pkt->pts, &
ost->
st->time_base),
966 av_ts2str(
pkt->dts), av_ts2timestr(
pkt->dts, &
ost->
st->time_base),
971 ret = av_interleaved_write_frame(s,
pkt);
977 av_packet_unref(
pkt);
1014 if (
ret == AVERROR(EAGAIN))
1020 if (
ret < 0 &&
ret != AVERROR_EOF) {
1021 av_log(NULL, AV_LOG_ERROR,
"Error applying bitstream filters to an output "
1034 AV_TIME_BASE_Q) >= 0) {
1043 double float_pts = AV_NOPTS_VALUE;
1045 if (!frame || frame->pts == AV_NOPTS_VALUE ||
1053 AVRational filter_tb = av_buffersink_get_time_base(
filter);
1054 AVRational tb = enc->time_base;
1055 int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
1057 tb.den <<= extra_bits;
1059 av_rescale_q(frame->pts, filter_tb, tb) -
1060 av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
1061 float_pts /= 1 << extra_bits;
1063 float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
1066 av_rescale_q(frame->pts, filter_tb, enc->time_base) -
1067 av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
1073 av_log(NULL, AV_LOG_INFO,
"filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
1074 frame ? av_ts2str(frame->pts) :
"NULL",
1075 frame ? av_ts2timestr(frame->pts, &enc->time_base) :
"NULL",
1077 enc ? enc->time_base.num : -1,
1078 enc ? enc->time_base.den : -1);
1088 int ret = AVERROR_BUG;
1089 char error[1024] = {0};
1096 av_log(NULL, AV_LOG_ERROR,
"Error initializing output stream %d:%d -- %s\n",
1126 av_log(NULL, AV_LOG_INFO,
"encoder <- type:audio "
1127 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1128 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
1129 enc->time_base.num, enc->time_base.den);
1132 ret = avcodec_send_frame(enc, frame);
1137 av_packet_unref(
pkt);
1138 ret = avcodec_receive_packet(enc,
pkt);
1139 if (
ret == AVERROR(EAGAIN))
1149 av_log(NULL, AV_LOG_INFO,
"encoder -> type:audio "
1150 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1151 av_ts2str(
pkt->pts), av_ts2timestr(
pkt->pts, &enc->time_base),
1152 av_ts2str(
pkt->dts), av_ts2timestr(
pkt->dts, &enc->time_base));
1160 av_log(NULL, AV_LOG_FATAL,
"Audio encoding failed\n");
1168 int subtitle_out_max_size = 1024 * 1024;
1169 int subtitle_out_size, nb, i;
1170 AVCodecContext *enc;
1174 if (sub->pts == AV_NOPTS_VALUE) {
1175 av_log(NULL, AV_LOG_ERROR,
"Subtitle packets must have a pts\n");
1186 av_log(NULL, AV_LOG_FATAL,
"Failed to allocate subtitle_out\n");
1194 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1203 for (i = 0; i < nb; i++) {
1204 unsigned save_num_rects = sub->num_rects;
1212 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1213 sub->end_display_time -= sub->start_display_time;
1214 sub->start_display_time = 0;
1220 subtitle_out_size = avcodec_encode_subtitle(enc,
subtitle_out,
1221 subtitle_out_max_size, sub);
1223 sub->num_rects = save_num_rects;
1224 if (subtitle_out_size < 0) {
1225 av_log(NULL, AV_LOG_FATAL,
"Subtitle encoding failed\n");
1229 av_packet_unref(
pkt);
1231 pkt->size = subtitle_out_size;
1233 pkt->duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 },
ost->
mux_timebase);
1234 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
1238 pkt->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 },
ost->
mux_timebase);
1240 pkt->pts += av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 },
ost->
mux_timebase);
1249 AVFrame *next_picture)
1251 int ret, format_video_sync;
1254 AVRational frame_rate;
1255 int nb_frames, nb0_frames, i;
1256 double delta, delta0;
1257 double duration = 0;
1258 double sync_ipts = AV_NOPTS_VALUE;
1269 frame_rate = av_buffersink_get_frame_rate(
filter);
1270 if (frame_rate.num > 0 && frame_rate.den > 0)
1271 duration = 1/(av_q2d(frame_rate) * av_q2d(enc->time_base));
1273 if(
ist &&
ist->st->start_time != AV_NOPTS_VALUE &&
ist->first_dts != AV_NOPTS_VALUE &&
ost->
frame_rate.num)
1274 duration = FFMIN(duration, 1/(av_q2d(
ost->
frame_rate) * av_q2d(enc->time_base)));
1281 lrintf(next_picture->pkt_duration * av_q2d(
ist->st->time_base) / av_q2d(enc->time_base)) > 0) {
1282 duration = lrintf(next_picture->pkt_duration * av_q2d(
ist->st->time_base) / av_q2d(enc->time_base));
1285 if (!next_picture) {
1292 delta = delta0 + duration;
1300 if(!strcmp(of->
ctx->oformat->name,
"avi")) {
1320 if (delta0 < -0.6) {
1321 av_log(NULL, AV_LOG_VERBOSE,
"Past duration %f too large\n", -delta0);
1323 av_log(NULL, AV_LOG_DEBUG,
"Clipping frame in rate conversion by %f\n", -delta0);
1329 switch (format_video_sync) {
1332 av_log(NULL, AV_LOG_DEBUG,
"Not duplicating %d initial frames\n", (
int)lrintf(delta0));
1341 }
else if (delta < -1.1)
1343 else if (delta > 1.1) {
1344 nb_frames = lrintf(delta);
1346 nb0_frames = llrintf(delta0 - 0.6);
1352 else if (delta > 0.6)
1365 nb0_frames = FFMIN(nb0_frames, nb_frames);
1374 av_log(NULL, AV_LOG_VERBOSE,
1375 "*** dropping frame %d from stream %d at ts %"PRId64
"\n",
1378 if (nb_frames > (nb0_frames &&
ost->
last_dropped) + (nb_frames > nb0_frames)) {
1380 av_log(NULL, AV_LOG_ERROR,
"%d frame duplication too large, skipping\n", nb_frames - 1);
1385 av_log(NULL, AV_LOG_VERBOSE,
"*** %d dup!\n", nb_frames - 1);
1387 av_log(NULL, AV_LOG_WARNING,
"More than %d frames duplicated\n",
dup_warning);
1395 for (i = 0; i < nb_frames; i++) {
1396 AVFrame *in_picture;
1397 int forced_keyframe = 0;
1400 if (i < nb0_frames && ost->last_frame) {
1403 in_picture = next_picture;
1413 in_picture->quality = enc->global_quality;
1414 in_picture->pict_type = 0;
1417 in_picture->pts != AV_NOPTS_VALUE)
1420 pts_time = in_picture->pts != AV_NOPTS_VALUE ?
1425 forced_keyframe = 1;
1431 ff_dlog(NULL,
"force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
1439 forced_keyframe = 1;
1450 && in_picture->key_frame==1
1452 forced_keyframe = 1;
1460 if (forced_keyframe) {
1461 in_picture->pict_type = AV_PICTURE_TYPE_I;
1462 av_log(NULL, AV_LOG_DEBUG,
"Forced keyframe at time %f\n", pts_time);
1467 av_log(NULL, AV_LOG_INFO,
"encoder <- type:video "
1468 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1469 av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
1470 enc->time_base.num, enc->time_base.den);
1475 ret = avcodec_send_frame(enc, in_picture);
1479 av_frame_remove_side_data(in_picture, AV_FRAME_DATA_A53_CC);
1482 av_packet_unref(
pkt);
1483 ret = avcodec_receive_packet(enc,
pkt);
1485 if (
ret == AVERROR(EAGAIN))
1491 av_log(NULL, AV_LOG_INFO,
"encoder -> type:video "
1492 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1493 av_ts2str(
pkt->pts), av_ts2timestr(
pkt->pts, &enc->time_base),
1494 av_ts2str(
pkt->dts), av_ts2timestr(
pkt->dts, &enc->time_base));
1497 if (
pkt->pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & AV_CODEC_CAP_DELAY))
1503 av_log(NULL, AV_LOG_INFO,
"encoder -> type:video "
1504 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1509 frame_size =
pkt->size;
1539 av_log(NULL, AV_LOG_FATAL,
"Video encoding failed\n");
1545 return -10.0 * log10(
d);
1550 AVCodecContext *enc;
1552 double ti1, bitrate, avg_bitrate;
1564 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1565 frame_number =
ost->
st->nb_frames;
1567 fprintf(
vstats_file,
"frame= %5d q= %2.1f ", frame_number,
1574 if (
ost->
error[0]>=0 && (enc->flags & AV_CODEC_FLAG_PSNR))
1579 ti1 = av_stream_get_end_pts(
ost->
st) * av_q2d(
ost->
st->time_base);
1583 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1584 avg_bitrate = (double)(
ost->
data_size * 8) / ti1 / 1000.0;
1585 fprintf(
vstats_file,
"s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1586 (
double)
ost->
data_size / 1024, ti1, bitrate, avg_bitrate);
1599 for (i = 0; i < of->
ctx->nb_streams; i++)
1612 AVFrame *filtered_frame = NULL;
1636 if (av_buffersink_get_type(
filter) == AVMEDIA_TYPE_AUDIO)
1640 return AVERROR(ENOMEM);
1643 return AVERROR(ENOMEM);
1648 ret = av_buffersink_get_frame_flags(
filter, filtered_frame,
1649 AV_BUFFERSINK_FLAG_NO_REQUEST);
1651 if (
ret != AVERROR(EAGAIN) &&
ret != AVERROR_EOF) {
1652 av_log(NULL, AV_LOG_WARNING,
1653 "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(
ret));
1654 }
else if (flush &&
ret == AVERROR_EOF) {
1655 if (av_buffersink_get_type(
filter) == AVMEDIA_TYPE_VIDEO)
1661 av_frame_unref(filtered_frame);
1665 switch (av_buffersink_get_type(
filter)) {
1666 case AVMEDIA_TYPE_VIDEO:
1668 enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
1672 case AVMEDIA_TYPE_AUDIO:
1673 if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&
1674 enc->channels != filtered_frame->channels) {
1675 av_log(NULL, AV_LOG_ERROR,
1676 "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1686 av_frame_unref(filtered_frame);
1695 uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
1696 uint64_t subtitle_size = 0;
1698 float percent = -1.0;
1705 case AVMEDIA_TYPE_VIDEO: video_size +=
ost->
data_size;
break;
1706 case AVMEDIA_TYPE_AUDIO: audio_size +=
ost->
data_size;
break;
1707 case AVMEDIA_TYPE_SUBTITLE: subtitle_size +=
ost->
data_size;
break;
1712 if ( (
ost->
enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
1713 != AV_CODEC_FLAG_PASS1)
1720 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: ",
1721 video_size / 1024.0,
1722 audio_size / 1024.0,
1723 subtitle_size / 1024.0,
1724 other_size / 1024.0,
1725 extra_size / 1024.0);
1727 av_log(NULL, AV_LOG_INFO,
"%f%%", percent);
1729 av_log(NULL, AV_LOG_INFO,
"unknown");
1730 av_log(NULL, AV_LOG_INFO,
"\n");
1735 uint64_t total_packets = 0, total_size = 0;
1737 av_log(NULL, AV_LOG_VERBOSE,
"Input file #%d (%s):\n",
1742 enum AVMediaType type =
ist->dec_ctx->codec_type;
1744 total_size +=
ist->data_size;
1745 total_packets +=
ist->nb_packets;
1747 av_log(NULL, AV_LOG_VERBOSE,
" Input stream #%d:%d (%s): ",
1749 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" packets read (%"PRIu64
" bytes); ",
1750 ist->nb_packets,
ist->data_size);
1752 if (
ist->decoding_needed) {
1753 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" frames decoded",
1754 ist->frames_decoded);
1755 if (type == AVMEDIA_TYPE_AUDIO)
1756 av_log(NULL, AV_LOG_VERBOSE,
" (%"PRIu64
" samples)",
ist->samples_decoded);
1757 av_log(NULL, AV_LOG_VERBOSE,
"; ");
1760 av_log(NULL, AV_LOG_VERBOSE,
"\n");
1763 av_log(NULL, AV_LOG_VERBOSE,
" Total: %"PRIu64
" packets (%"PRIu64
" bytes) demuxed\n",
1764 total_packets, total_size);
1769 uint64_t total_packets = 0, total_size = 0;
1771 av_log(NULL, AV_LOG_VERBOSE,
"Output file #%d (%s):\n",
1774 for (j = 0; j < of->
ctx->nb_streams; j++) {
1776 enum AVMediaType type =
ost->
enc_ctx->codec_type;
1781 av_log(NULL, AV_LOG_VERBOSE,
" Output stream #%d:%d (%s): ",
1784 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" frames encoded",
1786 if (type == AVMEDIA_TYPE_AUDIO)
1788 av_log(NULL, AV_LOG_VERBOSE,
"; ");
1791 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" packets muxed (%"PRIu64
" bytes); ",
1794 av_log(NULL, AV_LOG_VERBOSE,
"\n");
1797 av_log(NULL, AV_LOG_VERBOSE,
" Total: %"PRIu64
" packets (%"PRIu64
" bytes) muxed\n",
1798 total_packets, total_size);
1800 if(video_size +
data_size + audio_size + subtitle_size + extra_size == 0){
1801 av_log(NULL, AV_LOG_WARNING,
"Output file is empty, nothing was encoded ");
1803 av_log(NULL, AV_LOG_WARNING,
"\n");
1805 av_log(NULL, AV_LOG_WARNING,
"(check -ss / -t / -frames parameters if used)\n");
1812 AVFormatContext *oc = NULL;
1813 AVCodecContext *enc = NULL;
1815 int64_t
pts = INT64_MIN + 1;
1818 int frame_number = 0;
1821 int64_t total_size = 0;
1823 double bitrate = 0.0;
1826 float t = (cur_time-timer_start) / 1000000.0;
1831 total_size = avio_size(oc->pb);
1832 if (total_size <= 0) {
1833 total_size = avio_tell(oc->pb);
1844 quality =
ost->
quality / (float) FF_QP2LAMBDA;
1847 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1853 fps = t > 1 ? frame_number / t : 0;
1857 if (av_stream_get_end_pts(
ost->
st) != AV_NOPTS_VALUE)
1858 pts = FFMAX(
pts, av_rescale_q(av_stream_get_end_pts(
ost->
st),
1859 ost->
st->time_base, AV_TIME_BASE_Q));
1865 seconds = FFABS(
pts) / 1000;
1868 bitrate =
pts && total_size >= 0 ? total_size * 8 / (
pts / 1000.0) : -1;
1871 speed = t != 0.0 ? (double)
pts / AV_TIME_BASE / t : -1;
1875 report_callback(frame_number, fps, quality, total_size, seconds, bitrate, speed);
1879static void print_report(
int is_last_report, int64_t timer_start, int64_t cur_time)
1881 AVBPrint buf, buf_script;
1883 AVFormatContext *oc;
1885 AVCodecContext *enc;
1886 int frame_number, vid, i;
1889 int64_t
pts = INT64_MIN + 1;
1890 int hours, mins, secs, us;
1891 const char *hours_sign;
1895 if (!is_last_report) {
1910 t = (cur_time-timer_start) / 1000000.0;
1915 total_size = avio_size(oc->pb);
1916 if (total_size <= 0)
1917 total_size = avio_tell(oc->pb);
1920 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
1921 av_bprint_init(&buf_script, 0, AV_BPRINT_SIZE_AUTOMATIC);
1929 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1930 av_bprintf(&buf,
"q=%2.1f ", q);
1931 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
1934 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1938 fps = t > 1 ? frame_number / t : 0;
1939 av_bprintf(&buf,
"frame=%5d fps=%3.*f q=%3.1f ",
1940 frame_number, fps < 9.95, fps, q);
1941 av_bprintf(&buf_script,
"frame=%d\n", frame_number);
1942 av_bprintf(&buf_script,
"fps=%.2f\n", fps);
1943 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
1946 av_bprintf(&buf,
"L");
1952 for (j = 0; j < 32; j++)
1956 if ((enc->flags & AV_CODEC_FLAG_PSNR) && (
ost->
pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {
1958 double error, error_sum = 0;
1959 double scale, scale_sum = 0;
1961 char type[3] = {
'Y',
'U',
'V' };
1962 av_bprintf(&buf,
"PSNR=");
1963 for (j = 0; j < 3; j++) {
1964 if (is_last_report) {
1965 error = enc->error[j];
1966 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1969 scale = enc->width * enc->height * 255.0 * 255.0;
1975 p =
psnr(error / scale);
1976 av_bprintf(&buf,
"%c:%2.2f ", type[j], p);
1977 av_bprintf(&buf_script,
"stream_%d_%d_psnr_%c=%2.2f\n",
1980 p =
psnr(error_sum / scale_sum);
1981 av_bprintf(&buf,
"*:%2.2f ",
psnr(error_sum / scale_sum));
1982 av_bprintf(&buf_script,
"stream_%d_%d_psnr_all=%2.2f\n",
1988 if (av_stream_get_end_pts(
ost->
st) != AV_NOPTS_VALUE) {
1989 pts = FFMAX(
pts, av_rescale_q(av_stream_get_end_pts(
ost->
st),
1990 ost->
st->time_base, AV_TIME_BASE_Q));
2003 secs = FFABS(
pts) / AV_TIME_BASE;
2004 us = FFABS(
pts) % AV_TIME_BASE;
2009 hours_sign = (
pts < 0) ?
"-" :
"";
2011 bitrate =
pts && total_size >= 0 ? total_size * 8 / (
pts / 1000.0) : -1;
2012 speed = t != 0.0 ? (double)
pts / AV_TIME_BASE / t : -1;
2014 if (total_size < 0) av_bprintf(&buf,
"size=N/A time=");
2015 else av_bprintf(&buf,
"size=%8.0fkB time=", total_size / 1024.0);
2016 if (
pts == AV_NOPTS_VALUE) {
2017 av_bprintf(&buf,
"N/A ");
2019 av_bprintf(&buf,
"%s%02d:%02d:%02d.%02d ",
2020 hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
2024 av_bprintf(&buf,
"bitrate=N/A");
2025 av_bprintf(&buf_script,
"bitrate=N/A\n");
2027 av_bprintf(&buf,
"bitrate=%6.1fkbits/s", bitrate);
2028 av_bprintf(&buf_script,
"bitrate=%6.1fkbits/s\n", bitrate);
2031 if (total_size < 0) av_bprintf(&buf_script,
"total_size=N/A\n");
2032 else av_bprintf(&buf_script,
"total_size=%"PRId64
"\n", total_size);
2033 if (
pts == AV_NOPTS_VALUE) {
2034 av_bprintf(&buf_script,
"out_time_us=N/A\n");
2035 av_bprintf(&buf_script,
"out_time_ms=N/A\n");
2036 av_bprintf(&buf_script,
"out_time=N/A\n");
2038 av_bprintf(&buf_script,
"out_time_us=%"PRId64
"\n",
pts);
2039 av_bprintf(&buf_script,
"out_time_ms=%"PRId64
"\n",
pts);
2040 av_bprintf(&buf_script,
"out_time=%s%02d:%02d:%02d.%06d\n",
2041 hours_sign, hours, mins, secs, us);
2050 av_bprintf(&buf,
" speed=N/A");
2051 av_bprintf(&buf_script,
"speed=N/A\n");
2053 av_bprintf(&buf,
" speed=%4.3gx", speed);
2054 av_bprintf(&buf_script,
"speed=%4.3gx\n", speed);
2058 const char end = is_last_report ?
'\n' :
'\r';
2059 if (
print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
2060 fprintf(stderr,
"%s %c", buf.str, end);
2062 av_log(NULL, AV_LOG_INFO,
"%s %c", buf.str, end);
2066 av_bprint_finalize(&buf, NULL);
2069 av_bprintf(&buf_script,
"progress=%s\n",
2070 is_last_report ?
"end" :
"continue");
2072 FFMIN(buf_script.len, buf_script.size - 1));
2074 av_bprint_finalize(&buf_script, NULL);
2075 if (is_last_report) {
2077 av_log(NULL, AV_LOG_ERROR,
2078 "Error closing progress log, loss of information possible: %s\n", av_err2str(
ret));
2092 ifilter->
format = par->format;
2096 ifilter->
width = par->width;
2097 ifilter->
height = par->height;
2118 av_log(NULL, AV_LOG_WARNING,
2119 "Finishing stream %d:%d without any data written to it.\n",
2135 av_log(NULL, AV_LOG_ERROR,
"Error configuring filter graph\n");
2145 if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
2149 const char *desc = NULL;
2153 switch (enc->codec_type) {
2154 case AVMEDIA_TYPE_AUDIO:
2157 case AVMEDIA_TYPE_VIDEO:
2166 av_packet_unref(
pkt);
2167 while ((
ret = avcodec_receive_packet(enc,
pkt)) == AVERROR(EAGAIN)) {
2168 ret = avcodec_send_frame(enc, NULL);
2170 av_log(NULL, AV_LOG_FATAL,
"%s encoding failed: %s\n",
2178 if (
ret < 0 &&
ret != AVERROR_EOF) {
2179 av_log(NULL, AV_LOG_FATAL,
"%s encoding failed: %s\n",
2187 if (
ret == AVERROR_EOF) {
2192 av_packet_unref(
pkt);
2196 pkt_size =
pkt->size;
2230 int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q,
ost->
mux_timebase);
2231 AVPacket *opkt =
ost->
pkt;
2233 av_packet_unref(opkt);
2245 int64_t comp_start = start_time;
2248 if (
pkt->pts == AV_NOPTS_VALUE ?
2249 ist->pts < comp_start :
2250 pkt->pts < av_rescale_q(comp_start, AV_TIME_BASE_Q,
ist->st->time_base))
2273 if (
ost->
enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
2276 if (av_packet_ref(opkt,
pkt) < 0)
2279 if (
pkt->pts != AV_NOPTS_VALUE)
2282 if (
pkt->dts == AV_NOPTS_VALUE) {
2284 }
else if (
ost->
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2285 int duration = av_get_audio_frame_duration(
ist->dec_ctx,
pkt->size);
2287 duration =
ist->dec_ctx->frame_size;
2288 opkt->dts = av_rescale_delta(
ist->st->time_base,
pkt->dts,
2289 (AVRational){1, ist->dec_ctx->sample_rate}, duration,
2292 opkt->pts = opkt->dts - ost_tb_start_time;
2295 opkt->dts -= ost_tb_start_time;
2304 AVCodecContext *
dec =
ist->dec_ctx;
2306 if (!
dec->channel_layout) {
2307 char layout_name[256];
2309 if (
dec->channels >
ist->guess_layout_max)
2311 dec->channel_layout = av_get_default_channel_layout(
dec->channels);
2312 if (!
dec->channel_layout)
2314 av_get_channel_layout_string(layout_name,
sizeof(layout_name),
2315 dec->channels,
dec->channel_layout);
2316 av_log(NULL, AV_LOG_WARNING,
"Guessed Channel Layout for Input Stream "
2317 "#%d.%d : %s\n",
ist->file_index,
ist->st->index, layout_name);
2331 if (
ist->decoded_frame->decode_error_flags || (
ist->decoded_frame->flags & AV_FRAME_FLAG_CORRUPT)) {
2333 "%s: corrupt decoded frame in stream %d\n",
input_files[
ist->file_index]->
ctx->url,
ist->st->index);
2355 int need_reinit,
ret, i;
2358 need_reinit = ifilter->
format != frame->format;
2360 switch (ifilter->
ist->
st->codecpar->codec_type) {
2361 case AVMEDIA_TYPE_AUDIO:
2362 need_reinit |= ifilter->
sample_rate != frame->sample_rate ||
2363 ifilter->
channels != frame->channels ||
2366 case AVMEDIA_TYPE_VIDEO:
2367 need_reinit |= ifilter->
width != frame->width ||
2368 ifilter->
height != frame->height;
2386 if (need_reinit || !fg->
graph) {
2389 AVFrame *tmp = av_frame_clone(frame);
2391 return AVERROR(ENOMEM);
2392 av_frame_unref(frame);
2397 av_frame_free(&tmp);
2401 av_fifo_generic_write(ifilter->
frame_queue, &tmp,
sizeof(tmp), NULL);
2407 if (
ret < 0 &&
ret != AVERROR_EOF) {
2408 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(
ret));
2414 av_log(NULL, AV_LOG_ERROR,
"Error reinitializing filters!\n");
2419 ret = av_buffersrc_add_frame_flags(ifilter->
filter, frame, AV_BUFFERSRC_FLAG_PUSH);
2421 if (
ret != AVERROR_EOF)
2422 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(
ret));
2439 ret = av_buffersrc_close(ifilter->
filter,
pts, AV_BUFFERSRC_FLAG_PUSH);
2447 if (ifilter->
format < 0 && (ifilter->
type == AVMEDIA_TYPE_AUDIO || ifilter->
type == AVMEDIA_TYPE_VIDEO)) {
2448 av_log(NULL, AV_LOG_ERROR,
"Cannot determine format of input stream %d:%d after EOF\n", ifilter->
ist->
file_index, ifilter->
ist->
st->index);
2449 return AVERROR_INVALIDDATA;
2460static int decode(AVCodecContext *avctx, AVFrame *frame,
int *got_frame, AVPacket *
pkt)
2467 ret = avcodec_send_packet(avctx,
pkt);
2470 if (
ret < 0 &&
ret != AVERROR_EOF)
2474 ret = avcodec_receive_frame(avctx, frame);
2475 if (
ret < 0 &&
ret != AVERROR(EAGAIN))
2488 av_assert1(
ist->nb_filters > 0);
2489 for (i = 0; i <
ist->nb_filters; i++) {
2491 f =
ist->filter_frame;
2498 if (
ret == AVERROR_EOF)
2501 av_log(NULL, AV_LOG_ERROR,
2502 "Failed to inject frame into filter network: %s\n", av_err2str(
ret));
2513 AVCodecContext *avctx =
ist->dec_ctx;
2515 AVRational decoded_frame_tb;
2517 if (!
ist->decoded_frame && !(
ist->decoded_frame = av_frame_alloc()))
2518 return AVERROR(ENOMEM);
2519 if (!
ist->filter_frame && !(
ist->filter_frame = av_frame_alloc()))
2520 return AVERROR(ENOMEM);
2529 if (
ret >= 0 && avctx->sample_rate <= 0) {
2530 av_log(avctx, AV_LOG_ERROR,
"Sample rate %d invalid\n", avctx->sample_rate);
2531 ret = AVERROR_INVALIDDATA;
2534 if (
ret != AVERROR_EOF)
2541 ist->frames_decoded++;
2551 decoded_frame_tb =
ist->st->time_base;
2552 }
else if (
pkt &&
pkt->pts != AV_NOPTS_VALUE) {
2554 decoded_frame_tb =
ist->st->time_base;
2557 decoded_frame_tb = AV_TIME_BASE_Q;
2561 (AVRational){1, avctx->sample_rate},
decoded_frame->nb_samples, &
ist->filter_in_rescale_delta_last,
2562 (AVRational){1, avctx->sample_rate});
2566 av_frame_unref(
ist->filter_frame);
2568 return err < 0 ? err :
ret;
2575 int i,
ret = 0, err = 0;
2576 int64_t best_effort_timestamp;
2577 int64_t
dts = AV_NOPTS_VALUE;
2582 if (!eof &&
pkt &&
pkt->size == 0)
2585 if (!
ist->decoded_frame && !(
ist->decoded_frame = av_frame_alloc()))
2586 return AVERROR(ENOMEM);
2587 if (!
ist->filter_frame && !(
ist->filter_frame = av_frame_alloc()))
2588 return AVERROR(ENOMEM);
2590 if (
ist->dts != AV_NOPTS_VALUE)
2591 dts = av_rescale_q(
ist->dts, AV_TIME_BASE_Q,
ist->st->time_base);
2599 void *
new = av_realloc_array(
ist->dts_buffer,
ist->nb_dts_buffer + 1,
sizeof(
ist->dts_buffer[0]));
2601 return AVERROR(ENOMEM);
2602 ist->dts_buffer =
new;
2603 ist->dts_buffer[
ist->nb_dts_buffer++] =
dts;
2614 if (
ist->st->codecpar->video_delay <
ist->dec_ctx->has_b_frames) {
2615 if (
ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
2616 ist->st->codecpar->video_delay =
ist->dec_ctx->has_b_frames;
2618 av_log(
ist->dec_ctx, AV_LOG_WARNING,
2619 "video_delay is larger in decoder than demuxer %d > %d.\n"
2620 "If you want to help, upload a sample "
2621 "of this file to https://streams.videolan.org/upload/ "
2622 "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n",
2623 ist->dec_ctx->has_b_frames,
2624 ist->st->codecpar->video_delay);
2627 if (
ret != AVERROR_EOF)
2634 av_log(NULL, AV_LOG_DEBUG,
"Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
2638 ist->dec_ctx->width,
2639 ist->dec_ctx->height,
2640 ist->dec_ctx->pix_fmt);
2647 if(
ist->top_field_first>=0)
2650 ist->frames_decoded++;
2659 best_effort_timestamp=
decoded_frame->best_effort_timestamp;
2662 if (
ist->framerate.num)
2663 best_effort_timestamp =
ist->cfr_next_pts++;
2665 if (eof && best_effort_timestamp == AV_NOPTS_VALUE &&
ist->nb_dts_buffer > 0) {
2666 best_effort_timestamp =
ist->dts_buffer[0];
2668 for (i = 0; i <
ist->nb_dts_buffer - 1; i++)
2669 ist->dts_buffer[i] =
ist->dts_buffer[i + 1];
2670 ist->nb_dts_buffer--;
2673 if(best_effort_timestamp != AV_NOPTS_VALUE) {
2674 int64_t ts = av_rescale_q(
decoded_frame->pts = best_effort_timestamp,
ist->st->time_base, AV_TIME_BASE_Q);
2676 if (ts != AV_NOPTS_VALUE)
2677 ist->next_pts =
ist->pts = ts;
2681 av_log(NULL, AV_LOG_INFO,
"decoder -> ist_index:%d type:video "
2682 "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",
2685 best_effort_timestamp,
2686 av_ts2timestr(best_effort_timestamp, &
ist->st->time_base),
2688 ist->st->time_base.num,
ist->st->time_base.den);
2691 if (
ist->st->sample_aspect_ratio.num)
2697 av_frame_unref(
ist->filter_frame);
2699 return err < 0 ? err :
ret;
2707 int i,
ret = avcodec_decode_subtitle2(
ist->dec_ctx,
2719 if (
ist->fix_sub_duration) {
2721 if (
ist->prev_sub.got_output) {
2722 end = av_rescale(
subtitle.pts -
ist->prev_sub.subtitle.pts,
2723 1000, AV_TIME_BASE);
2724 if (end < ist->
prev_sub.subtitle.end_display_time) {
2725 av_log(
ist->dec_ctx, AV_LOG_DEBUG,
2726 "Subtitle duration reduced from %"PRId32
" to %d%s\n",
2727 ist->prev_sub.subtitle.end_display_time, end,
2728 end <= 0 ?
", dropping it" :
"");
2729 ist->prev_sub.subtitle.end_display_time = end;
2733 FFSWAP(
int,
ret,
ist->prev_sub.ret);
2734 FFSWAP(AVSubtitle,
subtitle,
ist->prev_sub.subtitle);
2742 if (
ist->sub2video.frame) {
2744 }
else if (
ist->nb_filters) {
2745 if (!
ist->sub2video.sub_queue)
2746 ist->sub2video.sub_queue = av_fifo_alloc(8 *
sizeof(AVSubtitle));
2747 if (!
ist->sub2video.sub_queue)
2749 if (!av_fifo_space(
ist->sub2video.sub_queue)) {
2750 ret = av_fifo_realloc2(
ist->sub2video.sub_queue, 2 * av_fifo_size(
ist->sub2video.sub_queue));
2761 ist->frames_decoded++;
2769 ||
ost->
enc->type != AVMEDIA_TYPE_SUBTITLE)
2785 int64_t
pts = av_rescale_q_rnd(
ist->pts, AV_TIME_BASE_Q,
ist->st->time_base,
2786 AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
2788 for (i = 0; i <
ist->nb_filters; i++) {
2801 int eof_reached = 0;
2805 if (!
ist->pkt && !(
ist->pkt = av_packet_alloc()))
2806 return AVERROR(ENOMEM);
2809 if (!
ist->saw_first_ts) {
2811 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;
2813 if (
pkt &&
pkt->pts != AV_NOPTS_VALUE && !
ist->decoding_needed) {
2815 ist->dts += av_rescale_q(
pkt->pts,
ist->st->time_base, AV_TIME_BASE_Q);
2818 ist->saw_first_ts = 1;
2821 if (
ist->next_dts == AV_NOPTS_VALUE)
2822 ist->next_dts =
ist->dts;
2823 if (
ist->next_pts == AV_NOPTS_VALUE)
2824 ist->next_pts =
ist->pts;
2827 av_packet_unref(avpkt);
2828 ret = av_packet_ref(avpkt,
pkt);
2833 if (
pkt &&
pkt->dts != AV_NOPTS_VALUE) {
2834 ist->next_dts =
ist->dts = av_rescale_q(
pkt->dts,
ist->st->time_base, AV_TIME_BASE_Q);
2835 if (
ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !
ist->decoding_needed)
2840 while (
ist->decoding_needed) {
2841 int64_t duration_dts = 0;
2842 int64_t duration_pts = 0;
2844 int decode_failed = 0;
2846 ist->pts =
ist->next_pts;
2847 ist->dts =
ist->next_dts;
2849 switch (
ist->dec_ctx->codec_type) {
2850 case AVMEDIA_TYPE_AUDIO:
2853 av_packet_unref(avpkt);
2855 case AVMEDIA_TYPE_VIDEO:
2859 if (
pkt &&
pkt->duration) {
2860 duration_dts = av_rescale_q(
pkt->duration,
ist->st->time_base, AV_TIME_BASE_Q);
2861 }
else if(
ist->dec_ctx->framerate.num != 0 &&
ist->dec_ctx->framerate.den != 0) {
2862 int ticks= av_stream_get_parser(
ist->st) ? av_stream_get_parser(
ist->st)->repeat_pict+1 :
ist->dec_ctx->ticks_per_frame;
2863 duration_dts = ((int64_t)AV_TIME_BASE *
2864 ist->dec_ctx->framerate.den * ticks) /
2865 ist->dec_ctx->framerate.num /
ist->dec_ctx->ticks_per_frame;
2868 if(
ist->dts != AV_NOPTS_VALUE && duration_dts) {
2869 ist->next_dts += duration_dts;
2871 ist->next_dts = AV_NOPTS_VALUE;
2875 if (duration_pts > 0) {
2876 ist->next_pts += av_rescale_q(duration_pts,
ist->st->time_base, AV_TIME_BASE_Q);
2878 ist->next_pts += duration_dts;
2881 av_packet_unref(avpkt);
2883 case AVMEDIA_TYPE_SUBTITLE:
2889 av_packet_unref(avpkt);
2895 if (
ret == AVERROR_EOF) {
2901 if (decode_failed) {
2902 av_log(NULL, AV_LOG_ERROR,
"Error while decoding stream #%d:%d: %s\n",
2903 ist->file_index,
ist->st->index, av_err2str(
ret));
2905 av_log(NULL, AV_LOG_FATAL,
"Error while processing the decoded "
2906 "data for stream #%d:%d\n",
ist->file_index,
ist->st->index);
2914 ist->got_output = 1;
2935 if (!
pkt &&
ist->decoding_needed && eof_reached && !no_eof) {
2938 av_log(NULL, AV_LOG_FATAL,
"Error marking filters as finished\n");
2944 if (!
ist->decoding_needed &&
pkt) {
2945 ist->dts =
ist->next_dts;
2946 switch (
ist->dec_ctx->codec_type) {
2947 case AVMEDIA_TYPE_AUDIO:
2948 av_assert1(
pkt->duration >= 0);
2949 if (
ist->dec_ctx->sample_rate) {
2950 ist->next_dts += ((int64_t)AV_TIME_BASE *
ist->dec_ctx->frame_size) /
2951 ist->dec_ctx->sample_rate;
2953 ist->next_dts += av_rescale_q(
pkt->duration,
ist->st->time_base, AV_TIME_BASE_Q);
2956 case AVMEDIA_TYPE_VIDEO:
2957 if (
ist->framerate.num) {
2959 AVRational time_base_q = AV_TIME_BASE_Q;
2960 int64_t
next_dts = av_rescale_q(
ist->next_dts, time_base_q, av_inv_q(
ist->framerate));
2961 ist->next_dts = av_rescale_q(
next_dts + 1, av_inv_q(
ist->framerate), time_base_q);
2962 }
else if (
pkt->duration) {
2963 ist->next_dts += av_rescale_q(
pkt->duration,
ist->st->time_base, AV_TIME_BASE_Q);
2964 }
else if(
ist->dec_ctx->framerate.num != 0) {
2965 int ticks= av_stream_get_parser(
ist->st) ? av_stream_get_parser(
ist->st)->repeat_pict + 1 :
ist->dec_ctx->ticks_per_frame;
2966 ist->next_dts += ((int64_t)AV_TIME_BASE *
2967 ist->dec_ctx->framerate.den * ticks) /
2968 ist->dec_ctx->framerate.num /
ist->dec_ctx->ticks_per_frame;
2973 ist->next_pts =
ist->next_dts;
2986 return !eof_reached;
2994 AVIOContext *sdp_pb;
2995 AVFormatContext **avc;
3006 if (!strcmp(
output_files[i]->ctx->oformat->name,
"rtp")) {
3015 av_sdp_create(avc, j, sdp,
sizeof(sdp));
3022 av_log(NULL, AV_LOG_ERROR,
"Failed to open sdp file '%s'\n",
sdp_filename);
3024 avio_print(sdp_pb, sdp);
3025 avio_closep(&sdp_pb);
3034static enum AVPixelFormat
get_format(AVCodecContext *s,
const enum AVPixelFormat *pix_fmts)
3037 const enum AVPixelFormat *p;
3040 for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
3041 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
3042 const AVCodecHWConfig *config = NULL;
3045 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
3051 config = avcodec_get_hw_config(s->codec, i);
3054 if (!(config->methods &
3055 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
3057 if (config->pix_fmt == *p)
3062 if (config->device_type !=
ist->hwaccel_device_type) {
3070 av_log(NULL, AV_LOG_FATAL,
3071 "%s hwaccel requested for input stream #%d:%d, "
3072 "but cannot be initialized.\n",
3073 av_hwdevice_get_type_name(config->device_type),
3074 ist->file_index,
ist->st->index);
3075 return AV_PIX_FMT_NONE;
3080 const HWAccel *hwaccel = NULL;
3092 if (hwaccel->
id !=
ist->hwaccel_id) {
3099 av_log(NULL, AV_LOG_FATAL,
3100 "%s hwaccel requested for input stream #%d:%d, "
3101 "but cannot be initialized.\n", hwaccel->
name,
3102 ist->file_index,
ist->st->index);
3103 return AV_PIX_FMT_NONE;
3107 if (
ist->hw_frames_ctx) {
3108 s->hw_frames_ctx = av_buffer_ref(
ist->hw_frames_ctx);
3109 if (!s->hw_frames_ctx)
3110 return AV_PIX_FMT_NONE;
3113 ist->hwaccel_pix_fmt = *p;
3120static int get_buffer(AVCodecContext *s, AVFrame *frame,
int flags)
3124 if (
ist->hwaccel_get_buffer && frame->format ==
ist->hwaccel_pix_fmt)
3125 return ist->hwaccel_get_buffer(s, frame, flags);
3127 return avcodec_default_get_buffer2(s, frame, flags);
3135 if (
ist->decoding_needed) {
3136 const AVCodec *codec =
ist->dec;
3138 snprintf(error, error_len,
"Decoder (codec %s) not found for input stream #%d:%d",
3139 avcodec_get_name(
ist->dec_ctx->codec_id),
ist->file_index,
ist->st->index);
3140 return AVERROR(EINVAL);
3143 ist->dec_ctx->opaque =
ist;
3146#if LIBAVCODEC_VERSION_MAJOR < 60
3147FF_DISABLE_DEPRECATION_WARNINGS
3148 ist->dec_ctx->thread_safe_callbacks = 1;
3149FF_ENABLE_DEPRECATION_WARNINGS
3152 if (
ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
3154 av_dict_set(&
ist->decoder_opts,
"compute_edt",
"1", AV_DICT_DONT_OVERWRITE);
3156 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");
3159 av_dict_set(&
ist->decoder_opts,
"sub_text_format",
"ass", AV_DICT_DONT_OVERWRITE);
3163 ist->dec_ctx->pkt_timebase =
ist->st->time_base;
3165 if (!av_dict_get(
ist->decoder_opts,
"threads", NULL, 0))
3166 av_dict_set(&
ist->decoder_opts,
"threads",
"auto", 0);
3168 if (
ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3169 av_dict_set(&
ist->decoder_opts,
"threads",
"1", 0);
3173 snprintf(error, error_len,
"Device setup failed for "
3174 "decoder on input stream #%d:%d : %s",
3175 ist->file_index,
ist->st->index, av_err2str(
ret));
3179 if ((
ret = avcodec_open2(
ist->dec_ctx, codec, &
ist->decoder_opts)) < 0) {
3180 if (
ret == AVERROR_EXPERIMENTAL)
3183 snprintf(error, error_len,
3184 "Error while opening decoder for input stream "
3186 ist->file_index,
ist->st->index, av_err2str(
ret));
3192 ist->next_pts = AV_NOPTS_VALUE;
3193 ist->next_dts = AV_NOPTS_VALUE;
3207 return FFDIFFSIGN(*(
const int64_t *)a, *(
const int64_t *)b);
3215 for (i = 0; i < of->
ctx->nb_streams; i++) {
3223 ret = avformat_write_header(of->
ctx, &of->
opts);
3225 av_log(NULL, AV_LOG_ERROR,
3226 "Could not write header for output file #%d "
3227 "(incorrect codec parameters ?): %s\n",
3241 for (i = 0; i < of->
ctx->nb_streams; i++) {
3253 av_packet_free(&
pkt);
3268 ret = avcodec_parameters_copy(ctx->par_in,
ost->
st->codecpar);
3272 ctx->time_base_in =
ost->
st->time_base;
3274 ret = av_bsf_init(ctx);
3276 av_log(NULL, AV_LOG_ERROR,
"Error initializing bitstream filter: %s\n",
3281 ret = avcodec_parameters_copy(
ost->
st->codecpar, ctx->par_out);
3285 ost->
st->time_base = ctx->time_base_out;
3294 AVCodecParameters *par_dst =
ost->
st->codecpar;
3298 uint32_t codec_tag = par_dst->codec_tag;
3306 av_log(NULL, AV_LOG_FATAL,
3307 "Error setting up codec context options.\n");
3311 ret = avcodec_parameters_from_context(par_src,
ost->
enc_ctx);
3313 av_log(NULL, AV_LOG_FATAL,
3314 "Error getting reference codec parameters.\n");
3319 unsigned int codec_tag_tmp;
3320 if (!of->
ctx->oformat->codec_tag ||
3321 av_codec_get_id (of->
ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
3322 !av_codec_get_tag2(of->
ctx->oformat->codec_tag, par_src->codec_id, &codec_tag_tmp))
3323 codec_tag = par_src->codec_tag;
3326 ret = avcodec_parameters_copy(par_dst, par_src);
3330 par_dst->codec_tag = codec_tag;
3338 ost->
st->avg_frame_rate =
ist->st->avg_frame_rate;
3345 if (
ost->
st->time_base.num <= 0 ||
ost->
st->time_base.den <= 0) {
3349 ost->
st->time_base = av_add_q(av_stream_get_codec_timebase(
ost->
st), (AVRational){0, 1});
3353 if (
ost->
st->duration <= 0 &&
ist->st->duration > 0)
3354 ost->
st->duration = av_rescale_q(
ist->st->duration,
ist->st->time_base,
ost->
st->time_base);
3357 ost->
st->disposition =
ist->st->disposition;
3359 if (
ist->st->nb_side_data) {
3360 for (i = 0; i <
ist->st->nb_side_data; i++) {
3361 const AVPacketSideData *sd_src = &
ist->st->side_data[i];
3364 dst_data = av_stream_new_side_data(
ost->
st, sd_src->type, sd_src->size);
3366 return AVERROR(ENOMEM);
3367 memcpy(dst_data, sd_src->data, sd_src->size);
3372 uint8_t *sd = av_stream_new_side_data(
ost->
st, AV_PKT_DATA_DISPLAYMATRIX,
3373 sizeof(int32_t) * 9);
3378 switch (par_dst->codec_type) {
3379 case AVMEDIA_TYPE_AUDIO:
3381 av_log(NULL, AV_LOG_FATAL,
"-acodec copy and -vol are incompatible (frames are not decoded)\n");
3384 if((par_dst->block_align == 1 || par_dst->block_align == 1152 || par_dst->block_align == 576) && par_dst->codec_id == AV_CODEC_ID_MP3)
3385 par_dst->block_align= 0;
3386 if(par_dst->codec_id == AV_CODEC_ID_AC3)
3387 par_dst->block_align= 0;
3389 case AVMEDIA_TYPE_VIDEO:
3393 (AVRational){ par_dst->height, par_dst->width });
3394 av_log(NULL, AV_LOG_WARNING,
"Overriding aspect ratio "
3395 "with stream copy may produce invalid files\n");
3397 else if (
ist->st->sample_aspect_ratio.num)
3398 sar =
ist->st->sample_aspect_ratio;
3400 sar = par_src->sample_aspect_ratio;
3401 ost->
st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
3402 ost->
st->avg_frame_rate =
ist->st->avg_frame_rate;
3403 ost->
st->r_frame_rate =
ist->st->r_frame_rate;
3414 AVDictionaryEntry *e;
3416 uint8_t *encoder_string;
3417 int encoder_string_len;
3418 int format_flags = 0;
3421 if (av_dict_get(
ost->
st->metadata,
"encoder", NULL, 0))
3424 e = av_dict_get(of->
opts,
"fflags", NULL, 0);
3426 const AVOption *o = av_opt_find(of->
ctx,
"fflags", NULL, 0, 0);
3429 av_opt_eval_flags(of->
ctx, o, e->value, &format_flags);
3433 const AVOption *o = av_opt_find(
ost->
enc_ctx,
"flags", NULL, 0, 0);
3436 av_opt_eval_flags(
ost->
enc_ctx, o, e->value, &codec_flags);
3439 encoder_string_len =
sizeof(LIBAVCODEC_IDENT) + strlen(
ost->
enc->name) + 2;
3440 encoder_string = av_mallocz(encoder_string_len);
3441 if (!encoder_string)
3444 if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & AV_CODEC_FLAG_BITEXACT))
3445 av_strlcpy(encoder_string, LIBAVCODEC_IDENT
" ", encoder_string_len);
3447 av_strlcpy(encoder_string,
"Lavc ", encoder_string_len);
3448 av_strlcat(encoder_string,
ost->
enc->name, encoder_string_len);
3449 av_dict_set(&
ost->
st->metadata,
"encoder", encoder_string,
3450 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
3454 AVCodecContext *avctx)
3457 int n = 1, i, size,
index = 0;
3460 for (p = kf; *p; p++)
3464 pts = av_malloc_array(size,
sizeof(*
pts));
3466 av_log(NULL, AV_LOG_FATAL,
"Could not allocate forced key frames array.\n");
3471 for (i = 0; i < n; i++) {
3472 char *next = strchr(p,
',');
3477 if (!memcmp(p,
"chapters", 8)) {
3482 if (avf->nb_chapters > INT_MAX - size ||
3483 !(
pts = av_realloc_f(
pts, size += avf->nb_chapters - 1,
3485 av_log(NULL, AV_LOG_FATAL,
3486 "Could not allocate forced key frames array.\n");
3490 t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3492 for (j = 0; j < avf->nb_chapters; j++) {
3493 AVChapter *c = avf->chapters[j];
3494 av_assert1(
index < size);
3495 pts[
index++] = av_rescale_q(c->start, c->time_base,
3496 avctx->time_base) + t;
3502 av_assert1(
index < size);
3503 pts[
index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3510 av_assert0(
index == size);
3520 AVFormatContext *oc;
3529 enc_ctx->time_base =
ist->st->time_base;
3534 av_log(oc, AV_LOG_WARNING,
"Input stream data not available, using default time base\n");
3537 enc_ctx->time_base = default_time_base;
3544 AVCodecContext *
dec_ctx = NULL;
3553 av_dict_set(&
ost->
st->metadata,
"rotate", NULL, 0);
3556 ost->
st->disposition =
ist->st->disposition;
3560 enc_ctx->chroma_sample_location =
dec_ctx->chroma_sample_location;
3562 for (j = 0; j < oc->nb_streams; j++) {
3563 AVStream *
st = oc->streams[j];
3564 if (
st !=
ost->
st &&
st->codecpar->codec_type ==
ost->
st->codecpar->codec_type)
3567 if (j == oc->nb_streams)
3568 if (
ost->
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
3569 ost->
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
3570 ost->
st->disposition = AV_DISPOSITION_DEFAULT;
3573 if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3582 av_log(NULL, AV_LOG_WARNING,
3584 "about the input framerate is available. Falling "
3585 "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
3586 "if you want a different framerate.\n",
3600 if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
3606 switch (enc_ctx->codec_type) {
3607 case AVMEDIA_TYPE_AUDIO:
3610 enc_ctx->bits_per_raw_sample = FFMIN(
dec_ctx->bits_per_raw_sample,
3611 av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
3612 enc_ctx->sample_rate = av_buffersink_get_sample_rate(
ost->
filter->
filter);
3613 enc_ctx->channel_layout = av_buffersink_get_channel_layout(
ost->
filter->
filter);
3619 case AVMEDIA_TYPE_VIDEO:
3622 if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
3623 enc_ctx->time_base = av_buffersink_get_time_base(
ost->
filter->
filter);
3626 av_log(oc, AV_LOG_WARNING,
"Frame rate very high for a muxer not efficiently supporting it.\n"
3627 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3632 enc_ctx->sample_aspect_ratio =
ost->
st->sample_aspect_ratio =
3639 enc_ctx->bits_per_raw_sample = FFMIN(
dec_ctx->bits_per_raw_sample,
3640 av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
3643 enc_ctx->color_range = frame->color_range;
3644 enc_ctx->color_primaries = frame->color_primaries;
3645 enc_ctx->color_trc = frame->color_trc;
3646 enc_ctx->colorspace = frame->colorspace;
3647 enc_ctx->chroma_sample_location = frame->chroma_location;
3655 enc_ctx->width !=
dec_ctx->width ||
3656 enc_ctx->height !=
dec_ctx->height ||
3657 enc_ctx->pix_fmt !=
dec_ctx->pix_fmt) {
3663 if (enc_ctx->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
3667 if (frame->interlaced_frame) {
3668 if (enc_ctx->codec->id == AV_CODEC_ID_MJPEG)
3669 enc_ctx->field_order = frame->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
3671 enc_ctx->field_order = frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
3673 enc_ctx->field_order = AV_FIELD_PROGRESSIVE;
3678 enc_ctx->field_order = AV_FIELD_BB;
3680 enc_ctx->field_order = AV_FIELD_TT;
3688 av_log(NULL, AV_LOG_ERROR,
3704 case AVMEDIA_TYPE_SUBTITLE:
3705 enc_ctx->time_base = AV_TIME_BASE_Q;
3706 if (!enc_ctx->width) {
3711 case AVMEDIA_TYPE_DATA:
3728 const AVCodec *codec =
ost->
enc;
3729 AVCodecContext *
dec = NULL;
3738 if (
dec &&
dec->subtitle_header) {
3740 ost->
enc_ctx->subtitle_header = av_mallocz(
dec->subtitle_header_size + 1);
3742 return AVERROR(ENOMEM);
3743 memcpy(
ost->
enc_ctx->subtitle_header,
dec->subtitle_header,
dec->subtitle_header_size);
3744 ost->
enc_ctx->subtitle_header_size =
dec->subtitle_header_size;
3748 if (
ost->
enc->type == AVMEDIA_TYPE_AUDIO &&
3756 snprintf(error, error_len,
"Device setup failed for "
3757 "encoder on output stream #%d:%d : %s",
3762 if (
ist &&
ist->dec->type == AVMEDIA_TYPE_SUBTITLE &&
ost->
enc->type == AVMEDIA_TYPE_SUBTITLE) {
3763 int input_props = 0, output_props = 0;
3764 AVCodecDescriptor
const *input_descriptor =
3765 avcodec_descriptor_get(
dec->codec_id);
3766 AVCodecDescriptor
const *output_descriptor =
3767 avcodec_descriptor_get(
ost->
enc_ctx->codec_id);
3768 if (input_descriptor)
3769 input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3770 if (output_descriptor)
3771 output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3772 if (input_props && output_props && input_props != output_props) {
3773 snprintf(error, error_len,
3774 "Subtitle encoding currently only possible from text to text "
3775 "or bitmap to bitmap");
3776 return AVERROR_INVALIDDATA;
3781 if (
ret == AVERROR_EXPERIMENTAL)
3783 snprintf(error, error_len,
3784 "Error while opening encoder for output stream #%d:%d - "
3785 "maybe incorrect parameters such as bit_rate, rate, width or height",
3789 if (
ost->
enc->type == AVMEDIA_TYPE_AUDIO &&
3790 !(
ost->
enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
3795 ost->
enc_ctx->codec_id != AV_CODEC_ID_CODEC2 )
3796 av_log(NULL, AV_LOG_WARNING,
"The bitrate parameter is set too low."
3797 " It takes bits/s as argument, not kbits/s\n");
3801 av_log(NULL, AV_LOG_FATAL,
3802 "Error initializing the output stream codec context.\n");
3809 for (i = 0; i <
ost->
enc_ctx->nb_coded_side_data; i++) {
3810 const AVPacketSideData *sd_src = &
ost->
enc_ctx->coded_side_data[i];
3813 dst_data = av_stream_new_side_data(
ost->
st, sd_src->type, sd_src->size);
3815 return AVERROR(ENOMEM);
3816 memcpy(dst_data, sd_src->data, sd_src->size);
3829 for (i = 0; i <
ist->st->nb_side_data; i++) {
3830 AVPacketSideData *sd = &
ist->st->side_data[i];
3831 if (sd->type != AV_PKT_DATA_CPB_PROPERTIES) {
3832 uint8_t *dst = av_stream_new_side_data(
ost->
st, sd->type, sd->size);
3834 return AVERROR(ENOMEM);
3835 memcpy(dst, sd->data, sd->size);
3836 if (
ist->autorotate && sd->type == AV_PKT_DATA_DISPLAYMATRIX)
3837 av_display_rotation_set((uint32_t *)dst, 0);
3843 if (
ost->
st->time_base.num <= 0 ||
ost->
st->time_base.den <= 0)
3844 ost->
st->time_base = av_add_q(
ost->
enc_ctx->time_base, (AVRational){0, 1});
3847 if (
ost->
st->duration <= 0 &&
ist &&
ist->st->duration > 0)
3848 ost->
st->duration = av_rescale_q(
ist->st->duration,
ist->st->time_base,
ost->
st->time_base);
3857 static const AVOption opts[] = {
3858 {
"disposition" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, (double)INT64_MAX, .unit =
"flags" },
3859 {
"default" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT }, .unit =
"flags" },
3860 {
"dub" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB }, .unit =
"flags" },
3861 {
"original" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL }, .unit =
"flags" },
3862 {
"comment" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT }, .unit =
"flags" },
3863 {
"lyrics" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS }, .unit =
"flags" },
3864 {
"karaoke" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE }, .unit =
"flags" },
3865 {
"forced" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED }, .unit =
"flags" },
3866 {
"hearing_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED }, .unit =
"flags" },
3867 {
"visual_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED }, .unit =
"flags" },
3868 {
"clean_effects" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS }, .unit =
"flags" },
3869 {
"attached_pic" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ATTACHED_PIC }, .unit =
"flags" },
3870 {
"captions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS }, .unit =
"flags" },
3871 {
"descriptions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS }, .unit =
"flags" },
3872 {
"dependent" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEPENDENT }, .unit =
"flags" },
3873 {
"metadata" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA }, .unit =
"flags" },
3876 static const AVClass
class = {
3878 .item_name = av_default_item_name,
3880 .version = LIBAVUTIL_VERSION_INT,
3882 const AVClass *pclass = &
class;
3908 AVStream *st = file->
ctx->streams[pkt->stream_index];
3912 av_log(file->
ctx, AV_LOG_WARNING,
3913 "New %s stream %d:%d at pos:%"PRId64
" and DTS:%ss\n",
3914 av_get_media_type_string(st->codecpar->codec_type),
3915 input_index, pkt->stream_index,
3916 pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
3922 int ret = 0, i, j, k;
3923 AVFormatContext *oc;
3926 char error[1024] = {0};
3984 for (j = 0; j < ifile->
ctx->nb_programs; j++) {
3985 AVProgram *p = ifile->
ctx->programs[j];
3986 int discard = AVDISCARD_ALL;
3988 for (k = 0; k < p->nb_stream_indexes; k++)
3990 discard = AVDISCARD_DEFAULT;
3993 p->discard = discard;
4000 if (oc->oformat->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
4009 av_log(NULL, AV_LOG_INFO,
"Stream mapping:\n");
4013 for (j = 0; j <
ist->nb_filters; j++) {
4015 av_log(NULL, AV_LOG_INFO,
" Stream #%d:%d (%s) -> %s",
4016 ist->file_index,
ist->st->index,
ist->dec ?
ist->dec->name :
"?",
4017 ist->filters[j]->name);
4019 av_log(NULL, AV_LOG_INFO,
" (graph %d)",
ist->filters[j]->graph->index);
4020 av_log(NULL, AV_LOG_INFO,
"\n");
4030 av_log(NULL, AV_LOG_INFO,
" File %s -> Stream #%d:%d\n",
4041 av_log(NULL, AV_LOG_INFO,
" -> Stream #%d:%d (%s)\n",
ost->
file_index,
4046 av_log(NULL, AV_LOG_INFO,
" Stream #%d:%d -> #%d:%d",
4052 av_log(NULL, AV_LOG_INFO,
" [sync #%d:%d]",
4056 av_log(NULL, AV_LOG_INFO,
" (copy)");
4059 const AVCodec *out_codec =
ost->
enc;
4060 const char *decoder_name =
"?";
4061 const char *in_codec_name =
"?";
4062 const char *encoder_name =
"?";
4063 const char *out_codec_name =
"?";
4064 const AVCodecDescriptor *desc;
4067 decoder_name = in_codec->name;
4068 desc = avcodec_descriptor_get(in_codec->id);
4070 in_codec_name = desc->name;
4071 if (!strcmp(decoder_name, in_codec_name))
4072 decoder_name =
"native";
4076 encoder_name = out_codec->name;
4077 desc = avcodec_descriptor_get(out_codec->id);
4079 out_codec_name = desc->name;
4080 if (!strcmp(encoder_name, out_codec_name))
4081 encoder_name =
"native";
4084 av_log(NULL, AV_LOG_INFO,
" (%s (%s) -> %s (%s))",
4085 in_codec_name, decoder_name,
4086 out_codec_name, encoder_name);
4088 av_log(NULL, AV_LOG_INFO,
"\n");
4092 av_log(NULL, AV_LOG_ERROR,
"%s\n", error);
4116 for (j = 0; j < of->
ctx->nb_streams; j++)
4135 int64_t opts_min = INT64_MAX;
4144 av_log(NULL, AV_LOG_DEBUG,
4145 "cur_dts is invalid st:%d (%d) [init:%d i_done:%d finish:%d] (this is harmless if it occurs once at the start per stream)\n",
4163 if (tcgetattr(0, &tty) == 0) {
4164 if (on) tty.c_lflag |= ECHO;
4165 else tty.c_lflag &= ~ECHO;
4166 tcsetattr(0, TCSANOW, &tty);
4175 return AVERROR_EXIT;
4183 return AVERROR_EXIT;
4184 if (key ==
'+') av_log_set_level(av_log_get_level()+10);
4185 if (key ==
'-') av_log_set_level(av_log_get_level()-10);
4194 av_log_set_level(AV_LOG_DEBUG);
4196 if (key ==
'c' || key ==
'C'){
4197 char buf[4096], target[64], command[256], arg[256] = {0};
4200 fprintf(stderr,
"\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
4203 while ((k =
read_key()) !=
'\n' && k !=
'\r' && i <
sizeof(buf)-1)
4208 fprintf(stderr,
"\n");
4210 (n = sscanf(buf,
"%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
4211 av_log(NULL, AV_LOG_DEBUG,
"Processing command target:%s time:%f command:%s arg:%s",
4212 target, time, command, arg);
4217 ret = avfilter_graph_send_command(fg->
graph, target, command, arg, buf,
sizeof(buf),
4218 key ==
'c' ? AVFILTER_CMD_FLAG_ONE : 0);
4219 fprintf(stderr,
"Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
4220 }
else if (key ==
'c') {
4221 fprintf(stderr,
"Queuing commands only on filters supporting the specific command is unsupported\n");
4222 ret = AVERROR_PATCHWELCOME;
4224 ret = avfilter_graph_queue_command(fg->
graph, target, command, arg, 0, time);
4226 fprintf(stderr,
"Queuing command failed with error %s\n", av_err2str(ret));
4231 av_log(NULL, AV_LOG_ERROR,
4232 "Parse error, at least 3 arguments were expected, "
4233 "only %d given in string '%s'\n", n, buf);
4236 if (key ==
'd' || key ==
'D'){
4240 if(!debug) debug = 1;
4241 while (debug & FF_DEBUG_DCT_COEFF)
4248 while ((k =
read_key()) !=
'\n' && k !=
'\r' && i <
sizeof(buf)-1)
4253 fprintf(stderr,
"\n");
4254 if (k <= 0 || sscanf(buf,
"%d", &debug)!=1)
4255 fprintf(stderr,
"error parsing debug value\n");
4264 if(debug) av_log_set_level(AV_LOG_DEBUG);
4265 fprintf(stderr,
"debug=%d\n", debug);
4268 fprintf(stderr,
"key function\n"
4269 "? show this help\n"
4270 "+ increase verbosity\n"
4271 "- decrease verbosity\n"
4272 "c Send command to first matching filter supporting it\n"
4273 "C Send/Queue command to all matching filters\n"
4274 "D cycle through available debug modes\n"
4275 "h dump packets/hex press to cycle through the 3 states\n"
4277 "s Show QP histogram\n"
4284static void *input_thread(
void *arg)
4287 AVPacket *pkt = f->
pkt, *queue_pkt;
4288 unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
4292 ret = av_read_frame(f->
ctx, pkt);
4294 if (ret == AVERROR(EAGAIN)) {
4299 av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
4302 queue_pkt = av_packet_alloc();
4304 av_packet_unref(pkt);
4305 av_thread_message_queue_set_err_recv(f->in_thread_queue, AVERROR(ENOMEM));
4308 av_packet_move_ref(queue_pkt, pkt);
4309 ret = av_thread_message_queue_send(f->in_thread_queue, &queue_pkt, flags);
4310 if (flags && ret == AVERROR(EAGAIN)) {
4312 ret = av_thread_message_queue_send(f->in_thread_queue, &queue_pkt, flags);
4313 av_log(f->
ctx, AV_LOG_WARNING,
4314 "Thread message queue blocking; consider raising the "
4315 "thread_queue_size option (current value: %d)\n",
4316 f->thread_queue_size);
4319 if (ret != AVERROR_EOF)
4320 av_log(f->
ctx, AV_LOG_ERROR,
4321 "Unable to send packet to main thread: %s\n",
4323 av_packet_free(&queue_pkt);
4324 av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
4332static void free_input_thread(
int i)
4337 if (!f || !f->in_thread_queue)
4339 av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
4340 while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
4341 av_packet_free(&pkt);
4343 pthread_join(f->thread, NULL);
4345 av_thread_message_queue_free(&f->in_thread_queue);
4348static void free_input_threads(
void)
4353 free_input_thread(i);
4356static int init_input_thread(
int i)
4361 if (f->thread_queue_size < 0)
4363 if (!f->thread_queue_size)
4366 if (f->
ctx->pb ? !f->
ctx->pb->seekable :
4367 strcmp(f->
ctx->iformat->name,
"lavfi"))
4368 f->non_blocking = 1;
4369 ret = av_thread_message_queue_alloc(&f->in_thread_queue,
4370 f->thread_queue_size,
sizeof(f->
pkt));
4374 if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
4375 av_log(NULL, AV_LOG_ERROR,
"pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
4376 av_thread_message_queue_free(&f->in_thread_queue);
4377 return AVERROR(ret);
4383static int init_input_threads(
void)
4388 ret = init_input_thread(i);
4395static int get_input_packet_mt(
InputFile *f, AVPacket **pkt)
4397 return av_thread_message_queue_recv(f->in_thread_queue, pkt,
4399 AV_THREAD_MESSAGE_NONBLOCK : 0);
4407 int64_t file_start =
copy_ts * (
4414 int64_t stream_ts_offset, pts, now;
4415 if (!
ist->nb_packets || (
ist->decoding_needed && !
ist->got_output))
continue;
4416 stream_ts_offset = FFMAX(
ist->first_dts != AV_NOPTS_VALUE ?
ist->first_dts : 0, file_start);
4417 pts = av_rescale(
ist->dts, 1000000, AV_TIME_BASE);
4418 now = (av_gettime_relative() -
ist->start) * scale + stream_ts_offset;
4420 return AVERROR(EAGAIN);
4425 if (f->thread_queue_size)
4426 return get_input_packet_mt(f, pkt);
4429 return av_read_frame(f->
ctx, *pkt);
4451static AVRational
duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
4452 AVRational time_base)
4458 return tmp_time_base;
4461 ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
4464 return tmp_time_base;
4473 AVCodecContext *avctx;
4474 int i, ret, has_audio = 0;
4475 int64_t duration = 0;
4477 ret = avformat_seek_file(is, -1, INT64_MIN, is->start_time, is->start_time, 0);
4483 avctx =
ist->dec_ctx;
4488 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
ist->nb_samples)
4494 avctx =
ist->dec_ctx;
4497 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
ist->nb_samples) {
4505 if (
ist->framerate.num) {
4506 duration = av_rescale_q(1, av_inv_q(
ist->framerate),
ist->st->time_base);
4507 }
else if (
ist->st->avg_frame_rate.num) {
4508 duration = av_rescale_q(1, av_inv_q(
ist->st->avg_frame_rate),
ist->st->time_base);
4517 if (
ist->max_pts >
ist->min_pts &&
ist->max_pts - (uint64_t)
ist->min_pts < INT64_MAX - duration)
4518 duration +=
ist->max_pts -
ist->min_pts;
4523 if (ifile->
loop > 0)
4539 AVFormatContext *is;
4542 int ret, thread_ret, i, j;
4545 int disable_discontinuity_correction =
copy_ts;
4550 if (ret == AVERROR(EAGAIN)) {
4554 if (ret < 0 && ifile->loop) {
4555 AVCodecContext *avctx;
4558 avctx =
ist->dec_ctx;
4559 if (
ist->decoding_needed) {
4563 avcodec_flush_buffers(avctx);
4567 free_input_thread(file_index);
4571 thread_ret = init_input_thread(file_index);
4576 av_log(NULL, AV_LOG_WARNING,
"Seek to start failed.\n");
4579 if (ret == AVERROR(EAGAIN)) {
4585 if (ret != AVERROR_EOF) {
4593 if (
ist->decoding_needed) {
4610 return AVERROR(EAGAIN);
4616 av_pkt_dump_log2(NULL, AV_LOG_INFO, pkt,
do_hex_dump,
4617 is->streams[pkt->stream_index]);
4621 if (pkt->stream_index >= ifile->
nb_streams) {
4623 goto discard_packet;
4628 ist->data_size += pkt->size;
4632 goto discard_packet;
4634 if (pkt->flags & AV_PKT_FLAG_CORRUPT) {
4636 "%s: corrupt input packet in stream %d\n", is->url, pkt->stream_index);
4642 av_log(NULL, AV_LOG_INFO,
"demuxer -> ist_index:%d type:%s "
4643 "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",
4644 ifile->
ist_index + pkt->stream_index, av_get_media_type_string(
ist->dec_ctx->codec_type),
4645 av_ts2str(
ist->next_dts), av_ts2timestr(
ist->next_dts, &AV_TIME_BASE_Q),
4646 av_ts2str(
ist->next_pts), av_ts2timestr(
ist->next_pts, &AV_TIME_BASE_Q),
4647 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &
ist->st->time_base),
4648 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &
ist->st->time_base),
4653 if(!
ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE &&
ist->st->pts_wrap_bits < 64){
4654 int64_t stime, stime2;
4658 if (
ist->next_dts == AV_NOPTS_VALUE
4660 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
4661 int64_t new_start_time = INT64_MAX;
4662 for (i=0; i<is->nb_streams; i++) {
4663 AVStream *st = is->streams[i];
4664 if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
4666 new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
4668 if (new_start_time > is->start_time) {
4669 av_log(is, AV_LOG_VERBOSE,
"Correcting start time by %"PRId64
"\n", new_start_time - is->start_time);
4674 stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q,
ist->st->time_base);
4675 stime2= stime + (1ULL<<
ist->st->pts_wrap_bits);
4676 ist->wrap_correction_done = 1;
4678 if(stime2 > stime && pkt->dts != AV_NOPTS_VALUE && pkt->dts > stime + (1LL<<(
ist->st->pts_wrap_bits-1))) {
4679 pkt->dts -= 1ULL<<
ist->st->pts_wrap_bits;
4680 ist->wrap_correction_done = 0;
4682 if(stime2 > stime && pkt->pts != AV_NOPTS_VALUE && pkt->pts > stime + (1LL<<(
ist->st->pts_wrap_bits-1))) {
4683 pkt->pts -= 1ULL<<
ist->st->pts_wrap_bits;
4684 ist->wrap_correction_done = 0;
4689 if (
ist->nb_packets == 1) {
4690 for (i = 0; i <
ist->st->nb_side_data; i++) {
4691 AVPacketSideData *src_sd = &
ist->st->side_data[i];
4694 if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
4697 if (av_packet_get_side_data(pkt, src_sd->type, NULL))
4700 dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
4704 memcpy(dst_data, src_sd->data, src_sd->size);
4708 if (pkt->dts != AV_NOPTS_VALUE)
4709 pkt->dts += av_rescale_q(ifile->
ts_offset, AV_TIME_BASE_Q,
ist->st->time_base);
4710 if (pkt->pts != AV_NOPTS_VALUE)
4711 pkt->pts += av_rescale_q(ifile->
ts_offset, AV_TIME_BASE_Q,
ist->st->time_base);
4713 if (pkt->pts != AV_NOPTS_VALUE)
4714 pkt->pts *=
ist->ts_scale;
4715 if (pkt->dts != AV_NOPTS_VALUE)
4716 pkt->dts *=
ist->ts_scale;
4718 pkt_dts = av_rescale_q_rnd(pkt->dts,
ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4719 if ((
ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
4720 ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
4721 pkt_dts != AV_NOPTS_VALUE &&
ist->next_dts == AV_NOPTS_VALUE && !
copy_ts
4722 && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->
last_ts != AV_NOPTS_VALUE) {
4723 int64_t delta = pkt_dts - ifile->
last_ts;
4727 av_log(NULL, AV_LOG_DEBUG,
4728 "Inter stream timestamp discontinuity %"PRId64
", new offset= %"PRId64
"\n",
4730 pkt->dts -= av_rescale_q(delta, AV_TIME_BASE_Q,
ist->st->time_base);
4731 if (pkt->pts != AV_NOPTS_VALUE)
4732 pkt->pts -= av_rescale_q(delta, AV_TIME_BASE_Q,
ist->st->time_base);
4737 if (pkt->pts != AV_NOPTS_VALUE) {
4738 pkt->pts += duration;
4739 ist->max_pts = FFMAX(pkt->pts,
ist->max_pts);
4740 ist->min_pts = FFMIN(pkt->pts,
ist->min_pts);
4743 if (pkt->dts != AV_NOPTS_VALUE)
4744 pkt->dts += duration;
4746 pkt_dts = av_rescale_q_rnd(pkt->dts,
ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4748 if (
copy_ts && pkt_dts != AV_NOPTS_VALUE &&
ist->next_dts != AV_NOPTS_VALUE &&
4749 (is->iformat->flags & AVFMT_TS_DISCONT) &&
ist->st->pts_wrap_bits < 60) {
4750 int64_t wrap_dts = av_rescale_q_rnd(pkt->dts + (1LL<<
ist->st->pts_wrap_bits),
4751 ist->st->time_base, AV_TIME_BASE_Q,
4752 AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4753 if (FFABS(wrap_dts -
ist->next_dts) < FFABS(pkt_dts -
ist->next_dts)/10)
4754 disable_discontinuity_correction = 0;
4757 if ((
ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
4758 ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
4759 pkt_dts != AV_NOPTS_VALUE &&
ist->next_dts != AV_NOPTS_VALUE &&
4760 !disable_discontinuity_correction) {
4761 int64_t delta = pkt_dts -
ist->next_dts;
4762 if (is->iformat->flags & AVFMT_TS_DISCONT) {
4765 pkt_dts + AV_TIME_BASE/10 < FFMAX(
ist->pts,
ist->dts)) {
4767 av_log(NULL, AV_LOG_DEBUG,
4768 "timestamp discontinuity for stream #%d:%d "
4769 "(id=%d, type=%s): %"PRId64
", new offset= %"PRId64
"\n",
4770 ist->file_index,
ist->st->index,
ist->st->id,
4771 av_get_media_type_string(
ist->dec_ctx->codec_type),
4773 pkt->dts -= av_rescale_q(delta, AV_TIME_BASE_Q,
ist->st->time_base);
4774 if (pkt->pts != AV_NOPTS_VALUE)
4775 pkt->pts -= av_rescale_q(delta, AV_TIME_BASE_Q,
ist->st->time_base);
4780 av_log(NULL, AV_LOG_WARNING,
"DTS %"PRId64
", next:%"PRId64
" st:%d invalid dropping\n", pkt->dts,
ist->next_dts, pkt->stream_index);
4781 pkt->dts = AV_NOPTS_VALUE;
4783 if (pkt->pts != AV_NOPTS_VALUE){
4784 int64_t pkt_pts = av_rescale_q(pkt->pts,
ist->st->time_base, AV_TIME_BASE_Q);
4785 delta = pkt_pts -
ist->next_dts;
4788 av_log(NULL, AV_LOG_WARNING,
"PTS %"PRId64
", next:%"PRId64
" invalid dropping st:%d\n", pkt->pts,
ist->next_dts, pkt->stream_index);
4789 pkt->pts = AV_NOPTS_VALUE;
4795 if (pkt->dts != AV_NOPTS_VALUE)
4796 ifile->
last_ts = av_rescale_q(pkt->dts,
ist->st->time_base, AV_TIME_BASE_Q);
4799 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",
4800 ifile->
ist_index + pkt->stream_index, av_get_media_type_string(
ist->dec_ctx->codec_type),
4801 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &
ist->st->time_base),
4802 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &
ist->st->time_base),
4813 if (ifile->thread_queue_size)
4814 av_packet_free(&pkt);
4817 av_packet_unref(pkt);
4832 int nb_requests, nb_requests_max = 0;
4837 ret = avfilter_graph_request_oldest(
graph->graph);
4841 if (ret == AVERROR_EOF) {
4843 for (i = 0; i <
graph->nb_outputs; i++)
4847 if (ret != AVERROR(EAGAIN))
4850 for (i = 0; i <
graph->nb_inputs; i++) {
4851 ifilter =
graph->inputs[i];
4856 nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->
filter);
4857 if (nb_requests > nb_requests_max) {
4858 nb_requests_max = nb_requests;
4864 for (i = 0; i <
graph->nb_outputs; i++)
4865 graph->outputs[i]->ost->unavailable = 1;
4888 av_log(NULL, AV_LOG_VERBOSE,
"No more inputs to read from, finishing.\n");
4896 av_log(NULL, AV_LOG_ERROR,
"Error reinitializing filters!\n");
4924 if (av_buffersink_get_type(
ost->
filter->
filter) == AVMEDIA_TYPE_AUDIO)
4950 if (ret == AVERROR(EAGAIN)) {
4957 return ret == AVERROR_EOF ? 0 : ret;
4968 AVFormatContext *os;
4971 int64_t timer_start;
4972 int64_t total_packets_written = 0;
4979 av_log(NULL, AV_LOG_INFO,
"Press [q] to stop, [?] for help\n");
4982 timer_start = av_gettime_relative();
4985 if ((ret = init_input_threads()) < 0)
4990 int64_t cur_time= av_gettime_relative();
4999 av_log(NULL, AV_LOG_VERBOSE,
"No more output streams to write to, finishing.\n");
5004 if (ret < 0 && ret != AVERROR_EOF) {
5005 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(ret));
5013 free_input_threads();
5031 av_log(NULL, AV_LOG_ERROR,
5032 "Nothing was written into output file %d (%s), because "
5033 "at least one of its streams received no packets.\n",
5037 if ((ret = av_write_trailer(os)) < 0) {
5038 av_log(NULL, AV_LOG_ERROR,
"Error writing trailer of %s: %s\n", os->url, av_err2str(ret));
5055 av_log(NULL, AV_LOG_FATAL,
"Empty output on stream %d.\n", i);
5061 av_log(NULL, AV_LOG_FATAL,
"Empty output\n");
5068 if (
ist->decoding_needed) {
5069 avcodec_close(
ist->dec_ctx);
5070 if (
ist->hwaccel_uninit)
5071 ist->hwaccel_uninit(
ist->dec_ctx);
5082 free_input_threads();
5091 av_log(NULL, AV_LOG_ERROR,
5092 "Error closing logfile, loss of information possible: %s\n",
5093 av_err2str(AVERROR(errno)));
5113 struct rusage rusage;
5115 getrusage(RUSAGE_SELF, &rusage);
5117 (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
5119 (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
5120#elif HAVE_GETPROCESSTIMES
5122 FILETIME c, e, k, u;
5123 proc = GetCurrentProcess();
5124 GetProcessTimes(proc, &c, &e, &k, &u);
5126 ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
5128 ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
5137#if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
5138 struct rusage rusage;
5139 getrusage(RUSAGE_SELF, &rusage);
5140 return (int64_t)rusage.ru_maxrss * 1024;
5141#elif HAVE_GETPROCESSMEMORYINFO
5143 PROCESS_MEMORY_COUNTERS memcounters;
5144 proc = GetCurrentProcess();
5145 memcounters.cb =
sizeof(memcounters);
5146 GetProcessMemoryInfo(proc, &memcounters,
sizeof(memcounters));
5147 return memcounters.PeakPagefileUsage;
5211 char _program_name[] =
"ffmpeg";
5215 #define OFFSET(x) offsetof(OptionsContext, x)
5233 {
"bsfs",
OPT_EXIT, { .func_arg =
show_bsfs },
"show available bit stream filters" },
5242 {
"report", 0, { .func_arg =
opt_report },
"generate a report" },
5243 {
"max_alloc",
HAS_ARG, { .func_arg =
opt_max_alloc },
"set maximum size of a single allocated block",
"bytes" },
5250 "list sources of the input device",
"device" },
5252 "list sinks of the output device",
"device" },
5257 "force format",
"fmt" },
5259 "overwrite output files" },
5261 "never overwrite output files" },
5263 "Ignore unknown stream types" },
5265 "Copy unknown stream types" },
5268 "codec name",
"codec" },
5271 "codec name",
"codec" },
5274 "preset name",
"preset" },
5277 "set input stream mapping",
5278 "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
5280 "map an audio channel from one stream to another",
"file.stream.channel[:syncfile.syncstream]" },
5283 "set metadata information of outfile from infile",
5284 "outfile[,metadata]:infile[,metadata]" },
5287 "set chapters mapping",
"input_file_index" },
5290 "record or transcode \"duration\" seconds of audio/video",
5293 "record or transcode stop time",
"time_stop" },
5295 "set the limit file size in bytes",
"limit_size" },
5298 "set the start time offset",
"time_off" },
5301 "set the start time offset relative to EOF",
"time_off" },
5304 "enable/disable seeking by timestamp with -ss" },
5307 "enable/disable accurate seeking with -ss" },
5310 "set the input ts offset",
"time_off" },
5313 "set the input ts scale",
"scale" },
5315 "set the recording timestamp ('now' to set the current time)",
"time" },
5317 "add metadata",
"string=string" },
5319 "add program with specified streams",
"title=string:st=number..." },
5322 "set the number of data frames to output",
"number" },
5324 "add timings for benchmarking" },
5326 "add timings for each task" },
5328 "write program-readable progress information",
"url" },
5330 "enable or disable interaction on standard input" },
5332 "set max runtime in seconds in CPU user time",
"limit" },
5334 "dump each input packet" },
5336 "when dumping packets, also dump the payload" },
5339 "read input at native frame rate",
"" },
5341 "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\" or \"dv50\" "
5342 "with optional prefixes \"pal-\", \"ntsc-\" or \"film-\")",
"type" },
5344 "video sync method",
"" },
5346 "frame drop threshold",
"" },
5348 "audio sync method",
"" },
5350 "audio drift threshold",
"threshold" },
5352 "copy timestamps" },
5354 "shift input timestamps to start at 0 when using copyts" },
5356 "copy input stream time base when stream copying",
"mode" },
5358 "shift input timestamps to start at 0 when using copyts" },
5360 "copy input stream time base when stream copying",
"mode" },
5363 "finish encoding within shortest input" },
5371 "timestamp discontinuity delta threshold",
"threshold" },
5373 "timestamp error delta threshold",
"threshold" },
5375 "exit on error",
"error" },
5377 "abort on the specified condition flags",
"flags" },
5380 "copy initial non-keyframes" },
5382 "copy or discard frames before start time" },
5384 "set the number of frames to output",
"number" },
5387 "force codec tag/fourcc",
"fourcc/tag" },
5390 "use fixed quality scale (VBR)",
"q" },
5393 "use fixed quality scale (VBR)",
"q" },
5395 "set profile",
"profile" },
5397 "set stream filtergraph",
"filter_graph" },
5399 "number of non-complex filter threads" },
5401 "read stream filtergraph description from a file",
"filename" },
5403 "reinit filtergraph on input parameter changes",
"" },
5405 "create a complex filtergraph",
"graph_description" },
5407 "number of threads for -filter_complex" },
5409 "create a complex filtergraph",
"graph_description" },
5411 "read complex filtergraph description from a file",
"filename" },
5413 "enable automatic conversion filters globally" },
5415 "print progress report during encoding", },
5417 "set the period at which ffmpeg updates stats and -progress output",
"time" },
5420 "add an attachment to the output file",
"filename" },
5423 "extract an attachment into a file",
"filename" },
5425 OPT_OFFSET, { .off =
OFFSET(loop) },
"set number of times input stream shall be looped",
"loop count" },
5427 "print timestamp debugging info" },
5429 "ratio of errors (0.0: no errors, 1.0: 100% errors) above which ffmpeg returns an error instead of success.",
"maximum error rate" },
5435 "disposition",
"" },
5437 { .off =
OFFSET(thread_queue_size) },
5438 "set the maximum number of queued packets from the demuxer" },
5440 "read and decode the streams to fill missing information with heuristics" },
5444 "set the number of video frames to output",
"number" },
5447 "set frame rate (Hz value, fraction or abbreviation)",
"rate" },
5450 "set frame size (WxH or abbreviation)",
"size" },
5453 "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)",
"aspect" },
5456 "set pixel format",
"format" },
5458 "set the number of bits per raw sample",
"number" },
5460 "deprecated use -g 1" },
5465 "rate control override for specific intervals",
"override" },
5468 "force video codec ('copy' to copy stream)",
"codec" },
5474 "set initial TimeCode value.",
"hh:mm:ss[:;.]ff" },
5476 "select the pass number (1 to 3)",
"n" },
5479 "select two pass log file name prefix",
"prefix" },
5481 "this option is deprecated, use the yadif filter instead" },
5483 "calculate PSNR of compressed frames" },
5485 "dump video coding statistics to file" },
5487 "dump video coding statistics to file",
"file" },
5489 "Version of the vstats format to use."},
5491 "set video filters",
"filter_graph" },
5494 "specify intra matrix coeffs",
"matrix" },
5497 "specify inter matrix coeffs",
"matrix" },
5500 "specify intra matrix coeffs",
"matrix" },
5503 "top=1/bottom=0/auto=-1 field first",
"" },
5506 "force video tag/fourcc",
"fourcc/tag" },
5508 "show QP histogram" },
5511 "force the selected framerate, disable the best supported framerate selection" },
5514 "set the value of an outfile streamid",
"streamIndex:value" },
5517 "force key frames at specified timestamps",
"timestamps" },
5519 "audio bitrate (please use -b:a)",
"bitrate" },
5521 "video bitrate (please use -b:v)",
"bitrate" },
5524 "use HW accelerated decoding",
"hwaccel name" },
5527 "select a device for HW acceleration",
"devicename" },
5530 "select output format used with HW accelerated decoding",
"format" },
5531 #if CONFIG_VIDEOTOOLBOX
5535 "show available HW acceleration methods" },
5538 "automatically insert correct rotate filters" },
5541 "automatically insert a scale filter at the end of the filter graph" },
5545 "set the number of audio frames to output",
"number" },
5547 "set audio quality (codec-specific)",
"quality", },
5550 "set audio sampling rate (in Hz)",
"rate" },
5553 "set number of audio channels",
"channels" },
5558 "force audio codec ('copy' to copy stream)",
"codec" },
5561 "force audio tag/fourcc",
"fourcc/tag" },
5563 "change audio volume (256=normal)" ,
"volume" },
5566 "set sample format",
"format" },
5569 "set channel layout",
"layout" },
5571 "set audio filters",
"filter_graph" },
5573 "set the maximum number of channels to try to guess the channel layout" },
5577 "disable subtitle" },
5579 "force subtitle codec ('copy' to copy stream)",
"codec" },
5581 ,
"force subtitle tag/fourcc",
"fourcc/tag" },
5583 "fix subtitles duration" },
5585 "set canvas size (WxH or abbreviation)",
"size" },
5589 "deprecated, use -channel",
"channel" },
5591 "deprecated, use -standard",
"standard" },
5596 "set the maximum demux-decode delay",
"seconds" },
5598 "set the initial demux-decode delay",
"seconds" },
5600 "specify a file in which to print sdp information",
"file" },
5603 "set the desired time base hint for output stream (1:24, 1:48000 or 0.04166, 2.0833e-5)",
"ratio" },
5605 "set the desired time base for the encoder (1:24, 1:48000 or 0.04166, 2.0833e-5). "
5606 "two special values are defined - "
5607 "0 = use frame rate (video) or sample rate (audio),"
5608 "-1 = match source time base",
"ratio" },
5611 "A comma-separated list of bitstream filters",
"bitstream_filters" },
5613 "deprecated",
"audio bitstream_filters" },
5615 "deprecated",
"video bitstream_filters" },
5618 "set the audio options to the indicated preset",
"preset" },
5620 "set the video options to the indicated preset",
"preset" },
5622 "set the subtitle options to the indicated preset",
"preset" },
5624 "set options from indicated preset file",
"filename" },
5627 "maximum number of packets that can be buffered while waiting for all streams to initialize",
"packets" },
5629 "set the threshold after which max_muxing_queue_size is taken into account",
"bytes" },
5633 "force data codec ('copy' to copy stream)",
"codec" },
5639 "set VAAPI hardware device (DRM path or X11 display name)",
"device" },
5644 "set QSV hardware device (DirectX adapter index, DRM path or X11 display name)",
"device"},
5648 "initialise hardware device",
"args" },
5650 "set hardware device used when filtering",
"device" },
5661 if (savedCode == 0) {
5669 setvbuf(stderr,NULL,_IONBF,0);
5671 av_log_set_flags(AV_LOG_SKIP_REPEATED);
5674 if(argc>1 && !strcmp(argv[1],
"-d")){
5682 avdevice_register_all();
5684 avformat_network_init();
5695 av_log(NULL, AV_LOG_WARNING,
"Use -h to get full help or, even better, run 'man %s'\n",
program_name);
5701 av_log(NULL, AV_LOG_FATAL,
"At least one output file must be specified\n");
5706 if (strcmp(
output_files[i]->ctx->oformat->name,
"rtp"))
5714 int64_t utime, stime, rtime;
5719 av_log(NULL, AV_LOG_INFO,
5720 "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
5721 utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
5723 av_log(NULL, AV_LOG_DEBUG,
"%"PRIu64
" frames successfully decoded, %"PRIu64
" decoding errors\n",
__thread jmp_buf ex_buf__
int(* init)(AVCodecContext *s)
int64_t start_time
start time in microseconds == AV_TIME_BASE units
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
struct OutputStream * ost
uint64_t * channel_layouts
struct FilterGraph * graph
int max_muxing_queue_size
int copy_initial_nonkeyframes
double forced_keyframes_expr_const_values[FKF_NB]
AVRational frame_aspect_ratio
double rotate_override_value
int audio_channels_mapped
size_t muxing_queue_data_threshold
AVDictionary * resample_opts
AVRational max_frame_rate
AVFifoBuffer * muxing_queue
AVCodecParameters * ref_par
const char * attachment_filename
struct InputStream * sync_ist
AVDictionary * encoder_opts
char * filters
filtergraph associated to the -filter option
int64_t forced_kf_ref_pts
char * filters_script
filtergraph script associated to the -filter_script option
AVExpr * forced_keyframes_pexpr
size_t muxing_queue_data_size