diff --git a/trunk/doc/CHANGELOG.md b/trunk/doc/CHANGELOG.md
index a360e9b94..6db811e9f 100644
--- a/trunk/doc/CHANGELOG.md
+++ b/trunk/doc/CHANGELOG.md
@@ -7,6 +7,7 @@ The changelog for SRS.
## SRS 7.0 Changelog
+* v7.0, 2025-08-27, Merge [#4455](https://github.com/ossrs/srs/pull/4455): Gather utility functions to kernel or protocol. v7.0.65 (#4455)
* v7.0, 2025-08-27, Merge [#4454](https://github.com/ossrs/srs/pull/4454): AI: Config: Move RTMP configs to rtmp{} section. v7.0.64 (#4454)
* v7.0, 2025-08-26, Merge [#4451](https://github.com/ossrs/srs/pull/4451): RTC: Fix null pointer crash in RTC2RTMP when start packet is missing. v7.0.63 (#4451)
* v7.0, 2025-08-25, Merge [#4452](https://github.com/ossrs/srs/pull/4452): AI: Implement stream publish token system to prevent race conditions across all protocols. v7.0.62 (#4452)
diff --git a/trunk/src/app/srs_app_caster_flv.cpp b/trunk/src/app/srs_app_caster_flv.cpp
index 021f71dcb..e479e5735 100644
--- a/trunk/src/app/srs_app_caster_flv.cpp
+++ b/trunk/src/app/srs_app_caster_flv.cpp
@@ -47,7 +47,7 @@ srs_error_t SrsHttpFlvListener::initialize(SrsConfDirective *c)
return srs_error_new(ERROR_STREAM_CASTER_PORT, "invalid port=%d", port);
}
- listener_->set_endpoint(srs_any_address_for_listener(), port)->set_label("PUSH-FLV");
+ listener_->set_endpoint(srs_net_address_any(), port)->set_label("PUSH-FLV");
if ((err = caster_->initialize(c)) != srs_success) {
return srs_error_wrap(err, "init caster port=%d", port);
@@ -162,20 +162,20 @@ srs_error_t SrsAppCasterFlv::serve_http(ISrsHttpResponseWriter *w, ISrsHttpMessa
SrsDynamicHttpConn *dconn = dynamic_cast(hconn->handler());
srs_assert(dconn);
- std::string app = srs_path_dirname(r->path());
- app = srs_string_trim_start(app, "/");
+ std::string app = srs_path_filepath_dir(r->path());
+ app = srs_strings_trim_start(app, "/");
- std::string stream = srs_path_basename(r->path());
- stream = srs_string_trim_start(stream, "/");
+ std::string stream = srs_path_filepath_base(r->path());
+ stream = srs_strings_trim_start(stream, "/");
std::string o = output;
if (!app.empty() && app != "/") {
- o = srs_string_replace(o, "[app]", app);
+ o = srs_strings_replace(o, "[app]", app);
}
- o = srs_string_replace(o, "[stream]", stream);
+ o = srs_strings_replace(o, "[stream]", stream);
// remove the extension.
- if (srs_string_ends_with(o, ".flv")) {
+ if (srs_strings_ends_with(o, ".flv")) {
o = o.substr(0, o.length() - 4);
}
diff --git a/trunk/src/app/srs_app_config.cpp b/trunk/src/app/srs_app_config.cpp
index c2a69779d..3981decc9 100644
--- a/trunk/src/app/srs_app_config.cpp
+++ b/trunk/src/app/srs_app_config.cpp
@@ -86,23 +86,23 @@ const char *_srs_version = "XCORE-" RTMP_SIG_SRS_SERVER;
#define SRS_OVERWRITE_BY_ENV_FLOAT_MILLISECONDS(key) \
if (!srs_getenv(key).empty()) \
return srs_utime_t(::atof(srs_getenv(key).c_str()) * SRS_UTIME_MILLISECONDS)
-#define SRS_OVERWRITE_BY_ENV_DIRECTIVE(key) \
- { \
- SrsConfDirective *dir = env_cache_->get(key); \
- if (!dir && !srs_getenv(key).empty()) { \
- std::vector vec = srs_string_split(srs_getenv(key), " "); \
- dir = new SrsConfDirective(); \
- dir->name = key; \
- for (size_t i = 0; i < vec.size(); ++i) { \
- std::string value = vec[i]; \
- if (!value.empty()) { \
- dir->args.push_back(value); \
- } \
- } \
- env_cache_->directives.push_back(dir); \
- } \
- if (dir) \
- return dir; \
+#define SRS_OVERWRITE_BY_ENV_DIRECTIVE(key) \
+ { \
+ SrsConfDirective *dir = env_cache_->get(key); \
+ if (!dir && !srs_getenv(key).empty()) { \
+ std::vector vec = srs_strings_split(srs_getenv(key), " "); \
+ dir = new SrsConfDirective(); \
+ dir->name = key; \
+ for (size_t i = 0; i < vec.size(); ++i) { \
+ std::string value = vec[i]; \
+ if (!value.empty()) { \
+ dir->args.push_back(value); \
+ } \
+ } \
+ env_cache_->directives.push_back(dir); \
+ } \
+ if (dir) \
+ return dir; \
}
/**
@@ -145,7 +145,7 @@ srs_error_t srs_detect_docker()
}
string s(buf, nn);
- if (srs_string_contains(s, "/docker")) {
+ if (srs_strings_contains(s, "/docker")) {
_srs_in_docker = true;
}
@@ -2479,10 +2479,10 @@ srs_error_t SrsConfig::check_normal_config()
for (int i = 0; i < (int)listens.size(); i++) {
int port;
string ip;
- srs_parse_endpoint(listens[i], ip, port);
+ srs_net_split_for_listener(listens[i], ip, port);
// check ip
- if (!srs_check_ip_addr_valid(ip)) {
+ if (!srs_net_is_valid_ip(ip)) {
return srs_error_new(ERROR_SYSTEM_CONFIG_INVALID, "listen.ip=%s is invalid", ip.c_str());
}
@@ -2786,7 +2786,7 @@ srs_error_t SrsConfig::check_normal_config()
}
// check mount suffix '.ts'
- if (http_remux_enabled && m == "mount" && srs_string_ends_with(conf->at(j)->arg0(), ".ts")) {
+ if (http_remux_enabled && m == "mount" && srs_strings_ends_with(conf->at(j)->arg0(), ".ts")) {
http_remux_ts = true;
}
}
@@ -2963,8 +2963,8 @@ SrsConfDirective *SrsConfig::get_root()
string srs_server_id_path(string pid_file)
{
- string path = srs_string_replace(pid_file, ".pid", ".id");
- if (!srs_string_ends_with(path, ".id")) {
+ string path = srs_strings_replace(pid_file, ".pid", ".id");
+ if (!srs_strings_ends_with(path, ".id")) {
path += ".id";
}
return path;
@@ -3064,7 +3064,7 @@ vector SrsConfig::get_listens()
std::vector ports;
if (!srs_getenv("srs.listen").empty()) { // SRS_LISTEN
- return srs_string_split(srs_getenv("srs.listen"), " ");
+ return srs_strings_split(srs_getenv("srs.listen"), " ");
}
SrsConfDirective *rtmp_conf = root->get("rtmp");
@@ -4046,7 +4046,7 @@ std::string SrsConfig::get_stream_caster_sip_candidate(SrsConfDirective *conf)
}
// If configed as ENV, but no ENV set, use default value.
- if (srs_string_starts_with(conf->arg0(), "$")) {
+ if (srs_strings_starts_with(conf->arg0(), "$")) {
return DEFAULT;
}
@@ -4191,7 +4191,7 @@ std::string SrsConfig::get_rtc_server_candidates()
// Note that the value content might be an environment variable.
std::string eval = srs_getenv("srs.rtc_server.candidate"); // SRS_RTC_SERVER_CANDIDATE
if (!eval.empty()) {
- if (!srs_string_starts_with(eval, "$"))
+ if (!srs_strings_starts_with(eval, "$"))
return eval;
SRS_OVERWRITE_BY_ENV_STRING(eval);
}
@@ -4214,7 +4214,7 @@ std::string SrsConfig::get_rtc_server_candidates()
}
// If configed as ENV, but no ENV set, use default value.
- if (srs_string_starts_with(conf->arg0(), "$")) {
+ if (srs_strings_starts_with(conf->arg0(), "$")) {
return DEFAULT;
}
@@ -6168,7 +6168,7 @@ bool SrsConfig::get_engine_enabled(SrsConfDirective *conf)
string srs_prefix_underscores_ifno(string name)
{
- if (srs_string_starts_with(name, "-")) {
+ if (srs_strings_starts_with(name, "-")) {
return name;
} else {
return "-" + name;
@@ -9043,7 +9043,7 @@ bool SrsConfig::get_rtmps_enabled()
vector SrsConfig::get_rtmps_listen()
{
if (!srs_getenv("srs.rtmps.listen").empty()) { // SRS_RTMPS_LISTEN
- return srs_string_split(srs_getenv("srs.rtmps.listen"), " ");
+ return srs_strings_split(srs_getenv("srs.rtmps.listen"), " ");
}
std::vector ports;
diff --git a/trunk/src/app/srs_app_coworkers.cpp b/trunk/src/app/srs_app_coworkers.cpp
index a79f7217f..be78576c1 100644
--- a/trunk/src/app/srs_app_coworkers.cpp
+++ b/trunk/src/app/srs_app_coworkers.cpp
@@ -56,7 +56,7 @@ SrsJsonAny *SrsCoWorkers::dumps(string vhost, string coworker, string app, strin
string list_hostport = listen_hostports.at(0);
if (list_hostport.find(":") != string::npos) {
- srs_parse_hostport(list_hostport, listen_host, listen_port);
+ srs_net_split_hostport(list_hostport, listen_host, listen_port);
} else {
listen_port = ::atoi(list_hostport.c_str());
}
@@ -74,7 +74,7 @@ SrsJsonAny *SrsCoWorkers::dumps(string vhost, string coworker, string app, strin
int coworker_port;
string coworker_host = coworker;
if (coworker.find(":") != string::npos) {
- srs_parse_hostport(coworker, coworker_host, coworker_port);
+ srs_net_split_hostport(coworker, coworker_host, coworker_port);
}
service_ip = coworker_host;
@@ -112,7 +112,7 @@ ISrsRequest *SrsCoWorkers::find_stream_info(string vhost, string app, string str
}
// Get stream information from local cache.
- string url = srs_generate_stream_url(conf->arg0(), app, stream);
+ string url = srs_net_url_encode_sid(conf->arg0(), app, stream);
map::iterator it = streams.find(url);
if (it == streams.end()) {
return NULL;
diff --git a/trunk/src/app/srs_app_dash.cpp b/trunk/src/app/srs_app_dash.cpp
index d2ed16c61..31e7d7781 100644
--- a/trunk/src/app/srs_app_dash.cpp
+++ b/trunk/src/app/srs_app_dash.cpp
@@ -208,7 +208,7 @@ srs_error_t SrsMpdWriter::on_publish()
mpd_file = _srs_config->get_dash_mpd_file(r->vhost);
string mpd_path = srs_path_build_stream(mpd_file, req->vhost, req->app, req->stream);
- fragment_home = srs_path_dirname(mpd_path) + "/" + req->stream;
+ fragment_home = srs_path_filepath_dir(mpd_path) + "/" + req->stream;
window_size_ = _srs_config->get_dash_window_size(r->vhost);
srs_trace("DASH: Config fragment=%dms, period=%dms, window=%d, timeshit=%dms, home=%s, mpd=%s",
@@ -232,11 +232,11 @@ srs_error_t SrsMpdWriter::write(SrsFormat *format, SrsFragmentWindow *afragments
string mpd_path = srs_path_build_stream(mpd_file, req->vhost, req->app, req->stream);
string full_path = home + "/" + mpd_path;
- string full_home = srs_path_dirname(full_path);
+ string full_home = srs_path_filepath_dir(full_path);
- fragment_home = srs_path_dirname(mpd_path) + "/" + req->stream;
+ fragment_home = srs_path_filepath_dir(mpd_path) + "/" + req->stream;
- if ((err = srs_create_dir_recursively(full_home)) != srs_success) {
+ if ((err = srs_os_mkdir_all(full_home)) != srs_success) {
return srs_error_wrap(err, "Create MPD home failed, home=%s", full_home.c_str());
}
@@ -248,11 +248,11 @@ srs_error_t SrsMpdWriter::write(SrsFormat *format, SrsFragmentWindow *afragments
<< " ns1:schemaLocation=\"urn:mpeg:dash:schema:mpd:2011 DASH-MPD.xsd\" " << endl
<< " xmlns=\"urn:mpeg:dash:schema:mpd:2011\" xmlns:ns1=\"http://www.w3.org/2001/XMLSchema-instance\" " << endl
<< " type=\"dynamic\" " << endl
- << " minimumUpdatePeriod=\"PT" << srs_fmt("%.3f", srsu2s(update_period)) << "S\" " << endl
- << " timeShiftBufferDepth=\"PT" << srs_fmt("%.3f", last_duration * window_size_) << "S\" " << endl
+ << " minimumUpdatePeriod=\"PT" << srs_fmt_sprintf("%.3f", srsu2s(update_period)) << "S\" " << endl
+ << " timeShiftBufferDepth=\"PT" << srs_fmt_sprintf("%.3f", last_duration * window_size_) << "S\" " << endl
<< " availabilityStartTime=\"" << srs_time_to_utc_format_str(availability_start_time_) << "\" " << endl
- << " publishTime=\"" << srs_time_to_utc_format_str(srs_get_system_time()) << "\" " << endl
- << " minBufferTime=\"PT" << srs_fmt("%.3f", 2 * last_duration) << "S\" >" << endl;
+ << " publishTime=\"" << srs_time_to_utc_format_str(srs_time_now_cached()) << "\" " << endl
+ << " minBufferTime=\"PT" << srs_fmt_sprintf("%.3f", 2 * last_duration) << "S\" >" << endl;
ss << " " << req->stream << "/" << "" << endl;
@@ -333,10 +333,10 @@ srs_error_t SrsMpdWriter::get_fragment(bool video, std::string &home, std::strin
if (video) {
sn = video_number_++;
- file_name = "video-" + srs_int2str(sn) + ".m4s";
+ file_name = "video-" + srs_strconv_format_int(sn) + ".m4s";
} else {
sn = audio_number_++;
- file_name = "audio-" + srs_int2str(sn) + ".m4s";
+ file_name = "audio-" + srs_strconv_format_int(sn) + ".m4s";
}
return err;
@@ -502,7 +502,7 @@ srs_error_t SrsDashController::on_audio(SrsSharedPtrMessage *shared_audio, SrsFo
if (first_dts_ == -1) {
first_dts_ = audio_dts;
- mpd->set_availability_start_time(srs_get_system_time() - first_dts_ * SRS_UTIME_MILLISECONDS);
+ mpd->set_availability_start_time(srs_time_now_cached() - first_dts_ * SRS_UTIME_MILLISECONDS);
}
// TODO: FIXME: Support pure audio streaming.
@@ -574,7 +574,7 @@ srs_error_t SrsDashController::on_video(SrsSharedPtrMessage *shared_video, SrsFo
if (first_dts_ == -1) {
first_dts_ = video_dts;
- mpd->set_availability_start_time(srs_get_system_time() - first_dts_ * SRS_UTIME_MILLISECONDS);
+ mpd->set_availability_start_time(srs_time_now_cached() - first_dts_ * SRS_UTIME_MILLISECONDS);
}
bool reopen = format->video->frame_type == SrsVideoAvcFrameTypeKeyFrame && vcurrent->duration() >= fragment;
@@ -651,7 +651,7 @@ srs_error_t SrsDashController::refresh_init_mp4(SrsSharedPtrMessage *msg, SrsFor
}
string full_home = home + "/" + req->app + "/" + req->stream;
- if ((err = srs_create_dir_recursively(full_home)) != srs_success) {
+ if ((err = srs_os_mkdir_all(full_home)) != srs_success) {
return srs_error_wrap(err, "Create media home failed, home=%s", full_home.c_str());
}
@@ -716,7 +716,7 @@ srs_error_t SrsDash::cycle()
srs_error_t err = srs_success;
if (last_update_time_ <= 0) {
- last_update_time_ = srs_get_system_time();
+ last_update_time_ = srs_time_now_cached();
}
if (!req) {
@@ -727,10 +727,10 @@ srs_error_t SrsDash::cycle()
if (dash_dispose <= 0) {
return err;
}
- if (srs_get_system_time() - last_update_time_ <= dash_dispose) {
+ if (srs_time_now_cached() - last_update_time_ <= dash_dispose) {
return err;
}
- last_update_time_ = srs_get_system_time();
+ last_update_time_ = srs_time_now_cached();
if (!disposable_) {
return err;
@@ -784,7 +784,7 @@ srs_error_t SrsDash::on_publish()
enabled = true;
// update the dash time, for dash_dispose.
- last_update_time_ = srs_get_system_time();
+ last_update_time_ = srs_time_now_cached();
if ((err = controller->on_publish()) != srs_success) {
return srs_error_wrap(err, "controller");
@@ -809,7 +809,7 @@ srs_error_t SrsDash::on_audio(SrsSharedPtrMessage *shared_audio, SrsFormat *form
}
// update the dash time, for dash_dispose.
- last_update_time_ = srs_get_system_time();
+ last_update_time_ = srs_time_now_cached();
if ((err = controller->on_audio(shared_audio, format)) != srs_success) {
return srs_error_wrap(err, "Consume audio failed");
@@ -831,7 +831,7 @@ srs_error_t SrsDash::on_video(SrsSharedPtrMessage *shared_video, SrsFormat *form
}
// update the dash time, for dash_dispose.
- last_update_time_ = srs_get_system_time();
+ last_update_time_ = srs_time_now_cached();
if ((err = controller->on_video(shared_video, format)) != srs_success) {
return srs_error_wrap(err, "Consume video failed");
diff --git a/trunk/src/app/srs_app_dvr.cpp b/trunk/src/app/srs_app_dvr.cpp
index 7013e2f3a..25dd56435 100644
--- a/trunk/src/app/srs_app_dvr.cpp
+++ b/trunk/src/app/srs_app_dvr.cpp
@@ -203,7 +203,7 @@ string SrsDvrSegmenter::generate_path()
std::string path_config = _srs_config->get_dvr_path(req->vhost);
// add [stream].[timestamp].flv as filename for dir
- if (!srs_string_ends_with(path_config, ".flv", ".mp4")) {
+ if (!srs_strings_ends_with(path_config, ".flv", ".mp4")) {
path_config += "/[stream].[timestamp].flv";
}
@@ -973,7 +973,7 @@ srs_error_t SrsDvr::initialize(SrsOriginHub *h, ISrsRequest *r)
std::string path = _srs_config->get_dvr_path(r->vhost);
SrsDvrSegmenter *segmenter = NULL;
- if (srs_string_ends_with(path, ".mp4")) {
+ if (srs_strings_ends_with(path, ".mp4")) {
segmenter = new SrsDvrMp4Segmenter();
} else {
segmenter = new SrsDvrFlvSegmenter();
diff --git a/trunk/src/app/srs_app_edge.cpp b/trunk/src/app/srs_app_edge.cpp
index 33368adef..f910621b1 100644
--- a/trunk/src/app/srs_app_edge.cpp
+++ b/trunk/src/app/srs_app_edge.cpp
@@ -81,13 +81,13 @@ srs_error_t SrsEdgeRtmpUpstream::connect(ISrsRequest *r, SrsLbRoundRobin *lb)
// select the origin.
std::string server = lb->select(conf->args);
int port = SRS_CONSTS_RTMP_DEFAULT_PORT;
- srs_parse_hostport(server, server, port);
+ srs_net_split_hostport(server, server, port);
// override the origin info by redirect.
if (!redirect.empty()) {
int _port;
string _schema, _vhost, _app, _stream, _param, _host;
- srs_discovery_tc_url(redirect, _schema, _host, _vhost, _app, _stream, _port, _param);
+ srs_net_url_parse_tcurl(redirect, _schema, _host, _vhost, _app, _stream, _port, _param);
server = _host;
port = _port;
@@ -99,9 +99,9 @@ srs_error_t SrsEdgeRtmpUpstream::connect(ISrsRequest *r, SrsLbRoundRobin *lb)
// support vhost tranform for edge,
std::string vhost = _srs_config->get_vhost_edge_transform_vhost(req->vhost);
- vhost = srs_string_replace(vhost, "[vhost]", req->vhost);
+ vhost = srs_strings_replace(vhost, "[vhost]", req->vhost);
- url = srs_generate_rtmp_url(server, port, req->host, vhost, req->app, req->stream, req->param);
+ url = srs_net_url_encode_rtmp_url(server, port, req->host, vhost, req->app, req->stream, req->param);
}
srs_freep(sdk);
@@ -211,7 +211,7 @@ srs_error_t SrsEdgeFlvUpstream::do_connect(ISrsRequest *r, SrsLbRoundRobin *lb,
if (schema_ == "https") {
port = SRS_DEFAULT_HTTPS_PORT;
}
- srs_parse_hostport(server, server, port);
+ srs_net_split_hostport(server, server, port);
// Remember the current selected server.
selected_ip = server;
@@ -227,14 +227,14 @@ srs_error_t SrsEdgeFlvUpstream::do_connect(ISrsRequest *r, SrsLbRoundRobin *lb,
sdk_ = new SrsHttpClient();
string path = "/" + req->app + "/" + req->stream;
- if (!srs_string_ends_with(req->stream, ".flv")) {
+ if (!srs_strings_ends_with(req->stream, ".flv")) {
path += ".flv";
}
if (!req->param.empty()) {
path += req->param;
}
- string url = schema_ + "://" + selected_ip + ":" + srs_int2str(selected_port);
+ string url = schema_ + "://" + selected_ip + ":" + srs_strconv_format_int(selected_port);
url += path;
srs_utime_t cto = SRS_EDGE_INGESTER_TIMEOUT;
@@ -266,11 +266,11 @@ srs_error_t SrsEdgeFlvUpstream::do_connect(ISrsRequest *r, SrsLbRoundRobin *lb,
string stream_name;
if (true) {
string tcUrl;
- srs_parse_rtmp_url(location, tcUrl, stream_name);
+ srs_net_url_parse_rtmp_url(location, tcUrl, stream_name);
int port;
string schema, host, vhost, param;
- srs_discovery_tc_url(tcUrl, schema, host, vhost, app, stream_name, port, param);
+ srs_net_url_parse_tcurl(tcUrl, schema, host, vhost, app, stream_name, port, param);
r->schema = schema;
r->host = host;
@@ -788,13 +788,13 @@ srs_error_t SrsEdgeForwarder::start()
// select the origin.
std::string server = lb->select(conf->args);
int port = SRS_CONSTS_RTMP_DEFAULT_PORT;
- srs_parse_hostport(server, server, port);
+ srs_net_split_hostport(server, server, port);
// support vhost tranform for edge,
std::string vhost = _srs_config->get_vhost_edge_transform_vhost(req->vhost);
- vhost = srs_string_replace(vhost, "[vhost]", req->vhost);
+ vhost = srs_strings_replace(vhost, "[vhost]", req->vhost);
- url = srs_generate_rtmp_url(server, port, req->host, vhost, req->app, req->stream, req->param);
+ url = srs_net_url_encode_rtmp_url(server, port, req->host, vhost, req->app, req->stream, req->param);
}
// We must stop the coroutine before disposing the sdk.
diff --git a/trunk/src/app/srs_app_encoder.cpp b/trunk/src/app/srs_app_encoder.cpp
index 1cc1fa39d..0d6f75c78 100644
--- a/trunk/src/app/srs_app_encoder.cpp
+++ b/trunk/src/app/srs_app_encoder.cpp
@@ -244,7 +244,7 @@ srs_error_t SrsEncoder::initialize_ffmpeg(SrsFFMPEG *ffmpeg, ISrsRequest *req, S
input = "rtmp://";
input += SRS_CONSTS_LOCALHOST;
input += ":";
- input += srs_int2str(req->port);
+ input += srs_strconv_format_int(req->port);
input += "/";
input += req->app;
input += "/";
@@ -262,12 +262,12 @@ srs_error_t SrsEncoder::initialize_ffmpeg(SrsFFMPEG *ffmpeg, ISrsRequest *req, S
std::string output = _srs_config->get_engine_output(engine);
// output stream, to other/self server
// ie. rtmp://localhost:1935/live/livestream_sd
- output = srs_string_replace(output, "[vhost]", req->vhost);
- output = srs_string_replace(output, "[port]", srs_int2str(req->port));
- output = srs_string_replace(output, "[app]", req->app);
- output = srs_string_replace(output, "[stream]", req->stream);
- output = srs_string_replace(output, "[param]", req->param);
- output = srs_string_replace(output, "[engine]", engine->arg0());
+ output = srs_strings_replace(output, "[vhost]", req->vhost);
+ output = srs_strings_replace(output, "[port]", srs_strconv_format_int(req->port));
+ output = srs_strings_replace(output, "[app]", req->app);
+ output = srs_strings_replace(output, "[stream]", req->stream);
+ output = srs_strings_replace(output, "[param]", req->param);
+ output = srs_strings_replace(output, "[engine]", engine->arg0());
output = srs_path_build_timestamp(output);
std::string log_file = SRS_CONSTS_NULL_FILE; // disabled
diff --git a/trunk/src/app/srs_app_ffmpeg.cpp b/trunk/src/app/srs_app_ffmpeg.cpp
index ad9b58fee..044c2b46b 100644
--- a/trunk/src/app/srs_app_ffmpeg.cpp
+++ b/trunk/src/app/srs_app_ffmpeg.cpp
@@ -175,7 +175,7 @@ srs_error_t SrsFFMPEG::initialize_transcode(SrsConfDirective *engine)
// for not rtmp input, donot append the iformat,
// for example, "-f flv" before "-i udp://192.168.1.252:2222"
- if (!srs_string_starts_with(input, "rtmp://")) {
+ if (!srs_strings_starts_with(input, "rtmp://")) {
iformat = "";
}
@@ -264,28 +264,28 @@ srs_error_t SrsFFMPEG::start()
if (vcodec != SRS_RTMP_ENCODER_COPY && vcodec != SRS_RTMP_ENCODER_NO_VIDEO) {
if (vbitrate > 0) {
params.push_back("-b:v");
- params.push_back(srs_int2str(vbitrate * 1000));
+ params.push_back(srs_strconv_format_int(vbitrate * 1000));
}
if (vfps > 0) {
params.push_back("-r");
- params.push_back(srs_float2str(vfps));
+ params.push_back(srs_strconv_format_float(vfps));
}
if (vwidth > 0 && vheight > 0) {
params.push_back("-s");
- params.push_back(srs_int2str(vwidth) + "x" + srs_int2str(vheight));
+ params.push_back(srs_strconv_format_int(vwidth) + "x" + srs_strconv_format_int(vheight));
}
// TODO: add aspect if needed.
if (vwidth > 0 && vheight > 0) {
params.push_back("-aspect");
- params.push_back(srs_int2str(vwidth) + ":" + srs_int2str(vheight));
+ params.push_back(srs_strconv_format_int(vwidth) + ":" + srs_strconv_format_int(vheight));
}
if (vthreads > 0) {
params.push_back("-threads");
- params.push_back(srs_int2str(vthreads));
+ params.push_back(srs_strconv_format_int(vthreads));
}
if (!vprofile.empty()) {
@@ -323,17 +323,17 @@ srs_error_t SrsFFMPEG::start()
if (acodec != SRS_RTMP_ENCODER_COPY) {
if (abitrate > 0) {
params.push_back("-b:a");
- params.push_back(srs_int2str(abitrate * 1000));
+ params.push_back(srs_strconv_format_int(abitrate * 1000));
}
if (asample_rate > 0) {
params.push_back("-ar");
- params.push_back(srs_int2str(asample_rate));
+ params.push_back(srs_strconv_format_int(asample_rate));
}
if (achannels > 0) {
params.push_back("-ac");
- params.push_back(srs_int2str(achannels));
+ params.push_back(srs_strconv_format_int(achannels));
}
// aparams
diff --git a/trunk/src/app/srs_app_forward.cpp b/trunk/src/app/srs_app_forward.cpp
index 3bac5177a..d9058f0c1 100644
--- a/trunk/src/app/srs_app_forward.cpp
+++ b/trunk/src/app/srs_app_forward.cpp
@@ -206,10 +206,10 @@ srs_error_t SrsForwarder::do_cycle()
int port = SRS_CONSTS_RTMP_DEFAULT_PORT;
// parse host:port from hostport.
- srs_parse_hostport(ep_forward, server, port);
+ srs_net_split_hostport(ep_forward, server, port);
// generate url
- url = srs_generate_rtmp_url(server, port, req->host, req->vhost, req->app, req->stream, req->param);
+ url = srs_net_url_encode_rtmp_url(server, port, req->host, req->vhost, req->app, req->stream, req->param);
}
srs_freep(sdk);
diff --git a/trunk/src/app/srs_app_fragment.cpp b/trunk/src/app/srs_app_fragment.cpp
index bd2f02535..6d3a8fcea 100644
--- a/trunk/src/app/srs_app_fragment.cpp
+++ b/trunk/src/app/srs_app_fragment.cpp
@@ -92,9 +92,9 @@ srs_error_t SrsFragment::create_dir()
{
srs_error_t err = srs_success;
- std::string segment_dir = srs_path_dirname(filepath);
+ std::string segment_dir = srs_path_filepath_dir(filepath);
- if ((err = srs_create_dir_recursively(segment_dir)) != srs_success) {
+ if ((err = srs_os_mkdir_all(segment_dir)) != srs_success) {
return srs_error_wrap(err, "create %s", segment_dir.c_str());
}
@@ -130,7 +130,7 @@ srs_error_t SrsFragment::rename()
if (true) {
std::stringstream ss;
ss << tempdur;
- full_path = srs_string_replace(full_path, "[duration]", ss.str());
+ full_path = srs_strings_replace(full_path, "[duration]", ss.str());
}
int r0 = ::rename(tmp_file.c_str(), full_path.c_str());
diff --git a/trunk/src/app/srs_app_gb28181.cpp b/trunk/src/app/srs_app_gb28181.cpp
index a3958d7be..b32f995f6 100644
--- a/trunk/src/app/srs_app_gb28181.cpp
+++ b/trunk/src/app/srs_app_gb28181.cpp
@@ -55,7 +55,7 @@ std::string srs_gb_session_state(SrsGbSessionState state)
std::string srs_gb_state(SrsGbSessionState ostate, SrsGbSessionState state)
{
- return srs_fmt("%s->%s", srs_gb_session_state(ostate).c_str(), srs_gb_session_state(state).c_str());
+ return srs_fmt_sprintf("%s->%s", srs_gb_session_state(ostate).c_str(), srs_gb_session_state(state).c_str());
}
std::string srs_gb_sip_state(SrsGbSipState state)
@@ -82,7 +82,7 @@ std::string srs_gb_sip_state(SrsGbSipState state)
std::string srs_sip_state(SrsGbSipState ostate, SrsGbSipState state)
{
- return srs_fmt("%s->%s", srs_gb_sip_state(ostate).c_str(), srs_gb_sip_state(state).c_str());
+ return srs_fmt_sprintf("%s->%s", srs_gb_sip_state(ostate).c_str(), srs_gb_sip_state(state).c_str());
}
SrsGbSession::SrsGbSession() : sip_(new SrsGbSipTcpConn()), media_(new SrsGbMediaTcpConn())
@@ -101,7 +101,7 @@ SrsGbSession::SrsGbSession() : sip_(new SrsGbSipTcpConn()), media_(new SrsGbMedi
reinvite_wait_ = 0;
ppp_ = new SrsAlonePithyPrint();
- startime_ = srs_update_system_time();
+ startime_ = srs_time_now_realtime();
total_packs_ = 0;
total_msgs_ = 0;
total_recovered_ = 0;
@@ -307,8 +307,8 @@ srs_error_t SrsGbSession::do_cycle()
ppp_->elapse();
if (ppp_->can_print()) {
- int alive = srsu2msi(srs_update_system_time() - startime_) / 1000;
- int pack_alive = srsu2msi(srs_update_system_time() - media_starttime_) / 1000;
+ int alive = srsu2msi(srs_time_now_realtime() - startime_) / 1000;
+ int pack_alive = srsu2msi(srs_time_now_realtime() - media_starttime_) / 1000;
srs_trace("Session: Alive=%ds, packs=%" PRId64 ", recover=%" PRId64 ", reserved=%" PRId64 ", msgs=%" PRId64 ", drop=%" PRId64 ", media(id=%u, alive=%ds, packs=%" PRId64 " recover=%" PRId64 ", reserved=%" PRId64 ", msgs=%" PRId64 ", drop=%" PRId64 ")",
alive, (total_packs_ + media_packs_), (total_recovered_ + media_recovered_), (total_reserved_ + media_reserved_),
(total_msgs_ + media_msgs_), (total_msgs_dropped_ + media_msgs_dropped_), media_id_, pack_alive, media_packs_,
@@ -335,7 +335,7 @@ srs_error_t SrsGbSession::drive_state()
// is connected, so we don't need to handle it here.
if (sip_->is_registered()) {
SRS_GB_CHANGE_STATE_TO(SrsGbSessionStateConnecting);
- connecting_starttime_ = srs_update_system_time();
+ connecting_starttime_ = srs_time_now_realtime();
}
// Invite if media is not connected.
@@ -351,7 +351,7 @@ srs_error_t SrsGbSession::drive_state()
}
if (state_ == SrsGbSessionStateConnecting) {
- if (srs_update_system_time() - connecting_starttime_ >= connecting_timeout_) {
+ if (srs_time_now_realtime() - connecting_starttime_ >= connecting_timeout_) {
if ((nn_timeout_++) > SRS_GB_MAX_TIMEOUT) {
return srs_error_new(ERROR_GB_TIMEOUT, "timeout");
}
@@ -376,9 +376,9 @@ srs_error_t SrsGbSession::drive_state()
// When media disconnected, we wait for a while then reinvite.
if (!media_->is_connected()) {
if (!reinviting_starttime_) {
- reinviting_starttime_ = srs_update_system_time();
+ reinviting_starttime_ = srs_time_now_realtime();
}
- if (srs_get_system_time() - reinviting_starttime_ > reinvite_wait_) {
+ if (srs_time_now_cached() - reinviting_starttime_ > reinvite_wait_) {
reinviting_starttime_ = 0;
srs_trace("Session: Re-invite for disconnect, state=%s, sip=%s, media=%d", srs_gb_session_state(state_).c_str(),
srs_gb_sip_state(sip_->state()).c_str(), media_->is_connected());
@@ -429,7 +429,7 @@ srs_error_t SrsGbListener::initialize(SrsConfDirective *conf)
srs_freep(conf_);
conf_ = conf->copy();
- string ip = srs_any_address_for_listener();
+ string ip = srs_net_address_any();
if (true) {
int port = _srs_config->get_stream_caster_listen(conf);
media_listener_->set_endpoint(ip, port)->set_label("GB-TCP");
@@ -772,17 +772,17 @@ void SrsGbSipTcpConn::invite_ack(SrsSipMessage *msg)
string pip = session_->pip(); // Parse from CANDIDATE
int sip_port;
query_ports(&sip_port, NULL);
- string gb_device_id = srs_fmt("sip:%s@%s", msg->to_address_user_.c_str(), msg->to_address_host_.c_str());
- string branch = srs_random_str(6);
+ string gb_device_id = srs_fmt_sprintf("sip:%s@%s", msg->to_address_user_.c_str(), msg->to_address_host_.c_str());
+ string branch = srs_rand_gen_str(6);
SrsSipMessage *req = new SrsSipMessage();
req->type_ = HTTP_REQUEST;
req->method_ = HTTP_ACK;
req->request_uri_ = gb_device_id;
- req->via_ = srs_fmt("SIP/2.0/TCP %s:%d;rport;branch=%s%s", pip.c_str(), sip_port, SRS_GB_BRANCH_MAGIC, branch.c_str());
+ req->via_ = srs_fmt_sprintf("SIP/2.0/TCP %s:%d;rport;branch=%s%s", pip.c_str(), sip_port, SRS_GB_BRANCH_MAGIC, branch.c_str());
req->from_ = msg->from_;
req->to_ = msg->to_;
- req->cseq_ = srs_fmt("%d ACK", msg->cseq_number_);
+ req->cseq_ = srs_fmt_sprintf("%d ACK", msg->cseq_number_);
req->call_id_ = msg->call_id_;
req->max_forwards_ = 70;
@@ -815,7 +815,7 @@ srs_error_t SrsGbSipTcpConn::invite_request(uint32_t *pssrc)
string ssrc = ssrc_str_;
for (int i = 0; ssrc.empty() && i < 16; i++) {
int flag = 0; // 0 is realtime.
- string ssrc_str = srs_fmt("%d%s%04d", flag, register_->ssrc_domain_id().c_str(), srs_random() % 10000);
+ string ssrc_str = srs_fmt_sprintf("%d%s%04d", flag, register_->ssrc_domain_id().c_str(), srs_rand_integer() % 10000);
uint32_t ssrc_v = (uint32_t)::atol(ssrc_str.c_str());
if (!_srs_gb_manager->find_by_fast_id(ssrc_v)) {
ssrc = ssrc_str;
@@ -836,13 +836,13 @@ srs_error_t SrsGbSipTcpConn::invite_request(uint32_t *pssrc)
string pip = session_->pip(); // Parse from CANDIDATE
int sip_port, media_port;
query_ports(&sip_port, &media_port);
- string srs_device_id = srs_fmt("sip:%s@%s", register_->request_uri_user_.c_str(), register_->request_uri_host_.c_str());
- string gb_device_id = srs_fmt("sip:%s@%s", register_->from_address_user_.c_str(), register_->from_address_host_.c_str());
- string subject = srs_fmt("%s:%s,%s:0", register_->from_address_user_.c_str(), ssrc_str_.c_str(), register_->request_uri_user_.c_str());
- string branch = srs_random_str(6);
- string tag = srs_random_str(8);
- string call_id = srs_random_str(16);
- int cseq = (int)(srs_random() % 1000); // TODO: FIXME: Increase.
+ string srs_device_id = srs_fmt_sprintf("sip:%s@%s", register_->request_uri_user_.c_str(), register_->request_uri_host_.c_str());
+ string gb_device_id = srs_fmt_sprintf("sip:%s@%s", register_->from_address_user_.c_str(), register_->from_address_host_.c_str());
+ string subject = srs_fmt_sprintf("%s:%s,%s:0", register_->from_address_user_.c_str(), ssrc_str_.c_str(), register_->request_uri_user_.c_str());
+ string branch = srs_rand_gen_str(6);
+ string tag = srs_rand_gen_str(8);
+ string call_id = srs_rand_gen_str(16);
+ int cseq = (int)(srs_rand_integer() % 1000); // TODO: FIXME: Increase.
SrsSdp local_sdp;
local_sdp.version_ = "0";
@@ -855,8 +855,8 @@ srs_error_t SrsGbSipTcpConn::invite_request(uint32_t *pssrc)
local_sdp.session_name_ = "Play";
local_sdp.start_time_ = 0;
local_sdp.end_time_ = 0;
- local_sdp.ice_lite_ = ""; // Disable this line.
- local_sdp.connection_ = srs_fmt("c=IN IP4 %s", pip.c_str()); // Session level connection.
+ local_sdp.ice_lite_ = ""; // Disable this line.
+ local_sdp.connection_ = srs_fmt_sprintf("c=IN IP4 %s", pip.c_str()); // Session level connection.
local_sdp.media_descs_.push_back(SrsMediaDesc("video"));
SrsMediaDesc &media = local_sdp.media_descs_.at(0);
@@ -885,13 +885,13 @@ srs_error_t SrsGbSipTcpConn::invite_request(uint32_t *pssrc)
req->type_ = HTTP_REQUEST;
req->method_ = HTTP_INVITE;
req->request_uri_ = gb_device_id;
- req->via_ = srs_fmt("SIP/2.0/TCP %s:%d;rport;branch=%s%s", pip.c_str(), sip_port, SRS_GB_BRANCH_MAGIC, branch.c_str());
- req->from_ = srs_fmt("<%s>;tag=SRS%s", srs_device_id.c_str(), tag.c_str());
- req->to_ = srs_fmt("<%s>", gb_device_id.c_str());
- req->cseq_ = srs_fmt("%d INVITE", cseq);
+ req->via_ = srs_fmt_sprintf("SIP/2.0/TCP %s:%d;rport;branch=%s%s", pip.c_str(), sip_port, SRS_GB_BRANCH_MAGIC, branch.c_str());
+ req->from_ = srs_fmt_sprintf("<%s>;tag=SRS%s", srs_device_id.c_str(), tag.c_str());
+ req->to_ = srs_fmt_sprintf("<%s>", gb_device_id.c_str());
+ req->cseq_ = srs_fmt_sprintf("%d INVITE", cseq);
req->call_id_ = call_id;
req->content_type_ = "Application/SDP";
- req->contact_ = srs_fmt("<%s>", srs_device_id.c_str());
+ req->contact_ = srs_fmt_sprintf("<%s>", srs_device_id.c_str());
req->max_forwards_ = 70;
req->subject_ = subject;
req->set_body(ss.str());
@@ -1236,7 +1236,7 @@ srs_error_t SrsGbSipTcpSender::do_cycle()
if (!msg->contact_.empty())
res.header()->set("Contact", msg->contact_);
if (msg->expires_ != UINT32_MAX)
- res.header()->set("Expires", srs_int2str(msg->expires_));
+ res.header()->set("Expires", srs_strconv_format_int(msg->expires_));
res.header()->set_content_length(msg->body_.length());
res.write_header(msg->status_);
@@ -1258,7 +1258,7 @@ srs_error_t SrsGbSipTcpSender::do_cycle()
if (!msg->subject_.empty())
req.header()->set("Subject", msg->subject_);
if (msg->max_forwards_)
- req.header()->set("Max-Forwards", srs_int2str(msg->max_forwards_));
+ req.header()->set("Max-Forwards", srs_strconv_format_int(msg->max_forwards_));
if (!msg->content_type_.empty())
req.header()->set_content_type(msg->content_type_);
@@ -1466,7 +1466,7 @@ srs_error_t SrsGbMediaTcpConn::do_cycle()
// Show tips about the buffer to parse.
if (reserved) {
- string bytes = srs_string_dumps_hex((const char *)(buffer_ + reserved), length, 16);
+ string bytes = srs_strings_dumps_hex((const char *)(buffer_ + reserved), length, 16);
srs_trace("PS: Consume reserved=%dB, length=%d, bytes=[%s]", reserved, length, bytes.c_str());
}
@@ -1483,7 +1483,7 @@ srs_error_t SrsGbMediaTcpConn::do_cycle()
reserved = 0; // Avoid reserving too much data.
}
if (reserved) {
- string bytes = srs_string_dumps_hex(b.head(), reserved, 16);
+ string bytes = srs_strings_dumps_hex(b.head(), reserved, 16);
srs_trace("PS: Reserved bytes for next loop, pos=%d, left=%d, total=%d, bytes=[%s]",
b.pos(), b.left(), b.size(), bytes.c_str());
// Copy the bytes left to the start of buffer. Note that the left(reserved) bytes might be overlapped with
@@ -1723,7 +1723,7 @@ srs_error_t SrsGbMuxer::mux_h264(SrsTsMessage *msg, SrsBuffer *avs)
if (
nt != SrsAvcNaluTypeSPS && nt != SrsAvcNaluTypePPS && nt != SrsAvcNaluTypeIDR &&
nt != SrsAvcNaluTypeNonIDR && nt != SrsAvcNaluTypeSEI && nt != SrsAvcNaluTypeAccessUnitDelimiter) {
- string bytes = srs_string_dumps_hex(frame, frame_size, 4);
+ string bytes = srs_strings_dumps_hex(frame, frame_size, 4);
srs_warn("GB: Ignore NALU nt=%d, frame=[%s]", nt, bytes.c_str());
return err;
}
@@ -2156,7 +2156,7 @@ srs_error_t SrsGbMuxer::connect()
// Cleanup the data before connect again.
close();
- string url = srs_string_replace(output_, "[stream]", session_->sip_transport()->device_id());
+ string url = srs_strings_replace(output_, "[stream]", session_->sip_transport()->device_id());
srs_trace("Muxer: Convert GB to RTMP %s", url.c_str());
srs_utime_t cto = SRS_CONSTS_RTMP_TIMEOUT;
@@ -2258,8 +2258,8 @@ SrsSipMessage *SrsSipMessage::set_body(std::string v)
{
body_ = v;
body_escaped_ = v;
- body_escaped_ = srs_string_replace(body_escaped_, "\r", "\\r");
- body_escaped_ = srs_string_replace(body_escaped_, "\n", "\\n");
+ body_escaped_ = srs_strings_replace(body_escaped_, "\r", "\\r");
+ body_escaped_ = srs_strings_replace(body_escaped_, "\n", "\\n");
return this;
}
@@ -2271,7 +2271,7 @@ srs_error_t SrsSipMessage::parse(ISrsHttpMessage *m)
// the next message when skip current invalid message.
string v;
ISrsHttpResponseReader *br = m->body_reader();
- if (!br->eof() && (err = srs_ioutil_read_all(br, v)) != srs_success) {
+ if (!br->eof() && (err = srs_io_readall(br, v)) != srs_success) {
return srs_error_wrap(err, "read body");
}
@@ -2282,7 +2282,7 @@ srs_error_t SrsSipMessage::parse(ISrsHttpMessage *m)
if (type_ == HTTP_REQUEST) {
// Parse request line.
method_ = (http_method)m->method();
- request_uri_ = srs_string_trim_start(m->path(), "/");
+ request_uri_ = srs_strings_trim_start(m->path(), "/");
srs_sip_parse_address(request_uri_, request_uri_user_, request_uri_host_);
} else if (type_ == HTTP_RESPONSE) {
// Parse status line for response.
@@ -2372,34 +2372,34 @@ srs_error_t SrsSipMessage::parse_via(const std::string &via)
{
srs_error_t err = srs_success;
- if (!srs_string_starts_with(via, "SIP/2.0/")) {
+ if (!srs_strings_starts_with(via, "SIP/2.0/")) {
return srs_error_new(ERROR_GB_SIP_HEADER, "Via protocol invalid");
}
- if (srs_string_starts_with(via, "SIP/2.0/TCP")) {
+ if (srs_strings_starts_with(via, "SIP/2.0/TCP")) {
via_transport_ = "TCP";
- } else if (srs_string_starts_with(via, "SIP/2.0/UDP")) {
+ } else if (srs_strings_starts_with(via, "SIP/2.0/UDP")) {
via_transport_ = "UDP";
} else {
return srs_error_new(ERROR_GB_SIP_HEADER, "Via transport invalid");
}
- vector vs = srs_string_split(via, " ");
+ vector vs = srs_strings_split(via, " ");
if (vs.size() <= 1)
return srs_error_new(ERROR_GB_SIP_HEADER, "Via no send-by");
- vector params = srs_string_split(vs[1], ";");
+ vector params = srs_strings_split(vs[1], ";");
if (params.size() <= 1)
return srs_error_new(ERROR_GB_SIP_HEADER, "Via no params");
via_send_by_ = params[0];
- srs_parse_hostport(via_send_by_, via_send_by_address_, via_send_by_port_);
+ srs_net_split_hostport(via_send_by_, via_send_by_address_, via_send_by_port_);
for (int i = 1; i < (int)params.size(); i++) {
string param = params[i];
- if (srs_string_starts_with(param, "rport")) {
+ if (srs_strings_starts_with(param, "rport")) {
via_rport_ = param;
- } else if (srs_string_starts_with(param, "branch")) {
+ } else if (srs_strings_starts_with(param, "branch")) {
via_branch_ = param;
}
}
@@ -2414,7 +2414,7 @@ srs_error_t SrsSipMessage::parse_via(const std::string &via)
return srs_error_new(ERROR_GB_SIP_HEADER, "Via no branch");
// The branch ID inserted by an element compliant with this specification MUST always begin with the characters
// "z9hG4bK". See https://www.ietf.org/rfc/rfc3261.html#section-8.1.1.7
- if (!srs_string_starts_with(via_branch_, string("branch=") + SRS_GB_BRANCH_MAGIC)) {
+ if (!srs_strings_starts_with(via_branch_, string("branch=") + SRS_GB_BRANCH_MAGIC)) {
return srs_error_new(ERROR_GB_SIP_HEADER, "Invalid branch=%s", via_branch_.c_str());
}
@@ -2425,14 +2425,14 @@ srs_error_t SrsSipMessage::parse_from(const std::string &from)
{
srs_error_t err = srs_success;
- vector params = srs_string_split(from, ";");
+ vector params = srs_strings_split(from, ";");
if (params.size() < 2)
return srs_error_new(ERROR_GB_SIP_HEADER, "From no params");
from_address_ = params[0];
for (int i = 1; i < (int)params.size(); i++) {
string param = params[i];
- if (srs_string_starts_with(param, "tag")) {
+ if (srs_strings_starts_with(param, "tag")) {
from_tag_ = param;
}
}
@@ -2449,14 +2449,14 @@ srs_error_t SrsSipMessage::parse_to(const std::string &to)
{
srs_error_t err = srs_success;
- vector params = srs_string_split(to, ";");
+ vector params = srs_strings_split(to, ";");
if (params.size() < 1)
return srs_error_new(ERROR_GB_SIP_HEADER, "To is empty");
to_address_ = params[0];
for (int i = 1; i < (int)params.size(); i++) {
string param = params[i];
- if (srs_string_starts_with(param, "tag")) {
+ if (srs_strings_starts_with(param, "tag")) {
to_tag_ = param;
}
}
@@ -2468,7 +2468,7 @@ srs_error_t SrsSipMessage::parse_cseq(const std::string &cseq)
{
srs_error_t err = srs_success;
- vector params = srs_string_split(cseq, " ");
+ vector params = srs_strings_split(cseq, " ");
if (params.size() < 2)
return srs_error_new(ERROR_GB_SIP_HEADER, "CSeq is empty");
@@ -2496,7 +2496,7 @@ srs_error_t SrsSipMessage::parse_contact(const std::string &contact)
srs_error_t err = srs_success;
srs_sip_parse_address(contact, contact_user_, contact_host_);
- srs_parse_hostport(contact_host_, contact_host_address_, contact_host_port_);
+ srs_net_split_hostport(contact_host_, contact_host_address_, contact_host_port_);
return err;
}
@@ -2506,7 +2506,7 @@ SrsPackContext::SrsPackContext(ISrsPsPackHandler *handler)
static uint32_t gid = 0;
media_id_ = ++gid;
- media_startime_ = srs_update_system_time();
+ media_startime_ = srs_time_now_realtime();
media_nn_recovered_ = 0;
media_nn_msgs_dropped_ = 0;
media_reserved_ = 0;
@@ -2541,8 +2541,8 @@ srs_error_t SrsPackContext::on_ts_message(SrsTsMessage *msg)
// We got new pack header and an optional system header.
// if (ps_->id_ != h->ps_->id_) {
// stringstream ss;
- // if (h->ps_->has_pack_header_) ss << srs_fmt(", clock=%" PRId64 ", rate=%d", h->ps_->system_clock_reference_base_, h->ps_->program_mux_rate_);
- // if (h->ps_->has_system_header_) ss << srs_fmt(", rate_bound=%d, video_bound=%d, audio_bound=%d", h->ps_->rate_bound_, h->ps_->video_bound_, h->ps_->audio_bound_);
+ // if (h->ps_->has_pack_header_) ss << srs_fmt_sprintf(", clock=%" PRId64 ", rate=%d", h->ps_->system_clock_reference_base_, h->ps_->program_mux_rate_);
+ // if (h->ps_->has_system_header_) ss << srs_fmt_sprintf(", rate_bound=%d, video_bound=%d, audio_bound=%d", h->ps_->rate_bound_, h->ps_->video_bound_, h->ps_->audio_bound_);
// srs_trace("PS: New pack header=%d, system=%d%s", h->ps_->has_pack_header_, h->ps_->has_system_header_, ss.str().c_str());
//}
@@ -2681,7 +2681,7 @@ srs_error_t SrsRecoverablePsContext::enter_recover_mode(SrsBuffer *stream, ISrsP
// Print the error information for debugging.
int npos = stream->pos();
stream->skip(pos - stream->pos());
- string bytes = srs_string_dumps_hex(stream->head(), stream->left(), 8);
+ string bytes = srs_strings_dumps_hex(stream->head(), stream->left(), 8);
SrsPsDecodeHelper &h = ctx_.helper_;
uint16_t pack_seq = h.pack_first_seq_;
@@ -2719,7 +2719,7 @@ srs_error_t SrsRecoverablePsContext::enter_recover_mode(SrsBuffer *stream, ISrsP
void SrsRecoverablePsContext::quit_recover_mode(SrsBuffer *stream, ISrsPsMessageHandler *handler)
{
- string bytes = srs_string_dumps_hex(stream->head(), stream->left(), 8);
+ string bytes = srs_strings_dumps_hex(stream->head(), stream->left(), 8);
srs_warn("PS: Quit recover=%d, seq=%u, bytes=[%s], pos=%d, left=%d", recover_, ctx_.helper_.rtp_seq_,
bytes.c_str(), stream->pos(), stream->left());
recover_ = 0;
diff --git a/trunk/src/app/srs_app_gb28181.hpp b/trunk/src/app/srs_app_gb28181.hpp
index f0939f67e..67bfd6c50 100644
--- a/trunk/src/app/srs_app_gb28181.hpp
+++ b/trunk/src/app/srs_app_gb28181.hpp
@@ -780,7 +780,7 @@ extern bool srs_skip_util_pack(SrsBuffer *stream);
// Parsed as:
// user: bob
// host: ossrs.io:5060
-// Note that the host can be parsed by srs_parse_hostport as host(ossrs.io) and port(5060).
+// Note that the host can be parsed by srs_net_split_hostport as host(ossrs.io) and port(5060).
extern void srs_sip_parse_address(const std::string &address, std::string &user, std::string &host);
// Manager for GB connections.
diff --git a/trunk/src/app/srs_app_hds.cpp b/trunk/src/app/srs_app_hds.cpp
index 760f4d9ee..4f42027c1 100644
--- a/trunk/src/app/srs_app_hds.cpp
+++ b/trunk/src/app/srs_app_hds.cpp
@@ -408,7 +408,7 @@ srs_error_t SrsHds::flush_mainfest()
hds_req->stream.c_str(), hds_req->stream.c_str(), hds_req->stream.c_str());
string dir = _srs_config->get_hds_path(hds_req->vhost) + "/" + hds_req->app;
- if ((err = srs_create_dir_recursively(dir)) != srs_success) {
+ if ((err = srs_os_mkdir_all(dir)) != srs_success) {
return srs_error_wrap(err, "hds create dir failed");
}
string path = dir + "/" + hds_req->stream + ".f4m";
diff --git a/trunk/src/app/srs_app_heartbeat.cpp b/trunk/src/app/srs_app_heartbeat.cpp
index fb4ae90a7..d8024971b 100644
--- a/trunk/src/app/srs_app_heartbeat.cpp
+++ b/trunk/src/app/srs_app_heartbeat.cpp
@@ -116,7 +116,7 @@ srs_error_t SrsHttpHeartbeat::do_heartbeat()
obj->set("srt", o);
uint16_t endpoint = _srs_config->get_srt_listen_port();
- o->append(SrsJsonAny::str(srs_fmt("udp://0.0.0.0:%d", endpoint).c_str()));
+ o->append(SrsJsonAny::str(srs_fmt_sprintf("udp://0.0.0.0:%d", endpoint).c_str()));
}
// For RTSP listen endpoints.
@@ -125,7 +125,7 @@ srs_error_t SrsHttpHeartbeat::do_heartbeat()
obj->set("rtsp", o);
int endpoint = _srs_config->get_rtsp_server_listen();
- o->append(SrsJsonAny::str(srs_fmt("rtsp://0.0.0.0:%d", endpoint).c_str()));
+ o->append(SrsJsonAny::str(srs_fmt_sprintf("rtsp://0.0.0.0:%d", endpoint).c_str()));
}
// For WebRTC listen endpoints.
@@ -134,11 +134,11 @@ srs_error_t SrsHttpHeartbeat::do_heartbeat()
obj->set("rtc", o);
int endpoint = _srs_config->get_rtc_server_listen();
- o->append(SrsJsonAny::str(srs_fmt("udp://0.0.0.0:%d", endpoint).c_str()));
+ o->append(SrsJsonAny::str(srs_fmt_sprintf("udp://0.0.0.0:%d", endpoint).c_str()));
if (_srs_config->get_rtc_server_tcp_enabled()) {
endpoint = _srs_config->get_rtc_server_tcp_listen();
- o->append(SrsJsonAny::str(srs_fmt("tcp://0.0.0.0:%d", endpoint).c_str()));
+ o->append(SrsJsonAny::str(srs_fmt_sprintf("tcp://0.0.0.0:%d", endpoint).c_str()));
}
}
}
diff --git a/trunk/src/app/srs_app_hls.cpp b/trunk/src/app/srs_app_hls.cpp
index 6bf1cdf42..e48dc7887 100644
--- a/trunk/src/app/srs_app_hls.cpp
+++ b/trunk/src/app/srs_app_hls.cpp
@@ -69,7 +69,7 @@ srs_error_t SrsHlsSegment::rename()
if (true) {
std::stringstream ss;
ss << srsu2msi(duration());
- uri = srs_string_replace(uri, "[duration]", ss.str());
+ uri = srs_strings_replace(uri, "[duration]", ss.str());
}
return SrsFragment::rename();
@@ -506,8 +506,8 @@ srs_error_t SrsHlsFmp4Muxer::write_init_mp4(SrsFormat *format, bool has_video, b
std::string path = hls_path + "/" + init_file;
// Create directory for the init file
- std::string init_dir = srs_path_dirname(path);
- if ((err = srs_create_dir_recursively(init_dir)) != srs_success) {
+ std::string init_dir = srs_path_filepath_dir(path);
+ if ((err = srs_os_mkdir_all(init_dir)) != srs_success) {
return srs_error_wrap(err, "Create init mp4 dir failed, dir=%s", init_dir.c_str());
}
@@ -542,19 +542,19 @@ srs_error_t SrsHlsFmp4Muxer::write_init_mp4(SrsFormat *format, bool has_video, b
// the ts url, relative or absolute url.
// TODO: FIXME: Use url and path manager.
std::string mp4_path = init_mp4->fullpath();
- if (srs_string_starts_with(mp4_path, m3u8_dir_)) {
+ if (srs_strings_starts_with(mp4_path, m3u8_dir_)) {
mp4_path = mp4_path.substr(m3u8_dir_.length());
}
- while (srs_string_starts_with(mp4_path, "/")) {
+ while (srs_strings_starts_with(mp4_path, "/")) {
mp4_path = mp4_path.substr(1);
}
string init_mp4_uri = hls_entry_prefix_;
- if (!hls_entry_prefix_.empty() && !srs_string_ends_with(hls_entry_prefix_, "/")) {
+ if (!hls_entry_prefix_.empty() && !srs_strings_ends_with(hls_entry_prefix_, "/")) {
init_mp4_uri += "/";
// add the http dir to uri.
- string http_dir = srs_path_dirname(m3u8_url_);
+ string http_dir = srs_path_filepath_dir(m3u8_url_);
if (!http_dir.empty()) {
init_mp4_uri += http_dir + "/";
}
@@ -563,7 +563,7 @@ srs_error_t SrsHlsFmp4Muxer::write_init_mp4(SrsFormat *format, bool has_video, b
// Convert to relative URI for m3u8 playlist.
// TODO: Need to resolve the relative URI from m3u8 and init file.
- init_mp4_uri_ = srs_path_basename(init_file);
+ init_mp4_uri_ = srs_path_filepath_base(init_file);
// use async to call the http hooks, for it will cause thread switch.
if ((err = async_->execute(new SrsDvrAsyncCallOnHls(_srs_context->get_id(), req_, init_mp4->fullpath(),
@@ -684,16 +684,16 @@ srs_error_t SrsHlsFmp4Muxer::update_config(ISrsRequest *r)
max_td_ = hls_fragment_ * hls_td_ratio;
// create m3u8 dir once.
- m3u8_dir_ = srs_path_dirname(m3u8_);
- if ((err = srs_create_dir_recursively(m3u8_dir_)) != srs_success) {
+ m3u8_dir_ = srs_path_filepath_dir(m3u8_);
+ if ((err = srs_os_mkdir_all(m3u8_dir_)) != srs_success) {
return srs_error_wrap(err, "create dir");
}
if (hls_keys_ && (hls_path_ != hls_key_file_path_)) {
string key_file = srs_path_build_stream(hls_key_file_, vhost, app, stream);
string key_url = hls_key_file_path_ + "/" + key_file;
- string key_dir = srs_path_dirname(key_url);
- if ((err = srs_create_dir_recursively(key_dir)) != srs_success) {
+ string key_dir = srs_path_filepath_dir(key_url);
+ if ((err = srs_os_mkdir_all(key_dir)) != srs_success) {
return srs_error_wrap(err, "create dir");
}
}
@@ -725,7 +725,7 @@ srs_error_t SrsHlsFmp4Muxer::segment_open(srs_utime_t basetime)
m4s_file = srs_path_build_stream(m4s_file, req_->vhost, req_->app, req_->stream);
if (hls_ts_floor_) {
// accept the floor ts for the first piece.
- int64_t current_floor_ts = srs_update_system_time() / hls_fragment_;
+ int64_t current_floor_ts = srs_time_now_realtime() / hls_fragment_;
if (!accept_floor_ts_) {
accept_floor_ts_ = current_floor_ts - 1;
} else {
@@ -751,7 +751,7 @@ srs_error_t SrsHlsFmp4Muxer::segment_open(srs_utime_t basetime)
// we always ensure the piece is increase one by one.
std::stringstream ts_floor;
ts_floor << accept_floor_ts_;
- m4s_file = srs_string_replace(m4s_file, "[timestamp]", ts_floor.str());
+ m4s_file = srs_strings_replace(m4s_file, "[timestamp]", ts_floor.str());
// TODO: FIMXE: we must use the accept ts floor time to generate the hour variable.
m4s_file = srs_path_build_timestamp(m4s_file);
@@ -761,7 +761,7 @@ srs_error_t SrsHlsFmp4Muxer::segment_open(srs_utime_t basetime)
if (true) {
std::stringstream ss;
ss << current_->sequence_no;
- m4s_file = srs_string_replace(m4s_file, "[seq]", ss.str());
+ m4s_file = srs_strings_replace(m4s_file, "[seq]", ss.str());
}
std::string m4s_path = hls_path_ + "/" + m4s_file;
@@ -770,19 +770,19 @@ srs_error_t SrsHlsFmp4Muxer::segment_open(srs_utime_t basetime)
// the ts url, relative or absolute url.
// TODO: FIXME: Use url and path manager.
std::string m4s_url = current_->fullpath();
- if (srs_string_starts_with(m4s_url, m3u8_dir_)) {
+ if (srs_strings_starts_with(m4s_url, m3u8_dir_)) {
m4s_url = m4s_url.substr(m3u8_dir_.length());
}
- while (srs_string_starts_with(m4s_url, "/")) {
+ while (srs_strings_starts_with(m4s_url, "/")) {
m4s_url = m4s_url.substr(1);
}
current_->uri += hls_entry_prefix_;
- if (!hls_entry_prefix_.empty() && !srs_string_ends_with(hls_entry_prefix_, "/")) {
+ if (!hls_entry_prefix_.empty() && !srs_strings_ends_with(hls_entry_prefix_, "/")) {
current_->uri += "/";
// add the http dir to uri.
- string http_dir = srs_path_dirname(m3u8_url_);
+ string http_dir = srs_path_filepath_dir(m3u8_url_);
if (!http_dir.empty()) {
current_->uri += http_dir + "/";
}
@@ -904,7 +904,7 @@ srs_error_t SrsHlsFmp4Muxer::write_hls_key()
}
string key_file = srs_path_build_stream(hls_key_file_, req_->vhost, req_->app, req_->stream);
- key_file = srs_string_replace(key_file, "[seq]", srs_int2str(current_->sequence_no));
+ key_file = srs_strings_replace(key_file, "[seq]", srs_strconv_format_int(current_->sequence_no));
string key_url = hls_key_file_path_ + "/" + key_file;
SrsFileWriter fw;
@@ -1013,11 +1013,11 @@ srs_error_t SrsHlsFmp4Muxer::_refresh_m3u8(std::string m3u8_file)
#if 1
if (hls_keys_ && ((segment->sequence_no % hls_fragments_per_key_) == 0)) {
char hexiv[33];
- srs_data_to_hex(hexiv, segment->iv, 16);
+ srs_hex_encode_to_string(hexiv, segment->iv, 16);
hexiv[32] = '\0';
string key_file = srs_path_build_stream(hls_key_file_, req_->vhost, req_->app, req_->stream);
- key_file = srs_string_replace(key_file, "[seq]", srs_int2str(segment->sequence_no));
+ key_file = srs_strings_replace(key_file, "[seq]", srs_strconv_format_int(segment->sequence_no));
string key_path = key_file;
// if key_url is not set,only use the file name
@@ -1040,10 +1040,10 @@ srs_error_t SrsHlsFmp4Muxer::_refresh_m3u8(std::string m3u8_file)
if (true) {
std::stringstream stemp;
stemp << srsu2msi(segment->duration());
- seg_uri = srs_string_replace(seg_uri, "[duration]", stemp.str());
+ seg_uri = srs_strings_replace(seg_uri, "[duration]", stemp.str());
}
// ss << segment->uri << SRS_CONSTS_LF;
- ss << srs_path_basename(seg_uri) << SRS_CONSTS_LF;
+ ss << srs_path_filepath_base(seg_uri) << SRS_CONSTS_LF;
}
// write m3u8 to writer.
@@ -1243,16 +1243,16 @@ srs_error_t SrsHlsMuxer::update_config(ISrsRequest *r, string entry_prefix,
max_td = fragment * _srs_config->get_hls_td_ratio(r->vhost);
// create m3u8 dir once.
- m3u8_dir = srs_path_dirname(m3u8);
- if ((err = srs_create_dir_recursively(m3u8_dir)) != srs_success) {
+ m3u8_dir = srs_path_filepath_dir(m3u8);
+ if ((err = srs_os_mkdir_all(m3u8_dir)) != srs_success) {
return srs_error_wrap(err, "create dir");
}
if (hls_keys && (hls_path != hls_key_file_path)) {
string key_file = srs_path_build_stream(hls_key_file, req->vhost, req->app, req->stream);
string key_url = hls_key_file_path + "/" + key_file;
- string key_dir = srs_path_dirname(key_url);
- if ((err = srs_create_dir_recursively(key_dir)) != srs_success) {
+ string key_dir = srs_path_filepath_dir(key_url);
+ if ((err = srs_os_mkdir_all(key_dir)) != srs_success) {
return srs_error_wrap(err, "create dir");
}
}
@@ -1285,7 +1285,7 @@ srs_error_t SrsHlsMuxer::recover_hls()
}
std::string body;
- if ((err = srs_ioutil_read_all(&fr, body)) != srs_success) {
+ if ((err = srs_io_readall(&fr, body)) != srs_success) {
return srs_error_wrap(err, "read data");
}
if (body.empty()) {
@@ -1307,13 +1307,13 @@ srs_error_t SrsHlsMuxer::recover_hls()
body = "";
}
- line = srs_string_replace(line, "\r", "");
- line = srs_string_replace(line, " ", "");
+ line = srs_strings_replace(line, "\r", "");
+ line = srs_strings_replace(line, " ", "");
// #EXT-X-VERSION:3
// the version must be 3.0
- if (srs_string_starts_with(line, "#EXT-X-VERSION:")) {
- if (!srs_string_ends_with(line, ":3")) {
+ if (srs_strings_starts_with(line, "#EXT-X-VERSION:")) {
+ if (!srs_strings_ends_with(line, ":3")) {
srs_warn("m3u8 3.0 required, actual is %s", line.c_str());
}
continue;
@@ -1321,27 +1321,27 @@ srs_error_t SrsHlsMuxer::recover_hls()
// #EXT-X-PLAYLIST-TYPE:VOD
// the playlist type, vod or nothing.
- if (srs_string_starts_with(line, "#EXT-X-PLAYLIST-TYPE:")) {
+ if (srs_strings_starts_with(line, "#EXT-X-PLAYLIST-TYPE:")) {
ptl = line;
continue;
}
// #EXT-X-MEDIA-SEQUENCE:4294967295
// the media sequence no.
- if (srs_string_starts_with(line, "#EXT-X-MEDIA-SEQUENCE:")) {
+ if (srs_strings_starts_with(line, "#EXT-X-MEDIA-SEQUENCE:")) {
_sequence_no = ::atof(line.substr(string("#EXT-X-MEDIA-SEQUENCE:").length()).c_str());
}
// #EXT-X-DISCONTINUITY
// the discontinuity tag.
- if (srs_string_starts_with(line, "#EXT-X-DISCONTINUITY")) {
+ if (srs_strings_starts_with(line, "#EXT-X-DISCONTINUITY")) {
discon = true;
}
// #EXTINF:11.401,
// livestream-5.ts
// parse each ts entry, expect current line is inf.
- if (!srs_string_starts_with(line, "#EXTINF:")) {
+ if (!srs_strings_starts_with(line, "#EXTINF:")) {
continue;
}
@@ -1451,7 +1451,7 @@ srs_error_t SrsHlsMuxer::segment_open()
ts_file = srs_path_build_stream(ts_file, req->vhost, req->app, req->stream);
if (hls_ts_floor) {
// accept the floor ts for the first piece.
- int64_t current_floor_ts = srs_update_system_time() / hls_fragment;
+ int64_t current_floor_ts = srs_time_now_realtime() / hls_fragment;
if (!accept_floor_ts) {
accept_floor_ts = current_floor_ts - 1;
} else {
@@ -1477,7 +1477,7 @@ srs_error_t SrsHlsMuxer::segment_open()
// we always ensure the piece is increase one by one.
std::stringstream ts_floor;
ts_floor << accept_floor_ts;
- ts_file = srs_string_replace(ts_file, "[timestamp]", ts_floor.str());
+ ts_file = srs_strings_replace(ts_file, "[timestamp]", ts_floor.str());
// TODO: FIMXE: we must use the accept ts floor time to generate the hour variable.
ts_file = srs_path_build_timestamp(ts_file);
@@ -1487,25 +1487,25 @@ srs_error_t SrsHlsMuxer::segment_open()
if (true) {
std::stringstream ss;
ss << current->sequence_no;
- ts_file = srs_string_replace(ts_file, "[seq]", ss.str());
+ ts_file = srs_strings_replace(ts_file, "[seq]", ss.str());
}
current->set_path(hls_path + "/" + ts_file);
// the ts url, relative or absolute url.
// TODO: FIXME: Use url and path manager.
std::string ts_url = current->fullpath();
- if (srs_string_starts_with(ts_url, m3u8_dir)) {
+ if (srs_strings_starts_with(ts_url, m3u8_dir)) {
ts_url = ts_url.substr(m3u8_dir.length());
}
- while (srs_string_starts_with(ts_url, "/")) {
+ while (srs_strings_starts_with(ts_url, "/")) {
ts_url = ts_url.substr(1);
}
current->uri += hls_entry_prefix;
- if (!hls_entry_prefix.empty() && !srs_string_ends_with(hls_entry_prefix, "/")) {
+ if (!hls_entry_prefix.empty() && !srs_strings_ends_with(hls_entry_prefix, "/")) {
current->uri += "/";
// add the http dir to uri.
- string http_dir = srs_path_dirname(m3u8_url);
+ string http_dir = srs_path_filepath_dir(m3u8_url);
if (!http_dir.empty()) {
current->uri += http_dir + "/";
}
@@ -1742,7 +1742,7 @@ srs_error_t SrsHlsMuxer::write_hls_key()
}
string key_file = srs_path_build_stream(hls_key_file, req->vhost, req->app, req->stream);
- key_file = srs_string_replace(key_file, "[seq]", srs_int2str(current->sequence_no));
+ key_file = srs_strings_replace(key_file, "[seq]", srs_strconv_format_int(current->sequence_no));
string key_url = hls_key_file_path + "/" + key_file;
SrsFileWriter fw;
@@ -1849,11 +1849,11 @@ srs_error_t SrsHlsMuxer::_refresh_m3u8(string m3u8_file)
if (hls_keys && ((segment->sequence_no % hls_fragments_per_key) == 0)) {
char hexiv[33];
- srs_data_to_hex(hexiv, segment->iv, 16);
+ srs_hex_encode_to_string(hexiv, segment->iv, 16);
hexiv[32] = '\0';
string key_file = srs_path_build_stream(hls_key_file, req->vhost, req->app, req->stream);
- key_file = srs_string_replace(key_file, "[seq]", srs_int2str(segment->sequence_no));
+ key_file = srs_strings_replace(key_file, "[seq]", srs_strconv_format_int(segment->sequence_no));
string key_path = key_file;
// if key_url is not set,only use the file name
@@ -1874,7 +1874,7 @@ srs_error_t SrsHlsMuxer::_refresh_m3u8(string m3u8_file)
if (true) {
std::stringstream stemp;
stemp << srsu2msi(segment->duration());
- seg_uri = srs_string_replace(seg_uri, "[duration]", stemp.str());
+ seg_uri = srs_strings_replace(seg_uri, "[duration]", stemp.str());
}
// ss << segment->uri << SRS_CONSTS_LF;
ss << seg_uri << SRS_CONSTS_LF;
@@ -2496,7 +2496,7 @@ srs_error_t SrsHls::cycle()
srs_error_t err = srs_success;
if (last_update_time <= 0) {
- last_update_time = srs_get_system_time();
+ last_update_time = srs_time_now_cached();
}
if (!req) {
@@ -2516,10 +2516,10 @@ srs_error_t SrsHls::cycle()
if (hls_dispose <= 0) {
return err;
}
- if (srs_get_system_time() - last_update_time <= hls_dispose) {
+ if (srs_time_now_cached() - last_update_time <= hls_dispose) {
return err;
}
- last_update_time = srs_get_system_time();
+ last_update_time = srs_time_now_cached();
if (!disposable) {
return err;
@@ -2573,7 +2573,7 @@ srs_error_t SrsHls::on_publish()
srs_error_t err = srs_success;
// update the hls time, for hls_dispose.
- last_update_time = srs_get_system_time();
+ last_update_time = srs_time_now_cached();
// support multiple publish.
if (enabled) {
@@ -2640,7 +2640,7 @@ srs_error_t SrsHls::on_audio(SrsSharedPtrMessage *shared_audio, SrsFormat *forma
}
// update the hls time, for hls_dispose.
- last_update_time = srs_get_system_time();
+ last_update_time = srs_time_now_cached();
SrsUniquePtr audio(shared_audio->copy());
@@ -2686,7 +2686,7 @@ srs_error_t SrsHls::on_video(SrsSharedPtrMessage *shared_video, SrsFormat *forma
}
// update the hls time, for hls_dispose.
- last_update_time = srs_get_system_time();
+ last_update_time = srs_time_now_cached();
SrsUniquePtr video(shared_video->copy());
diff --git a/trunk/src/app/srs_app_hourglass.cpp b/trunk/src/app/srs_app_hourglass.cpp
index bfa102f3e..e2e3c5cfd 100644
--- a/trunk/src/app/srs_app_hourglass.cpp
+++ b/trunk/src/app/srs_app_hourglass.cpp
@@ -209,7 +209,7 @@ srs_error_t SrsClockWallMonitor::on_timer(srs_utime_t interval)
static srs_utime_t clock = 0;
- srs_utime_t now = srs_update_system_time();
+ srs_utime_t now = srs_time_now_realtime();
if (!clock) {
clock = now;
return err;
diff --git a/trunk/src/app/srs_app_http_api.cpp b/trunk/src/app/srs_app_http_api.cpp
index 45a111694..938e23672 100644
--- a/trunk/src/app/srs_app_http_api.cpp
+++ b/trunk/src/app/srs_app_http_api.cpp
@@ -686,7 +686,7 @@ srs_error_t SrsGoApiRequests::serve_http(ISrsHttpResponseWriter *w, ISrsHttpMess
server->set("sigature", SrsJsonAny::str(RTMP_SIG_SRS_KEY));
server->set("version", SrsJsonAny::str(RTMP_SIG_SRS_VERSION));
server->set("link", SrsJsonAny::str(RTMP_SIG_SRS_URL));
- server->set("time", SrsJsonAny::integer(srsu2ms(srs_get_system_time())));
+ server->set("time", SrsJsonAny::integer(srsu2ms(srs_time_now_cached())));
return srs_api_response(w, r, obj->dumps());
}
diff --git a/trunk/src/app/srs_app_http_conn.cpp b/trunk/src/app/srs_app_http_conn.cpp
index fcf41aa59..f54e32376 100644
--- a/trunk/src/app/srs_app_http_conn.cpp
+++ b/trunk/src/app/srs_app_http_conn.cpp
@@ -61,7 +61,7 @@ SrsHttpConn::SrsHttpConn(ISrsHttpConnOwner *handler, ISrsProtocolReadWriter *fd,
skt = fd;
ip = cip;
port = cport;
- create_time = srsu2ms(srs_get_system_time());
+ create_time = srsu2ms(srs_time_now_cached());
delta_ = new SrsNetworkDelta();
delta_->set_io(skt, skt);
trd = new SrsSTCoroutine("http", this, _srs_context->get_id());
@@ -333,6 +333,8 @@ srs_error_t SrsHttpxConn::pop_message(ISrsHttpMessage **preq)
{
srs_error_t err = srs_success;
+ const int SRS_HTTP_READ_CACHE_BYTES = 4096;
+
ISrsProtocolReadWriter *io = io_;
if (ssl) {
io = ssl;
@@ -375,12 +377,12 @@ srs_error_t SrsHttpxConn::on_start()
// Do SSL handshake if HTTPS.
if (ssl) {
- srs_utime_t starttime = srs_update_system_time();
+ srs_utime_t starttime = srs_time_now_realtime();
if ((err = ssl->handshake(ssl_key_file_, ssl_cert_file_)) != srs_success) {
return srs_error_wrap(err, "handshake");
}
- int cost = srsu2msi(srs_update_system_time() - starttime);
+ int cost = srsu2msi(srs_time_now_realtime() - starttime);
srs_trace("https: stream server done, use key %s and cert %s, cost=%dms",
ssl_key_file_.c_str(), ssl_cert_file_.c_str(), cost);
}
diff --git a/trunk/src/app/srs_app_http_hooks.cpp b/trunk/src/app/srs_app_http_hooks.cpp
index 17ebb473e..aa021214a 100644
--- a/trunk/src/app/srs_app_http_hooks.cpp
+++ b/trunk/src/app/srs_app_http_hooks.cpp
@@ -349,8 +349,8 @@ srs_error_t SrsHttpHooks::on_hls(SrsContextId c, string url, ISrsRequest *req, s
std::string cwd = _srs_config->cwd();
// the ts_url is under the same dir of m3u8_url.
- string prefix = srs_path_dirname(m3u8_url);
- if (!prefix.empty() && !srs_string_is_http(ts_url)) {
+ string prefix = srs_path_filepath_dir(m3u8_url);
+ if (!prefix.empty() && !srs_net_url_is_http(ts_url)) {
ts_url = prefix + "/" + ts_url;
}
@@ -403,20 +403,20 @@ srs_error_t SrsHttpHooks::on_hls_notify(SrsContextId c, std::string url, ISrsReq
SrsContextId cid = c;
std::string cwd = _srs_config->cwd();
- if (srs_string_is_http(ts_url)) {
+ if (srs_net_url_is_http(ts_url)) {
url = ts_url;
}
SrsStatistic *stat = SrsStatistic::instance();
- url = srs_string_replace(url, "[server_id]", stat->server_id().c_str());
- url = srs_string_replace(url, "[service_id]", stat->service_id().c_str());
- url = srs_string_replace(url, "[app]", req->app);
- url = srs_string_replace(url, "[stream]", req->stream);
- url = srs_string_replace(url, "[ts_url]", ts_url);
- url = srs_string_replace(url, "[param]", req->param);
+ url = srs_strings_replace(url, "[server_id]", stat->server_id().c_str());
+ url = srs_strings_replace(url, "[service_id]", stat->service_id().c_str());
+ url = srs_strings_replace(url, "[app]", req->app);
+ url = srs_strings_replace(url, "[stream]", req->stream);
+ url = srs_strings_replace(url, "[ts_url]", ts_url);
+ url = srs_strings_replace(url, "[param]", req->param);
- int64_t starttime = srsu2ms(srs_update_system_time());
+ int64_t starttime = srsu2ms(srs_time_now_realtime());
SrsHttpUri uri;
if ((err = uri.initialize(url)) != srs_success) {
@@ -457,7 +457,7 @@ srs_error_t SrsHttpHooks::on_hls_notify(SrsContextId c, std::string url, ISrsReq
nb_read += (int)nb_bytes;
}
- int spenttime = (int)(srsu2ms(srs_update_system_time()) - starttime);
+ int spenttime = (int)(srsu2ms(srs_time_now_realtime()) - starttime);
srs_trace("http hook on_hls_notify success. client_id=%s, url=%s, code=%d, spent=%dms, read=%dB, err=%s",
cid.c_str(), url.c_str(), msg->status_code(), spenttime, nb_read, srs_error_desc(err).c_str());
diff --git a/trunk/src/app/srs_app_http_static.cpp b/trunk/src/app/srs_app_http_static.cpp
index 8020080a3..2d8994a2c 100644
--- a/trunk/src/app/srs_app_http_static.cpp
+++ b/trunk/src/app/srs_app_http_static.cpp
@@ -92,7 +92,7 @@ srs_error_t SrsHlsStream::serve_m3u8_ctx(ISrsHttpResponseWriter *w, ISrsHttpMess
// Correct the app and stream by path, which is created from template.
// @remark Be careful that the stream has extension now, might cause identify fail.
- req->stream = srs_path_basename(r->path());
+ req->stream = srs_path_filepath_base(r->path());
// Served by us.
*served = true;
@@ -107,7 +107,7 @@ srs_error_t SrsHlsStream::serve_m3u8_ctx(ISrsHttpResponseWriter *w, ISrsHttpMess
if (is_interrupt(ctx)) {
srs_warn("Reject: HLS stream is EOF, ctx=%s", ctx.c_str());
- return srs_go_http_error(w, SRS_CONSTS_HTTP_NotFound, srs_fmt("HLS stream %s is EOF", ctx.c_str()));
+ return srs_go_http_error(w, SRS_CONSTS_HTTP_NotFound, srs_fmt_sprintf("HLS stream %s is EOF", ctx.c_str()));
}
err = serve_exists_session(w, r, factory, fullpath);
@@ -154,7 +154,7 @@ srs_error_t SrsHlsStream::serve_new_session(ISrsHttpResponseWriter *w, ISrsHttpM
if (ctx.empty()) {
// make sure unique
do {
- ctx = srs_random_str(8); // the same as cid
+ ctx = srs_rand_gen_str(8); // the same as cid
} while (ctx_is_exist(ctx));
}
@@ -215,7 +215,7 @@ srs_error_t SrsHlsStream::serve_exists_session(ISrsHttpResponseWriter *w, ISrsHt
}
string content;
- if ((err = srs_ioutil_read_all(fs.get(), content)) != srs_success) {
+ if ((err = srs_io_readall(fs.get(), content)) != srs_success) {
return srs_error_wrap(err, "read %s", fullpath.c_str());
}
@@ -231,9 +231,9 @@ srs_error_t SrsHlsStream::serve_exists_session(ISrsHttpResponseWriter *w, ISrsHt
size_t pos_query = content.find(".ts?");
if (pos_query != string::npos) {
query += "&";
- content = srs_string_replace(content, ".ts?", query);
+ content = srs_strings_replace(content, ".ts?", query);
} else {
- content = srs_string_replace(content, ".ts", query);
+ content = srs_strings_replace(content, ".ts", query);
}
} else if (content.find(".m4s") != string::npos) {
string ctx = r->query_get(SRS_CONTEXT_IN_HLS);
@@ -242,9 +242,9 @@ srs_error_t SrsHlsStream::serve_exists_session(ISrsHttpResponseWriter *w, ISrsHt
size_t pos_query = content.find(".m4s?");
if (pos_query != string::npos) {
query += "&";
- content = srs_string_replace(content, ".m4s?", query);
+ content = srs_strings_replace(content, ".m4s?", query);
} else {
- content = srs_string_replace(content, ".m4s", query);
+ content = srs_strings_replace(content, ".m4s", query);
}
} else if (content.find("init.mp4") != string::npos) {
string ctx = r->query_get(SRS_CONTEXT_IN_HLS);
@@ -253,9 +253,9 @@ srs_error_t SrsHlsStream::serve_exists_session(ISrsHttpResponseWriter *w, ISrsHt
size_t pos_query = content.find("init.mp4?");
if (pos_query != string::npos) {
query += "&";
- content = srs_string_replace(content, "init.mp4?", query);
+ content = srs_strings_replace(content, "init.mp4?", query);
} else {
- content = srs_string_replace(content, "init.mp4", query);
+ content = srs_strings_replace(content, "init.mp4", query);
}
}
@@ -288,7 +288,7 @@ void SrsHlsStream::alive(std::string ctx, ISrsRequest *req)
SrsHlsVirtualConn *conn = new SrsHlsVirtualConn();
conn->req = req->copy();
conn->ctx = ctx;
- conn->request_time = srs_get_system_time();
+ conn->request_time = srs_time_now_cached();
map_ctx_info_.insert(make_pair(ctx, conn));
// Update the conn of stat client, which is used for receiving the event of kickoff.
@@ -304,7 +304,7 @@ void SrsHlsStream::alive(std::string ctx, ISrsRequest *req)
// Update alive time of context for virtual connection.
SrsHlsVirtualConn *conn = it->second;
if (!conn->interrupt) {
- conn->request_time = srs_get_system_time();
+ conn->request_time = srs_time_now_cached();
}
}
@@ -381,7 +381,7 @@ srs_error_t SrsHlsStream::on_timer(srs_utime_t interval)
SrsHlsVirtualConn *info = it->second;
srs_utime_t hls_window = _srs_config->get_hls_window(info->req->vhost);
- if (info->request_time + (2 * hls_window) < srs_get_system_time()) {
+ if (info->request_time + (2 * hls_window) < srs_time_now_cached()) {
SrsContextRestore(_srs_context->get_id());
_srs_context->set_id(SrsContextId().set_value(ctx));
@@ -666,14 +666,14 @@ srs_error_t SrsHttpStaticServer::mount_vhost(string vhost, string &pmount)
std::string dir = _srs_config->get_vhost_http_dir(vhost);
// replace the vhost variable
- mount = srs_string_replace(mount, "[vhost]", vhost);
- dir = srs_string_replace(dir, "[vhost]", vhost);
+ mount = srs_strings_replace(mount, "[vhost]", vhost);
+ dir = srs_strings_replace(dir, "[vhost]", vhost);
// remove the default vhost mount
- mount = srs_string_replace(mount, SRS_CONSTS_RTMP_DEFAULT_VHOST "/", "/");
+ mount = srs_strings_replace(mount, SRS_CONSTS_RTMP_DEFAULT_VHOST "/", "/");
// the dir mount must always ends with "/"
- if (mount != "/" && !srs_string_ends_with(mount, "/")) {
+ if (mount != "/" && !srs_strings_ends_with(mount, "/")) {
mount += "/";
}
diff --git a/trunk/src/app/srs_app_http_stream.cpp b/trunk/src/app/srs_app_http_stream.cpp
index ecf5bba5e..250a3ed84 100644
--- a/trunk/src/app/srs_app_http_stream.cpp
+++ b/trunk/src/app/srs_app_http_stream.cpp
@@ -655,9 +655,9 @@ srs_error_t SrsLiveStream::serve_http_impl(ISrsHttpResponseWriter *w, ISrsHttpMe
// Correct the app and stream by path, which is created from template.
// @remark Be careful that the stream has extension now, might cause identify fail.
- req->stream = srs_path_basename(r->path());
+ req->stream = srs_path_filepath_base(r->path());
// remove the extension of stream if have. for instance, test.flv -> test
- req->stream = srs_path_filename(req->stream);
+ req->stream = srs_path_filepath_filename(req->stream);
// update client ip
req->ip = hc->remote_ip();
@@ -745,7 +745,7 @@ srs_error_t SrsLiveStream::do_serve_http(SrsLiveSource *source, SrsLiveConsumer
bool has_video = _srs_config->get_vhost_http_remux_has_video(req->vhost);
bool guess_has_av = _srs_config->get_vhost_http_remux_guess_has_av(req->vhost);
- if (srs_string_ends_with(entry->pattern, ".flv")) {
+ if (srs_strings_ends_with(entry->pattern, ".flv")) {
w->header()->set_content_type("video/x-flv");
enc_desc = "FLV";
enc_raw = new SrsFlvStreamEncoder();
@@ -753,15 +753,15 @@ srs_error_t SrsLiveStream::do_serve_http(SrsLiveSource *source, SrsLiveConsumer
((SrsFlvStreamEncoder *)enc_raw)->set_has_audio(has_audio);
((SrsFlvStreamEncoder *)enc_raw)->set_has_video(has_video);
((SrsFlvStreamEncoder *)enc_raw)->set_guess_has_av(guess_has_av);
- } else if (srs_string_ends_with(entry->pattern, ".aac")) {
+ } else if (srs_strings_ends_with(entry->pattern, ".aac")) {
w->header()->set_content_type("audio/x-aac");
enc_desc = "AAC";
enc_raw = new SrsAacStreamEncoder();
- } else if (srs_string_ends_with(entry->pattern, ".mp3")) {
+ } else if (srs_strings_ends_with(entry->pattern, ".mp3")) {
w->header()->set_content_type("audio/mpeg");
enc_desc = "MP3";
enc_raw = new SrsMp3StreamEncoder();
- } else if (srs_string_ends_with(entry->pattern, ".ts")) {
+ } else if (srs_strings_ends_with(entry->pattern, ".ts")) {
w->header()->set_content_type("video/MP2T");
enc_desc = "TS";
enc_raw = new SrsTsStreamEncoder();
@@ -983,7 +983,7 @@ SrsLiveEntry::SrsLiveEntry(std::string m)
req = NULL;
- std::string ext = srs_path_filext(m);
+ std::string ext = srs_path_filepath_ext(m);
_is_flv = (ext == ".flv");
_is_ts = (ext == ".ts");
_is_mp3 = (ext == ".mp3");
@@ -1086,12 +1086,12 @@ srs_error_t SrsHttpStreamServer::http_mount(ISrsRequest *r)
std::string mount = tmpl->mount;
// replace the vhost variable
- mount = srs_string_replace(mount, "[vhost]", r->vhost);
- mount = srs_string_replace(mount, "[app]", r->app);
- mount = srs_string_replace(mount, "[stream]", r->stream);
+ mount = srs_strings_replace(mount, "[vhost]", r->vhost);
+ mount = srs_strings_replace(mount, "[app]", r->app);
+ mount = srs_strings_replace(mount, "[stream]", r->stream);
// remove the default vhost mount
- mount = srs_string_replace(mount, SRS_CONSTS_RTMP_DEFAULT_VHOST "/", "/");
+ mount = srs_strings_replace(mount, SRS_CONSTS_RTMP_DEFAULT_VHOST "/", "/");
entry = new SrsLiveEntry(mount);
@@ -1236,7 +1236,7 @@ srs_error_t SrsHttpStreamServer::hijack(ISrsHttpMessage *request, ISrsHttpHandle
// not-matched for "/livestream.flv", which is actually "/__defaultApp__/livestream.flv", HTTP not support default app.
// not-matched for "/live/show/livestream.flv"
string upath = request->path();
- if (srs_string_count(upath, "/") != srs_string_count(entry->mount, "/")) {
+ if (srs_strings_count(upath, "/") != srs_strings_count(entry->mount, "/")) {
return err;
}
diff --git a/trunk/src/app/srs_app_hybrid.cpp b/trunk/src/app/srs_app_hybrid.cpp
index 6304ec680..5820abbb7 100644
--- a/trunk/src/app/srs_app_hybrid.cpp
+++ b/trunk/src/app/srs_app_hybrid.cpp
@@ -639,7 +639,7 @@ srs_error_t SrsHybridServer::acquire_pid_file()
}
// write the pid
- string pid = srs_int2str(getpid());
+ string pid = srs_strconv_format_int(getpid());
if (write(fd, pid.c_str(), pid.length()) != (int)pid.length()) {
return srs_error_new(ERROR_SYSTEM_PID_WRITE_FILE, "write pid=%s to file=%s", pid.c_str(), pid_file.c_str());
}
@@ -819,7 +819,7 @@ srs_error_t srs_global_initialize()
_srs_reload_err = srs_success;
_srs_reload_state = SrsReloadStateInit;
- _srs_reload_id = srs_random_str(7);
+ _srs_reload_id = srs_rand_gen_str(7);
return err;
}
diff --git a/trunk/src/app/srs_app_ingest.cpp b/trunk/src/app/srs_app_ingest.cpp
index bf019490c..94c1c14ec 100644
--- a/trunk/src/app/srs_app_ingest.cpp
+++ b/trunk/src/app/srs_app_ingest.cpp
@@ -36,7 +36,7 @@ srs_error_t SrsIngesterFFMPEG::initialize(SrsFFMPEG *ff, string v, string i)
ffmpeg = ff;
vhost = v;
id = i;
- starttime = srs_get_system_time();
+ starttime = srs_time_now_cached();
return err;
}
@@ -48,7 +48,7 @@ string SrsIngesterFFMPEG::uri()
srs_utime_t SrsIngesterFFMPEG::alive()
{
- return srs_get_system_time() - starttime;
+ return srs_time_now_cached() - starttime;
}
bool SrsIngesterFFMPEG::equals(string v)
@@ -361,20 +361,20 @@ srs_error_t SrsIngester::initialize_ffmpeg(SrsFFMPEG *ffmpeg, SrsConfDirective *
std::string ip;
std::string ep = ip_ports[0];
- srs_parse_endpoint(ep, ip, port);
+ srs_net_split_for_listener(ep, ip, port);
}
std::string output = _srs_config->get_engine_output(engine);
// output stream, to other/self server
// ie. rtmp://localhost:1935/live/livestream_sd
- output = srs_string_replace(output, "[vhost]", vhost->arg0());
- output = srs_string_replace(output, "[port]", srs_int2str(port));
+ output = srs_strings_replace(output, "[vhost]", vhost->arg0());
+ output = srs_strings_replace(output, "[port]", srs_strconv_format_int(port));
output = srs_path_build_timestamp(output);
// Remove the only param with default vhost.
- output = srs_string_replace(output, "vhost=" SRS_CONSTS_RTMP_DEFAULT_VHOST, "");
- output = srs_string_replace(output, "?&", "?");
- output = srs_string_replace(output, "?/", "/"); // For params over app.
- output = srs_string_trim_end(output, "?");
+ output = srs_strings_replace(output, "vhost=" SRS_CONSTS_RTMP_DEFAULT_VHOST, "");
+ output = srs_strings_replace(output, "?&", "?");
+ output = srs_strings_replace(output, "?/", "/"); // For params over app.
+ output = srs_strings_trim_end(output, "?");
if (output.empty()) {
return srs_error_new(ERROR_ENCODER_NO_OUTPUT, "empty output url, ingest=%s", ingest->arg0().c_str());
}
@@ -384,8 +384,8 @@ srs_error_t SrsIngester::initialize_ffmpeg(SrsFFMPEG *ffmpeg, SrsConfDirective *
if (true) {
int port = SRS_CONSTS_RTMP_DEFAULT_PORT;
std::string tcUrl, schema, host, vhost2, param;
- srs_parse_rtmp_url(output, tcUrl, stream);
- srs_discovery_tc_url(tcUrl, schema, host, vhost2, app, stream, port, param);
+ srs_net_url_parse_rtmp_url(output, tcUrl, stream);
+ srs_net_url_parse_tcurl(tcUrl, schema, host, vhost2, app, stream, port, param);
}
std::string log_file = SRS_CONSTS_NULL_FILE; // disabled
@@ -474,7 +474,7 @@ void SrsIngester::show_ingest_log_message()
}
// random choose one ingester to report.
- int index = srs_random() % (int)ingesters.size();
+ int index = srs_rand_integer() % (int)ingesters.size();
SrsIngesterFFMPEG *ingester = ingesters.at(index);
// reportable
diff --git a/trunk/src/app/srs_app_latest_version.cpp b/trunk/src/app/srs_app_latest_version.cpp
index 21ae05daa..372954109 100644
--- a/trunk/src/app/srs_app_latest_version.cpp
+++ b/trunk/src/app/srs_app_latest_version.cpp
@@ -223,7 +223,7 @@ srs_error_t SrsLatestVersion::cycle()
}
string url;
- srs_utime_t starttime = srs_update_system_time();
+ srs_utime_t starttime = srs_time_now_realtime();
if ((err = query_latest_version(url)) != srs_success) {
srs_trace("query release err %s", srs_error_summary(err).c_str());
srs_freep(err); // Ignore any error.
@@ -231,7 +231,7 @@ srs_error_t SrsLatestVersion::cycle()
srs_trace("Finish query id=%s, session=%s, eip=%s, match=%s, stable=%s, cost=%dms, url=%s",
server_id_.c_str(), session_id_.c_str(), srs_get_public_internet_address().c_str(), match_version_.c_str(),
- stable_version_.c_str(), srsu2msi(srs_update_system_time() - starttime), url.c_str());
+ stable_version_.c_str(), srsu2msi(srs_time_now_realtime() - starttime), url.c_str());
srs_usleep(3600 * SRS_UTIME_SECONDS); // Every an hour.
}
@@ -249,8 +249,8 @@ srs_error_t SrsLatestVersion::query_latest_version(string &url)
<< "version=v" << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_REVISION
<< "&id=" << server_id_ << "&session=" << session_id_ << "&role=srs"
<< "&eip=" << srs_get_public_internet_address()
- << "&ts=" << srs_get_system_time()
- << "&alive=" << srsu2ms(srs_get_system_time() - srs_get_system_startup_time()) / 1000;
+ << "&ts=" << srs_time_now_cached()
+ << "&alive=" << srsu2ms(srs_time_now_cached() - srs_time_since_startup()) / 1000;
srs_build_features(ss);
SrsStatistic::instance()->dumps_hints_kv(ss);
url = ss.str();
diff --git a/trunk/src/app/srs_app_listener.cpp b/trunk/src/app/srs_app_listener.cpp
index 86ec4e4d3..d591cf589 100644
--- a/trunk/src/app/srs_app_listener.cpp
+++ b/trunk/src/app/srs_app_listener.cpp
@@ -255,7 +255,7 @@ SrsTcpListener *SrsTcpListener::set_endpoint(const std::string &endpoint)
{
std::string ip;
int port_;
- srs_parse_endpoint(endpoint, ip, port_);
+ srs_net_split_for_listener(endpoint, ip, port_);
return set_endpoint(ip, port_);
}
@@ -349,7 +349,7 @@ SrsMultipleTcpListeners *SrsMultipleTcpListeners::add(const std::vectorset_endpoint(ip, port));
@@ -694,7 +694,7 @@ srs_error_t SrsUdpMuxListener::cycle()
uint64_t nn_msgs_stage = 0;
uint64_t nn_msgs_last = 0;
uint64_t nn_loop = 0;
- srs_utime_t time_last = srs_get_system_time();
+ srs_utime_t time_last = srs_time_now_cached();
SrsUniquePtr pp_pkt_handler_err(new SrsErrorPithyPrint());
@@ -738,7 +738,7 @@ srs_error_t SrsUdpMuxListener::cycle()
_srs_context->set_id(cid);
// Append more information.
- err = srs_error_wrap(err, "size=%u, data=[%s]", skt.size(), srs_string_dumps_hex(skt.data(), skt.size(), 8).c_str());
+ err = srs_error_wrap(err, "size=%u, data=[%s]", skt.size(), srs_strings_dumps_hex(skt.data(), skt.size(), 8).c_str());
srs_warn("handle udp pkt, count=%u/%u, err: %s", pp_pkt_handler_err->nn_count, nn, srs_error_desc(err).c_str());
}
srs_freep(err);
@@ -752,11 +752,11 @@ srs_error_t SrsUdpMuxListener::cycle()
int pps_average = 0;
int pps_last = 0;
if (true) {
- if (srs_get_system_time() > srs_get_system_startup_time()) {
- pps_average = (int)(nn_msgs * SRS_UTIME_SECONDS / (srs_get_system_time() - srs_get_system_startup_time()));
+ if (srs_time_now_cached() > srs_time_since_startup()) {
+ pps_average = (int)(nn_msgs * SRS_UTIME_SECONDS / (srs_time_now_cached() - srs_time_since_startup()));
}
- if (srs_get_system_time() > time_last) {
- pps_last = (int)((nn_msgs - nn_msgs_last) * SRS_UTIME_SECONDS / (srs_get_system_time() - time_last));
+ if (srs_time_now_cached() > time_last) {
+ pps_last = (int)((nn_msgs - nn_msgs_last) * SRS_UTIME_SECONDS / (srs_time_now_cached() - time_last));
}
}
@@ -774,7 +774,7 @@ srs_error_t SrsUdpMuxListener::cycle()
srs_trace("<- RTC RECV #%d, udp %" PRId64 ", pps %d/%d%s, schedule %" PRId64,
srs_netfd_fileno(lfd), nn_msgs_stage, pps_average, pps_last, pps_unit.c_str(), nn_loop);
nn_msgs_last = nn_msgs;
- time_last = srs_get_system_time();
+ time_last = srs_time_now_cached();
nn_loop = 0;
nn_msgs_stage = 0;
}
diff --git a/trunk/src/app/srs_app_mpegts_udp.cpp b/trunk/src/app/srs_app_mpegts_udp.cpp
index fe057369d..ff526b505 100644
--- a/trunk/src/app/srs_app_mpegts_udp.cpp
+++ b/trunk/src/app/srs_app_mpegts_udp.cpp
@@ -52,7 +52,7 @@ srs_error_t SrsUdpCasterListener::initialize(SrsConfDirective *conf)
return srs_error_new(ERROR_STREAM_CASTER_PORT, "invalid port=%d", port);
}
- listener_->set_endpoint(srs_any_address_for_listener(), port)->set_label("MPEGTS");
+ listener_->set_endpoint(srs_net_address_any(), port)->set_label("MPEGTS");
if ((err = caster_->initialize(conf)) != srs_success) {
return srs_error_wrap(err, "init caster port=%d", port);
diff --git a/trunk/src/app/srs_app_ng_exec.cpp b/trunk/src/app/srs_app_ng_exec.cpp
index b79ba2bed..cb8a527cf 100644
--- a/trunk/src/app/srs_app_ng_exec.cpp
+++ b/trunk/src/app/srs_app_ng_exec.cpp
@@ -146,8 +146,8 @@ srs_error_t SrsNgExec::parse_exec_publish(ISrsRequest *req)
for (int i = 0; i < (int)ep->args.size(); i++) {
std::string epa = ep->args.at(i);
- if (srs_string_contains(epa, ">")) {
- vector epas = srs_string_split(epa, ">");
+ if (srs_strings_contains(epa, ">")) {
+ vector epas = srs_strings_split(epa, ">");
for (int j = 0; j < (int)epas.size(); j++) {
argv.push_back(parse(req, epas.at(j)));
if (j == 0) {
@@ -197,20 +197,20 @@ string SrsNgExec::parse(ISrsRequest *req, string tmpl)
{
string output = tmpl;
- output = srs_string_replace(output, "[vhost]", req->vhost);
- output = srs_string_replace(output, "[port]", srs_int2str(req->port));
- output = srs_string_replace(output, "[app]", req->app);
- output = srs_string_replace(output, "[stream]", req->stream);
+ output = srs_strings_replace(output, "[vhost]", req->vhost);
+ output = srs_strings_replace(output, "[port]", srs_strconv_format_int(req->port));
+ output = srs_strings_replace(output, "[app]", req->app);
+ output = srs_strings_replace(output, "[stream]", req->stream);
- output = srs_string_replace(output, "[tcUrl]", req->tcUrl);
- output = srs_string_replace(output, "[swfUrl]", req->swfUrl);
- output = srs_string_replace(output, "[pageUrl]", req->pageUrl);
+ output = srs_strings_replace(output, "[tcUrl]", req->tcUrl);
+ output = srs_strings_replace(output, "[swfUrl]", req->swfUrl);
+ output = srs_strings_replace(output, "[pageUrl]", req->pageUrl);
output = srs_path_build_timestamp(output);
if (output.find("[url]") != string::npos) {
- string url = srs_generate_rtmp_url(req->host, req->port, req->host, req->vhost, req->app, req->stream, req->param);
- output = srs_string_replace(output, "[url]", url);
+ string url = srs_net_url_encode_rtmp_url(req->host, req->port, req->host, req->vhost, req->app, req->stream, req->param);
+ output = srs_strings_replace(output, "[url]", url);
}
return output;
diff --git a/trunk/src/app/srs_app_pithy_print.cpp b/trunk/src/app/srs_app_pithy_print.cpp
index 3b460ba5f..596adcba3 100644
--- a/trunk/src/app/srs_app_pithy_print.cpp
+++ b/trunk/src/app/srs_app_pithy_print.cpp
@@ -136,14 +136,14 @@ bool SrsErrorPithyPrint::can_print(int error_code, uint32_t *pnn)
srs_utime_t tick = ticks[error_code];
if (!tick) {
- ticks[error_code] = tick = srs_get_system_time();
+ ticks[error_code] = tick = srs_time_now_cached();
}
- srs_utime_t diff = srs_get_system_time() - tick;
+ srs_utime_t diff = srs_time_now_cached() - tick;
diff = srs_max(0, diff);
stage->elapse(diff);
- ticks[error_code] = srs_get_system_time();
+ ticks[error_code] = srs_time_now_cached();
return new_stage || stage->can_print();
}
@@ -153,7 +153,7 @@ SrsAlonePithyPrint::SrsAlonePithyPrint() : info_(0)
// stage work for one print
info_.nb_clients = 1;
- previous_tick_ = srs_get_system_time();
+ previous_tick_ = srs_time_now_cached();
}
SrsAlonePithyPrint::~SrsAlonePithyPrint()
@@ -162,8 +162,8 @@ SrsAlonePithyPrint::~SrsAlonePithyPrint()
void SrsAlonePithyPrint::elapse()
{
- srs_utime_t diff = srs_get_system_time() - previous_tick_;
- previous_tick_ = srs_get_system_time();
+ srs_utime_t diff = srs_time_now_cached() - previous_tick_;
+ previous_tick_ = srs_time_now_cached();
diff = srs_max(0, diff);
@@ -183,7 +183,7 @@ SrsPithyPrint::SrsPithyPrint(int _stage_id)
stage_id = _stage_id;
cache_ = NULL;
client_id = enter_stage();
- previous_tick = srs_get_system_time();
+ previous_tick = srs_time_now_cached();
_age = 0;
}
@@ -344,12 +344,12 @@ void SrsPithyPrint::elapse()
}
srs_assert(stage != NULL);
- srs_utime_t diff = srs_get_system_time() - previous_tick;
+ srs_utime_t diff = srs_time_now_cached() - previous_tick;
diff = srs_max(0, diff);
stage->elapse(diff);
_age += diff;
- previous_tick = srs_get_system_time();
+ previous_tick = srs_time_now_cached();
}
bool SrsPithyPrint::can_print()
diff --git a/trunk/src/app/srs_app_process.cpp b/trunk/src/app/srs_app_process.cpp
index e7ed1231c..75bc526ff 100644
--- a/trunk/src/app/srs_app_process.cpp
+++ b/trunk/src/app/srs_app_process.cpp
@@ -63,25 +63,25 @@ srs_error_t SrsProcess::initialize(string binary, vector argv)
std::string nnffp = (i < (int)argv.size() - 2) ? argv[i + 2] : "";
// >file
- if (srs_string_starts_with(ffp, ">")) {
+ if (srs_strings_starts_with(ffp, ">")) {
stdout_file = ffp.substr(1);
continue;
}
// 1>file
- if (srs_string_starts_with(ffp, "1>")) {
+ if (srs_strings_starts_with(ffp, "1>")) {
stdout_file = ffp.substr(2);
continue;
}
// 2>file
- if (srs_string_starts_with(ffp, "2>")) {
+ if (srs_strings_starts_with(ffp, "2>")) {
stderr_file = ffp.substr(2);
continue;
}
// 1 >X
- if (ffp == "1" && srs_string_starts_with(nffp, ">")) {
+ if (ffp == "1" && srs_strings_starts_with(nffp, ">")) {
if (nffp == ">") {
// 1 > file
if (!nnffp.empty()) {
@@ -90,7 +90,7 @@ srs_error_t SrsProcess::initialize(string binary, vector argv)
}
} else {
// 1 >file
- stdout_file = srs_string_trim_start(nffp, ">");
+ stdout_file = srs_strings_trim_start(nffp, ">");
}
// skip the >
i++;
@@ -98,7 +98,7 @@ srs_error_t SrsProcess::initialize(string binary, vector argv)
}
// 2 >X
- if (ffp == "2" && srs_string_starts_with(nffp, ">")) {
+ if (ffp == "2" && srs_strings_starts_with(nffp, ">")) {
if (nffp == ">") {
// 2 > file
if (!nnffp.empty()) {
@@ -107,7 +107,7 @@ srs_error_t SrsProcess::initialize(string binary, vector argv)
}
} else {
// 2 >file
- stderr_file = srs_string_trim_start(nffp, ">");
+ stderr_file = srs_strings_trim_start(nffp, ">");
}
// skip the >
i++;
@@ -117,8 +117,8 @@ srs_error_t SrsProcess::initialize(string binary, vector argv)
params.push_back(ffp);
}
- actual_cli = srs_join_vector_string(params, " ");
- cli = srs_join_vector_string(argv, " ");
+ actual_cli = srs_strings_join(params, " ");
+ cli = srs_strings_join(argv, " ");
return err;
}
diff --git a/trunk/src/app/srs_app_recv_thread.cpp b/trunk/src/app/srs_app_recv_thread.cpp
index 8f8253000..c19562e4c 100644
--- a/trunk/src/app/srs_app_recv_thread.cpp
+++ b/trunk/src/app/srs_app_recv_thread.cpp
@@ -366,7 +366,7 @@ srs_error_t SrsPublishRecvThread::consume(SrsCommonMessage *msg)
// log to show the time of recv thread.
srs_verbose("recv thread now=%" PRId64 "us, got msg time=%" PRId64 "ms, size=%d",
- srs_update_system_time(), msg->header.timestamp, msg->size);
+ srs_time_now_realtime(), msg->header.timestamp, msg->size);
// the rtmp connection will handle this message
err = _conn->handle_publish_message(source_, msg);
diff --git a/trunk/src/app/srs_app_rtc_api.cpp b/trunk/src/app/srs_app_rtc_api.cpp
index 0c6477b8c..420ce12b8 100644
--- a/trunk/src/app/srs_app_rtc_api.cpp
+++ b/trunk/src/app/srs_app_rtc_api.cpp
@@ -128,10 +128,10 @@ srs_error_t SrsGoApiRtcPlay::do_serve_http(ISrsHttpResponseWriter *w, ISrsHttpMe
ruc.req_->ip = clientip;
ruc.api_ = api;
- srs_parse_rtmp_url(streamurl, ruc.req_->tcUrl, ruc.req_->stream);
+ srs_net_url_parse_rtmp_url(streamurl, ruc.req_->tcUrl, ruc.req_->stream);
- srs_discovery_tc_url(ruc.req_->tcUrl, ruc.req_->schema, ruc.req_->host, ruc.req_->vhost,
- ruc.req_->app, ruc.req_->stream, ruc.req_->port, ruc.req_->param);
+ srs_net_url_parse_tcurl(ruc.req_->tcUrl, ruc.req_->schema, ruc.req_->host, ruc.req_->vhost,
+ ruc.req_->app, ruc.req_->stream, ruc.req_->port, ruc.req_->param);
// discovery vhost, resolve the vhost from config
SrsConfDirective *parsed_vhost = _srs_config->get_vhost(ruc.req_->vhost);
@@ -249,7 +249,7 @@ srs_error_t SrsGoApiRtcPlay::serve_http(ISrsHttpResponseWriter *w, ISrsHttpMessa
string local_sdp_str = os.str();
// Filter the \r\n to \\r\\n for JSON.
- string local_sdp_escaped = srs_string_replace(local_sdp_str.c_str(), "\r\n", "\\r\\n");
+ string local_sdp_escaped = srs_strings_replace(local_sdp_str.c_str(), "\r\n", "\\r\\n");
ruc->local_sdp_str_ = local_sdp_str;
ruc->session_id_ = session->username();
@@ -257,7 +257,7 @@ srs_error_t SrsGoApiRtcPlay::serve_http(ISrsHttpResponseWriter *w, ISrsHttpMessa
srs_trace("RTC username=%s, dtls=%u, srtp=%u, offer=%dB, answer=%dB", session->username().c_str(),
ruc->dtls_, ruc->srtp_, ruc->remote_sdp_str_.length(), local_sdp_escaped.length());
- srs_trace("RTC remote offer: %s", srs_string_replace(ruc->remote_sdp_str_.c_str(), "\r\n", "\\r\\n").c_str());
+ srs_trace("RTC remote offer: %s", srs_strings_replace(ruc->remote_sdp_str_.c_str(), "\r\n", "\\r\\n").c_str());
srs_trace("RTC local answer: %s", local_sdp_escaped.c_str());
return err;
@@ -424,12 +424,12 @@ srs_error_t SrsGoApiRtcPublish::do_serve_http(ISrsHttpResponseWriter *w, ISrsHtt
ruc.req_->ip = clientip;
ruc.api_ = api;
- srs_parse_rtmp_url(streamurl, ruc.req_->tcUrl, ruc.req_->stream);
- srs_discovery_tc_url(ruc.req_->tcUrl, ruc.req_->schema, ruc.req_->host, ruc.req_->vhost,
- ruc.req_->app, ruc.req_->stream, ruc.req_->port, ruc.req_->param);
+ srs_net_url_parse_rtmp_url(streamurl, ruc.req_->tcUrl, ruc.req_->stream);
+ srs_net_url_parse_tcurl(ruc.req_->tcUrl, ruc.req_->schema, ruc.req_->host, ruc.req_->vhost,
+ ruc.req_->app, ruc.req_->stream, ruc.req_->port, ruc.req_->param);
// Identify WebRTC publisher by param upstream=rtc
- ruc.req_->param = srs_string_trim_start(ruc.req_->param + "&upstream=rtc", "&");
+ ruc.req_->param = srs_strings_trim_start(ruc.req_->param + "&upstream=rtc", "&");
// discovery vhost, resolve the vhost from config
SrsConfDirective *parsed_vhost = _srs_config->get_vhost(ruc.req_->vhost);
@@ -524,7 +524,7 @@ srs_error_t SrsGoApiRtcPublish::serve_http(ISrsHttpResponseWriter *w, ISrsHttpMe
string local_sdp_str = os.str();
// Filter the \r\n to \\r\\n for JSON.
- string local_sdp_escaped = srs_string_replace(local_sdp_str.c_str(), "\r\n", "\\r\\n");
+ string local_sdp_escaped = srs_strings_replace(local_sdp_str.c_str(), "\r\n", "\\r\\n");
ruc->local_sdp_str_ = local_sdp_str;
ruc->session_id_ = session->username();
@@ -532,7 +532,7 @@ srs_error_t SrsGoApiRtcPublish::serve_http(ISrsHttpResponseWriter *w, ISrsHttpMe
srs_trace("RTC username=%s, offer=%dB, answer=%dB", session->username().c_str(),
ruc->remote_sdp_str_.length(), local_sdp_escaped.length());
- srs_trace("RTC remote offer: %s", srs_string_replace(ruc->remote_sdp_str_.c_str(), "\r\n", "\\r\\n").c_str());
+ srs_trace("RTC remote offer: %s", srs_strings_replace(ruc->remote_sdp_str_.c_str(), "\r\n", "\\r\\n").c_str());
srs_trace("RTC local answer: %s", local_sdp_escaped.c_str());
return err;
@@ -655,8 +655,8 @@ srs_error_t SrsGoApiRtcWhip::serve_http(ISrsHttpResponseWriter *w, ISrsHttpMessa
// Setup the content type to SDP.
w->header()->set("Content-Type", "application/sdp");
// The location for DELETE resource, not required by SRS, but required by WHIP.
- w->header()->set("Location", srs_fmt("/rtc/v1/whip/?action=delete&token=%s&app=%s&stream=%s&session=%s",
- ruc.token_.c_str(), ruc.req_->app.c_str(), ruc.req_->stream.c_str(), ruc.session_id_.c_str()));
+ w->header()->set("Location", srs_fmt_sprintf("/rtc/v1/whip/?action=delete&token=%s&app=%s&stream=%s&session=%s",
+ ruc.token_.c_str(), ruc.req_->app.c_str(), ruc.req_->stream.c_str(), ruc.session_id_.c_str()));
w->header()->set_content_length((int64_t)sdp.length());
// Must be 201, see https://datatracker.ietf.org/doc/draft-ietf-wish-whip/
w->write_header(201);
@@ -697,7 +697,7 @@ srs_error_t SrsGoApiRtcWhip::do_serve_http(ISrsHttpResponseWriter *w, ISrsHttpMe
action = "publish";
}
// For whip-play or whep, parsed to https://datatracker.ietf.org/doc/draft-murillo-whep/
- if (srs_string_ends_with(r->path(), "/whip-play/") || srs_string_ends_with(r->path(), "/whep/")) {
+ if (srs_strings_ends_with(r->path(), "/whip-play/") || srs_strings_ends_with(r->path(), "/whep/")) {
action = "play";
}
diff --git a/trunk/src/app/srs_app_rtc_conn.cpp b/trunk/src/app/srs_app_rtc_conn.cpp
index 077274776..f3440042c 100644
--- a/trunk/src/app/srs_app_rtc_conn.cpp
+++ b/trunk/src/app/srs_app_rtc_conn.cpp
@@ -847,7 +847,7 @@ srs_error_t SrsRtcPlayStream::on_rtcp_nack(SrsRtcpNack *rtcp)
// If NACK disabled, print a log.
if (!nack_enabled_) {
vector sns = rtcp->get_lost_sns();
- srs_trace("RTC: NACK ssrc=%u, seq=%s, ignored", ssrc, srs_join_vector_string(sns, ",").c_str());
+ srs_trace("RTC: NACK ssrc=%u, seq=%s, ignored", ssrc, srs_strings_join(sns, ",").c_str());
return err;
}
@@ -1361,7 +1361,7 @@ srs_error_t SrsRtcPublishStream::on_twcc(uint16_t sn)
{
srs_error_t err = srs_success;
- srs_utime_t now = srs_get_system_time();
+ srs_utime_t now = srs_time_now_cached();
err = rtcp_twcc_.recv_packet(sn, now);
return err;
@@ -1538,13 +1538,13 @@ srs_error_t SrsRtcPublishStream::send_periodic_twcc()
if (last_time_send_twcc_) {
uint32_t nn = 0;
- srs_utime_t duration = srs_duration(last_time_send_twcc_, srs_get_system_time());
+ srs_utime_t duration = srs_time_since(last_time_send_twcc_, srs_time_now_cached());
if (duration > 130 * SRS_UTIME_MILLISECONDS && twcc_epp_->can_print(0, &nn)) {
srs_warn2(TAG_LARGE_TIMER, "twcc delay %dms > 100ms, count=%u/%u",
srsu2msi(duration), nn, twcc_epp_->nn_count);
}
}
- last_time_send_twcc_ = srs_get_system_time();
+ last_time_send_twcc_ = srs_time_now_cached();
if (!rtcp_twcc_.need_feedback()) {
return err;
@@ -1648,7 +1648,7 @@ srs_error_t SrsRtcPublishStream::on_rtcp_xr(SrsRtcpXr *rtcp)
uint32_t lrr = stream.read_4bytes();
uint32_t dlrr = stream.read_4bytes();
- SrsNtp cur_ntp = SrsNtp::from_time_ms(srs_update_system_time() / 1000);
+ SrsNtp cur_ntp = SrsNtp::from_time_ms(srs_time_now_realtime() / 1000);
uint32_t compact_ntp = (cur_ntp.ntp_second_ << 16) | (cur_ntp.ntp_fractions_ >> 16);
int rtt_ntp = compact_ntp - lrr - dlrr;
@@ -1954,7 +1954,7 @@ srs_error_t SrsRtcConnection::add_publisher(SrsRtcUserConfig *ruc, SrsSdp &local
// TODO: FIXME: Change to api of stream desc.
if ((err = negotiate_publish_capability(ruc, stream_desc.get())) != srs_success) {
- return srs_error_wrap(err, "publish negotiate, offer=%s", srs_string_replace(ruc->remote_sdp_str_.c_str(), "\r\n", "\\r\\n").c_str());
+ return srs_error_wrap(err, "publish negotiate, offer=%s", srs_strings_replace(ruc->remote_sdp_str_.c_str(), "\r\n", "\\r\\n").c_str());
}
if ((err = generate_publish_local_sdp(req, local_sdp, stream_desc.get(), ruc->remote_sdp_.is_unified(), ruc->audio_before_video_)) != srs_success) {
@@ -1993,7 +1993,7 @@ srs_error_t SrsRtcConnection::add_player(SrsRtcUserConfig *ruc, SrsSdp &local_sd
std::map play_sub_relations;
if ((err = negotiate_play_capability(ruc, play_sub_relations)) != srs_success) {
- return srs_error_wrap(err, "play negotiate, offer=%s", srs_string_replace(ruc->remote_sdp_str_.c_str(), "\r\n", "\\r\\n").c_str());
+ return srs_error_wrap(err, "play negotiate, offer=%s", srs_strings_replace(ruc->remote_sdp_str_.c_str(), "\r\n", "\\r\\n").c_str());
}
if (!play_sub_relations.size()) {
@@ -2032,7 +2032,7 @@ srs_error_t SrsRtcConnection::initialize(ISrsRequest *r, bool dtls, bool srtp, s
srs_error_t err = srs_success;
username_ = username;
- token_ = srs_random_str(9);
+ token_ = srs_rand_gen_str(9);
req_ = r->copy();
SrsSessionConfig *cfg = &local_sdp.session_negotiate_;
@@ -2042,7 +2042,7 @@ srs_error_t SrsRtcConnection::initialize(ISrsRequest *r, bool dtls, bool srtp, s
// TODO: FIXME: Support reload.
session_timeout = _srs_config->get_rtc_stun_timeout(req_->vhost);
- last_stun_time = srs_get_system_time();
+ last_stun_time = srs_time_now_cached();
nack_enabled_ = _srs_config->get_rtc_nack_enabled(req_->vhost);
@@ -2062,8 +2062,8 @@ srs_error_t SrsRtcConnection::on_rtcp(char *unprotected_buf, int nb_unprotected_
SrsRtcpCompound rtcp_compound;
if (srs_success != (err = rtcp_compound.decode(buffer.get()))) {
return srs_error_wrap(err, "decode rtcp plaintext=%u, bytes=[%s], at=%s", nb_unprotected_buf,
- srs_string_dumps_hex(unprotected_buf, nb_unprotected_buf, 8).c_str(),
- srs_string_dumps_hex(buffer->head(), buffer->left(), 8).c_str());
+ srs_strings_dumps_hex(unprotected_buf, nb_unprotected_buf, 8).c_str(),
+ srs_strings_dumps_hex(buffer->head(), buffer->left(), 8).c_str());
}
SrsRtcpCommon *rtcp_raw = NULL;
@@ -2073,7 +2073,7 @@ srs_error_t SrsRtcConnection::on_rtcp(char *unprotected_buf, int nb_unprotected_
if (srs_success != err) {
return srs_error_wrap(err, "plaintext=%u, bytes=[%s], rtcp=(%u,%u,%u,%u)", nb_unprotected_buf,
- srs_string_dumps_hex(rtcp->data(), rtcp->size(), rtcp->size()).c_str(),
+ srs_strings_dumps_hex(rtcp->data(), rtcp->size(), rtcp->size()).c_str(),
rtcp->get_rc(), rtcp->type(), rtcp->get_ssrc(), rtcp->size());
}
}
@@ -2282,12 +2282,12 @@ srs_error_t SrsRtcConnection::on_dtls_alert(std::string type, std::string desc)
bool SrsRtcConnection::is_alive()
{
- return last_stun_time + session_timeout > srs_get_system_time();
+ return last_stun_time + session_timeout > srs_time_now_cached();
}
void SrsRtcConnection::alive()
{
- last_stun_time = srs_get_system_time();
+ last_stun_time = srs_time_now_cached();
}
SrsRtcUdpNetwork *SrsRtcConnection::udp()
@@ -2366,7 +2366,7 @@ srs_error_t SrsRtcConnection::send_rtcp_rr(uint32_t ssrc, SrsRtpRingBuffer *rtp_
if (last_send_systime > 0) {
rr_lsr = (last_send_ntp.ntp_second_ << 16) | (last_send_ntp.ntp_fractions_ >> 16);
- uint32_t dlsr = (srs_update_system_time() - last_send_systime) / 1000;
+ uint32_t dlsr = (srs_time_now_realtime() - last_send_systime) / 1000;
rr_dlsr = ((dlsr / 1000) << 16) | ((dlsr % 1000) * 65536 / 1000);
}
@@ -2413,7 +2413,7 @@ srs_error_t SrsRtcConnection::send_rtcp_xr_rrtr(uint32_t ssrc)
| NTP timestamp, least significant word |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
- srs_utime_t now = srs_update_system_time();
+ srs_utime_t now = srs_time_now_realtime();
SrsNtp cur_ntp = SrsNtp::from_time_ms(now / 1000);
char buf[kRtpPacketSize];
@@ -2969,7 +2969,7 @@ srs_error_t SrsRtcConnection::generate_publish_local_sdp(ISrsRequest *req, SrsSd
local_sdp.version_ = "0";
local_sdp.username_ = RTMP_SIG_SRS_SERVER;
- local_sdp.session_id_ = srs_int2str((int64_t)this);
+ local_sdp.session_id_ = srs_strconv_format_int((int64_t)this);
local_sdp.session_version_ = "2";
local_sdp.nettype_ = "IN";
local_sdp.addrtype_ = "IP4";
@@ -3347,7 +3347,7 @@ srs_error_t SrsRtcConnection::generate_play_local_sdp(ISrsRequest *req, SrsSdp &
local_sdp.version_ = "0";
local_sdp.username_ = RTMP_SIG_SRS_SERVER;
- local_sdp.session_id_ = srs_int2str((int64_t)this);
+ local_sdp.session_id_ = srs_strconv_format_int((int64_t)this);
local_sdp.session_version_ = "2";
local_sdp.nettype_ = "IN";
local_sdp.addrtype_ = "IP4";
@@ -3361,7 +3361,7 @@ srs_error_t SrsRtcConnection::generate_play_local_sdp(ISrsRequest *req, SrsSdp &
local_sdp.group_policy_ = "BUNDLE";
- std::string cname = srs_random_str(16);
+ std::string cname = srs_rand_gen_str(16);
if (audio_before_video) {
if ((err = generate_play_local_sdp_for_audio(local_sdp, stream_desc, cname)) != srs_success) {
@@ -3458,11 +3458,11 @@ srs_error_t SrsRtcConnection::generate_play_local_sdp_for_video(SrsSdp &local_sd
if (!unified_plan) {
// for plan b, we only add one m= for video track.
if (i == 0) {
- video_track_generate_play_offer(track, "video-" + srs_int2str(i), local_sdp);
+ video_track_generate_play_offer(track, "video-" + srs_strconv_format_int(i), local_sdp);
}
} else {
// unified plan SDP, generate a m= for each video track.
- video_track_generate_play_offer(track, "video-" + srs_int2str(i), local_sdp);
+ video_track_generate_play_offer(track, "video-" + srs_strconv_format_int(i), local_sdp);
}
SrsMediaDesc &local_media_desc = local_sdp.media_descs_.back();
diff --git a/trunk/src/app/srs_app_rtc_dtls.cpp b/trunk/src/app/srs_app_rtc_dtls.cpp
index 537c2d853..ae14430a7 100644
--- a/trunk/src/app/srs_app_rtc_dtls.cpp
+++ b/trunk/src/app/srs_app_rtc_dtls.cpp
@@ -300,7 +300,7 @@ srs_error_t SrsDtlsCertificate::initialize()
X509_NAME *subject = X509_NAME_new();
srs_assert(subject);
- int serial = (int)srs_random();
+ int serial = (int)srs_rand_integer();
ASN1_INTEGER_set(X509_get_serialNumber(dtls_cert), serial);
const std::string &aor = RTMP_SIG_SRS_DOMAIN;
@@ -440,7 +440,7 @@ srs_error_t SrsDtlsImpl::write_dtls_data(void *data, int size)
if (size > 0 && (err = callback_->write_dtls_data(data, size)) != srs_success) {
return srs_error_wrap(err, "dtls send size=%u, data=[%s]", size,
- srs_string_dumps_hex((char *)data, size, 32).c_str());
+ srs_strings_dumps_hex((char *)data, size, 32).c_str());
}
// change_cipher_spec(20), alert(21), handshake(22), application_data(23)
@@ -563,7 +563,7 @@ srs_error_t SrsDtlsImpl::on_dtls(char *data, int nb_data)
if ((err = do_on_dtls(data, nb_data)) != srs_success) {
return srs_error_wrap(err, "on_dtls size=%u, data=[%s]", nb_data,
- srs_string_dumps_hex(data, nb_data, 32).c_str());
+ srs_strings_dumps_hex(data, nb_data, 32).c_str());
}
return err;
@@ -602,11 +602,11 @@ srs_error_t SrsDtlsImpl::do_on_dtls(char *data, int nb_data)
}
} else {
srs_trace("DTLS: read r0=%d, r1=%d, padding=%d, done=%d, data=[%s]",
- r0, r1, BIO_ctrl_pending(bio_in), handshake_done_for_us, srs_string_dumps_hex(buf, r0, 32).c_str());
+ r0, r1, BIO_ctrl_pending(bio_in), handshake_done_for_us, srs_strings_dumps_hex(buf, r0, 32).c_str());
if ((err = callback_->on_dtls_application_data(buf, r0)) != srs_success) {
return srs_error_wrap(err, "on DTLS data, done=%d, r1=%d, size=%u, data=[%s]", handshake_done_for_us,
- r1, r0, srs_string_dumps_hex(buf, r0, 32).c_str());
+ r1, r0, srs_strings_dumps_hex(buf, r0, 32).c_str());
}
}
diff --git a/trunk/src/app/srs_app_rtc_network.cpp b/trunk/src/app/srs_app_rtc_network.cpp
index 5086fecd8..0330148ad 100644
--- a/trunk/src/app/srs_app_rtc_network.cpp
+++ b/trunk/src/app/srs_app_rtc_network.cpp
@@ -878,7 +878,7 @@ srs_error_t SrsRtcTcpConn::handshake()
bool is_rtp_or_rtcp = srs_is_rtp_or_rtcp((uint8_t *)pkt_, npkt);
if (!is_stun) {
return srs_error_new(ERROR_RTC_TCP_PACKET, "invalid packet stun=%d, rtp/rtcp=%d, pkt=%s",
- is_stun, is_rtp_or_rtcp, srs_string_dumps_hex(pkt_, npkt, 8).c_str());
+ is_stun, is_rtp_or_rtcp, srs_strings_dumps_hex(pkt_, npkt, 8).c_str());
}
// Find session by ping(BindingRequest).
diff --git a/trunk/src/app/srs_app_rtc_queue.cpp b/trunk/src/app/srs_app_rtc_queue.cpp
index 7f543e96a..5c7b54fbe 100644
--- a/trunk/src/app/srs_app_rtc_queue.cpp
+++ b/trunk/src/app/srs_app_rtc_queue.cpp
@@ -193,7 +193,7 @@ SrsNackOption::SrsNackOption()
SrsRtpNackInfo::SrsRtpNackInfo()
{
- generate_time_ = srs_update_system_time();
+ generate_time_ = srs_time_now_realtime();
pre_req_nack_time_ = 0;
req_nack_count_ = 0;
}
@@ -259,7 +259,7 @@ void SrsRtpNackForReceiver::get_nack_seqs(SrsRtcpNack &seqs, uint32_t &timeout_n
return;
}
- srs_utime_t now = srs_get_system_time();
+ srs_utime_t now = srs_time_now_cached();
srs_utime_t interval = now - pre_check_time_;
if (interval < opts_.nack_check_interval) {
diff --git a/trunk/src/app/srs_app_rtc_sdp.cpp b/trunk/src/app/srs_app_rtc_sdp.cpp
index 20943a61f..61aa4c6b8 100644
--- a/trunk/src/app/srs_app_rtc_sdp.cpp
+++ b/trunk/src/app/srs_app_rtc_sdp.cpp
@@ -57,9 +57,9 @@ srs_error_t srs_parse_h264_fmtp(const std::string &fmtp, H264SpecificParam &h264
{
srs_error_t err = srs_success;
- std::vector vec = srs_string_split(fmtp, ";");
+ std::vector vec = srs_strings_split(fmtp, ";");
for (size_t i = 0; i < vec.size(); ++i) {
- std::vector kv = srs_string_split(vec[i], "=");
+ std::vector kv = srs_strings_split(vec[i], "=");
if (kv.size() != 2)
continue;
@@ -97,9 +97,9 @@ srs_error_t srs_parse_h265_fmtp(const std::string &fmtp, H265SpecificParam &h265
{
srs_error_t err = srs_success;
- std::vector vec = srs_string_split(fmtp, ";");
+ std::vector vec = srs_strings_split(fmtp, ";");
for (size_t i = 0; i < vec.size(); ++i) {
- std::vector kv = srs_string_split(vec[i], "=");
+ std::vector kv = srs_strings_split(vec[i], "=");
if (kv.size() != 2)
continue;
@@ -245,7 +245,7 @@ srs_error_t SrsSSRCInfo::encode(std::ostringstream &os)
// As GB28181 format:
// y=0100008888
if (label_ == "gb28181") {
- os << "y=" << (cname_.empty() ? srs_fmt("%u", ssrc_) : cname_) << kCRLF;
+ os << "y=" << (cname_.empty() ? srs_fmt_sprintf("%u", ssrc_) : cname_) << kCRLF;
return err;
}
@@ -836,7 +836,7 @@ srs_error_t SrsSdp::parse(const std::string &sdp_str)
}
// Strip the space of line, for pion WebRTC client.
- line = srs_string_trim_end(line, " ");
+ line = srs_strings_trim_end(line, " ");
if ((err = parse_line(line)) != srs_success) {
return srs_error_wrap(err, "parse sdp line failed");
@@ -1175,12 +1175,12 @@ srs_error_t SrsSdp::parse_gb28181_ssrc(const std::string &content)
// to standard format:
// a=ssrc:0100008888 cname:0100008888
// a=ssrc:0100008888 label:gb28181
- string cname = srs_fmt("a=ssrc:%s cname:%s", content.c_str(), content.c_str());
+ string cname = srs_fmt_sprintf("a=ssrc:%s cname:%s", content.c_str(), content.c_str());
if ((err = media_descs_.back().parse_line(cname)) != srs_success) {
return srs_error_wrap(err, "parse gb %s cname", content.c_str());
}
- string label = srs_fmt("a=ssrc:%s label:gb28181", content.c_str());
+ string label = srs_fmt_sprintf("a=ssrc:%s label:gb28181", content.c_str());
if ((err = media_descs_.back().parse_line(label)) != srs_success) {
return srs_error_wrap(err, "parse gb %s label", content.c_str());
}
@@ -1195,7 +1195,7 @@ srs_error_t SrsSdp::parse_attr_group(const std::string &value)
// Overlook the OBS WHIP group LS, as it is utilized for synchronizing the playback of
// the relevant media streams, see https://datatracker.ietf.org/doc/html/rfc5888#section-7
- if (srs_string_starts_with(value, "LS")) {
+ if (srs_strings_starts_with(value, "LS")) {
return err;
}
diff --git a/trunk/src/app/srs_app_rtc_server.cpp b/trunk/src/app/srs_app_rtc_server.cpp
index d0003da97..5b6dfc034 100644
--- a/trunk/src/app/srs_app_rtc_server.cpp
+++ b/trunk/src/app/srs_app_rtc_server.cpp
@@ -6,6 +6,8 @@
#include
+#include
+
#include
using namespace std;
@@ -59,6 +61,29 @@ extern SrsPps *_srs_pps_rnack2;
extern SrsPps *_srs_pps_rhnack;
extern SrsPps *_srs_pps_rmnack;
+// TODO: FIXME: Replace by ST dns resolve.
+string srs_dns_resolve(string host, int &family)
+{
+ addrinfo hints;
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = family;
+
+ addrinfo *r_raw = NULL;
+ if (getaddrinfo(host.c_str(), NULL, &hints, &r_raw)) {
+ return "";
+ }
+ SrsUniquePtr r(r_raw, freeaddrinfo);
+
+ char shost[64];
+ memset(shost, 0, sizeof(shost));
+ if (getnameinfo(r->ai_addr, r->ai_addrlen, shost, sizeof(shost), NULL, 0, NI_NUMERICHOST)) {
+ return "";
+ }
+
+ family = r->ai_family;
+ return string(shost);
+}
+
SrsRtcBlackhole::SrsRtcBlackhole()
{
blackhole = false;
@@ -90,7 +115,7 @@ srs_error_t SrsRtcBlackhole::initialize()
string host;
int port;
- srs_parse_hostport(blackhole_ep, host, port);
+ srs_net_split_hostport(blackhole_ep, host, port);
srs_freep(blackhole_addr);
blackhole_addr = new sockaddr_in();
@@ -167,12 +192,12 @@ srs_error_t api_server_as_candidates(string api, set &candidate_ips)
}
// Whether add domain name.
- if (!srs_is_ipv4(hostname) && _srs_config->get_keep_api_domain()) {
+ if (!srs_net_is_ipv4(hostname) && _srs_config->get_keep_api_domain()) {
candidate_ips.insert(hostname);
}
// Try to parse the domain name if not IP.
- if (!srs_is_ipv4(hostname) && _srs_config->get_resolve_api_domain()) {
+ if (!srs_net_is_ipv4(hostname) && _srs_config->get_resolve_api_domain()) {
int family = 0;
string ip = srs_dns_resolve(hostname, family);
if (ip.empty() || ip == SRS_CONSTS_LOCALHOST || ip == SRS_CONSTS_LOOPBACK || ip == SRS_CONSTS_LOOPBACK6) {
@@ -184,7 +209,7 @@ srs_error_t api_server_as_candidates(string api, set &candidate_ips)
}
// If hostname is IP, use it.
- if (srs_is_ipv4(hostname)) {
+ if (srs_net_is_ipv4(hostname)) {
candidate_ips.insert(hostname);
}
@@ -346,7 +371,7 @@ srs_error_t SrsRtcServer::listen_udp()
return srs_error_new(ERROR_RTC_PORT, "invalid port=%d", port);
}
- string ip = srs_any_address_for_listener();
+ string ip = srs_net_address_any();
srs_assert(listeners.empty());
int nn_listeners = _srs_config->get_rtc_server_reuseport();
@@ -543,8 +568,8 @@ srs_error_t SrsRtcServer::do_create_session(SrsRtcUserConfig *ruc, SrsSdp &local
// All tracks default as inactive, so we must enable them.
session->set_all_tracks_status(req->get_stream_url(), ruc->publish_, true);
- std::string local_pwd = ruc->req_->ice_pwd_.empty() ? srs_random_str(32) : ruc->req_->ice_pwd_;
- std::string local_ufrag = ruc->req_->ice_ufrag_.empty() ? srs_random_str(8) : ruc->req_->ice_ufrag_;
+ std::string local_pwd = ruc->req_->ice_pwd_.empty() ? srs_rand_gen_str(32) : ruc->req_->ice_pwd_;
+ std::string local_ufrag = ruc->req_->ice_ufrag_.empty() ? srs_rand_gen_str(8) : ruc->req_->ice_ufrag_;
// TODO: FIXME: Rename for a better name, it's not an username.
std::string username = "";
while (true) {
@@ -554,7 +579,7 @@ srs_error_t SrsRtcServer::do_create_session(SrsRtcUserConfig *ruc, SrsSdp &local
}
// Username conflict, regenerate a new one.
- local_ufrag = srs_random_str(8);
+ local_ufrag = srs_rand_gen_str(8);
}
local_sdp.set_ice_ufrag(local_ufrag);
@@ -572,9 +597,9 @@ srs_error_t SrsRtcServer::do_create_session(SrsRtcUserConfig *ruc, SrsSdp &local
for (set::iterator it = candidates.begin(); it != candidates.end(); ++it) {
string hostname;
int uport = udp_port;
- srs_parse_hostport(*it, hostname, uport);
+ srs_net_split_hostport(*it, hostname, uport);
int tport = tcp_port;
- srs_parse_hostport(*it, hostname, tport);
+ srs_net_split_hostport(*it, hostname, tport);
if (protocol == "udp") {
local_sdp.add_candidate("udp", hostname, uport, "host");
@@ -587,7 +612,7 @@ srs_error_t SrsRtcServer::do_create_session(SrsRtcUserConfig *ruc, SrsSdp &local
}
vector v = vector(candidates.begin(), candidates.end());
- srs_trace("RTC: Use candidates %s, protocol=%s", srs_join_vector_string(v, ", ").c_str(), protocol.c_str());
+ srs_trace("RTC: Use candidates %s, protocol=%s", srs_strings_join(v, ", ").c_str(), protocol.c_str());
}
// Setup the negotiate DTLS by config.
diff --git a/trunk/src/app/srs_app_rtc_server.hpp b/trunk/src/app/srs_app_rtc_server.hpp
index d1eed212f..177609437 100644
--- a/trunk/src/app/srs_app_rtc_server.hpp
+++ b/trunk/src/app/srs_app_rtc_server.hpp
@@ -142,4 +142,7 @@ public:
// Manager for RTC connections.
extern SrsResourceManager *_srs_rtc_manager;
+// The dns resolve utility, return the resolved ip address.
+extern std::string srs_dns_resolve(std::string host, int &family);
+
#endif
diff --git a/trunk/src/app/srs_app_rtc_source.cpp b/trunk/src/app/srs_app_rtc_source.cpp
index 916b41107..7e55c84a9 100644
--- a/trunk/src/app/srs_app_rtc_source.cpp
+++ b/trunk/src/app/srs_app_rtc_source.cpp
@@ -443,7 +443,7 @@ bool SrsRtcSource::stream_is_dead()
}
// Delay cleanup source.
- srs_utime_t now = srs_get_system_time();
+ srs_utime_t now = srs_time_now_cached();
if (now < stream_die_at_ + SRS_RTC_SOURCE_CLEANUP) {
return false;
}
@@ -473,7 +473,7 @@ void SrsRtcSource::init_for_play_before_publishing()
stream_desc->audio_track_desc_ = audio_track_desc;
audio_track_desc->type_ = "audio";
- audio_track_desc->id_ = "audio-" + srs_random_str(8);
+ audio_track_desc->id_ = "audio-" + srs_rand_gen_str(8);
uint32_t audio_ssrc = SrsRtcSSRCGenerator::instance()->generate_ssrc();
audio_track_desc->ssrc_ = audio_ssrc;
@@ -490,7 +490,7 @@ void SrsRtcSource::init_for_play_before_publishing()
stream_desc->video_track_descs_.push_back(h264_track_desc);
h264_track_desc->type_ = "video";
- h264_track_desc->id_ = "video-h264-" + srs_random_str(8);
+ h264_track_desc->id_ = "video-h264-" + srs_rand_gen_str(8);
uint32_t h264_ssrc = SrsRtcSSRCGenerator::instance()->generate_ssrc();
h264_track_desc->ssrc_ = h264_ssrc;
@@ -508,7 +508,7 @@ void SrsRtcSource::init_for_play_before_publishing()
stream_desc->video_track_descs_.push_back(h265_track_desc);
h265_track_desc->type_ = "video";
- h265_track_desc->id_ = "video-h265-" + srs_random_str(8);
+ h265_track_desc->id_ = "video-h265-" + srs_rand_gen_str(8);
uint32_t h265_ssrc = SrsRtcSSRCGenerator::instance()->generate_ssrc();
h265_track_desc->ssrc_ = h265_ssrc;
@@ -624,7 +624,7 @@ void SrsRtcSource::on_consumer_destroy(SrsRtcConsumer *consumer)
// Destroy and cleanup source when no publishers and consumers.
if (!is_created_ && consumers.empty()) {
- stream_die_at_ = srs_get_system_time();
+ stream_die_at_ = srs_time_now_cached();
}
}
@@ -739,7 +739,7 @@ void SrsRtcSource::on_unpublish()
// Destroy and cleanup source when no publishers and consumers.
if (consumers.empty()) {
- stream_die_at_ = srs_get_system_time();
+ stream_die_at_ = srs_time_now_cached();
}
}
@@ -1647,7 +1647,7 @@ srs_error_t SrsRtcFrameBuilderAudioPacketCache::process_packet(SrsRtpPacket *src
srs_error_t err = srs_success;
uint16_t seq = src->header.get_sequence();
- srs_utime_t now = srs_update_system_time();
+ srs_utime_t now = srs_time_now_realtime();
if (!initialized_) {
last_audio_seq_num_ = seq - 1;
@@ -2732,7 +2732,7 @@ SrsMediaPayloadType SrsAudioPayload::generate_media_payload_type()
media_payload_type.encoding_name_ = name_;
media_payload_type.clock_rate_ = sample_;
if (channel_ != 0) {
- media_payload_type.encoding_param_ = srs_int2str(channel_);
+ media_payload_type.encoding_param_ = srs_strconv_format_int(channel_);
}
media_payload_type.rtcp_fb_ = rtcp_fbs_;
@@ -2815,7 +2815,7 @@ SrsMediaPayloadType SrsRedPayload::generate_media_payload_type()
media_payload_type.encoding_name_ = name_;
media_payload_type.clock_rate_ = sample_;
if (channel_ != 0) {
- media_payload_type.encoding_param_ = srs_int2str(channel_);
+ media_payload_type.encoding_param_ = srs_strconv_format_int(channel_);
}
media_payload_type.rtcp_fb_ = rtcp_fbs_;
@@ -3087,7 +3087,7 @@ void SrsRtcRecvTrack::update_send_report_time(const SrsNtp &ntp, uint32_t rtp_ti
last_sender_report_rtp_time_ = rtp_time;
// TODO: FIXME: Use system wall clock.
- last_sender_report_sys_time_ = srs_update_system_time();
+ last_sender_report_sys_time_ = srs_time_now_realtime();
if (last_sender_report_rtp_time1_ > 0) {
// WebRTC using sender report to sync audio/video timestamp, because audio video have different timebase,
diff --git a/trunk/src/app/srs_app_rtmp_conn.cpp b/trunk/src/app/srs_app_rtmp_conn.cpp
index 85dde9422..a69647728 100644
--- a/trunk/src/app/srs_app_rtmp_conn.cpp
+++ b/trunk/src/app/srs_app_rtmp_conn.cpp
@@ -187,7 +187,7 @@ SrsRtmpConn::SrsRtmpConn(SrsServer *svr, SrsRtmpTransport *transport, string cip
manager = svr;
ip = cip;
port = cport;
- create_time = srsu2ms(srs_get_system_time());
+ create_time = srsu2ms(srs_time_now_cached());
#ifdef SRS_APM
span_main_ = _srs_apm->dummy();
span_connect_ = _srs_apm->dummy();
@@ -252,7 +252,7 @@ std::string SrsRtmpConn::desc()
std::string srs_ipv4_string(uint32_t rip)
{
- return srs_fmt("%d.%d.%d.%d", uint8_t(rip >> 24), uint8_t(rip >> 16), uint8_t(rip >> 8), uint8_t(rip));
+ return srs_fmt_sprintf("%d.%d.%d.%d", uint8_t(rip >> 24), uint8_t(rip >> 16), uint8_t(rip >> 8), uint8_t(rip));
}
// TODO: return detail message when error for client.
@@ -585,12 +585,12 @@ srs_error_t SrsRtmpConn::stream_service_cycle()
return srs_error_wrap(err, "rtmp: identify client");
}
- srs_discovery_tc_url(req->tcUrl, req->schema, req->host, req->vhost, req->app, req->stream, req->port, req->param);
+ srs_net_url_parse_tcurl(req->tcUrl, req->schema, req->host, req->vhost, req->app, req->stream, req->port, req->param);
// guess stream name
if (req->stream.empty()) {
string app = req->app, param = req->param;
- srs_guess_stream_by_app(req->app, req->param, req->stream);
+ srs_net_url_guess_stream(req->app, req->param, req->stream);
srs_trace("Guessing by app=%s, param=%s to app=%s, param=%s, stream=%s", app.c_str(), param.c_str(), req->app.c_str(), req->param.c_str(), req->stream.c_str());
}
@@ -612,7 +612,7 @@ srs_error_t SrsRtmpConn::stream_service_cycle()
req->vhost = parsed_vhost->arg0();
}
#ifdef SRS_APM
- span_client_->attr("vhost", req->vhost)->attr("http.host", req->host)->attr("http.server_name", req->vhost)->attr("http.target", srs_fmt("/%s/%s", req->app.c_str(), req->stream.c_str()));
+ span_client_->attr("vhost", req->vhost)->attr("http.host", req->host)->attr("http.server_name", req->vhost)->attr("http.target", srs_fmt_sprintf("/%s/%s", req->app.c_str(), req->stream.c_str()));
#endif
if (req->schema.empty() || req->vhost.empty() || req->port == 0 || req->app.empty()) {
@@ -828,7 +828,7 @@ srs_error_t SrsRtmpConn::playing(SrsSharedPtr source)
return srs_error_wrap(err, "discover coworkers, url=%s", url.c_str());
}
- string rurl = srs_generate_rtmp_url(host, port, req->host, req->vhost, req->app, req->stream, req->param);
+ string rurl = srs_net_url_encode_rtmp_url(host, port, req->host, req->vhost, req->app, req->stream, req->param);
srs_trace("rtmp: redirect in cluster, from=%s:%d, target=%s:%d, url=%s, rurl=%s",
req->host.c_str(), req->port, host.c_str(), port, url.c_str(), rurl.c_str());
@@ -913,7 +913,7 @@ srs_error_t SrsRtmpConn::do_playing(SrsSharedPtr source, SrsLiveC
srsu2msi(send_min_interval), srsu2msi(mw_sleep), mw_msgs, realtime, tcp_nodelay);
#ifdef SRS_APM
- SrsUniquePtr span(_srs_apm->span("play-cycle")->set_kind(SrsApmKindProducer)->as_child(span_client_)->attr("realtime", srs_fmt("%d", realtime))->end());
+ SrsUniquePtr span(_srs_apm->span("play-cycle")->set_kind(SrsApmKindProducer)->as_child(span_client_)->attr("realtime", srs_fmt_sprintf("%d", realtime))->end());
#endif
while (true) {
@@ -961,7 +961,7 @@ srs_error_t SrsRtmpConn::do_playing(SrsSharedPtr source, SrsLiveC
#ifdef SRS_APM
// TODO: Do not use pithy print for frame span.
- ISrsApmSpan *sample = _srs_apm->span("play-frame")->set_kind(SrsApmKindConsumer)->as_child(span.get())->attr("msgs", srs_fmt("%d", count))->attr("kbps", srs_fmt("%d", kbps->get_send_kbps_30s()));
+ ISrsApmSpan *sample = _srs_apm->span("play-frame")->set_kind(SrsApmKindConsumer)->as_child(span.get())->attr("msgs", srs_fmt_sprintf("%d", count))->attr("kbps", srs_fmt_sprintf("%d", kbps->get_send_kbps_30s()));
srs_freep(sample);
#endif
}
@@ -1088,7 +1088,7 @@ srs_error_t SrsRtmpConn::do_publishing(SrsSharedPtr source, SrsPu
}
#ifdef SRS_APM
- SrsUniquePtr span(_srs_apm->span("publish-cycle")->set_kind(SrsApmKindProducer)->as_child(span_client_)->attr("timeout", srs_fmt("%d", srsu2msi(publish_normal_timeout)))->end());
+ SrsUniquePtr span(_srs_apm->span("publish-cycle")->set_kind(SrsApmKindProducer)->as_child(span_client_)->attr("timeout", srs_fmt_sprintf("%d", srsu2msi(publish_normal_timeout)))->end());
#endif
// Response the start publishing message, let client start to publish messages.
@@ -1150,7 +1150,7 @@ srs_error_t SrsRtmpConn::do_publishing(SrsSharedPtr source, SrsPu
#ifdef SRS_APM
// TODO: Do not use pithy print for frame span.
- ISrsApmSpan *sample = _srs_apm->span("publish-frame")->set_kind(SrsApmKindConsumer)->as_child(span.get())->attr("msgs", srs_fmt("%" PRId64, nb_frames))->attr("kbps", srs_fmt("%d", kbps->get_recv_kbps_30s()));
+ ISrsApmSpan *sample = _srs_apm->span("publish-frame")->set_kind(SrsApmKindConsumer)->as_child(span.get())->attr("msgs", srs_fmt_sprintf("%" PRId64, nb_frames))->attr("kbps", srs_fmt_sprintf("%d", kbps->get_recv_kbps_30s()));
srs_freep(sample);
#endif
}
@@ -1448,7 +1448,7 @@ srs_error_t SrsRtmpConn::check_edge_token_traverse_auth()
// select the origin.
string server;
int port = SRS_CONSTS_RTMP_DEFAULT_PORT;
- srs_parse_hostport(hostport, server, port);
+ srs_net_split_hostport(hostport, server, port);
SrsUniquePtr transport(new SrsTcpClient(server, port, SRS_EDGE_TOKEN_TRAVERSE_TIMEOUT));
if ((err = transport->connect()) != srs_success) {
@@ -1716,7 +1716,7 @@ srs_error_t SrsRtmpConn::cycle()
// for error or exception report.
SrsUniquePtr span_final(_srs_apm->span("final")->set_kind(SrsApmKindServer)->as_child(span_client_));
if (srs_error_code(err) != 0) {
- span_final->record_error(err)->set_status(SrsApmStatusError, srs_fmt("fail code=%d", srs_error_code(err)));
+ span_final->record_error(err)->set_status(SrsApmStatusError, srs_fmt_sprintf("fail code=%d", srs_error_code(err)));
}
#endif
diff --git a/trunk/src/app/srs_app_rtsp_conn.cpp b/trunk/src/app/srs_app_rtsp_conn.cpp
index 19f1fc304..aa2fa8d2e 100644
--- a/trunk/src/app/srs_app_rtsp_conn.cpp
+++ b/trunk/src/app/srs_app_rtsp_conn.cpp
@@ -549,7 +549,7 @@ srs_error_t SrsRtspConnection::do_cycle()
} else if (req->is_describe()) {
// create session.
if (session_id_.empty()) {
- session_id_ = srs_random_str(8);
+ session_id_ = srs_rand_gen_str(8);
}
SrsUniquePtr res(new SrsRtspDescribeResponse((int)req->seq));
@@ -573,7 +573,7 @@ srs_error_t SrsRtspConnection::do_cycle()
}
// Filter the \r\n to \\r\\n for JSON.
- std::string local_sdp_escaped = srs_string_replace(sdp.c_str(), "\r\n", "\\r\\n");
+ std::string local_sdp_escaped = srs_strings_replace(sdp.c_str(), "\r\n", "\\r\\n");
srs_trace("RTSP: DESCRIBE cseq=%ld, session=%s, sdp: %s", req->seq, session_id_.c_str(), local_sdp_escaped.c_str());
} else if (req->is_setup()) {
srs_assert(req->transport);
@@ -595,7 +595,7 @@ srs_error_t SrsRtspConnection::do_cycle()
res->transport->copy(req->transport);
res->session = session_id_;
- res->ssrc = srs_int2str(ssrc);
+ res->ssrc = srs_strconv_format_int(ssrc);
res->client_port_min = req->transport->client_port_min;
res->client_port_max = req->transport->client_port_max;
// TODO: FIXME: listen local port
@@ -672,21 +672,21 @@ const SrsContextId &SrsRtspConnection::context_id()
bool SrsRtspConnection::is_alive()
{
- return last_stun_time + session_timeout > srs_get_system_time();
+ return last_stun_time + session_timeout > srs_time_now_cached();
}
void SrsRtspConnection::alive()
{
- last_stun_time = srs_get_system_time();
+ last_stun_time = srs_time_now_cached();
}
srs_error_t SrsRtspConnection::do_describe(SrsRtspRequest *req, std::string &sdp)
{
srs_error_t err = srs_success;
- srs_parse_rtmp_url(req->uri, request_->tcUrl, request_->stream);
+ srs_net_url_parse_rtmp_url(req->uri, request_->tcUrl, request_->stream);
- srs_discovery_tc_url(request_->tcUrl, request_->schema, request_->host, request_->vhost,
- request_->app, request_->stream, request_->port, request_->param);
+ srs_net_url_parse_tcurl(request_->tcUrl, request_->schema, request_->host, request_->vhost,
+ request_->app, request_->stream, request_->port, request_->param);
// discovery vhost, resolve the vhost from config
SrsConfDirective *parsed_vhost = _srs_config->get_vhost(request_->vhost);
@@ -722,13 +722,13 @@ srs_error_t SrsRtspConnection::do_describe(SrsRtspRequest *req, std::string &sdp
SrsRtcTrackDescription *audio_desc = source_->audio_desc();
if (audio_desc) {
SrsRtcTrackDescription *audio_track_desc = audio_desc->copy();
- audio_track_desc->id_ = srs_int2str(track_id);
+ audio_track_desc->id_ = srs_strconv_format_int(track_id);
tracks_.insert(std::make_pair(audio_track_desc->ssrc_, audio_track_desc));
SrsMediaDesc media_audio("audio");
media_audio.port_ = 0; // Port 0 indicates no UDP transport available
media_audio.protos_ = "RTP/AVP"; // MUST be RTP/AVP
- media_audio.control_ = req->uri + "/trackID=" + srs_int2str(track_id);
+ media_audio.control_ = req->uri + "/trackID=" + srs_strconv_format_int(track_id);
media_audio.recvonly_ = true;
media_audio.rtcp_mux_ = true;
@@ -740,7 +740,7 @@ srs_error_t SrsRtspConnection::do_describe(SrsRtspRequest *req, std::string &sdp
// if the payload is opus, and the encoding_param_ is channel
SrsAudioPayload *ap = dynamic_cast(audio_track_desc->media_);
if (ap) {
- ps_audio.encoding_param_ = srs_int2str(ap->channel_);
+ ps_audio.encoding_param_ = srs_strconv_format_int(ap->channel_);
// Append the AAC config hex to the fmtp line.
if (ap->name_ == "MPEG4-GENERIC" && !ap->aac_config_hex_.empty()) {
@@ -763,13 +763,13 @@ srs_error_t SrsRtspConnection::do_describe(SrsRtspRequest *req, std::string &sdp
SrsRtcTrackDescription *video_desc = source_->video_desc();
if (video_desc) {
SrsRtcTrackDescription *video_track_desc = video_desc->copy();
- video_track_desc->id_ = srs_int2str(track_id);
+ video_track_desc->id_ = srs_strconv_format_int(track_id);
tracks_.insert(std::make_pair(video_track_desc->ssrc_, video_track_desc));
SrsMediaDesc media_video("video");
media_video.port_ = 0; // Port 0 indicates no UDP transport available
media_video.protos_ = "RTP/AVP"; // MUST be RTP/AVP
- media_video.control_ = req->uri + "/trackID=" + srs_int2str(track_id);
+ media_video.control_ = req->uri + "/trackID=" + srs_strconv_format_int(track_id);
media_video.recvonly_ = true;
media_video.rtcp_mux_ = true;
@@ -886,7 +886,7 @@ srs_error_t SrsRtspConnection::http_hooks_on_play(ISrsRequest *req)
srs_error_t SrsRtspConnection::get_ssrc_by_stream_id(uint32_t stream_id, uint32_t *ssrc)
{
for (std::map::iterator it = tracks_.begin(); it != tracks_.end(); ++it) {
- if (it->second->id_ == srs_int2str(stream_id)) {
+ if (it->second->id_ == srs_strconv_format_int(stream_id)) {
*ssrc = it->second->ssrc_;
return srs_success;
}
diff --git a/trunk/src/app/srs_app_rtsp_source.cpp b/trunk/src/app/srs_app_rtsp_source.cpp
index 42bf2f1f0..ad70b167c 100644
--- a/trunk/src/app/srs_app_rtsp_source.cpp
+++ b/trunk/src/app/srs_app_rtsp_source.cpp
@@ -295,7 +295,7 @@ bool SrsRtspSource::stream_is_dead()
}
// Delay cleanup source.
- srs_utime_t now = srs_get_system_time();
+ srs_utime_t now = srs_time_now_cached();
if (now < stream_die_at_ + SRS_RTSP_SOURCE_CLEANUP) {
return false;
}
@@ -396,7 +396,7 @@ void SrsRtspSource::on_consumer_destroy(SrsRtspConsumer *consumer)
// Destroy and cleanup source when no publishers and consumers.
if (!is_created_ && consumers.empty()) {
- stream_die_at_ = srs_get_system_time();
+ stream_die_at_ = srs_time_now_cached();
}
}
@@ -458,7 +458,7 @@ void SrsRtspSource::on_unpublish()
// Destroy and cleanup source when no publishers and consumers.
if (consumers.empty()) {
- stream_die_at_ = srs_get_system_time();
+ stream_die_at_ = srs_time_now_cached();
}
}
@@ -542,7 +542,7 @@ srs_error_t SrsRtspRtpBuilder::initialize_audio_track(SrsAudioCodecId codec)
// Create audio track description from actual format data
SrsUniquePtr audio_desc(new SrsRtcTrackDescription());
audio_desc->type_ = "audio";
- audio_desc->id_ = "audio-" + srs_random_str(8);
+ audio_desc->id_ = "audio-" + srs_rand_gen_str(8);
audio_desc->direction_ = "recvonly";
// Generate SSRC for this track
@@ -574,7 +574,7 @@ srs_error_t SrsRtspRtpBuilder::initialize_audio_track(SrsAudioCodecId codec)
if (!asc.empty()) {
int hex_len = asc.size() * 2;
SrsUniquePtr hex_buf(new char[hex_len + 1]);
- srs_data_to_hex(hex_buf.get(), (const uint8_t *)asc.data(), asc.size());
+ srs_hex_encode_to_string(hex_buf.get(), (const uint8_t *)asc.data(), asc.size());
hex_buf.get()[hex_len] = '\0'; // Null terminate
std::string config_hex = std::string(hex_buf.get());
@@ -615,7 +615,7 @@ srs_error_t SrsRtspRtpBuilder::initialize_video_track(SrsVideoCodecId codec)
// Create video track description from actual format data
SrsUniquePtr video_desc(new SrsRtcTrackDescription());
video_desc->type_ = "video";
- video_desc->id_ = "video-" + codec_name + "-" + srs_random_str(8);
+ video_desc->id_ = "video-" + codec_name + "-" + srs_rand_gen_str(8);
video_desc->direction_ = "recvonly";
// Generate SSRC for this track
diff --git a/trunk/src/app/srs_app_security.cpp b/trunk/src/app/srs_app_security.cpp
index 2827f1cb2..97e12c2d2 100644
--- a/trunk/src/app/srs_app_security.cpp
+++ b/trunk/src/app/srs_app_security.cpp
@@ -70,8 +70,8 @@ srs_error_t SrsSecurity::allow_check(SrsConfDirective *rules, SrsRtmpConnType ty
}
allow_rules++;
- string cidr_ipv4 = srs_get_cidr_ipv4(rule->arg1());
- string cidr_mask = srs_get_cidr_mask(rule->arg1());
+ string cidr_ipv4 = srs_net_get_cidr_ipv4(rule->arg1());
+ string cidr_mask = srs_net_get_cidr_mask(rule->arg1());
switch (type) {
case SrsRtmpConnPlay:
@@ -85,7 +85,7 @@ srs_error_t SrsSecurity::allow_check(SrsConfDirective *rules, SrsRtmpConnType ty
if (rule->arg1() == "all" || rule->arg1() == ip) {
return srs_success; // OK
}
- if (srs_is_ipv4(cidr_ipv4) && cidr_mask != "" && srs_ipv4_within_mask(ip, cidr_ipv4, cidr_mask)) {
+ if (srs_net_is_ipv4(cidr_ipv4) && cidr_mask != "" && srs_net_ipv4_within_mask(ip, cidr_ipv4, cidr_mask)) {
return srs_success; // OK
}
break;
@@ -100,7 +100,7 @@ srs_error_t SrsSecurity::allow_check(SrsConfDirective *rules, SrsRtmpConnType ty
if (rule->arg1() == "all" || rule->arg1() == ip) {
return srs_success; // OK
}
- if (srs_is_ipv4(cidr_ipv4) && cidr_mask != "" && srs_ipv4_within_mask(ip, cidr_ipv4, cidr_mask)) {
+ if (srs_net_is_ipv4(cidr_ipv4) && cidr_mask != "" && srs_net_ipv4_within_mask(ip, cidr_ipv4, cidr_mask)) {
return srs_success; // OK
}
break;
@@ -125,8 +125,8 @@ srs_error_t SrsSecurity::deny_check(SrsConfDirective *rules, SrsRtmpConnType typ
continue;
}
- string cidr_ipv4 = srs_get_cidr_ipv4(rule->arg1());
- string cidr_mask = srs_get_cidr_mask(rule->arg1());
+ string cidr_ipv4 = srs_net_get_cidr_ipv4(rule->arg1());
+ string cidr_mask = srs_net_get_cidr_mask(rule->arg1());
switch (type) {
case SrsRtmpConnPlay:
@@ -140,7 +140,7 @@ srs_error_t SrsSecurity::deny_check(SrsConfDirective *rules, SrsRtmpConnType typ
if (rule->arg1() == "all" || rule->arg1() == ip) {
return srs_error_new(ERROR_SYSTEM_SECURITY_DENY, "deny by rule<%s>", rule->arg1().c_str());
}
- if (srs_is_ipv4(cidr_ipv4) && cidr_mask != "" && srs_ipv4_within_mask(ip, cidr_ipv4, cidr_mask)) {
+ if (srs_net_is_ipv4(cidr_ipv4) && cidr_mask != "" && srs_net_ipv4_within_mask(ip, cidr_ipv4, cidr_mask)) {
return srs_error_new(ERROR_SYSTEM_SECURITY_DENY, "deny by rule<%s>", rule->arg1().c_str());
}
break;
@@ -155,7 +155,7 @@ srs_error_t SrsSecurity::deny_check(SrsConfDirective *rules, SrsRtmpConnType typ
if (rule->arg1() == "all" || rule->arg1() == ip) {
return srs_error_new(ERROR_SYSTEM_SECURITY_DENY, "deny by rule<%s>", rule->arg1().c_str());
}
- if (srs_is_ipv4(cidr_ipv4) && cidr_mask != "" && srs_ipv4_within_mask(ip, cidr_ipv4, cidr_mask)) {
+ if (srs_net_is_ipv4(cidr_ipv4) && cidr_mask != "" && srs_net_ipv4_within_mask(ip, cidr_ipv4, cidr_mask)) {
return srs_error_new(ERROR_SYSTEM_SECURITY_DENY, "deny by rule<%s>", rule->arg1().c_str());
}
break;
diff --git a/trunk/src/app/srs_app_server.cpp b/trunk/src/app/srs_app_server.cpp
index 6c5e3152f..eacd7ae92 100644
--- a/trunk/src/app/srs_app_server.cpp
+++ b/trunk/src/app/srs_app_server.cpp
@@ -258,7 +258,7 @@ srs_error_t SrsInotifyWorker::start()
// #define IN_ONESHOT 0x80000000 /* only send event once */
// Watch the config directory events.
- string config_dir = srs_path_dirname(_srs_config->config());
+ string config_dir = srs_path_filepath_dir(_srs_config->config());
uint32_t mask = IN_MODIFY | IN_CREATE | IN_MOVED_TO;
int watch_conf = 0;
if ((watch_conf = ::inotify_add_watch(fd, config_dir.c_str(), mask)) < 0) {
@@ -281,7 +281,7 @@ srs_error_t SrsInotifyWorker::cycle()
#if !defined(SRS_OSX) && !defined(SRS_CYGWIN64)
string config_path = _srs_config->config();
- string config_file = srs_path_basename(config_path);
+ string config_file = srs_path_filepath_base(config_path);
string k8s_file = "..data";
while (true) {
@@ -515,7 +515,7 @@ srs_error_t SrsServer::initialize()
bool rtc = _srs_config->get_rtc_server_enabled();
bool rtc_tcp = _srs_config->get_rtc_server_tcp_enabled();
- string rtc_listen = srs_int2str(_srs_config->get_rtc_server_tcp_listen());
+ string rtc_listen = srs_strconv_format_int(_srs_config->get_rtc_server_tcp_listen());
// If enabled and listen is the same value, resue port for WebRTC over TCP.
if (stream && rtc && rtc_tcp && http_listen == rtc_listen) {
srs_trace("WebRTC tcp=%s reuses http=%s server", rtc_listen.c_str(), http_listen.c_str());
@@ -647,7 +647,7 @@ srs_error_t SrsServer::listen()
// Start WebRTC over TCP listener.
if (!reuse_rtc_over_server_ && _srs_config->get_rtc_server_tcp_enabled()) {
- webrtc_listener_->set_endpoint(srs_int2str(_srs_config->get_rtc_server_tcp_listen()))->set_label("WebRTC");
+ webrtc_listener_->set_endpoint(srs_strconv_format_int(_srs_config->get_rtc_server_tcp_listen()))->set_label("WebRTC");
if ((err = webrtc_listener_->listen()) != srs_success) {
return srs_error_wrap(err, "webrtc tcp listen");
}
@@ -656,7 +656,7 @@ srs_error_t SrsServer::listen()
#ifdef SRS_RTSP
// Start RTSP listener. RTC is a critical dependency.
if (_srs_config->get_rtsp_server_enabled()) {
- rtsp_listener_->set_endpoint(srs_int2str(_srs_config->get_rtsp_server_listen()))->set_label("RTSP");
+ rtsp_listener_->set_endpoint(srs_strconv_format_int(_srs_config->get_rtsp_server_listen()))->set_label("RTSP");
if ((err = rtsp_listener_->listen()) != srs_success) {
return srs_error_wrap(err, "rtsp listen");
}
@@ -1066,7 +1066,7 @@ srs_error_t SrsServer::do_cycle()
SrsReloadState state = SrsReloadStateInit;
_srs_reload_state = SrsReloadStateInit;
srs_freep(_srs_reload_err);
- _srs_reload_id = srs_random_str(7);
+ _srs_reload_id = srs_rand_gen_str(7);
err = _srs_config->reload(&state);
_srs_reload_state = state;
_srs_reload_err = srs_error_copy(err);
diff --git a/trunk/src/app/srs_app_source.cpp b/trunk/src/app/srs_app_source.cpp
index 61f9e1ca2..b30983d60 100644
--- a/trunk/src/app/srs_app_source.cpp
+++ b/trunk/src/app/srs_app_source.cpp
@@ -1533,8 +1533,8 @@ srs_error_t SrsOriginHub::create_backend_forwarders(bool &applied)
// create temp Request by url
SrsUniquePtr req(new SrsRequest());
- srs_parse_rtmp_url(url, req->tcUrl, req->stream);
- srs_discovery_tc_url(req->tcUrl, req->schema, req->host, req->vhost, req->app, req->stream, req->port, req->param);
+ srs_net_url_parse_rtmp_url(url, req->tcUrl, req->stream);
+ srs_net_url_parse_tcurl(req->tcUrl, req->schema, req->host, req->vhost, req->app, req->stream, req->port, req->param);
// create forwarder
SrsForwarder *forwarder = new SrsForwarder(this);
@@ -1977,7 +1977,7 @@ bool SrsLiveSource::stream_is_dead()
}
// Delay cleanup source.
- srs_utime_t now = srs_get_system_time();
+ srs_utime_t now = srs_time_now_cached();
if (now < stream_die_at_ + SRS_SOURCE_CLEANUP) {
return false;
}
@@ -1996,7 +1996,7 @@ bool SrsLiveSource::publisher_is_idle_for(srs_utime_t timeout)
return false;
}
- srs_utime_t now = srs_get_system_time();
+ srs_utime_t now = srs_time_now_cached();
if (now > publisher_idle_at_ + timeout) {
return true;
}
@@ -2324,7 +2324,7 @@ srs_error_t SrsLiveSource::on_audio_imp(SrsSharedPtrMessage *msg)
bool drop_for_reduce = false;
if (is_sequence_header && meta->previous_ash() && _srs_config->get_reduce_sequence_header(req->vhost)) {
if (meta->previous_ash()->size == msg->size) {
- drop_for_reduce = srs_bytes_equals(meta->previous_ash()->payload, msg->payload, msg->size);
+ drop_for_reduce = srs_bytes_equal(meta->previous_ash()->payload, msg->payload, msg->size);
srs_warn("drop for reduce sh audio, size=%d", msg->size);
}
}
@@ -2441,7 +2441,7 @@ srs_error_t SrsLiveSource::on_video_imp(SrsSharedPtrMessage *msg)
bool drop_for_reduce = false;
if (is_sequence_header && meta->previous_vsh() && _srs_config->get_reduce_sequence_header(req->vhost)) {
if (meta->previous_vsh()->size == msg->size) {
- drop_for_reduce = srs_bytes_equals(meta->previous_vsh()->payload, msg->payload, msg->size);
+ drop_for_reduce = srs_bytes_equal(meta->previous_vsh()->payload, msg->payload, msg->size);
srs_warn("drop for reduce sh video, size=%d", msg->size);
}
}
@@ -2631,7 +2631,7 @@ srs_error_t SrsLiveSource::on_publish()
// When no players, the publisher is idle now.
if (consumers.empty()) {
- publisher_idle_at_ = srs_get_system_time();
+ publisher_idle_at_ = srs_time_now_cached();
}
return err;
@@ -2680,7 +2680,7 @@ void SrsLiveSource::on_unpublish()
// no consumer, stream is die.
if (consumers.empty()) {
- stream_die_at_ = srs_get_system_time();
+ stream_die_at_ = srs_time_now_cached();
}
// Note that we should never set to unpublish before any other handler is done, especially the handler
@@ -2767,17 +2767,17 @@ void SrsLiveSource::on_consumer_destroy(SrsLiveConsumer *consumer)
// If no publishers, the stream is die.
if (can_publish_) {
- stream_die_at_ = srs_get_system_time();
+ stream_die_at_ = srs_time_now_cached();
}
// For edge server, the stream die when the last player quit, because the edge stream is created by player
// activities, so it should die when all players quit.
if (_srs_config->get_vhost_is_edge(req->vhost)) {
- stream_die_at_ = srs_get_system_time();
+ stream_die_at_ = srs_time_now_cached();
}
// When no players, the publisher is idle now.
- publisher_idle_at_ = srs_get_system_time();
+ publisher_idle_at_ = srs_time_now_cached();
}
}
diff --git a/trunk/src/app/srs_app_srt_server.cpp b/trunk/src/app/srs_app_srt_server.cpp
index 5690a6333..070b5c673 100644
--- a/trunk/src/app/srs_app_srt_server.cpp
+++ b/trunk/src/app/srs_app_srt_server.cpp
@@ -201,7 +201,7 @@ srs_error_t SrsSrtServer::listen_srt_mpegts()
int port;
string ip;
- srs_parse_endpoint(srs_int2str(_srs_config->get_srt_listen_port()), ip, port);
+ srs_net_split_for_listener(srs_strconv_format_int(_srs_config->get_srt_listen_port()), ip, port);
if ((err = acceptor->listen(ip, port)) != srs_success) {
return srs_error_wrap(err, "srt listen %s:%d", ip.c_str(), port);
diff --git a/trunk/src/app/srs_app_srt_source.cpp b/trunk/src/app/srs_app_srt_source.cpp
index 2ddfa4a18..b2e715063 100644
--- a/trunk/src/app/srs_app_srt_source.cpp
+++ b/trunk/src/app/srs_app_srt_source.cpp
@@ -985,7 +985,7 @@ bool SrsSrtSource::stream_is_dead()
}
// Delay cleanup source.
- srs_utime_t now = srs_get_system_time();
+ srs_utime_t now = srs_time_now_cached();
if (now < stream_die_at_ + SRS_SRT_SOURCE_CLEANUP) {
return false;
}
@@ -1072,7 +1072,7 @@ void SrsSrtSource::on_consumer_destroy(SrsSrtConsumer *consumer)
// Destroy and cleanup source when no publishers and consumers.
if (can_publish_ && consumers.empty()) {
- stream_die_at_ = srs_get_system_time();
+ stream_die_at_ = srs_time_now_cached();
}
}
@@ -1133,7 +1133,7 @@ void SrsSrtSource::on_unpublish()
// Destroy and cleanup source when no publishers and consumers.
if (consumers.empty()) {
- stream_die_at_ = srs_get_system_time();
+ stream_die_at_ = srs_time_now_cached();
}
}
diff --git a/trunk/src/app/srs_app_srt_utility.cpp b/trunk/src/app/srs_app_srt_utility.cpp
index f50ed67a6..efe38f480 100644
--- a/trunk/src/app/srs_app_srt_utility.cpp
+++ b/trunk/src/app/srs_app_srt_utility.cpp
@@ -40,10 +40,10 @@ bool srs_srt_streamid_info(const std::string &streamid, SrtMode &mode, std::stri
// Compatible with previous auth querystring, like this one:
// srt://127.0.0.1:10080?streamid=#!::h=live/livestream?secret=xxx,m=publish
- real_streamid = srs_string_replace(real_streamid, "?", ",");
+ real_streamid = srs_strings_replace(real_streamid, "?", ",");
std::map query;
- srs_parse_query_string(real_streamid, query);
+ srs_net_url_parse_query(real_streamid, query);
for (std::map::iterator it = query.begin(); it != query.end(); ++it) {
if (it->first == "h") {
std::string host = it->second;
@@ -141,7 +141,7 @@ bool srs_srt_streamid_to_request(const std::string &streamid, SrtMode &mode, ISr
request->host = srs_get_public_internet_address();
if (request->vhost.empty())
request->vhost = request->host;
- request->tcUrl = srs_generate_tc_url("srt", request->host, request->vhost, request->app, request->port);
+ request->tcUrl = srs_net_url_encode_tcurl("srt", request->host, request->vhost, request->app, request->port);
return ret;
}
diff --git a/trunk/src/app/srs_app_srt_utility.hpp b/trunk/src/app/srs_app_srt_utility.hpp
index f320805f0..c52fa74ef 100644
--- a/trunk/src/app/srs_app_srt_utility.hpp
+++ b/trunk/src/app/srs_app_srt_utility.hpp
@@ -12,6 +12,7 @@
#include
#include
+#include
#include
class ISrsRequest;
diff --git a/trunk/src/app/srs_app_statistic.cpp b/trunk/src/app/srs_app_statistic.cpp
index ad8c635b6..65096f211 100644
--- a/trunk/src/app/srs_app_statistic.cpp
+++ b/trunk/src/app/srs_app_statistic.cpp
@@ -24,7 +24,7 @@ using namespace std;
string srs_generate_stat_vid()
{
- return "vid-" + srs_random_str(7);
+ return "vid-" + srs_rand_gen_str(7);
}
SrsStatisticVhost::SrsStatisticVhost()
@@ -116,7 +116,7 @@ srs_error_t SrsStatisticStream::dumps(SrsJsonObject *obj)
obj->set("app", SrsJsonAny::str(app.c_str()));
obj->set("tcUrl", SrsJsonAny::str(tcUrl.c_str()));
obj->set("url", SrsJsonAny::str(url.c_str()));
- obj->set("live_ms", SrsJsonAny::integer(srsu2ms(srs_get_system_time())));
+ obj->set("live_ms", SrsJsonAny::integer(srsu2ms(srs_time_now_cached())));
obj->set("clients", SrsJsonAny::integer(nb_clients));
obj->set("frames", SrsJsonAny::integer(frames->sugar));
obj->set("send_bytes", SrsJsonAny::integer(kbps->get_send_bytes()));
@@ -207,7 +207,7 @@ SrsStatisticClient::SrsStatisticClient()
conn = NULL;
req = NULL;
type = SrsRtmpConnUnknown;
- create = srs_get_system_time();
+ create = srs_time_now_cached();
kbps = new SrsKbps();
}
@@ -233,7 +233,7 @@ srs_error_t SrsStatisticClient::dumps(SrsJsonObject *obj)
obj->set("name", SrsJsonAny::str(req->stream.c_str()));
obj->set("type", SrsJsonAny::str(srs_client_type_string(type).c_str()));
obj->set("publish", SrsJsonAny::boolean(srs_client_type_is_publish(type)));
- obj->set("alive", SrsJsonAny::number(srsu2ms(srs_get_system_time() - create) / 1000.0));
+ obj->set("alive", SrsJsonAny::number(srsu2ms(srs_time_now_cached() - create) / 1000.0));
obj->set("send_bytes", SrsJsonAny::integer(kbps->get_send_bytes()));
obj->set("recv_bytes", SrsJsonAny::integer(kbps->get_recv_bytes()));
@@ -568,7 +568,7 @@ std::string SrsStatistic::server_id()
std::string SrsStatistic::service_id()
{
if (service_id_.empty()) {
- service_id_ = srs_random_str(8);
+ service_id_ = srs_rand_gen_str(8);
}
return service_id_;
@@ -577,7 +577,7 @@ std::string SrsStatistic::service_id()
std::string SrsStatistic::service_pid()
{
if (service_pid_.empty()) {
- service_pid_ = srs_int2str(getpid());
+ service_pid_ = srs_strconv_format_int(getpid());
}
return service_pid_;
@@ -677,13 +677,13 @@ void SrsStatistic::dumps_hints_kv(std::stringstream &ss)
void SrsStatistic::dumps_cls_summaries(SrsClsSugar *sugar)
{
if (!vhosts.empty()) {
- sugar->kv("vhosts", srs_fmt("%d", (int)vhosts.size()));
+ sugar->kv("vhosts", srs_fmt_sprintf("%d", (int)vhosts.size()));
}
if (!streams.empty()) {
- sugar->kv("streams", srs_fmt("%d", (int)streams.size()));
+ sugar->kv("streams", srs_fmt_sprintf("%d", (int)streams.size()));
}
if (!clients.empty()) {
- sugar->kv("clients", srs_fmt("%d", (int)clients.size()));
+ sugar->kv("clients", srs_fmt_sprintf("%d", (int)clients.size()));
}
}
@@ -698,37 +698,37 @@ void SrsStatistic::dumps_cls_streams(SrsClsSugars *sugars)
SrsClsSugar *sugar = sugars->create();
sugar->kv("hint", "stream");
sugar->kv("version", RTMP_SIG_SRS_VERSION);
- sugar->kv("pid", srs_fmt("%d", getpid()));
+ sugar->kv("pid", srs_fmt_sprintf("%d", getpid()));
sugar->kv("sid", stream->id);
sugar->kv("url", stream->url);
if (stream->frames->r30s()) {
- sugar->kv("fps", srs_fmt("%d", stream->frames->r30s()));
+ sugar->kv("fps", srs_fmt_sprintf("%d", stream->frames->r30s()));
}
if (stream->width) {
- sugar->kv("width", srs_fmt("%d", stream->width));
+ sugar->kv("width", srs_fmt_sprintf("%d", stream->width));
}
if (stream->height) {
- sugar->kv("height", srs_fmt("%d", stream->height));
+ sugar->kv("height", srs_fmt_sprintf("%d", stream->height));
}
SrsStatisticClient *pub = find_client(stream->publisher_id);
if (pub) {
if (pub->kbps->get_recv_kbps_30s()) {
- sugar->kv("recv", srs_fmt("%d", pub->kbps->get_recv_kbps_30s()));
+ sugar->kv("recv", srs_fmt_sprintf("%d", pub->kbps->get_recv_kbps_30s()));
}
if (pub->kbps->get_send_kbps_30s()) {
- sugar->kv("send", srs_fmt("%d", pub->kbps->get_send_kbps_30s()));
+ sugar->kv("send", srs_fmt_sprintf("%d", pub->kbps->get_send_kbps_30s()));
}
}
- sugar->kv("clients", srs_fmt("%d", stream->nb_clients));
+ sugar->kv("clients", srs_fmt_sprintf("%d", stream->nb_clients));
if (stream->kbps->get_recv_kbps_30s()) {
- sugar->kv("recv2", srs_fmt("%d", stream->kbps->get_recv_kbps_30s()));
+ sugar->kv("recv2", srs_fmt_sprintf("%d", stream->kbps->get_recv_kbps_30s()));
}
if (stream->kbps->get_send_kbps_30s()) {
- sugar->kv("send2", srs_fmt("%d", stream->kbps->get_send_kbps_30s()));
+ sugar->kv("send2", srs_fmt_sprintf("%d", stream->kbps->get_send_kbps_30s()));
}
}
}
diff --git a/trunk/src/app/srs_app_tencentcloud.cpp b/trunk/src/app/srs_app_tencentcloud.cpp
index 92998ee20..fc5a4ca5c 100644
--- a/trunk/src/app/srs_app_tencentcloud.cpp
+++ b/trunk/src/app/srs_app_tencentcloud.cpp
@@ -489,7 +489,7 @@ SrsClsSugar::SrsClsSugar()
log_ = log_group_->add_log();
log_group_->set_source(srs_get_public_internet_address(true));
- log_->set_time(srs_get_system_time() / SRS_UTIME_MILLISECONDS);
+ log_->set_time(srs_time_now_cached() / SRS_UTIME_MILLISECONDS);
kv("agent", RTMP_SIG_SRS_SERVER);
string label = _srs_cls->label();
@@ -859,7 +859,7 @@ srs_error_t SrsClsClient::dump_summaries(SrsClsSugars *sugars)
SrsClsSugar *sugar = sugars->create();
sugar->kv("hint", "summary");
sugar->kv("version", RTMP_SIG_SRS_VERSION);
- sugar->kv("pid", srs_fmt("%d", getpid()));
+ sugar->kv("pid", srs_fmt_sprintf("%d", getpid()));
// Server ID to identify logs from a set of servers' logs.
SrsStatistic::instance()->dumps_cls_summaries(sugar);
@@ -868,7 +868,7 @@ srs_error_t SrsClsClient::dump_summaries(SrsClsSugars *sugars)
if (u->ok) {
// The cpu usage of SRS, 1 means 1/1000
if (u->percent > 0) {
- sugar->kv("cpu", srs_fmt("%d", (int)(u->percent * 1000)));
+ sugar->kv("cpu", srs_fmt_sprintf("%d", (int)(u->percent * 1000)));
}
}
@@ -876,11 +876,11 @@ srs_error_t SrsClsClient::dump_summaries(SrsClsSugars *sugars)
if (p->ok) {
// The uptime of SRS, in seconds.
if (p->srs_startup_time > 0) {
- sugar->kv("uptime", srs_fmt("%d", (int)((srs_get_system_time() - p->srs_startup_time) / SRS_UTIME_SECONDS)));
+ sugar->kv("uptime", srs_fmt_sprintf("%d", (int)((srs_time_now_cached() - p->srs_startup_time) / SRS_UTIME_SECONDS)));
}
// The load of system, load every 1 minute, 1 means 1/1000.
if (p->load_one_minutes > 0) {
- sugar->kv("load", srs_fmt("%d", (int)(p->load_one_minutes * 1000)));
+ sugar->kv("load", srs_fmt_sprintf("%d", (int)(p->load_one_minutes * 1000)));
}
}
@@ -894,7 +894,7 @@ srs_error_t SrsClsClient::dump_summaries(SrsClsSugars *sugars)
// The memory of SRS, 1 means 1/1000
if (self_mem_percent > 0) {
- sugar->kv("mem", srs_fmt("%d", (int)(self_mem_percent * 1000)));
+ sugar->kv("mem", srs_fmt_sprintf("%d", (int)(self_mem_percent * 1000)));
}
}
@@ -902,7 +902,7 @@ srs_error_t SrsClsClient::dump_summaries(SrsClsSugars *sugars)
if (s->ok) {
// The cpu usage of system, 1 means 1/1000
if (s->percent > 0) {
- sugar->kv("cpu2", srs_fmt("%d", (int)(s->percent * 1000)));
+ sugar->kv("cpu2", srs_fmt_sprintf("%d", (int)(s->percent * 1000)));
}
}
@@ -910,19 +910,19 @@ srs_error_t SrsClsClient::dump_summaries(SrsClsSugars *sugars)
if (nrs->ok) {
// The number of connections of SRS.
if (nrs->nb_conn_srs > 0) {
- sugar->kv("conn", srs_fmt("%d", nrs->nb_conn_srs));
+ sugar->kv("conn", srs_fmt_sprintf("%d", nrs->nb_conn_srs));
}
// The number of connections of system.
if (nrs->nb_conn_sys > 0) {
- sugar->kv("conn2", srs_fmt("%d", nrs->nb_conn_sys));
+ sugar->kv("conn2", srs_fmt_sprintf("%d", nrs->nb_conn_sys));
}
// The received kbps in 30s of SRS.
if (nrs->rkbps_30s > 0) {
- sugar->kv("recv", srs_fmt("%d", nrs->rkbps_30s));
+ sugar->kv("recv", srs_fmt_sprintf("%d", nrs->rkbps_30s));
}
// The sending out kbps in 30s of SRS.
if (nrs->skbps_30s > 0) {
- sugar->kv("send", srs_fmt("%d", nrs->skbps_30s));
+ sugar->kv("send", srs_fmt_sprintf("%d", nrs->skbps_30s));
}
}
@@ -1536,7 +1536,7 @@ srs_error_t SrsOtelSpan::encode(SrsBuffer *b)
SrsOtelEvent::SrsOtelEvent()
{
- time_ = srs_update_system_time();
+ time_ = srs_time_now_realtime();
}
SrsOtelEvent::~SrsOtelEvent()
@@ -1720,10 +1720,10 @@ SrsApmContext::SrsApmContext(const std::string &name)
name_ = name;
kind_ = SrsApmKindUnspecified;
- set_trace_id(srs_random_str(16));
- set_span_id(srs_random_str(8));
+ set_trace_id(srs_rand_gen_str(16));
+ set_span_id(srs_rand_gen_str(8));
// We must not use time cache, or span render might fail.
- start_time_ = srs_update_system_time();
+ start_time_ = srs_time_now_realtime();
ended_ = false;
status_ = SrsApmStatusUnset;
err_ = srs_success;
@@ -1762,13 +1762,13 @@ SrsApmContext::~SrsApmContext()
void SrsApmContext::set_trace_id(std::string v)
{
trace_id_ = v;
- str_trace_id_ = srs_string_dumps_hex(trace_id_.data(), trace_id_.length(), INT_MAX, 0, INT_MAX, 0);
+ str_trace_id_ = srs_strings_dumps_hex(trace_id_.data(), trace_id_.length(), INT_MAX, 0, INT_MAX, 0);
}
void SrsApmContext::set_span_id(std::string v)
{
span_id_ = v;
- str_span_id_ = srs_string_dumps_hex(span_id_.data(), span_id_.length(), INT_MAX, 0, INT_MAX, 0);
+ str_span_id_ = srs_strings_dumps_hex(span_id_.data(), span_id_.length(), INT_MAX, 0, INT_MAX, 0);
}
const char *SrsApmContext::format_trace_id()
@@ -1887,7 +1887,7 @@ void SrsApmContext::end()
otel->kind_ = kind_;
otel->start_time_unix_nano_ = start_time_ * 1000;
// We must not use time cache, or span render might fail.
- otel->end_time_unix_nano_ = srs_update_system_time() * 1000;
+ otel->end_time_unix_nano_ = srs_time_now_realtime() * 1000;
otel->status_->code_ = status_;
otel->status_->message_ = description_;
@@ -1907,13 +1907,13 @@ void SrsApmContext::end()
if (err_ != srs_success) {
// Set the events for detail about the error.
otel->events_.push_back(SrsOtelEvent::create("exception")
- ->add_attr(SrsOtelAttribute::kv("exception.type", srs_fmt("code_%d_%s", srs_error_code(err_), srs_error_code_str(err_).c_str())))
+ ->add_attr(SrsOtelAttribute::kv("exception.type", srs_fmt_sprintf("code_%d_%s", srs_error_code(err_), srs_error_code_str(err_).c_str())))
->add_attr(SrsOtelAttribute::kv("exception.message", srs_error_summary(err_)))
->add_attr(SrsOtelAttribute::kv("exception.stacktrace", srs_error_desc(err_))));
// We also use HTTP status code for APM to class the error. Note that it also works for non standard HTTP status
// code, for example, SRS error codes.
- otel->attributes_.push_back(SrsOtelAttribute::kv("http.status_code", srs_fmt("%d", srs_error_code(err_))));
+ otel->attributes_.push_back(SrsOtelAttribute::kv("http.status_code", srs_fmt_sprintf("%d", srs_error_code(err_))));
}
_srs_apm->snapshot(otel);
@@ -2039,7 +2039,7 @@ ISrsApmSpan *SrsApmSpan::extract(SrsAmf0Object *h)
return this;
std::string trace_parent = prop->to_str();
- vector vs = srs_string_split(trace_parent, "-");
+ vector vs = srs_strings_split(trace_parent, "-");
if (vs.size() != 4)
return this;
@@ -2152,7 +2152,7 @@ srs_error_t SrsApmClient::initialize()
}
// Please note that 4317 is for GRPC/HTTP2, while SRS only support HTTP and the port shoule be 55681.
- if (srs_string_contains(endpoint_, ":4317")) {
+ if (srs_strings_contains(endpoint_, ":4317")) {
return srs_error_new(ERROR_APM_ENDPOINT, "Port 4317 is for GRPC over HTTP2 for APM");
}
diff --git a/trunk/src/app/srs_app_utility.cpp b/trunk/src/app/srs_app_utility.cpp
index 895c15418..2ef9f0957 100644
--- a/trunk/src/app/srs_app_utility.cpp
+++ b/trunk/src/app/srs_app_utility.cpp
@@ -74,11 +74,11 @@ string srs_path_build_stream(string template_path, string vhost, string app, str
std::string path = template_path;
// variable [vhost]
- path = srs_string_replace(path, "[vhost]", vhost);
+ path = srs_strings_replace(path, "[vhost]", vhost);
// variable [app]
- path = srs_string_replace(path, "[app]", app);
+ path = srs_strings_replace(path, "[app]", app);
// variable [stream]
- path = srs_string_replace(path, "[stream]", stream);
+ path = srs_strings_replace(path, "[stream]", stream);
return path;
}
@@ -113,42 +113,42 @@ string srs_path_build_timestamp(string template_path)
// [2006], replace with current year.
if (true) {
snprintf(buf, sizeof(buf), "%04d", 1900 + now.tm_year);
- path = srs_string_replace(path, "[2006]", buf);
+ path = srs_strings_replace(path, "[2006]", buf);
}
// [01], replace this const to current month.
if (true) {
snprintf(buf, sizeof(buf), "%02d", 1 + now.tm_mon);
- path = srs_string_replace(path, "[01]", buf);
+ path = srs_strings_replace(path, "[01]", buf);
}
// [02], replace this const to current date.
if (true) {
snprintf(buf, sizeof(buf), "%02d", now.tm_mday);
- path = srs_string_replace(path, "[02]", buf);
+ path = srs_strings_replace(path, "[02]", buf);
}
// [15], replace this const to current hour.
if (true) {
snprintf(buf, sizeof(buf), "%02d", now.tm_hour);
- path = srs_string_replace(path, "[15]", buf);
+ path = srs_strings_replace(path, "[15]", buf);
}
// [04], repleace this const to current minute.
if (true) {
snprintf(buf, sizeof(buf), "%02d", now.tm_min);
- path = srs_string_replace(path, "[04]", buf);
+ path = srs_strings_replace(path, "[04]", buf);
}
// [05], repleace this const to current second.
if (true) {
snprintf(buf, sizeof(buf), "%02d", now.tm_sec);
- path = srs_string_replace(path, "[05]", buf);
+ path = srs_strings_replace(path, "[05]", buf);
}
// [999], repleace this const to current millisecond.
if (true) {
snprintf(buf, sizeof(buf), "%03d", (int)(tv.tv_usec / 1000));
- path = srs_string_replace(path, "[999]", buf);
+ path = srs_strings_replace(path, "[999]", buf);
}
// [timestamp],replace this const to current UNIX timestamp in ms.
if (true) {
int64_t now_us = ((int64_t)tv.tv_sec) * 1000 * 1000 + (int64_t)tv.tv_usec;
- path = srs_string_replace(path, "[timestamp]", srs_int2str(now_us / 1000));
+ path = srs_strings_replace(path, "[timestamp]", srs_strconv_format_int(now_us / 1000));
}
return path;
@@ -234,7 +234,7 @@ void srs_update_system_rusage()
return;
}
- _srs_system_rusage.sample_time = srsu2ms(srs_update_system_time());
+ _srs_system_rusage.sample_time = srsu2ms(srs_time_now_realtime());
_srs_system_rusage.ok = true;
}
@@ -420,7 +420,7 @@ void srs_update_proc_stat()
return;
}
- r.sample_time = srsu2ms(srs_update_system_time());
+ r.sample_time = srsu2ms(srs_time_now_realtime());
// calc usage in percent
SrsProcSystemStat &o = _srs_system_cpu_system_stat;
@@ -446,7 +446,7 @@ void srs_update_proc_stat()
return;
}
- r.sample_time = srsu2ms(srs_update_system_time());
+ r.sample_time = srsu2ms(srs_time_now_realtime());
// calc usage in percent
SrsProcSelfStat &o = _srs_system_cpu_self_stat;
@@ -498,7 +498,7 @@ bool srs_get_disk_vmstat_stat(SrsDiskStat &r)
return false;
}
- r.sample_time = srsu2ms(srs_update_system_time());
+ r.sample_time = srsu2ms(srs_time_now_realtime());
static char buf[1024];
while (fgets(buf, sizeof(buf), f)) {
@@ -521,7 +521,7 @@ bool srs_get_disk_vmstat_stat(SrsDiskStat &r)
bool srs_get_disk_diskstats_stat(SrsDiskStat &r)
{
r.ok = true;
- r.sample_time = srsu2ms(srs_update_system_time());
+ r.sample_time = srsu2ms(srs_time_now_realtime());
#if !defined(SRS_OSX)
// if disabled, ignore all devices.
@@ -712,7 +712,7 @@ void srs_update_meminfo()
fclose(f);
#endif
- r.sample_time = srsu2ms(srs_update_system_time());
+ r.sample_time = srsu2ms(srs_time_now_realtime());
r.MemActive = r.MemTotal - r.MemFree;
r.RealInUse = r.MemActive - r.Buffers - r.Cached;
r.NotInUse = r.MemTotal - r.RealInUse;
@@ -776,7 +776,7 @@ void srs_update_platform_info()
{
SrsPlatformInfo &r = _srs_system_platform_info;
- r.srs_startup_time = srsu2ms(srs_get_system_startup_time());
+ r.srs_startup_time = srsu2ms(srs_time_since_startup());
#if !defined(SRS_OSX)
if (true) {
@@ -1009,7 +1009,7 @@ void srs_update_network_devices()
_nb_srs_system_network_devices = i + 1;
srs_info("scan network device ifname=%s, total=%d", r.name, _nb_srs_system_network_devices);
- r.sample_time = srsu2ms(srs_update_system_time());
+ r.sample_time = srsu2ms(srs_time_now_realtime());
r.ok = true;
}
@@ -1160,7 +1160,7 @@ void srs_update_rtmp_server(int nb_conn, SrsKbps *kbps)
r.ok = true;
r.nb_conn_srs = nb_conn;
- r.sample_time = srsu2ms(srs_update_system_time());
+ r.sample_time = srsu2ms(srs_time_now_realtime());
r.rbytes = kbps->get_recv_bytes();
r.rkbps = kbps->get_recv_kbps();
@@ -1280,7 +1280,7 @@ void srs_api_dump_summaries(SrsJsonObject *obj)
self_mem_percent = (float)(r->r.ru_maxrss / (double)m->MemTotal);
}
- int64_t now = srsu2ms(srs_update_system_time());
+ int64_t now = srsu2ms(srs_time_now_realtime());
double srs_uptime = (now - p->srs_startup_time) / 100 / 10.0;
int64_t n_sample_time = 0;
@@ -1376,7 +1376,7 @@ void srs_api_dump_summaries(SrsJsonObject *obj)
string srs_getenv(const string &key)
{
string ekey = key;
- if (srs_string_starts_with(key, "$")) {
+ if (srs_strings_starts_with(key, "$")) {
ekey = key.substr(1);
}
diff --git a/trunk/src/app/srs_app_utility.hpp b/trunk/src/app/srs_app_utility.hpp
index d965ef365..189975759 100644
--- a/trunk/src/app/srs_app_utility.hpp
+++ b/trunk/src/app/srs_app_utility.hpp
@@ -19,6 +19,7 @@
#include
#include
+#include
#include
class SrsKbps;
diff --git a/trunk/src/core/srs_core_time.cpp b/trunk/src/core/srs_core_time.cpp
index d87e1ea3a..68ba596aa 100644
--- a/trunk/src/core/srs_core_time.cpp
+++ b/trunk/src/core/srs_core_time.cpp
@@ -6,7 +6,7 @@
#include
-srs_utime_t srs_duration(srs_utime_t start, srs_utime_t end)
+srs_utime_t srs_time_since(srs_utime_t start, srs_utime_t end)
{
if (start == 0 || end == 0) {
return 0;
diff --git a/trunk/src/core/srs_core_time.hpp b/trunk/src/core/srs_core_time.hpp
index f7da01878..9da7e71d8 100644
--- a/trunk/src/core/srs_core_time.hpp
+++ b/trunk/src/core/srs_core_time.hpp
@@ -23,7 +23,7 @@ typedef int64_t srs_utime_t;
#define srsu2si(us) int((us) / SRS_UTIME_SECONDS)
// Them time duration = end - start. return 0, if start or end is 0.
-srs_utime_t srs_duration(srs_utime_t start, srs_utime_t end);
+srs_utime_t srs_time_since(srs_utime_t start, srs_utime_t end);
// The time unit in seconds, for example 120 * SRS_UTIME_SECONDS means 120s.
#define SRS_UTIME_SECONDS 1000000LL
@@ -38,9 +38,9 @@ srs_utime_t srs_duration(srs_utime_t start, srs_utime_t end);
#define SRS_UTIME_NO_TIMEOUT ((srs_utime_t) - 1LL)
// Get current system time in srs_utime_t, use cache to avoid performance problem
-extern srs_utime_t srs_get_system_time();
-extern srs_utime_t srs_get_system_startup_time();
+extern srs_utime_t srs_time_now_cached();
+extern srs_utime_t srs_time_since_startup();
// A daemon st-thread updates it.
-extern srs_utime_t srs_update_system_time();
+extern srs_utime_t srs_time_now_realtime();
#endif
diff --git a/trunk/src/core/srs_core_version7.hpp b/trunk/src/core/srs_core_version7.hpp
index 614dff2d2..d4b15fd68 100644
--- a/trunk/src/core/srs_core_version7.hpp
+++ b/trunk/src/core/srs_core_version7.hpp
@@ -9,6 +9,6 @@
#define VERSION_MAJOR 7
#define VERSION_MINOR 0
-#define VERSION_REVISION 64
+#define VERSION_REVISION 65
#endif
\ No newline at end of file
diff --git a/trunk/src/kernel/srs_kernel_codec.cpp b/trunk/src/kernel/srs_kernel_codec.cpp
index 50604f0e9..05194cac9 100644
--- a/trunk/src/kernel/srs_kernel_codec.cpp
+++ b/trunk/src/kernel/srs_kernel_codec.cpp
@@ -18,6 +18,57 @@ using namespace std;
#include
#include
+srs_error_t srs_avc_nalu_read_uev(SrsBitBuffer *stream, int32_t &v)
+{
+ srs_error_t err = srs_success;
+
+ if (stream->empty()) {
+ return srs_error_new(ERROR_AVC_NALU_UEV, "empty stream");
+ }
+
+ // ue(v) in 9.1 Parsing process for Exp-Golomb codes
+ // ISO_IEC_14496-10-AVC-2012.pdf, page 227.
+ // Syntax elements coded as ue(v), me(v), or se(v) are Exp-Golomb-coded.
+ // leadingZeroBits = -1;
+ // for( b = 0; !b; leadingZeroBits++ )
+ // b = read_bits( 1 )
+ // The variable codeNum is then assigned as follows:
+ // codeNum = (2<empty(); leadingZeroBits++) {
+ b = stream->read_bit();
+ }
+
+ if (leadingZeroBits >= 31) {
+ return srs_error_new(ERROR_AVC_NALU_UEV, "%dbits overflow 31bits", leadingZeroBits);
+ }
+
+ v = (1 << leadingZeroBits) - 1;
+ for (int i = 0; i < (int)leadingZeroBits; i++) {
+ if (stream->empty()) {
+ return srs_error_new(ERROR_AVC_NALU_UEV, "no bytes for leadingZeroBits=%d", leadingZeroBits);
+ }
+
+ int32_t b = stream->read_bit();
+ v += b << (leadingZeroBits - 1 - i);
+ }
+
+ return err;
+}
+
+srs_error_t srs_avc_nalu_read_bit(SrsBitBuffer *stream, int8_t &v)
+{
+ srs_error_t err = srs_success;
+
+ if (stream->empty()) {
+ return srs_error_new(ERROR_AVC_NALU_UEV, "empty stream");
+ }
+
+ v = stream->read_bit();
+
+ return err;
+}
+
string srs_video_codec_id2str(SrsVideoCodecId codec)
{
switch (codec) {
@@ -3091,3 +3142,36 @@ srs_error_t SrsFormat::audio_aac_sequence_header_demux(char *data, int size)
return err;
}
+
+bool srs_avc_startswith_annexb(SrsBuffer *stream, int *pnb_start_code)
+{
+ if (!stream) {
+ return false;
+ }
+
+ char *bytes = stream->data() + stream->pos();
+ char *p = bytes;
+
+ for (;;) {
+ if (!stream->require((int)(p - bytes + 3))) {
+ return false;
+ }
+
+ // not match
+ if (p[0] != (char)0x00 || p[1] != (char)0x00) {
+ return false;
+ }
+
+ // match N[00] 00 00 01, where N>=0
+ if (p[2] == (char)0x01) {
+ if (pnb_start_code) {
+ *pnb_start_code = (int)(p - bytes) + 3;
+ }
+ return true;
+ }
+
+ p++;
+ }
+
+ return false;
+}
diff --git a/trunk/src/kernel/srs_kernel_codec.hpp b/trunk/src/kernel/srs_kernel_codec.hpp
index de80a95fd..667f4e5d2 100644
--- a/trunk/src/kernel/srs_kernel_codec.hpp
+++ b/trunk/src/kernel/srs_kernel_codec.hpp
@@ -1425,4 +1425,13 @@ public:
virtual srs_error_t audio_aac_sequence_header_demux(char *data, int size);
};
+// To read H.264 NALU uev.
+extern srs_error_t srs_avc_nalu_read_uev(SrsBitBuffer *stream, int32_t &v);
+extern srs_error_t srs_avc_nalu_read_bit(SrsBitBuffer *stream, int8_t &v);
+
+// Whether stream starts with the avc NALU in "AnnexB" from ISO_IEC_14496-10-AVC-2003.pdf, page 211.
+// The start code must be "N[00] 00 00 01" where N>=0
+// @param pnb_start_code output the size of start code, must >=3. NULL to ignore.
+extern bool srs_avc_startswith_annexb(SrsBuffer *stream, int *pnb_start_code = NULL);
+
#endif
diff --git a/trunk/src/kernel/srs_kernel_error.cpp b/trunk/src/kernel/srs_kernel_error.cpp
index 8f2800fac..12e1b11a4 100644
--- a/trunk/src/kernel/srs_kernel_error.cpp
+++ b/trunk/src/kernel/srs_kernel_error.cpp
@@ -156,12 +156,12 @@ void asan_report_callback(const char *str)
// No error code for assert failed.
errno = 0;
- std::vector asan_logs = srs_string_split(string(str), "\n");
+ std::vector asan_logs = srs_strings_split(string(str), "\n");
size_t log_count = asan_logs.size();
for (size_t i = 0; i < log_count; i++) {
std::string log = asan_logs[i];
- if (!srs_string_starts_with(srs_string_trim_start(log, " "), "#")) {
+ if (!srs_strings_starts_with(srs_strings_trim_start(log, " "), "#")) {
srs_error("%s", log.c_str());
continue;
}
diff --git a/trunk/src/kernel/srs_kernel_flv.cpp b/trunk/src/kernel/srs_kernel_flv.cpp
index b8aa5312a..dc622af63 100644
--- a/trunk/src/kernel/srs_kernel_flv.cpp
+++ b/trunk/src/kernel/srs_kernel_flv.cpp
@@ -28,6 +28,129 @@ using namespace std;
SrsPps *_srs_pps_objs_msgs = NULL;
+int srs_chunk_header_c0(int prefer_cid, uint32_t timestamp, int32_t payload_length, int8_t message_type, int32_t stream_id, char *cache, int nb_cache)
+{
+ // to directly set the field.
+ char *pp = NULL;
+
+ // generate the header.
+ char *p = cache;
+
+ // no header.
+ if (nb_cache < SRS_CONSTS_RTMP_MAX_FMT0_HEADER_SIZE) {
+ return 0;
+ }
+
+ // write new chunk stream header, fmt is 0
+ *p++ = 0x00 | (prefer_cid & 0x3F);
+
+ // chunk message header, 11 bytes
+ // timestamp, 3bytes, big-endian
+ if (timestamp < RTMP_EXTENDED_TIMESTAMP) {
+ pp = (char *)×tamp;
+ *p++ = pp[2];
+ *p++ = pp[1];
+ *p++ = pp[0];
+ } else {
+ *p++ = (char)0xFF;
+ *p++ = (char)0xFF;
+ *p++ = (char)0xFF;
+ }
+
+ // message_length, 3bytes, big-endian
+ pp = (char *)&payload_length;
+ *p++ = pp[2];
+ *p++ = pp[1];
+ *p++ = pp[0];
+
+ // message_type, 1bytes
+ *p++ = message_type;
+
+ // stream_id, 4bytes, little-endian
+ pp = (char *)&stream_id;
+ *p++ = pp[0];
+ *p++ = pp[1];
+ *p++ = pp[2];
+ *p++ = pp[3];
+
+ // for c0
+ // chunk extended timestamp header, 0 or 4 bytes, big-endian
+ //
+ // for c3:
+ // chunk extended timestamp header, 0 or 4 bytes, big-endian
+ // 6.1.3. Extended Timestamp
+ // This field is transmitted only when the normal time stamp in the
+ // chunk message header is set to 0x00ffffff. If normal time stamp is
+ // set to any value less than 0x00ffffff, this field MUST NOT be
+ // present. This field MUST NOT be present if the timestamp field is not
+ // present. Type 3 chunks MUST NOT have this field.
+ // adobe changed for Type3 chunk:
+ // FMLE always sendout the extended-timestamp,
+ // must send the extended-timestamp to FMS,
+ // must send the extended-timestamp to flash-player.
+ // @see: ngx_rtmp_prepare_message
+ // @see: http://blog.csdn.net/win_lin/article/details/13363699
+ // TODO: FIXME: extract to outer.
+ if (timestamp >= RTMP_EXTENDED_TIMESTAMP) {
+ pp = (char *)×tamp;
+ *p++ = pp[3];
+ *p++ = pp[2];
+ *p++ = pp[1];
+ *p++ = pp[0];
+ }
+
+ // always has header
+ return (int)(p - cache);
+}
+
+int srs_chunk_header_c3(int prefer_cid, uint32_t timestamp, char *cache, int nb_cache)
+{
+ // to directly set the field.
+ char *pp = NULL;
+
+ // generate the header.
+ char *p = cache;
+
+ // no header.
+ if (nb_cache < SRS_CONSTS_RTMP_MAX_FMT3_HEADER_SIZE) {
+ return 0;
+ }
+
+ // write no message header chunk stream, fmt is 3
+ // @remark, if prefer_cid > 0x3F, that is, use 2B/3B chunk header,
+ // SRS will rollback to 1B chunk header.
+ *p++ = 0xC0 | (prefer_cid & 0x3F);
+
+ // for c0
+ // chunk extended timestamp header, 0 or 4 bytes, big-endian
+ //
+ // for c3:
+ // chunk extended timestamp header, 0 or 4 bytes, big-endian
+ // 6.1.3. Extended Timestamp
+ // This field is transmitted only when the normal time stamp in the
+ // chunk message header is set to 0x00ffffff. If normal time stamp is
+ // set to any value less than 0x00ffffff, this field MUST NOT be
+ // present. This field MUST NOT be present if the timestamp field is not
+ // present. Type 3 chunks MUST NOT have this field.
+ // adobe changed for Type3 chunk:
+ // FMLE always sendout the extended-timestamp,
+ // must send the extended-timestamp to FMS,
+ // must send the extended-timestamp to flash-player.
+ // @see: ngx_rtmp_prepare_message
+ // @see: http://blog.csdn.net/win_lin/article/details/13363699
+ // TODO: FIXME: extract to outer.
+ if (timestamp >= RTMP_EXTENDED_TIMESTAMP) {
+ pp = (char *)×tamp;
+ *p++ = pp[3];
+ *p++ = pp[2];
+ *p++ = pp[1];
+ *p++ = pp[0];
+ }
+
+ // always has header
+ return (int)(p - cache);
+}
+
SrsMessageHeader::SrsMessageHeader()
{
message_type = 0;
diff --git a/trunk/src/kernel/srs_kernel_flv.hpp b/trunk/src/kernel/srs_kernel_flv.hpp
index b660c7851..dac4a572f 100644
--- a/trunk/src/kernel/srs_kernel_flv.hpp
+++ b/trunk/src/kernel/srs_kernel_flv.hpp
@@ -487,4 +487,16 @@ public:
virtual srs_error_t seek2(int64_t offset);
};
+// Generate the c0 chunk header for msg.
+// @param cache, the cache to write header.
+// @param nb_cache, the size of cache.
+// @return The size of header. 0 if cache not enough.
+extern int srs_chunk_header_c0(int prefer_cid, uint32_t timestamp, int32_t payload_length, int8_t message_type, int32_t stream_id, char *cache, int nb_cache);
+
+// Generate the c3 chunk header for msg.
+// @param cache, the cache to write header.
+// @param nb_cache, the size of cache.
+// @return the size of header. 0 if cache not enough.
+extern int srs_chunk_header_c3(int prefer_cid, uint32_t timestamp, char *cache, int nb_cache);
+
#endif
diff --git a/trunk/src/kernel/srs_kernel_kbps.cpp b/trunk/src/kernel/srs_kernel_kbps.cpp
index 577a8cf43..2db3092ca 100644
--- a/trunk/src/kernel/srs_kernel_kbps.cpp
+++ b/trunk/src/kernel/srs_kernel_kbps.cpp
@@ -107,7 +107,7 @@ SrsWallClock::~SrsWallClock()
srs_utime_t SrsWallClock::now()
{
- return srs_get_system_time();
+ return srs_time_now_cached();
}
SrsWallClock *_srs_clock = NULL;
diff --git a/trunk/src/kernel/srs_kernel_mp4.cpp b/trunk/src/kernel/srs_kernel_mp4.cpp
index d52b22fcf..9841c80d5 100644
--- a/trunk/src/kernel/srs_kernel_mp4.cpp
+++ b/trunk/src/kernel/srs_kernel_mp4.cpp
@@ -6895,7 +6895,7 @@ srs_error_t SrsMp4Encoder::copy_sequence_header(SrsFormat *format, bool vsh, uin
if (vsh) {
// AVC
if (format->vcodec->id == SrsVideoCodecIdAVC && !pavcc.empty()) {
- if (nb_sample == (uint32_t)pavcc.size() && srs_bytes_equals(sample, &pavcc[0], (int)pavcc.size())) {
+ if (nb_sample == (uint32_t)pavcc.size() && srs_bytes_equal(sample, &pavcc[0], (int)pavcc.size())) {
return err;
}
@@ -6903,7 +6903,7 @@ srs_error_t SrsMp4Encoder::copy_sequence_header(SrsFormat *format, bool vsh, uin
}
// HEVC
if (format->vcodec->id == SrsVideoCodecIdHEVC && !phvcc.empty()) {
- if (nb_sample == (uint32_t)phvcc.size() && srs_bytes_equals(sample, &phvcc[0], (int)phvcc.size())) {
+ if (nb_sample == (uint32_t)phvcc.size() && srs_bytes_equal(sample, &phvcc[0], (int)phvcc.size())) {
return err;
}
@@ -6912,7 +6912,7 @@ srs_error_t SrsMp4Encoder::copy_sequence_header(SrsFormat *format, bool vsh, uin
}
if (!vsh && !pasc.empty()) {
- if (nb_sample == (uint32_t)pasc.size() && srs_bytes_equals(sample, &pasc[0], (int)pasc.size())) {
+ if (nb_sample == (uint32_t)pasc.size() && srs_bytes_equal(sample, &pasc[0], (int)pasc.size())) {
return err;
}
diff --git a/trunk/src/kernel/srs_kernel_ts.cpp b/trunk/src/kernel/srs_kernel_ts.cpp
index 1a1ec1a09..41745b820 100644
--- a/trunk/src/kernel/srs_kernel_ts.cpp
+++ b/trunk/src/kernel/srs_kernel_ts.cpp
@@ -32,6 +32,129 @@ using namespace std;
#define TS_AUDIO_AAC_PID 0x101
#define TS_AUDIO_MP3_PID 0x102
+// @see pycrc reflect at https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L107
+uint64_t __crc32_reflect(uint64_t data, int width)
+{
+ uint64_t res = data & 0x01;
+
+ for (int i = 0; i < (int)width - 1; i++) {
+ data >>= 1;
+ res = (res << 1) | (data & 0x01);
+ }
+
+ return res;
+}
+
+// @see pycrc gen_table at https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L178
+void __crc32_make_table(uint32_t t[256], uint32_t poly, bool reflect_in)
+{
+ int width = 32; // 32bits checksum.
+ uint64_t msb_mask = (uint32_t)(0x01 << (width - 1));
+ uint64_t mask = (uint32_t)(((msb_mask - 1) << 1) | 1);
+
+ int tbl_idx_width = 8; // table index size.
+ int tbl_width = 0x01 << tbl_idx_width; // table size: 256
+
+ for (int i = 0; i < (int)tbl_width; i++) {
+ uint64_t reg = uint64_t(i);
+
+ if (reflect_in) {
+ reg = __crc32_reflect(reg, tbl_idx_width);
+ }
+
+ reg = reg << (width - tbl_idx_width);
+ for (int j = 0; j < tbl_idx_width; j++) {
+ if ((reg & msb_mask) != 0) {
+ reg = (reg << 1) ^ poly;
+ } else {
+ reg = reg << 1;
+ }
+ }
+
+ if (reflect_in) {
+ reg = __crc32_reflect(reg, width);
+ }
+
+ t[i] = (uint32_t)(reg & mask);
+ }
+}
+
+// @see pycrc table_driven at https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L207
+uint32_t __crc32_table_driven(uint32_t *t, const void *buf, int size, uint32_t previous, bool reflect_in, uint32_t xor_in, bool reflect_out, uint32_t xor_out)
+{
+ int width = 32; // 32bits checksum.
+ uint64_t msb_mask = (uint32_t)(0x01 << (width - 1));
+ uint64_t mask = (uint32_t)(((msb_mask - 1) << 1) | 1);
+
+ int tbl_idx_width = 8; // table index size.
+
+ uint8_t *p = (uint8_t *)buf;
+ uint64_t reg = 0;
+
+ if (!reflect_in) {
+ reg = xor_in;
+
+ for (int i = 0; i < (int)size; i++) {
+ uint8_t tblidx = (uint8_t)((reg >> (width - tbl_idx_width)) ^ p[i]);
+ reg = t[tblidx] ^ (reg << tbl_idx_width);
+ }
+ } else {
+ reg = previous ^ __crc32_reflect(xor_in, width);
+
+ for (int i = 0; i < (int)size; i++) {
+ uint8_t tblidx = (uint8_t)(reg ^ p[i]);
+ reg = t[tblidx] ^ (reg >> tbl_idx_width);
+ }
+
+ reg = __crc32_reflect(reg, width);
+ }
+
+ if (reflect_out) {
+ reg = __crc32_reflect(reg, width);
+ }
+
+ reg ^= xor_out;
+ return (uint32_t)(reg & mask);
+}
+
+// @see pycrc https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L238
+// IEEETable is the table for the MPEG polynomial.
+static uint32_t __crc32_MPEG_table[256];
+static bool __crc32_MPEG_table_initialized = false;
+
+// @see pycrc https://github.com/winlinvip/pycrc/blob/master/pycrc/models.py#L238
+// crc32('123456789') = 0x0376e6e7
+// where it's defined as model:
+// 'name': 'crc-32',
+// 'width': 32,
+// 'poly': 0x4c11db7,
+// 'reflect_in': False,
+// 'xor_in': 0xffffffff,
+// 'reflect_out': False,
+// 'xor_out': 0x0,
+// 'check': 0x0376e6e7,
+uint32_t srs_crc32_mpegts(const void *buf, int size)
+{
+ // @see golang IEEE of hash/crc32/crc32.go
+ // IEEE is by far and away the most common CRC-32 polynomial.
+ // Used by ethernet (IEEE 802.3), v.42, fddi, gzip, zip, png, ...
+ // @remark The poly of CRC32 IEEE is 0x04C11DB7, its reverse is 0xEDB88320,
+ // please read https://en.wikipedia.org/wiki/Cyclic_redundancy_check
+ uint32_t poly = 0x04C11DB7;
+
+ bool reflect_in = false;
+ uint32_t xor_in = 0xffffffff;
+ bool reflect_out = false;
+ uint32_t xor_out = 0x0;
+
+ if (!__crc32_MPEG_table_initialized) {
+ __crc32_make_table(__crc32_MPEG_table, poly, reflect_in);
+ __crc32_MPEG_table_initialized = true;
+ }
+
+ return __crc32_table_driven(__crc32_MPEG_table, buf, size, 0x00, reflect_in, xor_in, reflect_out, xor_out);
+}
+
string srs_ts_stream2string(SrsTsStream stream)
{
switch (stream) {
diff --git a/trunk/src/kernel/srs_kernel_ts.hpp b/trunk/src/kernel/srs_kernel_ts.hpp
index 3ec0b9af1..29746cf52 100644
--- a/trunk/src/kernel/srs_kernel_ts.hpp
+++ b/trunk/src/kernel/srs_kernel_ts.hpp
@@ -1417,4 +1417,7 @@ private:
virtual srs_error_t flush_video();
};
+// Cacl the crc32 of bytes in buf, for ffmpeg.
+extern uint32_t srs_crc32_mpegts(const void *buf, int size);
+
#endif
diff --git a/trunk/src/kernel/srs_kernel_utility.cpp b/trunk/src/kernel/srs_kernel_utility.cpp
index 3d294ec60..24447bd37 100644
--- a/trunk/src/kernel/srs_kernel_utility.cpp
+++ b/trunk/src/kernel/srs_kernel_utility.cpp
@@ -18,6 +18,7 @@
#include
#include
+#include
#include
using namespace std;
@@ -26,80 +27,33 @@ using namespace std;
#include
#include
#include
+#include
#include
+#include
+#include
+
// this value must:
// equals to (SRS_SYS_CYCLE_INTERVAL*SRS_SYS_TIME_RESOLUTION_MS_TIMES)*1000
// @see SRS_SYS_TIME_RESOLUTION_MS_TIMES
#define SYS_TIME_RESOLUTION_US 300 * 1000
-srs_error_t srs_avc_nalu_read_uev(SrsBitBuffer *stream, int32_t &v)
-{
- srs_error_t err = srs_success;
-
- if (stream->empty()) {
- return srs_error_new(ERROR_AVC_NALU_UEV, "empty stream");
- }
-
- // ue(v) in 9.1 Parsing process for Exp-Golomb codes
- // ISO_IEC_14496-10-AVC-2012.pdf, page 227.
- // Syntax elements coded as ue(v), me(v), or se(v) are Exp-Golomb-coded.
- // leadingZeroBits = -1;
- // for( b = 0; !b; leadingZeroBits++ )
- // b = read_bits( 1 )
- // The variable codeNum is then assigned as follows:
- // codeNum = (2<empty(); leadingZeroBits++) {
- b = stream->read_bit();
- }
-
- if (leadingZeroBits >= 31) {
- return srs_error_new(ERROR_AVC_NALU_UEV, "%dbits overflow 31bits", leadingZeroBits);
- }
-
- v = (1 << leadingZeroBits) - 1;
- for (int i = 0; i < (int)leadingZeroBits; i++) {
- if (stream->empty()) {
- return srs_error_new(ERROR_AVC_NALU_UEV, "no bytes for leadingZeroBits=%d", leadingZeroBits);
- }
-
- int32_t b = stream->read_bit();
- v += b << (leadingZeroBits - 1 - i);
- }
-
- return err;
-}
-
-srs_error_t srs_avc_nalu_read_bit(SrsBitBuffer *stream, int8_t &v)
-{
- srs_error_t err = srs_success;
-
- if (stream->empty()) {
- return srs_error_new(ERROR_AVC_NALU_UEV, "empty stream");
- }
-
- v = stream->read_bit();
-
- return err;
-}
-
srs_utime_t _srs_system_time_us_cache = 0;
srs_utime_t _srs_system_time_startup_time = 0;
-srs_utime_t srs_get_system_time()
+srs_utime_t srs_time_now_cached()
{
if (_srs_system_time_us_cache <= 0) {
- srs_update_system_time();
+ srs_time_now_realtime();
}
return _srs_system_time_us_cache;
}
-srs_utime_t srs_get_system_startup_time()
+srs_utime_t srs_time_since_startup()
{
if (_srs_system_time_startup_time <= 0) {
- srs_update_system_time();
+ srs_time_now_realtime();
}
return _srs_system_time_startup_time;
@@ -110,7 +64,7 @@ srs_utime_t srs_get_system_startup_time()
srs_gettimeofday_t _srs_gettimeofday = (srs_gettimeofday_t)::gettimeofday;
#endif
-srs_utime_t srs_update_system_time()
+srs_utime_t srs_time_now_realtime()
{
timeval now;
@@ -147,150 +101,6 @@ srs_utime_t srs_update_system_time()
return _srs_system_time_us_cache;
}
-// TODO: FIXME: Replace by ST dns resolve.
-string srs_dns_resolve(string host, int &family)
-{
- addrinfo hints;
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = family;
-
- addrinfo *r_raw = NULL;
- if (getaddrinfo(host.c_str(), NULL, &hints, &r_raw)) {
- return "";
- }
- SrsUniquePtr r(r_raw, freeaddrinfo);
-
- char shost[64];
- memset(shost, 0, sizeof(shost));
- if (getnameinfo(r->ai_addr, r->ai_addrlen, shost, sizeof(shost), NULL, 0, NI_NUMERICHOST)) {
- return "";
- }
-
- family = r->ai_family;
- return string(shost);
-}
-
-void srs_parse_hostport(string hostport, string &host, int &port)
-{
- // No host or port.
- if (hostport.empty()) {
- return;
- }
-
- size_t pos = string::npos;
-
- // Host only for ipv4.
- if ((pos = hostport.rfind(":")) == string::npos) {
- host = hostport;
- return;
- }
-
- // For ipv4(only one colon), host:port.
- if (hostport.find(":") == pos) {
- host = hostport.substr(0, pos);
- string p = hostport.substr(pos + 1);
- if (!p.empty() && p != "0") {
- port = ::atoi(p.c_str());
- }
- return;
- }
-
- // Host only for ipv6.
- if (hostport.at(0) != '[' || (pos = hostport.rfind("]:")) == string::npos) {
- host = hostport;
- return;
- }
-
- // For ipv6, [host]:port.
- host = hostport.substr(1, pos - 1);
- string p = hostport.substr(pos + 2);
- if (!p.empty() && p != "0") {
- port = ::atoi(p.c_str());
- }
-}
-
-string srs_any_address_for_listener()
-{
- bool ipv4_active = false;
- bool ipv6_active = false;
-
- if (true) {
- int fd = socket(AF_INET, SOCK_DGRAM, 0);
- if (fd != -1) {
- ipv4_active = true;
- close(fd);
- }
- }
- if (true) {
- int fd = socket(AF_INET6, SOCK_DGRAM, 0);
- if (fd != -1) {
- ipv6_active = true;
- close(fd);
- }
- }
-
- if (ipv6_active && !ipv4_active) {
- return SRS_CONSTS_LOOPBACK6;
- }
- return SRS_CONSTS_LOOPBACK;
-}
-
-void srs_parse_endpoint(string hostport, string &ip, int &port)
-{
- const size_t pos = hostport.rfind(":"); // Look for ":" from the end, to work with IPv6.
- if (pos != std::string::npos) {
- if ((pos >= 1) && (hostport[0] == '[') && (hostport[pos - 1] == ']')) {
- // Handle IPv6 in RFC 2732 format, e.g. [3ffe:dead:beef::1]:1935
- ip = hostport.substr(1, pos - 2);
- } else {
- // Handle IP address
- ip = hostport.substr(0, pos);
- }
-
- const string sport = hostport.substr(pos + 1);
- port = ::atoi(sport.c_str());
- } else {
- ip = srs_any_address_for_listener();
- port = ::atoi(hostport.c_str());
- }
-}
-
-bool srs_check_ip_addr_valid(string ip)
-{
- unsigned char buf[sizeof(struct in6_addr)];
-
- // check ipv4
- int ret = inet_pton(AF_INET, ip.data(), buf);
- if (ret > 0) {
- return true;
- }
-
- ret = inet_pton(AF_INET6, ip.data(), buf);
- if (ret > 0) {
- return true;
- }
-
- return false;
-}
-
-string srs_int2str(int64_t value)
-{
- return srs_fmt("%" PRId64, value);
-}
-
-string srs_float2str(double value)
-{
- // len(max int64_t) is 20, plus one "+-."
- char tmp[21 + 1];
- snprintf(tmp, sizeof(tmp), "%.2f", value);
- return tmp;
-}
-
-string srs_bool2switch(bool v)
-{
- return v ? "on" : "off";
-}
-
bool srs_is_little_endian()
{
// convert to network(big-endian) order, if not equals,
@@ -310,7 +120,25 @@ bool srs_is_little_endian()
return (little_endian_check == 1);
}
-string srs_string_replace(string str, string old_str, string new_str)
+string srs_strconv_format_int(int64_t value)
+{
+ return srs_fmt_sprintf("%" PRId64, value);
+}
+
+string srs_strconv_format_float(double value)
+{
+ // len(max int64_t) is 20, plus one "+-."
+ char tmp[21 + 1];
+ snprintf(tmp, sizeof(tmp), "%.2f", value);
+ return tmp;
+}
+
+string srs_strconv_format_bool(bool v)
+{
+ return v ? "on" : "off";
+}
+
+string srs_strings_replace(string str, string old_str, string new_str)
{
std::string ret = str;
@@ -327,7 +155,7 @@ string srs_string_replace(string str, string old_str, string new_str)
return ret;
}
-string srs_string_trim_end(string str, string trim_chars)
+string srs_strings_trim_end(string str, string trim_chars)
{
std::string ret = str;
@@ -345,7 +173,7 @@ string srs_string_trim_end(string str, string trim_chars)
return ret;
}
-string srs_string_trim_start(string str, string trim_chars)
+string srs_strings_trim_start(string str, string trim_chars)
{
std::string ret = str;
@@ -363,7 +191,7 @@ string srs_string_trim_start(string str, string trim_chars)
return ret;
}
-string srs_string_remove(string str, string remove_chars)
+string srs_strings_remove(string str, string remove_chars)
{
std::string ret = str;
@@ -411,63 +239,63 @@ string srs_erase_last_substr(string str, string erase_string)
return ret;
}
-bool srs_string_ends_with(string str, string flag)
+bool srs_strings_ends_with(string str, string flag)
{
const size_t pos = str.rfind(flag);
return (pos != string::npos) && (pos == str.length() - flag.length());
}
-bool srs_string_ends_with(string str, string flag0, string flag1)
+bool srs_strings_ends_with(string str, string flag0, string flag1)
{
- return srs_string_ends_with(str, flag0) || srs_string_ends_with(str, flag1);
+ return srs_strings_ends_with(str, flag0) || srs_strings_ends_with(str, flag1);
}
-bool srs_string_ends_with(string str, string flag0, string flag1, string flag2)
+bool srs_strings_ends_with(string str, string flag0, string flag1, string flag2)
{
- return srs_string_ends_with(str, flag0) || srs_string_ends_with(str, flag1) || srs_string_ends_with(str, flag2);
+ return srs_strings_ends_with(str, flag0) || srs_strings_ends_with(str, flag1) || srs_strings_ends_with(str, flag2);
}
-bool srs_string_ends_with(string str, string flag0, string flag1, string flag2, string flag3)
+bool srs_strings_ends_with(string str, string flag0, string flag1, string flag2, string flag3)
{
- return srs_string_ends_with(str, flag0) || srs_string_ends_with(str, flag1) || srs_string_ends_with(str, flag2) || srs_string_ends_with(str, flag3);
+ return srs_strings_ends_with(str, flag0) || srs_strings_ends_with(str, flag1) || srs_strings_ends_with(str, flag2) || srs_strings_ends_with(str, flag3);
}
-bool srs_string_starts_with(string str, string flag)
+bool srs_strings_starts_with(string str, string flag)
{
return str.find(flag) == 0;
}
-bool srs_string_starts_with(string str, string flag0, string flag1)
+bool srs_strings_starts_with(string str, string flag0, string flag1)
{
- return srs_string_starts_with(str, flag0) || srs_string_starts_with(str, flag1);
+ return srs_strings_starts_with(str, flag0) || srs_strings_starts_with(str, flag1);
}
-bool srs_string_starts_with(string str, string flag0, string flag1, string flag2)
+bool srs_strings_starts_with(string str, string flag0, string flag1, string flag2)
{
- return srs_string_starts_with(str, flag0, flag1) || srs_string_starts_with(str, flag2);
+ return srs_strings_starts_with(str, flag0, flag1) || srs_strings_starts_with(str, flag2);
}
-bool srs_string_starts_with(string str, string flag0, string flag1, string flag2, string flag3)
+bool srs_strings_starts_with(string str, string flag0, string flag1, string flag2, string flag3)
{
- return srs_string_starts_with(str, flag0, flag1, flag2) || srs_string_starts_with(str, flag3);
+ return srs_strings_starts_with(str, flag0, flag1, flag2) || srs_strings_starts_with(str, flag3);
}
-bool srs_string_contains(string str, string flag)
+bool srs_strings_contains(string str, string flag)
{
return str.find(flag) != string::npos;
}
-bool srs_string_contains(string str, string flag0, string flag1)
+bool srs_strings_contains(string str, string flag0, string flag1)
{
return str.find(flag0) != string::npos || str.find(flag1) != string::npos;
}
-bool srs_string_contains(string str, string flag0, string flag1, string flag2)
+bool srs_strings_contains(string str, string flag0, string flag1, string flag2)
{
return str.find(flag0) != string::npos || str.find(flag1) != string::npos || str.find(flag2) != string::npos;
}
-int srs_string_count(string str, string flag)
+int srs_strings_count(string str, string flag)
{
int nn = 0;
for (int i = 0; i < (int)flag.length(); i++) {
@@ -477,7 +305,7 @@ int srs_string_count(string str, string flag)
return nn;
}
-vector srs_string_split(string s, string seperator)
+vector srs_strings_split(string s, string seperator)
{
vector result;
if (seperator.empty()) {
@@ -497,7 +325,7 @@ vector srs_string_split(string s, string seperator)
return result;
}
-string srs_string_min_match(string str, vector seperators)
+string srs_strings_min_match(string str, vector seperators)
{
string match;
@@ -523,7 +351,7 @@ string srs_string_min_match(string str, vector seperators)
return match;
}
-vector srs_string_split(string str, vector seperators)
+vector srs_strings_split(string str, vector seperators)
{
vector arr;
@@ -531,7 +359,7 @@ vector srs_string_split(string str, vector seperators)
string s = str;
while (true) {
- string seperator = srs_string_min_match(s, seperators);
+ string seperator = srs_strings_min_match(s, seperators);
if (seperator.empty()) {
break;
}
@@ -551,7 +379,7 @@ vector srs_string_split(string str, vector seperators)
return arr;
}
-std::string srs_fmt(const char *fmt, ...)
+std::string srs_fmt_sprintf(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
@@ -607,7 +435,66 @@ int srs_do_create_dir_recursively(string dir)
return ret;
}
-bool srs_bytes_equals(void *pa, void *pb, int size)
+string srs_strings_dumps_hex(const std::string &str)
+{
+ return srs_strings_dumps_hex(str.c_str(), str.size());
+}
+
+string srs_strings_dumps_hex(const char *str, int length)
+{
+ return srs_strings_dumps_hex(str, length, INT_MAX);
+}
+
+string srs_strings_dumps_hex(const char *str, int length, int limit)
+{
+ return srs_strings_dumps_hex(str, length, limit, ' ', 128, '\n');
+}
+
+string srs_strings_dumps_hex(const char *str, int length, int limit, char seperator, int line_limit, char newline)
+{
+ // 1 byte trailing '\0'.
+ const int LIMIT = 1024 * 16 + 1;
+ static char buf[LIMIT];
+
+ int len = 0;
+ for (int i = 0; i < length && i < limit && len < LIMIT; ++i) {
+ int nb = snprintf(buf + len, LIMIT - len, "%02x", (uint8_t)str[i]);
+ if (nb <= 0 || nb >= LIMIT - len) {
+ break;
+ }
+ len += nb;
+
+ // Only append seperator and newline when not last byte.
+ if (i < length - 1 && i < limit - 1 && len < LIMIT) {
+ if (seperator) {
+ buf[len++] = seperator;
+ }
+
+ if (newline && line_limit && i > 0 && ((i + 1) % line_limit) == 0) {
+ buf[len++] = newline;
+ }
+ }
+ }
+
+ // Empty string.
+ if (len <= 0) {
+ return "";
+ }
+
+ // If overflow, cut the trailing newline.
+ if (newline && len >= LIMIT - 2 && buf[len - 1] == newline) {
+ len--;
+ }
+
+ // If overflow, cut the trailing seperator.
+ if (seperator && len >= LIMIT - 3 && buf[len - 1] == seperator) {
+ len--;
+ }
+
+ return string(buf, len);
+}
+
+bool srs_bytes_equal(void *pa, void *pb, int size)
{
uint8_t *a = (uint8_t *)pa;
uint8_t *b = (uint8_t *)pb;
@@ -629,7 +516,7 @@ bool srs_bytes_equals(void *pa, void *pb, int size)
return true;
}
-srs_error_t srs_create_dir_recursively(string dir)
+srs_error_t srs_os_mkdir_all(string dir)
{
int ret = srs_do_create_dir_recursively(dir);
@@ -652,7 +539,7 @@ bool srs_path_exists(std::string path)
return false;
}
-string srs_path_dirname(string path)
+string srs_path_filepath_dir(string path)
{
std::string dirname = path;
@@ -672,7 +559,7 @@ string srs_path_dirname(string path)
return dirname;
}
-string srs_path_basename(string path)
+string srs_path_filepath_base(string path)
{
std::string dirname = path;
size_t pos = string::npos;
@@ -688,7 +575,7 @@ string srs_path_basename(string path)
return dirname;
}
-string srs_path_filename(string path)
+string srs_path_filepath_filename(string path)
{
std::string filename = path;
size_t pos = string::npos;
@@ -700,7 +587,7 @@ string srs_path_filename(string path)
return filename;
}
-string srs_path_filext(string path)
+string srs_path_filepath_ext(string path)
{
size_t pos = string::npos;
@@ -711,399 +598,6 @@ string srs_path_filext(string path)
return "";
}
-bool srs_avc_startswith_annexb(SrsBuffer *stream, int *pnb_start_code)
-{
- if (!stream) {
- return false;
- }
-
- char *bytes = stream->data() + stream->pos();
- char *p = bytes;
-
- for (;;) {
- if (!stream->require((int)(p - bytes + 3))) {
- return false;
- }
-
- // not match
- if (p[0] != (char)0x00 || p[1] != (char)0x00) {
- return false;
- }
-
- // match N[00] 00 00 01, where N>=0
- if (p[2] == (char)0x01) {
- if (pnb_start_code) {
- *pnb_start_code = (int)(p - bytes) + 3;
- }
- return true;
- }
-
- p++;
- }
-
- return false;
-}
-
-bool srs_aac_startswith_adts(SrsBuffer *stream)
-{
- if (!stream) {
- return false;
- }
-
- char *bytes = stream->data() + stream->pos();
- char *p = bytes;
-
- if (!stream->require((int)(p - bytes) + 2)) {
- return false;
- }
-
- // matched 12bits 0xFFF,
- // @remark, we must cast the 0xff to char to compare.
- if (p[0] != (char)0xff || (char)(p[1] & 0xf0) != (char)0xf0) {
- return false;
- }
-
- return true;
-}
-
-// @see pycrc reflect at https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L107
-uint64_t __crc32_reflect(uint64_t data, int width)
-{
- uint64_t res = data & 0x01;
-
- for (int i = 0; i < (int)width - 1; i++) {
- data >>= 1;
- res = (res << 1) | (data & 0x01);
- }
-
- return res;
-}
-
-// @see pycrc gen_table at https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L178
-void __crc32_make_table(uint32_t t[256], uint32_t poly, bool reflect_in)
-{
- int width = 32; // 32bits checksum.
- uint64_t msb_mask = (uint32_t)(0x01 << (width - 1));
- uint64_t mask = (uint32_t)(((msb_mask - 1) << 1) | 1);
-
- int tbl_idx_width = 8; // table index size.
- int tbl_width = 0x01 << tbl_idx_width; // table size: 256
-
- for (int i = 0; i < (int)tbl_width; i++) {
- uint64_t reg = uint64_t(i);
-
- if (reflect_in) {
- reg = __crc32_reflect(reg, tbl_idx_width);
- }
-
- reg = reg << (width - tbl_idx_width);
- for (int j = 0; j < tbl_idx_width; j++) {
- if ((reg & msb_mask) != 0) {
- reg = (reg << 1) ^ poly;
- } else {
- reg = reg << 1;
- }
- }
-
- if (reflect_in) {
- reg = __crc32_reflect(reg, width);
- }
-
- t[i] = (uint32_t)(reg & mask);
- }
-}
-
-// @see pycrc table_driven at https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L207
-uint32_t __crc32_table_driven(uint32_t *t, const void *buf, int size, uint32_t previous, bool reflect_in, uint32_t xor_in, bool reflect_out, uint32_t xor_out)
-{
- int width = 32; // 32bits checksum.
- uint64_t msb_mask = (uint32_t)(0x01 << (width - 1));
- uint64_t mask = (uint32_t)(((msb_mask - 1) << 1) | 1);
-
- int tbl_idx_width = 8; // table index size.
-
- uint8_t *p = (uint8_t *)buf;
- uint64_t reg = 0;
-
- if (!reflect_in) {
- reg = xor_in;
-
- for (int i = 0; i < (int)size; i++) {
- uint8_t tblidx = (uint8_t)((reg >> (width - tbl_idx_width)) ^ p[i]);
- reg = t[tblidx] ^ (reg << tbl_idx_width);
- }
- } else {
- reg = previous ^ __crc32_reflect(xor_in, width);
-
- for (int i = 0; i < (int)size; i++) {
- uint8_t tblidx = (uint8_t)(reg ^ p[i]);
- reg = t[tblidx] ^ (reg >> tbl_idx_width);
- }
-
- reg = __crc32_reflect(reg, width);
- }
-
- if (reflect_out) {
- reg = __crc32_reflect(reg, width);
- }
-
- reg ^= xor_out;
- return (uint32_t)(reg & mask);
-}
-
-// @see pycrc https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L207
-// IEEETable is the table for the IEEE polynomial.
-static uint32_t __crc32_IEEE_table[256];
-static bool __crc32_IEEE_table_initialized = false;
-
-// @see pycrc https://github.com/winlinvip/pycrc/blob/master/pycrc/models.py#L220
-// crc32('123456789') = 0xcbf43926
-// where it's defined as model:
-// 'name': 'crc-32',
-// 'width': 32,
-// 'poly': 0x4c11db7,
-// 'reflect_in': True,
-// 'xor_in': 0xffffffff,
-// 'reflect_out': True,
-// 'xor_out': 0xffffffff,
-// 'check': 0xcbf43926,
-uint32_t srs_crc32_ieee(const void *buf, int size, uint32_t previous)
-{
- // @see golang IEEE of hash/crc32/crc32.go
- // IEEE is by far and away the most common CRC-32 polynomial.
- // Used by ethernet (IEEE 802.3), v.42, fddi, gzip, zip, png, ...
- // @remark The poly of CRC32 IEEE is 0x04C11DB7, its reverse is 0xEDB88320,
- // please read https://en.wikipedia.org/wiki/Cyclic_redundancy_check
- uint32_t poly = 0x04C11DB7;
-
- bool reflect_in = true;
- uint32_t xor_in = 0xffffffff;
- bool reflect_out = true;
- uint32_t xor_out = 0xffffffff;
-
- if (!__crc32_IEEE_table_initialized) {
- __crc32_make_table(__crc32_IEEE_table, poly, reflect_in);
- __crc32_IEEE_table_initialized = true;
- }
-
- return __crc32_table_driven(__crc32_IEEE_table, buf, size, previous, reflect_in, xor_in, reflect_out, xor_out);
-}
-
-// @see pycrc https://github.com/winlinvip/pycrc/blob/master/pycrc/algorithms.py#L238
-// IEEETable is the table for the MPEG polynomial.
-static uint32_t __crc32_MPEG_table[256];
-static bool __crc32_MPEG_table_initialized = false;
-
-// @see pycrc https://github.com/winlinvip/pycrc/blob/master/pycrc/models.py#L238
-// crc32('123456789') = 0x0376e6e7
-// where it's defined as model:
-// 'name': 'crc-32',
-// 'width': 32,
-// 'poly': 0x4c11db7,
-// 'reflect_in': False,
-// 'xor_in': 0xffffffff,
-// 'reflect_out': False,
-// 'xor_out': 0x0,
-// 'check': 0x0376e6e7,
-uint32_t srs_crc32_mpegts(const void *buf, int size)
-{
- // @see golang IEEE of hash/crc32/crc32.go
- // IEEE is by far and away the most common CRC-32 polynomial.
- // Used by ethernet (IEEE 802.3), v.42, fddi, gzip, zip, png, ...
- // @remark The poly of CRC32 IEEE is 0x04C11DB7, its reverse is 0xEDB88320,
- // please read https://en.wikipedia.org/wiki/Cyclic_redundancy_check
- uint32_t poly = 0x04C11DB7;
-
- bool reflect_in = false;
- uint32_t xor_in = 0xffffffff;
- bool reflect_out = false;
- uint32_t xor_out = 0x0;
-
- if (!__crc32_MPEG_table_initialized) {
- __crc32_make_table(__crc32_MPEG_table, poly, reflect_in);
- __crc32_MPEG_table_initialized = true;
- }
-
- return __crc32_table_driven(__crc32_MPEG_table, buf, size, 0x00, reflect_in, xor_in, reflect_out, xor_out);
-}
-
-// We use the standard encoding:
-// var StdEncoding = NewEncoding(encodeStd)
-// StdEncoding is the standard base64 encoding, as defined in RFC 4648.
-namespace
-{
-char padding = '=';
-string encoder = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-} // namespace
-// @see golang encoding/base64/base64.go
-srs_error_t srs_av_base64_decode(string cipher, string &plaintext)
-{
- srs_error_t err = srs_success;
-
- uint8_t decodeMap[256];
- memset(decodeMap, 0xff, sizeof(decodeMap));
-
- for (int i = 0; i < (int)encoder.length(); i++) {
- decodeMap[(uint8_t)encoder.at(i)] = uint8_t(i);
- }
-
- // decode is like Decode but returns an additional 'end' value, which
- // indicates if end-of-message padding or a partial quantum was encountered
- // and thus any additional data is an error.
- int si = 0;
-
- // skip over newlines
- for (; si < (int)cipher.length() && (cipher.at(si) == '\n' || cipher.at(si) == '\r'); si++) {
- }
-
- for (bool end = false; si < (int)cipher.length() && !end;) {
- // Decode quantum using the base64 alphabet
- uint8_t dbuf[4];
- memset(dbuf, 0x00, sizeof(dbuf));
-
- int dinc = 3;
- int dlen = 4;
- srs_assert(dinc > 0);
-
- for (int j = 0; j < (int)sizeof(dbuf); j++) {
- if (si == (int)cipher.length()) {
- if (padding != -1 || j < 2) {
- return srs_error_new(ERROR_BASE64_DECODE, "corrupt input at %d", si);
- }
-
- dinc = j - 1;
- dlen = j;
- end = true;
- break;
- }
-
- char in = cipher.at(si);
-
- si++;
- // skip over newlines
- for (; si < (int)cipher.length() && (cipher.at(si) == '\n' || cipher.at(si) == '\r'); si++) {
- }
-
- if (in == padding) {
- // We've reached the end and there's padding
- switch (j) {
- case 0:
- case 1:
- // incorrect padding
- return srs_error_new(ERROR_BASE64_DECODE, "corrupt input at %d", si);
- case 2:
- // "==" is expected, the first "=" is already consumed.
- if (si == (int)cipher.length()) {
- return srs_error_new(ERROR_BASE64_DECODE, "corrupt input at %d", si);
- }
- if (cipher.at(si) != padding) {
- // incorrect padding
- return srs_error_new(ERROR_BASE64_DECODE, "corrupt input at %d", si);
- }
-
- si++;
- // skip over newlines
- for (; si < (int)cipher.length() && (cipher.at(si) == '\n' || cipher.at(si) == '\r'); si++) {
- }
- }
-
- if (si < (int)cipher.length()) {
- // trailing garbage
- err = srs_error_new(ERROR_BASE64_DECODE, "corrupt input at %d", si);
- }
- dinc = 3;
- dlen = j;
- end = true;
- break;
- }
-
- dbuf[j] = decodeMap[(uint8_t)in];
- if (dbuf[j] == 0xff) {
- return srs_error_new(ERROR_BASE64_DECODE, "corrupt input at %d", si);
- }
- }
-
- // Convert 4x 6bit source bytes into 3 bytes
- uint32_t val = uint32_t(dbuf[0]) << 18 | uint32_t(dbuf[1]) << 12 | uint32_t(dbuf[2]) << 6 | uint32_t(dbuf[3]);
- if (dlen >= 2) {
- plaintext.append(1, char(val >> 16));
- }
- if (dlen >= 3) {
- plaintext.append(1, char(val >> 8));
- }
- if (dlen >= 4) {
- plaintext.append(1, char(val));
- }
- }
-
- return err;
-}
-
-// @see golang encoding/base64/base64.go
-srs_error_t srs_av_base64_encode(std::string plaintext, std::string &cipher)
-{
- srs_error_t err = srs_success;
- uint8_t decodeMap[256];
- memset(decodeMap, 0xff, sizeof(decodeMap));
-
- for (int i = 0; i < (int)encoder.length(); i++) {
- decodeMap[(uint8_t)encoder.at(i)] = uint8_t(i);
- }
- cipher.clear();
-
- uint32_t val = 0;
- int si = 0;
- int n = (plaintext.length() / 3) * 3;
- uint8_t *p = (uint8_t *)plaintext.c_str();
- while (si < n) {
- // Convert 3x 8bit source bytes into 4 bytes
- val = (uint32_t(p[si + 0]) << 16) | (uint32_t(p[si + 1]) << 8) | uint32_t(p[si + 2]);
-
- cipher += encoder[val >> 18 & 0x3f];
- cipher += encoder[val >> 12 & 0x3f];
- cipher += encoder[val >> 6 & 0x3f];
- cipher += encoder[val & 0x3f];
-
- si += 3;
- }
-
- int remain = plaintext.length() - si;
- if (0 == remain) {
- return err;
- }
-
- val = uint32_t(p[si + 0]) << 16;
- if (2 == remain) {
- val |= uint32_t(p[si + 1]) << 8;
- }
-
- cipher += encoder[val >> 18 & 0x3f];
- cipher += encoder[val >> 12 & 0x3f];
-
- switch (remain) {
- case 2:
- cipher += encoder[val >> 6 & 0x3f];
- cipher += padding;
- break;
- case 1:
- cipher += padding;
- cipher += padding;
- break;
- }
-
- return err;
-}
-
-#define SPACE_CHARS " \t\r\n"
-
-int av_toupper(int c)
-{
- if (c >= 'a' && c <= 'z') {
- c ^= 0x20;
- }
- return c;
-}
-
// fromHexChar converts a hex character into its value and a success flag.
uint8_t srs_from_hex_char(uint8_t c)
{
@@ -1120,7 +614,7 @@ uint8_t srs_from_hex_char(uint8_t c)
return -1;
}
-char *srs_data_to_hex(char *des, const u_int8_t *src, int len)
+char *srs_hex_encode_to_string(char *des, const u_int8_t *src, int len)
{
if (src == NULL || len == 0 || des == NULL) {
return NULL;
@@ -1136,7 +630,7 @@ char *srs_data_to_hex(char *des, const u_int8_t *src, int len)
return des;
}
-char *srs_data_to_hex_lowercase(char *des, const u_int8_t *src, int len)
+char *srs_hex_encode_to_string_lowercase(char *des, const u_int8_t *src, int len)
{
if (src == NULL || len == 0 || des == NULL) {
return NULL;
@@ -1152,7 +646,7 @@ char *srs_data_to_hex_lowercase(char *des, const u_int8_t *src, int len)
return des;
}
-int srs_hex_to_data(uint8_t *data, const char *p, int size)
+int srs_hex_decode_string(uint8_t *data, const char *p, int size)
{
if (size <= 0 || (size % 2) == 1) {
return -1;
@@ -1175,125 +669,355 @@ int srs_hex_to_data(uint8_t *data, const char *p, int size)
return size / 2;
}
-int srs_chunk_header_c0(int prefer_cid, uint32_t timestamp, int32_t payload_length, int8_t message_type, int32_t stream_id, char *cache, int nb_cache)
+void srs_rand_gen_bytes(char *bytes, int size)
{
- // to directly set the field.
- char *pp = NULL;
+ for (int i = 0; i < size; i++) {
+ // the common value in [0x0f, 0xf0]
+ bytes[i] = 0x0f + (srs_rand_integer() % (256 - 0x0f - 0x0f));
+ }
+}
- // generate the header.
- char *p = cache;
+std::string srs_rand_gen_str(int len)
+{
+ static string random_table = "01234567890123456789012345678901234567890123456789abcdefghijklmnopqrstuvwxyz";
- // no header.
- if (nb_cache < SRS_CONSTS_RTMP_MAX_FMT0_HEADER_SIZE) {
- return 0;
+ string ret;
+ ret.reserve(len);
+ for (int i = 0; i < len; ++i) {
+ ret.append(1, random_table[srs_rand_integer() % random_table.size()]);
}
- // write new chunk stream header, fmt is 0
- *p++ = 0x00 | (prefer_cid & 0x3F);
+ return ret;
+}
- // chunk message header, 11 bytes
- // timestamp, 3bytes, big-endian
- if (timestamp < RTMP_EXTENDED_TIMESTAMP) {
- pp = (char *)×tamp;
- *p++ = pp[2];
- *p++ = pp[1];
- *p++ = pp[0];
+long srs_rand_integer()
+{
+ static bool _random_initialized = false;
+ if (!_random_initialized) {
+ _random_initialized = true;
+ ::srandom((unsigned long)(srs_time_now_realtime() | (::getpid() << 13)));
+ }
+
+ return random();
+}
+
+bool srs_is_digit_number(string str)
+{
+ if (str.empty()) {
+ return false;
+ }
+
+ const char *p = str.c_str();
+ const char *p_end = str.data() + str.length();
+ for (; p < p_end; p++) {
+ if (*p != '0') {
+ break;
+ }
+ }
+ if (p == p_end) {
+ return true;
+ }
+
+ int64_t v = ::atoll(p);
+ int64_t powv = (int64_t)pow(10, p_end - p - 1);
+ return v / powv >= 1 && v / powv <= 9;
+}
+
+srs_error_t srs_io_readall(ISrsReader *in, std::string &content)
+{
+ srs_error_t err = srs_success;
+
+ const int SRS_HTTP_READ_CACHE_BYTES = 4096;
+
+ // Cache to read, it might cause coroutine switch, so we use local cache here.
+ SrsUniquePtr buf(new char[SRS_HTTP_READ_CACHE_BYTES]);
+
+ // Whatever, read util EOF.
+ while (true) {
+ ssize_t nb_read = 0;
+ if ((err = in->read(buf.get(), SRS_HTTP_READ_CACHE_BYTES, &nb_read)) != srs_success) {
+ int code = srs_error_code(err);
+ if (code == ERROR_SYSTEM_FILE_EOF || code == ERROR_HTTP_RESPONSE_EOF || code == ERROR_HTTP_REQUEST_EOF || code == ERROR_HTTP_STREAM_EOF) {
+ srs_freep(err);
+ return err;
+ }
+ return srs_error_wrap(err, "read body");
+ }
+
+ if (nb_read > 0) {
+ content.append(buf.get(), nb_read);
+ }
+ }
+
+ return err;
+}
+
+void srs_net_split_hostport(string hostport, string &host, int &port)
+{
+ // No host or port.
+ if (hostport.empty()) {
+ return;
+ }
+
+ size_t pos = string::npos;
+
+ // Host only for ipv4.
+ if ((pos = hostport.rfind(":")) == string::npos) {
+ host = hostport;
+ return;
+ }
+
+ // For ipv4(only one colon), host:port.
+ if (hostport.find(":") == pos) {
+ host = hostport.substr(0, pos);
+ string p = hostport.substr(pos + 1);
+ if (!p.empty() && p != "0") {
+ port = ::atoi(p.c_str());
+ }
+ return;
+ }
+
+ // Host only for ipv6.
+ if (hostport.at(0) != '[' || (pos = hostport.rfind("]:")) == string::npos) {
+ host = hostport;
+ return;
+ }
+
+ // For ipv6, [host]:port.
+ host = hostport.substr(1, pos - 1);
+ string p = hostport.substr(pos + 2);
+ if (!p.empty() && p != "0") {
+ port = ::atoi(p.c_str());
+ }
+}
+
+void srs_net_split_for_listener(string hostport, string &ip, int &port)
+{
+ const size_t pos = hostport.rfind(":"); // Look for ":" from the end, to work with IPv6.
+ if (pos != std::string::npos) {
+ if ((pos >= 1) && (hostport[0] == '[') && (hostport[pos - 1] == ']')) {
+ // Handle IPv6 in RFC 2732 format, e.g. [3ffe:dead:beef::1]:1935
+ ip = hostport.substr(1, pos - 2);
+ } else {
+ // Handle IP address
+ ip = hostport.substr(0, pos);
+ }
+
+ const string sport = hostport.substr(pos + 1);
+ port = ::atoi(sport.c_str());
} else {
- *p++ = (char)0xFF;
- *p++ = (char)0xFF;
- *p++ = (char)0xFF;
+ ip = srs_net_address_any();
+ port = ::atoi(hostport.c_str());
}
-
- // message_length, 3bytes, big-endian
- pp = (char *)&payload_length;
- *p++ = pp[2];
- *p++ = pp[1];
- *p++ = pp[0];
-
- // message_type, 1bytes
- *p++ = message_type;
-
- // stream_id, 4bytes, little-endian
- pp = (char *)&stream_id;
- *p++ = pp[0];
- *p++ = pp[1];
- *p++ = pp[2];
- *p++ = pp[3];
-
- // for c0
- // chunk extended timestamp header, 0 or 4 bytes, big-endian
- //
- // for c3:
- // chunk extended timestamp header, 0 or 4 bytes, big-endian
- // 6.1.3. Extended Timestamp
- // This field is transmitted only when the normal time stamp in the
- // chunk message header is set to 0x00ffffff. If normal time stamp is
- // set to any value less than 0x00ffffff, this field MUST NOT be
- // present. This field MUST NOT be present if the timestamp field is not
- // present. Type 3 chunks MUST NOT have this field.
- // adobe changed for Type3 chunk:
- // FMLE always sendout the extended-timestamp,
- // must send the extended-timestamp to FMS,
- // must send the extended-timestamp to flash-player.
- // @see: ngx_rtmp_prepare_message
- // @see: http://blog.csdn.net/win_lin/article/details/13363699
- // TODO: FIXME: extract to outer.
- if (timestamp >= RTMP_EXTENDED_TIMESTAMP) {
- pp = (char *)×tamp;
- *p++ = pp[3];
- *p++ = pp[2];
- *p++ = pp[1];
- *p++ = pp[0];
- }
-
- // always has header
- return (int)(p - cache);
}
-int srs_chunk_header_c3(int prefer_cid, uint32_t timestamp, char *cache, int nb_cache)
+string srs_net_address_any()
{
- // to directly set the field.
- char *pp = NULL;
+ bool ipv4_active = false;
+ bool ipv6_active = false;
- // generate the header.
- char *p = cache;
+ if (true) {
+ int fd = socket(AF_INET, SOCK_DGRAM, 0);
+ if (fd != -1) {
+ ipv4_active = true;
+ close(fd);
+ }
+ }
+ if (true) {
+ int fd = socket(AF_INET6, SOCK_DGRAM, 0);
+ if (fd != -1) {
+ ipv6_active = true;
+ close(fd);
+ }
+ }
- // no header.
- if (nb_cache < SRS_CONSTS_RTMP_MAX_FMT3_HEADER_SIZE) {
+ if (ipv6_active && !ipv4_active) {
+ return SRS_CONSTS_LOOPBACK6;
+ }
+ return SRS_CONSTS_LOOPBACK;
+}
+
+bool srs_net_is_valid_ip(string ip)
+{
+ unsigned char buf[sizeof(struct in6_addr)];
+
+ // check ipv4
+ int ret = inet_pton(AF_INET, ip.data(), buf);
+ if (ret > 0) {
+ return true;
+ }
+
+ ret = inet_pton(AF_INET6, ip.data(), buf);
+ if (ret > 0) {
+ return true;
+ }
+
+ return false;
+}
+
+bool srs_net_is_ipv4(string domain)
+{
+ for (int i = 0; i < (int)domain.length(); i++) {
+ char ch = domain.at(i);
+ if (ch == '.') {
+ continue;
+ }
+ if (ch >= '0' && ch <= '9') {
+ continue;
+ }
+
+ return false;
+ }
+
+ return true;
+}
+
+uint32_t srs_net_ipv4_to_integer(string ip)
+{
+ uint32_t addr = 0;
+ if (inet_pton(AF_INET, ip.c_str(), &addr) <= 0) {
return 0;
}
- // write no message header chunk stream, fmt is 3
- // @remark, if prefer_cid > 0x3F, that is, use 2B/3B chunk header,
- // SRS will rollback to 1B chunk header.
- *p++ = 0xC0 | (prefer_cid & 0x3F);
+ return ntohl(addr);
+}
- // for c0
- // chunk extended timestamp header, 0 or 4 bytes, big-endian
- //
- // for c3:
- // chunk extended timestamp header, 0 or 4 bytes, big-endian
- // 6.1.3. Extended Timestamp
- // This field is transmitted only when the normal time stamp in the
- // chunk message header is set to 0x00ffffff. If normal time stamp is
- // set to any value less than 0x00ffffff, this field MUST NOT be
- // present. This field MUST NOT be present if the timestamp field is not
- // present. Type 3 chunks MUST NOT have this field.
- // adobe changed for Type3 chunk:
- // FMLE always sendout the extended-timestamp,
- // must send the extended-timestamp to FMS,
- // must send the extended-timestamp to flash-player.
- // @see: ngx_rtmp_prepare_message
- // @see: http://blog.csdn.net/win_lin/article/details/13363699
- // TODO: FIXME: extract to outer.
- if (timestamp >= RTMP_EXTENDED_TIMESTAMP) {
- pp = (char *)×tamp;
- *p++ = pp[3];
- *p++ = pp[2];
- *p++ = pp[1];
- *p++ = pp[0];
+bool srs_net_ipv4_within_mask(string ip, string network, string mask)
+{
+ uint32_t ip_addr = srs_net_ipv4_to_integer(ip);
+ uint32_t mask_addr = srs_net_ipv4_to_integer(mask);
+ uint32_t network_addr = srs_net_ipv4_to_integer(network);
+
+ return (ip_addr & mask_addr) == (network_addr & mask_addr);
+}
+
+static struct CIDR_VALUE {
+ size_t length;
+ std::string mask;
+} CIDR_VALUES[32] = {
+ {1, "128.0.0.0"},
+ {2, "192.0.0.0"},
+ {3, "224.0.0.0"},
+ {4, "240.0.0.0"},
+ {5, "248.0.0.0"},
+ {6, "252.0.0.0"},
+ {7, "254.0.0.0"},
+ {8, "255.0.0.0"},
+ {9, "255.128.0.0"},
+ {10, "255.192.0.0"},
+ {11, "255.224.0.0"},
+ {12, "255.240.0.0"},
+ {13, "255.248.0.0"},
+ {14, "255.252.0.0"},
+ {15, "255.254.0.0"},
+ {16, "255.255.0.0"},
+ {17, "255.255.128.0"},
+ {18, "255.255.192.0"},
+ {19, "255.255.224.0"},
+ {20, "255.255.240.0"},
+ {21, "255.255.248.0"},
+ {22, "255.255.252.0"},
+ {23, "255.255.254.0"},
+ {24, "255.255.255.0"},
+ {25, "255.255.255.128"},
+ {26, "255.255.255.192"},
+ {27, "255.255.255.224"},
+ {28, "255.255.255.240"},
+ {29, "255.255.255.248"},
+ {30, "255.255.255.252"},
+ {31, "255.255.255.254"},
+ {32, "255.255.255.255"},
+};
+
+string srs_net_get_cidr_mask(string network_address)
+{
+ string delimiter = "/";
+
+ size_t delimiter_position = network_address.find(delimiter);
+ if (delimiter_position == string::npos) {
+ // Even if it does not have "/N", it can be a valid IP, by default "/32".
+ if (srs_net_is_ipv4(network_address)) {
+ return CIDR_VALUES[32 - 1].mask;
+ }
+ return "";
}
- // always has header
- return (int)(p - cache);
+ // Change here to include IPv6 support.
+ string is_ipv4_address = network_address.substr(0, delimiter_position);
+ if (!srs_net_is_ipv4(is_ipv4_address)) {
+ return "";
+ }
+
+ size_t cidr_length_position = delimiter_position + delimiter.length();
+ if (cidr_length_position >= network_address.length()) {
+ return "";
+ }
+
+ string cidr_length = network_address.substr(cidr_length_position, network_address.length());
+ if (cidr_length.length() <= 0) {
+ return "";
+ }
+
+ size_t cidr_length_num = 31;
+ try {
+ cidr_length_num = atoi(cidr_length.c_str());
+ if (cidr_length_num <= 0) {
+ return "";
+ }
+ } catch (...) {
+ return "";
+ }
+
+ return CIDR_VALUES[cidr_length_num - 1].mask;
+}
+
+string srs_net_get_cidr_ipv4(string network_address)
+{
+ string delimiter = "/";
+
+ size_t delimiter_position = network_address.find(delimiter);
+ if (delimiter_position == string::npos) {
+ // Even if it does not have "/N", it can be a valid IP, by default "/32".
+ if (srs_net_is_ipv4(network_address)) {
+ return network_address;
+ }
+ return "";
+ }
+
+ // Change here to include IPv6 support.
+ string ipv4_address = network_address.substr(0, delimiter_position);
+ if (!srs_net_is_ipv4(ipv4_address)) {
+ return "";
+ }
+
+ size_t cidr_length_position = delimiter_position + delimiter.length();
+ if (cidr_length_position >= network_address.length()) {
+ return "";
+ }
+
+ string cidr_length = network_address.substr(cidr_length_position, network_address.length());
+ if (cidr_length.length() <= 0) {
+ return "";
+ }
+
+ try {
+ size_t cidr_length_num = atoi(cidr_length.c_str());
+ if (cidr_length_num <= 0) {
+ return "";
+ }
+ } catch (...) {
+ return "";
+ }
+
+ return ipv4_address;
+}
+
+bool srs_net_url_is_http(string url)
+{
+ return srs_strings_starts_with(url, "http://", "https://");
+}
+
+bool srs_net_url_is_rtmp(string url)
+{
+ return srs_strings_starts_with(url, "rtmp://");
}
diff --git a/trunk/src/kernel/srs_kernel_utility.hpp b/trunk/src/kernel/srs_kernel_utility.hpp
index ba554d9c8..88788f902 100644
--- a/trunk/src/kernel/srs_kernel_utility.hpp
+++ b/trunk/src/kernel/srs_kernel_utility.hpp
@@ -9,154 +9,24 @@
#include
+#include