ffmpeg 日志系統av_log()


一般使用Error, Warning, Debug3個級別即可(見下面的顏色)。AV_LOG_QUIET

核心函數只有一個:av_log()。使用av_log()在控制台輸出日志的效果如下圖所示。





av_log()

av_log()是FFmpeg中輸出日志的函數。隨便打開一個FFmpeg的源代碼文件,就會發現其中遍布着av_log()函數。一般情況下FFmpeg類庫的源代碼中是不允許使用printf()這種的函數的,所有的輸出一律使用av_log()。
av_log()的聲明位於libavutil\log.h,如下所示。

  1.  * Send the specified message to the log if the level is less than or equal
  2.  * to the current av_log_level. By default, all logging messages are sent to
  3.  * stderr. This behavior can be altered by setting a different logging callback
  4.  * function.
  5.  * @see av_log_set_callback
  6.  *
  7.  * @param avcl A pointer to an arbitrary struct of which the first field is a
  8.  *        pointer to an AVClass struct.
  9.  * @param level The importance level of the message expressed using a @ref
  10.  *        lavu_log_constants "Logging Constant".
  11.  * @param fmt The format string (printf-compatible) that specifies how
  12.  *        subsequent arguments are converted to output.
  13.  */
  14. void av_log(void *avcl, int level, constchar *fmt, ...) av_printf_format(3, 4);  
 av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
 av_log(avctx, AV_LOG_ERROR, "Dimensions %dx%d not supported.\n", width, avctx->height);

這個函數的聲明有兩個地方比較特殊:

(1)函數最后一個參數是“…”
在C語言中,在函數參數數量不確定的情況下使用“…”來代表參數。例如printf()的原型定義如下


int  printf ( const  char *, ...);  


(2)它的聲明后面有一個av_printf_format(3, 4)。有關這個地方還沒有深入研究,網上資料中說它的作用是按照printf()的格式檢查av_log()的格式。
av_log()每個字段的含義如下:
avcl: 指定一個包含AVClass的結構體。
level:log的級別
fmt:和printf()一樣。
由此可見,av_log()和printf()的不同主要在於前面多了兩個參數。其中第一個參數指定該log 所屬的結構體 ,例如AVFormatContext、AVCodecContext等等。第二個參數指定log的級別:

有一個級別不輸出任何信息,即AV_LOG_QUIET。


可以通過av_log_get_level()獲得當前Log的級別,通過另一個函數av_log_set_level()設置當前的Log級別。

我們看一下H.264編碼的時候libx264的Log輸出的示例:
下面回到av_log()函數的源代碼。它的源代碼位於libavutil\log.c,如下所示。
  1. void av_log(void* avcl, int level, constchar *fmt, ...)  
  2. {  
  3.     AVClass* avc = avcl ? *(AVClass **) avcl : NULL;  
  4. va_list vl;  
  5.     va_start(vl, fmt);  
  6. if (avc && avc->version >= (50 << 16 | 15 << 8 | 2) &&  
  7.         avc->log_level_offset_offset && level >= AV_LOG_FATAL)  
  8.         level += *(int *) (((uint8_t *) avcl) + avc->log_level_offset_offset);  
  9.     av_vlog(avcl, level, fmt, vl);  
  10.     va_end(vl);  
  11. }  
首先來提一下C語言函數中“…”參數的含義。與它相關還涉及到以下4個部分:
(1)va_list變量
(2)va_start()
(3)va_arg()
(4)va_end()
va_list是一個指向函數的 參數的指針 。va_start()用於初始化va_list變量。va_arg()用於返回可變參數。va_end()用於結束可變參數的獲取。有關它們的用法可以參考一個小demo,如下所示。
  1. #include <stdio.h>  
  2. #include<stdarg.h>  
  3. void fun(int a,...){  
  4. va_list pp;  
  5.     va_start(pp,a);  
  6. do{  
  7.         printf("param =%d\n",a);  
  8.         a=va_arg(pp,int);//使 pp 指向下一個參數,將下一個參數的值賦給變量 a
  9.     }  
  10. while (a!=0);//直到參數為 0 時停止循環
  11. }  
  12. void main(){  
  13.     fun(20,40,60,80,0);  
  14. }  

av_log()的源代碼中,在va_start()和va_end()之間,調用了另一個函數av_vlog()。


av_vlog()

av_vlog()是一個FFmpeg的API函數。它的聲明位於libavutil\log.h中,如下所示。
  1. /**
  2.  * Send the specified message to the log if the level is less than or equal
  3.  * to the current av_log_level. By default, all logging messages are sent to
  4.  * stderr. This behavior can be altered by setting a different logging callback
  5.  * function.
  6.  * @see av_log_set_callback
  7.  *
  8.  * @param avcl A pointer to an arbitrary struct of which the first field is a
  9.  *        pointer to an AVClass struct.
  10.  * @param level The importance level of the message expressed using a @ref
  11.  *        lavu_log_constants "Logging Constant".
  12.  * @param fmt The format string (printf-compatible) that specifies how
  13.  *        subsequent arguments are converted to output.
  14.  * @param vl The arguments referenced by the format string.
  15.  */
  16. void av_vlog(void *avcl, int level, constchar *fmt, va_list vl);  


從聲明中可以看出,av_vlog()和av_log()的參數基本上是一模一樣的。

唯一的不同在於av_log()中的“…”變成了av_vlog()中的va_list。



av_vlog()的定義位於libavutil\log.c中,如下所示。
  1. void av_vlog(void* avcl, int level, constchar *fmt, va_list vl)  
  2. {  
  3. void (*log_callback)(void*, intconstchar*, va_list) = av_log_callback;  
  4. if (log_callback)  
  5.         log_callback(avcl, level, fmt, vl);  
  6. }  
從定義中可以看出,av_vlog()簡單調用了一個函數指針av_log_callback。av_log_callback是一個全局靜態變量,定義如下所示。
static  void (*av_log_callback)(void*, intconstchar*, va_list) =   av_log_default_callback;  

從代碼中可以看出,av_log_callback指針默認指向一個函數
av_log_default_callback ()。av_log_default_callback()即FFmpeg默認的Log函數






需要注意的是,這個Log函數是可以自定義的。按照指定的參數定義一個自定義的函數后,可以通過FFmpeg的另一個API函數av_log_set_callback()設定為Log函數
av_log_set_callback()的聲明如下所示。
  1. /**
  2.  * Set the logging callback
  3.  *
  4.  * @note The callback must be thread safe, even if the application does not use
  5.  *       threads itself as some codecs are multithreaded.
  6.  *
  7.  * @see av_log_default_callback
  8.  *
  9.  * @param callback A logging function with a compatible signature.
  10.  */
  11. void av_log_set_callback(void (*callback)(void*, intconstchar*, va_list));  

回調函數需要是一個線程安全函數,看源碼里面有個mutex鎖。

如果需要設置回默認的,按如下使用
av_log_set_callback(av_log_default_callback);

從聲明中可以看出,需要指定一個參數為(void*, int, const char*, va_list),返回值為void的函數作為Log函數。

av_log_set_callback()的定義很簡單,做了一個函數指針賦值的工作,如下所示。
  1. void av_log_set_callback(void (*callback)(void*, intconstchar*, va_list))  
  2. {  
  3.     av_log_callback = callback;  
  4. }  

例如,我們可以指定一個my_logoutput()函數作為Log的輸出函數,就可以將Log信息輸出到文本中(而不是屏幕上)。


  1. void my_logoutput(void* ptr, int level, constchar* fmt,va_list vl){  
  2. FILE *fp = fopen("my_log.txt","a+");     
  3. if(fp){     
  4.         vfprintf(fp,fmt,vl);  
  5.         fflush(fp);  
  6.         fclose(fp);  
  7.     }     
  8. }  
編輯好函數之后,使用av_log_set_callback()函數設置該函數為Log輸出函數即可。
  1. av_log_set_callback(my_logoutput);  

我們看看默認的日志函數功能是什么:

av_log_default_callback()的代碼是比較復雜的。其實如果我們僅僅是希望把Log信息輸出到屏幕上,遠不需要那么多代碼,只需要簡單打印一下就可以了。av_log_default_callback()之所以會那么復雜,主要是因為他還包含了很多的功能,比如說根據Log級別的不同將輸出的文本設置成不同的顏色。下圖顯示了不同級別的Log不同的背景顏色。

下面看一下av_log_default_callback()的源代碼大致的流程:
(1)如果輸入參數level大於系統當前的日志級別av_log_level,表明不需要做任何處理,直接返回。
(2)調用format_line()設定Log的輸出格式。格式化
(3)調用colored_fputs()設定Log的顏色。

format_line(), av_log_format_line()

format_line()用於設定Log的輸出格式。它本身並不是一個FFmpeg的API,但是FFmpeg有一個API函數av_log_format_line() 調用了這個函數。av_log_format_line()的聲明如下所示。
  1. /**
  2.  * Format a line of log      the same way as the default callback.
  3.  * @param line          buffer to receive the formated line
  4.  * @param line_size     size of the buffer
  5.  * @param print_prefix  used to store whether the prefix must be printed;
  6.  *                      must point to a persistent integer initially set to 1
  7.  */
  8. void av_log_format_line(void *ptr, int level, constchar *fmt, va_list vl,                      char *lineint line_sizeint *print_prefix);  

av_log_format_line()的定義如下所示。
  1. void av_log_format_line(void *ptr, int level, constchar *fmt, va_list vl,  
  2. char *line, int line_size, int *print_prefix)  
  3. {  
  4.     AVBPrint part[4];  
  5.     format_line(ptr, level, fmt, vl, part, print_prefix, NULL);  
  6.     snprintf(line, line_size, "%s%s%s%s", part[0].str, part[1].str, part[2].str, part[3].str);  
  7.     av_bprint_finalize(part+3, NULL);  
  8. }  

從代碼中可以看出,首先聲明了一個AVBPrint類型的數組,其中包含了4個元素;接着調用format_line()設定格式;
最后將設置格式后的AVBPrint數組中的4個元素連接起來
在這里遇到了一個結構體AVBPrint,它的定義位於libavutil\bprint.h,如下所示。
  1. /**
  2.  * Buffer to print data progressively
  3.  *
  4.  * The string buffer grows as necessary and is always 0-terminated.
  5.  * The content of the string is never accessed, and thus is
  6.  * encoding-agnostic and can even hold binary data.
  7.  *
  8.  * Small buffers are kept in the structure itself, and thus require no
  9.  * memory allocation at all (unless the contents of the buffer is needed
  10.  * after the structure goes out of scope). This is almost as lightweight as
  11.  * declaring a local "char buf[512]".
  12.  *
  13.  * The length of the string can go beyond the allocated size: the buffer is
  14.  * then truncated, but the functions still keep account of the actual total
  15.  * length.
  16.  *
  17.  * In other words, buf->len can be greater than buf->size and records the
  18.  * total length of what would have been to the buffer if there had been
  19.  * enough memory.
  20.  *
  21.  * Append operations do not need to be tested for failure: if a memory
  22.  * allocation fails, data stop being appended to the buffer, but the length
  23.  * is still updated. This situation can be tested with
  24.  * av_bprint_is_complete().
  25.  *
  26.  * The size_max field determines several possible behaviours:
  27.  *
  28.  * size_max = -1 (= UINT_MAX) or any large value will let the buffer be
  29.  * reallocated as necessary, with an amortized linear cost.
  30.  *
  31.  * size_max = 0 prevents writing anything to the buffer: only the total
  32.  * length is computed. The write operations can then possibly be repeated in
  33.  * a buffer with exactly the necessary size
  34.  * (using size_init = size_max = len + 1).
  35.  *
  36.  * size_max = 1 is automatically replaced by the exact size available in the
  37.  * structure itself, thus ensuring no dynamic memory allocation. The
  38.  * internal buffer is large enough to hold a reasonable paragraph of text,
  39.  * such as the current paragraph.
  40.  */
  41. typedef   struct AVBPrint {  
  42.     FF_PAD_STRUCTURE(1024,  
  43.     char *str;         /**< string so far */
  44.     unsigned len;      /**< length so far */
  45.     unsigned size;     /**< allocated memory */
  46.     unsigned size_max; /**< maximum allocated memory */
  47.      char reserved_internal_buffer[1];  
  48.     )  
  49. } AVBPrint;  

AVBPrint的注釋代碼很長,不再詳細敘述。在這里只要知道他是用於打印字符串的緩存 就可以了。它的名稱BPrint的意思應該就是“Buffer to Print ”。其中的str存儲了將要打印的字符串


format_line()函數的定義如下所示。
  1. staticvoid format_line(void *avcl, int level, constchar *fmt, va_list vl,  
  2.                         AVBPrint part[4], int *print_prefix, int type[2])  
  3. {  
  4.     AVClass* avc = avcl ? *(AVClass **) avcl : NULL;  
  5.     av_bprint_init(part+0, 0, 1);  
  6.     av_bprint_init(part+1, 0, 1);  
  7.     av_bprint_init(part+2, 0, 1);  
  8.     av_bprint_init(part+3, 0, 65536);  
  9. if(type) type[0] = type[1] = AV_CLASS_CATEGORY_NA + 16;  
  10. if (*print_prefix && avc) {  
  11. if (avc->parent_log_context_offset) {  
  12.             AVClass** parent = *(AVClass ***) (((uint8_t *) avcl) +  
  13.                                    avc->parent_log_context_offset);  
  14. if (parent && *parent) {  
  15.                 av_bprintf(part+0, "[%s @ %p] ",  
  16.                          (*parent)->item_name(parent), parent);  
  17. if(type) type[0] = get_category(parent);  
  18.             }  
  19.         }  
  20.         av_bprintf(part+1, "[%s @ %p] ",  
  21.                  avc->item_name(avcl), avcl);  
  22. if(type) type[1] = get_category(avcl);  
  23. if (flags & AV_LOG_PRINT_LEVEL)  
  24.             av_bprintf(part+2, "[%s] ", get_level_str(level));  
  25.     }  
  26.     av_vbprintf(part+3, fmt, vl);  
  27. if(*part[0].str || *part[1].str || *part[2].str || *part[3].str) {  
  28. char lastc = part[3].len && part[3].len <= part[3].size ? part[3].str[part[3].len - 1] : 0;  
  29.         *print_prefix = lastc == '\n' || lastc == '\r';  
  30.     }  
  31. }  

從代碼中可以看出,其分別處理了AVBPrint類型數組part的4個元素。由此我們也可以看出FFmpeg一條Log可以分成4個組成部分 。在這里涉及到幾個與AVBPrint相關的函數,由於篇幅的關系,不再分析它們的源代碼,僅僅列出它們的定義:
初始化AVBPrint的函數av_bprint_init()。
  1. /**
  2.  * Init a print buffer.
  3.  *
  4.  * @param buf        buffer to init
  5.  * @param size_init  initial size (including the final 0)
  6.  * @param size_max   maximum size;
  7.  *                   0 means do not write anything, just count the length;
  8.  *                   1 is replaced by the maximum value for automatic storage;
  9.  *                   any large value means that the internal buffer will be
  10.  *                   reallocated as needed up to that limit; -1 is converted to
  11.  *                   UINT_MAX, the largest limit possible.
  12.  *                   Check also AV_BPRINT_SIZE_* macros.
  13.  */
  14. void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max);  

向AVBPrint添加一個字符串 的函數av_bprintf()。

  1. /**
  2.  * Append a formatted string to a print buffer.
  3.  */
  4. void av_bprintf(AVBPrint *buf, constchar *fmt, ...) av_printf_format(2, 3);  

向AVBPrint添加一個字符串的函數av_vbprintf (),注意與av_bprintf()的不同在於其第3個參數不一樣。
  1. /**
  2.  * Append a formatted string to a print buffer.
  3.  */
  4. void av_vbprintf(AVBPrint *buf, constchar *fmt, va_list vl_arg);  
av_bprintf()的定義,位於libavutil\bprint.c,如下所示。

  1. void av_bprintf(AVBPrint *buf, constchar *fmt, ...)  
  2. {  
  3.     unsigned room;  
  4. char *dst;  
  5. va_list vl;  
  6. int extra_len;  
  7. while (1) {  
  8.         room = av_bprint_room(buf);  
  9.         dst = room ? buf->str + buf->len : NULL;  
  10.         va_start(vl, fmt);  
  11.         extra_len = vsnprintf(dst, room, fmt, vl);  
  12.         va_end(vl);  
  13. if (extra_len <= 0)  
  14. return;  
  15. if (extra_len < room)  
  16. break;  
  17. if (av_bprint_alloc(buf, extra_len))  
  18. break;  
  19.     }  
  20.     av_bprint_grow(buf, extra_len);  
  21. }  

可以看出av_bprintf()實際上調用了系統的vsnprintf ()完成了相應的功能。


看完以上幾個與AVBPrint相關函數之后,就可以來看一下format_line()的代碼了。例如,

part[0]對應的是目標結構體的父結構體的名稱(如果父結構體存在的話);

其打印格式形如“[%s @ %p]”其中前面的“%s”對應父結構體的名稱“%p”對應其所在的地址。


part[1]對應的是目標結構體自己的名稱;其打印格式形如“[%s @ %p]”,其中前面的“%s”對應本結構體的名稱,“%p”對應其所在的地址。


part[2]用於輸出Log的級別,這個字符串只有在flag中設置AV_LOG_PRINT_LEVEL的時候才能打印。


part[3]則是打印原本傳送進來的文本。


將format_line()函數處理后得到的4個字符串連接其來,就可以的到一條完整的Log信息。下面圖顯示了flag設置AV_LOG_PRINT_LEVEL后的打印出來的Log的格式。

默認情況下不設置flag打印出來的格式如下所示。



colored_fputs()

colored_fputs()函數用於將輸出的文本“上色”並且輸出


在這里有一點需要注意:Windows和Linux下控制台程序上色的方法是不一樣的。

Windows下是通過SetConsoleTextAttribute()方法給控制台中的文本上色;

Linux下則是通過添加一些ANSI控制碼完成上色。

Linux下控制台文字上色的方法

Linux下控制台顏色是通過添加專用數字來選擇的。這些數字夾在 "\e["和 "m"之間。如果指定一個以上的數字,則用分號將它們分開。

舉幾個例子:

(1)第一個數字(31)為前景顏色(紅色);第二個數字為(42)背景顏色(綠色)

  1. echo -e "\e[31;42m"  
(2)使用"\e[0m"序列將顏色重新設置為正常值


  1. echo -e "\e[0m" 或 echo -e "\033[0m"  
(3)顏色對應關系如下所示:
\e[30m -- \e[37m    設置前景色(字體顏色)
echo -e "\e[30m"    灰色
echo -e "\e[31m"    紅色    
echo -e "\e[32m"    綠色
echo -e "\e[33m"    黃色
echo -e "\e[34m"    藍色
echo -e "\e[35m"    紫色
echo -e "\e[36m"    淡藍色
echo -e "\e[37m"    白色     

\e[40m -- \e[47m    設置背景色
echo -e "\e[40m"    灰色
echo -e "\e[41m"    紅色
echo -e "\e[42m"    綠色
echo -e "\e[43m"    黃色
echo -e "\e[44m"    藍色
echo -e "\e[45m"    紫色
echo -e "\e[46m"    淡藍色
echo -e "\e[47m"    白色

具體到編程中,printf() 顏色設置示例代碼如下所示。
  1. int main()  
  2. {  
  3. printf("\e[31m Hello World. \e[0m \n"); // 紅色字體
  4. return 0;  
  5. }  

Windows下控制台文字上色的方法

Windows下控制台顏色是通過SetConsoleTextAttribute()函數完成的。SetConsoleTextAttribute()函數的原型如下所示。

  1. BOOL SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttributes);  
其中2個參數的含義如下所示:
hConsoleOutput:指向控制台的句柄。
wAttributes:文本屬性。

hConsoleOutput可以選擇以下3種句柄:
STD_INPUT_HANDLE:標准輸入的句柄
STD_OUTPUT_HANDLE:標准輸出的句柄
STD_ERROR_HANDLE:標准錯誤的句柄
wAttributes可以控制前景色和背景色
FOREGROUND_BLUE:字體顏色:藍
FOREGROUND_GREEN:字體顏色:綠
FOREGROUND_RED:字體顏色:紅
FOREGROUND_INTENSITY:前景色高亮顯示
BACKGROUND_BLUE:背景顏色:藍
BACKGROUND_GREEN:背景顏色:綠
BACKGROUND_RED:背景顏色:紅
BACKGROUND_INTENSITY背景色高亮顯示
控制台文本上色demo代碼如下所示。
  1. #include 
  2. #include 
  3. int main()  
  4. {  
  5.     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED);  
  6.     printf("red\n");  
  7.     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN);  
  8.     printf("green\n");  
  9.     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_BLUE);  
  10.     printf("blue\n");  
  11.     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED|FOREGROUND_GREEN);  
  12.     printf("red+green=yellow\n");  
  13.     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED|FOREGROUND_BLUE);  
  14.     printf("red+blue=purple\n");  
  15.     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN|FOREGROUND_BLUE);  
  16.     printf("green+blue=cyan\n");  
  17.     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED|BACKGROUND_GREEN);  
  18.     printf("Add background\n");  
  19. return 0;  
  20. }  

程序的運行結果如下圖所示。

colored_fputs()源代碼


從colored_fputs()的源代碼中可以看出如下流程:
首先根據宏定義判定系統的類型,如果系統類型是Windows,那么就調用SetConsoleTextAttribute()方法設定控制台文本的顏色,然后調用fputs()將Log記錄輸出到stderr(注意不是stdout);
如果系統類型是Linux,則通過添加特定字符串的方式設定控制台文本的顏色,然后將Log記錄輸出到stderr。
至此FFmpeg的日志輸出系統的源代碼就分析完畢了。

av_log() 函數
avcl:指定一個包含 AVClass 的結構體,指定該 log 所屬的結構體,如 AVFormatContext、AVCodecContext 等等,可以設置為 NULL

av_log(NULL, AV_LOG_DEBUG, "Hello World ! \n");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM