111#include "libavformat/avformat.h"
112#include "libavdevice/avdevice.h"
113#include "libswresample/swresample.h"
114#include "libavutil/opt.h"
115#include "libavutil/channel_layout.h"
116#include "libavutil/parseutils.h"
117#include "libavutil/samplefmt.h"
118#include "libavutil/fifo.h"
119#include "libavutil/hwcontext.h"
120#include "libavutil/internal.h"
121#include "libavutil/intreadwrite.h"
122#include "libavutil/dict.h"
123#include "libavutil/display.h"
124#include "libavutil/mathematics.h"
125#include "libavutil/pixdesc.h"
126#include "libavutil/avstring.h"
127#include "libavutil/libm.h"
128#include "libavutil/imgutils.h"
129#include "libavutil/timestamp.h"
130#include "libavutil/bprint.h"
131#include "libavutil/time.h"
132#include "libavutil/thread.h"
133#include "libavutil/threadmessage.h"
134#include "libavcodec/mathops.h"
135#include "libavformat/os_support.h"
137# include "libavfilter/avfilter.h"
138# include "libavfilter/buffersrc.h"
139# include "libavfilter/buffersink.h"
141#if HAVE_SYS_RESOURCE_H
143#include <sys/types.h>
144#include <sys/resource.h>
145#elif HAVE_GETPROCESSTIMES
148#if HAVE_GETPROCESSMEMORYINFO
152#if HAVE_SETCONSOLECTRLHANDLER
158#include <sys/select.h>
163#include <sys/ioctl.h>
176#include "libavutil/avassert.h"
223extern int opt_map(
void *optctx,
const char *opt,
const char *arg);
224extern int opt_map_channel(
void *optctx,
const char *opt,
const char *arg);
226extern int opt_data_frames(
void *optctx,
const char *opt,
const char *arg);
227extern int opt_progress(
void *optctx,
const char *opt,
const char *arg);
228extern int opt_target(
void *optctx,
const char *opt,
const char *arg);
229extern int opt_vsync(
void *optctx,
const char *opt,
const char *arg);
230extern int opt_abort_on(
void *optctx,
const char *opt,
const char *arg);
232extern int opt_qscale(
void *optctx,
const char *opt,
const char *arg);
233extern int opt_profile(
void *optctx,
const char *opt,
const char *arg);
236extern int opt_attach(
void *optctx,
const char *opt,
const char *arg);
238extern int opt_video_codec(
void *optctx,
const char *opt,
const char *arg);
239extern int opt_sameq(
void *optctx,
const char *opt,
const char *arg);
240extern int opt_timecode(
void *optctx,
const char *opt,
const char *arg);
241extern int opt_vstats_file(
void *optctx,
const char *opt,
const char *arg);
242extern int opt_vstats(
void *optctx,
const char *opt,
const char *arg);
244extern int opt_old2new(
void *optctx,
const char *opt,
const char *arg);
245extern int opt_streamid(
void *optctx,
const char *opt,
const char *arg);
246extern int opt_bitrate(
void *optctx,
const char *opt,
const char *arg);
247extern int show_hwaccels(
void *optctx,
const char *opt,
const char *arg);
251extern int opt_audio_codec(
void *optctx,
const char *opt,
const char *arg);
253extern int opt_preset(
void *optctx,
const char *opt,
const char *arg);
258extern int opt_sdp_file(
void *optctx,
const char *opt,
const char *arg);
260extern int opt_vaapi_device(
void *optctx,
const char *opt,
const char *arg);
263extern int opt_qsv_device(
void *optctx,
const char *opt,
const char *arg);
265extern int opt_data_codec(
void *optctx,
const char *opt,
const char *arg);
279__thread
struct termios oldtty;
280__thread
int restore_tty;
303 av_frame_unref(frame);
307 if ((ret = av_frame_get_buffer(frame, 0)) < 0)
309 memset(frame->data[0], 0, frame->height * frame->linesize[0]);
316 uint32_t *pal, *dst2;
320 if (r->type != SUBTITLE_BITMAP) {
321 av_log(NULL, AV_LOG_WARNING,
"sub2video: non-bitmap subtitle\n");
324 if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
325 av_log(NULL, AV_LOG_WARNING,
"sub2video: rectangle (%d %d %d %d) overflowing %d %d\n",
326 r->x, r->y, r->w, r->h, w, h
331 dst += r->y * dst_linesize + r->x * 4;
333 pal = (uint32_t *)r->data[1];
334 for (y = 0; y < r->h; y++) {
335 dst2 = (uint32_t *)dst;
337 for (x = 0; x < r->w; x++)
338 *(dst2++) = pal[*(src2++)];
340 src += r->linesize[0];
350 av_assert1(frame->data[0]);
353 ret = av_buffersrc_add_frame_flags(ist->
filters[i]->
filter, frame,
354 AV_BUFFERSRC_FLAG_KEEP_REF |
355 AV_BUFFERSRC_FLAG_PUSH);
356 if (ret != AVERROR_EOF && ret < 0)
357 av_log(NULL, AV_LOG_WARNING,
"Error while add the frame to buffer source(%s).\n",
368 int64_t pts, end_pts;
373 pts = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
374 AV_TIME_BASE_Q, ist->
st->time_base);
375 end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000LL,
376 AV_TIME_BASE_Q, ist->
st->time_base);
377 num_rects = sub->num_rects;
389 av_log(NULL, AV_LOG_ERROR,
390 "Impossible to get a blank canvas.\n");
393 dst = frame->data [0];
394 dst_linesize = frame->linesize[0];
395 for (i = 0; i < num_rects; i++)
418 pts2 = av_rescale_q(pts, ist->
st->time_base, ist2->
st->time_base) - 1;
420 if (pts2 <= ist2->sub2video.last_pts)
427 for (j = 0, nb_reqs = 0; j < ist2->
nb_filters; j++)
428 nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->
filters[j]->
filter);
443 if (ret != AVERROR_EOF && ret < 0)
444 av_log(NULL, AV_LOG_WARNING,
"Flush the frame error.\n");
454 tcsetattr (0, TCSANOW, &oldtty);
460 av_log(NULL, AV_LOG_QUIET,
"%s",
"");
492#if HAVE_SETCONSOLECTRLHANDLER
493static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
495 av_log(NULL, AV_LOG_DEBUG,
"\nReceived windows signal %ld\n", fdwCtrlType);
500 case CTRL_BREAK_EVENT:
504 case CTRL_CLOSE_EVENT:
505 case CTRL_LOGOFF_EVENT:
506 case CTRL_SHUTDOWN_EVENT:
518 av_log(NULL, AV_LOG_ERROR,
"Received unknown windows signal %ld\n", fdwCtrlType);
525#define SIGNAL(sig, func) \
527 action.sa_handler = func; \
528 sigaction(sig, &action, NULL); \
531#define SIGNAL(sig, func) \
538 #if defined __aarch64__ || defined __amd64__ || defined __x86_64__
539 struct sigaction action = {0};
541 struct sigaction action = {{0}};
547 sigfillset(&action.sa_mask);
550 action.sa_flags = SA_RESTART;
556 if (tcgetattr (0, &tty) == 0) {
560 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
561 |INLCR|IGNCR|ICRNL|IXON);
562 tty.c_oflag |= OPOST;
563 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
564 tty.c_cflag &= ~(CSIZE|PARENB);
569 tcsetattr (0, TCSANOW, &tty);
593#if HAVE_SETCONSOLECTRLHANDLER
594 SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
611 n = select(1, &rfds, NULL, NULL, &tv);
620# if HAVE_PEEKNAMEDPIPE
622 static HANDLE input_handle;
625 input_handle = GetStdHandle(STD_INPUT_HANDLE);
626 is_pipe = !GetConsoleMode(input_handle, &dw);
631 if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
665 av_log(NULL, AV_LOG_INFO,
"bench: maxrss=%ikB\n", maxrss);
670 avfilter_graph_free(&fg->
graph);
677 while (av_fifo_read(ifilter->
frame_queue, &frame, 1) >= 0)
678 av_frame_free(&frame);
685 avsubtitle_free(&sub);
689 av_freep(&ifilter->
name);
696 avfilter_inout_free(&ofilter->
out_tmp);
697 av_freep(&ofilter->
name);
698 av_channel_layout_uninit(&ofilter->
ch_layout);
717 av_log(NULL, AV_LOG_ERROR,
718 "Error closing vstats file, loss of information possible: %s\n",
719 av_err2str(AVERROR(errno)));
731 avformat_network_deinit();
734 av_log(NULL, AV_LOG_INFO,
"Exiting normally, received signal %d.\n",
737 av_log(NULL, AV_LOG_INFO,
"Exiting normally, received cancel request.\n");
739 av_log(NULL, AV_LOG_INFO,
"Conversion failed!\n");
750 int ost_idx = prev ? prev->
index + 1 : 0;
766 int ist_idx = prev ? prev->
st->index + 1 : 0;
781 const AVDictionaryEntry *t = NULL;
783 while ((t = av_dict_iterate(b, t))) {
784 av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
790 const AVDictionaryEntry *t;
791 if ((t = av_dict_get(m,
"", NULL, AV_DICT_IGNORE_SUFFIX))) {
792 av_log(NULL, AV_LOG_FATAL,
"Option %s not found.\n", t->key);
811 vsnprintf(buf,
sizeof(buf), fmt, va);
813 av_log(NULL, AV_LOG_INFO,
814 "bench: %8" PRIu64
" user %8" PRIu64
" sys %8" PRIu64
" real %s \n",
847 double float_pts = AV_NOPTS_VALUE;
848 const int64_t start_time = (of->
start_time == AV_NOPTS_VALUE) ?
851 AVCodecContext *
const enc = ost->
enc_ctx;
853 AVRational tb = enc->time_base;
854 AVRational filter_tb = frame->time_base;
855 const int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
857 if (frame->pts == AV_NOPTS_VALUE)
860 tb.den <<= extra_bits;
861 float_pts = av_rescale_q(frame->pts, filter_tb, tb) -
862 av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
863 float_pts /= 1 << extra_bits;
866 float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
868 frame->pts = av_rescale_q(frame->pts, filter_tb, enc->time_base) -
869 av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
870 frame->time_base = enc->time_base;
875 av_log(NULL, AV_LOG_INFO,
"filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
876 frame ? av_ts2str(frame->pts) :
"NULL",
877 (enc && frame) ? av_ts2timestr(frame->pts, &enc->time_base) :
"NULL",
879 enc ? enc->time_base.num : -1,
880 enc ? enc->time_base.den : -1);
887 char *error,
int error_len);
892 int ret = AVERROR_BUG;
893 char error[1024] = {0};
900 av_log(ost, AV_LOG_ERROR,
"Error initializing output stream: %s\n",
912 return -10.0 * log10(
d);
917 const uint8_t *sd = av_packet_get_side_data(
pkt, AV_PKT_DATA_QUALITY_STATS,
919 AVCodecContext *enc = ost->
enc_ctx;
920 int64_t frame_number;
921 double ti1, bitrate, avg_bitrate;
923 ost->
quality = sd ? AV_RL32(sd) : -1;
924 ost->
pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;
926 for (
int i = 0; i<FF_ARRAY_ELEMS(ost->
error); i++) {
928 ost->
error[i] = AV_RL64(sd + 8 + 8*i);
947 fprintf(
vstats_file,
"frame= %5"PRId64
" q= %2.1f ", frame_number,
948 ost->
quality / (
float)FF_QP2LAMBDA);
951 ost->
quality / (
float)FF_QP2LAMBDA);
954 if (ost->
error[0]>=0 && (enc->flags & AV_CODEC_FLAG_PSNR))
955 fprintf(
vstats_file,
"PSNR= %6.2f ",
psnr(ost->
error[0] / (enc->width * enc->height * 255.0 * 255.0)));
959 ti1 =
pkt->dts * av_q2d(
pkt->time_base);
963 bitrate = (
pkt->size * 8) / av_q2d(enc->time_base) / 1000.0;
964 avg_bitrate = (double)(ost->
data_size_enc * 8) / ti1 / 1000.0;
965 fprintf(
vstats_file,
"s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
966 (
double)ost->
data_size_enc / 1024, ti1, bitrate, avg_bitrate);
971 const AVFrame *frame,
const AVPacket *
pkt,
974 AVIOContext *io = es->
io;
975 AVRational tb = frame ? frame->time_base :
pkt->time_base;
976 int64_t
pts = frame ? frame->pts :
pkt->pts;
978 AVRational tbi = (AVRational){ 0, 1};
979 int64_t ptsi = INT64_MAX;
983 if ((frame && frame->opaque_ref) || (
pkt &&
pkt->opaque_ref)) {
984 fd = (
const FrameData*)(frame ? frame->opaque_ref->data :
pkt->opaque_ref->data);
1002 INFINITY : ptsi * av_q2d(tbi));
continue;
1011 default: av_assert0(0);
1019 double duration = FFMAX(
pkt->duration, 1) * av_q2d(tb);
1020 avio_printf(io,
"%g", 8.0 *
pkt->size / duration);
1024 double duration =
pkt->dts * av_q2d(tb);
1025 avio_printf(io,
"%g", duration > 0 ? 8.0 * ost->
data_size_enc / duration : -1.);
1028 default: av_assert0(0);
1038 AVCodecContext *enc = ost->
enc_ctx;
1039 AVPacket *
pkt = ost->
pkt;
1040 const char *type_desc = av_get_media_type_string(enc->codec_type);
1041 const char *action = frame ?
"encode" :
"flush";
1053 av_log(ost, AV_LOG_INFO,
"encoder <- type:%s "
1054 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1056 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
1057 enc->time_base.num, enc->time_base.den);
1063 ret = avcodec_send_frame(enc, frame);
1064 if (
ret < 0 && !(
ret == AVERROR_EOF && !frame)) {
1065 av_log(ost, AV_LOG_ERROR,
"Error submitting %s frame to the encoder\n",
1071 ret = avcodec_receive_packet(enc,
pkt);
1075 pkt->time_base = enc->time_base;
1078 if ((
ret >= 0 ||
ret == AVERROR_EOF) && ost->
logfile && enc->stats_out)
1079 fprintf(ost->
logfile,
"%s", enc->stats_out);
1081 if (
ret == AVERROR(EAGAIN)) {
1084 }
else if (
ret == AVERROR_EOF) {
1087 }
else if (
ret < 0) {
1088 av_log(ost, AV_LOG_ERROR,
"%s encoding failed\n", type_desc);
1092 if (enc->codec_type == AVMEDIA_TYPE_VIDEO)
1099 av_log(ost, AV_LOG_INFO,
"encoder -> type:%s "
1100 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s "
1101 "duration:%s duration_time:%s\n",
1103 av_ts2str(
pkt->pts), av_ts2timestr(
pkt->pts, &enc->time_base),
1104 av_ts2str(
pkt->dts), av_ts2timestr(
pkt->dts, &enc->time_base),
1105 av_ts2str(
pkt->duration), av_ts2timestr(
pkt->duration, &enc->time_base));
1112 av_log(ost, AV_LOG_INFO,
"encoder -> type:%s "
1113 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s "
1114 "duration:%s duration_time:%s\n",
1116 av_ts2str(
pkt->pts), av_ts2timestr(
pkt->pts, &enc->time_base),
1117 av_ts2str(
pkt->dts), av_ts2timestr(
pkt->dts, &enc->time_base),
1118 av_ts2str(
pkt->duration), av_ts2timestr(
pkt->duration, &enc->time_base));
1122 av_log(NULL, AV_LOG_ERROR,
1123 "Subtitle heartbeat logic failed in %s! (%s)\n",
1124 __func__, av_err2str(
ret));
1157 av_frame_unref(frame);
1158 if (
ret != AVERROR_EOF)
1163 AVFrame *enc_frame = ost->
sq_frame;
1167 if (
ret == AVERROR_EOF) {
1169 }
else if (
ret < 0) {
1170 return (
ret == AVERROR(EAGAIN)) ? 0 :
ret;
1175 av_frame_unref(enc_frame);
1177 if (
ret == AVERROR_EOF)
1187 AVCodecContext *enc = ost->
enc_ctx;
1190 if (frame->pts == AV_NOPTS_VALUE)
1195 av_rescale_q(frame->pts, frame->time_base, enc->time_base) -
1196 av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
1198 frame->time_base = enc->time_base;
1203 ost->
next_pts = frame->pts + frame->nb_samples;
1206 if (
ret < 0 &&
ret != AVERROR_EOF)
1214 int subtitle_out_max_size = 1024 * 1024;
1215 int subtitle_out_size, nb, i,
ret;
1216 AVCodecContext *enc;
1217 AVPacket *
pkt = ost->
pkt;
1220 if (sub->pts == AV_NOPTS_VALUE) {
1221 av_log(ost, AV_LOG_ERROR,
"Subtitle packets must have a pts\n");
1232 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1241 for (i = 0; i < nb; i++) {
1242 unsigned save_num_rects = sub->num_rects;
1247 ret = av_new_packet(
pkt, subtitle_out_max_size);
1253 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1254 sub->end_display_time -= sub->start_display_time;
1255 sub->start_display_time = 0;
1261 subtitle_out_size = avcodec_encode_subtitle(enc,
pkt->data,
pkt->size, sub);
1263 sub->num_rects = save_num_rects;
1264 if (subtitle_out_size < 0) {
1265 av_log(ost, AV_LOG_FATAL,
"Subtitle encoding failed\n");
1269 av_shrink_packet(
pkt, subtitle_out_size);
1271 pkt->pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q,
pkt->time_base);
1272 pkt->duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 },
pkt->time_base);
1273 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
1277 pkt->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 },
pkt->time_base);
1279 pkt->pts += av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 },
pkt->time_base);
1292 AVFrame *next_picture,
double duration,
1293 int64_t *nb_frames, int64_t *nb_frames_prev)
1295 double delta0, delta;
1300 delta0 = sync_ipts - ost->
next_pts;
1301 delta = delta0 + duration;
1305 *nb_frames_prev = 0;
1313 if (delta0 < -0.6) {
1314 av_log(ost, AV_LOG_VERBOSE,
"Past duration %f too large\n", -delta0);
1316 av_log(ost, AV_LOG_DEBUG,
"Clipping frame in rate conversion by %f\n", -delta0);
1325 av_log(ost, AV_LOG_DEBUG,
"Not duplicating %d initial frames\n", (
int)lrintf(delta0));
1334 }
else if (delta < -1.1)
1336 else if (delta > 1.1) {
1337 *nb_frames = llrintf(delta);
1339 *nb_frames_prev = llrintf(delta0 - 0.6);
1341 next_picture->duration = 1;
1346 else if (delta > 0.6)
1348 next_picture->duration = duration;
1352 next_picture->duration = duration;
1361 AVRational tb,
const AVFrame *in_picture,
1366 if (kf->
ref_pts == AV_NOPTS_VALUE)
1367 kf->
ref_pts = in_picture->pts;
1369 pts_time = (in_picture->pts - kf->
ref_pts) * av_q2d(tb);
1371 av_compare_ts(in_picture->pts, tb, kf->
pts[kf->
index], AV_TIME_BASE_Q) >= 0) {
1373 goto force_keyframe;
1374 }
else if (kf->
pexpr) {
1377 res = av_expr_eval(kf->
pexpr,
1379 ff_dlog(NULL,
"force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
1393 goto force_keyframe;
1396 in_picture->key_frame == 1 && !dup_idx) {
1397 goto force_keyframe;
1401 goto force_keyframe;
1404 return AV_PICTURE_TYPE_NONE;
1407 av_log(logctx, AV_LOG_DEBUG,
"Forced keyframe at time %f\n", pts_time);
1408 return AV_PICTURE_TYPE_I;
1414 AVFrame *next_picture)
1417 AVCodecContext *enc = ost->
enc_ctx;
1418 AVRational frame_rate;
1419 int64_t nb_frames, nb_frames_prev, i;
1420 double duration = 0;
1426 frame_rate = av_buffersink_get_frame_rate(filter);
1427 if (frame_rate.num > 0 && frame_rate.den > 0)
1428 duration = 1/(av_q2d(frame_rate) * av_q2d(enc->time_base));
1430 if(ist && ist->
st->start_time != AV_NOPTS_VALUE && ist->
first_dts != AV_NOPTS_VALUE && ost->
frame_rate.num)
1431 duration = FFMIN(duration, 1/(av_q2d(ost->
frame_rate) * av_q2d(enc->time_base)));
1438 lrintf(next_picture->duration * av_q2d(ist->
st->time_base) / av_q2d(enc->time_base)) > 0) {
1439 duration = lrintf(next_picture->duration * av_q2d(ist->
st->time_base) / av_q2d(enc->time_base));
1442 if (!next_picture) {
1449 &nb_frames, &nb_frames_prev);
1459 av_log(ost, AV_LOG_VERBOSE,
1460 "*** dropping frame %"PRId64
" at ts %"PRId64
"\n",
1463 if (nb_frames > (nb_frames_prev && ost->
last_dropped) + (nb_frames > nb_frames_prev)) {
1465 av_log(ost, AV_LOG_ERROR,
"%"PRId64
" frame duplication too large, skipping\n", nb_frames - 1);
1470 av_log(ost, AV_LOG_VERBOSE,
"*** %"PRId64
" dup!\n", nb_frames - 1);
1472 av_log(ost, AV_LOG_WARNING,
"More than %"PRIu64
" frames duplicated\n",
dup_warning);
1476 ost->
last_dropped = nb_frames == nb_frames_prev && next_picture;
1480 for (i = 0; i < nb_frames; i++) {
1481 AVFrame *in_picture;
1483 if (i < nb_frames_prev && ost->last_frame->buf[0]) {
1486 in_picture = next_picture;
1496 in_picture->quality = enc->global_quality;
1497 in_picture->pict_type =
forced_kf_apply(ost, &ost->
kf, enc->time_base, in_picture, i);
1500 if (
ret == AVERROR_EOF)
1511 av_frame_move_ref(ost->
last_frame, next_picture);
1522 AVFrame *filtered_frame = NULL;
1527 AVFilterContext *filter;
1528 AVCodecContext *enc = ost->enc_ctx;
1531 if (!ost->filter || !ost->filter->graph->graph)
1533 filter = ost->filter->filter;
1544 if (av_buffersink_get_type(filter) == AVMEDIA_TYPE_AUDIO)
1547 filtered_frame = ost->filtered_frame;
1550 ret = av_buffersink_get_frame_flags(filter, filtered_frame,
1551 AV_BUFFERSINK_FLAG_NO_REQUEST);
1553 if (
ret != AVERROR(EAGAIN) &&
ret != AVERROR_EOF) {
1554 av_log(NULL, AV_LOG_WARNING,
1555 "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(
ret));
1556 }
else if (flush &&
ret == AVERROR_EOF) {
1557 if (av_buffersink_get_type(filter) == AVMEDIA_TYPE_VIDEO)
1562 if (ost->finished) {
1563 av_frame_unref(filtered_frame);
1567 if (filtered_frame->pts != AV_NOPTS_VALUE) {
1568 AVRational tb = av_buffersink_get_time_base(filter);
1569 ost->last_filter_pts = av_rescale_q(filtered_frame->pts, tb,
1571 filtered_frame->time_base = tb;
1574 av_log(NULL, AV_LOG_INFO,
"filter_raw -> pts:%s pts_time:%s time_base:%d/%d\n",
1575 av_ts2str(filtered_frame->pts),
1576 av_ts2timestr(filtered_frame->pts, &tb),
1580 switch (av_buffersink_get_type(filter)) {
1581 case AVMEDIA_TYPE_VIDEO:
1582 if (!ost->frame_aspect_ratio.num)
1583 enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
1587 case AVMEDIA_TYPE_AUDIO:
1588 if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&
1589 enc->ch_layout.nb_channels != filtered_frame->ch_layout.nb_channels) {
1590 av_log(NULL, AV_LOG_ERROR,
1591 "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1601 av_frame_unref(filtered_frame);
1610 uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
1611 uint64_t subtitle_size = 0;
1613 float percent = -1.0;
1618 AVCodecParameters *
par = ost->st->codecpar;
1619 const uint64_t s = ost->data_size_mux;
1621 switch (
par->codec_type) {
1622 case AVMEDIA_TYPE_VIDEO: video_size += s;
break;
1623 case AVMEDIA_TYPE_AUDIO: audio_size += s;
break;
1624 case AVMEDIA_TYPE_SUBTITLE: subtitle_size += s;
break;
1625 default: other_size += s;
break;
1627 extra_size +=
par->extradata_size;
1630 (ost->enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
1631 != AV_CODEC_FLAG_PASS1)
1638 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: ",
1639 video_size / 1024.0,
1640 audio_size / 1024.0,
1641 subtitle_size / 1024.0,
1642 other_size / 1024.0,
1643 extra_size / 1024.0);
1645 av_log(NULL, AV_LOG_INFO,
"%f%%", percent);
1647 av_log(NULL, AV_LOG_INFO,
"unknown");
1648 av_log(NULL, AV_LOG_INFO,
"\n");
1653 uint64_t total_packets = 0, total_size = 0;
1655 av_log(NULL, AV_LOG_VERBOSE,
"Input file #%d (%s):\n",
1660 enum AVMediaType type = ist->
par->codec_type;
1665 av_log(NULL, AV_LOG_VERBOSE,
" Input stream #%d:%d (%s): ",
1666 i, j, av_get_media_type_string(type));
1667 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" packets read (%"PRIu64
" bytes); ",
1671 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" frames decoded",
1673 if (type == AVMEDIA_TYPE_AUDIO)
1674 av_log(NULL, AV_LOG_VERBOSE,
" (%"PRIu64
" samples)", ist->
samples_decoded);
1675 av_log(NULL, AV_LOG_VERBOSE,
"; ");
1678 av_log(NULL, AV_LOG_VERBOSE,
"\n");
1681 av_log(NULL, AV_LOG_VERBOSE,
" Total: %"PRIu64
" packets (%"PRIu64
" bytes) demuxed\n",
1682 total_packets, total_size);
1687 uint64_t total_packets = 0, total_size = 0;
1689 av_log(NULL, AV_LOG_VERBOSE,
"Output file #%d (%s):\n",
1694 enum AVMediaType type = ost->
st->codecpar->codec_type;
1699 av_log(NULL, AV_LOG_VERBOSE,
" Output stream #%d:%d (%s): ",
1700 i, j, av_get_media_type_string(type));
1702 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" frames encoded",
1704 if (type == AVMEDIA_TYPE_AUDIO)
1705 av_log(NULL, AV_LOG_VERBOSE,
" (%"PRIu64
" samples)", ost->
samples_encoded);
1706 av_log(NULL, AV_LOG_VERBOSE,
"; ");
1709 av_log(NULL, AV_LOG_VERBOSE,
"%"PRIu64
" packets muxed (%"PRIu64
" bytes); ",
1712 av_log(NULL, AV_LOG_VERBOSE,
"\n");
1715 av_log(NULL, AV_LOG_VERBOSE,
" Total: %"PRIu64
" packets (%"PRIu64
" bytes) muxed\n",
1716 total_packets, total_size);
1718 if(video_size +
data_size + audio_size + subtitle_size + extra_size == 0){
1719 av_log(NULL, AV_LOG_WARNING,
"Output file is empty, nothing was encoded ");
1721 av_log(NULL, AV_LOG_WARNING,
"\n");
1723 av_log(NULL, AV_LOG_WARNING,
"(check -ss / -t / -frames parameters if used)\n");
1728static void forward_report(uint64_t frame_number,
float fps,
float quality, int64_t total_size,
int seconds,
int microseconds,
double bitrate,
double speed)
1732 report_callback(frame_number, fps, quality, total_size, ((
double)seconds*1000) + ((
double)microseconds)/1000, bitrate, speed);
1736static void print_report(
int is_last_report, int64_t timer_start, int64_t cur_time)
1738 AVBPrint buf, buf_script;
1743 int64_t
pts = AV_NOPTS_VALUE;
1746 const char *hours_sign;
1751 int local_print_stats = 1;
1752 uint64_t frame_number = 0;
1757 local_print_stats = 0;
1759 if (!is_last_report) {
1769 t = (cur_time-timer_start) / 1000000.0;
1772 if (local_print_stats) {
1773 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
1774 av_bprint_init(&buf_script, 0, AV_BPRINT_SIZE_AUTOMATIC);
1777 const AVCodecContext *
const enc = ost->enc_ctx;
1778 q = enc ? ost->quality / (float) FF_QP2LAMBDA : -1;
1780 if (local_print_stats && vid && ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1781 av_bprintf(&buf,
"q=%2.1f ", q);
1782 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
1783 ost->file_index, ost->index, q);
1785 if (!vid && ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1786 frame_number = atomic_load(&ost->packets_written);
1787 fps = t > 1 ? frame_number / t : 0;
1788 if (local_print_stats) {
1789 av_bprintf(&buf,
"frame=%5"PRId64
" fps=%3.*f q=%3.1f ",
1790 frame_number, fps < 9.95, fps, q);
1791 av_bprintf(&buf_script,
"frame=%"PRId64
"\n", frame_number);
1792 av_bprintf(&buf_script,
"fps=%.2f\n", fps);
1793 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
1794 ost->file_index, ost->index, q);
1796 if (local_print_stats && is_last_report)
1797 av_bprintf(&buf,
"L");
1803 if (local_print_stats) {
1804 for (j = 0; j < 32; j++)
1809 if (local_print_stats && enc && (enc->flags & AV_CODEC_FLAG_PSNR) &&
1810 (ost->pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {
1812 double error, error_sum = 0;
1813 double scale, scale_sum = 0;
1815 char type[3] = {
'Y',
'U',
'V' };
1816 av_bprintf(&buf,
"PSNR=");
1817 for (j = 0; j < 3; j++) {
1818 if (is_last_report) {
1819 error = enc->error[j];
1820 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1822 error = ost->error[j];
1823 scale = enc->width * enc->height * 255.0 * 255.0;
1829 p =
psnr(error / scale);
1830 av_bprintf(&buf,
"%c:%2.2f ", type[j], p);
1831 av_bprintf(&buf_script,
"stream_%d_%d_psnr_%c=%2.2f\n",
1832 ost->file_index, ost->index, type[j] | 32, p);
1834 p =
psnr(error_sum / scale_sum);
1835 av_bprintf(&buf,
"*:%2.2f ",
psnr(error_sum / scale_sum));
1836 av_bprintf(&buf_script,
"stream_%d_%d_psnr_all=%2.2f\n",
1837 ost->file_index, ost->index, p);
1842 if (ost->last_mux_dts != AV_NOPTS_VALUE) {
1843 if (
pts == AV_NOPTS_VALUE || ost->last_mux_dts >
pts)
1844 pts = ost->last_mux_dts;
1857 us = FFABS64U(
pts) % AV_TIME_BASE;
1858 secs = FFABS64U(
pts) / AV_TIME_BASE % 60;
1859 mins = FFABS64U(
pts) / AV_TIME_BASE / 60 % 60;
1860 hours = FFABS64U(
pts) / AV_TIME_BASE / 3600;
1861 hours_sign = (
pts < 0) ?
"-" :
"";
1863 bitrate =
pts != AV_NOPTS_VALUE &&
pts && total_size >= 0 ? total_size * 8 / (
pts / 1000.0) : -1;
1864 speed =
pts != AV_NOPTS_VALUE && t != 0.0 ? (double)
pts / AV_TIME_BASE / t : -1;
1867 if (
pts == AV_NOPTS_VALUE) {
1868 forward_report(frame_number, fps, q, total_size, 0, 0, bitrate, speed);
1870 forward_report(frame_number, fps, q, total_size, secs, us, bitrate, speed);
1873 if (local_print_stats) {
1874 if (total_size < 0) av_bprintf(&buf,
"size=N/A time=");
1875 else av_bprintf(&buf,
"size=%8.0fkB time=", total_size / 1024.0);
1876 if (
pts == AV_NOPTS_VALUE) {
1877 av_bprintf(&buf,
"N/A ");
1879 av_bprintf(&buf,
"%s%02"PRId64
":%02d:%02d.%02d ",
1880 hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
1884 av_bprintf(&buf,
"bitrate=N/A");
1885 av_bprintf(&buf_script,
"bitrate=N/A\n");
1887 av_bprintf(&buf,
"bitrate=%6.1fkbits/s", bitrate);
1888 av_bprintf(&buf_script,
"bitrate=%6.1fkbits/s\n", bitrate);
1891 if (total_size < 0) av_bprintf(&buf_script,
"total_size=N/A\n");
1892 else av_bprintf(&buf_script,
"total_size=%"PRId64
"\n", total_size);
1893 if (
pts == AV_NOPTS_VALUE) {
1894 av_bprintf(&buf_script,
"out_time_us=N/A\n");
1895 av_bprintf(&buf_script,
"out_time_ms=N/A\n");
1896 av_bprintf(&buf_script,
"out_time=N/A\n");
1898 av_bprintf(&buf_script,
"out_time_us=%"PRId64
"\n",
pts);
1899 av_bprintf(&buf_script,
"out_time_ms=%"PRId64
"\n",
pts);
1900 av_bprintf(&buf_script,
"out_time=%s%02"PRId64
":%02d:%02d.%06d\n",
1901 hours_sign, hours, mins, secs, us);
1906 av_bprintf(&buf_script,
"dup_frames=%"PRId64
"\n",
nb_frames_dup);
1907 av_bprintf(&buf_script,
"drop_frames=%"PRId64
"\n",
nb_frames_drop);
1910 av_bprintf(&buf,
" speed=N/A");
1911 av_bprintf(&buf_script,
"speed=N/A\n");
1913 av_bprintf(&buf,
" speed=%4.3gx", speed);
1914 av_bprintf(&buf_script,
"speed=%4.3gx\n", speed);
1918 const char end = is_last_report ?
'\n' :
'\r';
1919 if (
print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
1922 av_log(NULL, AV_LOG_INFO,
"%s %c", buf.str, end);
1924 av_bprint_finalize(&buf, NULL);
1927 av_bprintf(&buf_script,
"progress=%s\n",
1928 is_last_report ?
"end" :
"continue");
1930 FFMIN(buf_script.len, buf_script.size - 1));
1932 av_bprint_finalize(&buf_script, NULL);
1933 if (is_last_report) {
1935 av_log(NULL, AV_LOG_ERROR,
1936 "Error closing progress log, loss of information possible: %s\n", av_err2str(
ret));
1971 if (ost->sq_idx_encode >= 0)
1976 AVCodecContext *enc = ost->enc_ctx;
1984 if (!ost->initialized) {
1987 av_log(ost, AV_LOG_WARNING,
1988 "Finishing stream without any data written to it.\n");
1990 if (ost->filter && !fg->
graph) {
1994 if (ifilter->
format < 0 &&
1996 av_log(ost, AV_LOG_ERROR,
"Error copying paramerets from input stream\n");
2006 av_log(ost, AV_LOG_ERROR,
"Error configuring filter graph\n");
2016 if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
2020 if (
ret != AVERROR_EOF)
2032 if (ost->
ist != ist)
2049 int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->
mux_timebase);
2050 AVPacket *opkt = ost->
pkt;
2052 av_packet_unref(opkt);
2064 if (
pkt->pts == AV_NOPTS_VALUE ?
2088 if (av_packet_ref(opkt,
pkt) < 0)
2093 if (
pkt->pts != AV_NOPTS_VALUE)
2094 opkt->pts = av_rescale_q(
pkt->pts, ist->
st->time_base, opkt->time_base) - ost_tb_start_time;
2096 if (
pkt->dts == AV_NOPTS_VALUE) {
2097 opkt->dts = av_rescale_q(ist->
dts, AV_TIME_BASE_Q, opkt->time_base);
2098 }
else if (ost->
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2099 int duration = av_get_audio_frame_duration2(ist->
par,
pkt->size);
2101 duration = ist->
par->frame_size;
2102 opkt->dts = av_rescale_delta(ist->
st->time_base,
pkt->dts,
2103 (AVRational){1, ist->par->sample_rate}, duration,
2106 opkt->pts = opkt->dts - ost_tb_start_time;
2108 opkt->dts = av_rescale_q(
pkt->dts, ist->
st->time_base, opkt->time_base);
2109 opkt->dts -= ost_tb_start_time;
2111 opkt->duration = av_rescale_q(
pkt->duration, ist->
st->time_base, opkt->time_base);
2116 av_log(NULL, AV_LOG_ERROR,
2117 "Subtitle heartbeat logic failed in %s! (%s)\n",
2118 __func__, av_err2str(
ret));
2161 AVFrameSideData *sd;
2162 int need_reinit,
ret;
2163 int buffersrc_flags = AV_BUFFERSRC_FLAG_PUSH;
2166 buffersrc_flags |= AV_BUFFERSRC_FLAG_KEEP_REF;
2169 need_reinit = ifilter->
format != frame->format;
2171 switch (ifilter->
ist->
par->codec_type) {
2172 case AVMEDIA_TYPE_AUDIO:
2173 need_reinit |= ifilter->
sample_rate != frame->sample_rate ||
2174 av_channel_layout_compare(&ifilter->
ch_layout, &frame->ch_layout);
2176 case AVMEDIA_TYPE_VIDEO:
2177 need_reinit |= ifilter->
width != frame->width ||
2178 ifilter->
height != frame->height;
2189 if ((sd = av_frame_get_side_data(frame, AV_FRAME_DATA_DISPLAYMATRIX))) {
2202 if (need_reinit || !fg->
graph) {
2204 AVFrame *tmp = av_frame_clone(frame);
2206 return AVERROR(ENOMEM);
2210 av_frame_free(&tmp);
2216 if (
ret < 0 &&
ret != AVERROR_EOF) {
2217 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(
ret));
2223 av_log(NULL, AV_LOG_ERROR,
"Error reinitializing filters!\n");
2228 ret = av_buffersrc_add_frame_flags(ifilter->
filter, frame, buffersrc_flags);
2230 if (
ret != AVERROR_EOF)
2231 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(
ret));
2248 ret = av_buffersrc_close(ifilter->
filter,
pts, AV_BUFFERSRC_FLAG_PUSH);
2254 if (ifilter->
format < 0) {
2259 if (ifilter->
format < 0 && (ifilter->
type == AVMEDIA_TYPE_AUDIO || ifilter->
type == AVMEDIA_TYPE_VIDEO)) {
2260 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);
2261 return AVERROR_INVALIDDATA;
2273 AVFrame *frame,
int *got_frame, AVPacket *
pkt)
2280 ret = avcodec_send_packet(avctx,
pkt);
2283 if (
ret < 0 &&
ret != AVERROR_EOF)
2287 ret = avcodec_receive_frame(avctx, frame);
2288 if (
ret < 0 &&
ret != AVERROR(EAGAIN))
2294 av_assert0(!frame->opaque_ref);
2295 frame->opaque_ref = av_buffer_allocz(
sizeof(*fd));
2296 if (!frame->opaque_ref) {
2297 av_frame_unref(frame);
2298 return AVERROR(ENOMEM);
2300 fd = (
FrameData*)frame->opaque_ref->data;
2301 fd->
pts = frame->pts;
2302 fd->
tb = avctx->pkt_timebase;
2303 fd->
idx = avctx->frame_num - 1;
2319 if (
ret == AVERROR_EOF)
2322 av_log(NULL, AV_LOG_ERROR,
2323 "Failed to inject frame into filter network: %s\n", av_err2str(
ret));
2334 AVCodecContext *avctx = ist->
dec_ctx;
2336 AVRational decoded_frame_tb;
2344 if (
ret != AVERROR_EOF)
2361 decoded_frame_tb = ist->
st->time_base;
2362 }
else if (
pkt &&
pkt->pts != AV_NOPTS_VALUE) {
2364 decoded_frame_tb = ist->
st->time_base;
2367 decoded_frame_tb = AV_TIME_BASE_Q;
2376 (AVRational){1, decoded_frame->sample_rate},
2379 (AVRational){1, decoded_frame->sample_rate});
2384 return err < 0 ? err :
ret;
2391 int i,
ret = 0, err = 0;
2392 int64_t best_effort_timestamp;
2393 int64_t
dts = AV_NOPTS_VALUE;
2398 if (!eof &&
pkt &&
pkt->size == 0)
2401 if (ist->
dts != AV_NOPTS_VALUE)
2402 dts = av_rescale_q(ist->
dts, AV_TIME_BASE_Q, ist->
st->time_base);
2412 return AVERROR(ENOMEM);
2425 if (ist->
par->video_delay < ist->
dec_ctx->has_b_frames) {
2426 if (ist->
dec_ctx->codec_id == AV_CODEC_ID_H264) {
2427 ist->
par->video_delay = ist->
dec_ctx->has_b_frames;
2429 av_log(ist->
dec_ctx, AV_LOG_WARNING,
2430 "video_delay is larger in decoder than demuxer %d > %d.\n"
2431 "If you want to help, upload a sample "
2432 "of this file to https://streams.videolan.org/upload/ "
2433 "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n",
2435 ist->
par->video_delay);
2438 if (
ret != AVERROR_EOF)
2445 av_log(NULL, AV_LOG_DEBUG,
"Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
2469 best_effort_timestamp=
decoded_frame->best_effort_timestamp;
2475 if (eof && best_effort_timestamp == AV_NOPTS_VALUE && ist->
nb_dts_buffer > 0) {
2483 if(best_effort_timestamp != AV_NOPTS_VALUE) {
2484 int64_t ts = av_rescale_q(
decoded_frame->pts = best_effort_timestamp, ist->
st->time_base, AV_TIME_BASE_Q);
2486 if (ts != AV_NOPTS_VALUE)
2491 av_log(NULL, AV_LOG_INFO,
"decoder -> ist_index:%d type:video "
2492 "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",
2495 best_effort_timestamp,
2496 av_ts2timestr(best_effort_timestamp, &ist->
st->time_base),
2498 ist->
st->time_base.num, ist->
st->time_base.den);
2501 if (ist->
st->sample_aspect_ratio.num)
2508 return err < 0 ? err :
ret;
2520 1000, AV_TIME_BASE);
2521 if (end < ist->
prev_sub.subtitle.end_display_time) {
2522 av_log(NULL, AV_LOG_DEBUG,
2523 "Subtitle duration reduced from %"PRId32
" to %d%s\n",
2525 end <= 0 ?
", dropping it" :
"");
2543 ist->
sub2video.
sub_queue = av_fifo_alloc2(8,
sizeof(AVSubtitle), AV_FIFO_FLAG_AUTO_GROW);
2558 || ost->enc_ctx->codec_type != AVMEDIA_TYPE_SUBTITLE)
2572 int ret = AVERROR_BUG;
2574 .format = src->format,
2575 .start_display_time = src->start_display_time,
2576 .end_display_time = src->end_display_time,
2582 if (!src->num_rects)
2585 if (!(tmp.rects = av_calloc(src->num_rects,
sizeof(*tmp.rects))))
2586 return AVERROR(ENOMEM);
2588 for (
int i = 0; i < src->num_rects; i++) {
2589 AVSubtitleRect *src_rect = src->rects[i];
2590 AVSubtitleRect *dst_rect;
2592 if (!(dst_rect = tmp.rects[i] = av_mallocz(
sizeof(*tmp.rects[0])))) {
2593 ret = AVERROR(ENOMEM);
2599 dst_rect->type = src_rect->type;
2600 dst_rect->flags = src_rect->flags;
2602 dst_rect->x = src_rect->x;
2603 dst_rect->y = src_rect->y;
2604 dst_rect->w = src_rect->w;
2605 dst_rect->h = src_rect->h;
2606 dst_rect->nb_colors = src_rect->nb_colors;
2609 if (!(dst_rect->text = av_strdup(src_rect->text))) {
2610 ret = AVERROR(ENOMEM);
2615 if (!(dst_rect->ass = av_strdup(src_rect->ass))) {
2616 ret = AVERROR(ENOMEM);
2620 for (
int j = 0; j < 4; j++) {
2624 size_t buf_size = src_rect->type == SUBTITLE_BITMAP && j == 1 ?
2626 src_rect->h * src_rect->linesize[j];
2628 if (!src_rect->data[j])
2631 if (!(dst_rect->data[j] = av_memdup(src_rect->data[j], buf_size))) {
2632 ret = AVERROR(ENOMEM);
2635 dst_rect->linesize[j] = src_rect->linesize[j];
2645 avsubtitle_free(&tmp);
2652 int ret = AVERROR_BUG;
2658 signal_pts <= prev_subtitle->
pts)
2672 int64_t signal_pts = av_rescale_q(
pkt->pts,
pkt->time_base,
2683 int ret = AVERROR_BUG;
2686 ist->
dec_ctx->codec_type != AVMEDIA_TYPE_SUBTITLE)
2704 int ret = avcodec_decode_subtitle2(ist->
dec_ctx,
2725 int64_t
pts = av_rescale_q_rnd(ist->
pts, AV_TIME_BASE_Q, ist->
st->time_base,
2726 AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
2739 const AVCodecParameters *
par = ist->
par;
2742 int eof_reached = 0;
2744 AVPacket *avpkt = ist->
pkt;
2748 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;
2752 ist->
dts += av_rescale_q(
pkt->pts, ist->
st->time_base, AV_TIME_BASE_Q);
2758 if (ist->
next_dts == AV_NOPTS_VALUE)
2760 if (ist->
next_pts == AV_NOPTS_VALUE)
2764 av_packet_unref(avpkt);
2765 ret = av_packet_ref(avpkt,
pkt);
2770 if (
pkt &&
pkt->dts != AV_NOPTS_VALUE) {
2771 ist->
next_dts = ist->
dts = av_rescale_q(
pkt->dts, ist->
st->time_base, AV_TIME_BASE_Q);
2778 int64_t duration_dts = 0;
2779 int64_t duration_pts = 0;
2781 int decode_failed = 0;
2786 switch (
par->codec_type) {
2787 case AVMEDIA_TYPE_AUDIO:
2790 av_packet_unref(avpkt);
2792 case AVMEDIA_TYPE_VIDEO:
2796 if (
pkt &&
pkt->duration) {
2797 duration_dts = av_rescale_q(
pkt->duration, ist->
st->time_base, AV_TIME_BASE_Q);
2798 }
else if(ist->
dec_ctx->framerate.num != 0 && ist->
dec_ctx->framerate.den != 0) {
2801 ist->
dec_ctx->ticks_per_frame;
2802 duration_dts = ((int64_t)AV_TIME_BASE *
2803 ist->
dec_ctx->framerate.den * ticks) /
2807 if(ist->
dts != AV_NOPTS_VALUE && duration_dts) {
2814 if (duration_pts > 0) {
2815 ist->
next_pts += av_rescale_q(duration_pts, ist->
st->time_base, AV_TIME_BASE_Q);
2820 av_packet_unref(avpkt);
2822 case AVMEDIA_TYPE_SUBTITLE:
2828 av_packet_unref(avpkt);
2834 if (
ret == AVERROR_EOF) {
2840 if (decode_failed) {
2841 av_log(NULL, AV_LOG_ERROR,
"Error while decoding stream #%d:%d: %s\n",
2844 av_log(NULL, AV_LOG_FATAL,
"Error while processing the decoded "
2845 "data for stream #%d:%d\n", ist->
file_index, ist->
st->index);
2877 av_log(NULL, AV_LOG_FATAL,
"Error marking filters as finished\n");
2885 switch (
par->codec_type) {
2886 case AVMEDIA_TYPE_AUDIO:
2887 av_assert1(
pkt->duration >= 0);
2888 if (
par->sample_rate) {
2889 ist->
next_dts += ((int64_t)AV_TIME_BASE *
par->frame_size) /
2892 ist->
next_dts += av_rescale_q(
pkt->duration, ist->
st->time_base, AV_TIME_BASE_Q);
2895 case AVMEDIA_TYPE_VIDEO:
2898 AVRational time_base_q = AV_TIME_BASE_Q;
2901 }
else if (
pkt->duration) {
2902 ist->
next_dts += av_rescale_q(
pkt->duration, ist->
st->time_base, AV_TIME_BASE_Q);
2903 }
else if(ist->
dec_ctx->framerate.num != 0) {
2906 ist->
dec_ctx->ticks_per_frame;
2907 ist->
next_dts += ((int64_t)AV_TIME_BASE *
2908 ist->
dec_ctx->framerate.den * ticks) /
2926 return !eof_reached;
2929static enum AVPixelFormat
get_format(AVCodecContext *s,
const enum AVPixelFormat *pix_fmts)
2932 const enum AVPixelFormat *p;
2935 for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
2936 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
2937 const AVCodecHWConfig *config = NULL;
2940 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
2946 config = avcodec_get_hw_config(s->codec, i);
2949 if (!(config->methods &
2950 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
2952 if (config->pix_fmt == *p)
2960 av_log(NULL, AV_LOG_FATAL,
2961 "%s hwaccel requested for input stream #%d:%d, "
2962 "but cannot be initialized.\n",
2963 av_hwdevice_get_type_name(config->device_type),
2965 return AV_PIX_FMT_NONE;
2983 const AVCodec *codec = ist->
dec;
2985 snprintf(error, error_len,
"Decoder (codec %s) not found for input stream #%d:%d",
2987 return AVERROR(EINVAL);
2993 if (ist->
dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
2995 av_dict_set(&ist->
decoder_opts,
"compute_edt",
"1", AV_DICT_DONT_OVERWRITE);
2997 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");
3002 ist->
dec_ctx->pkt_timebase = ist->
st->time_base;
3004 if (!av_dict_get(ist->
decoder_opts,
"threads", NULL, 0))
3007 if (ist->
st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3012 snprintf(error, error_len,
"Device setup failed for "
3013 "decoder on input stream #%d:%d : %s",
3019 if (
ret == AVERROR_EXPERIMENTAL)
3022 snprintf(error, error_len,
3023 "Error while opening decoder for input stream "
3042 AVCodecParameters *
par = ost->
st->codecpar;
3043 AVCodecContext *codec_ctx;
3046 uint32_t codec_tag =
par->codec_tag;
3048 av_assert0(ist && !ost->
filter);
3050 codec_ctx = avcodec_alloc_context3(NULL);
3052 return AVERROR(ENOMEM);
3054 ret = avcodec_parameters_to_context(codec_ctx, ist->
par);
3058 av_log(ost, AV_LOG_FATAL,
3059 "Error setting up codec context options.\n");
3060 avcodec_free_context(&codec_ctx);
3064 ret = avcodec_parameters_from_context(
par, codec_ctx);
3065 avcodec_free_context(&codec_ctx);
3067 av_log(ost, AV_LOG_FATAL,
3068 "Error getting reference codec parameters.\n");
3073 unsigned int codec_tag_tmp;
3074 if (!of->
format->codec_tag ||
3075 av_codec_get_id (of->
format->codec_tag,
par->codec_tag) ==
par->codec_id ||
3076 !av_codec_get_tag2(of->
format->codec_tag,
par->codec_id, &codec_tag_tmp))
3077 codec_tag =
par->codec_tag;
3080 par->codec_tag = codec_tag;
3088 ost->
st->avg_frame_rate = ist->
st->avg_frame_rate;
3095 if (ost->
st->time_base.num <= 0 || ost->
st->time_base.den <= 0) {
3099 ost->
st->time_base = av_add_q(av_stream_get_codec_timebase(ost->
st), (AVRational){0, 1});
3103 if (ost->
st->duration <= 0 && ist->
st->duration > 0)
3104 ost->
st->duration = av_rescale_q(ist->
st->duration, ist->
st->time_base, ost->
st->time_base);
3115 if (ist->
st->nb_side_data) {
3116 for (i = 0; i < ist->
st->nb_side_data; i++) {
3117 const AVPacketSideData *sd_src = &ist->
st->side_data[i];
3120 dst_data = av_stream_new_side_data(ost->
st, sd_src->type, sd_src->size);
3122 return AVERROR(ENOMEM);
3123 memcpy(dst_data, sd_src->data, sd_src->size);
3127#if FFMPEG_ROTATION_METADATA
3129 uint8_t *sd = av_stream_new_side_data(ost->
st, AV_PKT_DATA_DISPLAYMATRIX,
3130 sizeof(int32_t) * 9);
3136 switch (
par->codec_type) {
3137 case AVMEDIA_TYPE_AUDIO:
3138 if ((
par->block_align == 1 ||
par->block_align == 1152 ||
par->block_align == 576) &&
3139 par->codec_id == AV_CODEC_ID_MP3)
3140 par->block_align = 0;
3141 if (
par->codec_id == AV_CODEC_ID_AC3)
3142 par->block_align = 0;
3144 case AVMEDIA_TYPE_VIDEO:
3148 (AVRational){ par->height, par->width });
3149 av_log(ost, AV_LOG_WARNING,
"Overriding aspect ratio "
3150 "with stream copy may produce invalid files\n");
3152 else if (ist->
st->sample_aspect_ratio.num)
3153 sar = ist->
st->sample_aspect_ratio;
3155 sar =
par->sample_aspect_ratio;
3156 ost->
st->sample_aspect_ratio =
par->sample_aspect_ratio = sar;
3157 ost->
st->avg_frame_rate = ist->
st->avg_frame_rate;
3158 ost->
st->r_frame_rate = ist->
st->r_frame_rate;
3169 const char *cname = ost->
enc_ctx->codec->name;
3170 uint8_t *encoder_string;
3171 int encoder_string_len;
3173 if (av_dict_get(ost->
st->metadata,
"encoder", NULL, 0))
3176 encoder_string_len =
sizeof(LIBAVCODEC_IDENT) + strlen(cname) + 2;
3177 encoder_string = av_mallocz(encoder_string_len);
3178 if (!encoder_string)
3182 av_strlcpy(encoder_string, LIBAVCODEC_IDENT
" ", encoder_string_len);
3184 av_strlcpy(encoder_string,
"Lavc ", encoder_string_len);
3185 av_strlcat(encoder_string, cname, encoder_string_len);
3186 av_dict_set(&ost->
st->metadata,
"encoder", encoder_string,
3187 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
3193 AVCodecContext *enc_ctx = ost->
enc_ctx;
3202 enc_ctx->time_base = ist->
st->time_base;
3206 av_log(ost, AV_LOG_WARNING,
3207 "Input stream data not available, using default time base\n");
3210 enc_ctx->time_base = default_time_base;
3216 AVCodecContext *enc_ctx = ost->
enc_ctx;
3217 AVCodecContext *
dec_ctx = NULL;
3227 if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3232 av_log(ost, AV_LOG_WARNING,
3234 "about the input framerate is available. Falling "
3235 "back to a default value of 25fps. Use the -r option "
3236 "if you want a different framerate.\n");
3244 if (enc_ctx->codec->supported_framerates && !ost->
force_fps) {
3245 int idx = av_find_nearest_q_idx(ost->
frame_rate, enc_ctx->codec->supported_framerates);
3246 ost->
frame_rate = enc_ctx->codec->supported_framerates[idx];
3249 if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
3255 switch (enc_ctx->codec_type) {
3256 case AVMEDIA_TYPE_AUDIO:
3257 enc_ctx->sample_fmt = av_buffersink_get_format(ost->
filter->
filter);
3258 enc_ctx->sample_rate = av_buffersink_get_sample_rate(ost->
filter->
filter);
3259 ret = av_buffersink_get_ch_layout(ost->
filter->
filter, &enc_ctx->ch_layout);
3266 enc_ctx->bits_per_raw_sample = FFMIN(
dec_ctx->bits_per_raw_sample,
3267 av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
3272 case AVMEDIA_TYPE_VIDEO:
3275 if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
3276 enc_ctx->time_base = av_buffersink_get_time_base(ost->
filter->
filter);
3280 av_log(ost, AV_LOG_WARNING,
"Frame rate very high for a muxer not efficiently supporting it.\n"
3281 "Please consider specifying a lower framerate, a different muxer or "
3282 "setting vsync/fps_mode to vfr\n");
3285 enc_ctx->width = av_buffersink_get_w(ost->
filter->
filter);
3286 enc_ctx->height = av_buffersink_get_h(ost->
filter->
filter);
3287 enc_ctx->sample_aspect_ratio = ost->
st->sample_aspect_ratio =
3290 av_buffersink_get_sample_aspect_ratio(ost->
filter->
filter);
3292 enc_ctx->pix_fmt = av_buffersink_get_format(ost->
filter->
filter);
3297 enc_ctx->bits_per_raw_sample = FFMIN(
dec_ctx->bits_per_raw_sample,
3298 av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
3301 enc_ctx->color_range = frame->color_range;
3302 enc_ctx->color_primaries = frame->color_primaries;
3303 enc_ctx->color_trc = frame->color_trc;
3304 enc_ctx->colorspace = frame->colorspace;
3305 enc_ctx->chroma_sample_location = frame->chroma_location;
3314 if (enc_ctx->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
3318 if (frame->interlaced_frame) {
3319 if (enc_ctx->codec->id == AV_CODEC_ID_MJPEG)
3320 enc_ctx->field_order = frame->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
3322 enc_ctx->field_order = frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
3324 enc_ctx->field_order = AV_FIELD_PROGRESSIVE;
3329 enc_ctx->field_order = AV_FIELD_BB;
3331 enc_ctx->field_order = AV_FIELD_TT;
3335 case AVMEDIA_TYPE_SUBTITLE:
3336 enc_ctx->time_base = AV_TIME_BASE_Q;
3337 if (!enc_ctx->width) {
3338 enc_ctx->width = ost->
ist->
par->width;
3339 enc_ctx->height = ost->
ist->
par->height;
3343 ost->
enc_ctx->subtitle_header = av_mallocz(
dec_ctx->subtitle_header_size + 1);
3344 if (!ost->
enc_ctx->subtitle_header)
3345 return AVERROR(ENOMEM);
3347 dec_ctx->subtitle_header_size);
3348 ost->
enc_ctx->subtitle_header_size =
dec_ctx->subtitle_header_size;
3350 if (ist && ist->
dec->type == AVMEDIA_TYPE_SUBTITLE &&
3351 enc_ctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3352 int input_props = 0, output_props = 0;
3353 AVCodecDescriptor
const *input_descriptor =
3354 avcodec_descriptor_get(ist->
dec->id);
3355 AVCodecDescriptor
const *output_descriptor =
3356 avcodec_descriptor_get(ost->
enc_ctx->codec_id);
3357 if (input_descriptor)
3358 input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3359 if (output_descriptor)
3360 output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3361 if (input_props && output_props && input_props != output_props) {
3362 av_log(ost, AV_LOG_ERROR,
3363 "Subtitle encoding currently only possible from text to text "
3364 "or bitmap to bitmap");
3365 return AVERROR_INVALIDDATA;
3370 case AVMEDIA_TYPE_DATA:
3378 enc_ctx->flags |= AV_CODEC_FLAG_BITEXACT;
3389 char *error,
int error_len)
3394 const AVCodec *codec = ost->
enc_ctx->codec;
3401 if (!av_dict_get(ost->
encoder_opts,
"threads", NULL, 0))
3404 if (codec->capabilities & AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE) {
3405 ret = av_dict_set(&ost->
encoder_opts,
"flags",
"+copy_opaque", AV_DICT_MULTIKEY);
3412 snprintf(error, error_len,
"Device setup failed for "
3413 "encoder on output stream #%d:%d : %s",
3419 if (
ret == AVERROR_EXPERIMENTAL)
3421 snprintf(error, error_len,
3422 "Error while opening encoder for output stream #%d:%d - "
3423 "maybe incorrect parameters such as bit_rate, rate, width or height",
3427 if (codec->type == AVMEDIA_TYPE_AUDIO &&
3428 !(codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
3433 ost->
enc_ctx->codec_id != AV_CODEC_ID_CODEC2 )
3434 av_log(ost, AV_LOG_WARNING,
"The bitrate parameter is set too low."
3435 " It takes bits/s as argument, not kbits/s\n");
3437 ret = avcodec_parameters_from_context(ost->
st->codecpar, ost->
enc_ctx);
3439 av_log(ost, AV_LOG_FATAL,
3440 "Error initializing the output stream codec context.\n");
3444 if (ost->
enc_ctx->nb_coded_side_data) {
3447 for (i = 0; i < ost->
enc_ctx->nb_coded_side_data; i++) {
3448 const AVPacketSideData *sd_src = &ost->
enc_ctx->coded_side_data[i];
3451 dst_data = av_stream_new_side_data(ost->
st, sd_src->type, sd_src->size);
3453 return AVERROR(ENOMEM);
3454 memcpy(dst_data, sd_src->data, sd_src->size);
3467 for (i = 0; i < ist->
st->nb_side_data; i++) {
3468 AVPacketSideData *sd = &ist->
st->side_data[i];
3469 if (sd->type != AV_PKT_DATA_CPB_PROPERTIES) {
3470 uint8_t *dst = av_stream_new_side_data(ost->
st, sd->type, sd->size);
3472 return AVERROR(ENOMEM);
3473 memcpy(dst, sd->data, sd->size);
3474 if (ist->
autorotate && sd->type == AV_PKT_DATA_DISPLAYMATRIX)
3475 av_display_rotation_set((int32_t *)dst, 0);
3481 if (ost->
st->time_base.num <= 0 || ost->
st->time_base.den <= 0)
3482 ost->
st->time_base = av_add_q(ost->
enc_ctx->time_base, (AVRational){0, 1});
3485 if (ost->
st->duration <= 0 && ist && ist->
st->duration > 0)
3486 ost->
st->duration = av_rescale_q(ist->
st->duration, ist->
st->time_base, ost->
st->time_base);
3487 }
else if (ost->
ist) {
3503 char error[1024] = {0};
3529 (ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3530 ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))
3541 for (
int j = 0; j < ifile->
ctx->nb_programs; j++) {
3542 AVProgram *p = ifile->
ctx->programs[j];
3545 for (
int k = 0; k < p->nb_stream_indexes; k++)
3556 av_log(NULL, AV_LOG_INFO,
"Stream mapping:\n");
3558 for (
int j = 0; j < ist->nb_filters; j++) {
3560 av_log(NULL, AV_LOG_INFO,
" Stream #%d:%d (%s) -> %s",
3561 ist->file_index, ist->st->index, ist->dec ? ist->dec->name :
"?",
3562 ist->filters[j]->name);
3564 av_log(NULL, AV_LOG_INFO,
" (graph %d)", ist->filters[j]->graph->index);
3565 av_log(NULL, AV_LOG_INFO,
"\n");
3571 if (ost->attachment_filename) {
3573 av_log(NULL, AV_LOG_INFO,
" File %s -> Stream #%d:%d\n",
3574 ost->attachment_filename, ost->file_index, ost->index);
3580 av_log(NULL, AV_LOG_INFO,
" %s", ost->filter->name);
3582 av_log(NULL, AV_LOG_INFO,
" (graph %d)", ost->filter->graph->index);
3584 av_log(NULL, AV_LOG_INFO,
" -> Stream #%d:%d (%s)\n", ost->file_index,
3585 ost->index, ost->enc_ctx->codec->name);
3589 av_log(NULL, AV_LOG_INFO,
" Stream #%d:%d -> #%d:%d",
3590 ost->ist->file_index,
3591 ost->ist->st->index,
3595 const AVCodec *in_codec = ost->ist->dec;
3596 const AVCodec *out_codec = ost->enc_ctx->codec;
3597 const char *decoder_name =
"?";
3598 const char *in_codec_name =
"?";
3599 const char *encoder_name =
"?";
3600 const char *out_codec_name =
"?";
3601 const AVCodecDescriptor *desc;
3604 decoder_name = in_codec->name;
3605 desc = avcodec_descriptor_get(in_codec->id);
3607 in_codec_name = desc->name;
3608 if (!strcmp(decoder_name, in_codec_name))
3609 decoder_name =
"native";
3613 encoder_name = out_codec->name;
3614 desc = avcodec_descriptor_get(out_codec->id);
3616 out_codec_name = desc->name;
3617 if (!strcmp(encoder_name, out_codec_name))
3618 encoder_name =
"native";
3621 av_log(NULL, AV_LOG_INFO,
" (%s (%s) -> %s (%s))",
3622 in_codec_name, decoder_name,
3623 out_codec_name, encoder_name);
3625 av_log(NULL, AV_LOG_INFO,
" (copy)");
3626 av_log(NULL, AV_LOG_INFO,
"\n");
3630 av_log(NULL, AV_LOG_ERROR,
"%s\n", error);
3659 int64_t opts_min = INT64_MAX;
3665 if (ost->filter && ost->last_filter_pts != AV_NOPTS_VALUE) {
3668 opts = ost->last_mux_dts == AV_NOPTS_VALUE ?
3669 INT64_MIN : ost->last_mux_dts;
3670 if (ost->last_mux_dts == AV_NOPTS_VALUE)
3671 av_log(ost, AV_LOG_DEBUG,
3672 "cur_dts is invalid [init:%d i_done:%d finish:%d] (this is harmless if it occurs once at the start per stream)\n",
3673 ost->initialized, ost->inputs_done, ost->finished);
3676 if (!ost->initialized && !ost->inputs_done)
3677 return ost->unavailable ? NULL : ost;
3679 if (!ost->finished && opts < opts_min) {
3691 if (tcgetattr(0, &tty) == 0) {
3692 if (on) tty.c_lflag |= ECHO;
3693 else tty.c_lflag &= ~ECHO;
3694 tcsetattr(0, TCSANOW, &tty);
3703 return AVERROR_EXIT;
3711 av_log(NULL, AV_LOG_INFO,
"\n\n[q] command received. Exiting.\n\n");
3712 return AVERROR_EXIT;
3714 if (key ==
'+') av_log_set_level(av_log_get_level()+10);
3715 if (key ==
'-') av_log_set_level(av_log_get_level()-10);
3717 if (key ==
'c' || key ==
'C'){
3718 char buf[4096], target[64], command[256], arg[256] = {0};
3721 av_log(NULL,
AV_LOG_STDERR,
"\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
3724 while ((k =
read_key()) !=
'\n' && k !=
'\r' && i <
sizeof(buf)-1)
3731 (n = sscanf(buf,
"%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
3732 av_log(NULL, AV_LOG_DEBUG,
"Processing command target:%s time:%f command:%s arg:%s",
3733 target, time, command, arg);
3738 ret = avfilter_graph_send_command(fg->
graph, target, command, arg, buf,
sizeof(buf),
3739 key ==
'c' ? AVFILTER_CMD_FLAG_ONE : 0);
3740 av_log(NULL,
AV_LOG_STDERR,
"Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
3741 }
else if (key ==
'c') {
3742 av_log(NULL,
AV_LOG_STDERR,
"Queuing commands only on filters supporting the specific command is unsupported\n");
3743 ret = AVERROR_PATCHWELCOME;
3745 ret = avfilter_graph_queue_command(fg->
graph, target, command, arg, 0, time);
3747 av_log(NULL,
AV_LOG_STDERR,
"Queuing command failed with error %s\n", av_err2str(ret));
3752 av_log(NULL, AV_LOG_ERROR,
3753 "Parse error, at least 3 arguments were expected, "
3754 "only %d given in string '%s'\n", n, buf);
3757 if (key ==
'd' || key ==
'D'){
3763 debug = ist->
dec_ctx->debug << 1;
3765 if(!debug) debug = 1;
3766 while (debug & FF_DEBUG_DCT_COEFF)
3773 while ((k =
read_key()) !=
'\n' && k !=
'\r' && i <
sizeof(buf)-1)
3779 if (k <= 0 || sscanf(buf,
"%d", &debug)!=1)
3783 ist->dec_ctx->debug = debug;
3786 ost->enc_ctx->debug = debug;
3788 if(debug) av_log_set_level(AV_LOG_DEBUG);
3793 "? show this help\n"
3794 "+ increase verbosity\n"
3795 "- decrease verbosity\n"
3796 "c Send command to first matching filter supporting it\n"
3797 "C Send/Queue command to all matching filters\n"
3798 "D cycle through available debug modes\n"
3799 "h dump packets/hex press to cycle through the 3 states\n"
3801 "s Show QP histogram\n"
3810 if (ost->unavailable)
3821 ost->unavailable = 0;
3826 for (
int i = 0; i < ifile->
nb_streams; i++) {
3839 if (ist->
par->codec_type == AVMEDIA_TYPE_AUDIO) {
3844 (AVRational){ 1, ist->dec_ctx->sample_rate},
3845 ist->
st->time_base);
3850 avcodec_flush_buffers(ist->
dec_ctx);
3858 const int fmt_is_discont = ifile->
ctx->iformat->flags & AVFMT_TS_DISCONT;
3859 int disable_discontinuity_correction =
copy_ts;
3860 int64_t pkt_dts = av_rescale_q_rnd(pkt->dts, ist->
st->time_base, AV_TIME_BASE_Q,
3861 AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
3864 fmt_is_discont && ist->
st->pts_wrap_bits < 60) {
3865 int64_t wrap_dts = av_rescale_q_rnd(pkt->dts + (1LL<<ist->
st->pts_wrap_bits),
3866 ist->
st->time_base, AV_TIME_BASE_Q,
3867 AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
3869 disable_discontinuity_correction = 0;
3872 if (ist->
next_dts != AV_NOPTS_VALUE && !disable_discontinuity_correction) {
3873 int64_t delta = pkt_dts - ist->
next_dts;
3874 if (fmt_is_discont) {
3876 pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->
pts, ist->
dts)) {
3878 av_log(NULL, AV_LOG_DEBUG,
3879 "timestamp discontinuity for stream #%d:%d "
3880 "(id=%d, type=%s): %"PRId64
", new offset= %"PRId64
"\n",
3882 av_get_media_type_string(ist->
par->codec_type),
3884 pkt->dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->
st->time_base);
3885 if (pkt->pts != AV_NOPTS_VALUE)
3886 pkt->pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->
st->time_base);
3890 av_log(NULL, AV_LOG_WARNING,
"DTS %"PRId64
", next:%"PRId64
" st:%d invalid dropping\n", pkt->dts, ist->
next_dts, pkt->stream_index);
3891 pkt->dts = AV_NOPTS_VALUE;
3893 if (pkt->pts != AV_NOPTS_VALUE){
3894 int64_t pkt_pts = av_rescale_q(pkt->pts, ist->
st->time_base, AV_TIME_BASE_Q);
3897 av_log(NULL, AV_LOG_WARNING,
"PTS %"PRId64
", next:%"PRId64
" invalid dropping st:%d\n", pkt->pts, ist->
next_dts, pkt->stream_index);
3898 pkt->pts = AV_NOPTS_VALUE;
3903 fmt_is_discont && ifile->
last_ts != AV_NOPTS_VALUE) {
3904 int64_t delta = pkt_dts - ifile->
last_ts;
3907 av_log(NULL, AV_LOG_DEBUG,
3908 "Inter stream timestamp discontinuity %"PRId64
", new offset= %"PRId64
"\n",
3910 pkt->dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->
st->time_base);
3911 if (pkt->pts != AV_NOPTS_VALUE)
3912 pkt->pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->
st->time_base);
3916 ifile->
last_ts = av_rescale_q(pkt->dts, ist->
st->time_base, AV_TIME_BASE_Q);
3923 ist->
st->time_base);
3927 if (pkt->dts != AV_NOPTS_VALUE)
3929 if (pkt->pts != AV_NOPTS_VALUE)
3933 if ((ist->
par->codec_type == AVMEDIA_TYPE_VIDEO ||
3934 ist->
par->codec_type == AVMEDIA_TYPE_AUDIO) &&
3935 pkt->dts != AV_NOPTS_VALUE)
3949 AVFormatContext *is;
3957 if (ret == AVERROR(EAGAIN)) {
3964 return AVERROR(EAGAIN);
3967 if (ret != AVERROR_EOF) {
3983 if (ost->ist == ist &&
3984 (!ost->enc_ctx || ost->enc_ctx->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
3992 return AVERROR(EAGAIN);
3997 ist = ifile->
streams[pkt->stream_index];
4003 goto discard_packet;
4007 for (i = 0; i < ist->
st->nb_side_data; i++) {
4008 AVPacketSideData *src_sd = &ist->
st->side_data[i];
4011 if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
4014 if (av_packet_get_side_data(pkt, src_sd->type, NULL))
4017 dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
4021 memcpy(dst_data, src_sd->data, src_sd->size);
4029 av_log(NULL, AV_LOG_INFO,
"demuxer+ffmpeg -> ist_index:%d:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s duration:%s duration_time:%s off:%s off_time:%s\n",
4030 ifile->
index, pkt->stream_index,
4031 av_get_media_type_string(ist->
par->codec_type),
4032 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ist->
st->time_base),
4033 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ist->
st->time_base),
4034 av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, &ist->
st->time_base),
4044 av_packet_free(&pkt);
4059 int nb_requests, nb_requests_max = 0;
4064 ret = avfilter_graph_request_oldest(graph->
graph);
4068 if (ret == AVERROR_EOF) {
4074 if (ret != AVERROR(EAGAIN))
4077 for (i = 0; i < graph->
nb_inputs; i++) {
4078 ifilter = graph->
inputs[i];
4083 nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->
filter);
4084 if (nb_requests > nb_requests_max) {
4085 nb_requests_max = nb_requests;
4115 av_log(NULL, AV_LOG_VERBOSE,
"No more inputs to read from, finishing.\n");
4123 av_log(NULL, AV_LOG_ERROR,
"Error reinitializing filters!\n");
4151 if (av_buffersink_get_type(ost->
filter->
filter) == AVMEDIA_TYPE_AUDIO)
4158 }
else if (ost->
filter) {
4177 if (ret == AVERROR(EAGAIN)) {
4184 return ret == AVERROR_EOF ? 0 : ret;
4196 int64_t timer_start;
4197 int64_t total_packets_written = 0;
4204 av_log(NULL, AV_LOG_INFO,
"Press [q] to stop, [?] for help\n");
4207 timer_start = av_gettime_relative();
4210 int64_t cur_time= av_gettime_relative();
4219 av_log(NULL, AV_LOG_VERBOSE,
"No more output streams to write to, finishing.\n");
4224 if (ret < 0 && ret != AVERROR_EOF) {
4225 av_log(NULL, AV_LOG_ERROR,
"Error while filtering: %s\n", av_err2str(ret));
4255 uint64_t packets_written;
4256 packets_written = atomic_load(&ost->packets_written);
4257 total_packets_written += packets_written;
4259 av_log(ost, AV_LOG_FATAL,
"Empty output\n");
4265 av_log(NULL, AV_LOG_FATAL,
"Empty output\n");
4282 struct rusage rusage;
4284 getrusage(RUSAGE_SELF, &rusage);
4286 (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
4288 (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
4289#elif HAVE_GETPROCESSTIMES
4291 FILETIME c, e, k, u;
4292 proc = GetCurrentProcess();
4293 GetProcessTimes(proc, &c, &e, &k, &u);
4295 ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
4297 ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
4306#if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
4307 struct rusage rusage;
4308 getrusage(RUSAGE_SELF, &rusage);
4309 return (int64_t)rusage.ru_maxrss * 1024;
4310#elif HAVE_GETPROCESSMEMORYINFO
4312 PROCESS_MEMORY_COUNTERS memcounters;
4313 proc = GetCurrentProcess();
4314 memcounters.cb =
sizeof(memcounters);
4315 GetProcessMemoryInfo(proc, &memcounters,
sizeof(memcounters));
4316 return memcounters.PeakPagefileUsage;
4357 for(
int i = 0; i < FF_ARRAY_ELEMS(
qp_histogram); i++) {
4380 char _program_name[] =
"ffmpeg";
4384 #define OFFSET(x) offsetof(OptionsContext, x)
4402 {
"bsfs",
OPT_EXIT, { .func_arg =
show_bsfs },
"show available bit stream filters" },
4412 {
"report", 0, { .func_arg =
opt_report },
"generate a report" },
4413 {
"max_alloc",
HAS_ARG, { .func_arg =
opt_max_alloc },
"set maximum size of a single allocated block",
"bytes" },
4420 "list sources of the input device",
"device" },
4422 "list sinks of the output device",
"device" },
4427 "force format",
"fmt" },
4429 "overwrite output files" },
4431 "never overwrite output files" },
4433 "Ignore unknown stream types" },
4435 "Copy unknown stream types" },
4437 "allow recasting stream type in order to force a decoder of different media type" },
4440 "codec name",
"codec" },
4443 "codec name",
"codec" },
4446 "preset name",
"preset" },
4449 "set input stream mapping",
4450 "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
4451 #if FFMPEG_OPT_MAP_CHANNEL
4453 "map an audio channel from one stream to another (deprecated)",
"file.stream.channel[:syncfile.syncstream]" },
4457 "set metadata information of outfile from infile",
4458 "outfile[,metadata]:infile[,metadata]" },
4461 "set chapters mapping",
"input_file_index" },
4464 "record or transcode \"duration\" seconds of audio/video",
4467 "record or transcode stop time",
"time_stop" },
4469 "set the limit file size in bytes",
"limit_size" },
4472 "set the start time offset",
"time_off" },
4475 "set the start time offset relative to EOF",
"time_off" },
4478 "enable/disable seeking by timestamp with -ss" },
4481 "enable/disable accurate seeking with -ss" },
4484 "Indicate the input index for sync reference",
"sync ref" },
4487 "set the input ts offset",
"time_off" },
4490 "set the input ts scale",
"scale" },
4492 "set the recording timestamp ('now' to set the current time)",
"time" },
4494 "add metadata",
"string=string" },
4496 "add program with specified streams",
"title=string:st=number..." },
4499 "set the number of data frames to output",
"number" },
4501 "add timings for benchmarking" },
4503 "add timings for each task" },
4505 "write program-readable progress information",
"url" },
4507 "enable or disable interaction on standard input" },
4509 "set max runtime in seconds in CPU user time",
"limit" },
4511 "dump each input packet" },
4513 "when dumping packets, also dump the payload" },
4516 "read input at native frame rate; equivalent to -readrate 1",
"" },
4519 "read input at specified rate",
"speed" },
4521 "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\" or \"dv50\" "
4522 "with optional prefixes \"pal-\", \"ntsc-\" or \"film-\")",
"type" },
4524 "set video sync method globally; deprecated, use -fps_mode",
"" },
4526 "frame drop threshold",
"" },
4528 "audio drift threshold",
"threshold" },
4530 "copy timestamps" },
4532 "shift input timestamps to start at 0 when using copyts" },
4534 "copy input stream time base when stream copying",
"mode" },
4537 "finish encoding within shortest input" },
4539 "maximum buffering duration (in seconds) for the -shortest option" },
4547 "timestamp discontinuity delta threshold",
"threshold" },
4549 "timestamp error delta threshold",
"threshold" },
4551 "exit on error",
"error" },
4553 "abort on the specified condition flags",
"flags" },
4556 "copy initial non-keyframes" },
4558 "copy or discard frames before start time" },
4560 "set the number of frames to output",
"number" },
4563 "force codec tag/fourcc",
"fourcc/tag" },
4566 "use fixed quality scale (VBR)",
"q" },
4569 "use fixed quality scale (VBR)",
"q" },
4571 "set profile",
"profile" },
4573 "set stream filtergraph",
"filter_graph" },
4575 "number of non-complex filter threads" },
4577 "read stream filtergraph description from a file",
"filename" },
4579 "reinit filtergraph on input parameter changes",
"" },
4581 "create a complex filtergraph",
"graph_description" },
4583 "number of threads for -filter_complex" },
4585 "create a complex filtergraph",
"graph_description" },
4587 "read complex filtergraph description from a file",
"filename" },
4589 "enable automatic conversion filters globally" },
4591 "print progress report during encoding", },
4593 "set the period at which ffmpeg updates stats and -progress output",
"time" },
4596 "add an attachment to the output file",
"filename" },
4599 "extract an attachment into a file",
"filename" },
4601 OPT_OFFSET, { .off =
OFFSET(loop) },
"set number of times input stream shall be looped",
"loop count" },
4603 "print timestamp debugging info" },
4605 "ratio of decoding errors (0.0: no errors, 1.0: 100% errors) above which ffmpeg returns an error instead of success.",
"maximum error rate" },
4611 "disposition",
"" },
4613 { .off =
OFFSET(thread_queue_size) },
4614 "set the maximum number of queued packets from the demuxer" },
4616 "read and decode the streams to fill missing information with heuristics" },
4618 { .off =
OFFSET(bits_per_raw_sample) },
4619 "set the number of bits per raw sample",
"number" },
4622 "write encoding stats before encoding" },
4624 "write encoding stats after encoding" },
4626 "write packets stats before muxing" },
4628 "format of the stats written with -stats_enc_pre" },
4630 "format of the stats written with -stats_enc_post" },
4632 "format of the stats written with -stats_mux_pre" },
4636 "set the number of video frames to output",
"number" },
4639 "set frame rate (Hz value, fraction or abbreviation)",
"rate" },
4642 "set max frame rate (Hz value, fraction or abbreviation)",
"rate" },
4645 "set frame size (WxH or abbreviation)",
"size" },
4648 "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)",
"aspect" },
4651 "set pixel format",
"format" },
4654 "set pure counter-clockwise rotation in degrees for stream(s)",
4657 "set display horizontal flip for stream(s) "
4658 "(overrides any display rotation if it is not set)"},
4660 "set display vertical flip for stream(s) "
4661 "(overrides any display rotation if it is not set)"},
4666 "rate control override for specific intervals",
"override" },
4669 "force video codec ('copy' to copy stream)",
"codec" },
4671 "set initial TimeCode value.",
"hh:mm:ss[:;.]ff" },
4673 "select the pass number (1 to 3)",
"n" },
4676 "select two pass log file name prefix",
"prefix" },
4679 "calculate PSNR of compressed frames (deprecated, use -flags +psnr)" },
4682 "dump video coding statistics to file" },
4684 "dump video coding statistics to file",
"file" },
4686 "Version of the vstats format to use."},
4688 "set video filters",
"filter_graph" },
4691 "specify intra matrix coeffs",
"matrix" },
4694 "specify inter matrix coeffs",
"matrix" },
4697 "specify intra matrix coeffs",
"matrix" },
4700 "top=1/bottom=0/auto=-1 field first",
"" },
4703 "force video tag/fourcc",
"fourcc/tag" },
4705 "show QP histogram" },
4708 "set framerate mode for matching video streams; overrides vsync" },
4711 "force the selected framerate, disable the best supported framerate selection" },
4714 "set the value of an outfile streamid",
"streamIndex:value" },
4717 "force key frames at specified timestamps",
"timestamps" },
4719 "video bitrate (please use -b:v)",
"bitrate" },
4722 "use HW accelerated decoding",
"hwaccel name" },
4725 "select a device for HW acceleration",
"devicename" },
4728 "select output format used with HW accelerated decoding",
"format" },
4730 "show available HW acceleration methods" },
4733 "automatically insert correct rotate filters" },
4736 "automatically insert a scale filter at the end of the filter graph" },
4739 "set this video output stream to be a heartbeat stream for "
4740 "fix_sub_duration, according to which subtitles should be split at "
4741 "random access points" },
4745 "set the number of audio frames to output",
"number" },
4747 "set audio quality (codec-specific)",
"quality", },
4750 "set audio sampling rate (in Hz)",
"rate" },
4753 "set number of audio channels",
"channels" },
4758 "force audio codec ('copy' to copy stream)",
"codec" },
4760 "audio bitrate (please use -b:a)",
"bitrate" },
4763 "force audio tag/fourcc",
"fourcc/tag" },
4766 "set sample format",
"format" },
4769 "set channel layout",
"layout" },
4772 "set channel layout",
"layout" },
4774 "set audio filters",
"filter_graph" },
4776 "set the maximum number of channels to try to guess the channel layout" },
4780 "disable subtitle" },
4782 "force subtitle codec ('copy' to copy stream)",
"codec" },
4784 ,
"force subtitle tag/fourcc",
"fourcc/tag" },
4786 "fix subtitles duration" },
4788 "set canvas size (WxH or abbreviation)",
"size" },
4792 "set the maximum demux-decode delay",
"seconds" },
4794 "set the initial demux-decode delay",
"seconds" },
4796 "specify a file in which to print sdp information",
"file" },
4799 "set the desired time base hint for output stream (1:24, 1:48000 or 0.04166, 2.0833e-5)",
"ratio" },
4801 "set the desired time base for the encoder (1:24, 1:48000 or 0.04166, 2.0833e-5). "
4802 "two special values are defined - "
4803 "0 = use frame rate (video) or sample rate (audio),"
4804 "-1 = match source time base",
"ratio" },
4807 "A comma-separated list of bitstream filters",
"bitstream_filters" },
4809 "deprecated",
"audio bitstream_filters" },
4811 "deprecated",
"video bitstream_filters" },
4814 "set the audio options to the indicated preset",
"preset" },
4816 "set the video options to the indicated preset",
"preset" },
4818 "set the subtitle options to the indicated preset",
"preset" },
4820 "set options from indicated preset file",
"filename" },
4823 "maximum number of packets that can be buffered while waiting for all streams to initialize",
"packets" },
4825 "set the threshold after which max_muxing_queue_size is taken into account",
"bytes" },
4829 "force data codec ('copy' to copy stream)",
"codec" },
4835 "set VAAPI hardware device (DRM path or X11 display name)",
"device" },
4840 "set QSV hardware device (DirectX adapter index, DRM path or X11 display name)",
"device"},
4844 "initialise hardware device",
"args" },
4846 "set hardware device used when filtering",
"device" },
4857 if (savedCode == 0) {
4865 av_log_set_flags(AV_LOG_SKIP_REPEATED);
4869 avdevice_register_all();
4871 avformat_network_init();
4882 av_log(NULL, AV_LOG_WARNING,
"Use -h to get full help or, even better, run 'man %s'\n",
program_name);
4888 av_log(NULL, AV_LOG_FATAL,
"At least one output file must be specified\n");
4896 int64_t utime, stime, rtime;
4901 av_log(NULL, AV_LOG_INFO,
4902 "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
4903 utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
4905 av_log(NULL, AV_LOG_DEBUG,
"%"PRIu64
" frames successfully decoded, %"PRIu64
" decoding errors\n",
__thread jmp_buf ex_buf__
EncStatsComponent * components
double expr_const_values[FKF_NB]
const AVOutputFormat * format
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
struct FilterGraph * graph
AVChannelLayout ch_layout
unsigned int fix_sub_duration_heartbeat
int copy_initial_nonkeyframes
int64_t vsync_frame_number
AVRational frame_aspect_ratio
double rotate_override_value
enum VideoSyncMethod vsync_method
AVRational max_frame_rate
int64_t last_nb0_frames[3]
AVDictionary * encoder_opts
char * filters
filtergraph associated to the -filter option
atomic_uint_least64_t packets_written
char * filters_script
filtergraph script associated to the -filter_script option