Commit 6ede6a7f by 李维杰

增加日志

parent 8ddb3bac
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{5AD086E3-FAFF-4992-9204-DC166A2F3F6A}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>livegetpushpulladdress</RootNamespace>
<WindowsTargetPlatformVersion>10.0.18362.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<UseOfMfc>Static</UseOfMfc>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>../thirdparty/curl/include;../thirdparty/jsoncpp;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>../thirdparty/curl/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>../thirdparty/curl/include;../thirdparty/jsoncpp;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>../thirdparty/curl/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\thirdparty\curl\http_client.cpp" />
<ClCompile Include="..\thirdparty\curl\http_request.cpp" />
<ClCompile Include="..\thirdparty\jsoncpp\src\json_reader.cpp" />
<ClCompile Include="..\thirdparty\jsoncpp\src\json_value.cpp" />
<ClCompile Include="..\thirdparty\jsoncpp\src\json_writer.cpp" />
<ClCompile Include="live_get_push_pull_address.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\thirdparty\curl\http_client.h" />
<ClInclude Include="..\thirdparty\curl\http_request.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{5AD086E3-FAFF-4992-9204-DC166A2F3F6A}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>livegetpushpulladdress</RootNamespace>
<WindowsTargetPlatformVersion>10.0.22000.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<UseOfMfc>Static</UseOfMfc>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>../thirdparty/curl/include;../thirdparty/jsoncpp;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>../thirdparty/curl/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>../thirdparty/curl/include;../thirdparty/jsoncpp;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>../thirdparty/curl/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\thirdparty\curl\http_client.cpp" />
<ClCompile Include="..\thirdparty\curl\http_request.cpp" />
<ClCompile Include="..\thirdparty\jsoncpp\src\json_reader.cpp" />
<ClCompile Include="..\thirdparty\jsoncpp\src\json_value.cpp" />
<ClCompile Include="..\thirdparty\jsoncpp\src\json_writer.cpp" />
<ClCompile Include="live_get_push_pull_address.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\thirdparty\curl\http_client.h" />
<ClInclude Include="..\thirdparty\curl\http_request.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
\ No newline at end of file
#include "http_client.h"
#include <winsock.h>
#include <sstream>
#include "curl/curl.h"
#include "json/json.h"
#pragma comment(lib, "libcurl.lib")
static const std::string kUrl = "http://test-api.live.offcncloud.com/api/v1/board";
ZgHttpClient::ZgHttpClient()
:curl_(NULL),
file_(NULL)
{
curl_ = curl_easy_init();
}
ZgHttpClient::~ZgHttpClient()
{
curl_easy_cleanup(curl_);
curl_ = NULL;
}
size_t ZgHttpClient::Response(void *ptr, size_t size, size_t nmemb)
{
std::string message((const char*)ptr, (size_t)size * nmemb);
sResult_ = sResult_ + message;
return size * nmemb;
}
size_t ZgHttpClient::cbResponse(void *ptr, size_t size, size_t nmemb, void *userdata)
{
return ((ZgHttpClient *)userdata)->Response(ptr, size, nmemb);
}
static
int my_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
{
return 0;
}
bool ZgHttpClient::Post(std::string request, std::string params, std::map<std::string, std::string> headers, std::string &response, std::string context_type)
{
sError_ = "";
curl_easy_setopt(curl_, CURLOPT_URL, request.c_str());
struct curl_slist *headers_list = NULL;
//headers_list = curl_slist_append(headers_list, "Content-Type:application/json;charset=UTF-8");
//headers_list = curl_slist_append(headers_list, "Content-Type:application/x-www-form-urlencoded");
headers_list = curl_slist_append(headers_list, context_type.c_str());
std::map<std::string, std::string>::iterator itor;
for (itor = headers.begin(); itor != headers.end(); itor++)
{
std::string item = itor->first + ":" + itor->second;
headers_list = curl_slist_append(headers_list, item.c_str());
}
curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headers_list);
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, false); //disable https
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, false);
curl_easy_setopt(curl_, CURLOPT_POST, 1);
curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, params.c_str());
//设置接收数据的处理函数
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, cbResponse);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curl_, CURLOPT_TIMEOUT, 5);
CURLcode res = curl_easy_perform(curl_);
curl_slist_free_all(headers_list);
long nCode = 0;
res = curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &nCode);
if (nCode != 200)
{
response = sResult_;
sError_ = "";
return false;
}
response = sResult_;
sError_ = "";
return true;
}
bool ZgHttpClient::Get(std::string &url, std::list<std::string> &headerlist, std::string &result, std::string &sError)
{
curl_easy_setopt(curl_, CURLOPT_URL ,url.c_str());
curl_easy_setopt(curl_, CURLOPT_POST, 0);
struct curl_slist *headers = NULL;
if (headerlist.size() > 0)
{
std::list<std::string>::iterator itor;
for (itor = headerlist.begin(); itor != headerlist.end(); itor++)
{
headers = curl_slist_append(headers, itor->c_str());
}
if (headers != NULL)
{
curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headers);
}
}
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, false); //disable https
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, false);
curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl_, CURLOPT_READFUNCTION, NULL);
std::stringstream out;
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, cbResponse);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curl_, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_, CURLOPT_DEBUGFUNCTION, my_trace);
curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT, 50); // set transport and time out time
curl_easy_setopt(curl_, CURLOPT_TIMEOUT, 50);
CURLcode res = curl_easy_perform(curl_);
curl_slist_free_all(headers);
if (res != CURLE_OK)
{
sError = "post request failed\n";
sError_ = "";
return false;
}
std::string returnValue = out.str();
long nCode = 0;
res = curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &nCode);
if (nCode != 200)
{
sError = sError_;
sError_ = "";
return false;
}
result = sResult_;
sResult_ = "";
sError_ = "";
return true;
}
std::string ZgHttpClient::buildResponse(int code, std::string msg)
{
Json::Value root;
Json::StreamWriterBuilder builder;
builder["commentStyle"] = "None"; //固定这么写
builder["indentation"] = " "; //固定这么写
root["code"] = code;
root["data"] = msg.c_str();
return Json::writeString(builder, root);
}
int ZgHttpClient::cbProgressCallback(void *userdata, double dltotal, double dlnow, double ultotal, double ulnow)
{
return ((ZgHttpClient *)userdata)->ProgressCallback(dltotal, dlnow, ultotal, ulnow);
}
int ZgHttpClient::ProgressCallback(double dltotal, double dlnow, double ultotal, double ulnow)
{
return 0;
}
size_t ZgHttpClient::cbDownLoadCallback(void *ptr, size_t size, size_t nmemb, void *userdata)
{
return ((ZgHttpClient *)userdata)->DownLoadCallback(ptr, size, nmemb);
}
size_t ZgHttpClient::DownLoadCallback(void *ptr, size_t size, size_t nmemb)
{
size_t nWrite = fwrite(ptr, size, nmemb, file_);
return nWrite;
}
bool ZgHttpClient::DownLoad(std::string url, std::string filename, std::string &sError)
{
file_full_path_ = filename;
if (file_)
{
fclose(file_);
file_ = NULL;
}
file_ = fopen(file_full_path_.c_str(), "w");
if (file_)
{
fclose(file_);
file_ = NULL;
}
file_ = fopen(file_full_path_.c_str(), "ab+");
curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_, CURLOPT_POST, 0);
struct curl_slist *headers = NULL;
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, false); //disable https
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, false);
curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl_, CURLOPT_READFUNCTION, NULL);
std::stringstream out;
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, cbDownLoadCallback);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curl_, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT, 5); // set transport and time out time
curl_easy_setopt(curl_, CURLOPT_TIMEOUT, 5);
CURLcode res = curl_easy_perform(curl_);
curl_slist_free_all(headers);
if (res != CURLE_OK)
{
fclose(file_);
file_ = NULL;
sError = "post request failed\n";
sError_ = "";
return false;
}
fclose(file_);
file_ = NULL;
sResult_ = "";
sError_ = "";
return true;
#include "http_client.h"
#include <winsock.h>
#include <sstream>
#include "curl/curl.h"
#include "json/json.h"
#pragma comment(lib, "libcurl.lib")
//static const std::string kUrl = "http://test-api.live.offcncloud.com/api/v1/board";
static const std::string kUrl = "http://api.live.offcncloud.com/api/v1/board";
ZgHttpClient::ZgHttpClient()
:curl_(NULL),
file_(NULL)
{
curl_ = curl_easy_init();
}
ZgHttpClient::~ZgHttpClient()
{
curl_easy_cleanup(curl_);
curl_ = NULL;
}
size_t ZgHttpClient::Response(void *ptr, size_t size, size_t nmemb)
{
std::string message((const char*)ptr, (size_t)size * nmemb);
sResult_ = sResult_ + message;
return size * nmemb;
}
size_t ZgHttpClient::cbResponse(void *ptr, size_t size, size_t nmemb, void *userdata)
{
return ((ZgHttpClient *)userdata)->Response(ptr, size, nmemb);
}
static
int my_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
{
return 0;
}
bool ZgHttpClient::Post(std::string request, std::string params, std::map<std::string, std::string> headers, std::string &response, std::string context_type)
{
sError_ = "";
curl_easy_setopt(curl_, CURLOPT_URL, request.c_str());
struct curl_slist *headers_list = NULL;
//headers_list = curl_slist_append(headers_list, "Content-Type:application/json;charset=UTF-8");
//headers_list = curl_slist_append(headers_list, "Content-Type:application/x-www-form-urlencoded");
headers_list = curl_slist_append(headers_list, context_type.c_str());
std::map<std::string, std::string>::iterator itor;
for (itor = headers.begin(); itor != headers.end(); itor++)
{
std::string item = itor->first + ":" + itor->second;
headers_list = curl_slist_append(headers_list, item.c_str());
}
curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headers_list);
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, false); //disable https
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, false);
curl_easy_setopt(curl_, CURLOPT_POST, 1);
curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, params.c_str());
//设置接收数据的处理函数
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, cbResponse);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curl_, CURLOPT_TIMEOUT, 5);
CURLcode res = curl_easy_perform(curl_);
curl_slist_free_all(headers_list);
long nCode = 0;
res = curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &nCode);
if (nCode != 200)
{
response = sResult_;
sError_ = "";
return false;
}
response = sResult_;
sError_ = "";
return true;
}
bool ZgHttpClient::Get(std::string &url, std::list<std::string> &headerlist, std::string &result, std::string &sError)
{
curl_easy_setopt(curl_, CURLOPT_URL ,url.c_str());
curl_easy_setopt(curl_, CURLOPT_POST, 0);
struct curl_slist *headers = NULL;
if (headerlist.size() > 0)
{
std::list<std::string>::iterator itor;
for (itor = headerlist.begin(); itor != headerlist.end(); itor++)
{
headers = curl_slist_append(headers, itor->c_str());
}
if (headers != NULL)
{
curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headers);
}
}
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, false); //disable https
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, false);
curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl_, CURLOPT_READFUNCTION, NULL);
std::stringstream out;
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, cbResponse);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curl_, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_, CURLOPT_DEBUGFUNCTION, my_trace);
curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT, 50); // set transport and time out time
curl_easy_setopt(curl_, CURLOPT_TIMEOUT, 50);
CURLcode res = curl_easy_perform(curl_);
curl_slist_free_all(headers);
if (res != CURLE_OK)
{
sError = "post request failed\n";
sError_ = "";
return false;
}
std::string returnValue = out.str();
long nCode = 0;
res = curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &nCode);
if (nCode != 200)
{
sError = sError_;
sError_ = "";
return false;
}
result = sResult_;
sResult_ = "";
sError_ = "";
return true;
}
std::string ZgHttpClient::buildResponse(int code, std::string msg)
{
Json::Value root;
Json::StreamWriterBuilder builder;
builder["commentStyle"] = "None"; //固定这么写
builder["indentation"] = " "; //固定这么写
root["code"] = code;
root["data"] = msg.c_str();
return Json::writeString(builder, root);
}
int ZgHttpClient::cbProgressCallback(void *userdata, double dltotal, double dlnow, double ultotal, double ulnow)
{
return ((ZgHttpClient *)userdata)->ProgressCallback(dltotal, dlnow, ultotal, ulnow);
}
int ZgHttpClient::ProgressCallback(double dltotal, double dlnow, double ultotal, double ulnow)
{
return 0;
}
size_t ZgHttpClient::cbDownLoadCallback(void *ptr, size_t size, size_t nmemb, void *userdata)
{
return ((ZgHttpClient *)userdata)->DownLoadCallback(ptr, size, nmemb);
}
size_t ZgHttpClient::DownLoadCallback(void *ptr, size_t size, size_t nmemb)
{
size_t nWrite = fwrite(ptr, size, nmemb, file_);
return nWrite;
}
bool ZgHttpClient::DownLoad(std::string url, std::string filename, std::string &sError)
{
file_full_path_ = filename;
if (file_)
{
fclose(file_);
file_ = NULL;
}
file_ = fopen(file_full_path_.c_str(), "w");
if (file_)
{
fclose(file_);
file_ = NULL;
}
file_ = fopen(file_full_path_.c_str(), "ab+");
curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_, CURLOPT_POST, 0);
struct curl_slist *headers = NULL;
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, false); //disable https
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, false);
curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl_, CURLOPT_READFUNCTION, NULL);
std::stringstream out;
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, cbDownLoadCallback);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, this);
curl_easy_setopt(curl_, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT, 5); // set transport and time out time
curl_easy_setopt(curl_, CURLOPT_TIMEOUT, 5);
CURLcode res = curl_easy_perform(curl_);
curl_slist_free_all(headers);
if (res != CURLE_OK)
{
fclose(file_);
file_ = NULL;
sError = "post request failed\n";
sError_ = "";
return false;
}
fclose(file_);
file_ = NULL;
sResult_ = "";
sError_ = "";
return true;
}
\ No newline at end of file
#include "http_request.h"
#include "http_client.h"
#include "json/json.h"
#include <map>
#include <list>
HttpRequest *HttpRequest::instance_ = nullptr;
HttpRequest *HttpRequest::GetInstance()
{
if (instance_ == nullptr)
{
instance_ = new HttpRequest();
}
return instance_;
}
bool ParseJson(std::string message, Json::Value &root)
{
Json::CharReaderBuilder readerBuilder;
std::unique_ptr<Json::CharReader> const reader(readerBuilder.newCharReader());
const char *start_pos = message.c_str();
std::string err;
if (!reader->parse(start_pos, start_pos + message.length(), &root, &err))
{
return false;
}
return true;
}
bool HttpRequest::Init()
{
return HttpRequest::GetInstance()->Load();
}
bool HttpRequest::LogIn(std::string userid, std::string password, std::string &token, std::string &roomid)
{
ZgHttpClient client;
std::string params;
params = "nickname=" + userid + "&password=" + password + "&uuid=" + "{eae23299-d280-4be2-92a7-8494e18c799b}";
std::map<std::string, std::string> headers;
headers["zgl-clienttype"] = "OffcnLiveLR";
headers["zgl-systemtype"] = "Windows";
headers["zgl-systemversion"] = "10";
headers["zgl-clientversion"] = "3.1.1";
//"https://test-api.live.offcncloud.com/api/v1/users"
std::string req = HttpRequest::GetInstance()->web_server_url_ + "/api/v1/users";
std::string response;
if (!client.Post(req, params, headers, response))
{
return false;
}
Json::Value root;
if (!ParseJson(response, root)) return false;
int code = root["code"].asInt();
if (code != 0) return false;
if (!root["data"]) return false;
Json::Value data = root["data"];
if (!data["access_token"] || !data["room_id"]) return false;
token = data["access_token"].asString();
roomid = data["room_id"].asString();
return true;
}
std::string HttpRequest::GetWebServerUrl()
{
return HttpRequest::GetInstance()->web_server_url_;
}
bool HttpRequest::Load()
{
FILE *file = fopen("./config", "r");
if (file == NULL) return false;
long fileSize = 0;
fseek(file, 0, SEEK_END);
fileSize = ftell(file);
if (fileSize <= 0) return false;
char *p = new char[fileSize];
rewind(file);
long ret = fread(p, 1, fileSize, file);
if (ret <= 0)
{
delete p;
fclose(file);
return false;
}
std::string message(p);
delete p;
Json::Value root;
Json::CharReaderBuilder readerBuilder;
std::unique_ptr<Json::CharReader> const reader(readerBuilder.newCharReader());
const char *start_pos = message.c_str();
std::string err;
if (!reader->parse(start_pos, start_pos + message.length(), &root, &err))
{
return false;
}
if (root["web_server_url"])
{
web_server_url_ = root["web_server_url"].asString();
}
else
{
return false;
}
return true;
}
#include "http_request.h"
#include "http_client.h"
#include "json/json.h"
#include <map>
#include <list>
HttpRequest *HttpRequest::instance_ = nullptr;
HttpRequest *HttpRequest::GetInstance()
{
if (instance_ == nullptr)
{
instance_ = new HttpRequest();
}
return instance_;
}
bool ParseJson(std::string message, Json::Value &root)
{
Json::CharReaderBuilder readerBuilder;
std::unique_ptr<Json::CharReader> const reader(readerBuilder.newCharReader());
const char *start_pos = message.c_str();
std::string err;
if (!reader->parse(start_pos, start_pos + message.length(), &root, &err))
{
return false;
}
return true;
}
bool HttpRequest::Init()
{
return HttpRequest::GetInstance()->Load();
}
bool HttpRequest::LogIn(std::string userid, std::string password, std::string &token, std::string &roomid)
{
ZgHttpClient client;
std::string params;
params = "nickname=" + userid + "&password=" + password + "&uuid=" + "{eae23299-d280-4be2-92a7-8494e18c799b}";
std::map<std::string, std::string> headers;
headers["zgl-clienttype"] = "OffcnLiveLR";
headers["zgl-systemtype"] = "Windows";
headers["zgl-systemversion"] = "10";
headers["zgl-clientversion"] = "3.1.1";
//"https://test-api.live.offcncloud.com/api/v1/users"
HttpRequest::GetInstance()->web_server_url_ = "https://api.live.offcncloud.com";
std::string req = HttpRequest::GetInstance()->web_server_url_ + "/api/v1/users";
std::string response;
if (!client.Post(req, params, headers, response))
{
return false;
}
Json::Value root;
if (!ParseJson(response, root)) return false;
int code = root["code"].asInt();
if (code != 0) return false;
if (!root["data"]) return false;
Json::Value data = root["data"];
if (!data["access_token"] || !data["room_id"]) return false;
token = data["access_token"].asString();
roomid = data["room_id"].asString();
return true;
}
std::string HttpRequest::GetWebServerUrl()
{
return HttpRequest::GetInstance()->web_server_url_;
}
bool HttpRequest::Load()
{
FILE *file = fopen("./config", "r");
if (file == NULL) return false;
long fileSize = 0;
fseek(file, 0, SEEK_END);
fileSize = ftell(file);
if (fileSize <= 0) return false;
char *p = new char[fileSize];
rewind(file);
long ret = fread(p, 1, fileSize, file);
if (ret <= 0)
{
delete p;
fclose(file);
return false;
}
std::string message(p);
delete p;
Json::Value root;
Json::CharReaderBuilder readerBuilder;
std::unique_ptr<Json::CharReader> const reader(readerBuilder.newCharReader());
const char *start_pos = message.c_str();
std::string err;
if (!reader->parse(start_pos, start_pos + message.length(), &root, &err))
{
return false;
}
if (root["web_server_url"])
{
web_server_url_ = root["web_server_url"].asString();
}
else
{
return false;
}
return true;
}
bool HttpRequest::GetPullUrl(std::string token, std::map<std::string, std::string> &urls)
{
ZgHttpClient client;
......
#include "filereader.h"
#ifdef __cplusplus
extern "C"
{
#endif
#include "libavformat/avformat.h"
#ifdef __cplusplus
};
#endif
#define LogWrite
#define INF
CFileReader::CFileReader()
{
av_register_all();
avformat_network_init();
// 设置编解码库日志回调函数
av_log_set_callback(NULL);
resetReader();
}
CFileReader::~CFileReader()
{}
void CFileReader::resetReader()
{
m_bNetFile = false;
m_bEof = false;
m_nVideoIndex = -1;
m_nAudioIndex = -1;
m_inVideoStream = NULL;
m_inAudioStream = NULL;
m_inFormatContext = NULL;
}
int CFileReader::OpenFile(std::string filePath, std::string key/* = ""*/, int nTimeOutValue)
{
unsigned char *tmp;
resetReader();
const char *p = filePath.c_str();
if (filePath.length() > 4 && (p[0] == 'h' && p[1] == 't' && p[2] == 't' && p[3] == 'p'))
{
m_bNetFile = true;
}
aes_128_key_value_ = key;
m_inFormatContext = avformat_alloc_context();
if(!m_inFormatContext)
{
//LogWrite("OpenFile failed::LastError = %d, filePath = %s", CUtilityMethod::GetErrorNo(), filePath.c_str());
return -1;
}
//支持hls加密文件的播放
const AVClass *c;
const AVOption *o = NULL;
AVDictionary *format_opts = NULL;
if (aes_128_key_value_.length() > 0)
{
av_dict_set(&format_opts, "allowed_extensions", "ALL", AV_DICT_MATCH_CASE);
av_dict_set_int(&format_opts, "cryptkey_extend_len", 16, AV_DICT_MATCH_CASE);
av_dict_set(&format_opts, "cryptkey_extend", aes_128_key_value_.c_str(), AV_DICT_MATCH_CASE);
}
//禁用 HLS 使用多个链接拉取ts文件逻辑,多链接拉取有bug例如,正在播放第二个文件的中间时 取拉取第四个文件,拉取失败时会导致第二个文件剩下的数据无法播放
av_dict_set(&format_opts, "http_multiple", "0", 0);
int nRet = avformat_open_input(&m_inFormatContext, filePath.c_str(), 0, &format_opts);
if (nRet!=0)
{
char szBuffer[256] = { 0 };
av_make_error_string(szBuffer, 256, nRet);
//LogWrite("OpenFile failed:avformat_open_input return = %d, LastError = %d, filePath = %s", nRet, CUtilityMethod::GetErrorNo(), filePath.c_str());
goto err;
}
nRet = avformat_find_stream_info(m_inFormatContext, 0);
if (nRet < 0)
{
//LogWrite("OpenFile failed:avformat_find_stream_info return = %d, LastError = %d, filePath = %s", nRet, CUtilityMethod::GetErrorNo(), filePath.c_str());
goto err;
}
for(int i = 0; i < m_inFormatContext->nb_streams; i++)
{
if((m_inFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
(m_inFormatContext->streams[i]->codec->codec_id == AV_CODEC_ID_H264))
{
m_nVideoIndex = i;
m_inVideoStream = m_inFormatContext->streams[i];
}
if(m_inFormatContext->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO)
{
m_nAudioIndex = i;
m_inAudioStream = m_inFormatContext->streams[i];
}
}
//必须包含音频
if(m_nVideoIndex < 0 && m_nAudioIndex < 0)
{
//LogWrite("OpenFile failed:videoindex = %d, audioindex = %d", m_nVideoIndex, m_nAudioIndex);
goto err;
}
return 0;
err:
CloseFile();
return -1;
}
int CFileReader::CloseFile()
{
if(m_inFormatContext)
{
avformat_close_input(&m_inFormatContext);
avformat_free_context(m_inFormatContext);
m_inFormatContext = NULL;
}
return 0;
}
int CFileReader::ReadFile(AVPacket &pkt)
{
int nRet = av_read_frame(m_inFormatContext, &pkt);
if(nRet == AVERROR_EOF)
{
//LogWrite(INF, "ReadFile failed, return value = %d, LastError = %d", nRet, CUtilityMethod::GetErrorNo());
return -1;
}
return nRet;
}
int CFileReader::PauseRead(bool bPause)
{
int nRet = 0;
if (!IsNetFile()) return 0;
if (bPause)
{
nRet = av_read_pause(m_inFormatContext);
}
else
{
nRet = av_read_play(m_inFormatContext);
}
return nRet;
}
double CFileReader::GetFileTimeLength()
{
if(m_inFormatContext)
{
return (m_inFormatContext->duration)/1000000;
}
return 0;
}
int CFileReader::GetVideoSize(int &nWidth, int &nHeight)
{
if (m_nVideoIndex >= 0 && m_inVideoStream->codec)
{
nWidth = m_inVideoStream->codec->width;
nHeight = m_inVideoStream->codec->height;
}
else
{
nWidth = 0;
nHeight = 0;
}
return 0;
}
float CFileReader::GetVideoFrameRate()
{
if (m_nVideoIndex >= 0)
{
float num = m_inVideoStream->avg_frame_rate.num;
float den = m_inVideoStream->avg_frame_rate.den;
float tmp = num / den + 0.5;
return num / den + 0.5;
}
return 0;
}
int CFileReader::SeekFile(int streamIndex, long long minTs, long long timestamp_us, long long maxTs, int flags)
{
avformat_flush(m_inFormatContext);
return avformat_seek_file(m_inFormatContext, streamIndex, minTs, timestamp_us, maxTs, flags);
}
AVCodecID CFileReader::GetVideoCodecID()
{
if(m_nVideoIndex >= 0 && m_inVideoStream && m_inVideoStream->codec)
{
return m_inVideoStream->codec->codec_id;
}
return AV_CODEC_ID_NONE;
}
AVCodecID CFileReader::GetAudioCodecID()
{
if(m_inAudioStream && m_inAudioStream->codec)
{
return m_inAudioStream->codec->codec_id;
}
return AV_CODEC_ID_NONE;
}
int CFileReader::GetAudioRawFrameSize()
{
return 0;
}
int CFileReader::GetVideoRawFrameSize(int &width, int &height)
{
width = m_inVideoStream->codec->width;
height = m_inVideoStream->codec->height;
return 0;
}
bool CFileReader::IsAnnexb4Video()
{
//m3u8的ts中, extradata = NULL
if (!m_inVideoStream->codec->extradata || m_inVideoStream->codec->extradata[0] == 0)
{
return true;
}
return false;
}
bool CFileReader::IsVideoPacketNeedDecode(char *ptr)
{
char nType = GetNaluType(ptr, IsAnnexb4Video());
//m3u8的ts中, extradata = NULL, sps和pps跟随数据一起发来,所以需要解码这种类型的sps和pps
/*if ((nType == 7 || nType == 8) && m_inVideoStream->codec->extradata)
{
return false;
}
if (nType == 9)
{
return false;
}*/
if (nType == 6)
{
char subType = GetSeiSubType(ptr, IsAnnexb4Video());
if (subType != 5)
{
return false;
}
}
return true;
}
char CFileReader::GetNaluType(char *ptr, bool isAnnexb)
{
if (!isAnnexb)
{
return (*(ptr + 4) & 0x1f);
}
if (ptr[0] == 0 && ptr[1] == 0 && ptr[2] == 1) //寻找0x000001
{
return (*(ptr + 3) & 0x1f);
}
else if (ptr[0] == 0 && ptr[1] == 0 && ptr[2] == 0 && ptr[3] == 1) //寻找0x00000001
{
return (*(ptr + 4) & 0x1f);
}
return 0;
}
char CFileReader::GetSeiSubType(char *ptr, bool isAnnexb)
{
if (!isAnnexb)
{
return *(ptr + 5);
}
if (ptr[0] == 0 && ptr[1] == 0 && ptr[2] == 1) //寻找0x000001
{
return *(ptr + 4);
}
else if (ptr[0] == 0 && ptr[1] == 0 && ptr[2] == 0 && ptr[3] == 1) //寻找0x00000001
{
return *(ptr + 5);
}
return 0;
}
void CFileReader::SetEof(bool bEof)
{
m_bEof = bEof;
}
bool CFileReader::GetEof()
{
return m_bEof;
#include "filereader.h"
#ifdef __cplusplus
extern "C"
{
#endif
#include "libavformat/avformat.h"
#ifdef __cplusplus
};
#endif
#define LogWrite
#define INF
CFileReader::CFileReader()
{
av_register_all();
avformat_network_init();
// 设置编解码库日志回调函数
av_log_set_callback(NULL);
resetReader();
}
CFileReader::~CFileReader()
{}
void CFileReader::resetReader()
{
m_bNetFile = false;
m_bEof = false;
m_nVideoIndex = -1;
m_nAudioIndex = -1;
m_inVideoStream = NULL;
m_inAudioStream = NULL;
m_inFormatContext = NULL;
}
int CFileReader::OpenFile(std::string filePath, std::string key/* = ""*/, int nTimeOutValue)
{
unsigned char *tmp;
resetReader();
const char *p = filePath.c_str();
if (filePath.length() > 4 && (p[0] == 'h' && p[1] == 't' && p[2] == 't' && p[3] == 'p'))
{
m_bNetFile = true;
}
aes_128_key_value_ = key;
m_inFormatContext = avformat_alloc_context();
if(!m_inFormatContext)
{
//LogWrite("OpenFile failed::LastError = %d, filePath = %s", CUtilityMethod::GetErrorNo(), filePath.c_str());
return -1;
}
//支持hls加密文件的播放
const AVClass *c;
const AVOption *o = NULL;
AVDictionary *format_opts = NULL;
if (aes_128_key_value_.length() > 0)
{
av_dict_set(&format_opts, "allowed_extensions", "ALL", AV_DICT_MATCH_CASE);
av_dict_set_int(&format_opts, "cryptkey_extend_len", 16, AV_DICT_MATCH_CASE);
av_dict_set(&format_opts, "cryptkey_extend", aes_128_key_value_.c_str(), AV_DICT_MATCH_CASE);
}
//支持播放本地m3u8
av_dict_set(&format_opts, "protocol_whitelist", "file,crypto,http,https,tcp,tls", 0);
//禁用 HLS 使用多个链接拉取ts文件逻辑,多链接拉取有bug例如,正在播放第二个文件的中间时 取拉取第四个文件,拉取失败时会导致第二个文件剩下的数据无法播放
av_dict_set(&format_opts, "http_multiple", "0", 0);
int nRet = avformat_open_input(&m_inFormatContext, filePath.c_str(), 0, &format_opts);
if (nRet!=0)
{
char szBuffer[256] = { 0 };
av_make_error_string(szBuffer, 256, nRet);
//LogWrite("OpenFile failed:avformat_open_input return = %d, LastError = %d, filePath = %s", nRet, CUtilityMethod::GetErrorNo(), filePath.c_str());
goto err;
}
nRet = avformat_find_stream_info(m_inFormatContext, 0);
if (nRet < 0)
{
//LogWrite("OpenFile failed:avformat_find_stream_info return = %d, LastError = %d, filePath = %s", nRet, CUtilityMethod::GetErrorNo(), filePath.c_str());
goto err;
}
for(int i = 0; i < m_inFormatContext->nb_streams; i++)
{
if((m_inFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
(m_inFormatContext->streams[i]->codec->codec_id == AV_CODEC_ID_H264))
{
m_nVideoIndex = i;
m_inVideoStream = m_inFormatContext->streams[i];
}
if(m_inFormatContext->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO)
{
m_nAudioIndex = i;
m_inAudioStream = m_inFormatContext->streams[i];
}
}
//必须包含音频
if(m_nVideoIndex < 0 && m_nAudioIndex < 0)
{
//LogWrite("OpenFile failed:videoindex = %d, audioindex = %d", m_nVideoIndex, m_nAudioIndex);
goto err;
}
return 0;
err:
CloseFile();
return -1;
}
int CFileReader::CloseFile()
{
if(m_inFormatContext)
{
avformat_close_input(&m_inFormatContext);
avformat_free_context(m_inFormatContext);
m_inFormatContext = NULL;
}
return 0;
}
int CFileReader::ReadFile(AVPacket &pkt)
{
int nRet = av_read_frame(m_inFormatContext, &pkt);
if(nRet == AVERROR_EOF)
{
//LogWrite(INF, "ReadFile failed, return value = %d, LastError = %d", nRet, CUtilityMethod::GetErrorNo());
return -1;
}
return nRet;
}
int CFileReader::PauseRead(bool bPause)
{
int nRet = 0;
if (!IsNetFile()) return 0;
if (bPause)
{
nRet = av_read_pause(m_inFormatContext);
}
else
{
nRet = av_read_play(m_inFormatContext);
}
return nRet;
}
double CFileReader::GetFileTimeLength()
{
if(m_inFormatContext)
{
return (m_inFormatContext->duration)/1000000;
}
return 0;
}
int CFileReader::GetVideoSize(int &nWidth, int &nHeight)
{
if (m_nVideoIndex >= 0 && m_inVideoStream->codec)
{
nWidth = m_inVideoStream->codec->width;
nHeight = m_inVideoStream->codec->height;
}
else
{
nWidth = 0;
nHeight = 0;
}
return 0;
}
float CFileReader::GetVideoFrameRate()
{
if (m_nVideoIndex >= 0)
{
float num = m_inVideoStream->avg_frame_rate.num;
float den = m_inVideoStream->avg_frame_rate.den;
float tmp = num / den + 0.5;
return num / den + 0.5;
}
return 0;
}
int CFileReader::SeekFile(int streamIndex, long long minTs, long long timestamp_us, long long maxTs, int flags)
{
avformat_flush(m_inFormatContext);
return avformat_seek_file(m_inFormatContext, streamIndex, minTs, timestamp_us, maxTs, flags);
}
AVCodecID CFileReader::GetVideoCodecID()
{
if(m_nVideoIndex >= 0 && m_inVideoStream && m_inVideoStream->codec)
{
return m_inVideoStream->codec->codec_id;
}
return AV_CODEC_ID_NONE;
}
AVCodecID CFileReader::GetAudioCodecID()
{
if(m_inAudioStream && m_inAudioStream->codec)
{
return m_inAudioStream->codec->codec_id;
}
return AV_CODEC_ID_NONE;
}
int CFileReader::GetAudioRawFrameSize()
{
return 0;
}
int CFileReader::GetVideoRawFrameSize(int &width, int &height)
{
width = m_inVideoStream->codec->width;
height = m_inVideoStream->codec->height;
return 0;
}
bool CFileReader::IsAnnexb4Video()
{
//m3u8的ts中, extradata = NULL
if (!m_inVideoStream->codec->extradata || m_inVideoStream->codec->extradata[0] == 0)
{
return true;
}
return false;
}
bool CFileReader::IsVideoPacketNeedDecode(char *ptr)
{
char nType = GetNaluType(ptr, IsAnnexb4Video());
//m3u8的ts中, extradata = NULL, sps和pps跟随数据一起发来,所以需要解码这种类型的sps和pps
/*if ((nType == 7 || nType == 8) && m_inVideoStream->codec->extradata)
{
return false;
}
if (nType == 9)
{
return false;
}*/
if (nType == 6)
{
char subType = GetSeiSubType(ptr, IsAnnexb4Video());
if (subType != 5)
{
return false;
}
}
return true;
}
char CFileReader::GetNaluType(char *ptr, bool isAnnexb)
{
if (!isAnnexb)
{
return (*(ptr + 4) & 0x1f);
}
if (ptr[0] == 0 && ptr[1] == 0 && ptr[2] == 1) //寻找0x000001
{
return (*(ptr + 3) & 0x1f);
}
else if (ptr[0] == 0 && ptr[1] == 0 && ptr[2] == 0 && ptr[3] == 1) //寻找0x00000001
{
return (*(ptr + 4) & 0x1f);
}
return 0;
}
char CFileReader::GetSeiSubType(char *ptr, bool isAnnexb)
{
if (!isAnnexb)
{
return *(ptr + 5);
}
if (ptr[0] == 0 && ptr[1] == 0 && ptr[2] == 1) //寻找0x000001
{
return *(ptr + 4);
}
else if (ptr[0] == 0 && ptr[1] == 0 && ptr[2] == 0 && ptr[3] == 1) //寻找0x00000001
{
return *(ptr + 5);
}
return 0;
}
void CFileReader::SetEof(bool bEof)
{
m_bEof = bEof;
}
bool CFileReader::GetEof()
{
return m_bEof;
}
\ No newline at end of file
......@@ -138,7 +138,14 @@ void RebuildManager::CallBackWhiteBoardData(AVPacket &pkt)
std::string req((char *)info.m_pData + 6, info.m_nDataSize - 6);
int index = *(int *)(info.m_pData + 6 + 8);
printf("whitebaord's data index = %d\n", index);
//canvas id
char *p = (char *)info.m_pData + 32;
char tmp[32] = { 0 };
memcpy(tmp, p, 24);
printf("whitebaord's data index = %d, canvasid = %s\n", index, tmp);
if (m_pMqtt)
{
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment