| 1 |
/* |
| 2 |
* Copyright (C) 2013-2021 Jean-Luc Barrière |
| 3 |
* |
| 4 |
* SPDX-License-Identifier: GPL-2.0-or-later |
| 5 |
* See LICENSE.md for more information. |
| 6 |
*/ |
| 7 |
|
| 8 |
#include "debug.h" |
| 9 |
|
| 10 |
#include <cstdlib> |
| 11 |
#include <cstdarg> |
| 12 |
#include <cstdio> |
| 13 |
#include <cstring> |
| 14 |
#include <ctype.h> |
| 15 |
|
| 16 |
#ifdef _MSC_VER |
| 17 |
#define snprintf _snprintf |
| 18 |
#endif |
| 19 |
|
| 20 |
typedef struct |
| 21 |
{ |
| 22 |
const char* name; |
| 23 |
int cur_level; |
| 24 |
void (*msg_callback)(int level, char* msg); |
| 25 |
} debug_ctx_t; |
| 26 |
|
| 27 |
static debug_ctx_t debug_ctx = {"TSDemux", DEMUX_DBG_NONE, NULL}; |
| 28 |
|
| 29 |
/** |
| 30 |
* Set the debug level to be used for the subsystem |
| 31 |
* \param ctx the subsystem debug context to use |
| 32 |
* \param level the debug level for the subsystem |
| 33 |
* \return an integer subsystem id used for future interaction |
| 34 |
*/ |
| 35 |
static inline void __dbg_setlevel(debug_ctx_t* ctx, int level) |
| 36 |
{ |
| 37 |
if (ctx != NULL) |
| 38 |
{ |
| 39 |
ctx->cur_level = level; |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Generate a debug message at a given debug level |
| 45 |
* \param ctx the subsystem debug context to use |
| 46 |
* \param level the debug level of the debug message |
| 47 |
* \param fmt a printf style format string for the message |
| 48 |
* \param ... arguments to the format |
| 49 |
*/ |
| 50 |
static inline void __dbg(debug_ctx_t* ctx, int level, const char* fmt, va_list ap) |
| 51 |
{ |
| 52 |
if (ctx != NULL && level <= ctx->cur_level) |
| 53 |
{ |
| 54 |
char msg[4096]; |
| 55 |
int len = snprintf(msg, sizeof (msg), "(%s)", ctx->name); |
| 56 |
vsnprintf(msg + len, sizeof (msg) - len, fmt, ap); |
| 57 |
if (ctx->msg_callback) |
| 58 |
{ |
| 59 |
ctx->msg_callback(level, msg); |
| 60 |
} |
| 61 |
else |
| 62 |
{ |
| 63 |
fwrite(msg, strlen(msg), 1, stderr); |
| 64 |
} |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
void TSDemux::DBGLevel(int l) |
| 69 |
{ |
| 70 |
__dbg_setlevel(&debug_ctx, l); |
| 71 |
} |
| 72 |
|
| 73 |
void TSDemux::DBGAll() |
| 74 |
{ |
| 75 |
__dbg_setlevel(&debug_ctx, DEMUX_DBG_ALL); |
| 76 |
} |
| 77 |
|
| 78 |
void TSDemux::DBGNone() |
| 79 |
{ |
| 80 |
__dbg_setlevel(&debug_ctx, DEMUX_DBG_NONE); |
| 81 |
} |
| 82 |
|
| 83 |
void TSDemux::DBG(int level, const char* fmt, ...) |
| 84 |
{ |
| 85 |
va_list ap; |
| 86 |
|
| 87 |
va_start(ap, fmt); |
| 88 |
__dbg(&debug_ctx, level, fmt, ap); |
| 89 |
va_end(ap); |
| 90 |
} |
| 91 |
|
| 92 |
void TSDemux::SetDBGMsgCallback(void (*msgcb)(int level, char*)) |
| 93 |
{ |
| 94 |
debug_ctx.msg_callback = msgcb; |
| 95 |
} |