65 #include <stdatomic.h>
77 #include "libavformat/avformat.h"
78 #include "libavdevice/avdevice.h"
79 #include "libswresample/swresample.h"
80 #include "libavutil/opt.h"
81 #include "libavutil/channel_layout.h"
82 #include "libavutil/parseutils.h"
83 #include "libavutil/samplefmt.h"
84 #include "libavutil/fifo.h"
85 #include "libavutil/hwcontext.h"
86 #include "libavutil/internal.h"
87 #include "libavutil/intreadwrite.h"
88 #include "libavutil/dict.h"
89 #include "libavutil/display.h"
90 #include "libavutil/mathematics.h"
91 #include "libavutil/pixdesc.h"
92 #include "libavutil/avstring.h"
93 #include "libavutil/libm.h"
94 #include "libavutil/imgutils.h"
95 #include "libavutil/timestamp.h"
96 #include "libavutil/bprint.h"
97 #include "libavutil/time.h"
98 #include "libavutil/thread.h"
99 #include "libavutil/threadmessage.h"
100 #include "libavcodec/mathops.h"
101 #include "libavformat/os_support.h"
103 # include "libavfilter/avfilter.h"
104 # include "libavfilter/buffersrc.h"
105 # include "libavfilter/buffersink.h"
107 #if HAVE_SYS_RESOURCE_H
108 #include <sys/time.h>
109 #include <sys/types.h>
110 #include <sys/resource.h>
111 #elif HAVE_GETPROCESSTIMES
114 #if HAVE_GETPROCESSMEMORYINFO
118 #if HAVE_SETCONSOLECTRLHANDLER
123 #if HAVE_SYS_SELECT_H
124 #include <sys/select.h>
129 #include <sys/ioctl.h>
130 #include <sys/time.h>
141 #include "libavutil/avassert.h"
203 extern int opt_map(
void *optctx,
const char *opt,
const char *arg);
204 extern int opt_map_channel(
void *optctx,
const char *opt,
const char *arg);
206 extern int opt_data_frames(
void *optctx,
const char *opt,
const char *arg);
207 extern int opt_progress(
void *optctx,
const char *opt,
const char *arg);
208 extern int opt_target(
void *optctx,
const char *opt,
const char *arg);
209 extern int opt_vsync(
void *optctx,
const char *opt,
const char *arg);
210 extern int opt_abort_on(
void *optctx,
const char *opt,
const char *arg);
211 extern int opt_stats_period(
void *optctx,
const char *opt,
const char *arg);
212 extern int opt_qscale(
void *optctx,
const char *opt,
const char *arg);
213 extern int opt_profile(
void *optctx,
const char *opt,
const char *arg);
216 extern int opt_attach(
void *optctx,
const char *opt,
const char *arg);
217 extern int opt_video_frames(
void *optctx,
const char *opt,
const char *arg);
219 extern int opt_video_codec(
void *optctx,
const char *opt,
const char *arg);
220 extern int opt_sameq(
void *optctx,
const char *opt,
const char *arg);
221 extern int opt_timecode(
void *optctx,
const char *opt,
const char *arg);
223 extern int opt_vstats_file(
void *optctx,
const char *opt,
const char *arg);
224 extern int opt_vstats(
void *optctx,
const char *opt,
const char *arg);
225 extern int opt_video_frames(
void *optctx,
const char *opt,
const char *arg);
226 extern int opt_old2new(
void *optctx,
const char *opt,
const char *arg);
227 extern int opt_streamid(
void *optctx,
const char *opt,
const char *arg);
228 extern int opt_bitrate(
void *optctx,
const char *opt,
const char *arg);
229 extern int show_hwaccels(
void *optctx,
const char *opt,
const char *arg);
231 extern int opt_audio_frames(
void *optctx,
const char *opt,
const char *arg);
232 extern int opt_audio_qscale(
void *optctx,
const char *opt,
const char *arg);
233 extern int opt_audio_codec(
void *optctx,
const char *opt,
const char *arg);
235 extern int opt_preset(
void *optctx,
const char *opt,
const char *arg);
240 extern int opt_sdp_file(
void *optctx,
const char *opt,
const char *arg);
241 extern int opt_data_codec(
void *optctx,
const char *opt,
const char *arg);
249 __thread
struct termios oldtty;
250 __thread
int restore_tty;
254 static void free_input_threads(
void);
277 av_frame_unref(frame);
281 if ((ret = av_frame_get_buffer(frame, 0)) < 0)
283 memset(frame->data[0], 0, frame->height * frame->linesize[0]);
290 uint32_t *pal, *dst2;
294 if (r->type != SUBTITLE_BITMAP) {
295 av_log(NULL, AV_LOG_WARNING,
"sub2video: non-bitmap subtitle\n");
298 if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
299 av_log(NULL, AV_LOG_WARNING,
"sub2video: rectangle (%d %d %d %d) overflowing %d %d\n",
300 r->x, r->y, r->w, r->h, w, h
305 dst += r->y * dst_linesize + r->x * 4;
307 pal = (uint32_t *)r->data[1];
308 for (y = 0; y < r->h; y++) {
309 dst2 = (uint32_t *)dst;
311 for (x = 0; x < r->w; x++)
312 *(dst2++) = pal[*(src2++)];
314 src += r->linesize[0];
324 av_assert1(frame->data[0]);
327 ret = av_buffersrc_add_frame_flags(ist->
filters[i]->
filter, frame,
328 AV_BUFFERSRC_FLAG_KEEP_REF |
329 AV_BUFFERSRC_FLAG_PUSH);
330 if (ret != AVERROR_EOF && ret < 0)
331 av_log(NULL, AV_LOG_WARNING,
"Error while add the frame to buffer source(%s).\n",
342 int64_t pts, end_pts;
347 pts = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
348 AV_TIME_BASE_Q, ist->
st->time_base);
349 end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000LL,
350 AV_TIME_BASE_Q, ist->
st->time_base);
351 num_rects = sub->num_rects;
363 av_log(ist->
dec_ctx, AV_LOG_ERROR,
364 "Impossible to get a blank canvas.\n");
367 dst = frame->data [0];
368 dst_linesize = frame->linesize[0];
369 for (i = 0; i < num_rects; i++)
392 pts2 = av_rescale_q(pts, ist->
st->time_base, ist2->
st->time_base) - 1;
394 if (pts2 <= ist2->sub2video.last_pts)
401 for (j = 0, nb_reqs = 0; j < ist2->
nb_filters; j++)
402 nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->
filters[j]->
filter);
417 if (ret != AVERROR_EOF && ret < 0)
418 av_log(NULL, AV_LOG_WARNING,
"Flush the frame error.\n");
428 tcsetattr (0, TCSANOW, &oldtty);
434 av_log(NULL, AV_LOG_QUIET,
"%s",
"");
454 ret = write(2,
"Received > 3 system signals, hard exiting\n",
455 strlen(
"Received > 3 system signals, hard exiting\n"));
461 #if HAVE_SETCONSOLECTRLHANDLER
462 static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
464 av_log(NULL, AV_LOG_DEBUG,
"\nReceived windows signal %ld\n", fdwCtrlType);
469 case CTRL_BREAK_EVENT:
473 case CTRL_CLOSE_EVENT:
474 case CTRL_LOGOFF_EVENT:
475 case CTRL_SHUTDOWN_EVENT:
487 av_log(NULL, AV_LOG_ERROR,
"Received unknown windows signal %ld\n", fdwCtrlType);
494 #define SIGNAL(sig, func) \
496 action.sa_handler = func; \
497 sigaction(sig, &action, NULL); \
500 #define SIGNAL(sig, func) \
506 #if defined __linux__
507 struct sigaction action = {0};
511 sigfillset(&action.sa_mask);
514 action.sa_flags = SA_RESTART;
520 if (tcgetattr (0, &tty) == 0) {
524 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
525 |INLCR|IGNCR|ICRNL|IXON);
526 tty.c_oflag |= OPOST;
527 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
528 tty.c_cflag &= ~(CSIZE|PARENB);
533 tcsetattr (0, TCSANOW, &tty);
554 signal(SIGPIPE, SIG_IGN);
557 #if HAVE_SETCONSOLECTRLHANDLER
558 SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
575 n = select(1, &rfds, NULL, NULL, &tv);
584 # if HAVE_PEEKNAMEDPIPE
586 static HANDLE input_handle;
589 input_handle = GetStdHandle(STD_INPUT_HANDLE);
590 is_pipe = !GetConsoleMode(input_handle, &dw);
595 if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
629 av_log(NULL, AV_LOG_INFO,
"bench: maxrss=%ikB\n", maxrss);
634 avfilter_graph_free(&fg->
graph);
642 sizeof(frame), NULL);
643 av_frame_free(&frame);
650 &sub,
sizeof(sub), NULL);
651 avsubtitle_free(&sub);
656 av_freep(&ifilter->
name);
663 avfilter_inout_free(&ofilter->
out_tmp);
664 av_freep(&ofilter->
name);
686 if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
688 avformat_free_context(s);
689 av_dict_free(&of->
opts);
716 avcodec_free_context(&ost->
enc_ctx);
717 avcodec_parameters_free(&ost->
ref_par);
722 av_fifo_generic_read(ost->
muxing_queue, &pkt,
sizeof(pkt), NULL);
723 av_packet_unref(&pkt);
731 free_input_threads();
749 avcodec_free_context(&ist->
dec_ctx);
756 av_log(NULL, AV_LOG_ERROR,
757 "Error closing vstats file, loss of information possible: %s\n",
758 av_err2str(AVERROR(errno)));
769 avformat_network_deinit();
772 av_log(NULL, AV_LOG_INFO,
"Exiting normally, received signal %d.\n",
775 av_log(NULL, AV_LOG_INFO,
"Exiting normally, received cancel request.\n");
777 av_log(NULL, AV_LOG_INFO,
"Conversion failed!\n");
785 AVDictionaryEntry *t = NULL;
787 while ((t = av_dict_get(b,
"", t, AV_DICT_IGNORE_SUFFIX))) {
788 av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
794 AVDictionaryEntry *t;
795 if ((t = av_dict_get(m,
"", NULL, AV_DICT_IGNORE_SUFFIX))) {
796 av_log(NULL, AV_LOG_FATAL,
"Option %s not found.\n", t->key);
815 vsnprintf(buf,
sizeof(buf), fmt, va);
817 av_log(NULL, AV_LOG_INFO,
818 "bench: %8" PRIu64
" user %8" PRIu64
" sys %8" PRIu64
" real %s \n",
832 ost2->
finished |= ost == ost2 ? this_stream : others;
838 AVFormatContext *s = of->
ctx;
839 AVStream *
st = ost->
st;
850 if (!(
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->
encoding_needed) && !unqueue) {
852 av_packet_unref(pkt);
859 AVPacket tmp_pkt = {0};
862 unsigned int are_we_over_size =
864 int new_size = are_we_over_size ?
870 av_log(NULL, AV_LOG_ERROR,
871 "Too many packets buffered for output stream %d:%d.\n",
879 ret = av_packet_make_refcounted(pkt);
882 av_packet_move_ref(&tmp_pkt, pkt);
884 av_fifo_generic_write(ost->
muxing_queue, &tmp_pkt,
sizeof(tmp_pkt), NULL);
890 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
892 if (
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
894 uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,
896 ost->
quality = sd ? AV_RL32(sd) : -1;
897 ost->
pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;
899 for (i = 0; i<FF_ARRAY_ELEMS(ost->
error); i++) {
901 ost->
error[i] = AV_RL64(sd + 8 + 8*i);
907 if (pkt->duration > 0)
908 av_log(NULL, AV_LOG_WARNING,
"Overriding packet duration by frame rate, this should not happen\n");
909 pkt->duration = av_rescale_q(1, av_inv_q(ost->
frame_rate),
916 if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
917 if (pkt->dts != AV_NOPTS_VALUE &&
918 pkt->pts != AV_NOPTS_VALUE &&
919 pkt->dts > pkt->pts) {
920 av_log(s, AV_LOG_WARNING,
"Invalid DTS: %"PRId64
" PTS: %"PRId64
" in output stream %d:%d, replacing by guess\n",
928 if ((
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) &&
929 pkt->dts != AV_NOPTS_VALUE &&
930 !(
st->codecpar->codec_id == AV_CODEC_ID_VP9 && ost->
stream_copy) &&
932 int64_t max = ost->
last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
933 if (pkt->dts < max) {
934 int loglevel = max - pkt->dts > 2 ||
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
936 loglevel = AV_LOG_ERROR;
937 av_log(s, loglevel,
"Non-monotonous DTS in output stream "
938 "%d:%d; previous: %"PRId64
", current: %"PRId64
"; ",
941 av_log(NULL, AV_LOG_FATAL,
"aborting.\n");
944 av_log(s, loglevel,
"changing to %"PRId64
". This may result "
945 "in incorrect timestamps in the output file.\n",
947 if (pkt->pts >= pkt->dts)
948 pkt->pts = FFMAX(pkt->pts, max);
958 pkt->stream_index = ost->
index;
961 av_log(NULL, AV_LOG_INFO,
"muxer <- type:%s "
962 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
963 av_get_media_type_string(ost->
enc_ctx->codec_type),
964 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->
st->time_base),
965 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->
st->time_base),
970 ret = av_interleaved_write_frame(s, pkt);
976 av_packet_unref(pkt);
1008 ret = av_bsf_send_packet(ost->
bsf_ctx, eof ? NULL : pkt);
1011 while ((
ret = av_bsf_receive_packet(ost->
bsf_ctx, pkt)) >= 0)
1013 if (
ret == AVERROR(EAGAIN))
1019 if (
ret < 0 &&
ret != AVERROR_EOF) {
1020 av_log(NULL, AV_LOG_ERROR,
"Error applying bitstream filters to an output "
1033 AV_TIME_BASE_Q) >= 0) {
1042 double float_pts = AV_NOPTS_VALUE;
1043 AVCodecContext *enc = ost->
enc_ctx;
1044 if (!frame || frame->pts == AV_NOPTS_VALUE ||
1052 AVRational filter_tb = av_buffersink_get_time_base(filter);
1053 AVRational tb = enc->time_base;
1054 int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
1056 tb.den <<= extra_bits;
1058 av_rescale_q(frame->pts, filter_tb, tb) -
1059 av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
1060 float_pts /= 1 << extra_bits;
1062 float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
1065 av_rescale_q(frame->pts, filter_tb, enc->time_base) -
1066 av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
1072 av_log(NULL, AV_LOG_INFO,
"filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
1073 frame ? av_ts2str(frame->pts) :
"NULL",
1074 frame ? av_ts2timestr(frame->pts, &enc->time_base) :
"NULL",
1076 enc ? enc->time_base.num : -1,
1077 enc ? enc->time_base.den : -1);
1087 int ret = AVERROR_BUG;
1088 char error[1024] = {0};
1095 av_log(NULL, AV_LOG_ERROR,
"Error initializing output stream %d:%d -- %s\n",
1108 AVCodecContext *enc = ost->
enc_ctx;
1112 av_init_packet(&pkt);
1123 ost->
sync_opts = frame->pts + frame->nb_samples;
1127 av_assert0(pkt.size || !pkt.data);
1130 av_log(NULL, AV_LOG_INFO,
"encoder <- type:audio "
1131 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1132 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
1133 enc->time_base.num, enc->time_base.den);
1136 ret = avcodec_send_frame(enc, frame);
1141 ret = avcodec_receive_packet(enc, &pkt);
1142 if (
ret == AVERROR(EAGAIN))
1149 av_packet_rescale_ts(&pkt, enc->time_base, ost->
mux_timebase);
1152 av_log(NULL, AV_LOG_INFO,
"encoder -> type:audio "
1153 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1154 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
1155 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
1163 av_log(NULL, AV_LOG_FATAL,
"Audio encoding failed\n");
1171 int subtitle_out_max_size = 1024 * 1024;
1172 int subtitle_out_size, nb, i;
1173 AVCodecContext *enc;
1177 if (sub->pts == AV_NOPTS_VALUE) {
1178 av_log(NULL, AV_LOG_ERROR,
"Subtitle packets must have a pts\n");
1189 av_log(NULL, AV_LOG_FATAL,
"Failed to allocate subtitle_out\n");
1197 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1206 for (i = 0; i < nb; i++) {
1207 unsigned save_num_rects = sub->num_rects;
1209 ost->
sync_opts = av_rescale_q(
pts, AV_TIME_BASE_Q, enc->time_base);
1215 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1216 sub->end_display_time -= sub->start_display_time;
1217 sub->start_display_time = 0;
1223 subtitle_out_size = avcodec_encode_subtitle(enc,
subtitle_out,
1224 subtitle_out_max_size, sub);
1226 sub->num_rects = save_num_rects;
1227 if (subtitle_out_size < 0) {
1228 av_log(NULL, AV_LOG_FATAL,
"Subtitle encoding failed\n");
1232 av_init_packet(&pkt);
1234 pkt.size = subtitle_out_size;
1235 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->
mux_timebase);
1236 pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->
mux_timebase);
1237 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
1241 pkt.pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, ost->
mux_timebase);
1243 pkt.pts += av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->
mux_timebase);
1252 AVFrame *next_picture)
1254 int ret, format_video_sync;
1256 AVCodecContext *enc = ost->
enc_ctx;
1257 AVRational frame_rate;
1258 int nb_frames, nb0_frames, i;
1259 double delta, delta0;
1260 double duration = 0;
1261 double sync_ipts = AV_NOPTS_VALUE;
1272 frame_rate = av_buffersink_get_frame_rate(filter);
1273 if (frame_rate.num > 0 && frame_rate.den > 0)
1274 duration = 1/(av_q2d(frame_rate) * av_q2d(enc->time_base));
1276 if(ist && ist->
st->start_time != AV_NOPTS_VALUE && ist->
st->first_dts != AV_NOPTS_VALUE && ost->
frame_rate.num)
1277 duration = FFMIN(duration, 1/(av_q2d(ost->
frame_rate) * av_q2d(enc->time_base)));
1284 lrintf(next_picture->pkt_duration * av_q2d(ist->
st->time_base) / av_q2d(enc->time_base)) > 0) {
1285 duration = lrintf(next_picture->pkt_duration * av_q2d(ist->
st->time_base) / av_q2d(enc->time_base));
1288 if (!next_picture) {
1295 delta = delta0 + duration;
1303 if(!strcmp(of->
ctx->oformat->name,
"avi")) {
1323 if (delta0 < -0.6) {
1324 av_log(NULL, AV_LOG_VERBOSE,
"Past duration %f too large\n", -delta0);
1326 av_log(NULL, AV_LOG_DEBUG,
"Clipping frame in rate conversion by %f\n", -delta0);
1332 switch (format_video_sync) {
1335 av_log(NULL, AV_LOG_DEBUG,
"Not duplicating %d initial frames\n", (
int)lrintf(delta0));
1344 }
else if (delta < -1.1)
1346 else if (delta > 1.1) {
1347 nb_frames = lrintf(delta);
1349 nb0_frames = llrintf(delta0 - 0.6);
1355 else if (delta > 0.6)
1368 nb0_frames = FFMIN(nb0_frames, nb_frames);
1377 av_log(NULL, AV_LOG_VERBOSE,
1378 "*** dropping frame %d from stream %d at ts %"PRId64
"\n",
1381 if (nb_frames > (nb0_frames && ost->
last_dropped) + (nb_frames > nb0_frames)) {
1383 av_log(NULL, AV_LOG_ERROR,
"%d frame duplication too large, skipping\n", nb_frames - 1);
1388 av_log(NULL, AV_LOG_VERBOSE,
"*** %d dup!\n", nb_frames - 1);
1390 av_log(NULL, AV_LOG_WARNING,
"More than %d frames duplicated\n",
dup_warning);
1394 ost->
last_dropped = nb_frames == nb0_frames && next_picture;
1397 for (i = 0; i < nb_frames; i++) {
1398 AVFrame *in_picture;
1399 int forced_keyframe = 0;
1401 av_init_packet(&pkt);
1405 if (i < nb0_frames && ost->last_frame) {
1408 in_picture = next_picture;
1418 in_picture->quality = enc->global_quality;
1419 in_picture->pict_type = 0;
1422 in_picture->pts != AV_NOPTS_VALUE)
1425 pts_time = in_picture->pts != AV_NOPTS_VALUE ?
1430 forced_keyframe = 1;
1436 ff_dlog(NULL,
"force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
1444 forced_keyframe = 1;
1455 && in_picture->key_frame==1
1457 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 ret = avcodec_receive_packet(enc, &pkt);
1484 if (
ret == AVERROR(EAGAIN))
1490 av_log(NULL, AV_LOG_INFO,
"encoder -> type:video "
1491 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1492 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
1493 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
1496 if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & AV_CODEC_CAP_DELAY))
1499 av_packet_rescale_ts(&pkt, enc->time_base, ost->
mux_timebase);
1502 av_log(NULL, AV_LOG_INFO,
"encoder -> type:video "
1503 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1504 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->
mux_timebase),
1505 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->
mux_timebase));
1508 frame_size = pkt.size;
1512 if (ost->
logfile && enc->stats_out) {
1513 fprintf(ost->
logfile,
"%s", enc->stats_out);
1538 av_log(NULL, AV_LOG_FATAL,
"Video encoding failed\n");
1544 return -10.0 * log10(d);
1549 AVCodecContext *enc;
1551 double ti1, bitrate, avg_bitrate;
1563 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1564 frame_number = ost->
st->nb_frames;
1566 fprintf(
vstats_file,
"frame= %5d q= %2.1f ", frame_number,
1567 ost->
quality / (
float)FF_QP2LAMBDA);
1570 ost->
quality / (
float)FF_QP2LAMBDA);
1573 if (ost->
error[0]>=0 && (enc->flags & AV_CODEC_FLAG_PSNR))
1574 fprintf(
vstats_file,
"PSNR= %6.2f ",
psnr(ost->
error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1578 ti1 = av_stream_get_end_pts(ost->
st) * av_q2d(ost->
st->time_base);
1582 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1583 avg_bitrate = (double)(ost->
data_size * 8) / ti1 / 1000.0;
1584 fprintf(
vstats_file,
"s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1585 (
double)ost->
data_size / 1024, ti1, bitrate, avg_bitrate);
1598 for (i = 0; i < of->
ctx->nb_streams; i++)
1611 AVFrame *filtered_frame = NULL;
1618 AVFilterContext *filter;
1619 AVCodecContext *enc = ost->
enc_ctx;
1635 if (av_buffersink_get_type(filter) == AVMEDIA_TYPE_AUDIO)
1639 return AVERROR(ENOMEM);
1644 ret = av_buffersink_get_frame_flags(filter, filtered_frame,
1645 AV_BUFFERSINK_FLAG_NO_REQUEST);
1647 if (
ret != AVERROR(EAGAIN) &&
ret != AVERROR_EOF) {
1648 av_log(NULL, AV_LOG_WARNING,
1649 "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(
ret));
1650 }
else if (flush &&
ret == AVERROR_EOF) {
1651 if (av_buffersink_get_type(filter) == AVMEDIA_TYPE_VIDEO)
1657 av_frame_unref(filtered_frame);
1661 switch (av_buffersink_get_type(filter)) {
1662 case AVMEDIA_TYPE_VIDEO:
1664 enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
1668 case AVMEDIA_TYPE_AUDIO:
1669 if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&
1670 enc->channels != filtered_frame->channels) {
1671 av_log(NULL, AV_LOG_ERROR,
1672 "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1682 av_frame_unref(filtered_frame);
1691 uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
1692 uint64_t subtitle_size = 0;
1694 float percent = -1.0;
1700 switch (ost->
enc_ctx->codec_type) {
1701 case AVMEDIA_TYPE_VIDEO: video_size += ost->
data_size;
break;
1702 case AVMEDIA_TYPE_AUDIO: audio_size += ost->
data_size;
break;
1703 case AVMEDIA_TYPE_SUBTITLE: subtitle_size += ost->
data_size;
break;
1704 default: other_size += ost->
data_size;
break;
1706 extra_size += ost->
enc_ctx->extradata_size;
1708 if ( (ost->
enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
1709 != AV_CODEC_FLAG_PASS1)
1716 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: ",
1717 video_size / 1024.0,
1718 audio_size / 1024.0,
1719 subtitle_size / 1024.0,
1720 other_size / 1024.0,
1721 extra_size / 1024.0);
1723 av_log(NULL, AV_LOG_INFO,
"%f%%", percent);
1725 av_log(NULL, AV_LOG_INFO,
"unknown");
1726 av_log(NULL, AV_LOG_INFO,
"\n");
1731 uint64_t total_packets = 0, total_size = 0;
1733 av_log(NULL, AV_LOG_VERBOSE,
"Input file #%d (%s):\n",
1738 enum AVMediaType type = ist->
dec_ctx->codec_type;
1743 av_log(NULL, AV_LOG_VERBOSE,
" Input stream #%d:%d (%s): ",
1745 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" packets read (%"PRIu64
" bytes); ",
1749 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" frames decoded",
1751 if (type == AVMEDIA_TYPE_AUDIO)
1752 av_log(NULL, AV_LOG_VERBOSE,
" (%"PRIu64
" samples)", ist->
samples_decoded);
1753 av_log(NULL, AV_LOG_VERBOSE,
"; ");
1756 av_log(NULL, AV_LOG_VERBOSE,
"\n");
1759 av_log(NULL, AV_LOG_VERBOSE,
" Total: %"PRIu64
" packets (%"PRIu64
" bytes) demuxed\n",
1760 total_packets, total_size);
1765 uint64_t total_packets = 0, total_size = 0;
1767 av_log(NULL, AV_LOG_VERBOSE,
"Output file #%d (%s):\n",
1770 for (j = 0; j < of->
ctx->nb_streams; j++) {
1772 enum AVMediaType type = ost->
enc_ctx->codec_type;
1777 av_log(NULL, AV_LOG_VERBOSE,
" Output stream #%d:%d (%s): ",
1780 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" frames encoded",
1782 if (type == AVMEDIA_TYPE_AUDIO)
1783 av_log(NULL, AV_LOG_VERBOSE,
" (%"PRIu64
" samples)", ost->
samples_encoded);
1784 av_log(NULL, AV_LOG_VERBOSE,
"; ");
1787 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" packets muxed (%"PRIu64
" bytes); ",
1790 av_log(NULL, AV_LOG_VERBOSE,
"\n");
1793 av_log(NULL, AV_LOG_VERBOSE,
" Total: %"PRIu64
" packets (%"PRIu64
" bytes) muxed\n",
1794 total_packets, total_size);
1796 if(video_size +
data_size + audio_size + subtitle_size + extra_size == 0){
1797 av_log(NULL, AV_LOG_WARNING,
"Output file is empty, nothing was encoded ");
1799 av_log(NULL, AV_LOG_WARNING,
"\n");
1801 av_log(NULL, AV_LOG_WARNING,
"(check -ss / -t / -frames parameters if used)\n");
1806 static void forward_report(
int is_last_report, int64_t timer_start, int64_t cur_time)
1808 AVFormatContext *oc = NULL;
1809 AVCodecContext *enc = NULL;
1811 int64_t
pts = INT64_MIN + 1;
1814 int frame_number = 0;
1817 int64_t total_size = 0;
1819 double bitrate = 0.0;
1822 float t = (cur_time-timer_start) / 1000000.0;
1827 total_size = avio_size(oc->pb);
1828 if (total_size <= 0) {
1829 total_size = avio_tell(oc->pb);
1840 quality = ost->
quality / (float) FF_QP2LAMBDA;
1843 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1849 fps = t > 1 ? frame_number / t : 0;
1853 if (av_stream_get_end_pts(ost->
st) != AV_NOPTS_VALUE)
1854 pts = FFMAX(
pts, av_rescale_q(av_stream_get_end_pts(ost->
st),
1855 ost->
st->time_base, AV_TIME_BASE_Q));
1861 seconds = FFABS(
pts) / 1000;
1864 bitrate =
pts && total_size >= 0 ? total_size * 8 / (
pts / 1000.0) : -1;
1867 speed = t != 0.0 ? (double)
pts / AV_TIME_BASE / t : -1;
1871 report_callback(frame_number, fps, quality, total_size, seconds, bitrate, speed);
1875 static void print_report(
int is_last_report, int64_t timer_start, int64_t cur_time)
1877 AVBPrint buf, buf_script;
1879 AVFormatContext *oc;
1881 AVCodecContext *enc;
1882 int frame_number, vid, i;
1885 int64_t
pts = INT64_MIN + 1;
1886 int hours, mins, secs, us;
1887 const char *hours_sign;
1891 if (!is_last_report) {
1906 t = (cur_time-timer_start) / 1000000.0;
1911 total_size = avio_size(oc->pb);
1912 if (total_size <= 0)
1913 total_size = avio_tell(oc->pb);
1916 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
1917 av_bprint_init(&buf_script, 0, AV_BPRINT_SIZE_AUTOMATIC);
1923 q = ost->
quality / (float) FF_QP2LAMBDA;
1925 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1926 av_bprintf(&buf,
"q=%2.1f ", q);
1927 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
1930 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1934 fps = t > 1 ? frame_number / t : 0;
1935 av_bprintf(&buf,
"frame=%5d fps=%3.*f q=%3.1f ",
1936 frame_number, fps < 9.95, fps, q);
1937 av_bprintf(&buf_script,
"frame=%d\n", frame_number);
1938 av_bprintf(&buf_script,
"fps=%.2f\n", fps);
1939 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
1942 av_bprintf(&buf,
"L");
1948 for (j = 0; j < 32; j++)
1952 if ((enc->flags & AV_CODEC_FLAG_PSNR) && (ost->
pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {
1954 double error, error_sum = 0;
1955 double scale, scale_sum = 0;
1957 char type[3] = {
'Y',
'U',
'V' };
1958 av_bprintf(&buf,
"PSNR=");
1959 for (j = 0; j < 3; j++) {
1960 if (is_last_report) {
1961 error = enc->error[j];
1962 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1964 error = ost->
error[j];
1965 scale = enc->width * enc->height * 255.0 * 255.0;
1971 p =
psnr(error / scale);
1972 av_bprintf(&buf,
"%c:%2.2f ", type[j], p);
1973 av_bprintf(&buf_script,
"stream_%d_%d_psnr_%c=%2.2f\n",
1976 p =
psnr(error_sum / scale_sum);
1977 av_bprintf(&buf,
"*:%2.2f ",
psnr(error_sum / scale_sum));
1978 av_bprintf(&buf_script,
"stream_%d_%d_psnr_all=%2.2f\n",
1984 if (av_stream_get_end_pts(ost->
st) != AV_NOPTS_VALUE) {
1985 pts = FFMAX(
pts, av_rescale_q(av_stream_get_end_pts(ost->
st),
1986 ost->
st->time_base, AV_TIME_BASE_Q));
1999 secs = FFABS(
pts) / AV_TIME_BASE;
2000 us = FFABS(
pts) % AV_TIME_BASE;
2005 hours_sign = (
pts < 0) ?
"-" :
"";
2007 bitrate =
pts && total_size >= 0 ? total_size * 8 / (
pts / 1000.0) : -1;
2008 speed = t != 0.0 ? (double)
pts / AV_TIME_BASE / t : -1;
2010 if (total_size < 0) av_bprintf(&buf,
"size=N/A time=");
2011 else av_bprintf(&buf,
"size=%8.0fkB time=", total_size / 1024.0);
2012 if (
pts == AV_NOPTS_VALUE) {
2013 av_bprintf(&buf,
"N/A ");
2015 av_bprintf(&buf,
"%s%02d:%02d:%02d.%02d ",
2016 hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
2020 av_bprintf(&buf,
"bitrate=N/A");
2021 av_bprintf(&buf_script,
"bitrate=N/A\n");
2023 av_bprintf(&buf,
"bitrate=%6.1fkbits/s", bitrate);
2024 av_bprintf(&buf_script,
"bitrate=%6.1fkbits/s\n", bitrate);
2027 if (total_size < 0) av_bprintf(&buf_script,
"total_size=N/A\n");
2028 else av_bprintf(&buf_script,
"total_size=%"PRId64
"\n", total_size);
2029 if (
pts == AV_NOPTS_VALUE) {
2030 av_bprintf(&buf_script,
"out_time_us=N/A\n");
2031 av_bprintf(&buf_script,
"out_time_ms=N/A\n");
2032 av_bprintf(&buf_script,
"out_time=N/A\n");
2034 av_bprintf(&buf_script,
"out_time_us=%"PRId64
"\n",
pts);
2035 av_bprintf(&buf_script,
"out_time_ms=%"PRId64
"\n",
pts);
2036 av_bprintf(&buf_script,
"out_time=%s%02d:%02d:%02d.%06d\n",
2037 hours_sign, hours, mins, secs, us);
2046 av_bprintf(&buf,
" speed=N/A");
2047 av_bprintf(&buf_script,
"speed=N/A\n");
2049 av_bprintf(&buf,
" speed=%4.3gx", speed);
2050 av_bprintf(&buf_script,
"speed=%4.3gx\n", speed);
2054 const char end = is_last_report ?
'\n' :
'\r';
2055 if (
print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
2056 fprintf(stderr,
"%s %c", buf.str, end);
2058 av_log(NULL, AV_LOG_INFO,
"%s %c", buf.str, end);
2062 av_bprint_finalize(&buf, NULL);
2065 av_bprintf(&buf_script,
"progress=%s\n",
2066 is_last_report ?
"end" :
"continue");
2068 FFMIN(buf_script.len, buf_script.size - 1));
2070 av_bprint_finalize(&buf_script, NULL);
2071 if (is_last_report) {
2073 av_log(NULL, AV_LOG_ERROR,
2074 "Error closing progress log, loss of information possible: %s\n", av_err2str(
ret));
2088 ifilter->
format = par->format;
2092 ifilter->
width = par->width;
2093 ifilter->
height = par->height;
2103 AVCodecContext *enc = ost->
enc_ctx;
2114 av_log(NULL, AV_LOG_WARNING,
2115 "Finishing stream %d:%d without any data written to it.\n",
2131 av_log(NULL, AV_LOG_ERROR,
"Error configuring filter graph\n");
2141 if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
2145 const char *desc = NULL;
2149 switch (enc->codec_type) {
2150 case AVMEDIA_TYPE_AUDIO:
2153 case AVMEDIA_TYPE_VIDEO:
2160 av_init_packet(&pkt);
2166 while ((
ret = avcodec_receive_packet(enc, &pkt)) == AVERROR(EAGAIN)) {
2167 ret = avcodec_send_frame(enc, NULL);
2169 av_log(NULL, AV_LOG_FATAL,
"%s encoding failed: %s\n",
2177 if (
ret < 0 &&
ret != AVERROR_EOF) {
2178 av_log(NULL, AV_LOG_FATAL,
"%s encoding failed: %s\n",
2183 if (ost->
logfile && enc->stats_out) {
2184 fprintf(ost->
logfile,
"%s", enc->stats_out);
2186 if (
ret == AVERROR_EOF) {
2191 av_packet_unref(&pkt);
2194 av_packet_rescale_ts(&pkt, enc->time_base, ost->
mux_timebase);
2195 pkt_size = pkt.size;
2229 int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->
mux_timebase);
2234 av_init_packet(&opkt);
2241 if ((!ost->
frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
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))
2262 start_time = f->
ctx->start_time;
2272 if (ost->
enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
2275 if (av_packet_ref(&opkt, pkt) < 0)
2278 if (pkt->pts != AV_NOPTS_VALUE)
2279 opkt.pts = av_rescale_q(pkt->pts, ist->
st->time_base, ost->
mux_timebase) - ost_tb_start_time;
2281 if (pkt->dts == AV_NOPTS_VALUE) {
2283 }
else if (ost->
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2284 int duration = av_get_audio_frame_duration(ist->
dec_ctx, pkt->size);
2286 duration = ist->
dec_ctx->frame_size;
2287 opkt.dts = av_rescale_delta(ist->
st->time_base, pkt->dts,
2288 (AVRational){1, ist->dec_ctx->sample_rate}, duration,
2291 opkt.pts = opkt.dts - ost_tb_start_time;
2293 opkt.dts = av_rescale_q(pkt->dts, ist->
st->time_base, ost->
mux_timebase);
2294 opkt.dts -= ost_tb_start_time;
2296 opkt.duration = av_rescale_q(pkt->duration, ist->
st->time_base, ost->
mux_timebase);
2305 if (!
dec->channel_layout) {
2306 char layout_name[256];
2310 dec->channel_layout = av_get_default_channel_layout(
dec->channels);
2311 if (!
dec->channel_layout)
2313 av_get_channel_layout_string(layout_name,
sizeof(layout_name),
2314 dec->channels,
dec->channel_layout);
2315 av_log(NULL, AV_LOG_WARNING,
"Guessed Channel Layout for Input Stream "
2316 "#%d.%d : %s\n", ist->
file_index, ist->
st->index, layout_name);
2354 int need_reinit,
ret, i;
2357 need_reinit = ifilter->
format != frame->format;
2359 switch (ifilter->
ist->
st->codecpar->codec_type) {
2360 case AVMEDIA_TYPE_AUDIO:
2361 need_reinit |= ifilter->
sample_rate != frame->sample_rate ||
2362 ifilter->
channels != frame->channels ||
2365 case AVMEDIA_TYPE_VIDEO:
2366 need_reinit |= ifilter->
width != frame->width ||
2367 ifilter->
height != frame->height;
2385 if (need_reinit || !fg->
graph) {
2388 AVFrame *tmp = av_frame_clone(frame);
2390 return AVERROR(ENOMEM);
2391 av_frame_unref(frame);
2396 av_frame_free(&tmp);
2400 av_fifo_generic_write(ifilter->
frame_queue, &tmp,
sizeof(tmp), NULL);
2406 if (
ret < 0 &&
ret != AVERROR_EOF) {
2407 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(
ret));
2413 av_log(NULL, AV_LOG_ERROR,
"Error reinitializing filters!\n");
2418 ret = av_buffersrc_add_frame_flags(ifilter->
filter, frame, AV_BUFFERSRC_FLAG_PUSH);
2420 if (
ret != AVERROR_EOF)
2421 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(
ret));
2438 ret = av_buffersrc_close(ifilter->
filter,
pts, AV_BUFFERSRC_FLAG_PUSH);
2446 if (ifilter->
format < 0 && (ifilter->
type == AVMEDIA_TYPE_AUDIO || ifilter->
type == AVMEDIA_TYPE_VIDEO)) {
2447 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);
2448 return AVERROR_INVALIDDATA;
2459 static int decode(AVCodecContext *avctx, AVFrame *frame,
int *got_frame, AVPacket *pkt)
2466 ret = avcodec_send_packet(avctx, pkt);
2469 if (
ret < 0 &&
ret != AVERROR_EOF)
2473 ret = avcodec_receive_frame(avctx, frame);
2474 if (
ret < 0 &&
ret != AVERROR(EAGAIN))
2497 if (
ret == AVERROR_EOF)
2500 av_log(NULL, AV_LOG_ERROR,
2501 "Failed to inject frame into filter network: %s\n", av_err2str(
ret));
2512 AVCodecContext *avctx = ist->
dec_ctx;
2514 AVRational decoded_frame_tb;
2517 return AVERROR(ENOMEM);
2519 return AVERROR(ENOMEM);
2528 if (
ret >= 0 && avctx->sample_rate <= 0) {
2529 av_log(avctx, AV_LOG_ERROR,
"Sample rate %d invalid\n", avctx->sample_rate);
2530 ret = AVERROR_INVALIDDATA;
2533 if (
ret != AVERROR_EOF)
2550 decoded_frame_tb = ist->
st->time_base;
2551 }
else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
2553 decoded_frame_tb = ist->
st->time_base;
2556 decoded_frame_tb = AV_TIME_BASE_Q;
2561 (AVRational){1, avctx->sample_rate});
2567 return err < 0 ? err :
ret;
2574 int i,
ret = 0, err = 0;
2575 int64_t best_effort_timestamp;
2576 int64_t
dts = AV_NOPTS_VALUE;
2582 if (!eof && pkt && pkt->size == 0)
2586 return AVERROR(ENOMEM);
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);
2602 return AVERROR(ENOMEM);
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",
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",
2660 best_effort_timestamp=
decoded_frame->best_effort_timestamp;
2666 if (eof && best_effort_timestamp == AV_NOPTS_VALUE && ist->
nb_dts_buffer > 0) {
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)
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)
2700 return err < 0 ? err :
ret;
2708 int i,
ret = avcodec_decode_subtitle2(ist->
dec_ctx,
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",
2729 end <= 0 ?
", dropping it" :
"");
2768 || ost->
enc->type != AVMEDIA_TYPE_SUBTITLE)
2784 int64_t
pts = av_rescale_q_rnd(ist->
pts, AV_TIME_BASE_Q, ist->
st->time_base,
2785 AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
2800 int eof_reached = 0;
2804 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;
2807 ist->
dts += av_rescale_q(pkt->pts, ist->
st->time_base, AV_TIME_BASE_Q);
2813 if (ist->
next_dts == AV_NOPTS_VALUE)
2815 if (ist->
next_pts == AV_NOPTS_VALUE)
2820 av_init_packet(&avpkt);
2827 if (pkt && pkt->dts != AV_NOPTS_VALUE) {
2828 ist->
next_dts = ist->
dts = av_rescale_q(pkt->dts, ist->
st->time_base, AV_TIME_BASE_Q);
2835 int64_t duration_dts = 0;
2836 int64_t duration_pts = 0;
2838 int decode_failed = 0;
2843 switch (ist->
dec_ctx->codec_type) {
2844 case AVMEDIA_TYPE_AUDIO:
2848 case AVMEDIA_TYPE_VIDEO:
2852 if (pkt && pkt->duration) {
2853 duration_dts = av_rescale_q(pkt->duration, ist->
st->time_base, AV_TIME_BASE_Q);
2854 }
else if(ist->
dec_ctx->framerate.num != 0 && ist->
dec_ctx->framerate.den != 0) {
2855 int ticks= av_stream_get_parser(ist->
st) ? av_stream_get_parser(ist->
st)->repeat_pict+1 : ist->
dec_ctx->ticks_per_frame;
2856 duration_dts = ((int64_t)AV_TIME_BASE *
2857 ist->
dec_ctx->framerate.den * ticks) /
2861 if(ist->
dts != AV_NOPTS_VALUE && duration_dts) {
2868 if (duration_pts > 0) {
2869 ist->
next_pts += av_rescale_q(duration_pts, ist->
st->time_base, AV_TIME_BASE_Q);
2875 case AVMEDIA_TYPE_SUBTITLE:
2879 if (!pkt &&
ret >= 0)
2886 if (
ret == AVERROR_EOF) {
2892 if (decode_failed) {
2893 av_log(NULL, AV_LOG_ERROR,
"Error while decoding stream #%d:%d: %s\n",
2896 av_log(NULL, AV_LOG_FATAL,
"Error while processing the decoded "
2897 "data for stream #%d:%d\n", ist->
file_index, ist->
st->index);
2929 av_log(NULL, AV_LOG_FATAL,
"Error marking filters as finished\n");
2937 switch (ist->
dec_ctx->codec_type) {
2938 case AVMEDIA_TYPE_AUDIO:
2939 av_assert1(pkt->duration >= 0);
2940 if (ist->
dec_ctx->sample_rate) {
2944 ist->
next_dts += av_rescale_q(pkt->duration, ist->
st->time_base, AV_TIME_BASE_Q);
2947 case AVMEDIA_TYPE_VIDEO:
2950 AVRational time_base_q = AV_TIME_BASE_Q;
2953 }
else if (pkt->duration) {
2954 ist->
next_dts += av_rescale_q(pkt->duration, ist->
st->time_base, AV_TIME_BASE_Q);
2955 }
else if(ist->
dec_ctx->framerate.num != 0) {
2956 int ticks= av_stream_get_parser(ist->
st) ? av_stream_get_parser(ist->
st)->repeat_pict + 1 : ist->
dec_ctx->ticks_per_frame;
2957 ist->
next_dts += ((int64_t)AV_TIME_BASE *
2958 ist->
dec_ctx->framerate.den * ticks) /
2975 return !eof_reached;
2983 AVIOContext *sdp_pb;
2984 AVFormatContext **avc;
2995 if (!strcmp(
output_files[i]->ctx->oformat->name,
"rtp")) {
3004 av_sdp_create(avc, j, sdp,
sizeof(sdp));
3011 av_log(NULL, AV_LOG_ERROR,
"Failed to open sdp file '%s'\n",
sdp_filename);
3013 avio_print(sdp_pb, sdp);
3023 static enum AVPixelFormat
get_format(AVCodecContext *s,
const enum AVPixelFormat *pix_fmts)
3026 const enum AVPixelFormat *p;
3029 for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
3030 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
3031 const AVCodecHWConfig *config = NULL;
3034 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
3040 config = avcodec_get_hw_config(s->codec, i);
3043 if (!(config->methods &
3044 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
3046 if (config->pix_fmt == *p)
3059 av_log(NULL, AV_LOG_FATAL,
3060 "%s hwaccel requested for input stream #%d:%d, "
3061 "but cannot be initialized.\n",
3062 av_hwdevice_get_type_name(config->device_type),
3064 return AV_PIX_FMT_NONE;
3069 const HWAccel *hwaccel = NULL;
3088 av_log(NULL, AV_LOG_FATAL,
3089 "%s hwaccel requested for input stream #%d:%d, "
3090 "but cannot be initialized.\n", hwaccel->
name,
3092 return AV_PIX_FMT_NONE;
3098 if (!s->hw_frames_ctx)
3099 return AV_PIX_FMT_NONE;
3109 static int get_buffer(AVCodecContext *s, AVFrame *frame,
int flags)
3116 return avcodec_default_get_buffer2(s, frame, flags);
3125 AVCodec *codec = ist->
dec;
3127 snprintf(error, error_len,
"Decoder (codec %s) not found for input stream #%d:%d",
3129 return AVERROR(EINVAL);
3135 #if LIBAVCODEC_VERSION_MAJOR < 60
3136 ist->
dec_ctx->thread_safe_callbacks = 1;
3139 av_opt_set_int(ist->
dec_ctx,
"refcounted_frames", 1, 0);
3140 if (ist->
dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
3142 av_dict_set(&ist->
decoder_opts,
"compute_edt",
"1", AV_DICT_DONT_OVERWRITE);
3144 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");
3147 av_dict_set(&ist->
decoder_opts,
"sub_text_format",
"ass", AV_DICT_DONT_OVERWRITE);
3151 ist->
dec_ctx->pkt_timebase = ist->
st->time_base;
3153 if (!av_dict_get(ist->
decoder_opts,
"threads", NULL, 0))
3156 if (ist->
st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3161 snprintf(error, error_len,
"Device setup failed for "
3162 "decoder on input stream #%d:%d : %s",
3168 if (
ret == AVERROR_EXPERIMENTAL)
3171 snprintf(error, error_len,
3172 "Error while opening decoder for input stream "
3195 return FFDIFFSIGN(*(
const int64_t *)a, *(
const int64_t *)b);
3203 for (i = 0; i < of->
ctx->nb_streams; i++) {
3211 ret = avformat_write_header(of->
ctx, &of->
opts);
3213 av_log(NULL, AV_LOG_ERROR,
3214 "Could not write header for output file #%d "
3215 "(incorrect codec parameters ?): %s\n",
3229 for (i = 0; i < of->
ctx->nb_streams; i++) {
3238 av_fifo_generic_read(ost->
muxing_queue, &pkt,
sizeof(pkt), NULL);
3249 AVBSFContext *ctx = ost->
bsf_ctx;
3255 ret = avcodec_parameters_copy(ctx->par_in, ost->
st->codecpar);
3259 ctx->time_base_in = ost->
st->time_base;
3261 ret = av_bsf_init(ctx);
3263 av_log(NULL, AV_LOG_ERROR,
"Error initializing bitstream filter: %s\n",
3268 ret = avcodec_parameters_copy(ost->
st->codecpar, ctx->par_out);
3272 ost->
st->time_base = ctx->time_base_out;
3281 AVCodecParameters *par_dst = ost->
st->codecpar;
3282 AVCodecParameters *par_src = ost->
ref_par;
3285 uint32_t codec_tag = par_dst->codec_tag;
3287 av_assert0(ist && !ost->
filter);
3289 ret = avcodec_parameters_to_context(ost->
enc_ctx, ist->
st->codecpar);
3293 av_log(NULL, AV_LOG_FATAL,
3294 "Error setting up codec context options.\n");
3298 ret = avcodec_parameters_from_context(par_src, ost->
enc_ctx);
3300 av_log(NULL, AV_LOG_FATAL,
3301 "Error getting reference codec parameters.\n");
3306 unsigned int codec_tag_tmp;
3307 if (!of->
ctx->oformat->codec_tag ||
3308 av_codec_get_id (of->
ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
3309 !av_codec_get_tag2(of->
ctx->oformat->codec_tag, par_src->codec_id, &codec_tag_tmp))
3310 codec_tag = par_src->codec_tag;
3313 ret = avcodec_parameters_copy(par_dst, par_src);
3317 par_dst->codec_tag = codec_tag;
3323 ret = avformat_transfer_internal_stream_timing_info(of->
ctx->oformat, ost->
st, ist->
st,
copy_tb);
3328 if (ost->
st->time_base.num <= 0 || ost->
st->time_base.den <= 0)
3329 ost->
st->time_base = av_add_q(av_stream_get_codec_timebase(ost->
st), (AVRational){0, 1});
3332 if (ost->
st->duration <= 0 && ist->
st->duration > 0)
3333 ost->
st->duration = av_rescale_q(ist->
st->duration, ist->
st->time_base, ost->
st->time_base);
3336 ost->
st->disposition = ist->
st->disposition;
3338 if (ist->
st->nb_side_data) {
3339 for (i = 0; i < ist->
st->nb_side_data; i++) {
3340 const AVPacketSideData *sd_src = &ist->
st->side_data[i];
3343 dst_data = av_stream_new_side_data(ost->
st, sd_src->type, sd_src->size);
3345 return AVERROR(ENOMEM);
3346 memcpy(dst_data, sd_src->data, sd_src->size);
3351 uint8_t *sd = av_stream_new_side_data(ost->
st, AV_PKT_DATA_DISPLAYMATRIX,
3352 sizeof(int32_t) * 9);
3357 switch (par_dst->codec_type) {
3358 case AVMEDIA_TYPE_AUDIO:
3360 av_log(NULL, AV_LOG_FATAL,
"-acodec copy and -vol are incompatible (frames are not decoded)\n");
3363 if((par_dst->block_align == 1 || par_dst->block_align == 1152 || par_dst->block_align == 576) && par_dst->codec_id == AV_CODEC_ID_MP3)
3364 par_dst->block_align= 0;
3365 if(par_dst->codec_id == AV_CODEC_ID_AC3)
3366 par_dst->block_align= 0;
3368 case AVMEDIA_TYPE_VIDEO:
3372 (AVRational){ par_dst->height, par_dst->width });
3373 av_log(NULL, AV_LOG_WARNING,
"Overriding aspect ratio "
3374 "with stream copy may produce invalid files\n");
3376 else if (ist->
st->sample_aspect_ratio.num)
3377 sar = ist->
st->sample_aspect_ratio;
3379 sar = par_src->sample_aspect_ratio;
3380 ost->
st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
3381 ost->
st->avg_frame_rate = ist->
st->avg_frame_rate;
3382 ost->
st->r_frame_rate = ist->
st->r_frame_rate;
3393 AVDictionaryEntry *e;
3395 uint8_t *encoder_string;
3396 int encoder_string_len;
3397 int format_flags = 0;
3398 int codec_flags = ost->
enc_ctx->flags;
3400 if (av_dict_get(ost->
st->metadata,
"encoder", NULL, 0))
3403 e = av_dict_get(of->
opts,
"fflags", NULL, 0);
3405 const AVOption *o = av_opt_find(of->
ctx,
"fflags", NULL, 0, 0);
3408 av_opt_eval_flags(of->
ctx, o, e->value, &format_flags);
3412 const AVOption *o = av_opt_find(ost->
enc_ctx,
"flags", NULL, 0, 0);
3415 av_opt_eval_flags(ost->
enc_ctx, o, e->value, &codec_flags);
3418 encoder_string_len =
sizeof(LIBAVCODEC_IDENT) + strlen(ost->
enc->name) + 2;
3419 encoder_string = av_mallocz(encoder_string_len);
3420 if (!encoder_string)
3423 if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & AV_CODEC_FLAG_BITEXACT))
3424 av_strlcpy(encoder_string, LIBAVCODEC_IDENT
" ", encoder_string_len);
3426 av_strlcpy(encoder_string,
"Lavc ", encoder_string_len);
3427 av_strlcat(encoder_string, ost->
enc->name, encoder_string_len);
3428 av_dict_set(&ost->
st->metadata,
"encoder", encoder_string,
3429 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
3433 AVCodecContext *avctx)
3436 int n = 1, i, size, index = 0;
3439 for (p = kf; *p; p++)
3443 pts = av_malloc_array(size,
sizeof(*
pts));
3445 av_log(NULL, AV_LOG_FATAL,
"Could not allocate forced key frames array.\n");
3450 for (i = 0; i < n; i++) {
3451 char *next = strchr(p,
',');
3456 if (!memcmp(p,
"chapters", 8)) {
3461 if (avf->nb_chapters > INT_MAX - size ||
3462 !(
pts = av_realloc_f(
pts, size += avf->nb_chapters - 1,
3464 av_log(NULL, AV_LOG_FATAL,
3465 "Could not allocate forced key frames array.\n");
3469 t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3471 for (j = 0; j < avf->nb_chapters; j++) {
3472 AVChapter *c = avf->chapters[j];
3473 av_assert1(index < size);
3474 pts[index++] = av_rescale_q(c->start, c->time_base,
3475 avctx->time_base) + t;
3481 av_assert1(index < size);
3482 pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3489 av_assert0(index == size);
3498 AVCodecContext *enc_ctx = ost->
enc_ctx;
3499 AVFormatContext *oc;
3508 enc_ctx->time_base = ist->
st->time_base;
3513 av_log(oc, AV_LOG_WARNING,
"Input stream data not available, using default time base\n");
3516 enc_ctx->time_base = default_time_base;
3522 AVCodecContext *enc_ctx = ost->
enc_ctx;
3523 AVCodecContext *
dec_ctx = NULL;
3532 av_dict_set(&ost->
st->metadata,
"rotate", NULL, 0);
3535 ost->
st->disposition = ist->
st->disposition;
3539 enc_ctx->chroma_sample_location =
dec_ctx->chroma_sample_location;
3541 for (j = 0; j < oc->nb_streams; j++) {
3542 AVStream *
st = oc->streams[j];
3543 if (
st != ost->
st &&
st->codecpar->codec_type == ost->
st->codecpar->codec_type)
3546 if (j == oc->nb_streams)
3547 if (ost->
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
3548 ost->
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
3549 ost->
st->disposition = AV_DISPOSITION_DEFAULT;
3552 if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3561 av_log(NULL, AV_LOG_WARNING,
3563 "about the input framerate is available. Falling "
3564 "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
3565 "if you want a different framerate.\n",
3574 if (ost->
enc->supported_framerates && !ost->
force_fps) {
3575 int idx = av_find_nearest_q_idx(ost->
frame_rate, ost->
enc->supported_framerates);
3579 if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
3585 switch (enc_ctx->codec_type) {
3586 case AVMEDIA_TYPE_AUDIO:
3587 enc_ctx->sample_fmt = av_buffersink_get_format(ost->
filter->
filter);
3589 enc_ctx->bits_per_raw_sample = FFMIN(
dec_ctx->bits_per_raw_sample,
3590 av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
3591 enc_ctx->sample_rate = av_buffersink_get_sample_rate(ost->
filter->
filter);
3592 enc_ctx->channel_layout = av_buffersink_get_channel_layout(ost->
filter->
filter);
3593 enc_ctx->channels = av_buffersink_get_channels(ost->
filter->
filter);
3598 case AVMEDIA_TYPE_VIDEO:
3601 if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
3602 enc_ctx->time_base = av_buffersink_get_time_base(ost->
filter->
filter);
3605 av_log(oc, AV_LOG_WARNING,
"Frame rate very high for a muxer not efficiently supporting it.\n"
3606 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3609 enc_ctx->width = av_buffersink_get_w(ost->
filter->
filter);
3610 enc_ctx->height = av_buffersink_get_h(ost->
filter->
filter);
3611 enc_ctx->sample_aspect_ratio = ost->
st->sample_aspect_ratio =
3614 av_buffersink_get_sample_aspect_ratio(ost->
filter->
filter);
3616 enc_ctx->pix_fmt = av_buffersink_get_format(ost->
filter->
filter);
3618 enc_ctx->bits_per_raw_sample = FFMIN(
dec_ctx->bits_per_raw_sample,
3619 av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
3622 enc_ctx->color_range = frame->color_range;
3623 enc_ctx->color_primaries = frame->color_primaries;
3624 enc_ctx->color_trc = frame->color_trc;
3625 enc_ctx->colorspace = frame->colorspace;
3626 enc_ctx->chroma_sample_location = frame->chroma_location;
3634 enc_ctx->width !=
dec_ctx->width ||
3635 enc_ctx->height !=
dec_ctx->height ||
3636 enc_ctx->pix_fmt !=
dec_ctx->pix_fmt) {
3641 enc_ctx->field_order = AV_FIELD_BB;
3643 enc_ctx->field_order = AV_FIELD_TT;
3647 if (enc_ctx->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
3651 if (frame->interlaced_frame) {
3652 if (enc_ctx->codec->id == AV_CODEC_ID_MJPEG)
3653 enc_ctx->field_order = frame->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
3655 enc_ctx->field_order = frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
3657 enc_ctx->field_order = AV_FIELD_PROGRESSIVE;
3665 av_log(NULL, AV_LOG_ERROR,
3681 case AVMEDIA_TYPE_SUBTITLE:
3682 enc_ctx->time_base = AV_TIME_BASE_Q;
3683 if (!enc_ctx->width) {
3688 case AVMEDIA_TYPE_DATA:
3705 AVCodec *codec = ost->
enc;
3706 AVCodecContext *
dec = NULL;
3715 if (
dec &&
dec->subtitle_header) {
3717 ost->
enc_ctx->subtitle_header = av_mallocz(
dec->subtitle_header_size + 1);
3718 if (!ost->
enc_ctx->subtitle_header)
3719 return AVERROR(ENOMEM);
3720 memcpy(ost->
enc_ctx->subtitle_header,
dec->subtitle_header,
dec->subtitle_header_size);
3721 ost->
enc_ctx->subtitle_header_size =
dec->subtitle_header_size;
3723 if (!av_dict_get(ost->
encoder_opts,
"threads", NULL, 0))
3725 if (ost->
enc->type == AVMEDIA_TYPE_AUDIO &&
3733 snprintf(error, error_len,
"Device setup failed for "
3734 "encoder on output stream #%d:%d : %s",
3739 if (ist && ist->
dec->type == AVMEDIA_TYPE_SUBTITLE && ost->
enc->type == AVMEDIA_TYPE_SUBTITLE) {
3740 int input_props = 0, output_props = 0;
3741 AVCodecDescriptor
const *input_descriptor =
3742 avcodec_descriptor_get(
dec->codec_id);
3743 AVCodecDescriptor
const *output_descriptor =
3744 avcodec_descriptor_get(ost->
enc_ctx->codec_id);
3745 if (input_descriptor)
3746 input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3747 if (output_descriptor)
3748 output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3749 if (input_props && output_props && input_props != output_props) {
3750 snprintf(error, error_len,
3751 "Subtitle encoding currently only possible from text to text "
3752 "or bitmap to bitmap");
3753 return AVERROR_INVALIDDATA;
3758 if (
ret == AVERROR_EXPERIMENTAL)
3760 snprintf(error, error_len,
3761 "Error while opening encoder for output stream #%d:%d - "
3762 "maybe incorrect parameters such as bit_rate, rate, width or height",
3766 if (ost->
enc->type == AVMEDIA_TYPE_AUDIO &&
3767 !(ost->
enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
3772 ost->
enc_ctx->codec_id != AV_CODEC_ID_CODEC2 )
3773 av_log(NULL, AV_LOG_WARNING,
"The bitrate parameter is set too low."
3774 " It takes bits/s as argument, not kbits/s\n");
3776 ret = avcodec_parameters_from_context(ost->
st->codecpar, ost->
enc_ctx);
3778 av_log(NULL, AV_LOG_FATAL,
3779 "Error initializing the output stream codec context.\n");
3783 if (ost->
enc_ctx->nb_coded_side_data) {
3786 for (i = 0; i < ost->
enc_ctx->nb_coded_side_data; i++) {
3787 const AVPacketSideData *sd_src = &ost->
enc_ctx->coded_side_data[i];
3790 dst_data = av_stream_new_side_data(ost->
st, sd_src->type, sd_src->size);
3792 return AVERROR(ENOMEM);
3793 memcpy(dst_data, sd_src->data, sd_src->size);
3806 for (i = 0; i < ist->
st->nb_side_data; i++) {
3807 AVPacketSideData *sd = &ist->
st->side_data[i];
3808 if (sd->type != AV_PKT_DATA_CPB_PROPERTIES) {
3809 uint8_t *dst = av_stream_new_side_data(ost->
st, sd->type, sd->size);
3811 return AVERROR(ENOMEM);
3812 memcpy(dst, sd->data, sd->size);
3813 if (ist->
autorotate && sd->type == AV_PKT_DATA_DISPLAYMATRIX)
3814 av_display_rotation_set((uint32_t *)dst, 0);
3820 if (ost->
st->time_base.num <= 0 || ost->
st->time_base.den <= 0)
3821 ost->
st->time_base = av_add_q(ost->
enc_ctx->time_base, (AVRational){0, 1});
3824 if (ost->
st->duration <= 0 && ist && ist->
st->duration > 0)
3825 ost->
st->duration = av_rescale_q(ist->
st->duration, ist->
st->time_base, ost->
st->time_base);
3834 static const AVOption opts[] = {
3835 {
"disposition" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, (double)INT64_MAX, .unit =
"flags" },
3836 {
"default" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT }, .unit =
"flags" },
3837 {
"dub" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB }, .unit =
"flags" },
3838 {
"original" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL }, .unit =
"flags" },
3839 {
"comment" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT }, .unit =
"flags" },
3840 {
"lyrics" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS }, .unit =
"flags" },
3841 {
"karaoke" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE }, .unit =
"flags" },
3842 {
"forced" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED }, .unit =
"flags" },
3843 {
"hearing_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED }, .unit =
"flags" },
3844 {
"visual_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED }, .unit =
"flags" },
3845 {
"clean_effects" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS }, .unit =
"flags" },
3846 {
"attached_pic" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ATTACHED_PIC }, .unit =
"flags" },
3847 {
"captions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS }, .unit =
"flags" },
3848 {
"descriptions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS }, .unit =
"flags" },
3849 {
"dependent" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEPENDENT }, .unit =
"flags" },
3850 {
"metadata" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA }, .unit =
"flags" },
3853 static const AVClass
class = {
3855 .item_name = av_default_item_name,
3857 .version = LIBAVUTIL_VERSION_INT,
3859 const AVClass *pclass = &
class;
3861 ret = av_opt_eval_flags(&pclass, &opts[0], ost->
disposition, &ost->
st->disposition);
3885 AVStream *st = file->
ctx->streams[pkt->stream_index];
3889 av_log(file->
ctx, AV_LOG_WARNING,
3890 "New %s stream %d:%d at pos:%"PRId64
" and DTS:%ss\n",
3891 av_get_media_type_string(st->codecpar->codec_type),
3892 input_index, pkt->stream_index,
3893 pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
3899 int ret = 0, i, j, k;
3900 AVFormatContext *oc;
3903 char error[1024] = {0};
3961 for (j = 0; j < ifile->
ctx->nb_programs; j++) {
3962 AVProgram *p = ifile->
ctx->programs[j];
3963 int discard = AVDISCARD_ALL;
3965 for (k = 0; k < p->nb_stream_indexes; k++)
3967 discard = AVDISCARD_DEFAULT;
3970 p->discard = discard;
3977 if (oc->oformat->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
3986 av_log(NULL, AV_LOG_INFO,
"Stream mapping:\n");
3992 av_log(NULL, AV_LOG_INFO,
" Stream #%d:%d (%s) -> %s",
3997 av_log(NULL, AV_LOG_INFO,
"\n");
4007 av_log(NULL, AV_LOG_INFO,
" File %s -> Stream #%d:%d\n",
4014 av_log(NULL, AV_LOG_INFO,
" %s", ost->
filter->
name);
4018 av_log(NULL, AV_LOG_INFO,
" -> Stream #%d:%d (%s)\n", ost->
file_index,
4023 av_log(NULL, AV_LOG_INFO,
" Stream #%d:%d -> #%d:%d",
4029 av_log(NULL, AV_LOG_INFO,
" [sync #%d:%d]",
4033 av_log(NULL, AV_LOG_INFO,
" (copy)");
4036 const AVCodec *out_codec = ost->
enc;
4037 const char *decoder_name =
"?";
4038 const char *in_codec_name =
"?";
4039 const char *encoder_name =
"?";
4040 const char *out_codec_name =
"?";
4041 const AVCodecDescriptor *desc;
4044 decoder_name = in_codec->name;
4045 desc = avcodec_descriptor_get(in_codec->id);
4047 in_codec_name = desc->name;
4048 if (!strcmp(decoder_name, in_codec_name))
4049 decoder_name =
"native";
4053 encoder_name = out_codec->name;
4054 desc = avcodec_descriptor_get(out_codec->id);
4056 out_codec_name = desc->name;
4057 if (!strcmp(encoder_name, out_codec_name))
4058 encoder_name =
"native";
4061 av_log(NULL, AV_LOG_INFO,
" (%s (%s) -> %s (%s))",
4062 in_codec_name, decoder_name,
4063 out_codec_name, encoder_name);
4065 av_log(NULL, AV_LOG_INFO,
"\n");
4069 av_log(NULL, AV_LOG_ERROR,
"%s\n", error);
4093 for (j = 0; j < of->
ctx->nb_streams; j++)
4112 int64_t opts_min = INT64_MAX;
4117 int64_t opts = ost->
st->cur_dts == AV_NOPTS_VALUE ? INT64_MIN :
4118 av_rescale_q(ost->
st->cur_dts, ost->
st->time_base,
4120 if (ost->
st->cur_dts == AV_NOPTS_VALUE)
4121 av_log(NULL, AV_LOG_DEBUG,
4122 "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",
4128 if (!ost->
finished && opts < opts_min) {
4140 if (tcgetattr(0, &tty) == 0) {
4141 if (on) tty.c_lflag |= ECHO;
4142 else tty.c_lflag &= ~ECHO;
4143 tcsetattr(0, TCSANOW, &tty);
4152 return AVERROR_EXIT;
4160 return AVERROR_EXIT;
4161 if (key ==
'+') av_log_set_level(av_log_get_level()+10);
4162 if (key ==
'-') av_log_set_level(av_log_get_level()-10);
4171 av_log_set_level(AV_LOG_DEBUG);
4173 if (key ==
'c' || key ==
'C'){
4174 char buf[4096], target[64], command[256], arg[256] = {0};
4177 fprintf(stderr,
"\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
4180 while ((k =
read_key()) !=
'\n' && k !=
'\r' && i <
sizeof(buf)-1)
4185 fprintf(stderr,
"\n");
4187 (n = sscanf(buf,
"%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
4188 av_log(NULL, AV_LOG_DEBUG,
"Processing command target:%s time:%f command:%s arg:%s",
4189 target, time, command, arg);
4194 ret = avfilter_graph_send_command(fg->
graph, target, command, arg, buf,
sizeof(buf),
4195 key ==
'c' ? AVFILTER_CMD_FLAG_ONE : 0);
4196 fprintf(stderr,
"Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
4197 }
else if (key ==
'c') {
4198 fprintf(stderr,
"Queuing commands only on filters supporting the specific command is unsupported\n");
4199 ret = AVERROR_PATCHWELCOME;
4201 ret = avfilter_graph_queue_command(fg->
graph, target, command, arg, 0, time);
4203 fprintf(stderr,
"Queuing command failed with error %s\n", av_err2str(ret));
4208 av_log(NULL, AV_LOG_ERROR,
4209 "Parse error, at least 3 arguments were expected, "
4210 "only %d given in string '%s'\n", n, buf);
4213 if (key ==
'd' || key ==
'D'){
4217 if(!debug) debug = 1;
4218 while (debug & FF_DEBUG_DCT_COEFF)
4225 while ((k =
read_key()) !=
'\n' && k !=
'\r' && i <
sizeof(buf)-1)
4230 fprintf(stderr,
"\n");
4231 if (k <= 0 || sscanf(buf,
"%d", &debug)!=1)
4232 fprintf(stderr,
"error parsing debug value\n");
4241 if(debug) av_log_set_level(AV_LOG_DEBUG);
4242 fprintf(stderr,
"debug=%d\n", debug);
4245 fprintf(stderr,
"key function\n"
4246 "? show this help\n"
4247 "+ increase verbosity\n"
4248 "- decrease verbosity\n"
4249 "c Send command to first matching filter supporting it\n"
4250 "C Send/Queue command to all matching filters\n"
4251 "D cycle through available debug modes\n"
4252 "h dump packets/hex press to cycle through the 3 states\n"
4254 "s Show QP histogram\n"
4261 static void *input_thread(
void *arg)
4264 unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
4269 ret = av_read_frame(f->
ctx, &pkt);
4271 if (ret == AVERROR(EAGAIN)) {
4276 av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
4279 ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
4280 if (flags && ret == AVERROR(EAGAIN)) {
4282 ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
4283 av_log(f->
ctx, AV_LOG_WARNING,
4284 "Thread message queue blocking; consider raising the "
4285 "thread_queue_size option (current value: %d)\n",
4286 f->thread_queue_size);
4289 if (ret != AVERROR_EOF)
4290 av_log(f->
ctx, AV_LOG_ERROR,
4291 "Unable to send packet to main thread: %s\n",
4293 av_packet_unref(&pkt);
4294 av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
4302 static void free_input_thread(
int i)
4307 if (!f || !f->in_thread_queue)
4309 av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
4310 while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
4311 av_packet_unref(&pkt);
4313 pthread_join(f->thread, NULL);
4315 av_thread_message_queue_free(&f->in_thread_queue);
4318 static void free_input_threads(
void)
4323 free_input_thread(i);
4326 static int init_input_thread(
int i)
4331 if (f->thread_queue_size < 0)
4333 if (!f->thread_queue_size)
4336 if (f->
ctx->pb ? !f->
ctx->pb->seekable :
4337 strcmp(f->
ctx->iformat->name,
"lavfi"))
4338 f->non_blocking = 1;
4339 ret = av_thread_message_queue_alloc(&f->in_thread_queue,
4340 f->thread_queue_size,
sizeof(AVPacket));
4344 if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
4345 av_log(NULL, AV_LOG_ERROR,
"pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
4346 av_thread_message_queue_free(&f->in_thread_queue);
4347 return AVERROR(ret);
4353 static int init_input_threads(
void)
4358 ret = init_input_thread(i);
4365 static int get_input_packet_mt(
InputFile *f, AVPacket *pkt)
4367 return av_thread_message_queue_recv(f->in_thread_queue, pkt,
4369 AV_THREAD_MESSAGE_NONBLOCK : 0);
4379 int64_t pts = av_rescale(ist->
dts, 1000000, AV_TIME_BASE);
4380 int64_t now = av_gettime_relative() - ist->
start;
4382 return AVERROR(EAGAIN);
4387 if (f->thread_queue_size)
4388 return get_input_packet_mt(f, pkt);
4390 return av_read_frame(f->
ctx, pkt);
4412 static AVRational
duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
4413 AVRational time_base)
4419 return tmp_time_base;
4422 ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
4425 return tmp_time_base;
4434 AVCodecContext *avctx;
4435 int i, ret, has_audio = 0;
4436 int64_t duration = 0;
4438 ret = avformat_seek_file(is, -1, INT64_MIN, is->start_time, is->start_time, 0);
4449 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->
nb_samples)
4458 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->
nb_samples) {
4467 duration = av_rescale_q(1, av_inv_q(ist->
framerate), ist->
st->time_base);
4468 }
else if (ist->
st->avg_frame_rate.num) {
4469 duration = av_rescale_q(1, av_inv_q(ist->
st->avg_frame_rate), ist->
st->time_base);
4484 if (ifile->
loop > 0)
4500 AVFormatContext *is;
4503 int ret, thread_ret, i, j;
4506 int disable_discontinuity_correction =
copy_ts;
4511 if (ret == AVERROR(EAGAIN)) {
4515 if (ret < 0 && ifile->loop) {
4516 AVCodecContext *avctx;
4524 avcodec_flush_buffers(avctx);
4528 free_input_thread(file_index);
4532 thread_ret = init_input_thread(file_index);
4537 av_log(NULL, AV_LOG_WARNING,
"Seek to start failed.\n");
4540 if (ret == AVERROR(EAGAIN)) {
4546 if (ret != AVERROR_EOF) {
4571 return AVERROR(EAGAIN);
4577 av_pkt_dump_log2(NULL, AV_LOG_INFO, &pkt,
do_hex_dump,
4578 is->streams[pkt.stream_index]);
4584 goto discard_packet;
4593 goto discard_packet;
4595 if (pkt.flags & AV_PKT_FLAG_CORRUPT) {
4597 "%s: corrupt input packet in stream %d\n", is->url, pkt.stream_index);
4603 av_log(NULL, AV_LOG_INFO,
"demuxer -> ist_index:%d type:%s "
4604 "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",
4605 ifile->
ist_index + pkt.stream_index, av_get_media_type_string(ist->
dec_ctx->codec_type),
4608 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->
st->time_base),
4609 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->
st->time_base),
4615 int64_t stime, stime2;
4619 if ( ist->
next_dts == AV_NOPTS_VALUE
4621 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
4622 int64_t new_start_time = INT64_MAX;
4623 for (i=0; i<is->nb_streams; i++) {
4624 AVStream *st = is->streams[i];
4625 if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
4627 new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
4629 if (new_start_time > is->start_time) {
4630 av_log(is, AV_LOG_VERBOSE,
"Correcting start time by %"PRId64
"\n", new_start_time - is->start_time);
4635 stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->
st->time_base);
4636 stime2= stime + (1ULL<<ist->
st->pts_wrap_bits);
4639 if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->
st->pts_wrap_bits-1))) {
4640 pkt.dts -= 1ULL<<ist->
st->pts_wrap_bits;
4643 if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->
st->pts_wrap_bits-1))) {
4644 pkt.pts -= 1ULL<<ist->
st->pts_wrap_bits;
4651 for (i = 0; i < ist->
st->nb_side_data; i++) {
4652 AVPacketSideData *src_sd = &ist->
st->side_data[i];
4655 if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
4658 if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
4661 dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
4665 memcpy(dst_data, src_sd->data, src_sd->size);
4669 if (pkt.dts != AV_NOPTS_VALUE)
4670 pkt.dts += av_rescale_q(ifile->
ts_offset, AV_TIME_BASE_Q, ist->
st->time_base);
4671 if (pkt.pts != AV_NOPTS_VALUE)
4672 pkt.pts += av_rescale_q(ifile->
ts_offset, AV_TIME_BASE_Q, ist->
st->time_base);
4674 if (pkt.pts != AV_NOPTS_VALUE)
4676 if (pkt.dts != AV_NOPTS_VALUE)
4679 pkt_dts = av_rescale_q_rnd(pkt.dts, ist->
st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4680 if ((ist->
dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
4681 ist->
dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
4682 pkt_dts != AV_NOPTS_VALUE && ist->
next_dts == AV_NOPTS_VALUE && !
copy_ts
4683 && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->
last_ts != AV_NOPTS_VALUE) {
4684 int64_t delta = pkt_dts - ifile->
last_ts;
4688 av_log(NULL, AV_LOG_DEBUG,
4689 "Inter stream timestamp discontinuity %"PRId64
", new offset= %"PRId64
"\n",
4691 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->
st->time_base);
4692 if (pkt.pts != AV_NOPTS_VALUE)
4693 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->
st->time_base);
4698 if (pkt.pts != AV_NOPTS_VALUE) {
4699 pkt.pts += duration;
4704 if (pkt.dts != AV_NOPTS_VALUE)
4705 pkt.dts += duration;
4707 pkt_dts = av_rescale_q_rnd(pkt.dts, ist->
st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4709 if (
copy_ts && pkt_dts != AV_NOPTS_VALUE && ist->
next_dts != AV_NOPTS_VALUE &&
4710 (is->iformat->flags & AVFMT_TS_DISCONT) && ist->
st->pts_wrap_bits < 60) {
4711 int64_t wrap_dts = av_rescale_q_rnd(pkt.dts + (1LL<<ist->
st->pts_wrap_bits),
4712 ist->
st->time_base, AV_TIME_BASE_Q,
4713 AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4715 disable_discontinuity_correction = 0;
4718 if ((ist->
dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
4719 ist->
dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
4720 pkt_dts != AV_NOPTS_VALUE && ist->
next_dts != AV_NOPTS_VALUE &&
4721 !disable_discontinuity_correction) {
4722 int64_t delta = pkt_dts - ist->
next_dts;
4723 if (is->iformat->flags & AVFMT_TS_DISCONT) {
4726 pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->
pts, ist->
dts)) {
4728 av_log(NULL, AV_LOG_DEBUG,
4729 "timestamp discontinuity for stream #%d:%d "
4730 "(id=%d, type=%s): %"PRId64
", new offset= %"PRId64
"\n",
4732 av_get_media_type_string(ist->
dec_ctx->codec_type),
4734 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->
st->time_base);
4735 if (pkt.pts != AV_NOPTS_VALUE)
4736 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->
st->time_base);
4741 av_log(NULL, AV_LOG_WARNING,
"DTS %"PRId64
", next:%"PRId64
" st:%d invalid dropping\n", pkt.dts, ist->
next_dts, pkt.stream_index);
4742 pkt.dts = AV_NOPTS_VALUE;
4744 if (pkt.pts != AV_NOPTS_VALUE){
4745 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->
st->time_base, AV_TIME_BASE_Q);
4749 av_log(NULL, AV_LOG_WARNING,
"PTS %"PRId64
", next:%"PRId64
" invalid dropping st:%d\n", pkt.pts, ist->
next_dts, pkt.stream_index);
4750 pkt.pts = AV_NOPTS_VALUE;
4756 if (pkt.dts != AV_NOPTS_VALUE)
4757 ifile->
last_ts = av_rescale_q(pkt.dts, ist->
st->time_base, AV_TIME_BASE_Q);
4760 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",
4761 ifile->
ist_index + pkt.stream_index, av_get_media_type_string(ist->
dec_ctx->codec_type),
4762 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->
st->time_base),
4763 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->
st->time_base),
4773 av_packet_unref(&pkt);
4788 int nb_requests, nb_requests_max = 0;
4793 ret = avfilter_graph_request_oldest(graph->
graph);
4797 if (ret == AVERROR_EOF) {
4803 if (ret != AVERROR(EAGAIN))
4806 for (i = 0; i < graph->
nb_inputs; i++) {
4807 ifilter = graph->
inputs[i];
4812 nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->
filter);
4813 if (nb_requests > nb_requests_max) {
4814 nb_requests_max = nb_requests;
4844 av_log(NULL, AV_LOG_VERBOSE,
"No more inputs to read from, finishing.\n");
4852 av_log(NULL, AV_LOG_ERROR,
"Error reinitializing filters!\n");
4880 if (av_buffersink_get_type(ost->
filter->
filter) == AVMEDIA_TYPE_AUDIO)
4887 }
else if (ost->
filter) {
4906 if (ret == AVERROR(EAGAIN)) {
4913 return ret == AVERROR_EOF ? 0 : ret;
4924 AVFormatContext *os;
4927 int64_t timer_start;
4928 int64_t total_packets_written = 0;
4935 av_log(NULL, AV_LOG_INFO,
"Press [q] to stop, [?] for help\n");
4938 timer_start = av_gettime_relative();
4941 if ((ret = init_input_threads()) < 0)
4946 int64_t cur_time= av_gettime_relative();
4955 av_log(NULL, AV_LOG_VERBOSE,
"No more output streams to write to, finishing.\n");
4960 if (ret < 0 && ret != AVERROR_EOF) {
4961 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(ret));
4969 free_input_threads();
4987 av_log(NULL, AV_LOG_ERROR,
4988 "Nothing was written into output file %d (%s), because "
4989 "at least one of its streams received no packets.\n",
4993 if ((ret = av_write_trailer(os)) < 0) {
4994 av_log(NULL, AV_LOG_ERROR,
"Error writing trailer of %s: %s\n", os->url, av_err2str(ret));
5007 av_freep(&ost->
enc_ctx->stats_in);
5011 av_log(NULL, AV_LOG_FATAL,
"Empty output on stream %d.\n", i);
5017 av_log(NULL, AV_LOG_FATAL,
"Empty output\n");
5038 free_input_threads();
5047 av_log(NULL, AV_LOG_ERROR,
5048 "Error closing logfile, loss of information possible: %s\n",
5049 av_err2str(AVERROR(errno)));
5053 av_freep(&ost->
apad);
5069 struct rusage rusage;
5071 getrusage(RUSAGE_SELF, &rusage);
5073 (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
5075 (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
5076 #elif HAVE_GETPROCESSTIMES
5078 FILETIME c, e, k, u;
5079 proc = GetCurrentProcess();
5080 GetProcessTimes(proc, &c, &e, &k, &u);
5082 ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
5084 ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
5093 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
5094 struct rusage rusage;
5095 getrusage(RUSAGE_SELF, &rusage);
5096 return (int64_t)rusage.ru_maxrss * 1024;
5097 #elif HAVE_GETPROCESSMEMORYINFO
5099 PROCESS_MEMORY_COUNTERS memcounters;
5100 proc = GetCurrentProcess();
5101 memcounters.cb =
sizeof(memcounters);
5102 GetProcessMemoryInfo(proc, &memcounters,
sizeof(memcounters));
5103 return memcounters.PeakPagefileUsage;
5167 char _program_name[] =
"ffmpeg";
5171 #define OFFSET(x) offsetof(OptionsContext, x)
5189 {
"bsfs",
OPT_EXIT, { .func_arg =
show_bsfs },
"show available bit stream filters" },
5198 {
"report", 0, { .func_arg =
opt_report },
"generate a report" },
5199 {
"max_alloc",
HAS_ARG, { .func_arg =
opt_max_alloc },
"set maximum size of a single allocated block",
"bytes" },
5205 "list sources of the input device",
"device" },
5207 "list sinks of the output device",
"device" },
5212 "force format",
"fmt" },
5214 "overwrite output files" },
5216 "never overwrite output files" },
5218 "Ignore unknown stream types" },
5220 "Copy unknown stream types" },
5223 "codec name",
"codec" },
5226 "codec name",
"codec" },
5229 "preset name",
"preset" },
5232 "set input stream mapping",
5233 "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
5235 "map an audio channel from one stream to another",
"file.stream.channel[:syncfile.syncstream]" },
5238 "set metadata information of outfile from infile",
5239 "outfile[,metadata]:infile[,metadata]" },
5242 "set chapters mapping",
"input_file_index" },
5245 "record or transcode \"duration\" seconds of audio/video",
5248 "record or transcode stop time",
"time_stop" },
5250 "set the limit file size in bytes",
"limit_size" },
5253 "set the start time offset",
"time_off" },
5256 "set the start time offset relative to EOF",
"time_off" },
5259 "enable/disable seeking by timestamp with -ss" },
5262 "enable/disable accurate seeking with -ss" },
5265 "set the input ts offset",
"time_off" },
5268 "set the input ts scale",
"scale" },
5270 "set the recording timestamp ('now' to set the current time)",
"time" },
5272 "add metadata",
"string=string" },
5274 "add program with specified streams",
"title=string:st=number..." },
5277 "set the number of data frames to output",
"number" },
5279 "add timings for benchmarking" },
5281 "add timings for each task" },
5283 "write program-readable progress information",
"url" },
5285 "enable or disable interaction on standard input" },
5287 "set max runtime in seconds in CPU user time",
"limit" },
5289 "dump each input packet" },
5291 "when dumping packets, also dump the payload" },
5294 "read input at native frame rate",
"" },
5296 "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\" or \"dv50\" "
5297 "with optional prefixes \"pal-\", \"ntsc-\" or \"film-\")",
"type" },
5299 "video sync method",
"" },
5301 "frame drop threshold",
"" },
5303 "audio sync method",
"" },
5305 "audio drift threshold",
"threshold" },
5307 "copy timestamps" },
5309 "shift input timestamps to start at 0 when using copyts" },
5311 "copy input stream time base when stream copying",
"mode" },
5313 "shift input timestamps to start at 0 when using copyts" },
5315 "copy input stream time base when stream copying",
"mode" },
5318 "finish encoding within shortest input" },
5326 "timestamp discontinuity delta threshold",
"threshold" },
5328 "timestamp error delta threshold",
"threshold" },
5330 "exit on error",
"error" },
5332 "abort on the specified condition flags",
"flags" },
5335 "copy initial non-keyframes" },
5337 "copy or discard frames before start time" },
5339 "set the number of frames to output",
"number" },
5342 "force codec tag/fourcc",
"fourcc/tag" },
5345 "use fixed quality scale (VBR)",
"q" },
5348 "use fixed quality scale (VBR)",
"q" },
5350 "set profile",
"profile" },
5352 "set stream filtergraph",
"filter_graph" },
5354 "number of non-complex filter threads" },
5356 "read stream filtergraph description from a file",
"filename" },
5358 "reinit filtergraph on input parameter changes",
"" },
5360 "create a complex filtergraph",
"graph_description" },
5362 "number of threads for -filter_complex" },
5364 "create a complex filtergraph",
"graph_description" },
5366 "read complex filtergraph description from a file",
"filename" },
5368 "enable automatic conversion filters globally" },
5370 "print progress report during encoding", },
5372 "set the period at which ffmpeg updates stats and -progress output",
"time" },
5375 "add an attachment to the output file",
"filename" },
5378 "extract an attachment into a file",
"filename" },
5380 OPT_OFFSET, { .off =
OFFSET(loop) },
"set number of times input stream shall be looped",
"loop count" },
5382 "print timestamp debugging info" },
5384 "ratio of errors (0.0: no errors, 1.0: 100% errors) above which ffmpeg returns an error instead of success.",
"maximum error rate" },
5390 "disposition",
"" },
5392 { .off =
OFFSET(thread_queue_size) },
5393 "set the maximum number of queued packets from the demuxer" },
5395 "read and decode the streams to fill missing information with heuristics" },
5399 "set the number of video frames to output",
"number" },
5402 "set frame rate (Hz value, fraction or abbreviation)",
"rate" },
5405 "set frame size (WxH or abbreviation)",
"size" },
5408 "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)",
"aspect" },
5411 "set pixel format",
"format" },
5413 "set the number of bits per raw sample",
"number" },
5415 "deprecated use -g 1" },
5420 "rate control override for specific intervals",
"override" },
5423 "force video codec ('copy' to copy stream)",
"codec" },
5429 "set initial TimeCode value.",
"hh:mm:ss[:;.]ff" },
5431 "select the pass number (1 to 3)",
"n" },
5434 "select two pass log file name prefix",
"prefix" },
5436 "this option is deprecated, use the yadif filter instead" },
5438 "calculate PSNR of compressed frames" },
5440 "dump video coding statistics to file" },
5442 "dump video coding statistics to file",
"file" },
5444 "Version of the vstats format to use."},
5446 "set video filters",
"filter_graph" },
5449 "specify intra matrix coeffs",
"matrix" },
5452 "specify inter matrix coeffs",
"matrix" },
5455 "specify intra matrix coeffs",
"matrix" },
5458 "top=1/bottom=0/auto=-1 field first",
"" },
5461 "force video tag/fourcc",
"fourcc/tag" },
5463 "show QP histogram" },
5466 "force the selected framerate, disable the best supported framerate selection" },
5469 "set the value of an outfile streamid",
"streamIndex:value" },
5472 "force key frames at specified timestamps",
"timestamps" },
5474 "audio bitrate (please use -b:a)",
"bitrate" },
5476 "video bitrate (please use -b:v)",
"bitrate" },
5479 "use HW accelerated decoding",
"hwaccel name" },
5482 "select a device for HW acceleration",
"devicename" },
5485 "select output format used with HW accelerated decoding",
"format" },
5486 #if CONFIG_VIDEOTOOLBOX
5490 "show available HW acceleration methods" },
5493 "automatically insert correct rotate filters" },
5496 "automatically insert a scale filter at the end of the filter graph" },
5500 "set the number of audio frames to output",
"number" },
5502 "set audio quality (codec-specific)",
"quality", },
5505 "set audio sampling rate (in Hz)",
"rate" },
5508 "set number of audio channels",
"channels" },
5513 "force audio codec ('copy' to copy stream)",
"codec" },
5516 "force audio tag/fourcc",
"fourcc/tag" },
5518 "change audio volume (256=normal)" ,
"volume" },
5521 "set sample format",
"format" },
5524 "set channel layout",
"layout" },
5526 "set audio filters",
"filter_graph" },
5528 "set the maximum number of channels to try to guess the channel layout" },
5532 "disable subtitle" },
5534 "force subtitle codec ('copy' to copy stream)",
"codec" },
5536 ,
"force subtitle tag/fourcc",
"fourcc/tag" },
5538 "fix subtitles duration" },
5540 "set canvas size (WxH or abbreviation)",
"size" },
5544 "deprecated, use -channel",
"channel" },
5546 "deprecated, use -standard",
"standard" },
5551 "set the maximum demux-decode delay",
"seconds" },
5553 "set the initial demux-decode delay",
"seconds" },
5555 "specify a file in which to print sdp information",
"file" },
5558 "set the desired time base hint for output stream (1:24, 1:48000 or 0.04166, 2.0833e-5)",
"ratio" },
5560 "set the desired time base for the encoder (1:24, 1:48000 or 0.04166, 2.0833e-5). "
5561 "two special values are defined - "
5562 "0 = use frame rate (video) or sample rate (audio),"
5563 "-1 = match source time base",
"ratio" },
5566 "A comma-separated list of bitstream filters",
"bitstream_filters" },
5568 "deprecated",
"audio bitstream_filters" },
5570 "deprecated",
"video bitstream_filters" },
5573 "set the audio options to the indicated preset",
"preset" },
5575 "set the video options to the indicated preset",
"preset" },
5577 "set the subtitle options to the indicated preset",
"preset" },
5579 "set options from indicated preset file",
"filename" },
5582 "maximum number of packets that can be buffered while waiting for all streams to initialize",
"packets" },
5584 "set the threshold after which max_muxing_queue_size is taken into account",
"bytes" },
5588 "force data codec ('copy' to copy stream)",
"codec" },
5594 "set VAAPI hardware device (DRM path or X11 display name)",
"device" },
5599 "set QSV hardware device (DirectX adapter index, DRM path or X11 display name)",
"device"},
5603 "initialise hardware device",
"args" },
5605 "set hardware device used when filtering",
"device" },
5616 if (savedCode == 0) {
5624 setvbuf(stderr,NULL,_IONBF,0);
5626 av_log_set_flags(AV_LOG_SKIP_REPEATED);
5629 if(argc>1 && !strcmp(argv[1],
"-d")){
5637 avdevice_register_all();
5639 avformat_network_init();
5650 av_log(NULL, AV_LOG_WARNING,
"Use -h to get full help or, even better, run 'man %s'\n",
program_name);
5656 av_log(NULL, AV_LOG_FATAL,
"At least one output file must be specified\n");
5661 if (strcmp(
output_files[i]->ctx->oformat->name,
"rtp"))
5669 int64_t utime, stime, rtime;
5674 av_log(NULL, AV_LOG_INFO,
5675 "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
5676 utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
5678 av_log(NULL, AV_LOG_DEBUG,
"%"PRIu64
" frames successfully decoded, %"PRIu64
" decoding errors\n",
__thread jmp_buf ex_buf__
#define avformat_close_input
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