33 #include <stdatomic.h>
73 #if HAVE_SYS_RESOURCE_H
75 #include <sys/types.h>
76 #include <sys/resource.h>
77 #elif HAVE_GETPROCESSTIMES
80 #if HAVE_GETPROCESSMEMORYINFO
84 #if HAVE_SETCONSOLECTRLHANDLER
90 #include <sys/select.h>
95 #include <sys/ioctl.h>
164 static struct termios oldtty;
165 static int restore_tty;
169 static void free_input_threads(
void);
195 uint32_t *pal, *dst2;
203 if (
r->x < 0 ||
r->x +
r->w >
w ||
r->y < 0 ||
r->y +
r->h >
h) {
205 r->x,
r->y,
r->w,
r->h,
w,
h
210 dst +=
r->y * dst_linesize +
r->x * 4;
212 pal = (uint32_t *)
r->data[1];
213 for (y = 0; y <
r->h; y++) {
214 dst2 = (uint32_t *)dst;
216 for (x = 0; x <
r->w; x++)
217 *(dst2++) = pal[*(src2++)];
219 src +=
r->linesize[0];
247 int64_t
pts, end_pts;
256 num_rects =
sub->num_rects;
269 "Impossible to get a blank canvas.\n");
274 for (
i = 0;
i < num_rects;
i++)
299 if (pts2 <= ist2->sub2video.last_pts)
306 for (j = 0, nb_reqs = 0; j < ist2->
nb_filters; j++)
333 tcsetattr (0, TCSANOW, &oldtty);
358 ret = write(2,
"Received > 3 system signals, hard exiting\n",
359 strlen(
"Received > 3 system signals, hard exiting\n"));
365 #if HAVE_SETCONSOLECTRLHANDLER
366 static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
373 case CTRL_BREAK_EVENT:
377 case CTRL_CLOSE_EVENT:
378 case CTRL_LOGOFF_EVENT:
379 case CTRL_SHUTDOWN_EVENT:
398 #define SIGNAL(sig, func) \
400 action.sa_handler = func; \
401 sigaction(sig, &action, NULL); \
404 #define SIGNAL(sig, func) \
410 #if defined __linux__
411 struct sigaction action = {0};
415 sigfillset(&action.sa_mask);
418 action.sa_flags = SA_RESTART;
424 if (tcgetattr (0, &tty) == 0) {
428 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
429 |INLCR|IGNCR|ICRNL|IXON);
430 tty.c_oflag |= OPOST;
431 tty.c_lflag &= ~(
ECHO|ECHONL|ICANON|IEXTEN);
432 tty.c_cflag &= ~(CSIZE|PARENB);
437 tcsetattr (0, TCSANOW, &tty);
449 signal(SIGPIPE, SIG_IGN);
451 #if HAVE_SETCONSOLECTRLHANDLER
452 SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
469 n = select(1, &rfds,
NULL,
NULL, &tv);
478 # if HAVE_PEEKNAMEDPIPE
480 static HANDLE input_handle;
483 input_handle = GetStdHandle(STD_INPUT_HANDLE);
484 is_pipe = !GetConsoleMode(input_handle, &dw);
489 if (!PeekNamedPipe(input_handle,
NULL, 0,
NULL, &nchars,
NULL)) {
604 ost->audio_channels_mapped = 0;
612 if (
ost->muxing_queue) {
624 free_input_threads();
652 "Error closing vstats file, loss of information possible: %s\n",
711 "bench: %8" PRIu64
" user %8" PRIu64
" sys %8" PRIu64
" real %s \n",
725 ost2->
finished |=
ost == ost2 ? this_stream : others;
744 if (
ost->frame_number >=
ost->max_frames) {
755 unsigned int are_we_over_size =
756 (
ost->muxing_queue_data_size +
pkt->
size) >
ost->muxing_queue_data_threshold;
757 int new_size = are_we_over_size ?
759 ost->max_muxing_queue_size) :
764 "Too many packets buffered for output stream %d:%d.\n",
779 ost->muxing_queue_data_size += tmp_pkt->
size;
802 if (
ost->frame_rate.num &&
ost->is_cfr) {
816 av_log(
s,
AV_LOG_WARNING,
"Invalid DTS: %"PRId64
" PTS: %"PRId64
" in output stream %d:%d, replacing by guess\n",
833 av_log(
s, loglevel,
"Non-monotonous DTS in output stream "
834 "%d:%d; previous: %"PRId64
", current: %"PRId64
"; ",
840 av_log(
s, loglevel,
"changing to %"PRId64
". This may result "
841 "in incorrect timestamps in the output file.\n",
852 ost->packets_written++;
858 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
917 "packet for stream #%d:%d.\n",
ost->file_index,
ost->
index);
942 !enc || !
ost->filter || !
ost->filter->graph->graph)
959 float_pts +=
FFSIGN(float_pts) * 1.0 / (1<<17);
981 char *
error,
int error_len);
987 char error[1024] = {0};
989 if (
ost->initialized)
1020 ost->frames_encoded++;
1025 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1048 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1066 int subtitle_out_max_size = 1024 * 1024;
1067 int subtitle_out_size, nb,
i;
1101 for (
i = 0;
i < nb;
i++) {
1102 unsigned save_num_rects =
sub->num_rects;
1111 sub->end_display_time -=
sub->start_display_time;
1112 sub->start_display_time = 0;
1116 ost->frames_encoded++;
1119 subtitle_out_max_size,
sub);
1121 sub->num_rects = save_num_rects;
1122 if (subtitle_out_size < 0) {
1129 pkt->
size = subtitle_out_size;
1149 int ret, format_video_sync;
1153 int nb_frames, nb0_frames,
i;
1154 double delta, delta0;
1164 if (
ost->source_index >= 0)
1168 if (frame_rate.
num > 0 && frame_rate.
den > 0)
1174 if (!
ost->filters_script &&
1183 if (!next_picture) {
1185 nb0_frames = nb_frames =
mid_pred(
ost->last_nb0_frames[0],
1186 ost->last_nb0_frames[1],
1187 ost->last_nb0_frames[2]);
1189 delta0 = sync_ipts -
ost->sync_opts;
1218 if (delta0 < -0.6) {
1222 sync_ipts =
ost->sync_opts;
1227 switch (format_video_sync) {
1229 if (
ost->frame_number == 0 && delta0 >= 0.5) {
1239 }
else if (
delta < -1.1)
1241 else if (
delta > 1.1) {
1244 nb0_frames =
llrintf(delta0 - 0.6);
1250 else if (
delta > 0.6)
1262 nb_frames =
FFMIN(nb_frames,
ost->max_frames -
ost->frame_number);
1263 nb0_frames =
FFMIN(nb0_frames, nb_frames);
1265 memmove(
ost->last_nb0_frames + 1,
1266 ost->last_nb0_frames,
1268 ost->last_nb0_frames[0] = nb0_frames;
1270 if (nb0_frames == 0 &&
ost->last_dropped) {
1273 "*** dropping frame %d from stream %d at ts %"PRId64
"\n",
1276 if (nb_frames > (nb0_frames &&
ost->last_dropped) + (nb_frames > nb0_frames)) {
1282 nb_frames_dup += nb_frames - (nb0_frames &&
ost->last_dropped) - (nb_frames > nb0_frames);
1289 ost->last_dropped = nb_frames == nb0_frames && next_picture;
1292 for (
i = 0;
i < nb_frames;
i++) {
1294 int forced_keyframe = 0;
1297 if (i < nb0_frames && ost->last_frame) {
1298 in_picture =
ost->last_frame;
1300 in_picture = next_picture;
1305 in_picture->
pts =
ost->sync_opts;
1315 ost->forced_kf_ref_pts = in_picture->
pts;
1319 if (
ost->forced_kf_index <
ost->forced_kf_count &&
1320 in_picture->
pts >=
ost->forced_kf_pts[
ost->forced_kf_index]) {
1321 ost->forced_kf_index++;
1322 forced_keyframe = 1;
1323 }
else if (
ost->forced_keyframes_pexpr) {
1325 ost->forced_keyframes_expr_const_values[
FKF_T] = pts_time;
1327 ost->forced_keyframes_expr_const_values,
NULL);
1328 ff_dlog(
NULL,
"force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
1329 ost->forced_keyframes_expr_const_values[
FKF_N],
1332 ost->forced_keyframes_expr_const_values[
FKF_T],
1336 forced_keyframe = 1;
1338 ost->forced_keyframes_expr_const_values[
FKF_N];
1340 ost->forced_keyframes_expr_const_values[
FKF_T];
1344 ost->forced_keyframes_expr_const_values[
FKF_N] += 1;
1345 }
else if (
ost->forced_keyframes
1346 && !strncmp(
ost->forced_keyframes,
"source", 6)
1349 forced_keyframe = 1;
1352 if (forced_keyframe) {
1360 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1365 ost->frames_encoded++;
1384 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1396 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1415 ost->frame_number++;
1421 if (!
ost->last_frame)
1424 if (next_picture &&
ost->last_frame)
1437 return -10.0 * log10(d);
1444 double ti1,
bitrate, avg_bitrate;
1459 fprintf(
vstats_file,
"frame= %5d q= %2.1f ", frame_number,
1476 avg_bitrate = (double)(
ost->data_size * 8) / ti1 / 1000.0;
1477 fprintf(
vstats_file,
"s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1478 (
double)
ost->data_size / 1024, ti1,
bitrate, avg_bitrate);
1515 if (!
ost->filter || !
ost->filter->graph->graph)
1537 filtered_frame =
ost->filtered_frame;
1545 "Error in av_buffersink_get_frame_flags(): %s\n",
av_err2str(
ret));
1552 if (
ost->finished) {
1559 if (!
ost->frame_aspect_ratio.num)
1568 "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1587 uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
1588 uint64_t subtitle_size = 0;
1590 float percent = -1.0;
1596 switch (
ost->enc_ctx->codec_type) {
1600 default: other_size +=
ost->data_size;
break;
1602 extra_size +=
ost->enc_ctx->extradata_size;
1612 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: ",
1613 video_size / 1024.0,
1614 audio_size / 1024.0,
1615 subtitle_size / 1024.0,
1616 other_size / 1024.0,
1617 extra_size / 1024.0);
1627 uint64_t total_packets = 0, total_size = 0;
1632 for (j = 0; j <
f->nb_streams; j++) {
1656 total_packets, total_size);
1661 uint64_t total_packets = 0, total_size = 0;
1670 total_size +=
ost->data_size;
1671 total_packets +=
ost->packets_written;
1675 if (
ost->encoding_needed) {
1677 ost->frames_encoded);
1684 ost->packets_written,
ost->data_size);
1690 total_packets, total_size);
1692 if(video_size +
data_size + audio_size + subtitle_size + extra_size == 0){
1702 static void print_report(
int is_last_report, int64_t timer_start, int64_t cur_time)
1704 AVBPrint buf, buf_script;
1709 int frame_number, vid,
i;
1712 int64_t
pts = INT64_MIN + 1;
1713 static int64_t last_time = -1;
1714 static int first_report = 1;
1715 static int qp_histogram[52];
1716 int hours, mins, secs,
us;
1717 const char *hours_sign;
1724 if (!is_last_report) {
1725 if (last_time == -1) {
1726 last_time = cur_time;
1728 if (((cur_time - last_time) <
stats_period && !first_report) ||
1731 last_time = cur_time;
1734 t = (cur_time-timer_start) / 1000000.0;
1740 if (total_size <= 0)
1750 if (!
ost->stream_copy)
1755 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
1761 frame_number =
ost->frame_number;
1762 fps = t > 1 ? frame_number / t : 0;
1763 av_bprintf(&buf,
"frame=%5d fps=%3.*f q=%3.1f ",
1764 frame_number, fps < 9.95, fps, q);
1765 av_bprintf(&buf_script,
"frame=%d\n", frame_number);
1767 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
1776 for (j = 0; j < 32; j++)
1782 double error, error_sum = 0;
1783 double scale, scale_sum = 0;
1785 char type[3] = {
'Y',
'U',
'V' };
1787 for (j = 0; j < 3; j++) {
1788 if (is_last_report) {
1790 scale = enc->
width * enc->
height * 255.0 * 255.0 * frame_number;
1801 av_bprintf(&buf_script,
"stream_%d_%d_psnr_%c=%2.2f\n",
1804 p =
psnr(error_sum / scale_sum);
1806 av_bprintf(&buf_script,
"stream_%d_%d_psnr_all=%2.2f\n",
1833 hours_sign = (
pts < 0) ?
"-" :
"";
1835 bitrate =
pts && total_size >= 0 ? total_size * 8 / (
pts / 1000.0) : -1;
1838 if (total_size < 0)
av_bprintf(&buf,
"size=N/A time=");
1839 else av_bprintf(&buf,
"size=%8.0fkB time=", total_size / 1024.0);
1855 if (total_size < 0)
av_bprintf(&buf_script,
"total_size=N/A\n");
1856 else av_bprintf(&buf_script,
"total_size=%"PRId64
"\n", total_size);
1858 av_bprintf(&buf_script,
"out_time_us=N/A\n");
1859 av_bprintf(&buf_script,
"out_time_ms=N/A\n");
1864 av_bprintf(&buf_script,
"out_time=%s%02d:%02d:%02d.%06d\n",
1865 hours_sign, hours, mins, secs,
us);
1878 av_bprintf(&buf_script,
"speed=%4.3gx\n", speed);
1882 const char end = is_last_report ?
'\n' :
'\r';
1884 fprintf(stderr,
"%s %c", buf.str, end);
1894 is_last_report ?
"end" :
"continue");
1896 FFMIN(buf_script.len, buf_script.size - 1));
1899 if (is_last_report) {
1902 "Error closing progress log, loss of information possible: %s\n",
av_err2str(
ret));
1934 if (!
ost->encoding_needed)
1939 if (!
ost->initialized) {
1943 "Finishing stream %d:%d without any data written to it.\n",
2037 if (
ost->source_index != ist_index)
2065 !
ost->copy_initial_nonkeyframes)
2068 if (!
ost->frame_number && !
ost->copy_prior_start) {
2073 ist->
pts < comp_start :
2084 if (
f->recording_time != INT64_MAX) {
2114 opkt->
pts = opkt->
dts - ost_tb_start_time;
2117 opkt->
dts -= ost_tb_start_time;
2128 if (!
dec->channel_layout) {
2129 char layout_name[256];
2134 if (!
dec->channel_layout)
2137 dec->channels,
dec->channel_layout);
2177 int need_reinit,
ret,
i;
2208 if (need_reinit || !fg->
graph) {
2320 "Failed to inject frame into filter network: %s\n",
av_err2str(
ret));
2386 return err < 0 ? err :
ret;
2393 int i,
ret = 0, err = 0;
2394 int64_t best_effort_timestamp;
2437 "video_delay is larger in decoder than demuxer %d > %d.\n"
2438 "If you want to help, upload a sample "
2439 "of this file to https://streams.videolan.org/upload/ "
2440 "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n",
2500 "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",
2503 best_effort_timestamp,
2517 return err < 0 ? err :
ret;
2542 if (end < ist->
prev_sub.subtitle.end_display_time) {
2544 "Subtitle duration reduced from %"PRId32
" to %d%s\n",
2546 end <= 0 ?
", dropping it" :
"");
2619 int eof_reached = 0;
2657 int64_t duration_dts = 0;
2658 int64_t duration_pts = 0;
2660 int decode_failed = 0;
2691 if (duration_pts > 0) {
2717 if (decode_failed) {
2802 return !eof_reached;
2834 printf(
"SDP:\n%s\n", sdp);
2887 "%s hwaccel requested for input stream #%d:%d, "
2888 "but cannot be initialized.\n",
2916 "%s hwaccel requested for input stream #%d:%d, "
2917 "but cannot be initialized.\n", hwaccel->
name,
2925 if (!
s->hw_frames_ctx)
2954 snprintf(
error, error_len,
"Decoder (codec %s) not found for input stream #%d:%d",
2962 #if LIBAVCODEC_VERSION_MAJOR < 60
2970 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");
2988 "decoder on input stream #%d:%d : %s",
2998 "Error while opening decoder for input stream "
3014 if (
ost->source_index >= 0)
3021 return FFDIFFSIGN(*(
const int64_t *)
a, *(
const int64_t *)
b);
3031 if (!
ost->initialized)
3040 "Could not write header for output file #%d "
3041 "(incorrect codec parameters ?): %s\n",
3111 uint32_t codec_tag = par_dst->
codec_tag;
3120 "Error setting up codec context options.\n");
3127 "Error getting reference codec parameters.\n");
3132 unsigned int codec_tag_tmp;
3145 if (!
ost->frame_rate.num)
3172 memcpy(dst_data, sd_src->
data, sd_src->
size);
3176 if (
ost->rotate_overridden) {
3195 if (
ost->frame_aspect_ratio.num) {
3198 (
AVRational){ par_dst->height, par_dst->width });
3200 "with stream copy may produce invalid files\n");
3222 int encoder_string_len;
3223 int format_flags = 0;
3245 encoder_string =
av_mallocz(encoder_string_len);
3246 if (!encoder_string)
3252 av_strlcpy(encoder_string,
"Lavc ", encoder_string_len);
3253 av_strlcat(encoder_string,
ost->enc->name, encoder_string_len);
3265 for (p = kf; *p; p++)
3276 for (
i = 0;
i < n;
i++) {
3277 char *next = strchr(p,
',');
3282 if (!memcmp(p,
"chapters", 8)) {
3291 "Could not allocate forced key frames array.\n");
3318 ost->forced_kf_pts =
pts;
3327 if (
ost->enc_timebase.num > 0) {
3332 if (
ost->enc_timebase.num < 0) {
3379 if (!
ost->frame_rate.num)
3381 if (ist && !
ost->frame_rate.num)
3383 if (ist && !
ost->frame_rate.num)
3385 if (ist && !
ost->frame_rate.num && !
ost->max_frame_rate.num) {
3389 "about the input framerate is available. Falling "
3390 "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
3391 "if you want a different framerate.\n",
3395 if (
ost->max_frame_rate.num &&
3397 !
ost->frame_rate.den))
3398 ost->frame_rate =
ost->max_frame_rate;
3400 if (
ost->enc->supported_framerates && !
ost->force_fps) {
3402 ost->frame_rate =
ost->enc->supported_framerates[idx];
3407 ost->frame_rate.num,
ost->frame_rate.den, 65535);
3432 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3438 ost->frame_aspect_ratio.num ?
3466 if (
ost->top_field_first == 0) {
3468 }
else if (
ost->top_field_first == 1) {
3474 ost->top_field_first >= 0)
3486 if (
ost->forced_keyframes) {
3487 if (!strncmp(
ost->forced_keyframes,
"expr:", 5)) {
3492 "Invalid force_key_frames expression '%s'\n",
ost->forced_keyframes+5);
3495 ost->forced_keyframes_expr_const_values[
FKF_N] = 0;
3502 }
else if(strncmp(
ost->forced_keyframes,
"source", 6)) {
3509 if (!enc_ctx->
width) {
3527 char *
error,
int error_len)
3531 if (
ost->encoding_needed) {
3542 if (
dec &&
dec->subtitle_header) {
3545 if (!
ost->enc_ctx->subtitle_header)
3547 memcpy(
ost->enc_ctx->subtitle_header,
dec->subtitle_header,
dec->subtitle_header_size);
3548 ost->enc_ctx->subtitle_header_size =
dec->subtitle_header_size;
3561 "encoder on output stream #%d:%d : %s",
3567 int input_props = 0, output_props = 0;
3572 if (input_descriptor)
3574 if (output_descriptor)
3576 if (input_props && output_props && input_props != output_props) {
3578 "Subtitle encoding currently only possible from text to text "
3579 "or bitmap to bitmap");
3588 "Error while opening encoder for output stream #%d:%d - "
3589 "maybe incorrect parameters such as bit_rate, rate, width or height",
3596 ost->enc_ctx->frame_size);
3598 if (
ost->enc_ctx->bit_rate &&
ost->enc_ctx->bit_rate < 1000 &&
3601 " It takes bits/s as argument, not kbits/s\n");
3606 "Error initializing the output stream codec context.\n");
3610 if (
ost->enc_ctx->nb_coded_side_data) {
3613 for (
i = 0;
i <
ost->enc_ctx->nb_coded_side_data;
i++) {
3620 memcpy(dst_data, sd_src->
data, sd_src->
size);
3653 }
else if (
ost->stream_copy) {
3662 {
"disposition" ,
NULL, 0,
AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit =
"flags" },
3680 static const AVClass class = {
3686 const AVClass *pclass = &
class;
3700 ost->initialized = 1;
3717 "New %s stream %d:%d at pos:%"PRId64
" and DTS:%ss\n",
3726 int ret = 0,
i, j, k;
3730 char error[1024] = {0};
3750 if (
ifile->rate_emu)
3751 for (j = 0; j <
ifile->nb_streams; j++)
3788 for (j = 0; j <
ifile->ctx->nb_programs; j++) {
3832 if (
ost->attachment_filename) {
3857 ost->sync_ist->file_index,
3859 if (
ost->stream_copy)
3864 const char *decoder_name =
"?";
3865 const char *in_codec_name =
"?";
3866 const char *encoder_name =
"?";
3867 const char *out_codec_name =
"?";
3871 decoder_name = in_codec->
name;
3874 in_codec_name =
desc->name;
3875 if (!strcmp(decoder_name, in_codec_name))
3876 decoder_name =
"native";
3880 encoder_name = out_codec->
name;
3883 out_codec_name =
desc->name;
3884 if (!strcmp(encoder_name, out_codec_name))
3885 encoder_name =
"native";
3889 in_codec_name, decoder_name,
3890 out_codec_name, encoder_name);
3915 if (
ost->finished ||
3918 if (
ost->frame_number >=
ost->max_frames) {
3939 int64_t opts_min = INT64_MAX;
3949 "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",
3952 if (!
ost->initialized && !
ost->inputs_done)
3955 if (!
ost->finished &&
opts < opts_min) {
3967 if (tcgetattr(0, &tty) == 0) {
3968 if (on) tty.c_lflag |=
ECHO;
3969 else tty.c_lflag &= ~
ECHO;
3970 tcsetattr(0, TCSANOW, &tty);
3978 static int64_t last_time;
3984 last_time = cur_time;
4001 if (
key ==
'c' ||
key ==
'C'){
4002 char buf[4096], target[64],
command[256],
arg[256] = {0};
4005 fprintf(stderr,
"\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
4008 while ((k =
read_key()) !=
'\n' && k !=
'\r' &&
i <
sizeof(buf)-1)
4013 fprintf(stderr,
"\n");
4015 (n = sscanf(buf,
"%63[^ ] %lf %255[^ ] %255[^\n]", target, &time,
command,
arg)) >= 3) {
4024 fprintf(stderr,
"Command reply for stream %d: ret:%d res:\n%s",
i, ret, buf);
4025 }
else if (
key ==
'c') {
4026 fprintf(stderr,
"Queuing commands only on filters supporting the specific command is unsupported\n");
4031 fprintf(stderr,
"Queuing command failed with error %s\n",
av_err2str(ret));
4037 "Parse error, at least 3 arguments were expected, "
4038 "only %d given in string '%s'\n", n, buf);
4041 if (
key ==
'd' ||
key ==
'D'){
4045 if(!debug) debug = 1;
4053 while ((k =
read_key()) !=
'\n' && k !=
'\r' &&
i <
sizeof(buf)-1)
4058 fprintf(stderr,
"\n");
4059 if (k <= 0 || sscanf(buf,
"%d", &debug)!=1)
4060 fprintf(stderr,
"error parsing debug value\n");
4067 ost->enc_ctx->debug = debug;
4070 fprintf(stderr,
"debug=%d\n", debug);
4073 fprintf(stderr,
"key function\n"
4074 "? show this help\n"
4075 "+ increase verbosity\n"
4076 "- decrease verbosity\n"
4077 "c Send command to first matching filter supporting it\n"
4078 "C Send/Queue command to all matching filters\n"
4079 "D cycle through available debug modes\n"
4080 "h dump packets/hex press to cycle through the 3 states\n"
4082 "s Show QP histogram\n"
4089 static void *input_thread(
void *
arg)
4119 "Thread message queue blocking; consider raising the "
4120 "thread_queue_size option (current value: %d)\n",
4121 f->thread_queue_size);
4126 "Unable to send packet to main thread: %s\n",
4137 static void free_input_thread(
int i)
4142 if (!
f || !
f->in_thread_queue)
4153 static void free_input_threads(
void)
4158 free_input_thread(
i);
4161 static int init_input_thread(
int i)
4166 if (
f->thread_queue_size < 0)
4168 if (!
f->thread_queue_size)
4171 if (
f->ctx->pb ? !
f->ctx->pb->seekable :
4172 strcmp(
f->ctx->iformat->name,
"lavfi"))
4173 f->non_blocking = 1;
4175 f->thread_queue_size,
sizeof(
f->pkt));
4180 av_log(
NULL,
AV_LOG_ERROR,
"pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
4188 static int init_input_threads(
void)
4193 ret = init_input_thread(
i);
4212 for (
i = 0;
i <
f->nb_streams;
i++) {
4222 if (
f->thread_queue_size)
4223 return get_input_packet_mt(
f,
pkt);
4255 return tmp_time_base;
4261 return tmp_time_base;
4271 int i, ret, has_audio = 0;
4278 for (
i = 0;
i <
ifile->nb_streams;
i++) {
4289 for (
i = 0;
i <
ifile->nb_streams;
i++) {
4310 if (!
ifile->duration)
4320 if (
ifile->loop > 0)
4339 int ret, thread_ret,
i, j;
4342 int disable_discontinuity_correction =
copy_ts;
4351 if (ret < 0 && ifile->
loop) {
4353 for (
i = 0;
i <
ifile->nb_streams;
i++) {
4364 free_input_thread(file_index);
4368 thread_ret = init_input_thread(file_index);
4388 for (
i = 0;
i <
ifile->nb_streams;
i++) {
4400 if (
ost->source_index ==
ifile->ist_index +
i &&
4406 ifile->eof_reached = 1;
4420 goto discard_packet;
4429 goto discard_packet;
4440 "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",
4451 int64_t stime, stime2;
4456 &&
ifile->ts_offset == -
is->start_time
4458 int64_t new_start_time = INT64_MAX;
4459 for (
i=0;
i<
is->nb_streams;
i++) {
4465 if (new_start_time >
is->start_time) {
4467 ifile->ts_offset = -new_start_time;
4501 memcpy(dst_data, src_sd->
data, src_sd->
size);
4525 "Inter stream timestamp discontinuity %"PRId64
", new offset= %"PRId64
"\n",
4551 disable_discontinuity_correction = 0;
4557 !disable_discontinuity_correction) {
4565 "timestamp discontinuity for stream #%d:%d "
4566 "(id=%d, type=%s): %"PRId64
", new offset= %"PRId64
"\n",
4596 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",
4610 if (
ifile->thread_queue_size)
4629 int nb_requests, nb_requests_max = 0;
4654 if (nb_requests > nb_requests_max) {
4655 nb_requests_max = nb_requests;
4689 if (
ost->filter && !
ost->filter->graph->graph) {
4699 if (
ost->filter &&
ost->filter->graph->graph) {
4728 }
else if (
ost->filter) {
4730 for (
i = 0;
i <
ost->filter->graph->nb_inputs;
i++) {
4738 ost->inputs_done = 1;
4749 ost->unavailable = 1;
4768 int64_t timer_start;
4769 int64_t total_packets_written = 0;
4782 if ((ret = init_input_threads()) < 0)
4810 free_input_threads();
4829 "Nothing was written into output file %d (%s), because "
4830 "at least one of its streams received no packets.\n",
4847 if (
ost->encoding_needed) {
4850 total_packets_written +=
ost->packets_written;
4879 free_input_threads();
4887 if (fclose(
ost->logfile))
4889 "Error closing logfile, loss of information possible: %s\n",
4910 struct rusage rusage;
4912 getrusage(RUSAGE_SELF, &rusage);
4914 (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
4916 (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
4917 #elif HAVE_GETPROCESSTIMES
4919 FILETIME
c, e, k,
u;
4920 proc = GetCurrentProcess();
4921 GetProcessTimes(proc, &
c, &e, &k, &
u);
4923 ((int64_t)
u.dwHighDateTime << 32 |
u.dwLowDateTime) / 10;
4925 ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
4934 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
4935 struct rusage rusage;
4936 getrusage(RUSAGE_SELF, &rusage);
4937 return (int64_t)rusage.ru_maxrss * 1024;
4938 #elif HAVE_GETPROCESSMEMORYINFO
4940 PROCESS_MEMORY_COUNTERS memcounters;
4941 proc = GetCurrentProcess();
4942 memcounters.cb =
sizeof(memcounters);
4943 GetProcessMemoryInfo(proc, &memcounters,
sizeof(memcounters));
4944 return memcounters.PeakPagefileUsage;
4963 setvbuf(stderr,
NULL,_IONBF,0);
4968 if(argc>1 && !strcmp(argv[1],
"-d")){
5008 int64_t utime, stime, rtime;
5014 "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
5015 utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
static void flush(AVCodecContext *avctx)
#define ECHO(name, type, min, max)
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
#define av_assert0(cond)
assert() equivalent, that is always enabled.
#define FF_DEBUG_DCT_COEFF
Main libavdevice API header.
Main libavfilter public API header.
int64_t avio_size(AVIOContext *s)
Get the filesize.
#define avio_print(s,...)
Write strings (const char *) to the context.
#define AVIO_FLAG_WRITE
write-only
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
void avio_flush(AVIOContext *s)
Force flushing of buffered data.
int avio_open2(AVIOContext **s, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
Create and initialize a AVIOContext for accessing the resource indicated by url.
int avio_closep(AVIOContext **s)
Close the resource accessed by the AVIOContext *s, free it and set the pointer pointing to it to NULL...
uint8_t * av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type, buffer_size_t *size)
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, buffer_size_t size)
void av_bprintf(AVBPrint *buf, const char *fmt,...)
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
#define AV_BPRINT_SIZE_AUTOMATIC
memory buffer sink API for audio and video
Memory buffer source API.
static uint32_t codec_flags(enum AVCodecID codec_id)
#define flags(name, subs,...)
#define is(width, name, range_min, range_max, subs,...)
#define u(width, name, range_min, range_max)
#define us(width, name, range_min, range_max, subs,...)
static av_always_inline void filter(int16_t *output, ptrdiff_t out_stride, const int16_t *low, ptrdiff_t low_stride, const int16_t *high, ptrdiff_t high_stride, int len, int clip)
audio channel layout utility functions
void exit_program(int ret)
Wraps exit with a program-specific cleanup routine.
void init_dynload(void)
Initialize dynamic library loading.
void print_error(const char *filename, int err)
Print an error message to stderr, indicating filename and a human readable description of the error c...
void parse_loglevel(int argc, char **argv, const OptionDef *options)
Find the '-loglevel' option in the command line args and apply it.
void show_banner(int argc, char **argv, const OptionDef *options)
Print the program banner to stderr.
int64_t parse_time_or_die(const char *context, const char *timestr, int is_duration)
Parse a string specifying a time and return its corresponding value as a number of microseconds.
void register_exit(void(*cb)(int ret))
Register a program-specific cleanup routine.
void uninit_opts(void)
Uninitialize the cmdutils option system, in particular free the *_opts contexts and their contents.
#define media_type_string
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Copy the contents of src to dst.
void avcodec_parameters_free(AVCodecParameters **ppar)
Free an AVCodecParameters instance and everything associated with it and write NULL to the supplied p...
#define FFSWAP(type, a, b)
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
#define FFDIFFSIGN(x, y)
Comparator.
static enum AVPixelFormat pix_fmt
static float sub(float src0, float src1)
#define atomic_store(object, desired)
#define atomic_load(object)
#define ATOMIC_VAR_INIT(value)
void av_expr_free(AVExpr *e)
Free a parsed expression previously created with av_expr_parse().
double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
Evaluate a previously parsed expression.
int av_expr_parse(AVExpr **expr, const char *s, const char *const *const_names, const char *const *func1_names, double(*const *funcs1)(void *, double), const char *const *func2_names, double(*const *funcs2)(void *, double, double), int log_offset, void *log_ctx)
Parse an expression.
const char program_name[]
program name, defined by the program for show_version().
static int nb_frames_drop
AVIOContext * progress_avio
static int transcode(void)
static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output, int *decode_failed)
static void set_tty_echo(int on)
static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output, int *decode_failed)
static int check_keyboard_interaction(int64_t cur_time)
static void do_audio_out(OutputFile *of, OutputStream *ost, AVFrame *frame)
static BenchmarkTimeStamps get_benchmark_time_stamps(void)
static int need_output(void)
static volatile int received_sigterm
const char *const forced_keyframes_const_names[]
static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
static void do_subtitle_out(OutputFile *of, OutputStream *ost, AVSubtitle *sub)
static int init_input_stream(int ist_index, char *error, int error_len)
static void sub2video_push_ref(InputStream *ist, int64_t pts)
int guess_input_channel_layout(InputStream *ist)
static void print_sdp(void)
static int reap_filters(int flush)
Get and encode new output from any of the filtergraphs, without causing activity.
static int check_recording_time(OutputStream *ost)
static void do_video_out(OutputFile *of, OutputStream *ost, AVFrame *next_picture)
static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
static void print_final_stats(int64_t total_size)
static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
Perform a step of transcoding for the specified filter graph.
const AVIOInterruptCB int_cb
int main(int argc, char **argv)
static double psnr(double d)
static int init_output_bsfs(OutputStream *ost)
static int init_output_stream_encode(OutputStream *ost, AVFrame *frame)
static int main_return_code
static uint8_t * subtitle_out
static int send_frame_to_filters(InputStream *ist, AVFrame *decoded_frame)
static int64_t getmaxrss(void)
static void reset_eagain(void)
static void finish_output_stream(OutputStream *ost)
static void parse_forced_key_frames(char *kf, OutputStream *ost, AVCodecContext *avctx)
static OutputStream * choose_output(void)
Select the output stream to process.
FilterGraph ** filtergraphs
static int compare_int64(const void *a, const void *b)
static unsigned dup_warning
static int init_output_stream_wrapper(OutputStream *ost, AVFrame *frame, unsigned int fatal)
static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *duration_pts, int eof, int *decode_failed)
static int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame)
static void check_decode_result(InputStream *ist, int *got_output, int ret)
static void sub2video_heartbeat(InputStream *ist, int64_t pts)
static int process_input(int file_index)
static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
static int seek_to_start(InputFile *ifile, AVFormatContext *is)
static volatile int ffmpeg_exited
static int check_output_constraints(InputStream *ist, OutputStream *ost)
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
static void set_encoder_id(OutputFile *of, OutputStream *ost)
static int64_t decode_error_stat[2]
static int read_key(void)
static int check_init_output_file(OutputFile *of, int file_index)
static void close_output_stream(OutputStream *ost)
static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
#define SIGNAL(sig, func)
void sub2video_update(InputStream *ist, int64_t heartbeat_pts, AVSubtitle *sub)
static int init_output_stream(OutputStream *ost, AVFrame *frame, char *error, int error_len)
static int got_eagain(void)
static int send_filter_eof(InputStream *ist)
static int decode_interrupt_cb(void *ctx)
static void term_exit_sigsafe(void)
static void sub2video_flush(InputStream *ist)
static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h, AVSubtitleRect *r)
void remove_avoptions(AVDictionary **a, AVDictionary *b)
static int transcode_init(void)
static volatile int received_nb_signals
InputStream ** input_streams
static int64_t copy_ts_first_pts
static FILE * vstats_file
static void report_new_stream(int input_index, AVPacket *pkt)
static BenchmarkTimeStamps current_time
static void abort_codec_experimental(const AVCodec *c, int encoder)
static void update_benchmark(const char *fmt,...)
static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base, AVRational time_base)
static void ffmpeg_cleanup(int ret)
static double adjust_frame_pts_to_encoder_tb(OutputFile *of, OutputStream *ost, AVFrame *frame)
static int transcode_step(void)
Run a single step of transcoding.
static int ifilter_has_all_input_formats(FilterGraph *fg)
static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
static int init_output_stream_streamcopy(OutputStream *ost)
static unsigned nb_output_dumped
OutputStream ** output_streams
static int get_input_packet(InputFile *f, AVPacket **pkt)
static void do_video_stats(OutputStream *ost, int frame_size)
const int program_birth_year
program birth year, defined by the program for show_banner()
static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
OutputFile ** output_files
static int sub2video_get_blank_frame(InputStream *ist)
static void flush_encoders(void)
static void output_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int eof)
static InputStream * get_input_stream(OutputStream *ost)
void assert_avoptions(AVDictionary *m)
static void init_encoder_time_base(OutputStream *ost, AVRational default_time_base)
static void ifilter_parameters_from_codecpar(InputFilter *ifilter, AVCodecParameters *par)
static int ifilter_send_eof(InputFilter *ifilter, int64_t pts)
static void sigterm_handler(int sig)
static atomic_int transcode_init_done
int hw_device_setup_for_encode(OutputStream *ost)
int ifilter_parameters_from_frame(InputFilter *ifilter, const AVFrame *frame)
int frame_bits_per_raw_sample
float dts_error_threshold
int hwaccel_decode_init(AVCodecContext *avctx)
float frame_drop_threshold
#define DECODING_FOR_FILTER
int hw_device_setup_for_decode(InputStream *ist)
void hw_device_free_all(void)
int ffmpeg_parse_options(int argc, char **argv)
#define ABORT_ON_FLAG_EMPTY_OUTPUT
float dts_delta_threshold
int filtergraph_is_simple(FilterGraph *fg)
#define VSYNC_PASSTHROUGH
int configure_filtergraph(FilterGraph *fg)
#define ABORT_ON_FLAG_EMPTY_OUTPUT_STREAM
const OptionDef options[]
static int64_t start_time
a very simple circular buffer FIFO implementation
static AVCodecContext * dec_ctx
const AVOption * av_opt_find(void *obj, const char *name, const char *unit, int opt_flags, int search_flags)
Look for an option in an object.
int av_opt_set_dict(void *obj, AVDictionary **options)
Set all the options from a given dictionary on an object.
void av_get_channel_layout_string(char *buf, int buf_size, int nb_channels, uint64_t channel_layout)
Return a description of a channel layout.
int64_t av_get_default_channel_layout(int nb_channels)
Return default channel layout for a given number of channels.
void av_bsf_free(AVBSFContext **pctx)
Free a bitstream filter context and everything associated with it; write NULL into the supplied point...
int avcodec_parameters_from_context(AVCodecParameters *par, const AVCodecContext *codec)
Fill the parameters struct based on the values from the supplied codec context.
int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
#define AV_CODEC_FLAG_BITEXACT
Use only bitexact stuff (except (I)DCT).
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
#define AV_CODEC_FLAG_PASS2
Use internal 2pass ratecontrol in second pass mode.
int av_bsf_init(AVBSFContext *ctx)
Prepare the filter for use, after all the parameters and options have been set.
#define AV_CODEC_CAP_VARIABLE_FRAME_SIZE
Audio encoder supports receiving a different number of samples in each call.
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
const AVCodecHWConfig * avcodec_get_hw_config(const AVCodec *codec, int index)
Retrieve supported hardware configurations for a codec.
#define AV_CODEC_FLAG_INTERLACED_DCT
Use interlaced DCT.
int av_bsf_receive_packet(AVBSFContext *ctx, AVPacket *pkt)
Retrieve a filtered packet.
#define AV_CODEC_FLAG_PASS1
Use internal 2pass ratecontrol in first pass mode.
#define AV_CODEC_FLAG_INTERLACED_ME
interlaced motion estimation
void avsubtitle_free(AVSubtitle *sub)
Free all allocated data in the given subtitle struct.
int av_bsf_send_packet(AVBSFContext *ctx, AVPacket *pkt)
Submit a packet for filtering.
const AVCodecDescriptor * avcodec_descriptor_get(enum AVCodecID id)
#define AV_CODEC_PROP_BITMAP_SUB
Subtitle codec is bitmap based Decoded AVSubtitle data can be read from the AVSubtitleRect->pict fiel...
#define AV_CODEC_FLAG_PSNR
error[?] variables will be set during encoding.
int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par)
Fill the codec context based on the values from the supplied codec parameters.
#define AV_CODEC_CAP_PARAM_CHANGE
Codec supports changed parameters at any point.
#define AV_CODEC_PROP_TEXT_SUB
Subtitle codec is text based.
av_cold int avcodec_close(AVCodecContext *avctx)
Close a given AVCodecContext and free all the data associated with it (but not the AVCodecContext its...
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer.
@ AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX
The codec supports this format via the hw_device_ctx interface.
@ SUBTITLE_BITMAP
A bitmap, pict will be set.
@ AV_CODEC_ID_DVB_SUBTITLE
@ AV_CODEC_ID_MP3
preferred ID for decoding MPEG audio layer 1, 2 or 3
int avcodec_default_get_buffer2(AVCodecContext *s, AVFrame *frame, int flags)
The default callback for AVCodecContext.get_buffer2().
int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
Return decoded output data from a decoder.
int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub, int *got_sub_ptr, AVPacket *avpkt)
Decode a subtitle message.
int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
Supply raw packet data as input to a decoder.
int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
Read encoded data from the encoder.
int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
Supply a raw video or audio frame to the encoder.
@ AVDISCARD_ALL
discard all
@ AVDISCARD_DEFAULT
discard useless packets like 0 size packets in avi
int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size, const AVSubtitle *sub)
int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
Return audio frame duration.
void avcodec_flush_buffers(AVCodecContext *avctx)
Reset the internal codec state / flush internal buffers.
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
#define AV_PKT_FLAG_CORRUPT
The packet content is corrupted.
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
int av_packet_make_refcounted(AVPacket *pkt)
Ensure the data described by a given packet is reference counted.
void av_packet_move_ref(AVPacket *dst, AVPacket *src)
Move every field in src to dst and reset src.
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
int av_packet_ref(AVPacket *dst, const AVPacket *src)
Setup a new reference to the data described by a given packet.
void av_packet_rescale_ts(AVPacket *pkt, AVRational src_tb, AVRational dst_tb)
Convert valid timing fields (timestamps / durations) in a packet from one timebase to another.
@ AV_PKT_DATA_QUALITY_STATS
This side data contains quality related information from the encoder.
@ AV_PKT_DATA_DISPLAYMATRIX
This side data contains a 3x3 transformation matrix describing an affine transformation that needs to...
@ AV_PKT_DATA_CPB_PROPERTIES
This side data corresponds to the AVCPBProperties struct.
void avdevice_register_all(void)
Initialize libavdevice and register all the input and output devices.
uint8_t * av_stream_new_side_data(AVStream *stream, enum AVPacketSideDataType type, size_t size)
Allocate new information from stream.
int avformat_network_deinit(void)
Undo the initialization done by avformat_network_init.
int avformat_network_init(void)
Do global initialization of network libraries.
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Seek to timestamp ts.
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
av_warn_unused_result int avformat_write_header(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and write the stream header to an output media file.
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file ensuring correct interleaving.
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
enum AVCodecID av_codec_get_id(const struct AVCodecTag *const *tags, unsigned int tag)
Get the AVCodecID for the given codec tag tag.
AVRational av_stream_get_codec_timebase(const AVStream *st)
Get the internal codec timebase from a stream.
int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size)
Generate an SDP for an RTP session.
void av_pkt_dump_log2(void *avcl, int level, const AVPacket *pkt, int dump_payload, const AVStream *st)
Send a nice dump of a packet to the log.
int av_codec_get_tag2(const struct AVCodecTag *const *tags, enum AVCodecID id, unsigned int *tag)
Get the codec tag for the given codec id.
void av_dump_format(AVFormatContext *ic, int index, const char *url, int is_output)
Print detailed information about the input or output format, such as duration, bitrate,...
int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt, AVStream *ost, const AVStream *ist, enum AVTimebaseSource copy_tb)
Transfer internal timing information from one stream to another.
enum AVMediaType av_buffersink_get_type(const AVFilterContext *ctx)
int av_buffersink_get_sample_rate(const AVFilterContext *ctx)
int av_buffersink_get_format(const AVFilterContext *ctx)
AVRational av_buffersink_get_frame_rate(const AVFilterContext *ctx)
uint64_t av_buffersink_get_channel_layout(const AVFilterContext *ctx)
int av_buffersink_get_h(const AVFilterContext *ctx)
AVRational av_buffersink_get_sample_aspect_ratio(const AVFilterContext *ctx)
AVRational av_buffersink_get_time_base(const AVFilterContext *ctx)
int av_buffersink_get_w(const AVFilterContext *ctx)
int av_buffersink_get_channels(const AVFilterContext *ctx)
void av_buffersink_set_frame_size(AVFilterContext *ctx, unsigned frame_size)
Set the frame size for an audio buffer sink.
int attribute_align_arg av_buffersink_get_frame_flags(AVFilterContext *ctx, AVFrame *frame, int flags)
Get a frame with filtered data from sink and put it in frame.
#define AV_BUFFERSINK_FLAG_NO_REQUEST
Tell av_buffersink_get_buffer_ref() not to request a frame from its input.
int attribute_align_arg av_buffersrc_add_frame_flags(AVFilterContext *ctx, AVFrame *frame, int flags)
Add a frame to the buffer source.
int av_buffersrc_close(AVFilterContext *ctx, int64_t pts, unsigned flags)
Close the buffer source after EOF.
int attribute_align_arg av_buffersrc_add_frame(AVFilterContext *ctx, AVFrame *frame)
Add a frame to the buffer source.
unsigned av_buffersrc_get_nb_failed_requests(AVFilterContext *buffer_src)
Get the number of failed requests.
@ AV_BUFFERSRC_FLAG_KEEP_REF
Keep a reference to the frame.
@ AV_BUFFERSRC_FLAG_PUSH
Immediately push the frame to the output.
void avfilter_inout_free(AVFilterInOut **inout)
Free the supplied list of AVFilterInOut and set *inout to NULL.
int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, int flags, double ts)
Queue a command for one or more filter instances.
void avfilter_graph_free(AVFilterGraph **graph)
Free a graph, destroy its links, and set *graph to NULL.
int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
Send a command to one or more filter instances.
int avfilter_graph_request_oldest(AVFilterGraph *graph)
Request a frame on the oldest sink link.
#define AVFILTER_CMD_FLAG_ONE
Stop once a filter understood the command (for target=all for example), fast filters are favored auto...
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
AVBufferRef * av_buffer_ref(AVBufferRef *buf)
Create a new reference to an AVBuffer.
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key,...
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
#define AV_DICT_DONT_OVERWRITE
Don't overwrite existing entries.
#define AV_DICT_MATCH_CASE
Only get an entry with exact-case key match.
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
#define AVERROR_EXPERIMENTAL
Requested feature is flagged experimental. Set strict_std_compliance if you really want to use it.
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
#define AVERROR_EOF
End of file.
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
#define AV_FRAME_FLAG_CORRUPT
The frame data may be corrupted, e.g.
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
void av_frame_remove_side_data(AVFrame *frame, enum AVFrameSideDataType type)
Remove and free all side data instances of the given type.
AVFrame * av_frame_clone(const AVFrame *src)
Create a new frame that references the same data as src.
int av_frame_get_buffer(AVFrame *frame, int align)
Allocate new buffer(s) for audio or video data.
int av_frame_ref(AVFrame *dst, const AVFrame *src)
Set up a new reference to the data described by the source frame.
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
@ AV_FRAME_DATA_A53_CC
ATSC A53 Part 4 Closed Captions.
#define AV_LOG_QUIET
Print no output.
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
#define AV_LOG_WARNING
Something somehow does not look correct.
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
#define AV_LOG_VERBOSE
Detailed information.
#define AV_LOG_INFO
Standard information.
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
void av_log_set_callback(void(*callback)(void *, int, const char *, va_list))
Set the logging callback.
void av_log_set_level(int level)
Set the log level.
#define AV_LOG_SKIP_REPEATED
Skip repeated messages, this requires the user app to use av_log() instead of (f)printf as the 2 woul...
const char * av_default_item_name(void *ptr)
Return the context name.
int av_log_get_level(void)
Get the current log level.
void av_log_set_flags(int arg)
AVRational av_add_q(AVRational b, AVRational c)
Add two rationals.
AVRational av_mul_q(AVRational b, AVRational c)
Multiply two rationals.
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
int av_find_nearest_q_idx(AVRational q, const AVRational *q_list)
Find the value in a list of rationals nearest a given reference rational.
static AVRational av_make_q(int num, int den)
Create an AVRational.
static double av_q2d(AVRational a)
Convert an AVRational to a double.
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b)
Compare two timestamps each in its own time base.
int64_t av_rescale_delta(AVRational in_tb, int64_t in_ts, AVRational fs_tb, int duration, int64_t *last, AVRational out_tb)
Rescale a timestamp while preserving known durations.
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
int64_t av_rescale_q_rnd(int64_t a, AVRational bq, AVRational cq, enum AVRounding rnd)
Rescale a 64-bit integer by 2 rational numbers with specified rounding.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
@ AV_ROUND_PASS_MINMAX
Flag telling rescaling functions to pass INT64_MIN/MAX through unchanged, avoiding special cases for ...
@ AV_ROUND_NEAR_INF
Round to nearest and halfway cases away from zero.
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Allocate, reallocate, or free an array.
const char * av_get_media_type_string(enum AVMediaType media_type)
Return a string describing the media_type enum, NULL if media_type is unknown.
@ AVMEDIA_TYPE_DATA
Opaque data information usually continuous.
char av_get_picture_type_char(enum AVPictureType pict_type)
Return a single letter to describe the given picture type pict_type.
@ AV_PICTURE_TYPE_I
Intra.
@ AV_PICTURE_TYPE_NONE
Undefined.
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes,...
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
#define AV_NOPTS_VALUE
Undefined timestamp value.
#define AV_TIME_BASE
Internal time base represented as integer.
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
#define LIBAVUTIL_VERSION_INT
void av_display_rotation_set(int32_t matrix[9], double angle)
Initialize a transformation matrix describing a pure counterclockwise rotation by the specified angle...
int av_opt_eval_flags(void *obj, const AVOption *o, const char *val, int *flags_out)
const char * av_hwdevice_get_type_name(enum AVHWDeviceType type)
Get the string name of an AVHWDeviceType.
void av_fifo_freep(AVFifoBuffer **f)
Free an AVFifoBuffer and reset pointer to NULL.
int av_fifo_size(const AVFifoBuffer *f)
Return the amount of data in bytes in the AVFifoBuffer, that is the amount of data you can read from ...
int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void(*func)(void *, void *, int))
Feed data from an AVFifoBuffer to a user-supplied callback.
int av_fifo_space(const AVFifoBuffer *f)
Return the amount of space in bytes in the AVFifoBuffer, that is the amount of data you can write int...
AVFifoBuffer * av_fifo_alloc(unsigned int size)
Initialize an AVFifoBuffer.
int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int(*func)(void *, void *, int))
Feed data from a user-supplied callback to an AVFifoBuffer.
int av_fifo_realloc2(AVFifoBuffer *f, unsigned int new_size)
Resize an AVFifoBuffer.
common internal API header
static enum AVPixelFormat pix_fmts[]
Replacements for frequently missing libm functions.
static av_always_inline int pthread_join(pthread_t thread, void **value_ptr)
static av_always_inline int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
miscellaneous OS support macros and functions.
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
#define AV_PIX_FMT_FLAG_HWACCEL
Pixel format is an HW accelerated format.
AVPixelFormat
Pixel format.
#define FF_ARRAY_ELEMS(a)
The bitstream filter state.
uint8_t * data
The data buffer.
Describe the class of an AVClass context structure.
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
main external API structure.
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
int width
picture width / height.
char * stats_out
pass1 encoding statistics output buffer
enum AVSampleFormat sample_fmt
audio sample format
int global_quality
Global quality for codecs which cannot change it per frame.
enum AVColorRange color_range
MPEG vs JPEG YUV range.
AVRational pkt_timebase
Timebase in which pkt_dts/pts and AVPacket.dts/pts are.
enum AVPixelFormat(* get_format)(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
callback to negotiate the pixelFormat
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
enum AVMediaType codec_type
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
enum AVFieldOrder field_order
Field order.
int has_b_frames
Size of the frame reordering buffer in the decoder.
const struct AVCodec * codec
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
enum AVColorSpace colorspace
YUV colorspace type.
int sample_rate
samples per second
attribute_deprecated int thread_safe_callbacks
Set by the client if its custom get_buffer() callback can be called synchronously from another thread...
void * opaque
Private data of the user, can be used to carry app specific stuff.
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
int flags
AV_CODEC_FLAG_*.
int channels
number of audio channels
enum AVChromaLocation chroma_sample_location
This defines the location of chroma samples.
uint64_t error[AV_NUM_DATA_POINTERS]
error
uint64_t channel_layout
Audio channel layout.
int frame_size
Number of samples per channel in an audio frame.
int(* get_buffer2)(struct AVCodecContext *s, AVFrame *frame, int flags)
This callback is called at the beginning of each frame to get data buffer(s) for it.
This struct describes the properties of a single codec described by an AVCodecID.
int props
Codec properties, a combination of AV_CODEC_PROP_* flags.
enum AVHWDeviceType device_type
The device type associated with the configuration.
int methods
Bit set of AV_CODEC_HW_CONFIG_METHOD_* flags, describing the possible setup methods which can be used...
enum AVPixelFormat pix_fmt
For decoders, a hardware pixel format which that decoder may be able to decode to if suitable hardwar...
This struct describes the properties of an encoded stream.
uint64_t channel_layout
Audio only.
enum AVMediaType codec_type
General type of the encoded data.
int block_align
Audio only.
AVRational sample_aspect_ratio
Video only.
int video_delay
Video only.
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
int sample_rate
Audio only.
int repeat_pict
This field is used for proper frame duration computation in lavf.
const AVCodecDefault * defaults
Private codec-specific defaults.
const char * name
Name of the codec implementation.
int capabilities
Codec capabilities.
int depth
Number of bits in the component.
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
AVIOContext * pb
I/O context.
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
char * url
input or output URL.
unsigned int nb_chapters
Number of chapters in AVChapter array.
ff_const59 struct AVOutputFormat * oformat
The output container format.
AVStream ** streams
A list of all streams in the file.
This structure describes decoded (raw) audio or video data.
int nb_samples
number of audio samples (per channel) described by this frame
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
int64_t best_effort_timestamp
frame timestamp estimated using various heuristics, in stream time base
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
enum AVChromaLocation chroma_location
AVBufferRef * hw_frames_ctx
For hwaccel-format frames, this should be a reference to the AVHWFramesContext describing the frame.
int key_frame
1 -> keyframe, 0-> not
int64_t pkt_duration
duration of the corresponding packet, expressed in AVStream->time_base units, 0 if unknown.
int decode_error_flags
decode error flags of the frame, set to a combination of FF_DECODE_ERROR_xxx flags if the decoder pro...
int flags
Frame flags, a combination of AV_FRAME_FLAGS.
int channels
number of audio channels, only used for audio.
enum AVColorPrimaries color_primaries
uint64_t channel_layout
Channel layout of the audio data.
AVRational sample_aspect_ratio
Sample aspect ratio for the video frame, 0/1 if unknown/unspecified.
int top_field_first
If the content is interlaced, is top field displayed first.
int quality
quality (between 1 (good) and FF_LAMBDA_MAX (bad))
int interlaced_frame
The content of the picture is interlaced.
enum AVColorRange color_range
MPEG vs JPEG YUV range.
enum AVColorSpace colorspace
YUV colorspace type.
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
enum AVColorTransferCharacteristic color_trc
int sample_rate
Sample rate of the audio data.
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames,...
enum AVPictureType pict_type
Picture type of the frame.
Callback for checking whether to abort blocking functions.
enum AVPacketSideDataType type
This structure stores compressed data.
int flags
A combination of AV_PKT_FLAG values.
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
int64_t pos
byte position in stream, -1 if unknown
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
AVComponentDescriptor comp[4]
Parameters that describe how pixels are packed.
New fields can be added to the end with minor version bumps.
unsigned int nb_stream_indexes
unsigned int * stream_index
enum AVDiscard discard
selects which program to discard and which to feed to the caller
Rational number (pair of numerator and denominator).
AVPacketSideData * side_data
An array of side data that applies to the whole stream (i.e.
AVCodecParameters * codecpar
Codec parameters associated with this stream.
int64_t first_dts
Timestamp corresponding to the last dts sync point.
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
int64_t nb_frames
number of frames in this stream if known or 0
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
int64_t duration
Decoding: duration of the stream, in stream time base.
int id
Format-specific stream ID.
int index
stream index in AVFormatContext
int pts_wrap_bits
number of bits in pts (used for wrapping control)
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base.
AVRational avg_frame_rate
Average framerate.
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
int nb_side_data
The number of elements in the AVStream.side_data array.
AVRational r_frame_rate
Real base framerate of the stream.
int disposition
AV_DISPOSITION_* bit field.
uint32_t end_display_time
int64_t pts
Same as packet pts, in AV_TIME_BASE.
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
libswresample public header
#define av_malloc_array(a, b)
#define av_realloc_f(p, o, n)
static void error(const char *err)
void av_thread_message_queue_set_err_send(AVThreadMessageQueue *mq, int err)
Set the sending error code.
int av_thread_message_queue_recv(AVThreadMessageQueue *mq, void *msg, unsigned flags)
Receive a message from the queue.
int av_thread_message_queue_alloc(AVThreadMessageQueue **mq, unsigned nelem, unsigned elsize)
Allocate a new message queue.
void av_thread_message_queue_set_err_recv(AVThreadMessageQueue *mq, int err)
Set the receiving error code.
int av_thread_message_queue_send(AVThreadMessageQueue *mq, void *msg, unsigned flags)
Send a message on the queue.
void av_thread_message_queue_free(AVThreadMessageQueue **mq)
Free a message queue.
@ AV_THREAD_MESSAGE_NONBLOCK
Perform non-blocking operation.
int av_usleep(unsigned usec)
Sleep for a period of time.
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
timestamp utils, mostly useful for debugging/logging purposes
#define av_ts2str(ts)
Convenience macro, the return value should be used only directly in function arguments but never stan...
#define av_ts2timestr(ts, tb)
Convenience macro, the return value should be used only directly in function arguments but never stan...
static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)