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>
136 static struct termios oldtty;
137 static int restore_tty;
168 tcsetattr (0, TCSANOW, &oldtty);
192 ret = write(2,
"Received > 3 system signals, hard exiting\n",
193 strlen(
"Received > 3 system signals, hard exiting\n"));
199 #if HAVE_SETCONSOLECTRLHANDLER
200 static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
207 case CTRL_BREAK_EVENT:
211 case CTRL_CLOSE_EVENT:
212 case CTRL_LOGOFF_EVENT:
213 case CTRL_SHUTDOWN_EVENT:
232 #define SIGNAL(sig, func) \
234 action.sa_handler = func; \
235 sigaction(sig, &action, NULL); \
238 #define SIGNAL(sig, func) \
244 #if defined __linux__
245 struct sigaction action = {0};
249 sigfillset(&action.sa_mask);
252 action.sa_flags = SA_RESTART;
258 if (tcgetattr (0, &tty) == 0) {
262 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
263 |INLCR|IGNCR|ICRNL|IXON);
264 tty.c_oflag |= OPOST;
265 tty.c_lflag &= ~(
ECHO|ECHONL|ICANON|IEXTEN);
266 tty.c_cflag &= ~(CSIZE|PARENB);
271 tcsetattr (0, TCSANOW, &tty);
283 signal(SIGPIPE, SIG_IGN);
285 #if HAVE_SETCONSOLECTRLHANDLER
286 SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
303 n = select(1, &rfds,
NULL,
NULL, &tv);
312 # if HAVE_PEEKNAMEDPIPE && HAVE_GETSTDHANDLE
314 static HANDLE input_handle;
317 input_handle = GetStdHandle(STD_INPUT_HANDLE);
318 is_pipe = !GetConsoleMode(input_handle, &dw);
323 if (!PeekNamedPipe(input_handle,
NULL, 0,
NULL, &nchars,
NULL)) {
371 "Error closing vstats file, loss of information possible: %s\n",
401 int ost_idx = prev ? prev->
index + 1 : 0;
417 int ist_idx = prev ? prev->
index + 1 : 0;
422 return f->streams[ist_idx];
492 "bench: %8" PRIu64
" user %8" PRIu64
" sys %8" PRIu64
" real %s \n",
506 if (
ost->sq_idx_encode >= 0)
510 static void print_report(
int is_last_report, int64_t timer_start, int64_t cur_time)
512 AVBPrint buf, buf_script;
518 static int64_t last_time = -1;
519 static int first_report = 1;
520 uint64_t nb_frames_dup = 0, nb_frames_drop = 0;
523 const char *hours_sign;
530 if (!is_last_report) {
531 if (last_time == -1) {
532 last_time = cur_time;
534 if (((cur_time - last_time) <
stats_period && !first_report) ||
537 last_time = cur_time;
540 t = (cur_time-timer_start) / 1000000.0;
550 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
557 fps = t > 1 ? frame_number / t : 0;
558 av_bprintf(&buf,
"frame=%5"PRId64
" fps=%3.*f q=%3.1f ",
559 frame_number, fps < 9.95, fps, q);
560 av_bprintf(&buf_script,
"frame=%"PRId64
"\n", frame_number);
562 av_bprintf(&buf_script,
"stream_%d_%d_q=%.1f\n",
567 nb_frames_dup =
ost->filter->nb_frames_dup;
568 nb_frames_drop =
ost->filter->nb_frames_drop;
589 hours_sign = (
pts < 0) ?
"-" :
"";
594 if (total_size < 0)
av_bprintf(&buf,
"size=N/A time=");
595 else av_bprintf(&buf,
"size=%8.0fkB time=", total_size / 1024.0);
599 av_bprintf(&buf,
"%s%02"PRId64
":%02d:%02d.%02d ",
611 if (total_size < 0)
av_bprintf(&buf_script,
"total_size=N/A\n");
612 else av_bprintf(&buf_script,
"total_size=%"PRId64
"\n", total_size);
620 av_bprintf(&buf_script,
"out_time=%s%02"PRId64
":%02d:%02d.%06d\n",
621 hours_sign, hours, mins, secs,
us);
624 if (nb_frames_dup || nb_frames_drop)
625 av_bprintf(&buf,
" dup=%"PRId64
" drop=%"PRId64, nb_frames_dup, nb_frames_drop);
626 av_bprintf(&buf_script,
"dup_frames=%"PRId64
"\n", nb_frames_dup);
627 av_bprintf(&buf_script,
"drop_frames=%"PRId64
"\n", nb_frames_drop);
634 av_bprintf(&buf_script,
"speed=%4.3gx\n", speed);
638 const char end = is_last_report ?
'\n' :
'\r';
640 fprintf(stderr,
"%s %c", buf.str, end);
650 is_last_report ?
"end" :
"continue");
652 FFMIN(buf_script.len, buf_script.size - 1));
655 if (is_last_report) {
658 "Error closing progress log, loss of information possible: %s\n",
av_err2str(
ret));
669 .format =
src->format,
670 .start_display_time =
src->start_display_time,
671 .end_display_time =
src->end_display_time,
683 for (
int i = 0;
i <
src->num_rects;
i++) {
697 dst_rect->
x = src_rect->
x;
698 dst_rect->
y = src_rect->
y;
699 dst_rect->
w = src_rect->
w;
700 dst_rect->
h = src_rect->
h;
715 for (
int j = 0; j < 4; j++) {
723 if (!src_rect->
data[j])
766 sub =
av_memdup(subtitle,
sizeof(*subtitle));
769 memset(subtitle, 0,
sizeof(*subtitle));
837 if (
f->recording_time != INT64_MAX) {
847 for (
int oidx = 0; oidx < ist->
nb_outputs; oidx++) {
849 if (
ost->enc || (!
pkt && no_eof))
864 for (
int j = 0; j < ist->nb_filters; j++) {
867 ist->file_index, ist->index, ist->dec ? ist->dec->name :
"?",
868 ist->filters[j]->name);
877 if (
ost->attachment_filename) {
896 ost->ist->file_index,
902 const AVCodec *out_codec =
ost->enc_ctx->codec;
903 const char *decoder_name =
"?";
904 const char *in_codec_name =
"?";
905 const char *encoder_name =
"?";
906 const char *out_codec_name =
"?";
910 decoder_name = in_codec->
name;
913 in_codec_name =
desc->name;
914 if (!strcmp(decoder_name, in_codec_name))
915 decoder_name =
"native";
919 encoder_name = out_codec->
name;
922 out_codec_name =
desc->name;
923 if (!strcmp(encoder_name, out_codec_name))
924 encoder_name =
"native";
928 in_codec_name, decoder_name,
929 out_codec_name, encoder_name);
945 int64_t opts_min = INT64_MAX;
955 INT64_MIN :
ost->last_mux_dts;
958 if (!
ost->initialized && !
ost->finished) {
962 if (!
ost->finished &&
opts < opts_min) {
977 if (tcgetattr(0, &tty) == 0) {
978 if (
on) tty.c_lflag |=
ECHO;
979 else tty.c_lflag &= ~
ECHO;
980 tcsetattr(0, TCSANOW, &tty);
988 static int64_t last_time;
992 if (cur_time - last_time >= 100000) {
994 last_time = cur_time;
1003 if (
key ==
'c' ||
key ==
'C'){
1004 char buf[4096], target[64], command[256],
arg[256] = {0};
1007 fprintf(stderr,
"\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
1010 while ((k =
read_key()) !=
'\n' && k !=
'\r' &&
i <
sizeof(buf)-1)
1015 fprintf(stderr,
"\n");
1017 (n = sscanf(buf,
"%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command,
arg)) >= 3) {
1019 target, time, command,
arg);
1025 "Parse error, at least 3 arguments were expected, "
1026 "only %d given in string '%s'\n", n, buf);
1030 fprintf(stderr,
"key function\n"
1031 "? show this help\n"
1032 "+ increase verbosity\n"
1033 "- decrease verbosity\n"
1034 "c Send command to first matching filter supporting it\n"
1035 "C Send/Queue command to all matching filters\n"
1036 "h dump packets/hex press to cycle through the 3 states\n"
1038 "s Show QP histogram\n"
1050 ost->unavailable = 0;
1093 "Error retrieving a packet from demuxer: %s\n",
av_err2str(
ret));
1109 for (
int oidx = 0; oidx < ist->
nb_outputs; oidx++) {
1133 return ret < 0 ?
ret : 0;
1159 ost->unavailable = 1;
1184 int64_t timer_start;
1188 *err_rate_exceeded = 0;
1212 }
else if (
ret < 0) {
1242 *err_rate_exceeded = 1;
1243 }
else if (err_rate)
1266 struct rusage rusage;
1268 getrusage(RUSAGE_SELF, &rusage);
1270 (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
1272 (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
1273 #elif HAVE_GETPROCESSTIMES
1275 FILETIME
c, e, k,
u;
1276 proc = GetCurrentProcess();
1277 GetProcessTimes(proc, &
c, &e, &k, &
u);
1279 ((int64_t)
u.dwHighDateTime << 32 |
u.dwLowDateTime) / 10;
1281 ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
1290 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
1291 struct rusage rusage;
1292 getrusage(RUSAGE_SELF, &rusage);
1293 return (int64_t)rusage.ru_maxrss * 1024;
1294 #elif HAVE_GETPROCESSMEMORYINFO
1296 PROCESS_MEMORY_COUNTERS memcounters;
1297 proc = GetCurrentProcess();
1298 memcounters.cb =
sizeof(memcounters);
1299 GetProcessMemoryInfo(proc, &memcounters,
sizeof(memcounters));
1300 return memcounters.PeakPagefileUsage;
1308 int ret, err_rate_exceeded;
1313 setvbuf(stderr,
NULL,_IONBF,0);
1346 int64_t utime, stime, rtime;
1352 "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
1353 utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
1357 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)
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,...
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.
int av_buffer_make_writable(AVBufferRef **pbuf)
Create a writable reference from a given buffer reference, avoiding data copy if possible.
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
static int frame_data_ensure(AVFrame *frame, int writable)
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.
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
const FrameData * frame_data_c(AVFrame *frame)
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.