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
109#include <sys/types.h>
110#include <sys/resource.h>
111#elif HAVE_GETPROCESSTIMES
114#if HAVE_GETPROCESSMEMORYINFO
118#if HAVE_SETCONSOLECTRLHANDLER
124#include <sys/select.h>
129#include <sys/ioctl.h>
141#include "libavutil/avassert.h"
203extern int opt_map(
void *optctx,
const char *opt,
const char *arg);
204extern int opt_map_channel(
void *optctx,
const char *opt,
const char *arg);
206extern int opt_data_frames(
void *optctx,
const char *opt,
const char *arg);
207extern int opt_progress(
void *optctx,
const char *opt,
const char *arg);
208extern int opt_target(
void *optctx,
const char *opt,
const char *arg);
209extern int opt_vsync(
void *optctx,
const char *opt,
const char *arg);
210extern int opt_abort_on(
void *optctx,
const char *opt,
const char *arg);
212extern int opt_qscale(
void *optctx,
const char *opt,
const char *arg);
213extern int opt_profile(
void *optctx,
const char *opt,
const char *arg);
216extern int opt_attach(
void *optctx,
const char *opt,
const char *arg);
219extern int opt_video_codec(
void *optctx,
const char *opt,
const char *arg);
220extern int opt_sameq(
void *optctx,
const char *opt,
const char *arg);
221extern int opt_timecode(
void *optctx,
const char *opt,
const char *arg);
223extern int opt_vstats_file(
void *optctx,
const char *opt,
const char *arg);
224extern int opt_vstats(
void *optctx,
const char *opt,
const char *arg);
226extern int opt_old2new(
void *optctx,
const char *opt,
const char *arg);
227extern int opt_streamid(
void *optctx,
const char *opt,
const char *arg);
228extern int opt_bitrate(
void *optctx,
const char *opt,
const char *arg);
229extern int show_hwaccels(
void *optctx,
const char *opt,
const char *arg);
233extern int opt_audio_codec(
void *optctx,
const char *opt,
const char *arg);
235extern int opt_preset(
void *optctx,
const char *opt,
const char *arg);
240extern int opt_sdp_file(
void *optctx,
const char *opt,
const char *arg);
241extern int opt_data_codec(
void *optctx,
const char *opt,
const char *arg);
249__thread
struct termios oldtty;
250__thread
int restore_tty;
254static void free_input_threads(
void);
275 AVFrame *frame =
ist->sub2video.frame;
277 av_frame_unref(frame);
278 ist->sub2video.frame->width =
ist->dec_ctx->width ?
ist->dec_ctx->width :
ist->sub2video.w;
279 ist->sub2video.frame->height =
ist->dec_ctx->height ?
ist->dec_ctx->height :
ist->sub2video.h;
280 ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
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];
320 AVFrame *frame =
ist->sub2video.frame;
324 av_assert1(frame->data[0]);
325 ist->sub2video.last_pts = frame->pts = pts;
326 for (i = 0; i <
ist->nb_filters; i++) {
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",
338 AVFrame *frame =
ist->sub2video.frame;
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;
357 pts =
ist->sub2video.initialize ?
358 heartbeat_pts :
ist->sub2video.end_pts;
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++)
372 ist->sub2video.end_pts = end_pts;
373 ist->sub2video.initialize = 0;
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);
413 if (
ist->sub2video.end_pts < INT64_MAX)
415 for (i = 0; i <
ist->nb_filters; i++) {
416 ret = av_buffersrc_add_frame(
ist->filters[i]->filter, NULL);
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#if HAVE_SETCONSOLECTRLHANDLER
455static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
457 av_log(NULL, AV_LOG_DEBUG,
"\nReceived windows signal %ld\n", fdwCtrlType);
462 case CTRL_BREAK_EVENT:
466 case CTRL_CLOSE_EVENT:
467 case CTRL_LOGOFF_EVENT:
468 case CTRL_SHUTDOWN_EVENT:
480 av_log(NULL, AV_LOG_ERROR,
"Received unknown windows signal %ld\n", fdwCtrlType);
487#define SIGNAL(sig, func) \
489 action.sa_handler = func; \
490 sigaction(sig, &action, NULL); \
493#define SIGNAL(sig, func) \
500 #if defined __aarch64__ || defined __amd64__ || defined __x86_64__
501 struct sigaction action = {0};
503 struct sigaction action = {{0}};
509 sigfillset(&action.sa_mask);
512 action.sa_flags = SA_RESTART;
518 if (tcgetattr (0, &tty) == 0) {
522 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
523 |INLCR|IGNCR|ICRNL|IXON);
524 tty.c_oflag |= OPOST;
525 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
526 tty.c_cflag &= ~(CSIZE|PARENB);
531 tcsetattr (0, TCSANOW, &tty);
552 signal(SIGPIPE, SIG_IGN);
555#if HAVE_SETCONSOLECTRLHANDLER
556 SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
573 n = select(1, &rfds, NULL, NULL, &tv);
582# if HAVE_PEEKNAMEDPIPE
584 static HANDLE input_handle;
587 input_handle = GetStdHandle(STD_INPUT_HANDLE);
588 is_pipe = !GetConsoleMode(input_handle, &dw);
593 if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
627 av_log(NULL, AV_LOG_INFO,
"bench: maxrss=%ikB\n", maxrss);
632 avfilter_graph_free(&fg->
graph);
640 sizeof(frame), NULL);
641 av_frame_free(&frame);
644 if (
ist->sub2video.sub_queue) {
645 while (av_fifo_size(
ist->sub2video.sub_queue)) {
647 av_fifo_generic_read(
ist->sub2video.sub_queue,
648 &sub,
sizeof(sub), NULL);
649 avsubtitle_free(&sub);
651 av_fifo_freep(&
ist->sub2video.sub_queue);
654 av_freep(&ifilter->
name);
661 avfilter_inout_free(&ofilter->
out_tmp);
662 av_freep(&ofilter->
name);
684 if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
686 avformat_free_context(s);
687 av_dict_free(&of->
opts);
701 av_packet_free(&
ost->
pkt);
722 av_packet_free(&
pkt);
730 free_input_threads();
740 av_frame_free(&
ist->decoded_frame);
741 av_frame_free(&
ist->filter_frame);
742 av_packet_free(&
ist->pkt);
743 av_dict_free(&
ist->decoder_opts);
744 avsubtitle_free(&
ist->prev_sub.subtitle);
745 av_frame_free(&
ist->sub2video.frame);
746 av_freep(&
ist->filters);
747 av_freep(&
ist->hwaccel_device);
748 av_freep(&
ist->dts_buffer);
750 avcodec_free_context(&
ist->dec_ctx);
757 av_log(NULL, AV_LOG_ERROR,
758 "Error closing vstats file, loss of information possible: %s\n",
759 av_err2str(AVERROR(errno)));
770 avformat_network_deinit();
773 av_log(NULL, AV_LOG_INFO,
"Exiting normally, received signal %d.\n",
776 av_log(NULL, AV_LOG_INFO,
"Exiting normally, received cancel request.\n");
778 av_log(NULL, AV_LOG_INFO,
"Conversion failed!\n");
786 AVDictionaryEntry *t = NULL;
788 while ((t = av_dict_get(b,
"", t, AV_DICT_IGNORE_SUFFIX))) {
789 av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
795 AVDictionaryEntry *t;
796 if ((t = av_dict_get(m,
"", NULL, AV_DICT_IGNORE_SUFFIX))) {
797 av_log(NULL, AV_LOG_FATAL,
"Option %s not found.\n", t->key);
816 vsnprintf(buf,
sizeof(buf), fmt, va);
818 av_log(NULL, AV_LOG_INFO,
819 "bench: %8" PRIu64
" user %8" PRIu64
" sys %8" PRIu64
" real %s \n",
833 ost2->
finished |=
ost == ost2 ? this_stream : others;
839 AVFormatContext *s = of->
ctx;
853 av_packet_unref(
pkt);
863 unsigned int are_we_over_size =
865 int new_size = are_we_over_size ?
871 av_log(NULL, AV_LOG_ERROR,
872 "Too many packets buffered for output stream %d:%d.\n",
880 ret = av_packet_make_refcounted(
pkt);
883 tmp_pkt = av_packet_alloc();
886 av_packet_move_ref(tmp_pkt,
pkt);
888 av_fifo_generic_write(
ost->
muxing_queue, &tmp_pkt,
sizeof(tmp_pkt), NULL);
894 pkt->pts =
pkt->dts = AV_NOPTS_VALUE;
896 if (
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
898 uint8_t *sd = av_packet_get_side_data(
pkt, AV_PKT_DATA_QUALITY_STATS,
903 for (i = 0; i<FF_ARRAY_ELEMS(
ost->
error); i++) {
905 ost->
error[i] = AV_RL64(sd + 8 + 8*i);
911 if (
pkt->duration > 0)
912 av_log(NULL, AV_LOG_WARNING,
"Overriding packet duration by frame rate, this should not happen\n");
920 if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
921 if (
pkt->dts != AV_NOPTS_VALUE &&
922 pkt->pts != AV_NOPTS_VALUE &&
924 av_log(s, AV_LOG_WARNING,
"Invalid DTS: %"PRId64
" PTS: %"PRId64
" in output stream %d:%d, replacing by guess\n",
932 if ((
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) &&
933 pkt->dts != AV_NOPTS_VALUE &&
936 int64_t max =
ost->
last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
937 if (
pkt->dts < max) {
938 int loglevel = max -
pkt->dts > 2 ||
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
940 loglevel = AV_LOG_ERROR;
941 av_log(s, loglevel,
"Non-monotonous DTS in output stream "
942 "%d:%d; previous: %"PRId64
", current: %"PRId64
"; ",
945 av_log(NULL, AV_LOG_FATAL,
"aborting.\n");
948 av_log(s, loglevel,
"changing to %"PRId64
". This may result "
949 "in incorrect timestamps in the output file.\n",
952 pkt->pts = FFMAX(
pkt->pts, max);
965 av_log(NULL, AV_LOG_INFO,
"muxer <- type:%s "
966 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
967 av_get_media_type_string(
ost->
enc_ctx->codec_type),
968 av_ts2str(
pkt->pts), av_ts2timestr(
pkt->pts, &
ost->
st->time_base),
969 av_ts2str(
pkt->dts), av_ts2timestr(
pkt->dts, &
ost->
st->time_base),
974 ret = av_interleaved_write_frame(s,
pkt);
980 av_packet_unref(
pkt);
1017 if (
ret == AVERROR(EAGAIN))
1023 if (
ret < 0 &&
ret != AVERROR_EOF) {
1024 av_log(NULL, AV_LOG_ERROR,
"Error applying bitstream filters to an output "
1037 AV_TIME_BASE_Q) >= 0) {
1046 double float_pts = AV_NOPTS_VALUE;
1048 if (!frame || frame->pts == AV_NOPTS_VALUE ||
1056 AVRational filter_tb = av_buffersink_get_time_base(
filter);
1057 AVRational tb = enc->time_base;
1058 int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
1060 tb.den <<= extra_bits;
1062 av_rescale_q(frame->pts, filter_tb, tb) -
1063 av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
1064 float_pts /= 1 << extra_bits;
1066 float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
1069 av_rescale_q(frame->pts, filter_tb, enc->time_base) -
1070 av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
1076 av_log(NULL, AV_LOG_INFO,
"filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
1077 frame ? av_ts2str(frame->pts) :
"NULL",
1078 frame ? av_ts2timestr(frame->pts, &enc->time_base) :
"NULL",
1080 enc ? enc->time_base.num : -1,
1081 enc ? enc->time_base.den : -1);
1091 int ret = AVERROR_BUG;
1092 char error[1024] = {0};
1099 av_log(NULL, AV_LOG_ERROR,
"Error initializing output stream %d:%d -- %s\n",
1129 av_log(NULL, AV_LOG_INFO,
"encoder <- type:audio "
1130 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1131 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
1132 enc->time_base.num, enc->time_base.den);
1135 ret = avcodec_send_frame(enc, frame);
1140 av_packet_unref(
pkt);
1141 ret = avcodec_receive_packet(enc,
pkt);
1142 if (
ret == AVERROR(EAGAIN))
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;
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_packet_unref(
pkt);
1234 pkt->size = subtitle_out_size;
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;
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->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);
1398 for (i = 0; i < nb_frames; i++) {
1399 AVFrame *in_picture;
1400 int forced_keyframe = 0;
1403 if (i < nb0_frames && ost->last_frame) {
1406 in_picture = next_picture;
1416 in_picture->quality = enc->global_quality;
1417 in_picture->pict_type = 0;
1420 in_picture->pts != AV_NOPTS_VALUE)
1423 pts_time = in_picture->pts != AV_NOPTS_VALUE ?
1428 forced_keyframe = 1;
1434 ff_dlog(NULL,
"force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
1442 forced_keyframe = 1;
1453 && in_picture->key_frame==1
1455 forced_keyframe = 1;
1463 if (forced_keyframe) {
1464 in_picture->pict_type = AV_PICTURE_TYPE_I;
1465 av_log(NULL, AV_LOG_DEBUG,
"Forced keyframe at time %f\n", pts_time);
1470 av_log(NULL, AV_LOG_INFO,
"encoder <- type:video "
1471 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1472 av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
1473 enc->time_base.num, enc->time_base.den);
1478 ret = avcodec_send_frame(enc, in_picture);
1482 av_frame_remove_side_data(in_picture, AV_FRAME_DATA_A53_CC);
1485 av_packet_unref(
pkt);
1486 ret = avcodec_receive_packet(enc,
pkt);
1488 if (
ret == AVERROR(EAGAIN))
1494 av_log(NULL, AV_LOG_INFO,
"encoder -> type:video "
1495 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1496 av_ts2str(
pkt->pts), av_ts2timestr(
pkt->pts, &enc->time_base),
1497 av_ts2str(
pkt->dts), av_ts2timestr(
pkt->dts, &enc->time_base));
1500 if (
pkt->pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & AV_CODEC_CAP_DELAY))
1506 av_log(NULL, AV_LOG_INFO,
"encoder -> type:video "
1507 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1512 frame_size =
pkt->size;
1542 av_log(NULL, AV_LOG_FATAL,
"Video encoding failed\n");
1548 return -10.0 * log10(
d);
1553 AVCodecContext *enc;
1555 double ti1, bitrate, avg_bitrate;
1567 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1568 frame_number =
ost->
st->nb_frames;
1570 fprintf(
vstats_file,
"frame= %5d q= %2.1f ", frame_number,
1577 if (
ost->
error[0]>=0 && (enc->flags & AV_CODEC_FLAG_PSNR))
1582 ti1 = av_stream_get_end_pts(
ost->
st) * av_q2d(
ost->
st->time_base);
1586 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1587 avg_bitrate = (double)(
ost->
data_size * 8) / ti1 / 1000.0;
1588 fprintf(
vstats_file,
"s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1589 (
double)
ost->
data_size / 1024, ti1, bitrate, avg_bitrate);
1602 for (i = 0; i < of->
ctx->nb_streams; i++)
1615 AVFrame *filtered_frame = NULL;
1639 if (av_buffersink_get_type(
filter) == AVMEDIA_TYPE_AUDIO)
1643 return AVERROR(ENOMEM);
1646 return AVERROR(ENOMEM);
1651 ret = av_buffersink_get_frame_flags(
filter, filtered_frame,
1652 AV_BUFFERSINK_FLAG_NO_REQUEST);
1654 if (
ret != AVERROR(EAGAIN) &&
ret != AVERROR_EOF) {
1655 av_log(NULL, AV_LOG_WARNING,
1656 "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(
ret));
1657 }
else if (flush &&
ret == AVERROR_EOF) {
1658 if (av_buffersink_get_type(
filter) == AVMEDIA_TYPE_VIDEO)
1664 av_frame_unref(filtered_frame);
1668 switch (av_buffersink_get_type(
filter)) {
1669 case AVMEDIA_TYPE_VIDEO:
1671 enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
1675 case AVMEDIA_TYPE_AUDIO:
1676 if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&
1677 enc->channels != filtered_frame->channels) {
1678 av_log(NULL, AV_LOG_ERROR,
1679 "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1689 av_frame_unref(filtered_frame);
1698 uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
1699 uint64_t subtitle_size = 0;
1701 float percent = -1.0;
1708 case AVMEDIA_TYPE_VIDEO: video_size +=
ost->
data_size;
break;
1709 case AVMEDIA_TYPE_AUDIO: audio_size +=
ost->
data_size;
break;
1710 case AVMEDIA_TYPE_SUBTITLE: subtitle_size +=
ost->
data_size;
break;
1715 if ( (
ost->
enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
1716 != AV_CODEC_FLAG_PASS1)
1723 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: ",
1724 video_size / 1024.0,
1725 audio_size / 1024.0,
1726 subtitle_size / 1024.0,
1727 other_size / 1024.0,
1728 extra_size / 1024.0);
1730 av_log(NULL, AV_LOG_INFO,
"%f%%", percent);
1732 av_log(NULL, AV_LOG_INFO,
"unknown");
1733 av_log(NULL, AV_LOG_INFO,
"\n");
1738 uint64_t total_packets = 0, total_size = 0;
1740 av_log(NULL, AV_LOG_VERBOSE,
"Input file #%d (%s):\n",
1745 enum AVMediaType type =
ist->dec_ctx->codec_type;
1747 total_size +=
ist->data_size;
1748 total_packets +=
ist->nb_packets;
1750 av_log(NULL, AV_LOG_VERBOSE,
" Input stream #%d:%d (%s): ",
1752 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" packets read (%"PRIu64
" bytes); ",
1753 ist->nb_packets,
ist->data_size);
1755 if (
ist->decoding_needed) {
1756 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" frames decoded",
1757 ist->frames_decoded);
1758 if (type == AVMEDIA_TYPE_AUDIO)
1759 av_log(NULL, AV_LOG_VERBOSE,
" (%"PRIu64
" samples)",
ist->samples_decoded);
1760 av_log(NULL, AV_LOG_VERBOSE,
"; ");
1763 av_log(NULL, AV_LOG_VERBOSE,
"\n");
1766 av_log(NULL, AV_LOG_VERBOSE,
" Total: %"PRIu64
" packets (%"PRIu64
" bytes) demuxed\n",
1767 total_packets, total_size);
1772 uint64_t total_packets = 0, total_size = 0;
1774 av_log(NULL, AV_LOG_VERBOSE,
"Output file #%d (%s):\n",
1777 for (j = 0; j < of->
ctx->nb_streams; j++) {
1779 enum AVMediaType type =
ost->
enc_ctx->codec_type;
1784 av_log(NULL, AV_LOG_VERBOSE,
" Output stream #%d:%d (%s): ",
1787 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" frames encoded",
1789 if (type == AVMEDIA_TYPE_AUDIO)
1791 av_log(NULL, AV_LOG_VERBOSE,
"; ");
1794 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" packets muxed (%"PRIu64
" bytes); ",
1797 av_log(NULL, AV_LOG_VERBOSE,
"\n");
1800 av_log(NULL, AV_LOG_VERBOSE,
" Total: %"PRIu64
" packets (%"PRIu64
" bytes) muxed\n",
1801 total_packets, total_size);
1803 if(video_size +
data_size + audio_size + subtitle_size + extra_size == 0){
1804 av_log(NULL, AV_LOG_WARNING,
"Output file is empty, nothing was encoded ");
1806 av_log(NULL, AV_LOG_WARNING,
"\n");
1808 av_log(NULL, AV_LOG_WARNING,
"(check -ss / -t / -frames parameters if used)\n");
1815 AVFormatContext *oc = NULL;
1816 AVCodecContext *enc = NULL;
1818 int64_t
pts = INT64_MIN + 1;
1821 int frame_number = 0;
1824 int64_t total_size = 0;
1826 double bitrate = 0.0;
1829 float t = (cur_time-timer_start) / 1000000.0;
1834 total_size = avio_size(oc->pb);
1835 if (total_size <= 0) {
1836 total_size = avio_tell(oc->pb);
1847 quality =
ost->
quality / (float) FF_QP2LAMBDA;
1850 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1856 fps = t > 1 ? frame_number / t : 0;
1860 if (av_stream_get_end_pts(
ost->
st) != AV_NOPTS_VALUE)
1861 pts = FFMAX(
pts, av_rescale_q(av_stream_get_end_pts(
ost->
st),
1862 ost->
st->time_base, AV_TIME_BASE_Q));
1868 seconds = FFABS(
pts) / 1000;
1871 bitrate =
pts && total_size >= 0 ? total_size * 8 / (
pts / 1000.0) : -1;
1874 speed = t != 0.0 ? (double)
pts / AV_TIME_BASE / t : -1;
1878 report_callback(frame_number, fps, quality, total_size, seconds, bitrate, speed);
1882static void print_report(
int is_last_report, int64_t timer_start, int64_t cur_time)
1884 AVBPrint buf, buf_script;
1886 AVFormatContext *oc;
1888 AVCodecContext *enc;
1889 int frame_number, vid, i;
1892 int64_t
pts = INT64_MIN + 1;
1893 int hours, mins, secs, us;
1894 const char *hours_sign;
1898 if (!is_last_report) {
1913 t = (cur_time-timer_start) / 1000000.0;
1918 total_size = avio_size(oc->pb);
1919 if (total_size <= 0)
1920 total_size = avio_tell(oc->pb);
1923 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
1924 av_bprint_init(&buf_script, 0, AV_BPRINT_SIZE_AUTOMATIC);
1932 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1933 av_bprintf(&buf,
"q=%2.1f ", q);
1934 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
1937 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1941 fps = t > 1 ? frame_number / t : 0;
1942 av_bprintf(&buf,
"frame=%5d fps=%3.*f q=%3.1f ",
1943 frame_number, fps < 9.95, fps, q);
1944 av_bprintf(&buf_script,
"frame=%d\n", frame_number);
1945 av_bprintf(&buf_script,
"fps=%.2f\n", fps);
1946 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
1949 av_bprintf(&buf,
"L");
1955 for (j = 0; j < 32; j++)
1959 if ((enc->flags & AV_CODEC_FLAG_PSNR) && (
ost->
pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {
1961 double error, error_sum = 0;
1962 double scale, scale_sum = 0;
1964 char type[3] = {
'Y',
'U',
'V' };
1965 av_bprintf(&buf,
"PSNR=");
1966 for (j = 0; j < 3; j++) {
1967 if (is_last_report) {
1968 error = enc->error[j];
1969 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1972 scale = enc->width * enc->height * 255.0 * 255.0;
1978 p =
psnr(error / scale);
1979 av_bprintf(&buf,
"%c:%2.2f ", type[j], p);
1980 av_bprintf(&buf_script,
"stream_%d_%d_psnr_%c=%2.2f\n",
1983 p =
psnr(error_sum / scale_sum);
1984 av_bprintf(&buf,
"*:%2.2f ",
psnr(error_sum / scale_sum));
1985 av_bprintf(&buf_script,
"stream_%d_%d_psnr_all=%2.2f\n",
1991 if (av_stream_get_end_pts(
ost->
st) != AV_NOPTS_VALUE) {
1992 pts = FFMAX(
pts, av_rescale_q(av_stream_get_end_pts(
ost->
st),
1993 ost->
st->time_base, AV_TIME_BASE_Q));
2006 secs = FFABS(
pts) / AV_TIME_BASE;
2007 us = FFABS(
pts) % AV_TIME_BASE;
2012 hours_sign = (
pts < 0) ?
"-" :
"";
2014 bitrate =
pts && total_size >= 0 ? total_size * 8 / (
pts / 1000.0) : -1;
2015 speed = t != 0.0 ? (double)
pts / AV_TIME_BASE / t : -1;
2017 if (total_size < 0) av_bprintf(&buf,
"size=N/A time=");
2018 else av_bprintf(&buf,
"size=%8.0fkB time=", total_size / 1024.0);
2019 if (
pts == AV_NOPTS_VALUE) {
2020 av_bprintf(&buf,
"N/A ");
2022 av_bprintf(&buf,
"%s%02d:%02d:%02d.%02d ",
2023 hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
2027 av_bprintf(&buf,
"bitrate=N/A");
2028 av_bprintf(&buf_script,
"bitrate=N/A\n");
2030 av_bprintf(&buf,
"bitrate=%6.1fkbits/s", bitrate);
2031 av_bprintf(&buf_script,
"bitrate=%6.1fkbits/s\n", bitrate);
2034 if (total_size < 0) av_bprintf(&buf_script,
"total_size=N/A\n");
2035 else av_bprintf(&buf_script,
"total_size=%"PRId64
"\n", total_size);
2036 if (
pts == AV_NOPTS_VALUE) {
2037 av_bprintf(&buf_script,
"out_time_us=N/A\n");
2038 av_bprintf(&buf_script,
"out_time_ms=N/A\n");
2039 av_bprintf(&buf_script,
"out_time=N/A\n");
2041 av_bprintf(&buf_script,
"out_time_us=%"PRId64
"\n",
pts);
2042 av_bprintf(&buf_script,
"out_time_ms=%"PRId64
"\n",
pts);
2043 av_bprintf(&buf_script,
"out_time=%s%02d:%02d:%02d.%06d\n",
2044 hours_sign, hours, mins, secs, us);
2053 av_bprintf(&buf,
" speed=N/A");
2054 av_bprintf(&buf_script,
"speed=N/A\n");
2056 av_bprintf(&buf,
" speed=%4.3gx", speed);
2057 av_bprintf(&buf_script,
"speed=%4.3gx\n", speed);
2061 const char end = is_last_report ?
'\n' :
'\r';
2062 if (
print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
2063 fprintf(stderr,
"%s %c", buf.str, end);
2065 av_log(NULL, AV_LOG_INFO,
"%s %c", buf.str, end);
2069 av_bprint_finalize(&buf, NULL);
2072 av_bprintf(&buf_script,
"progress=%s\n",
2073 is_last_report ?
"end" :
"continue");
2075 FFMIN(buf_script.len, buf_script.size - 1));
2077 av_bprint_finalize(&buf_script, NULL);
2078 if (is_last_report) {
2080 av_log(NULL, AV_LOG_ERROR,
2081 "Error closing progress log, loss of information possible: %s\n", av_err2str(
ret));
2095 ifilter->
format = par->format;
2099 ifilter->
width = par->width;
2100 ifilter->
height = par->height;
2121 av_log(NULL, AV_LOG_WARNING,
2122 "Finishing stream %d:%d without any data written to it.\n",
2138 av_log(NULL, AV_LOG_ERROR,
"Error configuring filter graph\n");
2148 if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
2152 const char *desc = NULL;
2156 switch (enc->codec_type) {
2157 case AVMEDIA_TYPE_AUDIO:
2160 case AVMEDIA_TYPE_VIDEO:
2169 av_packet_unref(
pkt);
2170 while ((
ret = avcodec_receive_packet(enc,
pkt)) == AVERROR(EAGAIN)) {
2171 ret = avcodec_send_frame(enc, NULL);
2173 av_log(NULL, AV_LOG_FATAL,
"%s encoding failed: %s\n",
2181 if (
ret < 0 &&
ret != AVERROR_EOF) {
2182 av_log(NULL, AV_LOG_FATAL,
"%s encoding failed: %s\n",
2190 if (
ret == AVERROR_EOF) {
2195 av_packet_unref(
pkt);
2199 pkt_size =
pkt->size;
2233 int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q,
ost->
mux_timebase);
2234 AVPacket *opkt =
ost->
pkt;
2236 av_packet_unref(opkt);
2248 int64_t comp_start = start_time;
2251 if (
pkt->pts == AV_NOPTS_VALUE ?
2252 ist->pts < comp_start :
2253 pkt->pts < av_rescale_q(comp_start, AV_TIME_BASE_Q,
ist->st->time_base))
2276 if (
ost->
enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
2279 if (av_packet_ref(opkt,
pkt) < 0)
2282 if (
pkt->pts != AV_NOPTS_VALUE)
2285 if (
pkt->dts == AV_NOPTS_VALUE) {
2287 }
else if (
ost->
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2288 int duration = av_get_audio_frame_duration(
ist->dec_ctx,
pkt->size);
2290 duration =
ist->dec_ctx->frame_size;
2291 opkt->dts = av_rescale_delta(
ist->st->time_base,
pkt->dts,
2292 (AVRational){1, ist->dec_ctx->sample_rate}, duration,
2295 opkt->pts = opkt->dts - ost_tb_start_time;
2298 opkt->dts -= ost_tb_start_time;
2307 AVCodecContext *
dec =
ist->dec_ctx;
2309 if (!
dec->channel_layout) {
2310 char layout_name[256];
2312 if (
dec->channels >
ist->guess_layout_max)
2314 dec->channel_layout = av_get_default_channel_layout(
dec->channels);
2315 if (!
dec->channel_layout)
2317 av_get_channel_layout_string(layout_name,
sizeof(layout_name),
2318 dec->channels,
dec->channel_layout);
2319 av_log(NULL, AV_LOG_WARNING,
"Guessed Channel Layout for Input Stream "
2320 "#%d.%d : %s\n",
ist->file_index,
ist->st->index, layout_name);
2334 if (
ist->decoded_frame->decode_error_flags || (
ist->decoded_frame->flags & AV_FRAME_FLAG_CORRUPT)) {
2336 "%s: corrupt decoded frame in stream %d\n",
input_files[
ist->file_index]->
ctx->url,
ist->st->index);
2358 int need_reinit,
ret, i;
2361 need_reinit = ifilter->
format != frame->format;
2363 switch (ifilter->
ist->
st->codecpar->codec_type) {
2364 case AVMEDIA_TYPE_AUDIO:
2365 need_reinit |= ifilter->
sample_rate != frame->sample_rate ||
2366 ifilter->
channels != frame->channels ||
2369 case AVMEDIA_TYPE_VIDEO:
2370 need_reinit |= ifilter->
width != frame->width ||
2371 ifilter->
height != frame->height;
2389 if (need_reinit || !fg->
graph) {
2392 AVFrame *tmp = av_frame_clone(frame);
2394 return AVERROR(ENOMEM);
2395 av_frame_unref(frame);
2400 av_frame_free(&tmp);
2404 av_fifo_generic_write(ifilter->
frame_queue, &tmp,
sizeof(tmp), NULL);
2410 if (
ret < 0 &&
ret != AVERROR_EOF) {
2411 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(
ret));
2417 av_log(NULL, AV_LOG_ERROR,
"Error reinitializing filters!\n");
2422 ret = av_buffersrc_add_frame_flags(ifilter->
filter, frame, AV_BUFFERSRC_FLAG_PUSH);
2424 if (
ret != AVERROR_EOF)
2425 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(
ret));
2442 ret = av_buffersrc_close(ifilter->
filter,
pts, AV_BUFFERSRC_FLAG_PUSH);
2450 if (ifilter->
format < 0 && (ifilter->
type == AVMEDIA_TYPE_AUDIO || ifilter->
type == AVMEDIA_TYPE_VIDEO)) {
2451 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);
2452 return AVERROR_INVALIDDATA;
2463static int decode(AVCodecContext *avctx, AVFrame *frame,
int *got_frame, AVPacket *
pkt)
2470 ret = avcodec_send_packet(avctx,
pkt);
2473 if (
ret < 0 &&
ret != AVERROR_EOF)
2477 ret = avcodec_receive_frame(avctx, frame);
2478 if (
ret < 0 &&
ret != AVERROR(EAGAIN))
2491 av_assert1(
ist->nb_filters > 0);
2492 for (i = 0; i <
ist->nb_filters; i++) {
2494 f =
ist->filter_frame;
2501 if (
ret == AVERROR_EOF)
2504 av_log(NULL, AV_LOG_ERROR,
2505 "Failed to inject frame into filter network: %s\n", av_err2str(
ret));
2516 AVCodecContext *avctx =
ist->dec_ctx;
2518 AVRational decoded_frame_tb;
2520 if (!
ist->decoded_frame && !(
ist->decoded_frame = av_frame_alloc()))
2521 return AVERROR(ENOMEM);
2522 if (!
ist->filter_frame && !(
ist->filter_frame = av_frame_alloc()))
2523 return AVERROR(ENOMEM);
2532 if (
ret >= 0 && avctx->sample_rate <= 0) {
2533 av_log(avctx, AV_LOG_ERROR,
"Sample rate %d invalid\n", avctx->sample_rate);
2534 ret = AVERROR_INVALIDDATA;
2537 if (
ret != AVERROR_EOF)
2544 ist->frames_decoded++;
2554 decoded_frame_tb =
ist->st->time_base;
2555 }
else if (
pkt &&
pkt->pts != AV_NOPTS_VALUE) {
2557 decoded_frame_tb =
ist->st->time_base;
2560 decoded_frame_tb = AV_TIME_BASE_Q;
2564 (AVRational){1, avctx->sample_rate},
decoded_frame->nb_samples, &
ist->filter_in_rescale_delta_last,
2565 (AVRational){1, avctx->sample_rate});
2569 av_frame_unref(
ist->filter_frame);
2571 return err < 0 ? err :
ret;
2578 int i,
ret = 0, err = 0;
2579 int64_t best_effort_timestamp;
2580 int64_t
dts = AV_NOPTS_VALUE;
2585 if (!eof &&
pkt &&
pkt->size == 0)
2588 if (!
ist->decoded_frame && !(
ist->decoded_frame = av_frame_alloc()))
2589 return AVERROR(ENOMEM);
2590 if (!
ist->filter_frame && !(
ist->filter_frame = av_frame_alloc()))
2591 return AVERROR(ENOMEM);
2593 if (
ist->dts != AV_NOPTS_VALUE)
2594 dts = av_rescale_q(
ist->dts, AV_TIME_BASE_Q,
ist->st->time_base);
2602 void *
new = av_realloc_array(
ist->dts_buffer,
ist->nb_dts_buffer + 1,
sizeof(
ist->dts_buffer[0]));
2604 return AVERROR(ENOMEM);
2605 ist->dts_buffer =
new;
2606 ist->dts_buffer[
ist->nb_dts_buffer++] =
dts;
2617 if (
ist->st->codecpar->video_delay <
ist->dec_ctx->has_b_frames) {
2618 if (
ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
2619 ist->st->codecpar->video_delay =
ist->dec_ctx->has_b_frames;
2621 av_log(
ist->dec_ctx, AV_LOG_WARNING,
2622 "video_delay is larger in decoder than demuxer %d > %d.\n"
2623 "If you want to help, upload a sample "
2624 "of this file to https://streams.videolan.org/upload/ "
2625 "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n",
2626 ist->dec_ctx->has_b_frames,
2627 ist->st->codecpar->video_delay);
2630 if (
ret != AVERROR_EOF)
2637 av_log(NULL, AV_LOG_DEBUG,
"Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
2641 ist->dec_ctx->width,
2642 ist->dec_ctx->height,
2643 ist->dec_ctx->pix_fmt);
2650 if(
ist->top_field_first>=0)
2653 ist->frames_decoded++;
2662 best_effort_timestamp=
decoded_frame->best_effort_timestamp;
2665 if (
ist->framerate.num)
2666 best_effort_timestamp =
ist->cfr_next_pts++;
2668 if (eof && best_effort_timestamp == AV_NOPTS_VALUE &&
ist->nb_dts_buffer > 0) {
2669 best_effort_timestamp =
ist->dts_buffer[0];
2671 for (i = 0; i <
ist->nb_dts_buffer - 1; i++)
2672 ist->dts_buffer[i] =
ist->dts_buffer[i + 1];
2673 ist->nb_dts_buffer--;
2676 if(best_effort_timestamp != AV_NOPTS_VALUE) {
2677 int64_t ts = av_rescale_q(
decoded_frame->pts = best_effort_timestamp,
ist->st->time_base, AV_TIME_BASE_Q);
2679 if (ts != AV_NOPTS_VALUE)
2680 ist->next_pts =
ist->pts = ts;
2684 av_log(NULL, AV_LOG_INFO,
"decoder -> ist_index:%d type:video "
2685 "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",
2688 best_effort_timestamp,
2689 av_ts2timestr(best_effort_timestamp, &
ist->st->time_base),
2691 ist->st->time_base.num,
ist->st->time_base.den);
2694 if (
ist->st->sample_aspect_ratio.num)
2700 av_frame_unref(
ist->filter_frame);
2702 return err < 0 ? err :
ret;
2710 int i,
ret = avcodec_decode_subtitle2(
ist->dec_ctx,
2722 if (
ist->fix_sub_duration) {
2724 if (
ist->prev_sub.got_output) {
2725 end = av_rescale(
subtitle.pts -
ist->prev_sub.subtitle.pts,
2726 1000, AV_TIME_BASE);
2727 if (end < ist->
prev_sub.subtitle.end_display_time) {
2728 av_log(
ist->dec_ctx, AV_LOG_DEBUG,
2729 "Subtitle duration reduced from %"PRId32
" to %d%s\n",
2730 ist->prev_sub.subtitle.end_display_time, end,
2731 end <= 0 ?
", dropping it" :
"");
2732 ist->prev_sub.subtitle.end_display_time = end;
2736 FFSWAP(
int,
ret,
ist->prev_sub.ret);
2737 FFSWAP(AVSubtitle,
subtitle,
ist->prev_sub.subtitle);
2745 if (
ist->sub2video.frame) {
2747 }
else if (
ist->nb_filters) {
2748 if (!
ist->sub2video.sub_queue)
2749 ist->sub2video.sub_queue = av_fifo_alloc(8 *
sizeof(AVSubtitle));
2750 if (!
ist->sub2video.sub_queue)
2752 if (!av_fifo_space(
ist->sub2video.sub_queue)) {
2753 ret = av_fifo_realloc2(
ist->sub2video.sub_queue, 2 * av_fifo_size(
ist->sub2video.sub_queue));
2764 ist->frames_decoded++;
2772 ||
ost->
enc->type != AVMEDIA_TYPE_SUBTITLE)
2788 int64_t
pts = av_rescale_q_rnd(
ist->pts, AV_TIME_BASE_Q,
ist->st->time_base,
2789 AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
2791 for (i = 0; i <
ist->nb_filters; i++) {
2804 int eof_reached = 0;
2808 if (!
ist->pkt && !(
ist->pkt = av_packet_alloc()))
2809 return AVERROR(ENOMEM);
2812 if (!
ist->saw_first_ts) {
2814 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;
2816 if (
pkt &&
pkt->pts != AV_NOPTS_VALUE && !
ist->decoding_needed) {
2818 ist->dts += av_rescale_q(
pkt->pts,
ist->st->time_base, AV_TIME_BASE_Q);
2821 ist->saw_first_ts = 1;
2824 if (
ist->next_dts == AV_NOPTS_VALUE)
2825 ist->next_dts =
ist->dts;
2826 if (
ist->next_pts == AV_NOPTS_VALUE)
2827 ist->next_pts =
ist->pts;
2830 av_packet_unref(avpkt);
2831 ret = av_packet_ref(avpkt,
pkt);
2836 if (
pkt &&
pkt->dts != AV_NOPTS_VALUE) {
2837 ist->next_dts =
ist->dts = av_rescale_q(
pkt->dts,
ist->st->time_base, AV_TIME_BASE_Q);
2838 if (
ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !
ist->decoding_needed)
2843 while (
ist->decoding_needed) {
2844 int64_t duration_dts = 0;
2845 int64_t duration_pts = 0;
2847 int decode_failed = 0;
2849 ist->pts =
ist->next_pts;
2850 ist->dts =
ist->next_dts;
2852 switch (
ist->dec_ctx->codec_type) {
2853 case AVMEDIA_TYPE_AUDIO:
2856 av_packet_unref(avpkt);
2858 case AVMEDIA_TYPE_VIDEO:
2862 if (
pkt &&
pkt->duration) {
2863 duration_dts = av_rescale_q(
pkt->duration,
ist->st->time_base, AV_TIME_BASE_Q);
2864 }
else if(
ist->dec_ctx->framerate.num != 0 &&
ist->dec_ctx->framerate.den != 0) {
2865 int ticks= av_stream_get_parser(
ist->st) ? av_stream_get_parser(
ist->st)->repeat_pict+1 :
ist->dec_ctx->ticks_per_frame;
2866 duration_dts = ((int64_t)AV_TIME_BASE *
2867 ist->dec_ctx->framerate.den * ticks) /
2868 ist->dec_ctx->framerate.num /
ist->dec_ctx->ticks_per_frame;
2871 if(
ist->dts != AV_NOPTS_VALUE && duration_dts) {
2872 ist->next_dts += duration_dts;
2874 ist->next_dts = AV_NOPTS_VALUE;
2878 if (duration_pts > 0) {
2879 ist->next_pts += av_rescale_q(duration_pts,
ist->st->time_base, AV_TIME_BASE_Q);
2881 ist->next_pts += duration_dts;
2884 av_packet_unref(avpkt);
2886 case AVMEDIA_TYPE_SUBTITLE:
2892 av_packet_unref(avpkt);
2898 if (
ret == AVERROR_EOF) {
2904 if (decode_failed) {
2905 av_log(NULL, AV_LOG_ERROR,
"Error while decoding stream #%d:%d: %s\n",
2906 ist->file_index,
ist->st->index, av_err2str(
ret));
2908 av_log(NULL, AV_LOG_FATAL,
"Error while processing the decoded "
2909 "data for stream #%d:%d\n",
ist->file_index,
ist->st->index);
2917 ist->got_output = 1;
2938 if (!
pkt &&
ist->decoding_needed && eof_reached && !no_eof) {
2941 av_log(NULL, AV_LOG_FATAL,
"Error marking filters as finished\n");
2947 if (!
ist->decoding_needed &&
pkt) {
2948 ist->dts =
ist->next_dts;
2949 switch (
ist->dec_ctx->codec_type) {
2950 case AVMEDIA_TYPE_AUDIO:
2951 av_assert1(
pkt->duration >= 0);
2952 if (
ist->dec_ctx->sample_rate) {
2953 ist->next_dts += ((int64_t)AV_TIME_BASE *
ist->dec_ctx->frame_size) /
2954 ist->dec_ctx->sample_rate;
2956 ist->next_dts += av_rescale_q(
pkt->duration,
ist->st->time_base, AV_TIME_BASE_Q);
2959 case AVMEDIA_TYPE_VIDEO:
2960 if (
ist->framerate.num) {
2962 AVRational time_base_q = AV_TIME_BASE_Q;
2963 int64_t
next_dts = av_rescale_q(
ist->next_dts, time_base_q, av_inv_q(
ist->framerate));
2964 ist->next_dts = av_rescale_q(
next_dts + 1, av_inv_q(
ist->framerate), time_base_q);
2965 }
else if (
pkt->duration) {
2966 ist->next_dts += av_rescale_q(
pkt->duration,
ist->st->time_base, AV_TIME_BASE_Q);
2967 }
else if(
ist->dec_ctx->framerate.num != 0) {
2968 int ticks= av_stream_get_parser(
ist->st) ? av_stream_get_parser(
ist->st)->repeat_pict + 1 :
ist->dec_ctx->ticks_per_frame;
2969 ist->next_dts += ((int64_t)AV_TIME_BASE *
2970 ist->dec_ctx->framerate.den * ticks) /
2971 ist->dec_ctx->framerate.num /
ist->dec_ctx->ticks_per_frame;
2976 ist->next_pts =
ist->next_dts;
2989 return !eof_reached;
2997 AVIOContext *sdp_pb;
2998 AVFormatContext **avc;
3009 if (!strcmp(
output_files[i]->ctx->oformat->name,
"rtp")) {
3018 av_sdp_create(avc, j, sdp,
sizeof(sdp));
3025 av_log(NULL, AV_LOG_ERROR,
"Failed to open sdp file '%s'\n",
sdp_filename);
3027 avio_print(sdp_pb, sdp);
3028 avio_closep(&sdp_pb);
3037static enum AVPixelFormat
get_format(AVCodecContext *s,
const enum AVPixelFormat *pix_fmts)
3040 const enum AVPixelFormat *p;
3043 for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
3044 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
3045 const AVCodecHWConfig *config = NULL;
3048 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
3054 config = avcodec_get_hw_config(s->codec, i);
3057 if (!(config->methods &
3058 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
3060 if (config->pix_fmt == *p)
3065 if (config->device_type !=
ist->hwaccel_device_type) {
3073 av_log(NULL, AV_LOG_FATAL,
3074 "%s hwaccel requested for input stream #%d:%d, "
3075 "but cannot be initialized.\n",
3076 av_hwdevice_get_type_name(config->device_type),
3077 ist->file_index,
ist->st->index);
3078 return AV_PIX_FMT_NONE;
3083 const HWAccel *hwaccel = NULL;
3095 if (hwaccel->
id !=
ist->hwaccel_id) {
3102 av_log(NULL, AV_LOG_FATAL,
3103 "%s hwaccel requested for input stream #%d:%d, "
3104 "but cannot be initialized.\n", hwaccel->
name,
3105 ist->file_index,
ist->st->index);
3106 return AV_PIX_FMT_NONE;
3110 if (
ist->hw_frames_ctx) {
3111 s->hw_frames_ctx = av_buffer_ref(
ist->hw_frames_ctx);
3112 if (!s->hw_frames_ctx)
3113 return AV_PIX_FMT_NONE;
3116 ist->hwaccel_pix_fmt = *p;
3123static int get_buffer(AVCodecContext *s, AVFrame *frame,
int flags)
3127 if (
ist->hwaccel_get_buffer && frame->format ==
ist->hwaccel_pix_fmt)
3128 return ist->hwaccel_get_buffer(s, frame, flags);
3130 return avcodec_default_get_buffer2(s, frame, flags);
3138 if (
ist->decoding_needed) {
3139 const AVCodec *codec =
ist->dec;
3141 snprintf(error, error_len,
"Decoder (codec %s) not found for input stream #%d:%d",
3142 avcodec_get_name(
ist->dec_ctx->codec_id),
ist->file_index,
ist->st->index);
3143 return AVERROR(EINVAL);
3146 ist->dec_ctx->opaque =
ist;
3149#if LIBAVCODEC_VERSION_MAJOR < 60
3150FF_DISABLE_DEPRECATION_WARNINGS
3151 ist->dec_ctx->thread_safe_callbacks = 1;
3152FF_ENABLE_DEPRECATION_WARNINGS
3155 if (
ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
3157 av_dict_set(&
ist->decoder_opts,
"compute_edt",
"1", AV_DICT_DONT_OVERWRITE);
3159 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");
3162 av_dict_set(&
ist->decoder_opts,
"sub_text_format",
"ass", AV_DICT_DONT_OVERWRITE);
3166 ist->dec_ctx->pkt_timebase =
ist->st->time_base;
3168 if (!av_dict_get(
ist->decoder_opts,
"threads", NULL, 0))
3169 av_dict_set(&
ist->decoder_opts,
"threads",
"auto", 0);
3171 if (
ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3172 av_dict_set(&
ist->decoder_opts,
"threads",
"1", 0);
3176 snprintf(error, error_len,
"Device setup failed for "
3177 "decoder on input stream #%d:%d : %s",
3178 ist->file_index,
ist->st->index, av_err2str(
ret));
3182 if ((
ret = avcodec_open2(
ist->dec_ctx, codec, &
ist->decoder_opts)) < 0) {
3183 if (
ret == AVERROR_EXPERIMENTAL)
3186 snprintf(error, error_len,
3187 "Error while opening decoder for input stream "
3189 ist->file_index,
ist->st->index, av_err2str(
ret));
3195 ist->next_pts = AV_NOPTS_VALUE;
3196 ist->next_dts = AV_NOPTS_VALUE;
3210 return FFDIFFSIGN(*(
const int64_t *)a, *(
const int64_t *)b);
3218 for (i = 0; i < of->
ctx->nb_streams; i++) {
3226 ret = avformat_write_header(of->
ctx, &of->
opts);
3228 av_log(NULL, AV_LOG_ERROR,
3229 "Could not write header for output file #%d "
3230 "(incorrect codec parameters ?): %s\n",
3244 for (i = 0; i < of->
ctx->nb_streams; i++) {
3256 av_packet_free(&
pkt);
3271 ret = avcodec_parameters_copy(ctx->par_in,
ost->
st->codecpar);
3275 ctx->time_base_in =
ost->
st->time_base;
3277 ret = av_bsf_init(ctx);
3279 av_log(NULL, AV_LOG_ERROR,
"Error initializing bitstream filter: %s\n",
3284 ret = avcodec_parameters_copy(
ost->
st->codecpar, ctx->par_out);
3288 ost->
st->time_base = ctx->time_base_out;
3297 AVCodecParameters *par_dst =
ost->
st->codecpar;
3301 uint32_t codec_tag = par_dst->codec_tag;
3309 av_log(NULL, AV_LOG_FATAL,
3310 "Error setting up codec context options.\n");
3314 ret = avcodec_parameters_from_context(par_src,
ost->
enc_ctx);
3316 av_log(NULL, AV_LOG_FATAL,
3317 "Error getting reference codec parameters.\n");
3322 unsigned int codec_tag_tmp;
3323 if (!of->
ctx->oformat->codec_tag ||
3324 av_codec_get_id (of->
ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
3325 !av_codec_get_tag2(of->
ctx->oformat->codec_tag, par_src->codec_id, &codec_tag_tmp))
3326 codec_tag = par_src->codec_tag;
3329 ret = avcodec_parameters_copy(par_dst, par_src);
3333 par_dst->codec_tag = codec_tag;
3341 ost->
st->avg_frame_rate =
ist->st->avg_frame_rate;
3348 if (
ost->
st->time_base.num <= 0 ||
ost->
st->time_base.den <= 0) {
3352 ost->
st->time_base = av_add_q(av_stream_get_codec_timebase(
ost->
st), (AVRational){0, 1});
3356 if (
ost->
st->duration <= 0 &&
ist->st->duration > 0)
3357 ost->
st->duration = av_rescale_q(
ist->st->duration,
ist->st->time_base,
ost->
st->time_base);
3360 ost->
st->disposition =
ist->st->disposition;
3362 if (
ist->st->nb_side_data) {
3363 for (i = 0; i <
ist->st->nb_side_data; i++) {
3364 const AVPacketSideData *sd_src = &
ist->st->side_data[i];
3367 dst_data = av_stream_new_side_data(
ost->
st, sd_src->type, sd_src->size);
3369 return AVERROR(ENOMEM);
3370 memcpy(dst_data, sd_src->data, sd_src->size);
3375 uint8_t *sd = av_stream_new_side_data(
ost->
st, AV_PKT_DATA_DISPLAYMATRIX,
3376 sizeof(int32_t) * 9);
3381 switch (par_dst->codec_type) {
3382 case AVMEDIA_TYPE_AUDIO:
3384 av_log(NULL, AV_LOG_FATAL,
"-acodec copy and -vol are incompatible (frames are not decoded)\n");
3387 if((par_dst->block_align == 1 || par_dst->block_align == 1152 || par_dst->block_align == 576) && par_dst->codec_id == AV_CODEC_ID_MP3)
3388 par_dst->block_align= 0;
3389 if(par_dst->codec_id == AV_CODEC_ID_AC3)
3390 par_dst->block_align= 0;
3392 case AVMEDIA_TYPE_VIDEO:
3396 (AVRational){ par_dst->height, par_dst->width });
3397 av_log(NULL, AV_LOG_WARNING,
"Overriding aspect ratio "
3398 "with stream copy may produce invalid files\n");
3400 else if (
ist->st->sample_aspect_ratio.num)
3401 sar =
ist->st->sample_aspect_ratio;
3403 sar = par_src->sample_aspect_ratio;
3404 ost->
st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
3405 ost->
st->avg_frame_rate =
ist->st->avg_frame_rate;
3406 ost->
st->r_frame_rate =
ist->st->r_frame_rate;
3417 AVDictionaryEntry *e;
3419 uint8_t *encoder_string;
3420 int encoder_string_len;
3421 int format_flags = 0;
3424 if (av_dict_get(
ost->
st->metadata,
"encoder", NULL, 0))
3427 e = av_dict_get(of->
opts,
"fflags", NULL, 0);
3429 const AVOption *o = av_opt_find(of->
ctx,
"fflags", NULL, 0, 0);
3432 av_opt_eval_flags(of->
ctx, o, e->value, &format_flags);
3436 const AVOption *o = av_opt_find(
ost->
enc_ctx,
"flags", NULL, 0, 0);
3439 av_opt_eval_flags(
ost->
enc_ctx, o, e->value, &codec_flags);
3442 encoder_string_len =
sizeof(LIBAVCODEC_IDENT) + strlen(
ost->
enc->name) + 2;
3443 encoder_string = av_mallocz(encoder_string_len);
3444 if (!encoder_string)
3447 if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & AV_CODEC_FLAG_BITEXACT))
3448 av_strlcpy(encoder_string, LIBAVCODEC_IDENT
" ", encoder_string_len);
3450 av_strlcpy(encoder_string,
"Lavc ", encoder_string_len);
3451 av_strlcat(encoder_string,
ost->
enc->name, encoder_string_len);
3452 av_dict_set(&
ost->
st->metadata,
"encoder", encoder_string,
3453 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
3457 AVCodecContext *avctx)
3460 int n = 1, i, size,
index = 0;
3463 for (p = kf; *p; p++)
3467 pts = av_malloc_array(size,
sizeof(*
pts));
3469 av_log(NULL, AV_LOG_FATAL,
"Could not allocate forced key frames array.\n");
3474 for (i = 0; i < n; i++) {
3475 char *next = strchr(p,
',');
3480 if (!memcmp(p,
"chapters", 8)) {
3485 if (avf->nb_chapters > INT_MAX - size ||
3486 !(
pts = av_realloc_f(
pts, size += avf->nb_chapters - 1,
3488 av_log(NULL, AV_LOG_FATAL,
3489 "Could not allocate forced key frames array.\n");
3493 t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3495 for (j = 0; j < avf->nb_chapters; j++) {
3496 AVChapter *c = avf->chapters[j];
3497 av_assert1(
index < size);
3498 pts[
index++] = av_rescale_q(c->start, c->time_base,
3499 avctx->time_base) + t;
3505 av_assert1(
index < size);
3506 pts[
index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3513 av_assert0(
index == size);
3523 AVFormatContext *oc;
3532 enc_ctx->time_base =
ist->st->time_base;
3537 av_log(oc, AV_LOG_WARNING,
"Input stream data not available, using default time base\n");
3540 enc_ctx->time_base = default_time_base;
3547 AVCodecContext *
dec_ctx = NULL;
3556 av_dict_set(&
ost->
st->metadata,
"rotate", NULL, 0);
3559 ost->
st->disposition =
ist->st->disposition;
3563 enc_ctx->chroma_sample_location =
dec_ctx->chroma_sample_location;
3565 for (j = 0; j < oc->nb_streams; j++) {
3566 AVStream *
st = oc->streams[j];
3567 if (
st !=
ost->
st &&
st->codecpar->codec_type ==
ost->
st->codecpar->codec_type)
3570 if (j == oc->nb_streams)
3571 if (
ost->
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
3572 ost->
st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
3573 ost->
st->disposition = AV_DISPOSITION_DEFAULT;
3576 if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3585 av_log(NULL, AV_LOG_WARNING,
3587 "about the input framerate is available. Falling "
3588 "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
3589 "if you want a different framerate.\n",
3603 if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
3609 switch (enc_ctx->codec_type) {
3610 case AVMEDIA_TYPE_AUDIO:
3613 enc_ctx->bits_per_raw_sample = FFMIN(
dec_ctx->bits_per_raw_sample,
3614 av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
3615 enc_ctx->sample_rate = av_buffersink_get_sample_rate(
ost->
filter->
filter);
3616 enc_ctx->channel_layout = av_buffersink_get_channel_layout(
ost->
filter->
filter);
3622 case AVMEDIA_TYPE_VIDEO:
3625 if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
3626 enc_ctx->time_base = av_buffersink_get_time_base(
ost->
filter->
filter);
3629 av_log(oc, AV_LOG_WARNING,
"Frame rate very high for a muxer not efficiently supporting it.\n"
3630 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3635 enc_ctx->sample_aspect_ratio =
ost->
st->sample_aspect_ratio =
3642 enc_ctx->bits_per_raw_sample = FFMIN(
dec_ctx->bits_per_raw_sample,
3643 av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
3646 enc_ctx->color_range = frame->color_range;
3647 enc_ctx->color_primaries = frame->color_primaries;
3648 enc_ctx->color_trc = frame->color_trc;
3649 enc_ctx->colorspace = frame->colorspace;
3650 enc_ctx->chroma_sample_location = frame->chroma_location;
3658 enc_ctx->width !=
dec_ctx->width ||
3659 enc_ctx->height !=
dec_ctx->height ||
3660 enc_ctx->pix_fmt !=
dec_ctx->pix_fmt) {
3666 if (enc_ctx->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
3670 if (frame->interlaced_frame) {
3671 if (enc_ctx->codec->id == AV_CODEC_ID_MJPEG)
3672 enc_ctx->field_order = frame->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
3674 enc_ctx->field_order = frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
3676 enc_ctx->field_order = AV_FIELD_PROGRESSIVE;
3681 enc_ctx->field_order = AV_FIELD_BB;
3683 enc_ctx->field_order = AV_FIELD_TT;
3691 av_log(NULL, AV_LOG_ERROR,
3707 case AVMEDIA_TYPE_SUBTITLE:
3708 enc_ctx->time_base = AV_TIME_BASE_Q;
3709 if (!enc_ctx->width) {
3714 case AVMEDIA_TYPE_DATA:
3731 const AVCodec *codec =
ost->
enc;
3732 AVCodecContext *
dec = NULL;
3741 if (
dec &&
dec->subtitle_header) {
3743 ost->
enc_ctx->subtitle_header = av_mallocz(
dec->subtitle_header_size + 1);
3745 return AVERROR(ENOMEM);
3746 memcpy(
ost->
enc_ctx->subtitle_header,
dec->subtitle_header,
dec->subtitle_header_size);
3747 ost->
enc_ctx->subtitle_header_size =
dec->subtitle_header_size;
3751 if (
ost->
enc->type == AVMEDIA_TYPE_AUDIO &&
3759 snprintf(error, error_len,
"Device setup failed for "
3760 "encoder on output stream #%d:%d : %s",
3765 if (
ist &&
ist->dec->type == AVMEDIA_TYPE_SUBTITLE &&
ost->
enc->type == AVMEDIA_TYPE_SUBTITLE) {
3766 int input_props = 0, output_props = 0;
3767 AVCodecDescriptor
const *input_descriptor =
3768 avcodec_descriptor_get(
dec->codec_id);
3769 AVCodecDescriptor
const *output_descriptor =
3770 avcodec_descriptor_get(
ost->
enc_ctx->codec_id);
3771 if (input_descriptor)
3772 input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3773 if (output_descriptor)
3774 output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3775 if (input_props && output_props && input_props != output_props) {
3776 snprintf(error, error_len,
3777 "Subtitle encoding currently only possible from text to text "
3778 "or bitmap to bitmap");
3779 return AVERROR_INVALIDDATA;
3784 if (
ret == AVERROR_EXPERIMENTAL)
3786 snprintf(error, error_len,
3787 "Error while opening encoder for output stream #%d:%d - "
3788 "maybe incorrect parameters such as bit_rate, rate, width or height",
3792 if (
ost->
enc->type == AVMEDIA_TYPE_AUDIO &&
3793 !(
ost->
enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
3798 ost->
enc_ctx->codec_id != AV_CODEC_ID_CODEC2 )
3799 av_log(NULL, AV_LOG_WARNING,
"The bitrate parameter is set too low."
3800 " It takes bits/s as argument, not kbits/s\n");
3804 av_log(NULL, AV_LOG_FATAL,
3805 "Error initializing the output stream codec context.\n");
3812 for (i = 0; i <
ost->
enc_ctx->nb_coded_side_data; i++) {
3813 const AVPacketSideData *sd_src = &
ost->
enc_ctx->coded_side_data[i];
3816 dst_data = av_stream_new_side_data(
ost->
st, sd_src->type, sd_src->size);
3818 return AVERROR(ENOMEM);
3819 memcpy(dst_data, sd_src->data, sd_src->size);
3832 for (i = 0; i <
ist->st->nb_side_data; i++) {
3833 AVPacketSideData *sd = &
ist->st->side_data[i];
3834 if (sd->type != AV_PKT_DATA_CPB_PROPERTIES) {
3835 uint8_t *dst = av_stream_new_side_data(
ost->
st, sd->type, sd->size);
3837 return AVERROR(ENOMEM);
3838 memcpy(dst, sd->data, sd->size);
3839 if (
ist->autorotate && sd->type == AV_PKT_DATA_DISPLAYMATRIX)
3840 av_display_rotation_set((uint32_t *)dst, 0);
3846 if (
ost->
st->time_base.num <= 0 ||
ost->
st->time_base.den <= 0)
3847 ost->
st->time_base = av_add_q(
ost->
enc_ctx->time_base, (AVRational){0, 1});
3850 if (
ost->
st->duration <= 0 &&
ist &&
ist->st->duration > 0)
3851 ost->
st->duration = av_rescale_q(
ist->st->duration,
ist->st->time_base,
ost->
st->time_base);
3860 static const AVOption opts[] = {
3861 {
"disposition" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, (double)INT64_MAX, .unit =
"flags" },
3862 {
"default" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT }, .unit =
"flags" },
3863 {
"dub" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB }, .unit =
"flags" },
3864 {
"original" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL }, .unit =
"flags" },
3865 {
"comment" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT }, .unit =
"flags" },
3866 {
"lyrics" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS }, .unit =
"flags" },
3867 {
"karaoke" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE }, .unit =
"flags" },
3868 {
"forced" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED }, .unit =
"flags" },
3869 {
"hearing_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED }, .unit =
"flags" },
3870 {
"visual_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED }, .unit =
"flags" },
3871 {
"clean_effects" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS }, .unit =
"flags" },
3872 {
"attached_pic" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ATTACHED_PIC }, .unit =
"flags" },
3873 {
"captions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS }, .unit =
"flags" },
3874 {
"descriptions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS }, .unit =
"flags" },
3875 {
"dependent" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEPENDENT }, .unit =
"flags" },
3876 {
"metadata" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA }, .unit =
"flags" },
3879 static const AVClass
class = {
3881 .item_name = av_default_item_name,
3883 .version = LIBAVUTIL_VERSION_INT,
3885 const AVClass *pclass = &
class;
3911 AVStream *st = file->
ctx->streams[pkt->stream_index];
3915 av_log(file->
ctx, AV_LOG_WARNING,
3916 "New %s stream %d:%d at pos:%"PRId64
" and DTS:%ss\n",
3917 av_get_media_type_string(st->codecpar->codec_type),
3918 input_index, pkt->stream_index,
3919 pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
3925 int ret = 0, i, j, k;
3926 AVFormatContext *oc;
3929 char error[1024] = {0};
3987 for (j = 0; j < ifile->
ctx->nb_programs; j++) {
3988 AVProgram *p = ifile->
ctx->programs[j];
3989 int discard = AVDISCARD_ALL;
3991 for (k = 0; k < p->nb_stream_indexes; k++)
3993 discard = AVDISCARD_DEFAULT;
3996 p->discard = discard;
4003 if (oc->oformat->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
4012 av_log(NULL, AV_LOG_INFO,
"Stream mapping:\n");
4016 for (j = 0; j <
ist->nb_filters; j++) {
4018 av_log(NULL, AV_LOG_INFO,
" Stream #%d:%d (%s) -> %s",
4019 ist->file_index,
ist->st->index,
ist->dec ?
ist->dec->name :
"?",
4020 ist->filters[j]->name);
4022 av_log(NULL, AV_LOG_INFO,
" (graph %d)",
ist->filters[j]->graph->index);
4023 av_log(NULL, AV_LOG_INFO,
"\n");
4033 av_log(NULL, AV_LOG_INFO,
" File %s -> Stream #%d:%d\n",
4044 av_log(NULL, AV_LOG_INFO,
" -> Stream #%d:%d (%s)\n",
ost->
file_index,
4049 av_log(NULL, AV_LOG_INFO,
" Stream #%d:%d -> #%d:%d",
4055 av_log(NULL, AV_LOG_INFO,
" [sync #%d:%d]",
4059 av_log(NULL, AV_LOG_INFO,
" (copy)");
4062 const AVCodec *out_codec =
ost->
enc;
4063 const char *decoder_name =
"?";
4064 const char *in_codec_name =
"?";
4065 const char *encoder_name =
"?";
4066 const char *out_codec_name =
"?";
4067 const AVCodecDescriptor *desc;
4070 decoder_name = in_codec->name;
4071 desc = avcodec_descriptor_get(in_codec->id);
4073 in_codec_name = desc->name;
4074 if (!strcmp(decoder_name, in_codec_name))
4075 decoder_name =
"native";
4079 encoder_name = out_codec->name;
4080 desc = avcodec_descriptor_get(out_codec->id);
4082 out_codec_name = desc->name;
4083 if (!strcmp(encoder_name, out_codec_name))
4084 encoder_name =
"native";
4087 av_log(NULL, AV_LOG_INFO,
" (%s (%s) -> %s (%s))",
4088 in_codec_name, decoder_name,
4089 out_codec_name, encoder_name);
4091 av_log(NULL, AV_LOG_INFO,
"\n");
4095 av_log(NULL, AV_LOG_ERROR,
"%s\n", error);
4119 for (j = 0; j < of->
ctx->nb_streams; j++)
4138 int64_t opts_min = INT64_MAX;
4147 av_log(NULL, AV_LOG_DEBUG,
4148 "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",
4166 if (tcgetattr(0, &tty) == 0) {
4167 if (on) tty.c_lflag |= ECHO;
4168 else tty.c_lflag &= ~ECHO;
4169 tcsetattr(0, TCSANOW, &tty);
4178 return AVERROR_EXIT;
4186 return AVERROR_EXIT;
4187 if (key ==
'+') av_log_set_level(av_log_get_level()+10);
4188 if (key ==
'-') av_log_set_level(av_log_get_level()-10);
4197 av_log_set_level(AV_LOG_DEBUG);
4199 if (key ==
'c' || key ==
'C'){
4200 char buf[4096], target[64], command[256], arg[256] = {0};
4203 fprintf(stderr,
"\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
4206 while ((k =
read_key()) !=
'\n' && k !=
'\r' && i <
sizeof(buf)-1)
4211 fprintf(stderr,
"\n");
4213 (n = sscanf(buf,
"%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
4214 av_log(NULL, AV_LOG_DEBUG,
"Processing command target:%s time:%f command:%s arg:%s",
4215 target, time, command, arg);
4220 ret = avfilter_graph_send_command(fg->
graph, target, command, arg, buf,
sizeof(buf),
4221 key ==
'c' ? AVFILTER_CMD_FLAG_ONE : 0);
4222 fprintf(stderr,
"Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
4223 }
else if (key ==
'c') {
4224 fprintf(stderr,
"Queuing commands only on filters supporting the specific command is unsupported\n");
4225 ret = AVERROR_PATCHWELCOME;
4227 ret = avfilter_graph_queue_command(fg->
graph, target, command, arg, 0, time);
4229 fprintf(stderr,
"Queuing command failed with error %s\n", av_err2str(ret));
4234 av_log(NULL, AV_LOG_ERROR,
4235 "Parse error, at least 3 arguments were expected, "
4236 "only %d given in string '%s'\n", n, buf);
4239 if (key ==
'd' || key ==
'D'){
4243 if(!debug) debug = 1;
4244 while (debug & FF_DEBUG_DCT_COEFF)
4251 while ((k =
read_key()) !=
'\n' && k !=
'\r' && i <
sizeof(buf)-1)
4256 fprintf(stderr,
"\n");
4257 if (k <= 0 || sscanf(buf,
"%d", &debug)!=1)
4258 fprintf(stderr,
"error parsing debug value\n");
4267 if(debug) av_log_set_level(AV_LOG_DEBUG);
4268 fprintf(stderr,
"debug=%d\n", debug);
4271 fprintf(stderr,
"key function\n"
4272 "? show this help\n"
4273 "+ increase verbosity\n"
4274 "- decrease verbosity\n"
4275 "c Send command to first matching filter supporting it\n"
4276 "C Send/Queue command to all matching filters\n"
4277 "D cycle through available debug modes\n"
4278 "h dump packets/hex press to cycle through the 3 states\n"
4280 "s Show QP histogram\n"
4287static void *input_thread(
void *arg)
4290 AVPacket *pkt = f->
pkt, *queue_pkt;
4291 unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
4295 ret = av_read_frame(f->
ctx, pkt);
4297 if (ret == AVERROR(EAGAIN)) {
4302 av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
4305 queue_pkt = av_packet_alloc();
4307 av_packet_unref(pkt);
4308 av_thread_message_queue_set_err_recv(f->in_thread_queue, AVERROR(ENOMEM));
4311 av_packet_move_ref(queue_pkt, pkt);
4312 ret = av_thread_message_queue_send(f->in_thread_queue, &queue_pkt, flags);
4313 if (flags && ret == AVERROR(EAGAIN)) {
4315 ret = av_thread_message_queue_send(f->in_thread_queue, &queue_pkt, flags);
4316 av_log(f->
ctx, AV_LOG_WARNING,
4317 "Thread message queue blocking; consider raising the "
4318 "thread_queue_size option (current value: %d)\n",
4319 f->thread_queue_size);
4322 if (ret != AVERROR_EOF)
4323 av_log(f->
ctx, AV_LOG_ERROR,
4324 "Unable to send packet to main thread: %s\n",
4326 av_packet_free(&queue_pkt);
4327 av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
4335static void free_input_thread(
int i)
4340 if (!f || !f->in_thread_queue)
4342 av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
4343 while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
4344 av_packet_free(&pkt);
4346 pthread_join(f->thread, NULL);
4348 av_thread_message_queue_free(&f->in_thread_queue);
4351static void free_input_threads(
void)
4356 free_input_thread(i);
4359static int init_input_thread(
int i)
4364 if (f->thread_queue_size < 0)
4366 if (!f->thread_queue_size)
4369 if (f->
ctx->pb ? !f->
ctx->pb->seekable :
4370 strcmp(f->
ctx->iformat->name,
"lavfi"))
4371 f->non_blocking = 1;
4372 ret = av_thread_message_queue_alloc(&f->in_thread_queue,
4373 f->thread_queue_size,
sizeof(f->
pkt));
4377 if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
4378 av_log(NULL, AV_LOG_ERROR,
"pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
4379 av_thread_message_queue_free(&f->in_thread_queue);
4380 return AVERROR(ret);
4386static int init_input_threads(
void)
4391 ret = init_input_thread(i);
4398static int get_input_packet_mt(
InputFile *f, AVPacket **pkt)
4400 return av_thread_message_queue_recv(f->in_thread_queue, pkt,
4402 AV_THREAD_MESSAGE_NONBLOCK : 0);
4410 int64_t file_start =
copy_ts * (
4417 int64_t stream_ts_offset, pts, now;
4418 if (!
ist->nb_packets || (
ist->decoding_needed && !
ist->got_output))
continue;
4419 stream_ts_offset = FFMAX(
ist->first_dts != AV_NOPTS_VALUE ?
ist->first_dts : 0, file_start);
4420 pts = av_rescale(
ist->dts, 1000000, AV_TIME_BASE);
4421 now = (av_gettime_relative() -
ist->start) * scale + stream_ts_offset;
4423 return AVERROR(EAGAIN);
4428 if (f->thread_queue_size)
4429 return get_input_packet_mt(f, pkt);
4432 return av_read_frame(f->
ctx, *pkt);
4454static AVRational
duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
4455 AVRational time_base)
4461 return tmp_time_base;
4464 ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
4467 return tmp_time_base;
4476 AVCodecContext *avctx;
4477 int i, ret, has_audio = 0;
4478 int64_t duration = 0;
4480 ret = avformat_seek_file(is, -1, INT64_MIN, is->start_time, is->start_time, 0);
4486 avctx =
ist->dec_ctx;
4491 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
ist->nb_samples)
4497 avctx =
ist->dec_ctx;
4500 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
ist->nb_samples) {
4508 if (
ist->framerate.num) {
4509 duration = av_rescale_q(1, av_inv_q(
ist->framerate),
ist->st->time_base);
4510 }
else if (
ist->st->avg_frame_rate.num) {
4511 duration = av_rescale_q(1, av_inv_q(
ist->st->avg_frame_rate),
ist->st->time_base);
4520 if (
ist->max_pts >
ist->min_pts &&
ist->max_pts - (uint64_t)
ist->min_pts < INT64_MAX - duration)
4521 duration +=
ist->max_pts -
ist->min_pts;
4526 if (ifile->
loop > 0)
4542 AVFormatContext *is;
4545 int ret, thread_ret, i, j;
4548 int disable_discontinuity_correction =
copy_ts;
4553 if (ret == AVERROR(EAGAIN)) {
4557 if (ret < 0 && ifile->loop) {
4558 AVCodecContext *avctx;
4561 avctx =
ist->dec_ctx;
4562 if (
ist->decoding_needed) {
4566 avcodec_flush_buffers(avctx);
4570 free_input_thread(file_index);
4574 thread_ret = init_input_thread(file_index);
4579 av_log(NULL, AV_LOG_WARNING,
"Seek to start failed.\n");
4582 if (ret == AVERROR(EAGAIN)) {
4588 if (ret != AVERROR_EOF) {
4596 if (
ist->decoding_needed) {
4613 return AVERROR(EAGAIN);
4619 av_pkt_dump_log2(NULL, AV_LOG_INFO, pkt,
do_hex_dump,
4620 is->streams[pkt->stream_index]);
4624 if (pkt->stream_index >= ifile->
nb_streams) {
4626 goto discard_packet;
4631 ist->data_size += pkt->size;
4635 goto discard_packet;
4637 if (pkt->flags & AV_PKT_FLAG_CORRUPT) {
4639 "%s: corrupt input packet in stream %d\n", is->url, pkt->stream_index);
4645 av_log(NULL, AV_LOG_INFO,
"demuxer -> ist_index:%d type:%s "
4646 "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",
4647 ifile->
ist_index + pkt->stream_index, av_get_media_type_string(
ist->dec_ctx->codec_type),
4648 av_ts2str(
ist->next_dts), av_ts2timestr(
ist->next_dts, &AV_TIME_BASE_Q),
4649 av_ts2str(
ist->next_pts), av_ts2timestr(
ist->next_pts, &AV_TIME_BASE_Q),
4650 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &
ist->st->time_base),
4651 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &
ist->st->time_base),
4656 if(!
ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE &&
ist->st->pts_wrap_bits < 64){
4657 int64_t stime, stime2;
4661 if (
ist->next_dts == AV_NOPTS_VALUE
4663 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
4664 int64_t new_start_time = INT64_MAX;
4665 for (i=0; i<is->nb_streams; i++) {
4666 AVStream *st = is->streams[i];
4667 if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
4669 new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
4671 if (new_start_time > is->start_time) {
4672 av_log(is, AV_LOG_VERBOSE,
"Correcting start time by %"PRId64
"\n", new_start_time - is->start_time);
4677 stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q,
ist->st->time_base);
4678 stime2= stime + (1ULL<<
ist->st->pts_wrap_bits);
4679 ist->wrap_correction_done = 1;
4681 if(stime2 > stime && pkt->dts != AV_NOPTS_VALUE && pkt->dts > stime + (1LL<<(
ist->st->pts_wrap_bits-1))) {
4682 pkt->dts -= 1ULL<<
ist->st->pts_wrap_bits;
4683 ist->wrap_correction_done = 0;
4685 if(stime2 > stime && pkt->pts != AV_NOPTS_VALUE && pkt->pts > stime + (1LL<<(
ist->st->pts_wrap_bits-1))) {
4686 pkt->pts -= 1ULL<<
ist->st->pts_wrap_bits;
4687 ist->wrap_correction_done = 0;
4692 if (
ist->nb_packets == 1) {
4693 for (i = 0; i <
ist->st->nb_side_data; i++) {
4694 AVPacketSideData *src_sd = &
ist->st->side_data[i];
4697 if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
4700 if (av_packet_get_side_data(pkt, src_sd->type, NULL))
4703 dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
4707 memcpy(dst_data, src_sd->data, src_sd->size);
4711 if (pkt->dts != AV_NOPTS_VALUE)
4712 pkt->dts += av_rescale_q(ifile->
ts_offset, AV_TIME_BASE_Q,
ist->st->time_base);
4713 if (pkt->pts != AV_NOPTS_VALUE)
4714 pkt->pts += av_rescale_q(ifile->
ts_offset, AV_TIME_BASE_Q,
ist->st->time_base);
4716 if (pkt->pts != AV_NOPTS_VALUE)
4717 pkt->pts *=
ist->ts_scale;
4718 if (pkt->dts != AV_NOPTS_VALUE)
4719 pkt->dts *=
ist->ts_scale;
4721 pkt_dts = av_rescale_q_rnd(pkt->dts,
ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4722 if ((
ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
4723 ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
4724 pkt_dts != AV_NOPTS_VALUE &&
ist->next_dts == AV_NOPTS_VALUE && !
copy_ts
4725 && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->
last_ts != AV_NOPTS_VALUE) {
4726 int64_t delta = pkt_dts - ifile->
last_ts;
4730 av_log(NULL, AV_LOG_DEBUG,
4731 "Inter stream timestamp discontinuity %"PRId64
", new offset= %"PRId64
"\n",
4733 pkt->dts -= av_rescale_q(delta, AV_TIME_BASE_Q,
ist->st->time_base);
4734 if (pkt->pts != AV_NOPTS_VALUE)
4735 pkt->pts -= av_rescale_q(delta, AV_TIME_BASE_Q,
ist->st->time_base);
4740 if (pkt->pts != AV_NOPTS_VALUE) {
4741 pkt->pts += duration;
4742 ist->max_pts = FFMAX(pkt->pts,
ist->max_pts);
4743 ist->min_pts = FFMIN(pkt->pts,
ist->min_pts);
4746 if (pkt->dts != AV_NOPTS_VALUE)
4747 pkt->dts += duration;
4749 pkt_dts = av_rescale_q_rnd(pkt->dts,
ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4751 if (
copy_ts && pkt_dts != AV_NOPTS_VALUE &&
ist->next_dts != AV_NOPTS_VALUE &&
4752 (is->iformat->flags & AVFMT_TS_DISCONT) &&
ist->st->pts_wrap_bits < 60) {
4753 int64_t wrap_dts = av_rescale_q_rnd(pkt->dts + (1LL<<
ist->st->pts_wrap_bits),
4754 ist->st->time_base, AV_TIME_BASE_Q,
4755 AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4756 if (FFABS(wrap_dts -
ist->next_dts) < FFABS(pkt_dts -
ist->next_dts)/10)
4757 disable_discontinuity_correction = 0;
4760 if ((
ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
4761 ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
4762 pkt_dts != AV_NOPTS_VALUE &&
ist->next_dts != AV_NOPTS_VALUE &&
4763 !disable_discontinuity_correction) {
4764 int64_t delta = pkt_dts -
ist->next_dts;
4765 if (is->iformat->flags & AVFMT_TS_DISCONT) {
4768 pkt_dts + AV_TIME_BASE/10 < FFMAX(
ist->pts,
ist->dts)) {
4770 av_log(NULL, AV_LOG_DEBUG,
4771 "timestamp discontinuity for stream #%d:%d "
4772 "(id=%d, type=%s): %"PRId64
", new offset= %"PRId64
"\n",
4773 ist->file_index,
ist->st->index,
ist->st->id,
4774 av_get_media_type_string(
ist->dec_ctx->codec_type),
4776 pkt->dts -= av_rescale_q(delta, AV_TIME_BASE_Q,
ist->st->time_base);
4777 if (pkt->pts != AV_NOPTS_VALUE)
4778 pkt->pts -= av_rescale_q(delta, AV_TIME_BASE_Q,
ist->st->time_base);
4783 av_log(NULL, AV_LOG_WARNING,
"DTS %"PRId64
", next:%"PRId64
" st:%d invalid dropping\n", pkt->dts,
ist->next_dts, pkt->stream_index);
4784 pkt->dts = AV_NOPTS_VALUE;
4786 if (pkt->pts != AV_NOPTS_VALUE){
4787 int64_t pkt_pts = av_rescale_q(pkt->pts,
ist->st->time_base, AV_TIME_BASE_Q);
4788 delta = pkt_pts -
ist->next_dts;
4791 av_log(NULL, AV_LOG_WARNING,
"PTS %"PRId64
", next:%"PRId64
" invalid dropping st:%d\n", pkt->pts,
ist->next_dts, pkt->stream_index);
4792 pkt->pts = AV_NOPTS_VALUE;
4798 if (pkt->dts != AV_NOPTS_VALUE)
4799 ifile->
last_ts = av_rescale_q(pkt->dts,
ist->st->time_base, AV_TIME_BASE_Q);
4802 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",
4803 ifile->
ist_index + pkt->stream_index, av_get_media_type_string(
ist->dec_ctx->codec_type),
4804 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &
ist->st->time_base),
4805 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &
ist->st->time_base),
4816 if (ifile->thread_queue_size)
4817 av_packet_free(&pkt);
4820 av_packet_unref(pkt);
4835 int nb_requests, nb_requests_max = 0;
4840 ret = avfilter_graph_request_oldest(
graph->graph);
4844 if (ret == AVERROR_EOF) {
4846 for (i = 0; i <
graph->nb_outputs; i++)
4850 if (ret != AVERROR(EAGAIN))
4853 for (i = 0; i <
graph->nb_inputs; i++) {
4854 ifilter =
graph->inputs[i];
4859 nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->
filter);
4860 if (nb_requests > nb_requests_max) {
4861 nb_requests_max = nb_requests;
4867 for (i = 0; i <
graph->nb_outputs; i++)
4868 graph->outputs[i]->ost->unavailable = 1;
4891 av_log(NULL, AV_LOG_VERBOSE,
"No more inputs to read from, finishing.\n");
4899 av_log(NULL, AV_LOG_ERROR,
"Error reinitializing filters!\n");
4927 if (av_buffersink_get_type(
ost->
filter->
filter) == AVMEDIA_TYPE_AUDIO)
4953 if (ret == AVERROR(EAGAIN)) {
4960 return ret == AVERROR_EOF ? 0 : ret;
4971 AVFormatContext *os;
4974 int64_t timer_start;
4975 int64_t total_packets_written = 0;
4982 av_log(NULL, AV_LOG_INFO,
"Press [q] to stop, [?] for help\n");
4985 timer_start = av_gettime_relative();
4988 if ((ret = init_input_threads()) < 0)
4993 int64_t cur_time= av_gettime_relative();
5002 av_log(NULL, AV_LOG_VERBOSE,
"No more output streams to write to, finishing.\n");
5007 if (ret < 0 && ret != AVERROR_EOF) {
5008 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(ret));
5016 free_input_threads();
5034 av_log(NULL, AV_LOG_ERROR,
5035 "Nothing was written into output file %d (%s), because "
5036 "at least one of its streams received no packets.\n",
5040 if ((ret = av_write_trailer(os)) < 0) {
5041 av_log(NULL, AV_LOG_ERROR,
"Error writing trailer of %s: %s\n", os->url, av_err2str(ret));
5058 av_log(NULL, AV_LOG_FATAL,
"Empty output on stream %d.\n", i);
5064 av_log(NULL, AV_LOG_FATAL,
"Empty output\n");
5071 if (
ist->decoding_needed) {
5072 avcodec_close(
ist->dec_ctx);
5073 if (
ist->hwaccel_uninit)
5074 ist->hwaccel_uninit(
ist->dec_ctx);
5085 free_input_threads();
5094 av_log(NULL, AV_LOG_ERROR,
5095 "Error closing logfile, loss of information possible: %s\n",
5096 av_err2str(AVERROR(errno)));
5116 struct rusage rusage;
5118 getrusage(RUSAGE_SELF, &rusage);
5120 (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
5122 (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
5123#elif HAVE_GETPROCESSTIMES
5125 FILETIME c, e, k, u;
5126 proc = GetCurrentProcess();
5127 GetProcessTimes(proc, &c, &e, &k, &u);
5129 ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
5131 ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
5140#if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
5141 struct rusage rusage;
5142 getrusage(RUSAGE_SELF, &rusage);
5143 return (int64_t)rusage.ru_maxrss * 1024;
5144#elif HAVE_GETPROCESSMEMORYINFO
5146 PROCESS_MEMORY_COUNTERS memcounters;
5147 proc = GetCurrentProcess();
5148 memcounters.cb =
sizeof(memcounters);
5149 GetProcessMemoryInfo(proc, &memcounters,
sizeof(memcounters));
5150 return memcounters.PeakPagefileUsage;
5214 char _program_name[] =
"ffmpeg";
5218 #define OFFSET(x) offsetof(OptionsContext, x)
5236 {
"bsfs",
OPT_EXIT, { .func_arg =
show_bsfs },
"show available bit stream filters" },
5245 {
"report", 0, { .func_arg =
opt_report },
"generate a report" },
5246 {
"max_alloc",
HAS_ARG, { .func_arg =
opt_max_alloc },
"set maximum size of a single allocated block",
"bytes" },
5253 "list sources of the input device",
"device" },
5255 "list sinks of the output device",
"device" },
5260 "force format",
"fmt" },
5262 "overwrite output files" },
5264 "never overwrite output files" },
5266 "Ignore unknown stream types" },
5268 "Copy unknown stream types" },
5271 "codec name",
"codec" },
5274 "codec name",
"codec" },
5277 "preset name",
"preset" },
5280 "set input stream mapping",
5281 "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
5283 "map an audio channel from one stream to another",
"file.stream.channel[:syncfile.syncstream]" },
5286 "set metadata information of outfile from infile",
5287 "outfile[,metadata]:infile[,metadata]" },
5290 "set chapters mapping",
"input_file_index" },
5293 "record or transcode \"duration\" seconds of audio/video",
5296 "record or transcode stop time",
"time_stop" },
5298 "set the limit file size in bytes",
"limit_size" },
5301 "set the start time offset",
"time_off" },
5304 "set the start time offset relative to EOF",
"time_off" },
5307 "enable/disable seeking by timestamp with -ss" },
5310 "enable/disable accurate seeking with -ss" },
5313 "set the input ts offset",
"time_off" },
5316 "set the input ts scale",
"scale" },
5318 "set the recording timestamp ('now' to set the current time)",
"time" },
5320 "add metadata",
"string=string" },
5322 "add program with specified streams",
"title=string:st=number..." },
5325 "set the number of data frames to output",
"number" },
5327 "add timings for benchmarking" },
5329 "add timings for each task" },
5331 "write program-readable progress information",
"url" },
5333 "enable or disable interaction on standard input" },
5335 "set max runtime in seconds in CPU user time",
"limit" },
5337 "dump each input packet" },
5339 "when dumping packets, also dump the payload" },
5342 "read input at native frame rate",
"" },
5344 "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\" or \"dv50\" "
5345 "with optional prefixes \"pal-\", \"ntsc-\" or \"film-\")",
"type" },
5347 "video sync method",
"" },
5349 "frame drop threshold",
"" },
5351 "audio sync method",
"" },
5353 "audio drift threshold",
"threshold" },
5355 "copy timestamps" },
5357 "shift input timestamps to start at 0 when using copyts" },
5359 "copy input stream time base when stream copying",
"mode" },
5361 "shift input timestamps to start at 0 when using copyts" },
5363 "copy input stream time base when stream copying",
"mode" },
5366 "finish encoding within shortest input" },
5374 "timestamp discontinuity delta threshold",
"threshold" },
5376 "timestamp error delta threshold",
"threshold" },
5378 "exit on error",
"error" },
5380 "abort on the specified condition flags",
"flags" },
5383 "copy initial non-keyframes" },
5385 "copy or discard frames before start time" },
5387 "set the number of frames to output",
"number" },
5390 "force codec tag/fourcc",
"fourcc/tag" },
5393 "use fixed quality scale (VBR)",
"q" },
5396 "use fixed quality scale (VBR)",
"q" },
5398 "set profile",
"profile" },
5400 "set stream filtergraph",
"filter_graph" },
5402 "number of non-complex filter threads" },
5404 "read stream filtergraph description from a file",
"filename" },
5406 "reinit filtergraph on input parameter changes",
"" },
5408 "create a complex filtergraph",
"graph_description" },
5410 "number of threads for -filter_complex" },
5412 "create a complex filtergraph",
"graph_description" },
5414 "read complex filtergraph description from a file",
"filename" },
5416 "enable automatic conversion filters globally" },
5418 "print progress report during encoding", },
5420 "set the period at which ffmpeg updates stats and -progress output",
"time" },
5423 "add an attachment to the output file",
"filename" },
5426 "extract an attachment into a file",
"filename" },
5428 OPT_OFFSET, { .off =
OFFSET(loop) },
"set number of times input stream shall be looped",
"loop count" },
5430 "print timestamp debugging info" },
5432 "ratio of errors (0.0: no errors, 1.0: 100% errors) above which ffmpeg returns an error instead of success.",
"maximum error rate" },
5438 "disposition",
"" },
5440 { .off =
OFFSET(thread_queue_size) },
5441 "set the maximum number of queued packets from the demuxer" },
5443 "read and decode the streams to fill missing information with heuristics" },
5447 "set the number of video frames to output",
"number" },
5450 "set frame rate (Hz value, fraction or abbreviation)",
"rate" },
5453 "set frame size (WxH or abbreviation)",
"size" },
5456 "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)",
"aspect" },
5459 "set pixel format",
"format" },
5461 "set the number of bits per raw sample",
"number" },
5463 "deprecated use -g 1" },
5468 "rate control override for specific intervals",
"override" },
5471 "force video codec ('copy' to copy stream)",
"codec" },
5477 "set initial TimeCode value.",
"hh:mm:ss[:;.]ff" },
5479 "select the pass number (1 to 3)",
"n" },
5482 "select two pass log file name prefix",
"prefix" },
5484 "this option is deprecated, use the yadif filter instead" },
5486 "calculate PSNR of compressed frames" },
5488 "dump video coding statistics to file" },
5490 "dump video coding statistics to file",
"file" },
5492 "Version of the vstats format to use."},
5494 "set video filters",
"filter_graph" },
5497 "specify intra matrix coeffs",
"matrix" },
5500 "specify inter matrix coeffs",
"matrix" },
5503 "specify intra matrix coeffs",
"matrix" },
5506 "top=1/bottom=0/auto=-1 field first",
"" },
5509 "force video tag/fourcc",
"fourcc/tag" },
5511 "show QP histogram" },
5514 "force the selected framerate, disable the best supported framerate selection" },
5517 "set the value of an outfile streamid",
"streamIndex:value" },
5520 "force key frames at specified timestamps",
"timestamps" },
5522 "audio bitrate (please use -b:a)",
"bitrate" },
5524 "video bitrate (please use -b:v)",
"bitrate" },
5527 "use HW accelerated decoding",
"hwaccel name" },
5530 "select a device for HW acceleration",
"devicename" },
5533 "select output format used with HW accelerated decoding",
"format" },
5534 #if CONFIG_VIDEOTOOLBOX
5538 "show available HW acceleration methods" },
5541 "automatically insert correct rotate filters" },
5544 "automatically insert a scale filter at the end of the filter graph" },
5548 "set the number of audio frames to output",
"number" },
5550 "set audio quality (codec-specific)",
"quality", },
5553 "set audio sampling rate (in Hz)",
"rate" },
5556 "set number of audio channels",
"channels" },
5561 "force audio codec ('copy' to copy stream)",
"codec" },
5564 "force audio tag/fourcc",
"fourcc/tag" },
5566 "change audio volume (256=normal)" ,
"volume" },
5569 "set sample format",
"format" },
5572 "set channel layout",
"layout" },
5574 "set audio filters",
"filter_graph" },
5576 "set the maximum number of channels to try to guess the channel layout" },
5580 "disable subtitle" },
5582 "force subtitle codec ('copy' to copy stream)",
"codec" },
5584 ,
"force subtitle tag/fourcc",
"fourcc/tag" },
5586 "fix subtitles duration" },
5588 "set canvas size (WxH or abbreviation)",
"size" },
5592 "deprecated, use -channel",
"channel" },
5594 "deprecated, use -standard",
"standard" },
5599 "set the maximum demux-decode delay",
"seconds" },
5601 "set the initial demux-decode delay",
"seconds" },
5603 "specify a file in which to print sdp information",
"file" },
5606 "set the desired time base hint for output stream (1:24, 1:48000 or 0.04166, 2.0833e-5)",
"ratio" },
5608 "set the desired time base for the encoder (1:24, 1:48000 or 0.04166, 2.0833e-5). "
5609 "two special values are defined - "
5610 "0 = use frame rate (video) or sample rate (audio),"
5611 "-1 = match source time base",
"ratio" },
5614 "A comma-separated list of bitstream filters",
"bitstream_filters" },
5616 "deprecated",
"audio bitstream_filters" },
5618 "deprecated",
"video bitstream_filters" },
5621 "set the audio options to the indicated preset",
"preset" },
5623 "set the video options to the indicated preset",
"preset" },
5625 "set the subtitle options to the indicated preset",
"preset" },
5627 "set options from indicated preset file",
"filename" },
5630 "maximum number of packets that can be buffered while waiting for all streams to initialize",
"packets" },
5632 "set the threshold after which max_muxing_queue_size is taken into account",
"bytes" },
5636 "force data codec ('copy' to copy stream)",
"codec" },
5642 "set VAAPI hardware device (DRM path or X11 display name)",
"device" },
5647 "set QSV hardware device (DirectX adapter index, DRM path or X11 display name)",
"device"},
5651 "initialise hardware device",
"args" },
5653 "set hardware device used when filtering",
"device" },
5664 if (savedCode == 0) {
5672 setvbuf(stderr,NULL,_IONBF,0);
5674 av_log_set_flags(AV_LOG_SKIP_REPEATED);
5677 if(argc>1 && !strcmp(argv[1],
"-d")){
5685 avdevice_register_all();
5687 avformat_network_init();
5698 av_log(NULL, AV_LOG_WARNING,
"Use -h to get full help or, even better, run 'man %s'\n",
program_name);
5704 av_log(NULL, AV_LOG_FATAL,
"At least one output file must be specified\n");
5709 if (strcmp(
output_files[i]->ctx->oformat->name,
"rtp"))
5717 int64_t utime, stime, rtime;
5722 av_log(NULL, AV_LOG_INFO,
5723 "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
5724 utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
5726 av_log(NULL, AV_LOG_DEBUG,
"%"PRIu64
" frames successfully decoded, %"PRIu64
" decoding errors\n",
__thread jmp_buf ex_buf__
int(* init)(AVCodecContext *s)
int64_t start_time
start time in microseconds == AV_TIME_BASE units
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
struct OutputStream * ost
uint64_t * channel_layouts
struct FilterGraph * graph
int max_muxing_queue_size
int copy_initial_nonkeyframes
double forced_keyframes_expr_const_values[FKF_NB]
AVRational frame_aspect_ratio
double rotate_override_value
int audio_channels_mapped
size_t muxing_queue_data_threshold
AVDictionary * resample_opts
AVRational max_frame_rate
AVFifoBuffer * muxing_queue
AVCodecParameters * ref_par
const char * attachment_filename
struct InputStream * sync_ist
AVDictionary * encoder_opts
char * filters
filtergraph associated to the -filter option
int64_t forced_kf_ref_pts
char * filters_script
filtergraph script associated to the -filter_script option
AVExpr * forced_keyframes_pexpr
size_t muxing_queue_data_size