<NME> config.cpp
<BEF> ﻿/*
 * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
 *
 * This file is part of ZLMediaKit(https://github.com/xia-chu/ZLMediaKit).
 *
 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
 */

#include "Common/config.h"
#include "Util/NoticeCenter.h"
#include "Util/logger.h"
#include "Util/onceToken.h"
#include "Util/util.h"
#include <assert.h>
#include <stdio.h>

using namespace std;
using namespace toolkit;

namespace mediakit {

bool loadIniConfig(const char *ini_path) {
    string ini;
    if (ini_path && ini_path[0] != '\0') {
        ini = ini_path;
    } else {
        ini = exePath() + ".ini";
    }
    try {
        mINI::Instance().parseFile(ini);
        NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastReloadConfig);
        return true;
    } catch (std::exception &) {
        InfoL << "dump ini file to:" << ini;
        mINI::Instance().dumpFile(ini);
        return false;
    }
}
////////////广播名称///////////
namespace Broadcast {
const string kBroadcastMediaChanged = "kBroadcastMediaChanged";
const string kBroadcastRecordMP4 = "kBroadcastRecordMP4";
const string kBroadcastRecordTs = "kBroadcastRecordTs";
const string kBroadcastHttpRequest = "kBroadcastHttpRequest";
const string kBroadcastHttpAccess = "kBroadcastHttpAccess";
const string kBroadcastOnGetRtspRealm = "kBroadcastOnGetRtspRealm";
const string kBroadcastOnRtspAuth = "kBroadcastOnRtspAuth";
const string kBroadcastMediaPlayed = "kBroadcastMediaPlayed";
const string kBroadcastMediaPublish = "kBroadcastMediaPublish";
const string kBroadcastFlowReport = "kBroadcastFlowReport";
const string kBroadcastReloadConfig = "kBroadcastReloadConfig";
const string kBroadcastShellLogin = "kBroadcastShellLogin";
const string kBroadcastNotFoundStream = "kBroadcastNotFoundStream";
const string kBroadcastStreamNoneReader = "kBroadcastStreamNoneReader";
const string kBroadcastHttpBeforeAccess = "kBroadcastHttpBeforeAccess";
const string kBroadcastSendRtpStopped = "kBroadcastSendRtpStopped";

} // namespace Broadcast

// 通用配置项目
namespace General {
#define GENERAL_FIELD "general."
const string kMediaServerId = GENERAL_FIELD "mediaServerId";
const string kFlowThreshold = GENERAL_FIELD "flowThreshold";
const string kStreamNoneReaderDelayMS = GENERAL_FIELD "streamNoneReaderDelayMS";
const string kMaxStreamWaitTimeMS = GENERAL_FIELD "maxStreamWaitMS";
const string kEnableVhost = GENERAL_FIELD "enableVhost";
const string kAddMuteAudio = GENERAL_FIELD "addMuteAudio";
const string kResetWhenRePlay = GENERAL_FIELD "resetWhenRePlay";
const string kPublishToHls = GENERAL_FIELD "publishToHls";
const string kPublishToMP4 = GENERAL_FIELD "publishToMP4";
const string kMergeWriteMS = GENERAL_FIELD "mergeWriteMS";
const string kModifyStamp = GENERAL_FIELD "modifyStamp";
const string kHlsDemand = GENERAL_FIELD "hls_demand";
const string kRtspDemand = GENERAL_FIELD "rtsp_demand";
const string kRtmpDemand = GENERAL_FIELD "rtmp_demand";
const string kTSDemand = GENERAL_FIELD "ts_demand";
const string kFMP4Demand = GENERAL_FIELD "fmp4_demand";
const string kEnableAudio = GENERAL_FIELD "enable_audio";
const string kCheckNvidiaDev = GENERAL_FIELD "check_nvidia_dev";
const string kEnableFFmpegLog = GENERAL_FIELD "enable_ffmpeg_log";
const string kWaitTrackReadyMS = GENERAL_FIELD "wait_track_ready_ms";
const string kWaitAddTrackMS = GENERAL_FIELD "wait_add_track_ms";
const string kUnreadyFrameCache = GENERAL_FIELD "unready_frame_cache";
const string kContinuePushMS = GENERAL_FIELD "continue_push_ms";

static onceToken token([]() {
    mINI::Instance()[kFlowThreshold] = 1024;
    mINI::Instance()[kStreamNoneReaderDelayMS] = 20 * 1000;
    mINI::Instance()[kMaxStreamWaitTimeMS] = 15 * 1000;
    mINI::Instance()[kEnableVhost] = 0;
    mINI::Instance()[kAddMuteAudio] = 1;
    mINI::Instance()[kResetWhenRePlay] = 1;
    mINI::Instance()[kPublishToHls] = 1;
    mINI::Instance()[kPublishToMP4] = 0;
    mINI::Instance()[kMergeWriteMS] = 0;
    mINI::Instance()[kModifyStamp] = 0;
    mINI::Instance()[kMediaServerId] = makeRandStr(16);
    mINI::Instance()[kHlsDemand] = 0;
    mINI::Instance()[kRtspDemand] = 0;
    mINI::Instance()[kRtmpDemand] = 0;
    mINI::Instance()[kTSDemand] = 0;
    mINI::Instance()[kFMP4Demand] = 0;
    mINI::Instance()[kEnableAudio] = 1;
    mINI::Instance()[kCheckNvidiaDev] = 1;
    mINI::Instance()[kEnableFFmpegLog] = 0;
    mINI::Instance()[kWaitTrackReadyMS] = 10000;
    mINI::Instance()[kWaitAddTrackMS] = 3000;
    mINI::Instance()[kUnreadyFrameCache] = 100;
    mINI::Instance()[kContinuePushMS] = 15 * 1000;
});

} // namespace General

////////////HTTP配置///////////
namespace Http {
#define HTTP_FIELD "http."
const string kSendBufSize = HTTP_FIELD "sendBufSize";
const string kMaxReqSize = HTTP_FIELD "maxReqSize";
const string kKeepAliveSecond = HTTP_FIELD "keepAliveSecond";
const string kCharSet = HTTP_FIELD "charSet";
const string kRootPath = HTTP_FIELD "rootPath";
const string kVirtualPath = HTTP_FIELD "virtualPath";
const string kNotFound = HTTP_FIELD "notFound";
const string kDirMenu = HTTP_FIELD "dirMenu";
const string kForbidCacheSuffix = HTTP_FIELD "forbidCacheSuffix";
const string kForwardedIpHeader = HTTP_FIELD "forwarded_ip_header";

static onceToken token([]() {
    mINI::Instance()[kSendBufSize] = 64 * 1024;
    mINI::Instance()[kMaxReqSize] = 4 * 10240;
    mINI::Instance()[kKeepAliveSecond] = 15;
    mINI::Instance()[kDirMenu] = true;
    mINI::Instance()[kVirtualPath] = "";

#if defined(_WIN32)
    mINI::Instance()[kCharSet] = "gb2312";
#else
    mINI::Instance()[kCharSet] = "utf-8";
#endif

    mINI::Instance()[kRootPath] = "./www";
    mINI::Instance()[kNotFound] = StrPrinter << "<html>"
                                                "<head><title>404 Not Found</title></head>"
                                                "<body bgcolor=\"white\">"
                                                "<center><h1>您访问的资源不存在！</h1></center>"
                                                "<hr><center>"
                                             << kServerName
                                             << "</center>"
                                                "</body>"
                                                "</html>"
                                             << endl;
    mINI::Instance()[kForbidCacheSuffix] = "";
    mINI::Instance()[kForwardedIpHeader] = "";
});

} // namespace Http

////////////SHELL配置///////////
namespace Shell {
#define SHELL_FIELD "shell."
const string kMaxReqSize = SHELL_FIELD "maxReqSize";

static onceToken token([]() { mINI::Instance()[kMaxReqSize] = 1024; });
} // namespace Shell

////////////RTSP服务器配置///////////
namespace Rtsp {
#define RTSP_FIELD "rtsp."
const string kAuthBasic = RTSP_FIELD "authBasic";
const string kHandshakeSecond = RTSP_FIELD "handshakeSecond";
const string kKeepAliveSecond = RTSP_FIELD "keepAliveSecond";
const string kDirectProxy = RTSP_FIELD "directProxy";
const string kLowLatency = RTSP_FIELD"lowLatency";

static onceToken token([]() {
    // 默认Md5方式认证
    mINI::Instance()[kAuthBasic] = 0;
    mINI::Instance()[kHandshakeSecond] = 15;
    mINI::Instance()[kKeepAliveSecond] = 15;
    mINI::Instance()[kDirectProxy] = 1;
    mINI::Instance()[kLowLatency] = 0;
});
} // namespace Rtsp

////////////RTMP服务器配置///////////
namespace Rtmp {
#define RTMP_FIELD "rtmp."
const string kModifyStamp = RTMP_FIELD "modifyStamp";
const string kHandshakeSecond = RTMP_FIELD "handshakeSecond";
const string kKeepAliveSecond = RTMP_FIELD "keepAliveSecond";

static onceToken token([]() {
    mINI::Instance()[kModifyStamp] = false;
    mINI::Instance()[kHandshakeSecond] = 15;
    mINI::Instance()[kKeepAliveSecond] = 15;
});
} // namespace Rtmp

////////////RTP配置///////////
namespace Rtp {
#define RTP_FIELD "rtp."
// RTP打包最大MTU,公网情况下更小
const string kVideoMtuSize = RTP_FIELD "videoMtuSize";
const string kAudioMtuSize = RTP_FIELD "audioMtuSize";
// rtp包最大长度限制，单位是KB
const string kRtpMaxSize = RTP_FIELD "rtpMaxSize";
namespace MultiCast {
#define MULTI_FIELD "multicast."
//组播分配起始地址
#define MULTI_ADDR_MIN (0xE00000FF + 10)
const char kAddrMin[] = MULTI_FIELD"addrMin";

//组播分配截止地址
#define MULTI_ADDR_MAX (0xEFFFFFFF)
const char kAddrMax[] = MULTI_FIELD"addrMax";

//组播TTL
#define MULTI_UDP_TTL 64
const char kUdpTTL[] = MULTI_FIELD"udpTTL";

onceToken token([](){
	mINI::Instance()[kAddrMin] = MULTI_ADDR_MIN;
	mINI::Instance()[kAddrMax] = MULTI_ADDR_MAX;
	mINI::Instance()[kUdpTTL] = MULTI_UDP_TTL;
},nullptr);

const string kAddrMin = MULTI_FIELD "addrMin";
// 组播分配截止地址
const string kAddrMax = MULTI_FIELD "addrMax";
// 组播TTL
const string kUdpTTL = MULTI_FIELD "udpTTL";

static onceToken token([]() {
    mINI::Instance()[kAddrMin] = "239.0.0.0";
    mINI::Instance()[kAddrMax] = "239.255.255.255";
    mINI::Instance()[kUdpTTL] = 64;
});
} // namespace MultiCast

////////////录像配置///////////
namespace Record {
#define RECORD_FIELD "record."
const string kAppName = RECORD_FIELD "appName";
const string kSampleMS = RECORD_FIELD "sampleMS";
const string kFileSecond = RECORD_FIELD "fileSecond";
const string kFilePath = RECORD_FIELD "filePath";
const string kFileBufSize = RECORD_FIELD "fileBufSize";
const string kFastStart = RECORD_FIELD "fastStart";
const string kFileRepeat = RECORD_FIELD "fileRepeat";
const string kMP4AsPlayer = RECORD_FIELD "mp4_as_player";

static onceToken token([]() {
    mINI::Instance()[kAppName] = "record";
    mINI::Instance()[kSampleMS] = 500;
    mINI::Instance()[kFileSecond] = 60 * 60;
    mINI::Instance()[kFilePath] = "./www";
    mINI::Instance()[kFileBufSize] = 64 * 1024;
    mINI::Instance()[kFastStart] = false;
    mINI::Instance()[kFileRepeat] = false;
    mINI::Instance()[kMP4AsPlayer] = false;
});
} // namespace Record

////////////HLS相关配置///////////
namespace Hls {
#define HLS_FIELD "hls."
const string kSegmentDuration = HLS_FIELD "segDur";
const string kSegmentNum = HLS_FIELD "segNum";
const string kSegmentKeep = HLS_FIELD "segKeep";
const string kSegmentRetain = HLS_FIELD "segRetain";
const string kFileBufSize = HLS_FIELD "fileBufSize";
const string kFilePath = HLS_FIELD "filePath";
const string kBroadcastRecordTs = HLS_FIELD "broadcastRecordTs";
const string kDeleteDelaySec = HLS_FIELD "deleteDelaySec";

static onceToken token([]() {
    mINI::Instance()[kSegmentDuration] = 2;
    mINI::Instance()[kSegmentNum] = 3;
    mINI::Instance()[kSegmentKeep] = false;
    mINI::Instance()[kSegmentRetain] = 5;
    mINI::Instance()[kFileBufSize] = 64 * 1024;
    mINI::Instance()[kFilePath] = "./www";
    mINI::Instance()[kBroadcastRecordTs] = false;
    mINI::Instance()[kDeleteDelaySec] = 10;
});
} // namespace Hls

////////////Rtp代理相关配置///////////
namespace RtpProxy {
#define RTP_PROXY_FIELD "rtp_proxy."
const string kDumpDir = RTP_PROXY_FIELD "dumpDir";
const string kTimeoutSec = RTP_PROXY_FIELD "timeoutSec";
const string kPortRange = RTP_PROXY_FIELD "port_range";
const string kH264PT = RTP_PROXY_FIELD "h264_pt";
const string kH265PT = RTP_PROXY_FIELD "h265_pt";
const string kPSPT = RTP_PROXY_FIELD "ps_pt";
const string kTSPT = RTP_PROXY_FIELD "ts_pt";
const string kOpusPT = RTP_PROXY_FIELD "opus_pt";
const string kG711UPT = RTP_PROXY_FIELD "g711u_pt";
const string kG711APT = RTP_PROXY_FIELD "g711a_pt";

static onceToken token([]() {
    mINI::Instance()[kDumpDir] = "";
    mINI::Instance()[kTimeoutSec] = 15;
    mINI::Instance()[kPortRange] = "30000-35000";
    mINI::Instance()[kH264PT] = 98;
    mINI::Instance()[kH265PT] = 99;
    mINI::Instance()[kPSPT] = 96;
    mINI::Instance()[kTSPT] = 33;
    mINI::Instance()[kOpusPT] = 100;
    mINI::Instance()[kG711UPT] = 0;
    mINI::Instance()[kG711APT] = 8;
});
} // namespace RtpProxy

namespace Client {
const string kNetAdapter = "net_adapter";
const string kRtpType = "rtp_type";
const string kRtspUser = "rtsp_user";
const string kRtspPwd = "rtsp_pwd";
const string kRtspPwdIsMD5 = "rtsp_pwd_md5";
const string kTimeoutMS = "protocol_timeout_ms";
const string kMediaTimeoutMS = "media_timeout_ms";
const string kBeatIntervalMS = "beat_interval_ms";
const string kBenchmarkMode = "benchmark_mode";
const string kWaitTrackReady = "wait_track_ready";
const string kPlayTrack = "play_track";
} // namespace Client

} // namespace mediakit

#ifdef ENABLE_MEM_DEBUG

extern "C" {
extern void *__real_malloc(size_t);
extern void __real_free(void *);
extern void *__real_realloc(void *ptr, size_t c);
void *__wrap_malloc(size_t c);
void __wrap_free(void *ptr);
void *__wrap_calloc(size_t __nmemb, size_t __size);
void *__wrap_realloc(void *ptr, size_t c);
}

#define BLOCK_TYPES 16
#define MIN_BLOCK_SIZE 128

static int get_mem_block_type(size_t c) {
    int ret = 0;
    while (c > MIN_BLOCK_SIZE && ret + 1 < BLOCK_TYPES) {
        c >>= 1;
        ++ret;
    }
    return ret;
}

std::vector<size_t> getBlockTypeSize() {
    std::vector<size_t> ret;
    ret.resize(BLOCK_TYPES);
    size_t block_size = MIN_BLOCK_SIZE;
    for (auto i = 0; i < BLOCK_TYPES; ++i) {
        ret[i] = block_size;
        block_size <<= 1;
    }
    return ret;
}

class MemThreadInfo {
public:
    using Ptr = std::shared_ptr<MemThreadInfo>;
    atomic<uint64_t> mem_usage { 0 };
    atomic<uint64_t> mem_block { 0 };
    atomic<uint64_t> mem_block_map[BLOCK_TYPES];

    static MemThreadInfo *Instance(bool is_thread_local) {
        if (!is_thread_local) {
            static auto instance = new MemThreadInfo(is_thread_local);
            return instance;
        }
        static auto thread_local instance = new MemThreadInfo(is_thread_local);
        return instance;
    }

    ~MemThreadInfo() {
        // printf("%s %d\r\n", __FUNCTION__, (int) _is_thread_local);
    }

    MemThreadInfo(bool is_thread_local) {
        _is_thread_local = is_thread_local;
        if (_is_thread_local) {
            // 确保所有线程退出后才能释放全局内存统计器
            total_mem = Instance(false);
        }
        // printf("%s %d\r\n", __FUNCTION__, (int) _is_thread_local);
    }

    void *operator new(size_t sz) { return __real_malloc(sz); }

    void operator delete(void *ptr) { __real_free(ptr); }

    void addBlock(size_t c) {
        if (total_mem) {
            total_mem->addBlock(c);
        }
        mem_usage += c;
        ++mem_block_map[get_mem_block_type(c)];
        ++mem_block;
    }

    void delBlock(size_t c) {
        if (total_mem) {
            total_mem->delBlock(c);
        }
        mem_usage -= c;
        --mem_block_map[get_mem_block_type(c)];
        if (0 == --mem_block) {
            delete this;
        }
    }

private:
    bool _is_thread_local;
    MemThreadInfo *total_mem = nullptr;
};

class MemThreadInfoLocal {
public:
    MemThreadInfoLocal() {
        ptr = MemThreadInfo::Instance(true);
        ptr->addBlock(1);
    }

    ~MemThreadInfoLocal() { ptr->delBlock(1); }

    MemThreadInfo *get() const { return ptr; }

private:
    MemThreadInfo *ptr;
};

// 该变量主要确保线程退出后才能释放MemThreadInfo变量
static thread_local MemThreadInfoLocal s_thread_mem_info;

uint64_t getTotalMemUsage() {
    return MemThreadInfo::Instance(false)->mem_usage.load();
}

uint64_t getTotalMemBlock() {
    return MemThreadInfo::Instance(false)->mem_block.load();
}

uint64_t getTotalMemBlockByType(int type) {
    assert(type < BLOCK_TYPES);
    return MemThreadInfo::Instance(false)->mem_block_map[type].load();
}

uint64_t getThisThreadMemUsage() {
    return MemThreadInfo::Instance(true)->mem_usage.load();
}

uint64_t getThisThreadMemBlock() {
    return MemThreadInfo::Instance(true)->mem_block.load();
}

uint64_t getThisThreadMemBlockByType(int type) {
    assert(type < BLOCK_TYPES);
    return MemThreadInfo::Instance(true)->mem_block_map[type].load();
}

class MemCookie {
public:
    static constexpr uint32_t kMagic = 0xFEFDFCFB;
    uint32_t magic;
    uint32_t size;
    MemThreadInfo *alloc_info;
    char ptr;
};

#define MEM_OFFSET offsetof(MemCookie, ptr)

#if (defined(__linux__) && !defined(ANDROID)) || defined(__MACH__)
#define MAX_STACK_FRAMES 128
#define MEM_WARING
#include <execinfo.h>
#include <limits.h>
#include <sys/resource.h>
#include <sys/wait.h>

static void print_mem_waring(size_t c) {
    void *array[MAX_STACK_FRAMES];
    int size = backtrace(array, MAX_STACK_FRAMES);
    char **strings = backtrace_symbols(array, size);
    printf("malloc big memory:%d, back trace:\r\n", (int)c);
    for (int i = 0; i < size; ++i) {
        printf("[%d]: %s\r\n", i, strings[i]);
    }
    __real_free(strings);
}
#endif

static void init_cookie(MemCookie *cookie, size_t c) {
    cookie->magic = MemCookie::kMagic;
    cookie->size = c;
    cookie->alloc_info = s_thread_mem_info.get();
    cookie->alloc_info->addBlock(c);

#if defined(MEM_WARING)
    static auto env = getenv("MEM_WARN_SIZE");
    static size_t s_mem_waring_size = atoll(env ? env : "0");
    if (s_mem_waring_size > 1024 && c >= s_mem_waring_size) {
        print_mem_waring(c);
    }
#endif
}

static void un_init_cookie(MemCookie *cookie) {
    cookie->alloc_info->delBlock(cookie->size);
}

void *__wrap_malloc(size_t c) {
    c += MEM_OFFSET;
    auto cookie = (MemCookie *)__real_malloc(c);
    if (cookie) {
        init_cookie(cookie, c);
        return &cookie->ptr;
    }
    return nullptr;
}

void __wrap_free(void *ptr) {
    if (!ptr) {
        return;
    }
    auto cookie = (MemCookie *)((char *)ptr - MEM_OFFSET);
    if (cookie->magic != MemCookie::kMagic) {
        __real_free(ptr);
        return;
    }
    un_init_cookie(cookie);
    __real_free(cookie);
}

void *__wrap_calloc(size_t __nmemb, size_t __size) {
    auto size = __nmemb * __size;
    auto ret = malloc(size);
    if (ret) {
        memset(ret, 0, size);
    }
    return ret;
}

void *__wrap_realloc(void *ptr, size_t c) {
    if (!ptr) {
        return malloc(c);
    }

    auto cookie = (MemCookie *)((char *)ptr - MEM_OFFSET);
    if (cookie->magic != MemCookie::kMagic) {
        return __real_realloc(ptr, c);
    }

    un_init_cookie(cookie);
    c += MEM_OFFSET;
    cookie = (MemCookie *)__real_realloc(cookie, c);
    if (cookie) {
        init_cookie(cookie, c);
        return &cookie->ptr;
    }
    return nullptr;
}

void *operator new(std::size_t size) {
    auto ret = malloc(size);
    if (ret) {
        return ret;
    }
    throw std::bad_alloc();
}

void operator delete(void *ptr) noexcept {
    free(ptr);
}

void operator delete(void *ptr, std::size_t) noexcept {
    free(ptr);
}

void *operator new[](std::size_t size) {
    auto ret = malloc(size);
    if (ret) {
        return ret;
    }
    throw std::bad_alloc();
}

void operator delete[](void *ptr) noexcept {
    free(ptr);
}

void operator delete[](void *ptr, std::size_t) noexcept {
    free(ptr);
}
#endif

<MSG> 组播地址改成字符串

<DFF> @@ -210,20 +210,16 @@ onceToken token([](){
 namespace MultiCast {
 #define MULTI_FIELD "multicast."
 //组播分配起始地址
-#define MULTI_ADDR_MIN (0xE00000FF + 10)
 const char kAddrMin[] = MULTI_FIELD"addrMin";
-
 //组播分配截止地址
-#define MULTI_ADDR_MAX (0xEFFFFFFF)
 const char kAddrMax[] = MULTI_FIELD"addrMax";
-
 //组播TTL
 #define MULTI_UDP_TTL 64
 const char kUdpTTL[] = MULTI_FIELD"udpTTL";
 
 onceToken token([](){
-	mINI::Instance()[kAddrMin] = MULTI_ADDR_MIN;
-	mINI::Instance()[kAddrMax] = MULTI_ADDR_MAX;
+	mINI::Instance()[kAddrMin] = "239.0.0.0";
+	mINI::Instance()[kAddrMax] = "239.255.255.255";
 	mINI::Instance()[kUdpTTL] = MULTI_UDP_TTL;
 },nullptr);
 

{'commit': 'diff --git a/src/Common/config.cpp b/src/Common/config.cpp\nindex 909631b7..73b2d405 100644\n--- a/src/Common/config.cpp\n+++ b/src/Common/config.cpp\n@@ -210,20 +210,16 @@ onceToken token([](){\n namespace MultiCast {\n #define MULTI_FIELD "multicast."\n //组播分配起始地址\n-#define MULTI_ADDR_MIN (0xE00000FF + 10)\n const char kAddrMin[] = MULTI_FIELD"addrMin";\n-\n //组播分配截止地址\n-#define MULTI_ADDR_MAX (0xEFFFFFFF)\n const char kAddrMax[] = MULTI_FIELD"addrMax";\n-\n //组播TTL\n #define MULTI_UDP_TTL 64\n const char kUdpTTL[] = MULTI_FIELD"udpTTL";\n \n onceToken token([](){\n-\tmINI::Instance()[kAddrMin] = MULTI_ADDR_MIN;\n-\tmINI::Instance()[kAddrMax] = MULTI_ADDR_MAX;\n+\tmINI::Instance()[kAddrMin] = "239.0.0.0";\n+\tmINI::Instance()[kAddrMax] = "239.255.255.255";\n \tmINI::Instance()[kUdpTTL] = MULTI_UDP_TTL;\n },nullptr);\n \ndiff --git a/src/Rtsp/RtpBroadCaster.cpp b/src/Rtsp/RtpBroadCaster.cpp\nindex 6f36f995..c6823f45 100644\n--- a/src/Rtsp/RtpBroadCaster.cpp\n+++ b/src/Rtsp/RtpBroadCaster.cpp\n@@ -26,6 +26,7 @@\n \n #include <list>\n #include <type_traits>\n+#include <arpa/inet.h>\n #include "RtpBroadCaster.h"\n #include "Util/util.h"\n #include "Network/sockutil.h"\n@@ -36,12 +37,20 @@ using namespace std;\n namespace ZL {\n namespace Rtsp {\n \n+static uint32_t addressToInt(const string &ip){\n+    struct in_addr addr;\n+    bzero(&addr,sizeof(addr));\n+\n+    inet_aton(ip.data(),&addr);\n+    return (uint32_t)ntohl((uint32_t &)addr.s_addr);\n+}\n \n std::shared_ptr<uint32_t> MultiCastAddressMaker::obtain(uint32_t iTry) {\n \tlock_guard<recursive_mutex> lck(m_mtx);\n-\tstatic uint32_t addrMin = mINI::Instance()[Config::MultiCast::kAddrMin].as<uint32_t>();\n-\tstatic uint32_t addrMax = mINI::Instance()[Config::MultiCast::kAddrMax].as<uint32_t>();\n-\tif(m_iAddr > addrMax){\n+\tstatic uint32_t addrMin = addressToInt(mINI::Instance()[Config::MultiCast::kAddrMin]);\n+\tstatic uint32_t addrMax = addressToInt(mINI::Instance()[Config::MultiCast::kAddrMax]);\n+\n+\tif(m_iAddr > addrMax || m_iAddr == 0){\n \t\tm_iAddr = addrMin;\n \t}\n \tauto iGotAddr =  m_iAddr++;\n@@ -56,8 +65,7 @@ std::shared_ptr<uint32_t> MultiCastAddressMaker::obtain(uint32_t iTry) {\n \t}\n \tm_setBadAddr.emplace(iGotAddr);\n \tstd::shared_ptr<uint32_t> ret(new uint32_t(iGotAddr),[](uint32_t *ptr){\n-\t\tauto val = *ptr;\n-\t\tMultiCastAddressMaker::Instance().release(val);\n+\t\tMultiCastAddressMaker::Instance().release(*ptr);\n \t\tdelete ptr;\n \t});\n \treturn ret;\ndiff --git a/src/Rtsp/RtpBroadCaster.h b/src/Rtsp/RtpBroadCaster.h\nindex 135903bd..0f318d39 100644\n--- a/src/Rtsp/RtpBroadCaster.h\n+++ b/src/Rtsp/RtpBroadCaster.h\n@@ -65,7 +65,7 @@ public:\n private:\n \tMultiCastAddressMaker(){};\n \tvoid release(uint32_t iAddr);\n-\tuint32_t m_iAddr = mINI::Instance()[Config::MultiCast::kAddrMin].as<uint32_t>();\n+\tuint32_t m_iAddr = 0;\n \trecursive_mutex m_mtx;\n \tunordered_set<uint32_t> m_setBadAddr;\n };\n', 'commit_subject': '组播地址改成字符串', 'repo_name': 'xiongziliang/ZLMediaKit', 'committer': {'name': 'xiongziliang', 'email': '2c1ef1aaf06ec408d7b37a0565446d2bba75fe9a@qq.com', 'time_sec': '1517982224', 'tz_offset': '480', 'date': {'seconds': '1517982224'}}, 'commit_tree': '4d41341afa3f322bc37b50dca774c9540bd6638a', 'commit_message': '组播地址改成字符串\n', 'language_name': 'Java', 'license': 'mit', 'hunks': '@@ -210,20 +210,16 @@ onceToken token([](){\n namespace MultiCast {\n #define MULTI_FIELD "multicast."\n //组播分配起始地址\n-#define MULTI_ADDR_MIN (0xE00000FF + 10)\n const char kAddrMin[] = MULTI_FIELD"addrMin";\n-\n //组播分配截止地址\n-#define MULTI_ADDR_MAX (0xEFFFFFFF)\n const char kAddrMax[] = MULTI_FIELD"addrMax";\n-\n //组播TTL\n #define MULTI_UDP_TTL 64\n const char kUdpTTL[] = MULTI_FIELD"udpTTL";\n \n onceToken token([](){\n-\tmINI::Instance()[kAddrMin] = MULTI_ADDR_MIN;\n-\tmINI::Instance()[kAddrMax] = MULTI_ADDR_MAX;\n+\tmINI::Instance()[kAddrMin] = "239.0.0.0";\n+\tmINI::Instance()[kAddrMax] = "239.255.255.255";\n \tmINI::Instance()[kUdpTTL] = MULTI_UDP_TTL;\n },nullptr);\n \n', 'addition_count': 2, 'deletion_count': 6, 'src_file': 'a/src/Common/config.cpp', 'tgt_file': 'b/src/Common/config.cpp', 'file_extension': '.cpp', 'before_file': '\ufeff/*\n * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.\n *\n * This file is part of ZLMediaKit(https://github.com/xia-chu/ZLMediaKit).\n *\n * Use of this source code is governed by MIT license that can be found in the\n * LICENSE file in the root of the source tree. All contributing project authors\n * may be found in the AUTHORS file in the root of the source tree.\n */\n\n#include "Common/config.h"\n#include "Util/NoticeCenter.h"\n#include "Util/logger.h"\n#include "Util/onceToken.h"\n#include "Util/util.h"\n#include <assert.h>\n#include <stdio.h>\n\nusing namespace std;\nusing namespace toolkit;\n\nnamespace mediakit {\n\nbool loadIniConfig(const char *ini_path) {\n    string ini;\n    if (ini_path && ini_path[0] != \'\\0\') {\n        ini = ini_path;\n    } else {\n        ini = exePath() + ".ini";\n    }\n    try {\n        mINI::Instance().parseFile(ini);\n        NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastReloadConfig);\n        return true;\n    } catch (std::exception &) {\n        InfoL << "dump ini file to:" << ini;\n        mINI::Instance().dumpFile(ini);\n        return false;\n    }\n}\n////////////广播名称///////////\nnamespace Broadcast {\nconst string kBroadcastMediaChanged = "kBroadcastMediaChanged";\nconst string kBroadcastRecordMP4 = "kBroadcastRecordMP4";\nconst string kBroadcastRecordTs = "kBroadcastRecordTs";\nconst string kBroadcastHttpRequest = "kBroadcastHttpRequest";\nconst string kBroadcastHttpAccess = "kBroadcastHttpAccess";\nconst string kBroadcastOnGetRtspRealm = "kBroadcastOnGetRtspRealm";\nconst string kBroadcastOnRtspAuth = "kBroadcastOnRtspAuth";\nconst string kBroadcastMediaPlayed = "kBroadcastMediaPlayed";\nconst string kBroadcastMediaPublish = "kBroadcastMediaPublish";\nconst string kBroadcastFlowReport = "kBroadcastFlowReport";\nconst string kBroadcastReloadConfig = "kBroadcastReloadConfig";\nconst string kBroadcastShellLogin = "kBroadcastShellLogin";\nconst string kBroadcastNotFoundStream = "kBroadcastNotFoundStream";\nconst string kBroadcastStreamNoneReader = "kBroadcastStreamNoneReader";\nconst string kBroadcastHttpBeforeAccess = "kBroadcastHttpBeforeAccess";\nconst string kBroadcastSendRtpStopped = "kBroadcastSendRtpStopped";\n\n} // namespace Broadcast\n\n// 通用配置项目\nnamespace General {\n#define GENERAL_FIELD "general."\nconst string kMediaServerId = GENERAL_FIELD "mediaServerId";\nconst string kFlowThreshold = GENERAL_FIELD "flowThreshold";\nconst string kStreamNoneReaderDelayMS = GENERAL_FIELD "streamNoneReaderDelayMS";\nconst string kMaxStreamWaitTimeMS = GENERAL_FIELD "maxStreamWaitMS";\nconst string kEnableVhost = GENERAL_FIELD "enableVhost";\nconst string kAddMuteAudio = GENERAL_FIELD "addMuteAudio";\nconst string kResetWhenRePlay = GENERAL_FIELD "resetWhenRePlay";\nconst string kPublishToHls = GENERAL_FIELD "publishToHls";\nconst string kPublishToMP4 = GENERAL_FIELD "publishToMP4";\nconst string kMergeWriteMS = GENERAL_FIELD "mergeWriteMS";\nconst string kModifyStamp = GENERAL_FIELD "modifyStamp";\nconst string kHlsDemand = GENERAL_FIELD "hls_demand";\nconst string kRtspDemand = GENERAL_FIELD "rtsp_demand";\nconst string kRtmpDemand = GENERAL_FIELD "rtmp_demand";\nconst string kTSDemand = GENERAL_FIELD "ts_demand";\nconst string kFMP4Demand = GENERAL_FIELD "fmp4_demand";\nconst string kEnableAudio = GENERAL_FIELD "enable_audio";\nconst string kCheckNvidiaDev = GENERAL_FIELD "check_nvidia_dev";\nconst string kEnableFFmpegLog = GENERAL_FIELD "enable_ffmpeg_log";\nconst string kWaitTrackReadyMS = GENERAL_FIELD "wait_track_ready_ms";\nconst string kWaitAddTrackMS = GENERAL_FIELD "wait_add_track_ms";\nconst string kUnreadyFrameCache = GENERAL_FIELD "unready_frame_cache";\nconst string kContinuePushMS = GENERAL_FIELD "continue_push_ms";\n\nstatic onceToken token([]() {\n    mINI::Instance()[kFlowThreshold] = 1024;\n    mINI::Instance()[kStreamNoneReaderDelayMS] = 20 * 1000;\n    mINI::Instance()[kMaxStreamWaitTimeMS] = 15 * 1000;\n    mINI::Instance()[kEnableVhost] = 0;\n    mINI::Instance()[kAddMuteAudio] = 1;\n    mINI::Instance()[kResetWhenRePlay] = 1;\n    mINI::Instance()[kPublishToHls] = 1;\n    mINI::Instance()[kPublishToMP4] = 0;\n    mINI::Instance()[kMergeWriteMS] = 0;\n    mINI::Instance()[kModifyStamp] = 0;\n    mINI::Instance()[kMediaServerId] = makeRandStr(16);\n    mINI::Instance()[kHlsDemand] = 0;\n    mINI::Instance()[kRtspDemand] = 0;\n    mINI::Instance()[kRtmpDemand] = 0;\n    mINI::Instance()[kTSDemand] = 0;\n    mINI::Instance()[kFMP4Demand] = 0;\n    mINI::Instance()[kEnableAudio] = 1;\n    mINI::Instance()[kCheckNvidiaDev] = 1;\n    mINI::Instance()[kEnableFFmpegLog] = 0;\n    mINI::Instance()[kWaitTrackReadyMS] = 10000;\n    mINI::Instance()[kWaitAddTrackMS] = 3000;\n    mINI::Instance()[kUnreadyFrameCache] = 100;\n    mINI::Instance()[kContinuePushMS] = 15 * 1000;\n});\n\n} // namespace General\n\n////////////HTTP配置///////////\nnamespace Http {\n#define HTTP_FIELD "http."\nconst string kSendBufSize = HTTP_FIELD "sendBufSize";\nconst string kMaxReqSize = HTTP_FIELD "maxReqSize";\nconst string kKeepAliveSecond = HTTP_FIELD "keepAliveSecond";\nconst string kCharSet = HTTP_FIELD "charSet";\nconst string kRootPath = HTTP_FIELD "rootPath";\nconst string kVirtualPath = HTTP_FIELD "virtualPath";\nconst string kNotFound = HTTP_FIELD "notFound";\nconst string kDirMenu = HTTP_FIELD "dirMenu";\nconst string kForbidCacheSuffix = HTTP_FIELD "forbidCacheSuffix";\nconst string kForwardedIpHeader = HTTP_FIELD "forwarded_ip_header";\n\nstatic onceToken token([]() {\n    mINI::Instance()[kSendBufSize] = 64 * 1024;\n    mINI::Instance()[kMaxReqSize] = 4 * 10240;\n    mINI::Instance()[kKeepAliveSecond] = 15;\n    mINI::Instance()[kDirMenu] = true;\n    mINI::Instance()[kVirtualPath] = "";\n\n#if defined(_WIN32)\n    mINI::Instance()[kCharSet] = "gb2312";\n#else\n    mINI::Instance()[kCharSet] = "utf-8";\n#endif\n\n    mINI::Instance()[kRootPath] = "./www";\n    mINI::Instance()[kNotFound] = StrPrinter << "<html>"\n                                                "<head><title>404 Not Found</title></head>"\n                                                "<body bgcolor=\\"white\\">"\n                                                "<center><h1>您访问的资源不存在！</h1></center>"\n                                                "<hr><center>"\n                                             << kServerName\n                                             << "</center>"\n                                                "</body>"\n                                                "</html>"\n                                             << endl;\n    mINI::Instance()[kForbidCacheSuffix] = "";\n    mINI::Instance()[kForwardedIpHeader] = "";\n});\n\n} // namespace Http\n\n////////////SHELL配置///////////\nnamespace Shell {\n#define SHELL_FIELD "shell."\nconst string kMaxReqSize = SHELL_FIELD "maxReqSize";\n\nstatic onceToken token([]() { mINI::Instance()[kMaxReqSize] = 1024; });\n} // namespace Shell\n\n////////////RTSP服务器配置///////////\nnamespace Rtsp {\n#define RTSP_FIELD "rtsp."\nconst string kAuthBasic = RTSP_FIELD "authBasic";\nconst string kHandshakeSecond = RTSP_FIELD "handshakeSecond";\nconst string kKeepAliveSecond = RTSP_FIELD "keepAliveSecond";\nconst string kDirectProxy = RTSP_FIELD "directProxy";\nconst string kLowLatency = RTSP_FIELD"lowLatency";\n\nstatic onceToken token([]() {\n    // 默认Md5方式认证\n    mINI::Instance()[kAuthBasic] = 0;\n    mINI::Instance()[kHandshakeSecond] = 15;\n    mINI::Instance()[kKeepAliveSecond] = 15;\n    mINI::Instance()[kDirectProxy] = 1;\n    mINI::Instance()[kLowLatency] = 0;\n});\n} // namespace Rtsp\n\n////////////RTMP服务器配置///////////\nnamespace Rtmp {\n#define RTMP_FIELD "rtmp."\nconst string kModifyStamp = RTMP_FIELD "modifyStamp";\nconst string kHandshakeSecond = RTMP_FIELD "handshakeSecond";\nconst string kKeepAliveSecond = RTMP_FIELD "keepAliveSecond";\n\nstatic onceToken token([]() {\n    mINI::Instance()[kModifyStamp] = false;\n    mINI::Instance()[kHandshakeSecond] = 15;\n    mINI::Instance()[kKeepAliveSecond] = 15;\n});\n} // namespace Rtmp\n\n////////////RTP配置///////////\nnamespace Rtp {\n#define RTP_FIELD "rtp."\n// RTP打包最大MTU,公网情况下更小\nconst string kVideoMtuSize = RTP_FIELD "videoMtuSize";\nconst string kAudioMtuSize = RTP_FIELD "audioMtuSize";\n// rtp包最大长度限制，单位是KB\nconst string kRtpMaxSize = RTP_FIELD "rtpMaxSize";\nnamespace MultiCast {\n#define MULTI_FIELD "multicast."\n//组播分配起始地址\n#define MULTI_ADDR_MIN (0xE00000FF + 10)\nconst char kAddrMin[] = MULTI_FIELD"addrMin";\n\n//组播分配截止地址\n#define MULTI_ADDR_MAX (0xEFFFFFFF)\nconst char kAddrMax[] = MULTI_FIELD"addrMax";\n\n//组播TTL\n#define MULTI_UDP_TTL 64\nconst char kUdpTTL[] = MULTI_FIELD"udpTTL";\n\nonceToken token([](){\n\tmINI::Instance()[kAddrMin] = MULTI_ADDR_MIN;\n\tmINI::Instance()[kAddrMax] = MULTI_ADDR_MAX;\n\tmINI::Instance()[kUdpTTL] = MULTI_UDP_TTL;\n},nullptr);\n\nconst string kAddrMin = MULTI_FIELD "addrMin";\n// 组播分配截止地址\nconst string kAddrMax = MULTI_FIELD "addrMax";\n// 组播TTL\nconst string kUdpTTL = MULTI_FIELD "udpTTL";\n\nstatic onceToken token([]() {\n    mINI::Instance()[kAddrMin] = "239.0.0.0";\n    mINI::Instance()[kAddrMax] = "239.255.255.255";\n    mINI::Instance()[kUdpTTL] = 64;\n});\n} // namespace MultiCast\n\n////////////录像配置///////////\nnamespace Record {\n#define RECORD_FIELD "record."\nconst string kAppName = RECORD_FIELD "appName";\nconst string kSampleMS = RECORD_FIELD "sampleMS";\nconst string kFileSecond = RECORD_FIELD "fileSecond";\nconst string kFilePath = RECORD_FIELD "filePath";\nconst string kFileBufSize = RECORD_FIELD "fileBufSize";\nconst string kFastStart = RECORD_FIELD "fastStart";\nconst string kFileRepeat = RECORD_FIELD "fileRepeat";\nconst string kMP4AsPlayer = RECORD_FIELD "mp4_as_player";\n\nstatic onceToken token([]() {\n    mINI::Instance()[kAppName] = "record";\n    mINI::Instance()[kSampleMS] = 500;\n    mINI::Instance()[kFileSecond] = 60 * 60;\n    mINI::Instance()[kFilePath] = "./www";\n    mINI::Instance()[kFileBufSize] = 64 * 1024;\n    mINI::Instance()[kFastStart] = false;\n    mINI::Instance()[kFileRepeat] = false;\n    mINI::Instance()[kMP4AsPlayer] = false;\n});\n} // namespace Record\n\n////////////HLS相关配置///////////\nnamespace Hls {\n#define HLS_FIELD "hls."\nconst string kSegmentDuration = HLS_FIELD "segDur";\nconst string kSegmentNum = HLS_FIELD "segNum";\nconst string kSegmentKeep = HLS_FIELD "segKeep";\nconst string kSegmentRetain = HLS_FIELD "segRetain";\nconst string kFileBufSize = HLS_FIELD "fileBufSize";\nconst string kFilePath = HLS_FIELD "filePath";\nconst string kBroadcastRecordTs = HLS_FIELD "broadcastRecordTs";\nconst string kDeleteDelaySec = HLS_FIELD "deleteDelaySec";\n\nstatic onceToken token([]() {\n    mINI::Instance()[kSegmentDuration] = 2;\n    mINI::Instance()[kSegmentNum] = 3;\n    mINI::Instance()[kSegmentKeep] = false;\n    mINI::Instance()[kSegmentRetain] = 5;\n    mINI::Instance()[kFileBufSize] = 64 * 1024;\n    mINI::Instance()[kFilePath] = "./www";\n    mINI::Instance()[kBroadcastRecordTs] = false;\n    mINI::Instance()[kDeleteDelaySec] = 10;\n});\n} // namespace Hls\n\n////////////Rtp代理相关配置///////////\nnamespace RtpProxy {\n#define RTP_PROXY_FIELD "rtp_proxy."\nconst string kDumpDir = RTP_PROXY_FIELD "dumpDir";\nconst string kTimeoutSec = RTP_PROXY_FIELD "timeoutSec";\nconst string kPortRange = RTP_PROXY_FIELD "port_range";\nconst string kH264PT = RTP_PROXY_FIELD "h264_pt";\nconst string kH265PT = RTP_PROXY_FIELD "h265_pt";\nconst string kPSPT = RTP_PROXY_FIELD "ps_pt";\nconst string kTSPT = RTP_PROXY_FIELD "ts_pt";\nconst string kOpusPT = RTP_PROXY_FIELD "opus_pt";\nconst string kG711UPT = RTP_PROXY_FIELD "g711u_pt";\nconst string kG711APT = RTP_PROXY_FIELD "g711a_pt";\n\nstatic onceToken token([]() {\n    mINI::Instance()[kDumpDir] = "";\n    mINI::Instance()[kTimeoutSec] = 15;\n    mINI::Instance()[kPortRange] = "30000-35000";\n    mINI::Instance()[kH264PT] = 98;\n    mINI::Instance()[kH265PT] = 99;\n    mINI::Instance()[kPSPT] = 96;\n    mINI::Instance()[kTSPT] = 33;\n    mINI::Instance()[kOpusPT] = 100;\n    mINI::Instance()[kG711UPT] = 0;\n    mINI::Instance()[kG711APT] = 8;\n});\n} // namespace RtpProxy\n\nnamespace Client {\nconst string kNetAdapter = "net_adapter";\nconst string kRtpType = "rtp_type";\nconst string kRtspUser = "rtsp_user";\nconst string kRtspPwd = "rtsp_pwd";\nconst string kRtspPwdIsMD5 = "rtsp_pwd_md5";\nconst string kTimeoutMS = "protocol_timeout_ms";\nconst string kMediaTimeoutMS = "media_timeout_ms";\nconst string kBeatIntervalMS = "beat_interval_ms";\nconst string kBenchmarkMode = "benchmark_mode";\nconst string kWaitTrackReady = "wait_track_ready";\nconst string kPlayTrack = "play_track";\n} // namespace Client\n\n} // namespace mediakit\n\n#ifdef ENABLE_MEM_DEBUG\n\nextern "C" {\nextern void *__real_malloc(size_t);\nextern void __real_free(void *);\nextern void *__real_realloc(void *ptr, size_t c);\nvoid *__wrap_malloc(size_t c);\nvoid __wrap_free(void *ptr);\nvoid *__wrap_calloc(size_t __nmemb, size_t __size);\nvoid *__wrap_realloc(void *ptr, size_t c);\n}\n\n#define BLOCK_TYPES 16\n#define MIN_BLOCK_SIZE 128\n\nstatic int get_mem_block_type(size_t c) {\n    int ret = 0;\n    while (c > MIN_BLOCK_SIZE && ret + 1 < BLOCK_TYPES) {\n        c >>= 1;\n        ++ret;\n    }\n    return ret;\n}\n\nstd::vector<size_t> getBlockTypeSize() {\n    std::vector<size_t> ret;\n    ret.resize(BLOCK_TYPES);\n    size_t block_size = MIN_BLOCK_SIZE;\n    for (auto i = 0; i < BLOCK_TYPES; ++i) {\n        ret[i] = block_size;\n        block_size <<= 1;\n    }\n    return ret;\n}\n\nclass MemThreadInfo {\npublic:\n    using Ptr = std::shared_ptr<MemThreadInfo>;\n    atomic<uint64_t> mem_usage { 0 };\n    atomic<uint64_t> mem_block { 0 };\n    atomic<uint64_t> mem_block_map[BLOCK_TYPES];\n\n    static MemThreadInfo *Instance(bool is_thread_local) {\n        if (!is_thread_local) {\n            static auto instance = new MemThreadInfo(is_thread_local);\n            return instance;\n        }\n        static auto thread_local instance = new MemThreadInfo(is_thread_local);\n        return instance;\n    }\n\n    ~MemThreadInfo() {\n        // printf("%s %d\\r\\n", __FUNCTION__, (int) _is_thread_local);\n    }\n\n    MemThreadInfo(bool is_thread_local) {\n        _is_thread_local = is_thread_local;\n        if (_is_thread_local) {\n            // 确保所有线程退出后才能释放全局内存统计器\n            total_mem = Instance(false);\n        }\n        // printf("%s %d\\r\\n", __FUNCTION__, (int) _is_thread_local);\n    }\n\n    void *operator new(size_t sz) { return __real_malloc(sz); }\n\n    void operator delete(void *ptr) { __real_free(ptr); }\n\n    void addBlock(size_t c) {\n        if (total_mem) {\n            total_mem->addBlock(c);\n        }\n        mem_usage += c;\n        ++mem_block_map[get_mem_block_type(c)];\n        ++mem_block;\n    }\n\n    void delBlock(size_t c) {\n        if (total_mem) {\n            total_mem->delBlock(c);\n        }\n        mem_usage -= c;\n        --mem_block_map[get_mem_block_type(c)];\n        if (0 == --mem_block) {\n            delete this;\n        }\n    }\n\nprivate:\n    bool _is_thread_local;\n    MemThreadInfo *total_mem = nullptr;\n};\n\nclass MemThreadInfoLocal {\npublic:\n    MemThreadInfoLocal() {\n        ptr = MemThreadInfo::Instance(true);\n        ptr->addBlock(1);\n    }\n\n    ~MemThreadInfoLocal() { ptr->delBlock(1); }\n\n    MemThreadInfo *get() const { return ptr; }\n\nprivate:\n    MemThreadInfo *ptr;\n};\n\n// 该变量主要确保线程退出后才能释放MemThreadInfo变量\nstatic thread_local MemThreadInfoLocal s_thread_mem_info;\n\nuint64_t getTotalMemUsage() {\n    return MemThreadInfo::Instance(false)->mem_usage.load();\n}\n\nuint64_t getTotalMemBlock() {\n    return MemThreadInfo::Instance(false)->mem_block.load();\n}\n\nuint64_t getTotalMemBlockByType(int type) {\n    assert(type < BLOCK_TYPES);\n    return MemThreadInfo::Instance(false)->mem_block_map[type].load();\n}\n\nuint64_t getThisThreadMemUsage() {\n    return MemThreadInfo::Instance(true)->mem_usage.load();\n}\n\nuint64_t getThisThreadMemBlock() {\n    return MemThreadInfo::Instance(true)->mem_block.load();\n}\n\nuint64_t getThisThreadMemBlockByType(int type) {\n    assert(type < BLOCK_TYPES);\n    return MemThreadInfo::Instance(true)->mem_block_map[type].load();\n}\n\nclass MemCookie {\npublic:\n    static constexpr uint32_t kMagic = 0xFEFDFCFB;\n    uint32_t magic;\n    uint32_t size;\n    MemThreadInfo *alloc_info;\n    char ptr;\n};\n\n#define MEM_OFFSET offsetof(MemCookie, ptr)\n\n#if (defined(__linux__) && !defined(ANDROID)) || defined(__MACH__)\n#define MAX_STACK_FRAMES 128\n#define MEM_WARING\n#include <execinfo.h>\n#include <limits.h>\n#include <sys/resource.h>\n#include <sys/wait.h>\n\nstatic void print_mem_waring(size_t c) {\n    void *array[MAX_STACK_FRAMES];\n    int size = backtrace(array, MAX_STACK_FRAMES);\n    char **strings = backtrace_symbols(array, size);\n    printf("malloc big memory:%d, back trace:\\r\\n", (int)c);\n    for (int i = 0; i < size; ++i) {\n        printf("[%d]: %s\\r\\n", i, strings[i]);\n    }\n    __real_free(strings);\n}\n#endif\n\nstatic void init_cookie(MemCookie *cookie, size_t c) {\n    cookie->magic = MemCookie::kMagic;\n    cookie->size = c;\n    cookie->alloc_info = s_thread_mem_info.get();\n    cookie->alloc_info->addBlock(c);\n\n#if defined(MEM_WARING)\n    static auto env = getenv("MEM_WARN_SIZE");\n    static size_t s_mem_waring_size = atoll(env ? env : "0");\n    if (s_mem_waring_size > 1024 && c >= s_mem_waring_size) {\n        print_mem_waring(c);\n    }\n#endif\n}\n\nstatic void un_init_cookie(MemCookie *cookie) {\n    cookie->alloc_info->delBlock(cookie->size);\n}\n\nvoid *__wrap_malloc(size_t c) {\n    c += MEM_OFFSET;\n    auto cookie = (MemCookie *)__real_malloc(c);\n    if (cookie) {\n        init_cookie(cookie, c);\n        return &cookie->ptr;\n    }\n    return nullptr;\n}\n\nvoid __wrap_free(void *ptr) {\n    if (!ptr) {\n        return;\n    }\n    auto cookie = (MemCookie *)((char *)ptr - MEM_OFFSET);\n    if (cookie->magic != MemCookie::kMagic) {\n        __real_free(ptr);\n        return;\n    }\n    un_init_cookie(cookie);\n    __real_free(cookie);\n}\n\nvoid *__wrap_calloc(size_t __nmemb, size_t __size) {\n    auto size = __nmemb * __size;\n    auto ret = malloc(size);\n    if (ret) {\n        memset(ret, 0, size);\n    }\n    return ret;\n}\n\nvoid *__wrap_realloc(void *ptr, size_t c) {\n    if (!ptr) {\n        return malloc(c);\n    }\n\n    auto cookie = (MemCookie *)((char *)ptr - MEM_OFFSET);\n    if (cookie->magic != MemCookie::kMagic) {\n        return __real_realloc(ptr, c);\n    }\n\n    un_init_cookie(cookie);\n    c += MEM_OFFSET;\n    cookie = (MemCookie *)__real_realloc(cookie, c);\n    if (cookie) {\n        init_cookie(cookie, c);\n        return &cookie->ptr;\n    }\n    return nullptr;\n}\n\nvoid *operator new(std::size_t size) {\n    auto ret = malloc(size);\n    if (ret) {\n        return ret;\n    }\n    throw std::bad_alloc();\n}\n\nvoid operator delete(void *ptr) noexcept {\n    free(ptr);\n}\n\nvoid operator delete(void *ptr, std::size_t) noexcept {\n    free(ptr);\n}\n\nvoid *operator new[](std::size_t size) {\n    auto ret = malloc(size);\n    if (ret) {\n        return ret;\n    }\n    throw std::bad_alloc();\n}\n\nvoid operator delete[](void *ptr) noexcept {\n    free(ptr);\n}\n\nvoid operator delete[](void *ptr, std::size_t) noexcept {\n    free(ptr);\n}\n#endif\n', 'message': '组播地址改成字符串\n', 'author_name': 'xiongziliang', 'lang': 'cpp'}