AVLog是FFmpeg的日志输出工具。在FFmpeg中所有的日志输出不是通过printf()函数而是通过av_log()函数。av_log()会最终调用fprintf(stderr,…)函数将日志内容输出到命令行界面上。但是在一些非命令行程序(MFC程序,Android程序等)中,av_log()调用的fprintf(stderr,…)就无法将日志内容显示出来了。对于这种情况,FFmpeg提供了日志回调函数av_log_set_callback()。该函数可以指定一个自定义的日志输出函数,将日志输出到指定的位置。
下面的自定义函数FFmpegLogFunc()将日志输出到了“ffmpeglog.txt”文本中。
void FFmpegLogFunc(void ptr, int level, const char fmt, va_list vl) {
FILE *fp = fopen("FFmpegLog.txt", "a+");
if (fp) {
vfprintf(fp, fmt, vl);
fflush(fp);
fclose(fp);
}
}
av_log_set_callback(FFmpegLogFunc);
使用说明
av_log(NULL, AV_LOG_WARNING, "start to write oneline to test av_log\n");
日志回调函数调整
1)选择性的打印,代码如下
void FFmpegLogFunc(void ptr, int level, const char fmt,va_list vl)
{
FILE *fp = fopen("ffmpeglog.txt","a+");
if(level > AV_LOG_ERROR) return;
if(fp)
{
vfprintf(fp,fmt,vl);
fflush(fp);
fclose(fp);
}
}
2)避免每次打开文件
void FFmpegLogFunc(void ptr, int level, const char fmt,va_list vl)
{
static FILE *fp = NULL;
if(NULL == fp)
{
fp = fopen("ffmpeglog.txt","a+");
}
if(fp)
{
vfprintf(fp,fmt,vl);
fflush(fp);
}
}
3)指定日志输出的等级
调用av_log_set_level(AV_LOG_DEBUG);
说明:比AV_LOG_DEBUG等级高的都不会输入到文件
等级最高的的宏定义是#define AV_LOG_TRACE 56
完整测试代码
#include <libavformat/avformat.h>
void FFmpegLogFunc(void* ptr, int level, const char * fmt, va_list vl) {
FILE *fp = fopen("FFmpegLog.txt", "a+");
if (fp) {
/*
struct tm sys;
GetLocalTime(&sys);
char szTime[128] = { 0 };
sprintf(szTime, "I:%4d-%02d-%02d %02d:%02d:%02d ms:%03d:", sys.wYear, sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond, sys.wMilliseconds);
fwrite(szTime, strlen(szTime), 1, fp);
*/
vfprintf(fp, fmt, vl);
fflush(fp);
fclose(fp);
}
}
int main(int argc, char *argv[])
{
int err_code;
char errors[1024];
AVFormatContext *fmt_ctx = NULL;
if(argc < 2){
fprintf(stderr, "[Usage]you should input media file!\n");
return -1;
}
char *src_filename = argv[1];
av_log_set_level(AV_LOG_INFO);
av_log_set_callback(FFmpegLogFunc);
av_log(NULL ,AV_LOG_INFO, "av_log src_filename:%s\n", src_filename);
printf( "printf src_filename:%s\n", src_filename);
av_register_all();
/* open input file, and allocate format context */
if ((err_code=avformat_open_input(&fmt_ctx, src_filename, NULL, NULL)) < 0) {
av_strerror(err_code, errors, 1024);
fprintf(stderr, "Could not open source file %s, %d(%s)\n", src_filename, err_code, errors);
exit(1);
}
printf("open source file succes \n");
/* retreive stream information */
if((err_code = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
av_strerror(err_code, errors, 1024);
fprintf(stderr, "Could not open source file %s, %d(%s)\n", src_filename, err_code, errors);
exit(1);
}
printf("avformat_find_stream_info success\n");
/* dump input information to stderr */
av_dump_format(fmt_ctx, 0, src_filename, 0);
printf("after av_dump_format\n");
/* close input file */
avformat_close_input(&fmt_ctx);
return 0;
}
参考
http://www.bkjia.com/ASPjc/1034665.html