Go to the documentation of this file.
30 #include <stdatomic.h>
43 #if HAVE_SYS_RESOURCE_H
45 #include <sys/types.h>
46 #include <sys/resource.h>
47 #elif HAVE_GETPROCESSTIMES
50 #if HAVE_GETPROCESSMEMORYINFO
54 #if HAVE_SETCONSOLECTRLHANDLER
59 #include <sys/select.h>
64 #include <sys/ioctl.h>
135 static struct termios oldtty;
136 static int restore_tty;
167 tcsetattr (0, TCSANOW, &oldtty);
191 ret = write(2,
"Received > 3 system signals, hard exiting\n",
192 strlen(
"Received > 3 system signals, hard exiting\n"));
198 #if HAVE_SETCONSOLECTRLHANDLER
199 static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
206 case CTRL_BREAK_EVENT:
210 case CTRL_CLOSE_EVENT:
211 case CTRL_LOGOFF_EVENT:
212 case CTRL_SHUTDOWN_EVENT:
231 #define SIGNAL(sig, func) \
233 action.sa_handler = func; \
234 sigaction(sig, &action, NULL); \
237 #define SIGNAL(sig, func) \
243 #if defined __linux__
244 struct sigaction action = {0};
248 sigfillset(&action.sa_mask);
251 action.sa_flags = SA_RESTART;
257 if (tcgetattr (0, &tty) == 0) {
261 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
262 |INLCR|IGNCR|ICRNL|IXON);
263 tty.c_oflag |= OPOST;
264 tty.c_lflag &= ~(
ECHO|ECHONL|ICANON|IEXTEN);
265 tty.c_cflag &= ~(CSIZE|PARENB);
270 tcsetattr (0, TCSANOW, &tty);
282 signal(SIGPIPE, SIG_IGN);
284 #if HAVE_SETCONSOLECTRLHANDLER
285 SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
302 n = select(1, &rfds,
NULL,
NULL, &tv);
311 # if HAVE_PEEKNAMEDPIPE && HAVE_GETSTDHANDLE
313 static HANDLE input_handle;
316 input_handle = GetStdHandle(STD_INPUT_HANDLE);
317 is_pipe = !GetConsoleMode(input_handle, &dw);
322 if (!PeekNamedPipe(input_handle,
NULL, 0,
NULL, &nchars,
NULL)) {
370 "Error closing vstats file, loss of information possible: %s\n",
400 int ost_idx = prev ? prev->
index + 1 : 0;
416 int ist_idx = prev ? prev->
index + 1 : 0;
421 return f->streams[ist_idx];
478 "bench: %8" PRIu64
" user %8" PRIu64
" sys %8" PRIu64
" real %s \n",
492 if (
ost->sq_idx_encode >= 0)
496 static void print_report(
int is_last_report, int64_t timer_start, int64_t cur_time)
498 AVBPrint buf, buf_script;
504 static int64_t last_time = -1;
505 static int first_report = 1;
506 uint64_t nb_frames_dup = 0, nb_frames_drop = 0;
509 const char *hours_sign;
516 if (!is_last_report) {
517 if (last_time == -1) {
518 last_time = cur_time;
520 if (((cur_time - last_time) <
stats_period && !first_report) ||
523 last_time = cur_time;
526 t = (cur_time-timer_start) / 1000000.0;
536 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
543 fps = t > 1 ? frame_number / t : 0;
544 av_bprintf(&buf,
"frame=%5"PRId64
" fps=%3.*f q=%3.1f ",
545 frame_number, fps < 9.95, fps, q);
546 av_bprintf(&buf_script,
"frame=%"PRId64
"\n", frame_number);
548 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
553 nb_frames_dup =
ost->filter->nb_frames_dup;
554 nb_frames_drop =
ost->filter->nb_frames_drop;
575 hours_sign = (
pts < 0) ?
"-" :
"";
580 if (total_size < 0)
av_bprintf(&buf,
"size=N/A time=");
581 else av_bprintf(&buf,
"size=%8.0fkB time=", total_size / 1024.0);
585 av_bprintf(&buf,
"%s%02"PRId64
":%02d:%02d.%02d ",
597 if (total_size < 0)
av_bprintf(&buf_script,
"total_size=N/A\n");
598 else av_bprintf(&buf_script,
"total_size=%"PRId64
"\n", total_size);
606 av_bprintf(&buf_script,
"out_time=%s%02"PRId64
":%02d:%02d.%06d\n",
607 hours_sign, hours, mins, secs,
us);
610 if (nb_frames_dup || nb_frames_drop)
611 av_bprintf(&buf,
" dup=%"PRId64
" drop=%"PRId64, nb_frames_dup, nb_frames_drop);
612 av_bprintf(&buf_script,
"dup_frames=%"PRId64
"\n", nb_frames_dup);
613 av_bprintf(&buf_script,
"drop_frames=%"PRId64
"\n", nb_frames_drop);
620 av_bprintf(&buf_script,
"speed=%4.3gx\n", speed);
624 const char end = is_last_report ?
'\n' :
'\r';
626 fprintf(stderr,
"%s %c", buf.str, end);
636 is_last_report ?
"end" :
"continue");
638 FFMIN(buf_script.len, buf_script.size - 1));
641 if (is_last_report) {
644 "Error closing progress log, loss of information possible: %s\n",
av_err2str(
ret));
655 .format =
src->format,
656 .start_display_time =
src->start_display_time,
657 .end_display_time =
src->end_display_time,
669 for (
int i = 0;
i <
src->num_rects;
i++) {
683 dst_rect->
x = src_rect->
x;
684 dst_rect->
y = src_rect->
y;
685 dst_rect->
w = src_rect->
w;
686 dst_rect->
h = src_rect->
h;
701 for (
int j = 0; j < 4; j++) {
709 if (!src_rect->
data[j])
752 sub =
av_memdup(subtitle,
sizeof(*subtitle));
755 memset(subtitle, 0,
sizeof(*subtitle));
823 if (
f->recording_time != INT64_MAX) {
833 for (
int oidx = 0; oidx < ist->
nb_outputs; oidx++) {
835 if (
ost->enc || (!
pkt && no_eof))
850 for (
int j = 0; j < ist->nb_filters; j++) {
853 ist->file_index, ist->index, ist->dec ? ist->dec->name :
"?",
854 ist->filters[j]->name);
863 if (
ost->attachment_filename) {
882 ost->ist->file_index,
888 const AVCodec *out_codec =
ost->enc_ctx->codec;
889 const char *decoder_name =
"?";
890 const char *in_codec_name =
"?";
891 const char *encoder_name =
"?";
892 const char *out_codec_name =
"?";
896 decoder_name = in_codec->
name;
899 in_codec_name =
desc->name;
900 if (!strcmp(decoder_name, in_codec_name))
901 decoder_name =
"native";
905 encoder_name = out_codec->
name;
908 out_codec_name =
desc->name;
909 if (!strcmp(encoder_name, out_codec_name))
910 encoder_name =
"native";
914 in_codec_name, decoder_name,
915 out_codec_name, encoder_name);
931 int64_t opts_min = INT64_MAX;
941 INT64_MIN :
ost->last_mux_dts;
944 if (!
ost->initialized && !
ost->finished) {
948 if (!
ost->finished &&
opts < opts_min) {
963 if (tcgetattr(0, &tty) == 0) {
964 if (
on) tty.c_lflag |=
ECHO;
965 else tty.c_lflag &= ~
ECHO;
966 tcsetattr(0, TCSANOW, &tty);
974 static int64_t last_time;
978 if (cur_time - last_time >= 100000) {
980 last_time = cur_time;
989 if (
key ==
'c' ||
key ==
'C'){
990 char buf[4096], target[64], command[256],
arg[256] = {0};
993 fprintf(stderr,
"\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
996 while ((k =
read_key()) !=
'\n' && k !=
'\r' &&
i <
sizeof(buf)-1)
1001 fprintf(stderr,
"\n");
1003 (n = sscanf(buf,
"%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command,
arg)) >= 3) {
1005 target, time, command,
arg);
1011 "Parse error, at least 3 arguments were expected, "
1012 "only %d given in string '%s'\n", n, buf);
1016 fprintf(stderr,
"key function\n"
1017 "? show this help\n"
1018 "+ increase verbosity\n"
1019 "- decrease verbosity\n"
1020 "c Send command to first matching filter supporting it\n"
1021 "C Send/Queue command to all matching filters\n"
1022 "h dump packets/hex press to cycle through the 3 states\n"
1024 "s Show QP histogram\n"
1036 ost->unavailable = 0;
1079 "Error retrieving a packet from demuxer: %s\n",
av_err2str(
ret));
1095 for (
int oidx = 0; oidx < ist->
nb_outputs; oidx++) {
1119 return ret < 0 ?
ret : 0;
1145 ost->unavailable = 1;
1170 int64_t timer_start;
1174 *err_rate_exceeded = 0;
1198 }
else if (
ret < 0) {
1228 *err_rate_exceeded = 1;
1229 }
else if (err_rate)
1252 struct rusage rusage;
1254 getrusage(RUSAGE_SELF, &rusage);
1256 (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
1258 (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
1259 #elif HAVE_GETPROCESSTIMES
1261 FILETIME
c, e, k,
u;
1262 proc = GetCurrentProcess();
1263 GetProcessTimes(proc, &
c, &e, &k, &
u);
1265 ((int64_t)
u.dwHighDateTime << 32 |
u.dwLowDateTime) / 10;
1267 ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
1276 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
1277 struct rusage rusage;
1278 getrusage(RUSAGE_SELF, &rusage);
1279 return (int64_t)rusage.ru_maxrss * 1024;
1280 #elif HAVE_GETPROCESSMEMORYINFO
1282 PROCESS_MEMORY_COUNTERS memcounters;
1283 proc = GetCurrentProcess();
1284 memcounters.cb =
sizeof(memcounters);
1285 GetProcessMemoryInfo(proc, &memcounters,
sizeof(memcounters));
1286 return memcounters.PeakPagefileUsage;
1294 int ret, err_rate_exceeded;
1299 setvbuf(stderr,
NULL,_IONBF,0);
1332 int64_t utime, stime, rtime;
1338 "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
1339 utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
1343 err_rate_exceeded ? 69 :
ret;
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
#define AV_LOG_WARNING
Something somehow does not look correct.
int of_streamcopy(OutputStream *ost, const AVPacket *pkt, int64_t dts)
#define atomic_store(object, desired)
static void reset_eagain(void)
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
static volatile int ffmpeg_exited
void close_output_stream(OutputStream *ost)
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
#define u(width, name, range_min, range_max)
#define AV_LOG_QUIET
Print no output.
int reap_filters(FilterGraph *fg, int flush)
Get and encode new output from specified filtergraph, without causing activity.
#define AVERROR_EOF
End of file.
uint8_t * data
The data buffer.
void fg_free(FilterGraph **pfg)
void remove_avoptions(AVDictionary **a, AVDictionary *b)
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
InputStream * ist_iter(InputStream *prev)
int ffmpeg_parse_options(int argc, char **argv)
This structure describes decoded (raw) audio or video data.
static av_cold void cleanup(FlashSV2Context *s)
int64_t of_filesize(OutputFile *of)
static BenchmarkTimeStamps current_time
#define ATOMIC_VAR_INIT(value)
unsigned nb_output_dumped
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key,...
#define AV_LOG_VERBOSE
Detailed information.
AVIOContext * progress_avio
const int program_birth_year
program birth year, defined by the program for show_banner()
AVBufferRef * buf[AV_NUM_DATA_POINTERS]
AVBuffer references backing the data for this frame.
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
static void term_exit_sigsafe(void)
#define ECHO(name, type, min, max)
Callback for checking whether to abort blocking functions.
void * av_memdup(const void *p, size_t size)
Duplicate a buffer with av_malloc().
AVBufferRef * opaque_ref
Frame owner's private data.
AVBufferRef * opaque_ref
AVBufferRef for free use by the API user.
int x
top left corner of pict, undefined when pict is not set
#define AVERROR_OPTION_NOT_FOUND
Option not found.
#define AV_BPRINT_SIZE_AUTOMATIC
void update_benchmark(const char *fmt,...)
#define us(width, name, range_min, range_max, subs,...)
int trigger_fix_sub_duration_heartbeat(OutputStream *ost, const AVPacket *pkt)
void fg_send_command(FilterGraph *fg, double time, const char *target, const char *command, const char *arg, int all_filters)
int avformat_network_init(void)
Do global initialization of network libraries.
char * ass
0 terminated ASS/SSA compatible event line.
void avsubtitle_free(AVSubtitle *sub)
Free all allocated data in the given subtitle struct.
static void ffmpeg_cleanup(int ret)
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
static void decode_flush(InputFile *ifile)
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
int fg_transcode_step(FilterGraph *graph, InputStream **best_ist)
Perform a step of transcoding for the specified filter graph.
void of_free(OutputFile **pof)
This struct describes the properties of a single codec described by an AVCodecID.
static BenchmarkTimeStamps get_benchmark_time_stamps(void)
static int64_t copy_ts_first_pts
void ifilter_sub2video_heartbeat(InputFilter *ifilter, int64_t pts, AVRational tb)
int y
top left corner of pict, undefined when pict is not set
int subtitle_wrap_frame(AVFrame *frame, AVSubtitle *subtitle, int copy)
#define av_assert0(cond)
assert() equivalent, that is always enabled.
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
s EdgeDetect Foobar g libavfilter vf_edgedetect c libavfilter vf_foobar c edit libavfilter and add an entry for foobar following the pattern of the other filters edit libavfilter allfilters and add an entry for foobar following the pattern of the other filters configure make j< whatever > ffmpeg ffmpeg i you should get a foobar png with Lena edge detected That s your new playground is ready Some little details about what s going on
int av_usleep(unsigned usec)
Sleep for a period of time.
#define atomic_load(object)
char * text
0 terminated plain UTF-8 text
static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
static int process_input(int file_index)
static int transcode(int *err_rate_exceeded)
void of_enc_stats_close(void)
void avio_flush(AVIOContext *s)
Force flushing of buffered data.
int av_log_get_level(void)
Get the current log level.
void init_dynload(void)
Initialize dynamic library loading.
int w
width of pict, undefined when pict is not set
int main(int argc, char **argv)
Rational number (pair of numerator and denominator).
static int64_t getmaxrss(void)
static int check_keyboard_interaction(int64_t cur_time)
void av_log_set_flags(int arg)
uint8_t * data[4]
data+linesize for the bitmap of this subtitle.
static int transcode_step(OutputStream *ost)
Run a single step of transcoding.
static void print_stream_maps(void)
int ifile_get_packet(InputFile *f, AVPacket **pkt)
Get next input packet from the demuxer.
OutputStream * ost_iter(OutputStream *prev)
static void sub2video_heartbeat(InputFile *infile, int64_t pts, AVRational tb)
static volatile int received_nb_signals
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
AVBufferRef * av_buffer_create(uint8_t *data, size_t size, void(*free)(void *opaque, uint8_t *data), void *opaque, int flags)
Create an AVBuffer from an existing array.
static void subtitle_free(void *opaque, uint8_t *data)
static int decode_interrupt_cb(void *ctx)
const OptionDef options[]
static void copy(const float *p1, float *p2, const int length)
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
OutputFile ** output_files
#define SIGNAL(sig, func)
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
int copy_av_subtitle(AVSubtitle *dst, const AVSubtitle *src)
static volatile int received_sigterm
static int64_t start_time
int filtergraph_is_simple(const FilterGraph *fg)
int sq_send(SyncQueue *sq, unsigned int stream_idx, SyncQueueFrame frame)
Submit a frame for the stream with index stream_idx.
void uninit_opts(void)
Uninitialize the cmdutils option system, in particular free the *_opts contexts and their contents.
#define AV_NOPTS_VALUE
Undefined timestamp value.
int check_avoptions(AVDictionary *m)
FrameData * frame_data(AVFrame *frame)
Get our axiliary frame data attached to the frame, allocating it if needed.
void show_banner(int argc, char **argv, const OptionDef *options)
Print the program banner to stderr.
int fix_sub_duration_heartbeat(InputStream *ist, int64_t signal_pts)
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
The reader does not expect b to be semantically here and if the code is changed by maybe adding a a division or other the signedness will almost certainly be mistaken To avoid this confusion a new type was SUINT is the C unsigned type but it holds a signed int to use the same example SUINT a
int flags
A combination of AV_PKT_FLAG values.
@ SUBTITLE_BITMAP
A bitmap, pict will be set.
#define AV_LOG_INFO
Standard information.
int avio_closep(AVIOContext **s)
Close the resource accessed by the AVIOContext *s, free it and set the pointer pointing to it to NULL...
int of_output_packet(OutputFile *of, OutputStream *ost, AVPacket *pkt)
void av_log_set_level(int level)
Set the log level.
#define i(width, name, range_min, range_max)
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
int nb_colors
number of colors in pict, undefined when pict is not set
#define AV_TIME_BASE
Internal time base represented as integer.
static void sigterm_handler(int sig)
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
const char * name
Name of the codec implementation.
FilterGraph ** filtergraphs
const AVIOInterruptCB int_cb
void * av_calloc(size_t nmemb, size_t size)
void parse_loglevel(int argc, char **argv, const OptionDef *options)
Find the '-loglevel' option in the command line args and apply it.
AVBufferRef * av_buffer_allocz(size_t size)
Same as av_buffer_alloc(), except the returned buffer will be initialized to zero.
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
int h
height of pict, undefined when pict is not set
int dec_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
Submit a packet for decoding.
void hw_device_free_all(void)
void av_bprintf(AVBPrint *buf, const char *fmt,...)
#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...
#define AV_DICT_MATCH_CASE
Only get an entry with exact-case key match.
void ifile_close(InputFile **f)
int avformat_network_deinit(void)
Undo the initialization done by avformat_network_init.
int index
stream index in AVFormatContext
static atomic_int transcode_init_done
const char program_name[]
program name, defined by the program for show_version().
static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
enum AVMediaType codec_type
char * av_strdup(const char *s)
Duplicate a string.
A reference to a data buffer.
This structure stores compressed data.
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 AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
static int err_merge(int err0, int err1)
Merge two return codes - return one of the error codes if at least one of them was negative,...
const AVCodecDescriptor * avcodec_descriptor_get(enum AVCodecID id)
static void set_tty_echo(int on)
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
static int read_key(void)
int of_write_trailer(OutputFile *of)
static int choose_output(OutputStream **post)
Select the output stream to process.
const AVDictionaryEntry * av_dict_iterate(const AVDictionary *m, const AVDictionaryEntry *prev)
Iterate over a dictionary.
static uint32_t BS_FUNC() read(BSCTX *bc, unsigned int n)
Return n bits from the buffer, n has to be in the 0-32 range.
AVRational time_base
Time base of the packet's timestamps.
void avdevice_register_all(void)
Initialize libavdevice and register all the input and output devices.