62 #include <stdatomic.h>
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
105 #include <sys/time.h>
106 #include <sys/types.h>
107 #include <sys/resource.h>
108 #elif HAVE_GETPROCESSTIMES
111 #if HAVE_GETPROCESSMEMORYINFO
115 #if HAVE_SETCONSOLECTRLHANDLER
120 #if HAVE_SYS_SELECT_H
121 #include <sys/select.h>
126 #include <sys/ioctl.h>
127 #include <sys/time.h>
138 #include "libavutil/avassert.h"
200 extern int opt_map(
void *optctx,
const char *opt,
const char *arg);
201 extern int opt_map_channel(
void *optctx,
const char *opt,
const char *arg);
203 extern int opt_data_frames(
void *optctx,
const char *opt,
const char *arg);
204 extern int opt_progress(
void *optctx,
const char *opt,
const char *arg);
205 extern int opt_target(
void *optctx,
const char *opt,
const char *arg);
206 extern int opt_vsync(
void *optctx,
const char *opt,
const char *arg);
207 extern int opt_abort_on(
void *optctx,
const char *opt,
const char *arg);
208 extern int opt_stats_period(
void *optctx,
const char *opt,
const char *arg);
209 extern int opt_qscale(
void *optctx,
const char *opt,
const char *arg);
210 extern int opt_profile(
void *optctx,
const char *opt,
const char *arg);
213 extern int opt_attach(
void *optctx,
const char *opt,
const char *arg);
214 extern int opt_video_frames(
void *optctx,
const char *opt,
const char *arg);
216 extern int opt_video_codec(
void *optctx,
const char *opt,
const char *arg);
217 extern int opt_sameq(
void *optctx,
const char *opt,
const char *arg);
218 extern int opt_timecode(
void *optctx,
const char *opt,
const char *arg);
220 extern int opt_vstats_file(
void *optctx,
const char *opt,
const char *arg);
221 extern int opt_vstats(
void *optctx,
const char *opt,
const char *arg);
222 extern int opt_video_frames(
void *optctx,
const char *opt,
const char *arg);
223 extern int opt_old2new(
void *optctx,
const char *opt,
const char *arg);
224 extern int opt_streamid(
void *optctx,
const char *opt,
const char *arg);
225 extern int opt_bitrate(
void *optctx,
const char *opt,
const char *arg);
226 extern int show_hwaccels(
void *optctx,
const char *opt,
const char *arg);
228 extern int opt_audio_frames(
void *optctx,
const char *opt,
const char *arg);
229 extern int opt_audio_qscale(
void *optctx,
const char *opt,
const char *arg);
230 extern int opt_audio_codec(
void *optctx,
const char *opt,
const char *arg);
232 extern int opt_preset(
void *optctx,
const char *opt,
const char *arg);
237 extern int opt_sdp_file(
void *optctx,
const char *opt,
const char *arg);
238 extern int opt_data_codec(
void *optctx,
const char *opt,
const char *arg);
239 extern int opt_vaapi_device(
void *optctx,
const char *opt,
const char *arg);
247 __thread
struct termios oldtty;
248 __thread
int restore_tty;
252 static void free_input_threads(
void);
273 AVFrame *frame =
ist->sub2video.frame;
275 av_frame_unref(frame);
276 ist->sub2video.frame->width =
ist->dec_ctx->width ?
ist->dec_ctx->width :
ist->sub2video.w;
277 ist->sub2video.frame->height =
ist->dec_ctx->height ?
ist->dec_ctx->height :
ist->sub2video.h;
278 ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
279 if ((ret = av_frame_get_buffer(frame, 0)) < 0)
281 memset(frame->data[0], 0, frame->height * frame->linesize[0]);
288 uint32_t *pal, *dst2;
292 if (r->type != SUBTITLE_BITMAP) {
293 av_log(NULL, AV_LOG_WARNING,
"sub2video: non-bitmap subtitle\n");
296 if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
297 av_log(NULL, AV_LOG_WARNING,
"sub2video: rectangle (%d %d %d %d) overflowing %d %d\n",
298 r->x, r->y, r->w, r->h, w, h
303 dst += r->y * dst_linesize + r->x * 4;
305 pal = (uint32_t *)r->data[1];
306 for (y = 0; y < r->h; y++) {
307 dst2 = (uint32_t *)dst;
309 for (x = 0; x < r->w; x++)
310 *(dst2++) = pal[*(src2++)];
312 src += r->linesize[0];
318 AVFrame *frame =
ist->sub2video.frame;
322 av_assert1(frame->data[0]);
323 ist->sub2video.last_pts = frame->pts = pts;
324 for (i = 0; i <
ist->nb_filters; i++) {
325 ret = av_buffersrc_add_frame_flags(
ist->filters[i]->filter, frame,
326 AV_BUFFERSRC_FLAG_KEEP_REF |
327 AV_BUFFERSRC_FLAG_PUSH);
328 if (ret != AVERROR_EOF && ret < 0)
329 av_log(NULL, AV_LOG_WARNING,
"Error while add the frame to buffer source(%s).\n",
336 AVFrame *frame =
ist->sub2video.frame;
340 int64_t pts, end_pts;
345 pts = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
346 AV_TIME_BASE_Q,
ist->st->time_base);
347 end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000LL,
348 AV_TIME_BASE_Q,
ist->st->time_base);
349 num_rects = sub->num_rects;
355 pts =
ist->sub2video.initialize ?
356 heartbeat_pts :
ist->sub2video.end_pts;
361 av_log(
ist->dec_ctx, AV_LOG_ERROR,
362 "Impossible to get a blank canvas.\n");
365 dst = frame->data [0];
366 dst_linesize = frame->linesize[0];
367 for (i = 0; i < num_rects; i++)
370 ist->sub2video.end_pts = end_pts;
371 ist->sub2video.initialize = 0;
390 pts2 = av_rescale_q(pts,
ist->st->time_base, ist2->
st->time_base) - 1;
392 if (pts2 <= ist2->sub2video.last_pts)
399 for (j = 0, nb_reqs = 0; j < ist2->
nb_filters; j++)
400 nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->
filters[j]->
filter);
411 if (
ist->sub2video.end_pts < INT64_MAX)
413 for (i = 0; i <
ist->nb_filters; i++) {
414 ret = av_buffersrc_add_frame(
ist->filters[i]->filter, NULL);
415 if (ret != AVERROR_EOF && ret < 0)
416 av_log(NULL, AV_LOG_WARNING,
"Flush the frame error.\n");
426 tcsetattr (0, TCSANOW, &oldtty);
432 av_log(NULL, AV_LOG_QUIET,
"%s",
"");
452 #if HAVE_SETCONSOLECTRLHANDLER
453 static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
455 av_log(NULL, AV_LOG_DEBUG,
"\nReceived windows signal %ld\n", fdwCtrlType);
460 case CTRL_BREAK_EVENT:
464 case CTRL_CLOSE_EVENT:
465 case CTRL_LOGOFF_EVENT:
466 case CTRL_SHUTDOWN_EVENT:
478 av_log(NULL, AV_LOG_ERROR,
"Received unknown windows signal %ld\n", fdwCtrlType);
485 #define SIGNAL(sig, func) \
487 action.sa_handler = func; \
488 sigaction(sig, &action, NULL); \
491 #define SIGNAL(sig, func) \
497 #if defined __linux__
498 #if defined __aarch64__ || defined __amd64__ || defined __x86_64__
499 struct sigaction action = {0};
501 struct sigaction action = {{0}};
507 sigfillset(&action.sa_mask);
510 action.sa_flags = SA_RESTART;
516 if (tcgetattr (0, &tty) == 0) {
520 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
521 |INLCR|IGNCR|ICRNL|IXON);
522 tty.c_oflag |= OPOST;
523 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
524 tty.c_cflag &= ~(CSIZE|PARENB);
529 tcsetattr (0, TCSANOW, &tty);
550 signal(SIGPIPE, SIG_IGN);
553 #if HAVE_SETCONSOLECTRLHANDLER
554 SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
571 n = select(1, &rfds, NULL, NULL, &tv);
580 # if HAVE_PEEKNAMEDPIPE
582 static HANDLE input_handle;
585 input_handle = GetStdHandle(STD_INPUT_HANDLE);
586 is_pipe = !GetConsoleMode(input_handle, &dw);
591 if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
625 av_log(NULL, AV_LOG_INFO,
"bench: maxrss=%ikB\n", maxrss);
630 avfilter_graph_free(&fg->
graph);
638 sizeof(frame), NULL);
639 av_frame_free(&frame);
642 if (
ist->sub2video.sub_queue) {
643 while (av_fifo_size(
ist->sub2video.sub_queue)) {
645 av_fifo_generic_read(
ist->sub2video.sub_queue,
646 &sub,
sizeof(sub), NULL);
647 avsubtitle_free(&sub);
649 av_fifo_freep(&
ist->sub2video.sub_queue);
652 av_freep(&ifilter->
name);
659 avfilter_inout_free(&ofilter->
out_tmp);
660 av_freep(&ofilter->
name);
682 if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
684 avformat_free_context(s);
685 av_dict_free(&of->
opts);
699 av_packet_free(&
ost->
pkt);
720 av_packet_free(&
pkt);
728 free_input_threads();
738 av_frame_free(&
ist->decoded_frame);
739 av_frame_free(&
ist->filter_frame);
740 av_packet_free(&
ist->pkt);
741 av_dict_free(&
ist->decoder_opts);
742 avsubtitle_free(&
ist->prev_sub.subtitle);
743 av_frame_free(&
ist->sub2video.frame);
744 av_freep(&
ist->filters);
745 av_freep(&
ist->hwaccel_device);
746 av_freep(&
ist->dts_buffer);
748 avcodec_free_context(&
ist->dec_ctx);
755 av_log(NULL, AV_LOG_ERROR,
756 "Error closing vstats file, loss of information possible: %s\n",
757 av_err2str(AVERROR(errno)));
768 avformat_network_deinit();
771 av_log(NULL, AV_LOG_INFO,
"Exiting normally, received signal %d.\n",
774 av_log(NULL, AV_LOG_INFO,
"Exiting normally, received cancel request.\n");
776 av_log(NULL, AV_LOG_INFO,
"Conversion failed!\n");
784 AVDictionaryEntry *t = NULL;
786 while ((t = av_dict_get(b,
"", t, AV_DICT_IGNORE_SUFFIX))) {
787 av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
793 AVDictionaryEntry *t;
794 if ((t = av_dict_get(m,
"", NULL, AV_DICT_IGNORE_SUFFIX))) {
795 av_log(NULL, AV_LOG_FATAL,
"Option %s not found.\n", t->key);
814 vsnprintf(buf,
sizeof(buf), fmt, va);
816 av_log(NULL, AV_LOG_INFO,
817 "bench: %8" PRIu64
" user %8" PRIu64
" sys %8" PRIu64
" real %s \n",
831 ost2->
finished |=
ost == ost2 ? this_stream : others;
837 AVFormatContext *s = of->
ctx;
851 av_packet_unref(
pkt);
861 unsigned int are_we_over_size =
863 int new_size = are_we_over_size ?
869 av_log(NULL, AV_LOG_ERROR,
870 "Too many packets buffered for output stream %d:%d.\n",
878 ret = av_packet_make_refcounted(
pkt);
881 tmp_pkt = av_packet_alloc();
884 av_packet_move_ref(tmp_pkt,
pkt);
886 av_fifo_generic_write(
ost->
muxing_queue, &tmp_pkt,
sizeof(tmp_pkt), NULL);
892 pkt->pts =
pkt->dts = AV_NOPTS_VALUE;
894 if (
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
896 uint8_t *sd = av_packet_get_side_data(
pkt, AV_PKT_DATA_QUALITY_STATS,
901 for (i = 0; i<FF_ARRAY_ELEMS(
ost->
error); i++) {
903 ost->
error[i] = AV_RL64(sd + 8 + 8*i);
909 if (
pkt->duration > 0)
910 av_log(NULL, AV_LOG_WARNING,
"Overriding packet duration by frame rate, this should not happen\n");
918 if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
919 if (
pkt->dts != AV_NOPTS_VALUE &&
920 pkt->pts != AV_NOPTS_VALUE &&
922 av_log(s, AV_LOG_WARNING,
"Invalid DTS: %"PRId64
" PTS: %"PRId64
" in output stream %d:%d, replacing by guess\n",
930 if ((
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) &&
931 pkt->dts != AV_NOPTS_VALUE &&
934 int64_t max =
ost->
last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
935 if (
pkt->dts < max) {
936 int loglevel = max -
pkt->dts > 2 ||
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
938 loglevel = AV_LOG_ERROR;
939 av_log(s, loglevel,
"Non-monotonous DTS in output stream "
940 "%d:%d; previous: %"PRId64
", current: %"PRId64
"; ",
943 av_log(NULL, AV_LOG_FATAL,
"aborting.\n");
946 av_log(s, loglevel,
"changing to %"PRId64
". This may result "
947 "in incorrect timestamps in the output file.\n",
950 pkt->pts = FFMAX(
pkt->pts, max);
963 av_log(NULL, AV_LOG_INFO,
"muxer <- type:%s "
964 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
965 av_get_media_type_string(
ost->
enc_ctx->codec_type),
966 av_ts2str(
pkt->pts), av_ts2timestr(
pkt->pts, &
ost->
st->time_base),
967 av_ts2str(
pkt->dts), av_ts2timestr(
pkt->dts, &
ost->
st->time_base),
972 ret = av_interleaved_write_frame(s,
pkt);
978 av_packet_unref(
pkt);
1015 if (
ret == AVERROR(EAGAIN))
1021 if (
ret < 0 &&
ret != AVERROR_EOF) {
1022 av_log(NULL, AV_LOG_ERROR,
"Error applying bitstream filters to an output "
1035 AV_TIME_BASE_Q) >= 0) {
1044 double float_pts = AV_NOPTS_VALUE;
1046 if (!frame || frame->pts == AV_NOPTS_VALUE ||
1054 AVRational filter_tb = av_buffersink_get_time_base(
filter);
1055 AVRational tb = enc->time_base;
1056 int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
1058 tb.den <<= extra_bits;
1060 av_rescale_q(frame->pts, filter_tb, tb) -
1061 av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
1062 float_pts /= 1 << extra_bits;
1064 float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
1067 av_rescale_q(frame->pts, filter_tb, enc->time_base) -
1068 av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
1074 av_log(NULL, AV_LOG_INFO,
"filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
1075 frame ? av_ts2str(frame->pts) :
"NULL",
1076 frame ? av_ts2timestr(frame->pts, &enc->time_base) :
"NULL",
1078 enc ? enc->time_base.num : -1,
1079 enc ? enc->time_base.den : -1);
1089 int ret = AVERROR_BUG;
1090 char error[1024] = {0};
1097 av_log(NULL, AV_LOG_ERROR,
"Error initializing output stream %d:%d -- %s\n",
1127 av_log(NULL, AV_LOG_INFO,
"encoder <- type:audio "
1128 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1129 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
1130 enc->time_base.num, enc->time_base.den);
1133 ret = avcodec_send_frame(enc, frame);
1138 av_packet_unref(
pkt);
1139 ret = avcodec_receive_packet(enc,
pkt);
1140 if (
ret == AVERROR(EAGAIN))
1150 av_log(NULL, AV_LOG_INFO,
"encoder -> type:audio "
1151 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1152 av_ts2str(
pkt->pts), av_ts2timestr(
pkt->pts, &enc->time_base),
1153 av_ts2str(
pkt->dts), av_ts2timestr(
pkt->dts, &enc->time_base));
1161 av_log(NULL, AV_LOG_FATAL,
"Audio encoding failed\n");
1169 int subtitle_out_max_size = 1024 * 1024;
1170 int subtitle_out_size, nb, i;
1171 AVCodecContext *enc;
1175 if (sub->pts == AV_NOPTS_VALUE) {
1176 av_log(NULL, AV_LOG_ERROR,
"Subtitle packets must have a pts\n");
1187 av_log(NULL, AV_LOG_FATAL,
"Failed to allocate subtitle_out\n");
1195 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1204 for (i = 0; i < nb; i++) {
1205 unsigned save_num_rects = sub->num_rects;
1213 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1214 sub->end_display_time -= sub->start_display_time;
1215 sub->start_display_time = 0;
1221 subtitle_out_size = avcodec_encode_subtitle(enc,
subtitle_out,
1222 subtitle_out_max_size, sub);
1224 sub->num_rects = save_num_rects;
1225 if (subtitle_out_size < 0) {
1226 av_log(NULL, AV_LOG_FATAL,
"Subtitle encoding failed\n");
1230 av_packet_unref(
pkt);
1232 pkt->size = subtitle_out_size;
1234 pkt->duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 },
ost->
mux_timebase);
1235 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
1239 pkt->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 },
ost->
mux_timebase);
1241 pkt->pts += av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 },
ost->
mux_timebase);
1250 AVFrame *next_picture)
1252 int ret, format_video_sync;
1255 AVRational frame_rate;
1256 int nb_frames, nb0_frames, i;
1257 double delta, delta0;
1258 double duration = 0;
1259 double sync_ipts = AV_NOPTS_VALUE;
1270 frame_rate = av_buffersink_get_frame_rate(
filter);
1271 if (frame_rate.num > 0 && frame_rate.den > 0)
1272 duration = 1/(av_q2d(frame_rate) * av_q2d(enc->time_base));
1274 if(
ist &&
ist->st->start_time != AV_NOPTS_VALUE &&
ist->first_dts != AV_NOPTS_VALUE &&
ost->
frame_rate.num)
1275 duration = FFMIN(duration, 1/(av_q2d(
ost->
frame_rate) * av_q2d(enc->time_base)));
1282 lrintf(next_picture->pkt_duration * av_q2d(
ist->st->time_base) / av_q2d(enc->time_base)) > 0) {
1283 duration = lrintf(next_picture->pkt_duration * av_q2d(
ist->st->time_base) / av_q2d(enc->time_base));
1286 if (!next_picture) {
1293 delta = delta0 + duration;
1301 if(!strcmp(of->
ctx->oformat->name,
"avi")) {
1321 if (delta0 < -0.6) {
1322 av_log(NULL, AV_LOG_VERBOSE,
"Past duration %f too large\n", -delta0);
1324 av_log(NULL, AV_LOG_DEBUG,
"Clipping frame in rate conversion by %f\n", -delta0);
1330 switch (format_video_sync) {
1333 av_log(NULL, AV_LOG_DEBUG,
"Not duplicating %d initial frames\n", (
int)lrintf(delta0));
1342 }
else if (delta < -1.1)
1344 else if (delta > 1.1) {
1345 nb_frames = lrintf(delta);
1347 nb0_frames = llrintf(delta0 - 0.6);
1353 else if (delta > 0.6)
1366 nb0_frames = FFMIN(nb0_frames, nb_frames);
1375 av_log(NULL, AV_LOG_VERBOSE,
1376 "*** dropping frame %d from stream %d at ts %"PRId64
"\n",
1379 if (nb_frames > (nb0_frames &&
ost->
last_dropped) + (nb_frames > nb0_frames)) {
1381 av_log(NULL, AV_LOG_ERROR,
"%d frame duplication too large, skipping\n", nb_frames - 1);
1386 av_log(NULL, AV_LOG_VERBOSE,
"*** %d dup!\n", nb_frames - 1);
1388 av_log(NULL, AV_LOG_WARNING,
"More than %d frames duplicated\n",
dup_warning);
1396 for (i = 0; i < nb_frames; i++) {
1397 AVFrame *in_picture;
1398 int forced_keyframe = 0;
1401 if (i < nb0_frames && ost->last_frame) {
1404 in_picture = next_picture;
1414 in_picture->quality = enc->global_quality;
1415 in_picture->pict_type = 0;
1418 in_picture->pts != AV_NOPTS_VALUE)
1421 pts_time = in_picture->pts != AV_NOPTS_VALUE ?
1426 forced_keyframe = 1;
1432 ff_dlog(NULL,
"force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
1440 forced_keyframe = 1;
1451 && in_picture->key_frame==1
1453 forced_keyframe = 1;
1461 if (forced_keyframe) {
1462 in_picture->pict_type = AV_PICTURE_TYPE_I;
1463 av_log(NULL, AV_LOG_DEBUG,
"Forced keyframe at time %f\n", pts_time);
1468 av_log(NULL, AV_LOG_INFO,
"encoder <- type:video "
1469 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1470 av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
1471 enc->time_base.num, enc->time_base.den);
1476 ret = avcodec_send_frame(enc, in_picture);
1480 av_frame_remove_side_data(in_picture, AV_FRAME_DATA_A53_CC);
1483 av_packet_unref(
pkt);
1484 ret = avcodec_receive_packet(enc,
pkt);
1486 if (
ret == AVERROR(EAGAIN))
1492 av_log(NULL, AV_LOG_INFO,
"encoder -> type:video "
1493 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1494 av_ts2str(
pkt->pts), av_ts2timestr(
pkt->pts, &enc->time_base),
1495 av_ts2str(
pkt->dts), av_ts2timestr(
pkt->dts, &enc->time_base));
1498 if (
pkt->pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & AV_CODEC_CAP_DELAY))
1504 av_log(NULL, AV_LOG_INFO,
"encoder -> type:video "
1505 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1510 frame_size =
pkt->size;
1540 av_log(NULL, AV_LOG_FATAL,
"Video encoding failed\n");
1546 return -10.0 * log10(
d);
1551 AVCodecContext *enc;
1553 double ti1, bitrate, avg_bitrate;
1565 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1566 frame_number =
ost->
st->nb_frames;
1568 fprintf(
vstats_file,
"frame= %5d q= %2.1f ", frame_number,
1575 if (
ost->
error[0]>=0 && (enc->flags & AV_CODEC_FLAG_PSNR))
1580 ti1 = av_stream_get_end_pts(
ost->
st) * av_q2d(
ost->
st->time_base);
1584 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1585 avg_bitrate = (double)(
ost->
data_size * 8) / ti1 / 1000.0;
1586 fprintf(
vstats_file,
"s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1587 (
double)
ost->
data_size / 1024, ti1, bitrate, avg_bitrate);
1600 for (i = 0; i < of->
ctx->nb_streams; i++)
1613 AVFrame *filtered_frame = NULL;
1637 if (av_buffersink_get_type(
filter) == AVMEDIA_TYPE_AUDIO)
1641 return AVERROR(ENOMEM);
1644 return AVERROR(ENOMEM);
1649 ret = av_buffersink_get_frame_flags(
filter, filtered_frame,
1650 AV_BUFFERSINK_FLAG_NO_REQUEST);
1652 if (
ret != AVERROR(EAGAIN) &&
ret != AVERROR_EOF) {
1653 av_log(NULL, AV_LOG_WARNING,
1654 "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(
ret));
1655 }
else if (flush &&
ret == AVERROR_EOF) {
1656 if (av_buffersink_get_type(
filter) == AVMEDIA_TYPE_VIDEO)
1662 av_frame_unref(filtered_frame);
1666 switch (av_buffersink_get_type(
filter)) {
1667 case AVMEDIA_TYPE_VIDEO:
1669 enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
1673 case AVMEDIA_TYPE_AUDIO:
1674 if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&
1675 enc->channels != filtered_frame->channels) {
1676 av_log(NULL, AV_LOG_ERROR,
1677 "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1687 av_frame_unref(filtered_frame);
1696 uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
1697 uint64_t subtitle_size = 0;
1699 float percent = -1.0;
1706 case AVMEDIA_TYPE_VIDEO: video_size +=
ost->
data_size;
break;
1707 case AVMEDIA_TYPE_AUDIO: audio_size +=
ost->
data_size;
break;
1708 case AVMEDIA_TYPE_SUBTITLE: subtitle_size +=
ost->
data_size;
break;
1713 if ( (
ost->
enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
1714 != AV_CODEC_FLAG_PASS1)
1721 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: ",
1722 video_size / 1024.0,
1723 audio_size / 1024.0,
1724 subtitle_size / 1024.0,
1725 other_size / 1024.0,
1726 extra_size / 1024.0);
1728 av_log(NULL, AV_LOG_INFO,
"%f%%", percent);
1730 av_log(NULL, AV_LOG_INFO,
"unknown");
1731 av_log(NULL, AV_LOG_INFO,
"\n");
1736 uint64_t total_packets = 0, total_size = 0;
1738 av_log(NULL, AV_LOG_VERBOSE,
"Input file #%d (%s):\n",
1743 enum AVMediaType type =
ist->dec_ctx->codec_type;
1745 total_size +=
ist->data_size;
1746 total_packets +=
ist->nb_packets;
1748 av_log(NULL, AV_LOG_VERBOSE,
" Input stream #%d:%d (%s): ",
1750 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" packets read (%"PRIu64
" bytes); ",
1751 ist->nb_packets,
ist->data_size);
1753 if (
ist->decoding_needed) {
1754 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" frames decoded",
1755 ist->frames_decoded);
1756 if (type == AVMEDIA_TYPE_AUDIO)
1757 av_log(NULL, AV_LOG_VERBOSE,
" (%"PRIu64
" samples)",
ist->samples_decoded);
1758 av_log(NULL, AV_LOG_VERBOSE,
"; ");
1761 av_log(NULL, AV_LOG_VERBOSE,
"\n");
1764 av_log(NULL, AV_LOG_VERBOSE,
" Total: %"PRIu64
" packets (%"PRIu64
" bytes) demuxed\n",
1765 total_packets, total_size);
1770 uint64_t total_packets = 0, total_size = 0;
1772 av_log(NULL, AV_LOG_VERBOSE,
"Output file #%d (%s):\n",
1775 for (j = 0; j < of->
ctx->nb_streams; j++) {
1777 enum AVMediaType type =
ost->
enc_ctx->codec_type;
1782 av_log(NULL, AV_LOG_VERBOSE,
" Output stream #%d:%d (%s): ",
1785 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" frames encoded",
1787 if (type == AVMEDIA_TYPE_AUDIO)
1789 av_log(NULL, AV_LOG_VERBOSE,
"; ");
1792 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" packets muxed (%"PRIu64
" bytes); ",
1795 av_log(NULL, AV_LOG_VERBOSE,
"\n");
1798 av_log(NULL, AV_LOG_VERBOSE,
" Total: %"PRIu64
" packets (%"PRIu64
" bytes) muxed\n",
1799 total_packets, total_size);
1801 if(video_size +
data_size + audio_size + subtitle_size + extra_size == 0){
1802 av_log(NULL, AV_LOG_WARNING,
"Output file is empty, nothing was encoded ");
1804 av_log(NULL, AV_LOG_WARNING,
"\n");
1806 av_log(NULL, AV_LOG_WARNING,
"(check -ss / -t / -frames parameters if used)\n");
1811 static void forward_report(
int is_last_report, int64_t timer_start, int64_t cur_time)
1813 AVFormatContext *oc = NULL;
1814 AVCodecContext *enc = NULL;
1816 int64_t
pts = INT64_MIN + 1;
1819 int frame_number = 0;
1822 int64_t total_size = 0;
1824 double bitrate = 0.0;
1827 float t = (cur_time-timer_start) / 1000000.0;
1832 total_size = avio_size(oc->pb);
1833 if (total_size <= 0) {
1834 total_size = avio_tell(oc->pb);
1845 quality =
ost->
quality / (float) FF_QP2LAMBDA;
1848 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1854 fps = t > 1 ? frame_number / t : 0;
1858 if (av_stream_get_end_pts(
ost->
st) != AV_NOPTS_VALUE)
1859 pts = FFMAX(
pts, av_rescale_q(av_stream_get_end_pts(
ost->
st),
1860 ost->
st->time_base, AV_TIME_BASE_Q));
1866 seconds = FFABS(
pts) / 1000;
1869 bitrate =
pts && total_size >= 0 ? total_size * 8 / (
pts / 1000.0) : -1;
1872 speed = t != 0.0 ? (double)
pts / AV_TIME_BASE / t : -1;
1876 report_callback(frame_number, fps, quality, total_size, seconds, bitrate, speed);
1880 static void print_report(
int is_last_report, int64_t timer_start, int64_t cur_time)
1882 AVBPrint buf, buf_script;
1884 AVFormatContext *oc;
1886 AVCodecContext *enc;
1887 int frame_number, vid, i;
1890 int64_t
pts = INT64_MIN + 1;
1891 int hours, mins, secs, us;
1892 const char *hours_sign;
1896 if (!is_last_report) {
1911 t = (cur_time-timer_start) / 1000000.0;
1916 total_size = avio_size(oc->pb);
1917 if (total_size <= 0)
1918 total_size = avio_tell(oc->pb);
1921 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
1922 av_bprint_init(&buf_script, 0, AV_BPRINT_SIZE_AUTOMATIC);
1930 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1931 av_bprintf(&buf,
"q=%2.1f ", q);
1932 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
1935 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1939 fps = t > 1 ? frame_number / t : 0;
1940 av_bprintf(&buf,
"frame=%5d fps=%3.*f q=%3.1f ",
1941 frame_number, fps < 9.95, fps, q);
1942 av_bprintf(&buf_script,
"frame=%d\n", frame_number);
1943 av_bprintf(&buf_script,
"fps=%.2f\n", fps);
1944 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
1947 av_bprintf(&buf,
"L");
1953 for (j = 0; j < 32; j++)
1957 if ((enc->flags & AV_CODEC_FLAG_PSNR) && (
ost->
pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {
1959 double error, error_sum = 0;
1960 double scale, scale_sum = 0;
1962 char type[3] = {
'Y',
'U',
'V' };
1963 av_bprintf(&buf,
"PSNR=");
1964 for (j = 0; j < 3; j++) {
1965 if (is_last_report) {
1966 error = enc->error[j];
1967 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1970 scale = enc->width * enc->height * 255.0 * 255.0;
1976 p =
psnr(error / scale);
1977 av_bprintf(&buf,
"%c:%2.2f ", type[j], p);
1978 av_bprintf(&buf_script,
"stream_%d_%d_psnr_%c=%2.2f\n",
1981 p =
psnr(error_sum / scale_sum);
1982 av_bprintf(&buf,
"*:%2.2f ",
psnr(error_sum / scale_sum));
1983 av_bprintf(&buf_script,
"stream_%d_%d_psnr_all=%2.2f\n",
1989 if (av_stream_get_end_pts(
ost->
st) != AV_NOPTS_VALUE) {
1990 pts = FFMAX(
pts, av_rescale_q(av_stream_get_end_pts(
ost->
st),
1991 ost->
st->time_base, AV_TIME_BASE_Q));
2004 secs = FFABS(
pts) / AV_TIME_BASE;
2005 us = FFABS(
pts) % AV_TIME_BASE;
2010 hours_sign = (
pts < 0) ?
"-" :
"";
2012 bitrate =
pts && total_size >= 0 ? total_size * 8 / (
pts / 1000.0) : -1;
2013 speed = t != 0.0 ? (double)
pts / AV_TIME_BASE / t : -1;
2015 if (total_size < 0) av_bprintf(&buf,
"size=N/A time=");
2016 else av_bprintf(&buf,
"size=%8.0fkB time=", total_size / 1024.0);
2017 if (
pts == AV_NOPTS_VALUE) {
2018 av_bprintf(&buf,
"N/A ");
2020 av_bprintf(&buf,
"%s%02d:%02d:%02d.%02d ",
2021 hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
2025 av_bprintf(&buf,
"bitrate=N/A");
2026 av_bprintf(&buf_script,
"bitrate=N/A\n");
2028 av_bprintf(&buf,
"bitrate=%6.1fkbits/s", bitrate);
2029 av_bprintf(&buf_script,
"bitrate=%6.1fkbits/s\n", bitrate);
2032 if (total_size < 0) av_bprintf(&buf_script,
"total_size=N/A\n");
2033 else av_bprintf(&buf_script,
"total_size=%"PRId64
"\n", total_size);
2034 if (
pts == AV_NOPTS_VALUE) {
2035 av_bprintf(&buf_script,
"out_time_us=N/A\n");
2036 av_bprintf(&buf_script,
"out_time_ms=N/A\n");
2037 av_bprintf(&buf_script,
"out_time=N/A\n");
2039 av_bprintf(&buf_script,
"out_time_us=%"PRId64
"\n",
pts);
2040 av_bprintf(&buf_script,
"out_time_ms=%"PRId64
"\n",
pts);
2041 av_bprintf(&buf_script,
"out_time=%s%02d:%02d:%02d.%06d\n",
2042 hours_sign, hours, mins, secs, us);
2051 av_bprintf(&buf,
" speed=N/A");
2052 av_bprintf(&buf_script,
"speed=N/A\n");
2054 av_bprintf(&buf,
" speed=%4.3gx", speed);
2055 av_bprintf(&buf_script,
"speed=%4.3gx\n", speed);
2059 const char end = is_last_report ?
'\n' :
'\r';
2060 if (
print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
2061 fprintf(stderr,
"%s %c", buf.str, end);
2063 av_log(NULL, AV_LOG_INFO,
"%s %c", buf.str, end);
2067 av_bprint_finalize(&buf, NULL);
2070 av_bprintf(&buf_script,
"progress=%s\n",
2071 is_last_report ?
"end" :
"continue");
2073 FFMIN(buf_script.len, buf_script.size - 1));
2075 av_bprint_finalize(&buf_script, NULL);
2076 if (is_last_report) {
2078 av_log(NULL, AV_LOG_ERROR,
2079 "Error closing progress log, loss of information possible: %s\n", av_err2str(
ret));
2093 ifilter->
format = par->format;
2097 ifilter->
width = par->width;
2098 ifilter->
height = par->height;
2119 av_log(NULL, AV_LOG_WARNING,
2120 "Finishing stream %d:%d without any data written to it.\n",
2136 av_log(NULL, AV_LOG_ERROR,
"Error configuring filter graph\n");
2146 if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
2150 const char *desc = NULL;
2154 switch (enc->codec_type) {
2155 case AVMEDIA_TYPE_AUDIO:
2158 case AVMEDIA_TYPE_VIDEO:
2167 av_packet_unref(
pkt);
2168 while ((
ret = avcodec_receive_packet(enc,
pkt)) == AVERROR(EAGAIN)) {
2169 ret = avcodec_send_frame(enc, NULL);
2171 av_log(NULL, AV_LOG_FATAL,
"%s encoding failed: %s\n",
2179 if (
ret < 0 &&
ret != AVERROR_EOF) {
2180 av_log(NULL, AV_LOG_FATAL,
"%s encoding failed: %s\n",
2188 if (
ret == AVERROR_EOF) {
2193 av_packet_unref(
pkt);
2197 pkt_size =
pkt->size;
2231 int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q,
ost->
mux_timebase);
2232 AVPacket *opkt =
ost->
pkt;
2234 av_packet_unref(opkt);
2246 int64_t comp_start = start_time;
2249 if (
pkt->pts == AV_NOPTS_VALUE ?
2250 ist->pts < comp_start :
2251 pkt->pts < av_rescale_q(comp_start, AV_TIME_BASE_Q,
ist->st->time_base))
2274 if (
ost->
enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
2277 if (av_packet_ref(opkt,
pkt) < 0)
2280 if (
pkt->pts != AV_NOPTS_VALUE)
2283 if (
pkt->dts == AV_NOPTS_VALUE) {
2285 }
else if (
ost->
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2286 int duration = av_get_audio_frame_duration(
ist->dec_ctx,
pkt->size);
2288 duration =
ist->dec_ctx->frame_size;
2289 opkt->dts = av_rescale_delta(
ist->st->time_base,
pkt->dts,
2290 (AVRational){1, ist->dec_ctx->sample_rate}, duration,
2293 opkt->pts = opkt->dts - ost_tb_start_time;
2296 opkt->dts -= ost_tb_start_time;
2305 AVCodecContext *
dec =
ist->dec_ctx;
2307 if (!
dec->channel_layout) {
2308 char layout_name[256];
2310 if (
dec->channels >
ist->guess_layout_max)
2312 dec->channel_layout = av_get_default_channel_layout(
dec->channels);
2313 if (!
dec->channel_layout)
2315 av_get_channel_layout_string(layout_name,
sizeof(layout_name),
2316 dec->channels,
dec->channel_layout);
2317 av_log(NULL, AV_LOG_WARNING,
"Guessed Channel Layout for Input Stream "
2318 "#%d.%d : %s\n",
ist->file_index,
ist->st->index, layout_name);
2332 if (
ist->decoded_frame->decode_error_flags || (
ist->decoded_frame->flags & AV_FRAME_FLAG_CORRUPT)) {
2334 "%s: corrupt decoded frame in stream %d\n",
input_files[
ist->file_index]->
ctx->url,
ist->st->index);
2356 int need_reinit,
ret, i;
2359 need_reinit = ifilter->
format != frame->format;
2361 switch (ifilter->
ist->
st->codecpar->codec_type) {
2362 case AVMEDIA_TYPE_AUDIO:
2363 need_reinit |= ifilter->
sample_rate != frame->sample_rate ||
2364 ifilter->
channels != frame->channels ||
2367 case AVMEDIA_TYPE_VIDEO:
2368 need_reinit |= ifilter->
width != frame->width ||
2369 ifilter->
height != frame->height;
2387 if (need_reinit || !fg->
graph) {
2390 AVFrame *tmp = av_frame_clone(frame);
2392 return AVERROR(ENOMEM);
2393 av_frame_unref(frame);
2398 av_frame_free(&tmp);
2402 av_fifo_generic_write(ifilter->
frame_queue, &tmp,
sizeof(tmp), NULL);
2408 if (
ret < 0 &&
ret != AVERROR_EOF) {
2409 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(
ret));
2415 av_log(NULL, AV_LOG_ERROR,
"Error reinitializing filters!\n");
2420 ret = av_buffersrc_add_frame_flags(ifilter->
filter, frame, AV_BUFFERSRC_FLAG_PUSH);
2422 if (
ret != AVERROR_EOF)
2423 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(
ret));
2440 ret = av_buffersrc_close(ifilter->
filter,
pts, AV_BUFFERSRC_FLAG_PUSH);
2448 if (ifilter->
format < 0 && (ifilter->
type == AVMEDIA_TYPE_AUDIO || ifilter->
type == AVMEDIA_TYPE_VIDEO)) {
2449 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);
2450 return AVERROR_INVALIDDATA;
2461 static int decode(AVCodecContext *avctx, AVFrame *frame,
int *got_frame, AVPacket *
pkt)
2468 ret = avcodec_send_packet(avctx,
pkt);
2471 if (
ret < 0 &&
ret != AVERROR_EOF)
2475 ret = avcodec_receive_frame(avctx, frame);
2476 if (
ret < 0 &&
ret != AVERROR(EAGAIN))
2489 av_assert1(
ist->nb_filters > 0);
2490 for (i = 0; i <
ist->nb_filters; i++) {
2492 f =
ist->filter_frame;
2499 if (
ret == AVERROR_EOF)
2502 av_log(NULL, AV_LOG_ERROR,
2503 "Failed to inject frame into filter network: %s\n", av_err2str(
ret));
2514 AVCodecContext *avctx =
ist->dec_ctx;
2516 AVRational decoded_frame_tb;
2518 if (!
ist->decoded_frame && !(
ist->decoded_frame = av_frame_alloc()))
2519 return AVERROR(ENOMEM);
2520 if (!
ist->filter_frame && !(
ist->filter_frame = av_frame_alloc()))
2521 return AVERROR(ENOMEM);
2530 if (
ret >= 0 && avctx->sample_rate <= 0) {
2531 av_log(avctx, AV_LOG_ERROR,
"Sample rate %d invalid\n", avctx->sample_rate);
2532 ret = AVERROR_INVALIDDATA;
2535 if (
ret != AVERROR_EOF)
2542 ist->frames_decoded++;
2552 decoded_frame_tb =
ist->st->time_base;
2553 }
else if (
pkt &&
pkt->pts != AV_NOPTS_VALUE) {
2555 decoded_frame_tb =
ist->st->time_base;
2558 decoded_frame_tb = AV_TIME_BASE_Q;
2562 (AVRational){1, avctx->sample_rate},
decoded_frame->nb_samples, &
ist->filter_in_rescale_delta_last,
2563 (AVRational){1, avctx->sample_rate});
2567 av_frame_unref(
ist->filter_frame);
2569 return err < 0 ? err :
ret;
2576 int i,
ret = 0, err = 0;
2577 int64_t best_effort_timestamp;
2578 int64_t
dts = AV_NOPTS_VALUE;
2583 if (!eof &&
pkt &&
pkt->size == 0)
2586 if (!
ist->decoded_frame && !(
ist->decoded_frame = av_frame_alloc()))
2587 return AVERROR(ENOMEM);
2588 if (!
ist->filter_frame && !(
ist->filter_frame = av_frame_alloc()))
2589 return AVERROR(ENOMEM);
2591 if (
ist->dts != AV_NOPTS_VALUE)
2592 dts = av_rescale_q(
ist->dts, AV_TIME_BASE_Q,
ist->st->time_base);
2600 void *
new = av_realloc_array(
ist->dts_buffer,
ist->nb_dts_buffer + 1,
sizeof(
ist->dts_buffer[0]));
2602 return AVERROR(ENOMEM);
2603 ist->dts_buffer =
new;
2604 ist->dts_buffer[
ist->nb_dts_buffer++] =
dts;
2615 if (
ist->st->codecpar->video_delay <
ist->dec_ctx->has_b_frames) {
2616 if (
ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
2617 ist->st->codecpar->video_delay =
ist->dec_ctx->has_b_frames;
2619 av_log(
ist->dec_ctx, AV_LOG_WARNING,
2620 "video_delay is larger in decoder than demuxer %d > %d.\n"
2621 "If you want to help, upload a sample "
2622 "of this file to https://streams.videolan.org/upload/ "
2623 "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n",
2624 ist->dec_ctx->has_b_frames,
2625 ist->st->codecpar->video_delay);
2628 if (
ret != AVERROR_EOF)
2635 av_log(NULL, AV_LOG_DEBUG,
"Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
2639 ist->dec_ctx->width,
2640 ist->dec_ctx->height,
2641 ist->dec_ctx->pix_fmt);
2648 if(
ist->top_field_first>=0)
2651 ist->frames_decoded++;
2660 best_effort_timestamp=
decoded_frame->best_effort_timestamp;
2663 if (
ist->framerate.num)
2664 best_effort_timestamp =
ist->cfr_next_pts++;
2666 if (eof && best_effort_timestamp == AV_NOPTS_VALUE &&
ist->nb_dts_buffer > 0) {
2667 best_effort_timestamp =
ist->dts_buffer[0];
2669 for (i = 0; i <
ist->nb_dts_buffer - 1; i++)
2670 ist->dts_buffer[i] =
ist->dts_buffer[i + 1];
2671 ist->nb_dts_buffer--;
2674 if(best_effort_timestamp != AV_NOPTS_VALUE) {
2675 int64_t ts = av_rescale_q(
decoded_frame->pts = best_effort_timestamp,
ist->st->time_base, AV_TIME_BASE_Q);
2677 if (ts != AV_NOPTS_VALUE)
2678 ist->next_pts =
ist->pts = ts;
2682 av_log(NULL, AV_LOG_INFO,
"decoder -> ist_index:%d type:video "
2683 "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",
2686 best_effort_timestamp,
2687 av_ts2timestr(best_effort_timestamp, &
ist->st->time_base),
2689 ist->st->time_base.num,
ist->st->time_base.den);
2692 if (
ist->st->sample_aspect_ratio.num)
2698 av_frame_unref(
ist->filter_frame);
2700 return err < 0 ? err :
ret;
2708 int i,
ret = avcodec_decode_subtitle2(
ist->dec_ctx,
2720 if (
ist->fix_sub_duration) {
2722 if (
ist->prev_sub.got_output) {
2723 end = av_rescale(
subtitle.pts -
ist->prev_sub.subtitle.pts,
2724 1000, AV_TIME_BASE);
2725 if (end < ist->
prev_sub.subtitle.end_display_time) {
2726 av_log(
ist->dec_ctx, AV_LOG_DEBUG,
2727 "Subtitle duration reduced from %"PRId32
" to %d%s\n",
2728 ist->prev_sub.subtitle.end_display_time, end,
2729 end <= 0 ?
", dropping it" :
"");
2730 ist->prev_sub.subtitle.end_display_time = end;
2734 FFSWAP(
int,
ret,
ist->prev_sub.ret);
2735 FFSWAP(AVSubtitle,
subtitle,
ist->prev_sub.subtitle);
2743 if (
ist->sub2video.frame) {
2745 }
else if (
ist->nb_filters) {
2746 if (!
ist->sub2video.sub_queue)
2747 ist->sub2video.sub_queue = av_fifo_alloc(8 *
sizeof(AVSubtitle));
2748 if (!
ist->sub2video.sub_queue)
2750 if (!av_fifo_space(
ist->sub2video.sub_queue)) {
2751 ret = av_fifo_realloc2(
ist->sub2video.sub_queue, 2 * av_fifo_size(
ist->sub2video.sub_queue));
2762 ist->frames_decoded++;
2770 ||
ost->
enc->type != AVMEDIA_TYPE_SUBTITLE)
2786 int64_t
pts = av_rescale_q_rnd(
ist->pts, AV_TIME_BASE_Q,
ist->st->time_base,
2787 AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
2789 for (i = 0; i <
ist->nb_filters; i++) {
2802 int eof_reached = 0;
2806 if (!
ist->pkt && !(
ist->pkt = av_packet_alloc()))
2807 return AVERROR(ENOMEM);
2810 if (!
ist->saw_first_ts) {
2812 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;
2814 if (
pkt &&
pkt->pts != AV_NOPTS_VALUE && !
ist->decoding_needed) {
2816 ist->dts += av_rescale_q(
pkt->pts,
ist->st->time_base, AV_TIME_BASE_Q);
2819 ist->saw_first_ts = 1;
2822 if (
ist->next_dts == AV_NOPTS_VALUE)
2823 ist->next_dts =
ist->dts;
2824 if (
ist->next_pts == AV_NOPTS_VALUE)
2825 ist->next_pts =
ist->pts;
2828 av_packet_unref(avpkt);
2829 ret = av_packet_ref(avpkt,
pkt);
2834 if (
pkt &&
pkt->dts != AV_NOPTS_VALUE) {
2835 ist->next_dts =
ist->dts = av_rescale_q(
pkt->dts,
ist->st->time_base, AV_TIME_BASE_Q);
2836 if (
ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !
ist->decoding_needed)
2841 while (
ist->decoding_needed) {
2842 int64_t duration_dts = 0;
2843 int64_t duration_pts = 0;
2845 int decode_failed = 0;
2847 ist->pts =
ist->next_pts;
2848 ist->dts =
ist->next_dts;
2850 switch (
ist->dec_ctx->codec_type) {
2851 case AVMEDIA_TYPE_AUDIO:
2854 av_packet_unref(avpkt);
2856 case AVMEDIA_TYPE_VIDEO:
2860 if (
pkt &&
pkt->duration) {
2861 duration_dts = av_rescale_q(
pkt->duration,
ist->st->time_base, AV_TIME_BASE_Q);
2862 }
else if(
ist->dec_ctx->framerate.num != 0 &&
ist->dec_ctx->framerate.den != 0) {
2863 int ticks= av_stream_get_parser(
ist->st) ? av_stream_get_parser(
ist->st)->repeat_pict+1 :
ist->dec_ctx->ticks_per_frame;
2864 duration_dts = ((int64_t)AV_TIME_BASE *
2865 ist->dec_ctx->framerate.den * ticks) /
2866 ist->dec_ctx->framerate.num /
ist->dec_ctx->ticks_per_frame;
2869 if(
ist->dts != AV_NOPTS_VALUE && duration_dts) {
2870 ist->next_dts += duration_dts;
2872 ist->next_dts = AV_NOPTS_VALUE;
2876 if (duration_pts > 0) {
2877 ist->next_pts += av_rescale_q(duration_pts,
ist->st->time_base, AV_TIME_BASE_Q);
2879 ist->next_pts += duration_dts;
2882 av_packet_unref(avpkt);
2884 case AVMEDIA_TYPE_SUBTITLE:
2890 av_packet_unref(avpkt);
2896 if (
ret == AVERROR_EOF) {
2902 if (decode_failed) {
2903 av_log(NULL, AV_LOG_ERROR,
"Error while decoding stream #%d:%d: %s\n",
2904 ist->file_index,
ist->st->index, av_err2str(
ret));
2906 av_log(NULL, AV_LOG_FATAL,
"Error while processing the decoded "
2907 "data for stream #%d:%d\n",
ist->file_index,
ist->st->index);
2915 ist->got_output = 1;
2936 if (!
pkt &&
ist->decoding_needed && eof_reached && !no_eof) {
2939 av_log(NULL, AV_LOG_FATAL,
"Error marking filters as finished\n");
2945 if (!
ist->decoding_needed &&
pkt) {
2946 ist->dts =
ist->next_dts;
2947 switch (
ist->dec_ctx->codec_type) {
2948 case AVMEDIA_TYPE_AUDIO:
2949 av_assert1(
pkt->duration >= 0);
2950 if (
ist->dec_ctx->sample_rate) {
2951 ist->next_dts += ((int64_t)AV_TIME_BASE *
ist->dec_ctx->frame_size) /
2952 ist->dec_ctx->sample_rate;
2954 ist->next_dts += av_rescale_q(
pkt->duration,
ist->st->time_base, AV_TIME_BASE_Q);
2957 case AVMEDIA_TYPE_VIDEO:
2958 if (
ist->framerate.num) {
2960 AVRational time_base_q = AV_TIME_BASE_Q;
2961 int64_t
next_dts = av_rescale_q(
ist->next_dts, time_base_q, av_inv_q(
ist->framerate));
2962 ist->next_dts = av_rescale_q(
next_dts + 1, av_inv_q(
ist->framerate), time_base_q);
2963 }
else if (
pkt->duration) {
2964 ist->next_dts += av_rescale_q(
pkt->duration,
ist->st->time_base, AV_TIME_BASE_Q);
2965 }
else if(
ist->dec_ctx->framerate.num != 0) {
2966 int ticks= av_stream_get_parser(
ist->st) ? av_stream_get_parser(
ist->st)->repeat_pict + 1 :
ist->dec_ctx->ticks_per_frame;
2967 ist->next_dts += ((int64_t)AV_TIME_BASE *
2968 ist->dec_ctx->framerate.den * ticks) /
2969 ist->dec_ctx->framerate.num /
ist->dec_ctx->ticks_per_frame;
2974 ist->next_pts =
ist->next_dts;
2987 return !eof_reached;
2995 AVIOContext *sdp_pb;
2996 AVFormatContext **avc;
3007 if (!strcmp(
output_files[i]->ctx->oformat->name,
"rtp")) {
3016 av_sdp_create(avc, j, sdp,
sizeof(sdp));
3023 av_log(NULL, AV_LOG_ERROR,
"Failed to open sdp file '%s'\n",
sdp_filename);
3025 avio_print(sdp_pb, sdp);
3026 avio_closep(&sdp_pb);
3035 static enum AVPixelFormat
get_format(AVCodecContext *s,
const enum AVPixelFormat *pix_fmts)
3038 const enum AVPixelFormat *p;
3041 for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
3042 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
3043 const AVCodecHWConfig *config = NULL;
3046 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
3052 config = avcodec_get_hw_config(s->codec, i);
3055 if (!(config->methods &
3056 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
3058 if (config->pix_fmt == *p)
3063 if (config->device_type !=
ist->hwaccel_device_type) {
3071 av_log(NULL, AV_LOG_FATAL,
3072 "%s hwaccel requested for input stream #%d:%d, "
3073 "but cannot be initialized.\n",
3074 av_hwdevice_get_type_name(config->device_type),
3075 ist->file_index,
ist->st->index);
3076 return AV_PIX_FMT_NONE;
3081 const HWAccel *hwaccel = NULL;
3093 if (hwaccel->
id !=
ist->hwaccel_id) {
3100 av_log(NULL, AV_LOG_FATAL,
3101 "%s hwaccel requested for input stream #%d:%d, "
3102 "but cannot be initialized.\n", hwaccel->
name,
3103 ist->file_index,
ist->st->index);
3104 return AV_PIX_FMT_NONE;
3108 if (
ist->hw_frames_ctx) {
3109 s->hw_frames_ctx = av_buffer_ref(
ist->hw_frames_ctx);
3110 if (!s->hw_frames_ctx)
3111 return AV_PIX_FMT_NONE;
3114 ist->hwaccel_pix_fmt = *p;
3121 static int get_buffer(AVCodecContext *s, AVFrame *frame,
int flags)
3125 if (
ist->hwaccel_get_buffer && frame->format ==
ist->hwaccel_pix_fmt)
3126 return ist->hwaccel_get_buffer(s, frame, flags);
3128 return avcodec_default_get_buffer2(s, frame, flags);
3136 if (
ist->decoding_needed) {
3137 const AVCodec *codec =
ist->dec;
3139 snprintf(error, error_len,
"Decoder (codec %s) not found for input stream #%d:%d",
3140 avcodec_get_name(
ist->dec_ctx->codec_id),
ist->file_index,
ist->st->index);
3141 return AVERROR(EINVAL);
3144 ist->dec_ctx->opaque =
ist;
3147 #if LIBAVCODEC_VERSION_MAJOR < 60
3148 FF_DISABLE_DEPRECATION_WARNINGS
3149 ist->dec_ctx->thread_safe_callbacks = 1;
3150 FF_ENABLE_DEPRECATION_WARNINGS
3153 if (
ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
3155 av_dict_set(&
ist->decoder_opts,
"compute_edt",
"1", AV_DICT_DONT_OVERWRITE);
3157 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");
3160 av_dict_set(&
ist->decoder_opts,
"sub_text_format",
"ass", AV_DICT_DONT_OVERWRITE);
3164 ist->dec_ctx->pkt_timebase =
ist->st->time_base;
3166 if (!av_dict_get(
ist->decoder_opts,
"threads", NULL, 0))
3167 av_dict_set(&
ist->decoder_opts,
"threads",
"auto", 0);
3169 if (
ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3170 av_dict_set(&
ist->decoder_opts,
"threads",
"1", 0);
3174 snprintf(error, error_len,
"Device setup failed for "
3175 "decoder on input stream #%d:%d : %s",
3176 ist->file_index,
ist->st->index, av_err2str(
ret));
3180 if ((
ret = avcodec_open2(
ist->dec_ctx, codec, &
ist->decoder_opts)) < 0) {
3181 if (
ret == AVERROR_EXPERIMENTAL)
3184 snprintf(error, error_len,
3185 "Error while opening decoder for input stream "
3187 ist->file_index,
ist->st->index, av_err2str(
ret));
3193 ist->next_pts = AV_NOPTS_VALUE;
3194 ist->next_dts = AV_NOPTS_VALUE;
3208 return FFDIFFSIGN(*(
const int64_t *)a, *(
const int64_t *)b);
3216 for (i = 0; i < of->
ctx->nb_streams; i++) {
3224 ret = avformat_write_header(of->
ctx, &of->
opts);
3226 av_log(NULL, AV_LOG_ERROR,
3227 "Could not write header for output file #%d "
3228 "(incorrect codec parameters ?): %s\n",
3242 for (i = 0; i < of->
ctx->nb_streams; i++) {
3254 av_packet_free(&
pkt);
3269 ret = avcodec_parameters_copy(ctx->par_in,
ost->
st->codecpar);
3273 ctx->time_base_in =
ost->
st->time_base;
3275 ret = av_bsf_init(ctx);
3277 av_log(NULL, AV_LOG_ERROR,
"Error initializing bitstream filter: %s\n",
3282 ret = avcodec_parameters_copy(
ost->
st->codecpar, ctx->par_out);
3286 ost->
st->time_base = ctx->time_base_out;
3295 AVCodecParameters *par_dst =
ost->
st->codecpar;
3299 uint32_t codec_tag = par_dst->codec_tag;
3307 av_log(NULL, AV_LOG_FATAL,
3308 "Error setting up codec context options.\n");
3312 ret = avcodec_parameters_from_context(par_src,
ost->
enc_ctx);
3314 av_log(NULL, AV_LOG_FATAL,
3315 "Error getting reference codec parameters.\n");
3320 unsigned int codec_tag_tmp;
3321 if (!of->
ctx->oformat->codec_tag ||
3322 av_codec_get_id (of->
ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
3323 !av_codec_get_tag2(of->
ctx->oformat->codec_tag, par_src->codec_id, &codec_tag_tmp))
3324 codec_tag = par_src->codec_tag;
3327 ret = avcodec_parameters_copy(par_dst, par_src);
3331 par_dst->codec_tag = codec_tag;
3339 ost->
st->avg_frame_rate =
ist->st->avg_frame_rate;
3346 if (
ost->
st->time_base.num <= 0 ||
ost->
st->time_base.den <= 0) {
3350 ost->
st->time_base = av_add_q(av_stream_get_codec_timebase(
ost->
st), (AVRational){0, 1});
3354 if (
ost->
st->duration <= 0 &&
ist->st->duration > 0)
3355 ost->
st->duration = av_rescale_q(
ist->st->duration,
ist->st->time_base,
ost->
st->time_base);
3358 ost->
st->disposition =
ist->st->disposition;
3360 if (
ist->st->nb_side_data) {
3361 for (i = 0; i <
ist->st->nb_side_data; i++) {
3362 const AVPacketSideData *sd_src = &
ist->st->side_data[i];
3365 dst_data = av_stream_new_side_data(
ost->
st, sd_src->type, sd_src->size);
3367 return AVERROR(ENOMEM);
3368 memcpy(dst_data, sd_src->data, sd_src->size);
3373 uint8_t *sd = av_stream_new_side_data(
ost->
st, AV_PKT_DATA_DISPLAYMATRIX,
3374 sizeof(int32_t) * 9);
3379 switch (par_dst->codec_type) {
3380 case AVMEDIA_TYPE_AUDIO:
3382 av_log(NULL, AV_LOG_FATAL,
"-acodec copy and -vol are incompatible (frames are not decoded)\n");
3385 if((par_dst->block_align == 1 || par_dst->block_align == 1152 || par_dst->block_align == 576) && par_dst->codec_id == AV_CODEC_ID_MP3)
3386 par_dst->block_align= 0;
3387 if(par_dst->codec_id == AV_CODEC_ID_AC3)
3388 par_dst->block_align= 0;
3390 case AVMEDIA_TYPE_VIDEO:
3394 (AVRational){ par_dst->height, par_dst->width });
3395 av_log(NULL, AV_LOG_WARNING,
"Overriding aspect ratio "
3396 "with stream copy may produce invalid files\n");
3398 else if (
ist->st->sample_aspect_ratio.num)
3399 sar =
ist->st->sample_aspect_ratio;
3401 sar = par_src->sample_aspect_ratio;
3402 ost->
st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
3403 ost->
st->avg_frame_rate =
ist->st->avg_frame_rate;
3404 ost->
st->r_frame_rate =
ist->st->r_frame_rate;
3415 AVDictionaryEntry *e;
3417 uint8_t *encoder_string;
3418 int encoder_string_len;
3419 int format_flags = 0;
3422 if (av_dict_get(
ost->
st->metadata,
"encoder", NULL, 0))
3425 e = av_dict_get(of->
opts,
"fflags", NULL, 0);
3427 const AVOption *o = av_opt_find(of->
ctx,
"fflags", NULL, 0, 0);
3430 av_opt_eval_flags(of->
ctx, o, e->value, &format_flags);
3434 const AVOption *o = av_opt_find(
ost->
enc_ctx,
"flags", NULL, 0, 0);
3437 av_opt_eval_flags(
ost->
enc_ctx, o, e->value, &codec_flags);
3440 encoder_string_len =
sizeof(LIBAVCODEC_IDENT) + strlen(
ost->
enc->name) + 2;
3441 encoder_string = av_mallocz(encoder_string_len);
3442 if (!encoder_string)
3445 if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & AV_CODEC_FLAG_BITEXACT))
3446 av_strlcpy(encoder_string, LIBAVCODEC_IDENT
" ", encoder_string_len);
3448 av_strlcpy(encoder_string,
"Lavc ", encoder_string_len);
3449 av_strlcat(encoder_string,
ost->
enc->name, encoder_string_len);
3450 av_dict_set(&
ost->
st->metadata,
"encoder", encoder_string,
3451 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
3455 AVCodecContext *avctx)
3458 int n = 1, i, size,
index = 0;
3461 for (p = kf; *p; p++)
3465 pts = av_malloc_array(size,
sizeof(*
pts));
3467 av_log(NULL, AV_LOG_FATAL,
"Could not allocate forced key frames array.\n");
3472 for (i = 0; i < n; i++) {
3473 char *next = strchr(p,
',');
3478 if (!memcmp(p,
"chapters", 8)) {
3483 if (avf->nb_chapters > INT_MAX - size ||
3484 !(
pts = av_realloc_f(
pts, size += avf->nb_chapters - 1,
3486 av_log(NULL, AV_LOG_FATAL,
3487 "Could not allocate forced key frames array.\n");
3491 t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3493 for (j = 0; j < avf->nb_chapters; j++) {
3494 AVChapter *c = avf->chapters[j];
3495 av_assert1(
index < size);
3496 pts[
index++] = av_rescale_q(c->start, c->time_base,
3497 avctx->time_base) + t;
3503 av_assert1(
index < size);
3504 pts[
index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3511 av_assert0(
index == size);
3521 AVFormatContext *oc;
3530 enc_ctx->time_base =
ist->st->time_base;
3535 av_log(oc, AV_LOG_WARNING,
"Input stream data not available, using default time base\n");
3538 enc_ctx->time_base = default_time_base;
3545 AVCodecContext *
dec_ctx = NULL;
3554 av_dict_set(&
ost->
st->metadata,
"rotate", NULL, 0);
3557 ost->
st->disposition =
ist->st->disposition;
3561 enc_ctx->chroma_sample_location =
dec_ctx->chroma_sample_location;
3563 for (j = 0; j < oc->nb_streams; j++) {
3564 AVStream *
st = oc->streams[j];
3565 if (
st !=
ost->
st &&
st->codecpar->codec_type ==
ost->
st->codecpar->codec_type)
3568 if (j == oc->nb_streams)
3569 if (
ost->
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
3570 ost->
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
3571 ost->
st->disposition = AV_DISPOSITION_DEFAULT;
3574 if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3583 av_log(NULL, AV_LOG_WARNING,
3585 "about the input framerate is available. Falling "
3586 "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
3587 "if you want a different framerate.\n",
3601 if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
3607 switch (enc_ctx->codec_type) {
3608 case AVMEDIA_TYPE_AUDIO:
3611 enc_ctx->bits_per_raw_sample = FFMIN(
dec_ctx->bits_per_raw_sample,
3612 av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
3613 enc_ctx->sample_rate = av_buffersink_get_sample_rate(
ost->
filter->
filter);
3614 enc_ctx->channel_layout = av_buffersink_get_channel_layout(
ost->
filter->
filter);
3620 case AVMEDIA_TYPE_VIDEO:
3623 if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
3624 enc_ctx->time_base = av_buffersink_get_time_base(
ost->
filter->
filter);
3627 av_log(oc, AV_LOG_WARNING,
"Frame rate very high for a muxer not efficiently supporting it.\n"
3628 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3633 enc_ctx->sample_aspect_ratio =
ost->
st->sample_aspect_ratio =
3640 enc_ctx->bits_per_raw_sample = FFMIN(
dec_ctx->bits_per_raw_sample,
3641 av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
3644 enc_ctx->color_range = frame->color_range;
3645 enc_ctx->color_primaries = frame->color_primaries;
3646 enc_ctx->color_trc = frame->color_trc;
3647 enc_ctx->colorspace = frame->colorspace;
3648 enc_ctx->chroma_sample_location = frame->chroma_location;
3656 enc_ctx->width !=
dec_ctx->width ||
3657 enc_ctx->height !=
dec_ctx->height ||
3658 enc_ctx->pix_fmt !=
dec_ctx->pix_fmt) {
3664 if (enc_ctx->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
3668 if (frame->interlaced_frame) {
3669 if (enc_ctx->codec->id == AV_CODEC_ID_MJPEG)
3670 enc_ctx->field_order = frame->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
3672 enc_ctx->field_order = frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
3674 enc_ctx->field_order = AV_FIELD_PROGRESSIVE;
3679 enc_ctx->field_order = AV_FIELD_BB;
3681 enc_ctx->field_order = AV_FIELD_TT;
3689 av_log(NULL, AV_LOG_ERROR,
3705 case AVMEDIA_TYPE_SUBTITLE:
3706 enc_ctx->time_base = AV_TIME_BASE_Q;
3707 if (!enc_ctx->width) {
3712 case AVMEDIA_TYPE_DATA:
3729 const AVCodec *codec =
ost->
enc;
3730 AVCodecContext *
dec = NULL;
3739 if (
dec &&
dec->subtitle_header) {
3741 ost->
enc_ctx->subtitle_header = av_mallocz(
dec->subtitle_header_size + 1);
3743 return AVERROR(ENOMEM);
3744 memcpy(
ost->
enc_ctx->subtitle_header,
dec->subtitle_header,
dec->subtitle_header_size);
3745 ost->
enc_ctx->subtitle_header_size =
dec->subtitle_header_size;
3749 if (
ost->
enc->type == AVMEDIA_TYPE_AUDIO &&
3757 snprintf(error, error_len,
"Device setup failed for "
3758 "encoder on output stream #%d:%d : %s",
3763 if (
ist &&
ist->dec->type == AVMEDIA_TYPE_SUBTITLE &&
ost->
enc->type == AVMEDIA_TYPE_SUBTITLE) {
3764 int input_props = 0, output_props = 0;
3765 AVCodecDescriptor
const *input_descriptor =
3766 avcodec_descriptor_get(
dec->codec_id);
3767 AVCodecDescriptor
const *output_descriptor =
3768 avcodec_descriptor_get(
ost->
enc_ctx->codec_id);
3769 if (input_descriptor)
3770 input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3771 if (output_descriptor)
3772 output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3773 if (input_props && output_props && input_props != output_props) {
3774 snprintf(error, error_len,
3775 "Subtitle encoding currently only possible from text to text "
3776 "or bitmap to bitmap");
3777 return AVERROR_INVALIDDATA;
3782 if (
ret == AVERROR_EXPERIMENTAL)
3784 snprintf(error, error_len,
3785 "Error while opening encoder for output stream #%d:%d - "
3786 "maybe incorrect parameters such as bit_rate, rate, width or height",
3790 if (
ost->
enc->type == AVMEDIA_TYPE_AUDIO &&
3791 !(
ost->
enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
3796 ost->
enc_ctx->codec_id != AV_CODEC_ID_CODEC2 )
3797 av_log(NULL, AV_LOG_WARNING,
"The bitrate parameter is set too low."
3798 " It takes bits/s as argument, not kbits/s\n");
3802 av_log(NULL, AV_LOG_FATAL,
3803 "Error initializing the output stream codec context.\n");
3810 for (i = 0; i <
ost->
enc_ctx->nb_coded_side_data; i++) {
3811 const AVPacketSideData *sd_src = &
ost->
enc_ctx->coded_side_data[i];
3814 dst_data = av_stream_new_side_data(
ost->
st, sd_src->type, sd_src->size);
3816 return AVERROR(ENOMEM);
3817 memcpy(dst_data, sd_src->data, sd_src->size);
3830 for (i = 0; i <
ist->st->nb_side_data; i++) {
3831 AVPacketSideData *sd = &
ist->st->side_data[i];
3832 if (sd->type != AV_PKT_DATA_CPB_PROPERTIES) {
3833 uint8_t *dst = av_stream_new_side_data(
ost->
st, sd->type, sd->size);
3835 return AVERROR(ENOMEM);
3836 memcpy(dst, sd->data, sd->size);
3837 if (
ist->autorotate && sd->type == AV_PKT_DATA_DISPLAYMATRIX)
3838 av_display_rotation_set((uint32_t *)dst, 0);
3844 if (
ost->
st->time_base.num <= 0 ||
ost->
st->time_base.den <= 0)
3845 ost->
st->time_base = av_add_q(
ost->
enc_ctx->time_base, (AVRational){0, 1});
3848 if (
ost->
st->duration <= 0 &&
ist &&
ist->st->duration > 0)
3849 ost->
st->duration = av_rescale_q(
ist->st->duration,
ist->st->time_base,
ost->
st->time_base);
3858 static const AVOption opts[] = {
3859 {
"disposition" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, (double)INT64_MAX, .unit =
"flags" },
3860 {
"default" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT }, .unit =
"flags" },
3861 {
"dub" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB }, .unit =
"flags" },
3862 {
"original" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL }, .unit =
"flags" },
3863 {
"comment" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT }, .unit =
"flags" },
3864 {
"lyrics" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS }, .unit =
"flags" },
3865 {
"karaoke" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE }, .unit =
"flags" },
3866 {
"forced" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED }, .unit =
"flags" },
3867 {
"hearing_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED }, .unit =
"flags" },
3868 {
"visual_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED }, .unit =
"flags" },
3869 {
"clean_effects" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS }, .unit =
"flags" },
3870 {
"attached_pic" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ATTACHED_PIC }, .unit =
"flags" },
3871 {
"captions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS }, .unit =
"flags" },
3872 {
"descriptions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS }, .unit =
"flags" },
3873 {
"dependent" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEPENDENT }, .unit =
"flags" },
3874 {
"metadata" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA }, .unit =
"flags" },
3877 static const AVClass
class = {
3879 .item_name = av_default_item_name,
3881 .version = LIBAVUTIL_VERSION_INT,
3883 const AVClass *pclass = &
class;
3909 AVStream *st = file->
ctx->streams[pkt->stream_index];
3913 av_log(file->
ctx, AV_LOG_WARNING,
3914 "New %s stream %d:%d at pos:%"PRId64
" and DTS:%ss\n",
3915 av_get_media_type_string(st->codecpar->codec_type),
3916 input_index, pkt->stream_index,
3917 pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
3923 int ret = 0, i, j, k;
3924 AVFormatContext *oc;
3927 char error[1024] = {0};
3985 for (j = 0; j < ifile->
ctx->nb_programs; j++) {
3986 AVProgram *p = ifile->
ctx->programs[j];
3987 int discard = AVDISCARD_ALL;
3989 for (k = 0; k < p->nb_stream_indexes; k++)
3991 discard = AVDISCARD_DEFAULT;
3994 p->discard = discard;
4001 if (oc->oformat->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
4010 av_log(NULL, AV_LOG_INFO,
"Stream mapping:\n");
4014 for (j = 0; j <
ist->nb_filters; j++) {
4016 av_log(NULL, AV_LOG_INFO,
" Stream #%d:%d (%s) -> %s",
4017 ist->file_index,
ist->st->index,
ist->dec ?
ist->dec->name :
"?",
4018 ist->filters[j]->name);
4020 av_log(NULL, AV_LOG_INFO,
" (graph %d)",
ist->filters[j]->graph->index);
4021 av_log(NULL, AV_LOG_INFO,
"\n");
4031 av_log(NULL, AV_LOG_INFO,
" File %s -> Stream #%d:%d\n",
4042 av_log(NULL, AV_LOG_INFO,
" -> Stream #%d:%d (%s)\n",
ost->
file_index,
4047 av_log(NULL, AV_LOG_INFO,
" Stream #%d:%d -> #%d:%d",
4053 av_log(NULL, AV_LOG_INFO,
" [sync #%d:%d]",
4057 av_log(NULL, AV_LOG_INFO,
" (copy)");
4060 const AVCodec *out_codec =
ost->
enc;
4061 const char *decoder_name =
"?";
4062 const char *in_codec_name =
"?";
4063 const char *encoder_name =
"?";
4064 const char *out_codec_name =
"?";
4065 const AVCodecDescriptor *desc;
4068 decoder_name = in_codec->name;
4069 desc = avcodec_descriptor_get(in_codec->id);
4071 in_codec_name = desc->name;
4072 if (!strcmp(decoder_name, in_codec_name))
4073 decoder_name =
"native";
4077 encoder_name = out_codec->name;
4078 desc = avcodec_descriptor_get(out_codec->id);
4080 out_codec_name = desc->name;
4081 if (!strcmp(encoder_name, out_codec_name))
4082 encoder_name =
"native";
4085 av_log(NULL, AV_LOG_INFO,
" (%s (%s) -> %s (%s))",
4086 in_codec_name, decoder_name,
4087 out_codec_name, encoder_name);
4089 av_log(NULL, AV_LOG_INFO,
"\n");
4093 av_log(NULL, AV_LOG_ERROR,
"%s\n", error);
4117 for (j = 0; j < of->
ctx->nb_streams; j++)
4136 int64_t opts_min = INT64_MAX;
4145 av_log(NULL, AV_LOG_DEBUG,
4146 "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",
4164 if (tcgetattr(0, &tty) == 0) {
4165 if (on) tty.c_lflag |= ECHO;
4166 else tty.c_lflag &= ~ECHO;
4167 tcsetattr(0, TCSANOW, &tty);
4176 return AVERROR_EXIT;
4184 return AVERROR_EXIT;
4185 if (key ==
'+') av_log_set_level(av_log_get_level()+10);
4186 if (key ==
'-') av_log_set_level(av_log_get_level()-10);
4195 av_log_set_level(AV_LOG_DEBUG);
4197 if (key ==
'c' || key ==
'C'){
4198 char buf[4096], target[64], command[256], arg[256] = {0};
4201 fprintf(stderr,
"\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
4204 while ((k =
read_key()) !=
'\n' && k !=
'\r' && i <
sizeof(buf)-1)
4209 fprintf(stderr,
"\n");
4211 (n = sscanf(buf,
"%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
4212 av_log(NULL, AV_LOG_DEBUG,
"Processing command target:%s time:%f command:%s arg:%s",
4213 target, time, command, arg);
4218 ret = avfilter_graph_send_command(fg->
graph, target, command, arg, buf,
sizeof(buf),
4219 key ==
'c' ? AVFILTER_CMD_FLAG_ONE : 0);
4220 fprintf(stderr,
"Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
4221 }
else if (key ==
'c') {
4222 fprintf(stderr,
"Queuing commands only on filters supporting the specific command is unsupported\n");
4223 ret = AVERROR_PATCHWELCOME;
4225 ret = avfilter_graph_queue_command(fg->
graph, target, command, arg, 0, time);
4227 fprintf(stderr,
"Queuing command failed with error %s\n", av_err2str(ret));
4232 av_log(NULL, AV_LOG_ERROR,
4233 "Parse error, at least 3 arguments were expected, "
4234 "only %d given in string '%s'\n", n, buf);
4237 if (key ==
'd' || key ==
'D'){
4241 if(!debug) debug = 1;
4242 while (debug & FF_DEBUG_DCT_COEFF)
4249 while ((k =
read_key()) !=
'\n' && k !=
'\r' && i <
sizeof(buf)-1)
4254 fprintf(stderr,
"\n");
4255 if (k <= 0 || sscanf(buf,
"%d", &debug)!=1)
4256 fprintf(stderr,
"error parsing debug value\n");
4265 if(debug) av_log_set_level(AV_LOG_DEBUG);
4266 fprintf(stderr,
"debug=%d\n", debug);
4269 fprintf(stderr,
"key function\n"
4270 "? show this help\n"
4271 "+ increase verbosity\n"
4272 "- decrease verbosity\n"
4273 "c Send command to first matching filter supporting it\n"
4274 "C Send/Queue command to all matching filters\n"
4275 "D cycle through available debug modes\n"
4276 "h dump packets/hex press to cycle through the 3 states\n"
4278 "s Show QP histogram\n"
4285 static void *input_thread(
void *arg)
4288 AVPacket *pkt = f->
pkt, *queue_pkt;
4289 unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
4293 ret = av_read_frame(f->
ctx, pkt);
4295 if (ret == AVERROR(EAGAIN)) {
4300 av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
4303 queue_pkt = av_packet_alloc();
4305 av_packet_unref(pkt);
4306 av_thread_message_queue_set_err_recv(f->in_thread_queue, AVERROR(ENOMEM));
4309 av_packet_move_ref(queue_pkt, pkt);
4310 ret = av_thread_message_queue_send(f->in_thread_queue, &queue_pkt, flags);
4311 if (flags && ret == AVERROR(EAGAIN)) {
4313 ret = av_thread_message_queue_send(f->in_thread_queue, &queue_pkt, flags);
4314 av_log(f->
ctx, AV_LOG_WARNING,
4315 "Thread message queue blocking; consider raising the "
4316 "thread_queue_size option (current value: %d)\n",
4317 f->thread_queue_size);
4320 if (ret != AVERROR_EOF)
4321 av_log(f->
ctx, AV_LOG_ERROR,
4322 "Unable to send packet to main thread: %s\n",
4324 av_packet_free(&queue_pkt);
4325 av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
4333 static void free_input_thread(
int i)
4338 if (!f || !f->in_thread_queue)
4340 av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
4341 while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
4342 av_packet_free(&pkt);
4344 pthread_join(f->thread, NULL);
4346 av_thread_message_queue_free(&f->in_thread_queue);
4349 static void free_input_threads(
void)
4354 free_input_thread(i);
4357 static int init_input_thread(
int i)
4362 if (f->thread_queue_size < 0)
4364 if (!f->thread_queue_size)
4367 if (f->
ctx->pb ? !f->
ctx->pb->seekable :
4368 strcmp(f->
ctx->iformat->name,
"lavfi"))
4369 f->non_blocking = 1;
4370 ret = av_thread_message_queue_alloc(&f->in_thread_queue,
4371 f->thread_queue_size,
sizeof(f->
pkt));
4375 if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
4376 av_log(NULL, AV_LOG_ERROR,
"pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
4377 av_thread_message_queue_free(&f->in_thread_queue);
4378 return AVERROR(ret);
4384 static int init_input_threads(
void)
4389 ret = init_input_thread(i);
4396 static int get_input_packet_mt(
InputFile *f, AVPacket **pkt)
4398 return av_thread_message_queue_recv(f->in_thread_queue, pkt,
4400 AV_THREAD_MESSAGE_NONBLOCK : 0);
4408 int64_t file_start =
copy_ts * (
4415 int64_t stream_ts_offset, pts, now;
4416 if (!
ist->nb_packets || (
ist->decoding_needed && !
ist->got_output))
continue;
4417 stream_ts_offset = FFMAX(
ist->first_dts != AV_NOPTS_VALUE ?
ist->first_dts : 0, file_start);
4418 pts = av_rescale(
ist->dts, 1000000, AV_TIME_BASE);
4419 now = (av_gettime_relative() -
ist->start) * scale + stream_ts_offset;
4421 return AVERROR(EAGAIN);
4426 if (f->thread_queue_size)
4427 return get_input_packet_mt(f, pkt);
4430 return av_read_frame(f->
ctx, *pkt);
4452 static AVRational
duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
4453 AVRational time_base)
4459 return tmp_time_base;
4462 ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
4465 return tmp_time_base;
4474 AVCodecContext *avctx;
4475 int i, ret, has_audio = 0;
4476 int64_t duration = 0;
4478 ret = avformat_seek_file(is, -1, INT64_MIN, is->start_time, is->start_time, 0);
4484 avctx =
ist->dec_ctx;
4489 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
ist->nb_samples)
4495 avctx =
ist->dec_ctx;
4498 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
ist->nb_samples) {
4506 if (
ist->framerate.num) {
4507 duration = av_rescale_q(1, av_inv_q(
ist->framerate),
ist->st->time_base);
4508 }
else if (
ist->st->avg_frame_rate.num) {
4509 duration = av_rescale_q(1, av_inv_q(
ist->st->avg_frame_rate),
ist->st->time_base);
4518 if (
ist->max_pts >
ist->min_pts &&
ist->max_pts - (uint64_t)
ist->min_pts < INT64_MAX - duration)
4519 duration +=
ist->max_pts -
ist->min_pts;
4524 if (ifile->
loop > 0)
4540 AVFormatContext *is;
4543 int ret, thread_ret, i, j;
4546 int disable_discontinuity_correction =
copy_ts;
4551 if (ret == AVERROR(EAGAIN)) {
4555 if (ret < 0 && ifile->loop) {
4556 AVCodecContext *avctx;
4559 avctx =
ist->dec_ctx;
4560 if (
ist->decoding_needed) {
4564 avcodec_flush_buffers(avctx);
4568 free_input_thread(file_index);
4572 thread_ret = init_input_thread(file_index);
4577 av_log(NULL, AV_LOG_WARNING,
"Seek to start failed.\n");
4580 if (ret == AVERROR(EAGAIN)) {
4586 if (ret != AVERROR_EOF) {
4594 if (
ist->decoding_needed) {
4611 return AVERROR(EAGAIN);
4617 av_pkt_dump_log2(NULL, AV_LOG_INFO, pkt,
do_hex_dump,
4618 is->streams[pkt->stream_index]);
4622 if (pkt->stream_index >= ifile->
nb_streams) {
4624 goto discard_packet;
4629 ist->data_size += pkt->size;
4633 goto discard_packet;
4635 if (pkt->flags & AV_PKT_FLAG_CORRUPT) {
4637 "%s: corrupt input packet in stream %d\n", is->url, pkt->stream_index);
4643 av_log(NULL, AV_LOG_INFO,
"demuxer -> ist_index:%d type:%s "
4644 "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",
4645 ifile->
ist_index + pkt->stream_index, av_get_media_type_string(
ist->dec_ctx->codec_type),
4646 av_ts2str(
ist->next_dts), av_ts2timestr(
ist->next_dts, &AV_TIME_BASE_Q),
4647 av_ts2str(
ist->next_pts), av_ts2timestr(
ist->next_pts, &AV_TIME_BASE_Q),
4648 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &
ist->st->time_base),
4649 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &
ist->st->time_base),
4654 if(!
ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE &&
ist->st->pts_wrap_bits < 64){
4655 int64_t stime, stime2;
4659 if (
ist->next_dts == AV_NOPTS_VALUE
4661 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
4662 int64_t new_start_time = INT64_MAX;
4663 for (i=0; i<is->nb_streams; i++) {
4664 AVStream *st = is->streams[i];
4665 if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
4667 new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
4669 if (new_start_time > is->start_time) {
4670 av_log(is, AV_LOG_VERBOSE,
"Correcting start time by %"PRId64
"\n", new_start_time - is->start_time);
4675 stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q,
ist->st->time_base);
4676 stime2= stime + (1ULL<<
ist->st->pts_wrap_bits);
4677 ist->wrap_correction_done = 1;
4679 if(stime2 > stime && pkt->dts != AV_NOPTS_VALUE && pkt->dts > stime + (1LL<<(
ist->st->pts_wrap_bits-1))) {
4680 pkt->dts -= 1ULL<<
ist->st->pts_wrap_bits;
4681 ist->wrap_correction_done = 0;
4683 if(stime2 > stime && pkt->pts != AV_NOPTS_VALUE && pkt->pts > stime + (1LL<<(
ist->st->pts_wrap_bits-1))) {
4684 pkt->pts -= 1ULL<<
ist->st->pts_wrap_bits;
4685 ist->wrap_correction_done = 0;
4690 if (
ist->nb_packets == 1) {
4691 for (i = 0; i <
ist->st->nb_side_data; i++) {
4692 AVPacketSideData *src_sd = &
ist->st->side_data[i];
4695 if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
4698 if (av_packet_get_side_data(pkt, src_sd->type, NULL))
4701 dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
4705 memcpy(dst_data, src_sd->data, src_sd->size);
4709 if (pkt->dts != AV_NOPTS_VALUE)
4710 pkt->dts += av_rescale_q(ifile->
ts_offset, AV_TIME_BASE_Q,
ist->st->time_base);
4711 if (pkt->pts != AV_NOPTS_VALUE)
4712 pkt->pts += av_rescale_q(ifile->
ts_offset, AV_TIME_BASE_Q,
ist->st->time_base);
4714 if (pkt->pts != AV_NOPTS_VALUE)
4715 pkt->pts *=
ist->ts_scale;
4716 if (pkt->dts != AV_NOPTS_VALUE)
4717 pkt->dts *=
ist->ts_scale;
4719 pkt_dts = av_rescale_q_rnd(pkt->dts,
ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4720 if ((
ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
4721 ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
4722 pkt_dts != AV_NOPTS_VALUE &&
ist->next_dts == AV_NOPTS_VALUE && !
copy_ts
4723 && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->
last_ts != AV_NOPTS_VALUE) {
4724 int64_t delta = pkt_dts - ifile->
last_ts;
4728 av_log(NULL, AV_LOG_DEBUG,
4729 "Inter stream timestamp discontinuity %"PRId64
", new offset= %"PRId64
"\n",
4731 pkt->dts -= av_rescale_q(delta, AV_TIME_BASE_Q,
ist->st->time_base);
4732 if (pkt->pts != AV_NOPTS_VALUE)
4733 pkt->pts -= av_rescale_q(delta, AV_TIME_BASE_Q,
ist->st->time_base);
4738 if (pkt->pts != AV_NOPTS_VALUE) {
4739 pkt->pts += duration;
4740 ist->max_pts = FFMAX(pkt->pts,
ist->max_pts);
4741 ist->min_pts = FFMIN(pkt->pts,
ist->min_pts);
4744 if (pkt->dts != AV_NOPTS_VALUE)
4745 pkt->dts += duration;
4747 pkt_dts = av_rescale_q_rnd(pkt->dts,
ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4749 if (
copy_ts && pkt_dts != AV_NOPTS_VALUE &&
ist->next_dts != AV_NOPTS_VALUE &&
4750 (is->iformat->flags & AVFMT_TS_DISCONT) &&
ist->st->pts_wrap_bits < 60) {
4751 int64_t wrap_dts = av_rescale_q_rnd(pkt->dts + (1LL<<
ist->st->pts_wrap_bits),
4752 ist->st->time_base, AV_TIME_BASE_Q,
4753 AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4754 if (FFABS(wrap_dts -
ist->next_dts) < FFABS(pkt_dts -
ist->next_dts)/10)
4755 disable_discontinuity_correction = 0;
4758 if ((
ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
4759 ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
4760 pkt_dts != AV_NOPTS_VALUE &&
ist->next_dts != AV_NOPTS_VALUE &&
4761 !disable_discontinuity_correction) {
4762 int64_t delta = pkt_dts -
ist->next_dts;
4763 if (is->iformat->flags & AVFMT_TS_DISCONT) {
4766 pkt_dts + AV_TIME_BASE/10 < FFMAX(
ist->pts,
ist->dts)) {
4768 av_log(NULL, AV_LOG_DEBUG,
4769 "timestamp discontinuity for stream #%d:%d "
4770 "(id=%d, type=%s): %"PRId64
", new offset= %"PRId64
"\n",
4771 ist->file_index,
ist->st->index,
ist->st->id,
4772 av_get_media_type_string(
ist->dec_ctx->codec_type),
4774 pkt->dts -= av_rescale_q(delta, AV_TIME_BASE_Q,
ist->st->time_base);
4775 if (pkt->pts != AV_NOPTS_VALUE)
4776 pkt->pts -= av_rescale_q(delta, AV_TIME_BASE_Q,
ist->st->time_base);
4781 av_log(NULL, AV_LOG_WARNING,
"DTS %"PRId64
", next:%"PRId64
" st:%d invalid dropping\n", pkt->dts,
ist->next_dts, pkt->stream_index);
4782 pkt->dts = AV_NOPTS_VALUE;
4784 if (pkt->pts != AV_NOPTS_VALUE){
4785 int64_t pkt_pts = av_rescale_q(pkt->pts,
ist->st->time_base, AV_TIME_BASE_Q);
4786 delta = pkt_pts -
ist->next_dts;
4789 av_log(NULL, AV_LOG_WARNING,
"PTS %"PRId64
", next:%"PRId64
" invalid dropping st:%d\n", pkt->pts,
ist->next_dts, pkt->stream_index);
4790 pkt->pts = AV_NOPTS_VALUE;
4796 if (pkt->dts != AV_NOPTS_VALUE)
4797 ifile->
last_ts = av_rescale_q(pkt->dts,
ist->st->time_base, AV_TIME_BASE_Q);
4800 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",
4801 ifile->
ist_index + pkt->stream_index, av_get_media_type_string(
ist->dec_ctx->codec_type),
4802 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &
ist->st->time_base),
4803 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &
ist->st->time_base),
4814 if (ifile->thread_queue_size)
4815 av_packet_free(&pkt);
4818 av_packet_unref(pkt);
4833 int nb_requests, nb_requests_max = 0;
4838 ret = avfilter_graph_request_oldest(
graph->graph);
4842 if (ret == AVERROR_EOF) {
4844 for (i = 0; i <
graph->nb_outputs; i++)
4848 if (ret != AVERROR(EAGAIN))
4851 for (i = 0; i <
graph->nb_inputs; i++) {
4852 ifilter =
graph->inputs[i];
4857 nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->
filter);
4858 if (nb_requests > nb_requests_max) {
4859 nb_requests_max = nb_requests;
4865 for (i = 0; i <
graph->nb_outputs; i++)
4866 graph->outputs[i]->ost->unavailable = 1;
4889 av_log(NULL, AV_LOG_VERBOSE,
"No more inputs to read from, finishing.\n");
4897 av_log(NULL, AV_LOG_ERROR,
"Error reinitializing filters!\n");
4925 if (av_buffersink_get_type(
ost->
filter->
filter) == AVMEDIA_TYPE_AUDIO)
4951 if (ret == AVERROR(EAGAIN)) {
4958 return ret == AVERROR_EOF ? 0 : ret;
4969 AVFormatContext *os;
4972 int64_t timer_start;
4973 int64_t total_packets_written = 0;
4980 av_log(NULL, AV_LOG_INFO,
"Press [q] to stop, [?] for help\n");
4983 timer_start = av_gettime_relative();
4986 if ((ret = init_input_threads()) < 0)
4991 int64_t cur_time= av_gettime_relative();
5000 av_log(NULL, AV_LOG_VERBOSE,
"No more output streams to write to, finishing.\n");
5005 if (ret < 0 && ret != AVERROR_EOF) {
5006 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(ret));
5014 free_input_threads();
5032 av_log(NULL, AV_LOG_ERROR,
5033 "Nothing was written into output file %d (%s), because "
5034 "at least one of its streams received no packets.\n",
5038 if ((ret = av_write_trailer(os)) < 0) {
5039 av_log(NULL, AV_LOG_ERROR,
"Error writing trailer of %s: %s\n", os->url, av_err2str(ret));
5056 av_log(NULL, AV_LOG_FATAL,
"Empty output on stream %d.\n", i);
5062 av_log(NULL, AV_LOG_FATAL,
"Empty output\n");
5069 if (
ist->decoding_needed) {
5070 avcodec_close(
ist->dec_ctx);
5071 if (
ist->hwaccel_uninit)
5072 ist->hwaccel_uninit(
ist->dec_ctx);
5083 free_input_threads();
5092 av_log(NULL, AV_LOG_ERROR,
5093 "Error closing logfile, loss of information possible: %s\n",
5094 av_err2str(AVERROR(errno)));
5114 struct rusage rusage;
5116 getrusage(RUSAGE_SELF, &rusage);
5118 (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
5120 (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
5121 #elif HAVE_GETPROCESSTIMES
5123 FILETIME c, e, k, u;
5124 proc = GetCurrentProcess();
5125 GetProcessTimes(proc, &c, &e, &k, &u);
5127 ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
5129 ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
5138 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
5139 struct rusage rusage;
5140 getrusage(RUSAGE_SELF, &rusage);
5141 return (int64_t)rusage.ru_maxrss * 1024;
5142 #elif HAVE_GETPROCESSMEMORYINFO
5144 PROCESS_MEMORY_COUNTERS memcounters;
5145 proc = GetCurrentProcess();
5146 memcounters.cb =
sizeof(memcounters);
5147 GetProcessMemoryInfo(proc, &memcounters,
sizeof(memcounters));
5148 return memcounters.PeakPagefileUsage;
5212 char _program_name[] =
"ffmpeg";
5216 #define OFFSET(x) offsetof(OptionsContext, x)
5234 {
"bsfs",
OPT_EXIT, { .func_arg =
show_bsfs },
"show available bit stream filters" },
5243 {
"report", 0, { .func_arg =
opt_report },
"generate a report" },
5244 {
"max_alloc",
HAS_ARG, { .func_arg =
opt_max_alloc },
"set maximum size of a single allocated block",
"bytes" },
5251 "list sources of the input device",
"device" },
5253 "list sinks of the output device",
"device" },
5258 "force format",
"fmt" },
5260 "overwrite output files" },
5262 "never overwrite output files" },
5264 "Ignore unknown stream types" },
5266 "Copy unknown stream types" },
5269 "codec name",
"codec" },
5272 "codec name",
"codec" },
5275 "preset name",
"preset" },
5278 "set input stream mapping",
5279 "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
5281 "map an audio channel from one stream to another",
"file.stream.channel[:syncfile.syncstream]" },
5284 "set metadata information of outfile from infile",
5285 "outfile[,metadata]:infile[,metadata]" },
5288 "set chapters mapping",
"input_file_index" },
5291 "record or transcode \"duration\" seconds of audio/video",
5294 "record or transcode stop time",
"time_stop" },
5296 "set the limit file size in bytes",
"limit_size" },
5299 "set the start time offset",
"time_off" },
5302 "set the start time offset relative to EOF",
"time_off" },
5305 "enable/disable seeking by timestamp with -ss" },
5308 "enable/disable accurate seeking with -ss" },
5311 "set the input ts offset",
"time_off" },
5314 "set the input ts scale",
"scale" },
5316 "set the recording timestamp ('now' to set the current time)",
"time" },
5318 "add metadata",
"string=string" },
5320 "add program with specified streams",
"title=string:st=number..." },
5323 "set the number of data frames to output",
"number" },
5325 "add timings for benchmarking" },
5327 "add timings for each task" },
5329 "write program-readable progress information",
"url" },
5331 "enable or disable interaction on standard input" },
5333 "set max runtime in seconds in CPU user time",
"limit" },
5335 "dump each input packet" },
5337 "when dumping packets, also dump the payload" },
5340 "read input at native frame rate",
"" },
5342 "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\" or \"dv50\" "
5343 "with optional prefixes \"pal-\", \"ntsc-\" or \"film-\")",
"type" },
5345 "video sync method",
"" },
5347 "frame drop threshold",
"" },
5349 "audio sync method",
"" },
5351 "audio drift threshold",
"threshold" },
5353 "copy timestamps" },
5355 "shift input timestamps to start at 0 when using copyts" },
5357 "copy input stream time base when stream copying",
"mode" },
5359 "shift input timestamps to start at 0 when using copyts" },
5361 "copy input stream time base when stream copying",
"mode" },
5364 "finish encoding within shortest input" },
5372 "timestamp discontinuity delta threshold",
"threshold" },
5374 "timestamp error delta threshold",
"threshold" },
5376 "exit on error",
"error" },
5378 "abort on the specified condition flags",
"flags" },
5381 "copy initial non-keyframes" },
5383 "copy or discard frames before start time" },
5385 "set the number of frames to output",
"number" },
5388 "force codec tag/fourcc",
"fourcc/tag" },
5391 "use fixed quality scale (VBR)",
"q" },
5394 "use fixed quality scale (VBR)",
"q" },
5396 "set profile",
"profile" },
5398 "set stream filtergraph",
"filter_graph" },
5400 "number of non-complex filter threads" },
5402 "read stream filtergraph description from a file",
"filename" },
5404 "reinit filtergraph on input parameter changes",
"" },
5406 "create a complex filtergraph",
"graph_description" },
5408 "number of threads for -filter_complex" },
5410 "create a complex filtergraph",
"graph_description" },
5412 "read complex filtergraph description from a file",
"filename" },
5414 "enable automatic conversion filters globally" },
5416 "print progress report during encoding", },
5418 "set the period at which ffmpeg updates stats and -progress output",
"time" },
5421 "add an attachment to the output file",
"filename" },
5424 "extract an attachment into a file",
"filename" },
5426 OPT_OFFSET, { .off =
OFFSET(loop) },
"set number of times input stream shall be looped",
"loop count" },
5428 "print timestamp debugging info" },
5430 "ratio of errors (0.0: no errors, 1.0: 100% errors) above which ffmpeg returns an error instead of success.",
"maximum error rate" },
5436 "disposition",
"" },
5438 { .off =
OFFSET(thread_queue_size) },
5439 "set the maximum number of queued packets from the demuxer" },
5441 "read and decode the streams to fill missing information with heuristics" },
5445 "set the number of video frames to output",
"number" },
5448 "set frame rate (Hz value, fraction or abbreviation)",
"rate" },
5451 "set frame size (WxH or abbreviation)",
"size" },
5454 "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)",
"aspect" },
5457 "set pixel format",
"format" },
5459 "set the number of bits per raw sample",
"number" },
5461 "deprecated use -g 1" },
5466 "rate control override for specific intervals",
"override" },
5469 "force video codec ('copy' to copy stream)",
"codec" },
5475 "set initial TimeCode value.",
"hh:mm:ss[:;.]ff" },
5477 "select the pass number (1 to 3)",
"n" },
5480 "select two pass log file name prefix",
"prefix" },
5482 "this option is deprecated, use the yadif filter instead" },
5484 "calculate PSNR of compressed frames" },
5486 "dump video coding statistics to file" },
5488 "dump video coding statistics to file",
"file" },
5490 "Version of the vstats format to use."},
5492 "set video filters",
"filter_graph" },
5495 "specify intra matrix coeffs",
"matrix" },
5498 "specify inter matrix coeffs",
"matrix" },
5501 "specify intra matrix coeffs",
"matrix" },
5504 "top=1/bottom=0/auto=-1 field first",
"" },
5507 "force video tag/fourcc",
"fourcc/tag" },
5509 "show QP histogram" },
5512 "force the selected framerate, disable the best supported framerate selection" },
5515 "set the value of an outfile streamid",
"streamIndex:value" },
5518 "force key frames at specified timestamps",
"timestamps" },
5520 "audio bitrate (please use -b:a)",
"bitrate" },
5522 "video bitrate (please use -b:v)",
"bitrate" },
5525 "use HW accelerated decoding",
"hwaccel name" },
5528 "select a device for HW acceleration",
"devicename" },
5531 "select output format used with HW accelerated decoding",
"format" },
5532 #if CONFIG_VIDEOTOOLBOX
5536 "show available HW acceleration methods" },
5539 "automatically insert correct rotate filters" },
5542 "automatically insert a scale filter at the end of the filter graph" },
5546 "set the number of audio frames to output",
"number" },
5548 "set audio quality (codec-specific)",
"quality", },
5551 "set audio sampling rate (in Hz)",
"rate" },
5554 "set number of audio channels",
"channels" },
5559 "force audio codec ('copy' to copy stream)",
"codec" },
5562 "force audio tag/fourcc",
"fourcc/tag" },
5564 "change audio volume (256=normal)" ,
"volume" },
5567 "set sample format",
"format" },
5570 "set channel layout",
"layout" },
5572 "set audio filters",
"filter_graph" },
5574 "set the maximum number of channels to try to guess the channel layout" },
5578 "disable subtitle" },
5580 "force subtitle codec ('copy' to copy stream)",
"codec" },
5582 ,
"force subtitle tag/fourcc",
"fourcc/tag" },
5584 "fix subtitles duration" },
5586 "set canvas size (WxH or abbreviation)",
"size" },
5590 "deprecated, use -channel",
"channel" },
5592 "deprecated, use -standard",
"standard" },
5597 "set the maximum demux-decode delay",
"seconds" },
5599 "set the initial demux-decode delay",
"seconds" },
5601 "specify a file in which to print sdp information",
"file" },
5604 "set the desired time base hint for output stream (1:24, 1:48000 or 0.04166, 2.0833e-5)",
"ratio" },
5606 "set the desired time base for the encoder (1:24, 1:48000 or 0.04166, 2.0833e-5). "
5607 "two special values are defined - "
5608 "0 = use frame rate (video) or sample rate (audio),"
5609 "-1 = match source time base",
"ratio" },
5612 "A comma-separated list of bitstream filters",
"bitstream_filters" },
5614 "deprecated",
"audio bitstream_filters" },
5616 "deprecated",
"video bitstream_filters" },
5619 "set the audio options to the indicated preset",
"preset" },
5621 "set the video options to the indicated preset",
"preset" },
5623 "set the subtitle options to the indicated preset",
"preset" },
5625 "set options from indicated preset file",
"filename" },
5628 "maximum number of packets that can be buffered while waiting for all streams to initialize",
"packets" },
5630 "set the threshold after which max_muxing_queue_size is taken into account",
"bytes" },
5634 "force data codec ('copy' to copy stream)",
"codec" },
5640 "set VAAPI hardware device (DRM path or X11 display name)",
"device" },
5645 "set QSV hardware device (DirectX adapter index, DRM path or X11 display name)",
"device"},
5649 "initialise hardware device",
"args" },
5651 "set hardware device used when filtering",
"device" },
5662 if (savedCode == 0) {
5670 setvbuf(stderr,NULL,_IONBF,0);
5672 av_log_set_flags(AV_LOG_SKIP_REPEATED);
5675 if(argc>1 && !strcmp(argv[1],
"-d")){
5683 avdevice_register_all();
5685 avformat_network_init();
5696 av_log(NULL, AV_LOG_WARNING,
"Use -h to get full help or, even better, run 'man %s'\n",
program_name);
5702 av_log(NULL, AV_LOG_FATAL,
"At least one output file must be specified\n");
5707 if (strcmp(
output_files[i]->ctx->oformat->name,
"rtp"))
5715 int64_t utime, stime, rtime;
5720 av_log(NULL, AV_LOG_INFO,
5721 "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
5722 utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
5724 av_log(NULL, AV_LOG_DEBUG,
"%"PRIu64
" frames successfully decoded, %"PRIu64
" decoding errors\n",