winlin

refine the thread model for the retry threads

要显示太多修改。

为保证性能只显示 21 of 21+ 个文件。

... ... @@ -81,11 +81,11 @@ vhost __defaultVhost__ {
vhost dev {
enabled on;
gop_cache on;
hls on;
hls off;
hls_path ./objs/nginx/html;
hls_fragment 5;
hls_window 30;
#forward 127.0.0.1:19350;
forward 127.0.0.1:19350;
http_hooks {
enabled off;
on_connect http://127.0.0.1:8085/api/v1/clients;
... ... @@ -96,7 +96,7 @@ vhost dev {
on_stop http://127.0.0.1:8085/api/v1/sessions;
}
transcode {
enabled off;
enabled on;
ffmpeg ./objs/ffmpeg/bin/ffmpeg;
engine dev {
enabled on;
... ...
... ... @@ -116,7 +116,7 @@ MODULE_FILES=("srs_core" "srs_core_log" "srs_core_server"
"srs_core_handshake" "srs_core_pithy_print"
"srs_core_config" "srs_core_refer" "srs_core_reload"
"srs_core_hls" "srs_core_forward" "srs_core_encoder"
"srs_core_http")
"srs_core_http" "srs_core_thread")
MODULE_DIR="src/core" . auto/modules.sh
CORE_OBJS="${MODULE_OBJS[@]}"
... ...
不能预览此文件类型
... ... @@ -111,3 +111,17 @@ void srs_vhost_resolve(std::string& vhost, std::string& app)
}
}
}
void srs_close_stfd(st_netfd_t& stfd)
{
if (stfd) {
int fd = st_netfd_fileno(stfd);
st_netfd_close(stfd);
stfd = NULL;
// st does not close it sometimes,
// close it manually.
close(fd);
}
}
... ...
... ... @@ -46,6 +46,8 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <stddef.h>
#include <sys/types.h>
#include <st.h>
// generated by configure.
#include <srs_auto_headers.hpp>
... ... @@ -102,4 +104,7 @@ extern std::string srs_dns_resolve(std::string host);
// app...vhost...request_vhost
extern void srs_vhost_resolve(std::string& vhost, std::string& app);
// close the netfd, and close the underlayer fd.
extern void srs_close_stfd(st_netfd_t& stfd);
#endif
\ No newline at end of file
... ...
... ... @@ -36,15 +36,7 @@ SrsConnection::SrsConnection(SrsServer* srs_server, st_netfd_t client_stfd)
SrsConnection::~SrsConnection()
{
if (stfd) {
int fd = st_netfd_fileno(stfd);
st_netfd_close(stfd);
stfd = NULL;
// st does not close it sometimes,
// close it manually.
close(fd);
}
srs_close_stfd(stfd);
}
int SrsConnection::start()
... ...
... ... @@ -30,8 +30,6 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <srs_core.hpp>
#include <st.h>
class SrsServer;
class SrsConnection
{
... ...
... ... @@ -483,52 +483,15 @@ void SrsFFMPEG::stop()
SrsEncoder::SrsEncoder()
{
tid = NULL;
loop = false;
pthread = new SrsThread(this, SRS_ENCODER_SLEEP_MS);
pithy_print = new SrsPithyPrint(SRS_STAGE_ENCODER);
}
SrsEncoder::~SrsEncoder()
{
on_unpublish();
}
int SrsEncoder::parse_scope_engines(SrsRequest* req)
{
int ret = ERROR_SUCCESS;
// parse all transcode engines.
SrsConfDirective* conf = NULL;
// parse vhost scope engines
std::string scope = "";
if ((conf = config->get_transcode(req->vhost, scope)) != NULL) {
if ((ret = parse_transcode(req, conf)) != ERROR_SUCCESS) {
srs_error("parse vhost scope=%s transcode engines failed. "
"ret=%d", scope.c_str(), ret);
return ret;
}
}
// parse app scope engines
scope = req->app;
if ((conf = config->get_transcode(req->vhost, scope)) != NULL) {
if ((ret = parse_transcode(req, conf)) != ERROR_SUCCESS) {
srs_error("parse app scope=%s transcode engines failed. "
"ret=%d", scope.c_str(), ret);
return ret;
}
}
// parse stream scope engines
scope += "/";
scope += req->stream;
if ((conf = config->get_transcode(req->vhost, scope)) != NULL) {
if ((ret = parse_transcode(req, conf)) != ERROR_SUCCESS) {
srs_error("parse stream scope=%s transcode engines failed. "
"ret=%d", scope.c_str(), ret);
return ret;
}
}
return ret;
srs_freep(pthread);
}
int SrsEncoder::on_publish(SrsRequest* req)
... ... @@ -539,6 +502,7 @@ int SrsEncoder::on_publish(SrsRequest* req)
// ignore the loop encoder
if (ret == ERROR_ENCODER_LOOP) {
clear_engines();
ret = ERROR_SUCCESS;
}
... ... @@ -548,9 +512,7 @@ int SrsEncoder::on_publish(SrsRequest* req)
}
// start thread to run all encoding engines.
srs_assert(!tid);
if((tid = st_thread_create(encoder_thread, this, 1, 0)) == NULL) {
ret = ERROR_ST_CREATE_FORWARD_THREAD;
if ((ret = pthread->start()) != ERROR_SUCCESS) {
srs_error("st_thread_create failed. ret=%d", ret);
return ret;
}
... ... @@ -560,23 +522,58 @@ int SrsEncoder::on_publish(SrsRequest* req)
void SrsEncoder::on_unpublish()
{
if (tid) {
loop = false;
st_thread_interrupt(tid);
st_thread_join(tid, NULL);
tid = NULL;
pthread->stop();
clear_engines();
}
int SrsEncoder::cycle()
{
int ret = ERROR_SUCCESS;
std::vector<SrsFFMPEG*>::iterator it;
for (it = ffmpegs.begin(); it != ffmpegs.end(); ++it) {
SrsFFMPEG* ffmpeg = *it;
// start all ffmpegs.
if ((ret = ffmpeg->start()) != ERROR_SUCCESS) {
srs_error("ffmpeg start failed. ret=%d", ret);
return ret;
}
// check ffmpeg status.
if ((ret = ffmpeg->cycle()) != ERROR_SUCCESS) {
srs_error("ffmpeg cycle failed. ret=%d", ret);
return ret;
}
}
clear_engines();
// pithy print
encoder();
pithy_print->elapse(SRS_ENCODER_SLEEP_MS);
return ret;
}
void SrsEncoder::on_leave_loop()
{
// kill ffmpeg when finished and it alive
std::vector<SrsFFMPEG*>::iterator it;
for (it = ffmpegs.begin(); it != ffmpegs.end(); ++it) {
SrsFFMPEG* ffmpeg = *it;
ffmpeg->stop();
}
}
void SrsEncoder::clear_engines()
{
std::vector<SrsFFMPEG*>::iterator it;
for (it = ffmpegs.begin(); it != ffmpegs.end(); ++it) {
SrsFFMPEG* ffmpeg = *it;
srs_freep(ffmpeg);
}
ffmpegs.clear();
}
... ... @@ -585,6 +582,45 @@ SrsFFMPEG* SrsEncoder::at(int index)
return ffmpegs[index];
}
int SrsEncoder::parse_scope_engines(SrsRequest* req)
{
int ret = ERROR_SUCCESS;
// parse all transcode engines.
SrsConfDirective* conf = NULL;
// parse vhost scope engines
std::string scope = "";
if ((conf = config->get_transcode(req->vhost, scope)) != NULL) {
if ((ret = parse_transcode(req, conf)) != ERROR_SUCCESS) {
srs_error("parse vhost scope=%s transcode engines failed. "
"ret=%d", scope.c_str(), ret);
return ret;
}
}
// parse app scope engines
scope = req->app;
if ((conf = config->get_transcode(req->vhost, scope)) != NULL) {
if ((ret = parse_transcode(req, conf)) != ERROR_SUCCESS) {
srs_error("parse app scope=%s transcode engines failed. "
"ret=%d", scope.c_str(), ret);
return ret;
}
}
// parse stream scope engines
scope += "/";
scope += req->stream;
if ((conf = config->get_transcode(req->vhost, scope)) != NULL) {
if ((ret = parse_transcode(req, conf)) != ERROR_SUCCESS) {
srs_error("parse stream scope=%s transcode engines failed. "
"ret=%d", scope.c_str(), ret);
return ret;
}
}
return ret;
}
int SrsEncoder::parse_transcode(SrsRequest* req, SrsConfDirective* conf)
{
int ret = ERROR_SUCCESS;
... ... @@ -631,7 +667,6 @@ int SrsEncoder::parse_transcode(SrsRequest* req, SrsConfDirective* conf)
// if got a loop, donot transcode the whole stream.
if (ret == ERROR_ENCODER_LOOP) {
clear_engines();
break;
}
... ... @@ -646,85 +681,14 @@ int SrsEncoder::parse_transcode(SrsRequest* req, SrsConfDirective* conf)
return ret;
}
int SrsEncoder::cycle()
{
int ret = ERROR_SUCCESS;
std::vector<SrsFFMPEG*>::iterator it;
for (it = ffmpegs.begin(); it != ffmpegs.end(); ++it) {
SrsFFMPEG* ffmpeg = *it;
// start all ffmpegs.
if ((ret = ffmpeg->start()) != ERROR_SUCCESS) {
srs_error("ffmpeg start failed. ret=%d", ret);
return ret;
}
// check ffmpeg status.
if ((ret = ffmpeg->cycle()) != ERROR_SUCCESS) {
srs_error("ffmpeg cycle failed. ret=%d", ret);
return ret;
}
}
return ret;
}
void SrsEncoder::encoder_cycle()
{
int ret = ERROR_SUCCESS;
log_context->generate_id();
srs_trace("encoder cycle start");
SrsPithyPrint pithy_print(SRS_STAGE_ENCODER);
while (loop) {
if ((ret = cycle()) != ERROR_SUCCESS) {
srs_warn("encoder cycle failed, ignored and retry, ret=%d", ret);
} else {
srs_info("encoder cycle success, retry");
}
if (!loop) {
break;
}
encoder(&pithy_print);
pithy_print.elapse(SRS_ENCODER_SLEEP_MS);
st_usleep(SRS_ENCODER_SLEEP_MS * 1000);
}
// kill ffmpeg when finished and it alive
std::vector<SrsFFMPEG*>::iterator it;
for (it = ffmpegs.begin(); it != ffmpegs.end(); ++it) {
SrsFFMPEG* ffmpeg = *it;
ffmpeg->stop();
}
srs_trace("encoder cycle finished");
}
void SrsEncoder::encoder(SrsPithyPrint* pithy_print)
void SrsEncoder::encoder()
{
// reportable
if (pithy_print->can_print()) {
srs_trace("-> time=%"PRId64", encoders=%d",
pithy_print->get_age(), (int)ffmpegs.size());
// TODO: FIXME: show more info.
srs_trace("-> time=%"PRId64", encoders=%d", pithy_print->get_age(), (int)ffmpegs.size());
}
}
void* SrsEncoder::encoder_thread(void* arg)
{
SrsEncoder* obj = (SrsEncoder*)arg;
srs_assert(obj != NULL);
obj->loop = true;
obj->encoder_cycle();
return NULL;
}
#endif
... ...
... ... @@ -32,7 +32,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <string>
#include <vector>
#include <st.h>
#include <srs_core_thread.hpp>
class SrsConfDirective;
class SrsRequest;
... ... @@ -85,28 +85,29 @@ public:
* the encoder for a stream,
* may use multiple ffmpegs to transcode the specified stream.
*/
class SrsEncoder
class SrsEncoder : public ISrsThreadHandler
{
private:
std::vector<SrsFFMPEG*> ffmpegs;
private:
st_thread_t tid;
bool loop;
SrsThread* pthread;
SrsPithyPrint* pithy_print;
public:
SrsEncoder();
virtual ~SrsEncoder();
public:
virtual int on_publish(SrsRequest* req);
virtual void on_unpublish();
// interface ISrsThreadHandler.
public:
virtual int cycle();
virtual void on_leave_loop();
private:
virtual int parse_scope_engines(SrsRequest* req);
virtual void clear_engines();
virtual SrsFFMPEG* at(int index);
virtual int parse_scope_engines(SrsRequest* req);
virtual int parse_transcode(SrsRequest* req, SrsConfDirective* conf);
virtual int cycle();
virtual void encoder_cycle();
virtual void encoder(SrsPithyPrint* pithy_print);
static void* encoder_thread(void* arg);
virtual void encoder();
};
#endif
... ...
... ... @@ -37,8 +37,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#define ERROR_ST_OPEN_SOCKET 102
#define ERROR_ST_CREATE_LISTEN_THREAD 103
#define ERROR_ST_CREATE_CYCLE_THREAD 104
#define ERROR_ST_CREATE_FORWARD_THREAD 105
#define ERROR_ST_CONNECT 106
#define ERROR_ST_CONNECT 105
#define ERROR_SOCKET_CREATE 200
#define ERROR_SOCKET_SETREUSE 201
... ...
/*
The MIT License (MIT)
Copyright (c) 2013 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <srs_core_forward.hpp>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <srs_core_error.hpp>
#include <srs_core_rtmp.hpp>
#include <srs_core_log.hpp>
#include <srs_core_protocol.hpp>
#include <srs_core_pithy_print.hpp>
#include <srs_core_rtmp.hpp>
#include <srs_core_config.hpp>
#define SRS_PULSE_TIMEOUT_MS 100
#define SRS_FORWARDER_SLEEP_MS 2000
#define SRS_SEND_TIMEOUT_US 3000000L
#define SRS_RECV_TIMEOUT_US SRS_SEND_TIMEOUT_US
SrsForwarder::SrsForwarder()
{
client = NULL;
stfd = NULL;
stream_id = 0;
tid = NULL;
loop = false;
}
SrsForwarder::~SrsForwarder()
{
on_unpublish();
std::vector<SrsSharedPtrMessage*>::iterator it;
for (it = msgs.begin(); it != msgs.end(); ++it) {
SrsSharedPtrMessage* msg = *it;
srs_freep(msg);
}
msgs.clear();
}
int SrsForwarder::on_publish(SrsRequest* req, std::string forward_server)
{
int ret = ERROR_SUCCESS;
// forward app
app = req->app;
stream_name = req->stream;
server = forward_server;
std::string s_port = RTMP_DEFAULT_PORTS;
port = RTMP_DEFAULT_PORT;
size_t pos = forward_server.find(":");
if (pos != std::string::npos) {
s_port = forward_server.substr(pos + 1);
server = forward_server.substr(0, pos);
}
// discovery vhost
std::string vhost = req->vhost;
srs_vhost_resolve(vhost, s_port);
port = ::atoi(s_port.c_str());
// generate tcUrl
tc_url = "rtmp://";
tc_url += vhost;
tc_url += "/";
tc_url += req->app;
// dead loop check
std::string source_ep = req->vhost;
source_ep += ":";
source_ep += req->port;
std::string dest_ep = vhost;
dest_ep += ":";
dest_ep += s_port;
if (source_ep == dest_ep) {
ret = ERROR_SYSTEM_FORWARD_LOOP;
srs_warn("farder loop detected. src=%s, dest=%s, ret=%d",
source_ep.c_str(), dest_ep.c_str(), ret);
return ret;
}
srs_trace("start forward %s to %s, stream: %s/%s",
source_ep.c_str(), dest_ep.c_str(), tc_url.c_str(),
stream_name.c_str());
// TODO: seems bug when republish and reforward.
// start forward
if ((ret = open_socket()) != ERROR_SUCCESS) {
return ret;
}
srs_assert(!tid);
if((tid = st_thread_create(forward_thread, this, 1, 0)) == NULL){
ret = ERROR_ST_CREATE_FORWARD_THREAD;
srs_error("st_thread_create failed. ret=%d", ret);
return ret;
}
return ret;
}
void SrsForwarder::on_unpublish()
{
if (tid) {
loop = false;
st_thread_interrupt(tid);
st_thread_join(tid, NULL);
tid = NULL;
}
if (stfd) {
int fd = st_netfd_fileno(stfd);
st_netfd_close(stfd);
stfd = NULL;
// st does not close it sometimes,
// close it manually.
close(fd);
}
srs_freep(client);
}
int SrsForwarder::on_meta_data(SrsSharedPtrMessage* metadata)
{
int ret = ERROR_SUCCESS;
msgs.push_back(metadata);
return ret;
}
int SrsForwarder::on_audio(SrsSharedPtrMessage* msg)
{
int ret = ERROR_SUCCESS;
// TODO: FIXME: must drop the msgs when server failed.
msgs.push_back(msg);
return ret;
}
int SrsForwarder::on_video(SrsSharedPtrMessage* msg)
{
int ret = ERROR_SUCCESS;
// TODO: FIXME: must drop the msgs when server failed.
msgs.push_back(msg);
return ret;
}
int SrsForwarder::open_socket()
{
int ret = ERROR_SUCCESS;
srs_trace("forward stream=%s, tcUrl=%s to server=%s, port=%d",
stream_name.c_str(), tc_url.c_str(), server.c_str(), port);
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == -1){
ret = ERROR_SOCKET_CREATE;
srs_error("create socket error. ret=%d", ret);
return ret;
}
stfd = st_netfd_open_socket(sock);
if(stfd == NULL){
ret = ERROR_ST_OPEN_SOCKET;
srs_error("st_netfd_open_socket failed. ret=%d", ret);
return ret;
}
srs_freep(client);
client = new SrsRtmpClient(stfd);
return ret;
}
int SrsForwarder::connect_server()
{
int ret = ERROR_SUCCESS;
std::string ip = srs_dns_resolve(server);
if (ip.empty()) {
ret = ERROR_SYSTEM_IP_INVALID;
srs_error("dns resolve server error, ip empty. ret=%d", ret);
return ret;
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip.c_str());
if (st_connect(stfd, (const struct sockaddr*)&addr, sizeof(sockaddr_in), ST_UTIME_NO_TIMEOUT) == -1){
ret = ERROR_ST_CONNECT;
srs_error("connect to server error. ip=%s, port=%d, ret=%d", ip.c_str(), port, ret);
return ret;
}
srs_trace("connect to server success. server=%s, ip=%s, port=%d", server.c_str(), ip.c_str(), port);
return ret;
}
int SrsForwarder::cycle()
{
int ret = ERROR_SUCCESS;
client->set_recv_timeout(SRS_RECV_TIMEOUT_US);
client->set_send_timeout(SRS_SEND_TIMEOUT_US);
if ((ret = connect_server()) != ERROR_SUCCESS) {
return ret;
}
srs_assert(client);
if ((ret = client->handshake()) != ERROR_SUCCESS) {
srs_error("handshake with server failed. ret=%d", ret);
return ret;
}
if ((ret = client->connect_app(app, tc_url)) != ERROR_SUCCESS) {
srs_error("connect with server failed, tcUrl=%s. ret=%d", tc_url.c_str(), ret);
return ret;
}
if ((ret = client->create_stream(stream_id)) != ERROR_SUCCESS) {
srs_error("connect with server failed, stream_id=%d. ret=%d", stream_id, ret);
return ret;
}
// TODO: FIXME: need to cache the metadata and sequence header when reconnect.
if ((ret = client->publish(stream_name, stream_id)) != ERROR_SUCCESS) {
srs_error("connect with server failed, stream_name=%s, stream_id=%d. ret=%d",
stream_name.c_str(), stream_id, ret);
return ret;
}
if ((ret = forward()) != ERROR_SUCCESS) {
return ret;
}
return ret;
}
int SrsForwarder::forward()
{
int ret = ERROR_SUCCESS;
client->set_recv_timeout(SRS_PULSE_TIMEOUT_MS * 1000);
SrsPithyPrint pithy_print(SRS_STAGE_FORWARDER);
while (loop) {
pithy_print.elapse(SRS_PULSE_TIMEOUT_MS);
// switch to other st-threads.
st_usleep(0);
// read from client.
if (true) {
SrsCommonMessage* msg = NULL;
ret = client->recv_message(&msg);
srs_verbose("play loop recv message. ret=%d", ret);
if (ret != ERROR_SUCCESS && ret != ERROR_SOCKET_TIMEOUT) {
srs_error("recv server control message failed. ret=%d", ret);
return ret;
}
}
// ignore when no messages.
int count = (int)msgs.size();
if (msgs.empty()) {
continue;
}
// reportable
if (pithy_print.can_print()) {
srs_trace("-> time=%"PRId64", msgs=%d, obytes=%"PRId64", ibytes=%"PRId64", okbps=%d, ikbps=%d",
pithy_print.get_age(), count, client->get_send_bytes(), client->get_recv_bytes(), client->get_send_kbps(), client->get_recv_kbps());
}
// all msgs to forward.
int i = 0;
for (i = 0; i < count; i++) {
SrsSharedPtrMessage* msg = msgs[i];
msgs[i] = NULL;
// we erased the sendout messages, the msg must not be NULL.
srs_assert(msg);
ret = client->send_message(msg);
if (ret != ERROR_SUCCESS) {
srs_error("forwarder send message to server failed. ret=%d", ret);
// convert the index to count when error.
i++;
break;
}
}
// clear sendout mesages.
if (i < count) {
srs_warn("clear forwarded msg, total=%d, forwarded=%d, ret=%d", count, i, ret);
} else {
srs_info("clear forwarded msg, total=%d, forwarded=%d, ret=%d", count, i, ret);
}
msgs.erase(msgs.begin(), msgs.begin() + i);
if (ret != ERROR_SUCCESS) {
break;
}
}
return ret;
}
void SrsForwarder::forward_cycle()
{
int ret = ERROR_SUCCESS;
log_context->generate_id();
srs_trace("forward cycle start");
while (loop) {
if ((ret = cycle()) != ERROR_SUCCESS) {
srs_warn("forward cycle failed, ignored and retry, ret=%d", ret);
} else {
srs_info("forward cycle success, retry");
}
if (!loop) {
break;
}
st_usleep(SRS_FORWARDER_SLEEP_MS * 1000);
if ((ret = open_socket()) != ERROR_SUCCESS) {
srs_warn("forward cycle reopen failed, ignored and retry, ret=%d", ret);
} else {
srs_info("forward cycle reopen success");
}
}
srs_trace("forward cycle finished");
}
void* SrsForwarder::forward_thread(void* arg)
{
SrsForwarder* obj = (SrsForwarder*)arg;
srs_assert(obj != NULL);
obj->loop = true;
obj->forward_cycle();
return NULL;
}
/*
The MIT License (MIT)
Copyright (c) 2013 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <srs_core_forward.hpp>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <srs_core_error.hpp>
#include <srs_core_rtmp.hpp>
#include <srs_core_log.hpp>
#include <srs_core_protocol.hpp>
#include <srs_core_pithy_print.hpp>
#include <srs_core_rtmp.hpp>
#include <srs_core_config.hpp>
#define SRS_PULSE_TIMEOUT_MS 100
#define SRS_FORWARDER_SLEEP_MS 2000
#define SRS_SEND_TIMEOUT_US 3000000L
#define SRS_RECV_TIMEOUT_US SRS_SEND_TIMEOUT_US
SrsForwarder::SrsForwarder()
{
client = NULL;
stfd = NULL;
stream_id = 0;
pthread = new SrsThread(this, SRS_FORWARDER_SLEEP_MS);
}
SrsForwarder::~SrsForwarder()
{
on_unpublish();
std::vector<SrsSharedPtrMessage*>::iterator it;
for (it = msgs.begin(); it != msgs.end(); ++it) {
SrsSharedPtrMessage* msg = *it;
srs_freep(msg);
}
msgs.clear();
srs_freep(pthread);
}
int SrsForwarder::on_publish(SrsRequest* req, std::string forward_server)
{
int ret = ERROR_SUCCESS;
// forward app
app = req->app;
stream_name = req->stream;
server = forward_server;
std::string s_port = RTMP_DEFAULT_PORTS;
port = RTMP_DEFAULT_PORT;
size_t pos = forward_server.find(":");
if (pos != std::string::npos) {
s_port = forward_server.substr(pos + 1);
server = forward_server.substr(0, pos);
}
// discovery vhost
std::string vhost = req->vhost;
srs_vhost_resolve(vhost, s_port);
port = ::atoi(s_port.c_str());
// generate tcUrl
tc_url = "rtmp://";
tc_url += vhost;
tc_url += "/";
tc_url += req->app;
// dead loop check
std::string source_ep = req->vhost;
source_ep += ":";
source_ep += req->port;
std::string dest_ep = vhost;
dest_ep += ":";
dest_ep += s_port;
if (source_ep == dest_ep) {
ret = ERROR_SYSTEM_FORWARD_LOOP;
srs_warn("farder loop detected. src=%s, dest=%s, ret=%d",
source_ep.c_str(), dest_ep.c_str(), ret);
return ret;
}
srs_trace("start forward %s to %s, stream: %s/%s",
source_ep.c_str(), dest_ep.c_str(), tc_url.c_str(),
stream_name.c_str());
if ((ret = pthread->start()) != ERROR_SUCCESS) {
srs_error("start srs thread failed. ret=%d", ret);
return ret;
}
return ret;
}
void SrsForwarder::on_unpublish()
{
pthread->stop();
close_underlayer_socket();
srs_freep(client);
}
int SrsForwarder::on_meta_data(SrsSharedPtrMessage* metadata)
{
int ret = ERROR_SUCCESS;
msgs.push_back(metadata);
return ret;
}
int SrsForwarder::on_audio(SrsSharedPtrMessage* msg)
{
int ret = ERROR_SUCCESS;
// TODO: FIXME: must drop the msgs when server failed.
msgs.push_back(msg);
return ret;
}
int SrsForwarder::on_video(SrsSharedPtrMessage* msg)
{
int ret = ERROR_SUCCESS;
// TODO: FIXME: must drop the msgs when server failed.
msgs.push_back(msg);
return ret;
}
int SrsForwarder::cycle()
{
int ret = ERROR_SUCCESS;
if ((ret = connect_server()) != ERROR_SUCCESS) {
return ret;
}
srs_assert(client);
client->set_recv_timeout(SRS_RECV_TIMEOUT_US);
client->set_send_timeout(SRS_SEND_TIMEOUT_US);
if ((ret = client->handshake()) != ERROR_SUCCESS) {
srs_error("handshake with server failed. ret=%d", ret);
return ret;
}
if ((ret = client->connect_app(app, tc_url)) != ERROR_SUCCESS) {
srs_error("connect with server failed, tcUrl=%s. ret=%d", tc_url.c_str(), ret);
return ret;
}
if ((ret = client->create_stream(stream_id)) != ERROR_SUCCESS) {
srs_error("connect with server failed, stream_id=%d. ret=%d", stream_id, ret);
return ret;
}
// TODO: FIXME: need to cache the metadata and sequence header when reconnect.
if ((ret = client->publish(stream_name, stream_id)) != ERROR_SUCCESS) {
srs_error("connect with server failed, stream_name=%s, stream_id=%d. ret=%d",
stream_name.c_str(), stream_id, ret);
return ret;
}
if ((ret = forward()) != ERROR_SUCCESS) {
return ret;
}
return ret;
}
void SrsForwarder::close_underlayer_socket()
{
srs_close_stfd(stfd);
}
int SrsForwarder::connect_server()
{
int ret = ERROR_SUCCESS;
// reopen
close_underlayer_socket();
// open socket.
srs_trace("forward stream=%s, tcUrl=%s to server=%s, port=%d",
stream_name.c_str(), tc_url.c_str(), server.c_str(), port);
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == -1){
ret = ERROR_SOCKET_CREATE;
srs_error("create socket error. ret=%d", ret);
return ret;
}
srs_assert(!stfd);
stfd = st_netfd_open_socket(sock);
if(stfd == NULL){
ret = ERROR_ST_OPEN_SOCKET;
srs_error("st_netfd_open_socket failed. ret=%d", ret);
return ret;
}
srs_freep(client);
client = new SrsRtmpClient(stfd);
// connect to server.
std::string ip = srs_dns_resolve(server);
if (ip.empty()) {
ret = ERROR_SYSTEM_IP_INVALID;
srs_error("dns resolve server error, ip empty. ret=%d", ret);
return ret;
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip.c_str());
if (st_connect(stfd, (const struct sockaddr*)&addr, sizeof(sockaddr_in), ST_UTIME_NO_TIMEOUT) == -1){
ret = ERROR_ST_CONNECT;
srs_error("connect to server error. ip=%s, port=%d, ret=%d", ip.c_str(), port, ret);
return ret;
}
srs_trace("connect to server success. server=%s, ip=%s, port=%d", server.c_str(), ip.c_str(), port);
return ret;
}
int SrsForwarder::forward()
{
int ret = ERROR_SUCCESS;
client->set_recv_timeout(SRS_PULSE_TIMEOUT_MS * 1000);
SrsPithyPrint pithy_print(SRS_STAGE_FORWARDER);
while (true) {
// switch to other st-threads.
st_usleep(0);
// read from client.
if (true) {
SrsCommonMessage* msg = NULL;
ret = client->recv_message(&msg);
srs_verbose("play loop recv message. ret=%d", ret);
if (ret != ERROR_SUCCESS && ret != ERROR_SOCKET_TIMEOUT) {
srs_error("recv server control message failed. ret=%d", ret);
return ret;
}
}
// ignore when no messages.
int count = (int)msgs.size();
if (msgs.empty()) {
continue;
}
// pithy print
pithy_print.elapse(SRS_PULSE_TIMEOUT_MS);
if (pithy_print.can_print()) {
srs_trace("-> time=%"PRId64", msgs=%d, obytes=%"PRId64", ibytes=%"PRId64", okbps=%d, ikbps=%d",
pithy_print.get_age(), count, client->get_send_bytes(), client->get_recv_bytes(), client->get_send_kbps(), client->get_recv_kbps());
}
// all msgs to forward.
int i = 0;
for (i = 0; i < count; i++) {
SrsSharedPtrMessage* msg = msgs[i];
msgs[i] = NULL;
// we erased the sendout messages, the msg must not be NULL.
srs_assert(msg);
ret = client->send_message(msg);
if (ret != ERROR_SUCCESS) {
srs_error("forwarder send message to server failed. ret=%d", ret);
// convert the index to count when error.
i++;
break;
}
}
// clear sendout mesages.
if (i < count) {
srs_warn("clear forwarded msg, total=%d, forwarded=%d, ret=%d", count, i, ret);
} else {
srs_info("clear forwarded msg, total=%d, forwarded=%d, ret=%d", count, i, ret);
}
msgs.erase(msgs.begin(), msgs.begin() + i);
if (ret != ERROR_SUCCESS) {
break;
}
}
return ret;
}
... ...
... ... @@ -32,7 +32,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <string>
#include <vector>
#include <st.h>
#include <srs_core_thread.hpp>
class SrsSharedPtrMessage;
class SrsOnMetaDataPacket;
... ... @@ -42,7 +42,7 @@ class SrsRequest;
/**
* forward the stream to other servers.
*/
class SrsForwarder
class SrsForwarder : public ISrsThreadHandler
{
private:
std::string app;
... ... @@ -53,8 +53,7 @@ private:
int port;
private:
st_netfd_t stfd;
st_thread_t tid;
bool loop;
SrsThread* pthread;
private:
SrsRtmpClient* client;
std::vector<SrsSharedPtrMessage*> msgs;
... ... @@ -67,14 +66,13 @@ public:
virtual int on_meta_data(SrsSharedPtrMessage* metadata);
virtual int on_audio(SrsSharedPtrMessage* msg);
virtual int on_video(SrsSharedPtrMessage* msg);
// interface ISrsThreadHandler.
public:
virtual int cycle();
private:
virtual int open_socket();
virtual void close_underlayer_socket();
virtual int connect_server();
private:
virtual int cycle();
virtual int forward();
virtual void forward_cycle();
static void* forward_thread(void* arg);
};
#endif
... ...
... ... @@ -184,15 +184,7 @@ void SrsHttpClient::disconnect()
{
connected = false;
if (stfd) {
int fd = st_netfd_fileno(stfd);
st_netfd_close(stfd);
stfd = NULL;
// st does not close it sometimes,
// close it manually.
::close(fd);
}
srs_close_stfd(stfd);
}
int SrsHttpClient::connect(SrsHttpUri* uri)
... ...
... ... @@ -36,7 +36,6 @@ class SrsSocket;
#include <string>
#include <st.h>
#include <http_parser.h>
#define SRS_HTTP_HEADER_BUFFER 1024
... ...
... ... @@ -29,8 +29,6 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <string>
#include <map>
#include <st.h>
ILogContext::ILogContext()
{
}
... ...
... ... @@ -33,8 +33,6 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <map>
#include <string>
#include <st.h>
#include <srs_core_log.hpp>
#include <srs_core_error.hpp>
... ...
/*
The MIT License (MIT)
Copyright (c) 2013 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <srs_core_rtmp.hpp>
#include <srs_core_log.hpp>
#include <srs_core_error.hpp>
#include <srs_core_socket.hpp>
#include <srs_core_protocol.hpp>
#include <srs_core_autofree.hpp>
#include <srs_core_amf0.hpp>
#include <srs_core_handshake.hpp>
#include <srs_core_config.hpp>
/**
* the signature for packets to client.
*/
#define RTMP_SIG_FMS_VER "3,5,3,888"
#define RTMP_SIG_AMF0_VER 0
#define RTMP_SIG_CLIENT_ID "ASAICiss"
/**
* onStatus consts.
*/
#define StatusLevel "level"
#define StatusCode "code"
#define StatusDescription "description"
#define StatusDetails "details"
#define StatusClientId "clientid"
// status value
#define StatusLevelStatus "status"
// code value
#define StatusCodeConnectSuccess "NetConnection.Connect.Success"
#define StatusCodeStreamReset "NetStream.Play.Reset"
#define StatusCodeStreamStart "NetStream.Play.Start"
#define StatusCodeStreamPause "NetStream.Pause.Notify"
#define StatusCodeStreamUnpause "NetStream.Unpause.Notify"
#define StatusCodePublishStart "NetStream.Publish.Start"
#define StatusCodeDataStart "NetStream.Data.Start"
#define StatusCodeUnpublishSuccess "NetStream.Unpublish.Success"
// FMLE
#define RTMP_AMF0_COMMAND_ON_FC_PUBLISH "onFCPublish"
#define RTMP_AMF0_COMMAND_ON_FC_UNPUBLISH "onFCUnpublish"
// default stream id for response the createStream request.
#define SRS_DEFAULT_SID 1
SrsRequest::SrsRequest()
{
objectEncoding = RTMP_SIG_AMF0_VER;
}
SrsRequest::~SrsRequest()
{
}
int SrsRequest::discovery_app()
{
int ret = ERROR_SUCCESS;
size_t pos = std::string::npos;
std::string url = tcUrl;
if ((pos = url.find("://")) != std::string::npos) {
schema = url.substr(0, pos);
url = url.substr(schema.length() + 3);
srs_verbose("discovery schema=%s", schema.c_str());
}
if ((pos = url.find("/")) != std::string::npos) {
vhost = url.substr(0, pos);
url = url.substr(vhost.length() + 1);
srs_verbose("discovery vhost=%s", vhost.c_str());
}
port = RTMP_DEFAULT_PORTS;
if ((pos = vhost.find(":")) != std::string::npos) {
port = vhost.substr(pos + 1);
vhost = vhost.substr(0, pos);
srs_verbose("discovery vhost=%s, port=%s", vhost.c_str(), port.c_str());
}
app = url;
srs_vhost_resolve(vhost, app);
// resolve the vhost from config
SrsConfDirective* parsed_vhost = config->get_vhost(vhost);
if (parsed_vhost) {
vhost = parsed_vhost->arg0();
}
// TODO: discovery the params of vhost.
srs_info("discovery app success. schema=%s, vhost=%s, port=%s, app=%s",
schema.c_str(), vhost.c_str(), port.c_str(), app.c_str());
if (schema.empty() || vhost.empty() || port.empty() || app.empty()) {
ret = ERROR_RTMP_REQ_TCURL;
srs_error("discovery tcUrl failed. "
"tcUrl=%s, schema=%s, vhost=%s, port=%s, app=%s, ret=%d",
tcUrl.c_str(), schema.c_str(), vhost.c_str(), port.c_str(), app.c_str(), ret);
return ret;
}
strip();
return ret;
}
std::string SrsRequest::get_stream_url()
{
std::string url = "";
url += vhost;
url += "/";
url += app;
url += "/";
url += stream;
return url;
}
void SrsRequest::strip()
{
trim(vhost, "/ \n\r\t");
trim(app, "/ \n\r\t");
trim(stream, "/ \n\r\t");
}
std::string& SrsRequest::trim(std::string& str, std::string chs)
{
for (int i = 0; i < (int)chs.length(); i++) {
char ch = chs.at(i);
for (std::string::iterator it = str.begin(); it != str.end();) {
if (ch == *it) {
it = str.erase(it);
} else {
++it;
}
}
}
return str;
}
SrsResponse::SrsResponse()
{
stream_id = SRS_DEFAULT_SID;
}
SrsResponse::~SrsResponse()
{
}
SrsRtmpClient::SrsRtmpClient(st_netfd_t _stfd)
{
stfd = _stfd;
protocol = new SrsProtocol(stfd);
}
SrsRtmpClient::~SrsRtmpClient()
{
srs_freep(protocol);
}
void SrsRtmpClient::set_recv_timeout(int64_t timeout_us)
{
protocol->set_recv_timeout(timeout_us);
}
void SrsRtmpClient::set_send_timeout(int64_t timeout_us)
{
protocol->set_send_timeout(timeout_us);
}
int64_t SrsRtmpClient::get_recv_bytes()
{
return protocol->get_recv_bytes();
}
int64_t SrsRtmpClient::get_send_bytes()
{
return protocol->get_send_bytes();
}
int SrsRtmpClient::get_recv_kbps()
{
return protocol->get_recv_kbps();
}
int SrsRtmpClient::get_send_kbps()
{
return protocol->get_send_kbps();
}
int SrsRtmpClient::recv_message(SrsCommonMessage** pmsg)
{
return protocol->recv_message(pmsg);
}
int SrsRtmpClient::send_message(ISrsMessage* msg)
{
return protocol->send_message(msg);
}
int SrsRtmpClient::handshake()
{
int ret = ERROR_SUCCESS;
SrsSocket skt(stfd);
SrsComplexHandshake complex_hs;
SrsSimpleHandshake simple_hs;
if ((ret = simple_hs.handshake_with_server(skt, complex_hs)) != ERROR_SUCCESS) {
return ret;
}
return ret;
}
int SrsRtmpClient::connect_app(std::string app, std::string tc_url)
{
int ret = ERROR_SUCCESS;
// Connect(vhost, app)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsConnectAppPacket* pkt = new SrsConnectAppPacket();
msg->set_packet(pkt, 0);
pkt->command_object = new SrsAmf0Object();
pkt->command_object->set("app", new SrsAmf0String(app.c_str()));
pkt->command_object->set("swfUrl", new SrsAmf0String());
pkt->command_object->set("tcUrl", new SrsAmf0String(tc_url.c_str()));
pkt->command_object->set("fpad", new SrsAmf0Boolean(false));
pkt->command_object->set("capabilities", new SrsAmf0Number(239));
pkt->command_object->set("audioCodecs", new SrsAmf0Number(3575));
pkt->command_object->set("videoCodecs", new SrsAmf0Number(252));
pkt->command_object->set("videoFunction", new SrsAmf0Number(1));
pkt->command_object->set("pageUrl", new SrsAmf0String());
pkt->command_object->set("objectEncoding", new SrsAmf0Number(0));
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
return ret;
}
}
// Set Window Acknowledgement size(2500000)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsSetWindowAckSizePacket* pkt = new SrsSetWindowAckSizePacket();
pkt->ackowledgement_window_size = 2500000;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
return ret;
}
}
// expect connect _result
SrsCommonMessage* msg = NULL;
SrsConnectAppResPacket* pkt = NULL;
if ((ret = srs_rtmp_expect_message<SrsConnectAppResPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
srs_error("expect connect app response message failed. ret=%d", ret);
return ret;
}
SrsAutoFree(SrsCommonMessage, msg, false);
srs_info("get connect app response message");
return ret;
}
int SrsRtmpClient::create_stream(int& stream_id)
{
int ret = ERROR_SUCCESS;
// CreateStream
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsCreateStreamPacket* pkt = new SrsCreateStreamPacket();
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
return ret;
}
}
// CreateStream _result.
if (true) {
SrsCommonMessage* msg = NULL;
SrsCreateStreamResPacket* pkt = NULL;
if ((ret = srs_rtmp_expect_message<SrsCreateStreamResPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
srs_error("expect create stream response message failed. ret=%d", ret);
return ret;
}
SrsAutoFree(SrsCommonMessage, msg, false);
srs_info("get create stream response message");
stream_id = (int)pkt->stream_id;
}
return ret;
}
int SrsRtmpClient::play(std::string stream, int stream_id)
{
int ret = ERROR_SUCCESS;
// Play(stream)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsPlayPacket* pkt = new SrsPlayPacket();
pkt->stream_name = stream;
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send play stream failed. "
"stream=%s, stream_id=%d, ret=%d",
stream.c_str(), stream_id, ret);
return ret;
}
}
// SetBufferLength(1000ms)
int buffer_length_ms = 1000;
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsUserControlPacket* pkt = new SrsUserControlPacket();
pkt->event_type = SrcPCUCSetBufferLength;
pkt->event_data = stream_id;
pkt->extra_data = buffer_length_ms;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send set buffer length failed. "
"stream=%s, stream_id=%d, bufferLength=%d, ret=%d",
stream.c_str(), stream_id, buffer_length_ms, ret);
return ret;
}
}
return ret;
}
int SrsRtmpClient::publish(std::string stream, int stream_id)
{
int ret = ERROR_SUCCESS;
// publish(stream)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsPublishPacket* pkt = new SrsPublishPacket();
pkt->stream_name = stream;
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send publish message failed. "
"stream=%s, stream_id=%d, ret=%d",
stream.c_str(), stream_id, ret);
return ret;
}
}
return ret;
}
SrsRtmp::SrsRtmp(st_netfd_t client_stfd)
{
protocol = new SrsProtocol(client_stfd);
stfd = client_stfd;
}
SrsRtmp::~SrsRtmp()
{
srs_freep(protocol);
}
SrsProtocol* SrsRtmp::get_protocol()
{
return protocol;
}
void SrsRtmp::set_recv_timeout(int64_t timeout_us)
{
protocol->set_recv_timeout(timeout_us);
}
int64_t SrsRtmp::get_recv_timeout()
{
return protocol->get_recv_timeout();
}
void SrsRtmp::set_send_timeout(int64_t timeout_us)
{
protocol->set_send_timeout(timeout_us);
}
int64_t SrsRtmp::get_recv_bytes()
{
return protocol->get_recv_bytes();
}
int64_t SrsRtmp::get_send_bytes()
{
return protocol->get_send_bytes();
}
int SrsRtmp::get_recv_kbps()
{
return protocol->get_recv_kbps();
}
int SrsRtmp::get_send_kbps()
{
return protocol->get_send_kbps();
}
int SrsRtmp::recv_message(SrsCommonMessage** pmsg)
{
return protocol->recv_message(pmsg);
}
int SrsRtmp::send_message(ISrsMessage* msg)
{
return protocol->send_message(msg);
}
int SrsRtmp::handshake()
{
int ret = ERROR_SUCCESS;
SrsSocket skt(stfd);
SrsComplexHandshake complex_hs;
SrsSimpleHandshake simple_hs;
if ((ret = simple_hs.handshake_with_client(skt, complex_hs)) != ERROR_SUCCESS) {
return ret;
}
return ret;
}
int SrsRtmp::connect_app(SrsRequest* req)
{
int ret = ERROR_SUCCESS;
SrsCommonMessage* msg = NULL;
SrsConnectAppPacket* pkt = NULL;
if ((ret = srs_rtmp_expect_message<SrsConnectAppPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
srs_error("expect connect app message failed. ret=%d", ret);
return ret;
}
SrsAutoFree(SrsCommonMessage, msg, false);
srs_info("get connect app message");
SrsAmf0Any* prop = NULL;
if ((prop = pkt->command_object->ensure_property_string("tcUrl")) == NULL) {
ret = ERROR_RTMP_REQ_CONNECT;
srs_error("invalid request, must specifies the tcUrl. ret=%d", ret);
return ret;
}
req->tcUrl = srs_amf0_convert<SrsAmf0String>(prop)->value;
if ((prop = pkt->command_object->ensure_property_string("pageUrl")) != NULL) {
req->pageUrl = srs_amf0_convert<SrsAmf0String>(prop)->value;
}
if ((prop = pkt->command_object->ensure_property_string("swfUrl")) != NULL) {
req->swfUrl = srs_amf0_convert<SrsAmf0String>(prop)->value;
}
if ((prop = pkt->command_object->ensure_property_number("objectEncoding")) != NULL) {
req->objectEncoding = srs_amf0_convert<SrsAmf0Number>(prop)->value;
}
srs_info("get connect app message params success.");
return req->discovery_app();
}
int SrsRtmp::set_window_ack_size(int ack_size)
{
int ret = ERROR_SUCCESS;
SrsCommonMessage* msg = new SrsCommonMessage();
SrsSetWindowAckSizePacket* pkt = new SrsSetWindowAckSizePacket();
pkt->ackowledgement_window_size = ack_size;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send ack size message failed. ret=%d", ret);
return ret;
}
srs_info("send ack size message success. ack_size=%d", ack_size);
return ret;
}
int SrsRtmp::set_peer_bandwidth(int bandwidth, int type)
{
int ret = ERROR_SUCCESS;
SrsCommonMessage* msg = new SrsCommonMessage();
SrsSetPeerBandwidthPacket* pkt = new SrsSetPeerBandwidthPacket();
pkt->bandwidth = bandwidth;
pkt->type = type;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send set bandwidth message failed. ret=%d", ret);
return ret;
}
srs_info("send set bandwidth message "
"success. bandwidth=%d, type=%d", bandwidth, type);
return ret;
}
int SrsRtmp::response_connect_app(SrsRequest* req)
{
int ret = ERROR_SUCCESS;
SrsCommonMessage* msg = new SrsCommonMessage();
SrsConnectAppResPacket* pkt = new SrsConnectAppResPacket();
pkt->props->set("fmsVer", new SrsAmf0String("FMS/"RTMP_SIG_FMS_VER));
pkt->props->set("capabilities", new SrsAmf0Number(127));
pkt->props->set("mode", new SrsAmf0Number(1));
pkt->info->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->info->set(StatusCode, new SrsAmf0String(StatusCodeConnectSuccess));
pkt->info->set(StatusDescription, new SrsAmf0String("Connection succeeded"));
pkt->info->set("objectEncoding", new SrsAmf0Number(req->objectEncoding));
SrsASrsAmf0EcmaArray* data = new SrsASrsAmf0EcmaArray();
pkt->info->set("data", data);
data->set("srs_version", new SrsAmf0String(RTMP_SIG_FMS_VER));
data->set("srs_server", new SrsAmf0String(RTMP_SIG_SRS_NAME));
data->set("srs_license", new SrsAmf0String(RTMP_SIG_SRS_LICENSE));
data->set("srs_role", new SrsAmf0String(RTMP_SIG_SRS_ROLE));
data->set("srs_url", new SrsAmf0String(RTMP_SIG_SRS_URL));
data->set("srs_version", new SrsAmf0String(RTMP_SIG_SRS_VERSION));
data->set("srs_site", new SrsAmf0String(RTMP_SIG_SRS_WEB));
data->set("srs_email", new SrsAmf0String(RTMP_SIG_SRS_EMAIL));
data->set("srs_copyright", new SrsAmf0String(RTMP_SIG_SRS_COPYRIGHT));
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send connect app response message failed. ret=%d", ret);
return ret;
}
srs_info("send connect app response message success.");
return ret;
}
int SrsRtmp::on_bw_done()
{
int ret = ERROR_SUCCESS;
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnBWDonePacket* pkt = new SrsOnBWDonePacket();
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onBWDone message failed. ret=%d", ret);
return ret;
}
srs_info("send onBWDone message success.");
return ret;
}
int SrsRtmp::identify_client(int stream_id, SrsClientType& type, std::string& stream_name)
{
type = SrsClientUnknown;
int ret = ERROR_SUCCESS;
while (true) {
SrsCommonMessage* msg = NULL;
if ((ret = protocol->recv_message(&msg)) != ERROR_SUCCESS) {
srs_error("recv identify client message failed. ret=%d", ret);
return ret;
}
SrsAutoFree(SrsCommonMessage, msg, false);
if (!msg->header.is_amf0_command() && !msg->header.is_amf3_command()) {
srs_trace("identify ignore messages except "
"AMF0/AMF3 command message. type=%#x", msg->header.message_type);
continue;
}
if ((ret = msg->decode_packet(protocol)) != ERROR_SUCCESS) {
srs_error("identify decode message failed. ret=%d", ret);
return ret;
}
SrsPacket* pkt = msg->get_packet();
if (dynamic_cast<SrsCreateStreamPacket*>(pkt)) {
srs_info("identify client by create stream, play or flash publish.");
return identify_create_stream_client(
dynamic_cast<SrsCreateStreamPacket*>(pkt), stream_id, type, stream_name);
}
if (dynamic_cast<SrsFMLEStartPacket*>(pkt)) {
srs_info("identify client by releaseStream, fmle publish.");
return identify_fmle_publish_client(
dynamic_cast<SrsFMLEStartPacket*>(pkt), type, stream_name);
}
srs_trace("ignore AMF0/AMF3 command message.");
}
return ret;
}
int SrsRtmp::set_chunk_size(int chunk_size)
{
int ret = ERROR_SUCCESS;
SrsCommonMessage* msg = new SrsCommonMessage();
SrsSetChunkSizePacket* pkt = new SrsSetChunkSizePacket();
pkt->chunk_size = chunk_size;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send set chunk size message failed. ret=%d", ret);
return ret;
}
srs_info("send set chunk size message success. chunk_size=%d", chunk_size);
return ret;
}
int SrsRtmp::start_play(int stream_id)
{
int ret = ERROR_SUCCESS;
// StreamBegin
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsUserControlPacket* pkt = new SrsUserControlPacket();
pkt->event_type = SrcPCUCStreamBegin;
pkt->event_data = stream_id;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send PCUC(StreamBegin) message failed. ret=%d", ret);
return ret;
}
srs_info("send PCUC(StreamBegin) message success.");
}
// onStatus(NetStream.Play.Reset)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeStreamReset));
pkt->data->set(StatusDescription, new SrsAmf0String("Playing and resetting stream."));
pkt->data->set(StatusDetails, new SrsAmf0String("stream"));
pkt->data->set(StatusClientId, new SrsAmf0String(RTMP_SIG_CLIENT_ID));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Play.Reset) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Play.Reset) message success.");
}
// onStatus(NetStream.Play.Start)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeStreamStart));
pkt->data->set(StatusDescription, new SrsAmf0String("Started playing stream."));
pkt->data->set(StatusDetails, new SrsAmf0String("stream"));
pkt->data->set(StatusClientId, new SrsAmf0String(RTMP_SIG_CLIENT_ID));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Play.Reset) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Play.Reset) message success.");
}
// |RtmpSampleAccess(false, false)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsSampleAccessPacket* pkt = new SrsSampleAccessPacket();
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send |RtmpSampleAccess(false, false) message failed. ret=%d", ret);
return ret;
}
srs_info("send |RtmpSampleAccess(false, false) message success.");
}
// onStatus(NetStream.Data.Start)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusDataPacket* pkt = new SrsOnStatusDataPacket();
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeDataStart));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Data.Start) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Data.Start) message success.");
}
srs_info("start play success.");
return ret;
}
int SrsRtmp::on_play_client_pause(int stream_id, bool is_pause)
{
int ret = ERROR_SUCCESS;
if (is_pause) {
// onStatus(NetStream.Pause.Notify)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeStreamPause));
pkt->data->set(StatusDescription, new SrsAmf0String("Paused stream."));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Pause.Notify) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Pause.Notify) message success.");
}
// StreamEOF
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsUserControlPacket* pkt = new SrsUserControlPacket();
pkt->event_type = SrcPCUCStreamEOF;
pkt->event_data = stream_id;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send PCUC(StreamEOF) message failed. ret=%d", ret);
return ret;
}
srs_info("send PCUC(StreamEOF) message success.");
}
} else {
// onStatus(NetStream.Unpause.Notify)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeStreamUnpause));
pkt->data->set(StatusDescription, new SrsAmf0String("Unpaused stream."));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Unpause.Notify) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Unpause.Notify) message success.");
}
// StreanBegin
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsUserControlPacket* pkt = new SrsUserControlPacket();
pkt->event_type = SrcPCUCStreamBegin;
pkt->event_data = stream_id;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send PCUC(StreanBegin) message failed. ret=%d", ret);
return ret;
}
srs_info("send PCUC(StreanBegin) message success.");
}
}
return ret;
}
int SrsRtmp::start_fmle_publish(int stream_id)
{
int ret = ERROR_SUCCESS;
// FCPublish
double fc_publish_tid = 0;
if (true) {
SrsCommonMessage* msg = NULL;
SrsFMLEStartPacket* pkt = NULL;
if ((ret = srs_rtmp_expect_message<SrsFMLEStartPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
srs_error("recv FCPublish message failed. ret=%d", ret);
return ret;
}
srs_info("recv FCPublish request message success.");
SrsAutoFree(SrsCommonMessage, msg, false);
fc_publish_tid = pkt->transaction_id;
}
// FCPublish response
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsFMLEStartResPacket* pkt = new SrsFMLEStartResPacket(fc_publish_tid);
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send FCPublish response message failed. ret=%d", ret);
return ret;
}
srs_info("send FCPublish response message success.");
}
// createStream
double create_stream_tid = 0;
if (true) {
SrsCommonMessage* msg = NULL;
SrsCreateStreamPacket* pkt = NULL;
if ((ret = srs_rtmp_expect_message<SrsCreateStreamPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
srs_error("recv createStream message failed. ret=%d", ret);
return ret;
}
srs_info("recv createStream request message success.");
SrsAutoFree(SrsCommonMessage, msg, false);
create_stream_tid = pkt->transaction_id;
}
// createStream response
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsCreateStreamResPacket* pkt = new SrsCreateStreamResPacket(create_stream_tid, stream_id);
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send createStream response message failed. ret=%d", ret);
return ret;
}
srs_info("send createStream response message success.");
}
// publish
if (true) {
SrsCommonMessage* msg = NULL;
SrsPublishPacket* pkt = NULL;
if ((ret = srs_rtmp_expect_message<SrsPublishPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
srs_error("recv publish message failed. ret=%d", ret);
return ret;
}
srs_info("recv publish request message success.");
SrsAutoFree(SrsCommonMessage, msg, false);
}
// publish response onFCPublish(NetStream.Publish.Start)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->command_name = RTMP_AMF0_COMMAND_ON_FC_PUBLISH;
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodePublishStart));
pkt->data->set(StatusDescription, new SrsAmf0String("Started publishing stream."));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onFCPublish(NetStream.Publish.Start) message failed. ret=%d", ret);
return ret;
}
srs_info("send onFCPublish(NetStream.Publish.Start) message success.");
}
// publish response onStatus(NetStream.Publish.Start)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodePublishStart));
pkt->data->set(StatusDescription, new SrsAmf0String("Started publishing stream."));
pkt->data->set(StatusClientId, new SrsAmf0String(RTMP_SIG_CLIENT_ID));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Publish.Start) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Publish.Start) message success.");
}
srs_info("FMLE publish success.");
return ret;
}
int SrsRtmp::fmle_unpublish(int stream_id, double unpublish_tid)
{
int ret = ERROR_SUCCESS;
// publish response onFCUnpublish(NetStream.unpublish.Success)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->command_name = RTMP_AMF0_COMMAND_ON_FC_UNPUBLISH;
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeUnpublishSuccess));
pkt->data->set(StatusDescription, new SrsAmf0String("Stop publishing stream."));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onFCUnpublish(NetStream.unpublish.Success) message failed. ret=%d", ret);
return ret;
}
srs_info("send onFCUnpublish(NetStream.unpublish.Success) message success.");
}
// FCUnpublish response
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsFMLEStartResPacket* pkt = new SrsFMLEStartResPacket(unpublish_tid);
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send FCUnpublish response message failed. ret=%d", ret);
return ret;
}
srs_info("send FCUnpublish response message success.");
}
// publish response onStatus(NetStream.Unpublish.Success)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeUnpublishSuccess));
pkt->data->set(StatusDescription, new SrsAmf0String("Stream is now unpublished"));
pkt->data->set(StatusClientId, new SrsAmf0String(RTMP_SIG_CLIENT_ID));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Unpublish.Success) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Unpublish.Success) message success.");
}
srs_info("FMLE unpublish success.");
return ret;
}
int SrsRtmp::start_flash_publish(int stream_id)
{
int ret = ERROR_SUCCESS;
// publish response onStatus(NetStream.Publish.Start)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodePublishStart));
pkt->data->set(StatusDescription, new SrsAmf0String("Started publishing stream."));
pkt->data->set(StatusClientId, new SrsAmf0String(RTMP_SIG_CLIENT_ID));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Publish.Start) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Publish.Start) message success.");
}
srs_info("flash publish success.");
return ret;
}
int SrsRtmp::identify_create_stream_client(SrsCreateStreamPacket* req, int stream_id, SrsClientType& type, std::string& stream_name)
{
int ret = ERROR_SUCCESS;
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsCreateStreamResPacket* pkt = new SrsCreateStreamResPacket(req->transaction_id, stream_id);
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send createStream response message failed. ret=%d", ret);
return ret;
}
srs_info("send createStream response message success.");
}
while (true) {
SrsCommonMessage* msg = NULL;
if ((ret = protocol->recv_message(&msg)) != ERROR_SUCCESS) {
srs_error("recv identify client message failed. ret=%d", ret);
return ret;
}
SrsAutoFree(SrsCommonMessage, msg, false);
if (!msg->header.is_amf0_command() && !msg->header.is_amf3_command()) {
srs_trace("identify ignore messages except "
"AMF0/AMF3 command message. type=%#x", msg->header.message_type);
continue;
}
if ((ret = msg->decode_packet(protocol)) != ERROR_SUCCESS) {
srs_error("identify decode message failed. ret=%d", ret);
return ret;
}
SrsPacket* pkt = msg->get_packet();
if (dynamic_cast<SrsPlayPacket*>(pkt)) {
SrsPlayPacket* play = dynamic_cast<SrsPlayPacket*>(pkt);
type = SrsClientPlay;
stream_name = play->stream_name;
srs_trace("identity client type=play, stream_name=%s", stream_name.c_str());
return ret;
}
if (dynamic_cast<SrsPublishPacket*>(pkt)) {
srs_info("identify client by publish, falsh publish.");
return identify_flash_publish_client(
dynamic_cast<SrsPublishPacket*>(pkt), type, stream_name);
}
srs_trace("ignore AMF0/AMF3 command message.");
}
return ret;
}
int SrsRtmp::identify_fmle_publish_client(SrsFMLEStartPacket* req, SrsClientType& type, std::string& stream_name)
{
int ret = ERROR_SUCCESS;
type = SrsClientFMLEPublish;
stream_name = req->stream_name;
// releaseStream response
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsFMLEStartResPacket* pkt = new SrsFMLEStartResPacket(req->transaction_id);
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send releaseStream response message failed. ret=%d", ret);
return ret;
}
srs_info("send releaseStream response message success.");
}
return ret;
}
int SrsRtmp::identify_flash_publish_client(SrsPublishPacket* req, SrsClientType& type, std::string& stream_name)
{
int ret = ERROR_SUCCESS;
type = SrsClientFlashPublish;
stream_name = req->stream_name;
return ret;
}
/*
The MIT License (MIT)
Copyright (c) 2013 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <srs_core_rtmp.hpp>
#include <srs_core_log.hpp>
#include <srs_core_error.hpp>
#include <srs_core_socket.hpp>
#include <srs_core_protocol.hpp>
#include <srs_core_autofree.hpp>
#include <srs_core_amf0.hpp>
#include <srs_core_handshake.hpp>
#include <srs_core_config.hpp>
/**
* the signature for packets to client.
*/
#define RTMP_SIG_FMS_VER "3,5,3,888"
#define RTMP_SIG_AMF0_VER 0
#define RTMP_SIG_CLIENT_ID "ASAICiss"
/**
* onStatus consts.
*/
#define StatusLevel "level"
#define StatusCode "code"
#define StatusDescription "description"
#define StatusDetails "details"
#define StatusClientId "clientid"
// status value
#define StatusLevelStatus "status"
// code value
#define StatusCodeConnectSuccess "NetConnection.Connect.Success"
#define StatusCodeStreamReset "NetStream.Play.Reset"
#define StatusCodeStreamStart "NetStream.Play.Start"
#define StatusCodeStreamPause "NetStream.Pause.Notify"
#define StatusCodeStreamUnpause "NetStream.Unpause.Notify"
#define StatusCodePublishStart "NetStream.Publish.Start"
#define StatusCodeDataStart "NetStream.Data.Start"
#define StatusCodeUnpublishSuccess "NetStream.Unpublish.Success"
// FMLE
#define RTMP_AMF0_COMMAND_ON_FC_PUBLISH "onFCPublish"
#define RTMP_AMF0_COMMAND_ON_FC_UNPUBLISH "onFCUnpublish"
// default stream id for response the createStream request.
#define SRS_DEFAULT_SID 1
SrsRequest::SrsRequest()
{
objectEncoding = RTMP_SIG_AMF0_VER;
}
SrsRequest::~SrsRequest()
{
}
int SrsRequest::discovery_app()
{
int ret = ERROR_SUCCESS;
size_t pos = std::string::npos;
std::string url = tcUrl;
if ((pos = url.find("://")) != std::string::npos) {
schema = url.substr(0, pos);
url = url.substr(schema.length() + 3);
srs_verbose("discovery schema=%s", schema.c_str());
}
if ((pos = url.find("/")) != std::string::npos) {
vhost = url.substr(0, pos);
url = url.substr(vhost.length() + 1);
srs_verbose("discovery vhost=%s", vhost.c_str());
}
port = RTMP_DEFAULT_PORTS;
if ((pos = vhost.find(":")) != std::string::npos) {
port = vhost.substr(pos + 1);
vhost = vhost.substr(0, pos);
srs_verbose("discovery vhost=%s, port=%s", vhost.c_str(), port.c_str());
}
app = url;
srs_vhost_resolve(vhost, app);
// resolve the vhost from config
SrsConfDirective* parsed_vhost = config->get_vhost(vhost);
if (parsed_vhost) {
vhost = parsed_vhost->arg0();
}
// TODO: discovery the params of vhost.
srs_info("discovery app success. schema=%s, vhost=%s, port=%s, app=%s",
schema.c_str(), vhost.c_str(), port.c_str(), app.c_str());
if (schema.empty() || vhost.empty() || port.empty() || app.empty()) {
ret = ERROR_RTMP_REQ_TCURL;
srs_error("discovery tcUrl failed. "
"tcUrl=%s, schema=%s, vhost=%s, port=%s, app=%s, ret=%d",
tcUrl.c_str(), schema.c_str(), vhost.c_str(), port.c_str(), app.c_str(), ret);
return ret;
}
strip();
return ret;
}
std::string SrsRequest::get_stream_url()
{
std::string url = "";
url += vhost;
url += "/";
url += app;
url += "/";
url += stream;
return url;
}
void SrsRequest::strip()
{
trim(vhost, "/ \n\r\t");
trim(app, "/ \n\r\t");
trim(stream, "/ \n\r\t");
}
std::string& SrsRequest::trim(std::string& str, std::string chs)
{
for (int i = 0; i < (int)chs.length(); i++) {
char ch = chs.at(i);
for (std::string::iterator it = str.begin(); it != str.end();) {
if (ch == *it) {
it = str.erase(it);
} else {
++it;
}
}
}
return str;
}
SrsResponse::SrsResponse()
{
stream_id = SRS_DEFAULT_SID;
}
SrsResponse::~SrsResponse()
{
}
SrsRtmpClient::SrsRtmpClient(st_netfd_t _stfd)
{
stfd = _stfd;
protocol = new SrsProtocol(stfd);
}
SrsRtmpClient::~SrsRtmpClient()
{
srs_freep(protocol);
}
void SrsRtmpClient::set_recv_timeout(int64_t timeout_us)
{
protocol->set_recv_timeout(timeout_us);
}
void SrsRtmpClient::set_send_timeout(int64_t timeout_us)
{
protocol->set_send_timeout(timeout_us);
}
int64_t SrsRtmpClient::get_recv_bytes()
{
return protocol->get_recv_bytes();
}
int64_t SrsRtmpClient::get_send_bytes()
{
return protocol->get_send_bytes();
}
int SrsRtmpClient::get_recv_kbps()
{
return protocol->get_recv_kbps();
}
int SrsRtmpClient::get_send_kbps()
{
return protocol->get_send_kbps();
}
int SrsRtmpClient::recv_message(SrsCommonMessage** pmsg)
{
return protocol->recv_message(pmsg);
}
int SrsRtmpClient::send_message(ISrsMessage* msg)
{
return protocol->send_message(msg);
}
int SrsRtmpClient::handshake()
{
int ret = ERROR_SUCCESS;
SrsSocket skt(stfd);
SrsComplexHandshake complex_hs;
SrsSimpleHandshake simple_hs;
if ((ret = simple_hs.handshake_with_server(skt, complex_hs)) != ERROR_SUCCESS) {
return ret;
}
return ret;
}
int SrsRtmpClient::connect_app(std::string app, std::string tc_url)
{
int ret = ERROR_SUCCESS;
// Connect(vhost, app)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsConnectAppPacket* pkt = new SrsConnectAppPacket();
msg->set_packet(pkt, 0);
pkt->command_object = new SrsAmf0Object();
pkt->command_object->set("app", new SrsAmf0String(app.c_str()));
pkt->command_object->set("swfUrl", new SrsAmf0String());
pkt->command_object->set("tcUrl", new SrsAmf0String(tc_url.c_str()));
pkt->command_object->set("fpad", new SrsAmf0Boolean(false));
pkt->command_object->set("capabilities", new SrsAmf0Number(239));
pkt->command_object->set("audioCodecs", new SrsAmf0Number(3575));
pkt->command_object->set("videoCodecs", new SrsAmf0Number(252));
pkt->command_object->set("videoFunction", new SrsAmf0Number(1));
pkt->command_object->set("pageUrl", new SrsAmf0String());
pkt->command_object->set("objectEncoding", new SrsAmf0Number(0));
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
return ret;
}
}
// Set Window Acknowledgement size(2500000)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsSetWindowAckSizePacket* pkt = new SrsSetWindowAckSizePacket();
pkt->ackowledgement_window_size = 2500000;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
return ret;
}
}
// expect connect _result
SrsCommonMessage* msg = NULL;
SrsConnectAppResPacket* pkt = NULL;
if ((ret = srs_rtmp_expect_message<SrsConnectAppResPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
srs_error("expect connect app response message failed. ret=%d", ret);
return ret;
}
SrsAutoFree(SrsCommonMessage, msg, false);
srs_info("get connect app response message");
return ret;
}
int SrsRtmpClient::create_stream(int& stream_id)
{
int ret = ERROR_SUCCESS;
// CreateStream
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsCreateStreamPacket* pkt = new SrsCreateStreamPacket();
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
return ret;
}
}
// CreateStream _result.
if (true) {
SrsCommonMessage* msg = NULL;
SrsCreateStreamResPacket* pkt = NULL;
if ((ret = srs_rtmp_expect_message<SrsCreateStreamResPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
srs_error("expect create stream response message failed. ret=%d", ret);
return ret;
}
SrsAutoFree(SrsCommonMessage, msg, false);
srs_info("get create stream response message");
stream_id = (int)pkt->stream_id;
}
return ret;
}
int SrsRtmpClient::play(std::string stream, int stream_id)
{
int ret = ERROR_SUCCESS;
// Play(stream)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsPlayPacket* pkt = new SrsPlayPacket();
pkt->stream_name = stream;
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send play stream failed. "
"stream=%s, stream_id=%d, ret=%d",
stream.c_str(), stream_id, ret);
return ret;
}
}
// SetBufferLength(1000ms)
int buffer_length_ms = 1000;
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsUserControlPacket* pkt = new SrsUserControlPacket();
pkt->event_type = SrcPCUCSetBufferLength;
pkt->event_data = stream_id;
pkt->extra_data = buffer_length_ms;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send set buffer length failed. "
"stream=%s, stream_id=%d, bufferLength=%d, ret=%d",
stream.c_str(), stream_id, buffer_length_ms, ret);
return ret;
}
}
return ret;
}
int SrsRtmpClient::publish(std::string stream, int stream_id)
{
int ret = ERROR_SUCCESS;
// publish(stream)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsPublishPacket* pkt = new SrsPublishPacket();
pkt->stream_name = stream;
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send publish message failed. "
"stream=%s, stream_id=%d, ret=%d",
stream.c_str(), stream_id, ret);
return ret;
}
}
return ret;
}
SrsRtmp::SrsRtmp(st_netfd_t client_stfd)
{
protocol = new SrsProtocol(client_stfd);
stfd = client_stfd;
}
SrsRtmp::~SrsRtmp()
{
srs_freep(protocol);
}
SrsProtocol* SrsRtmp::get_protocol()
{
return protocol;
}
void SrsRtmp::set_recv_timeout(int64_t timeout_us)
{
protocol->set_recv_timeout(timeout_us);
}
int64_t SrsRtmp::get_recv_timeout()
{
return protocol->get_recv_timeout();
}
void SrsRtmp::set_send_timeout(int64_t timeout_us)
{
protocol->set_send_timeout(timeout_us);
}
int64_t SrsRtmp::get_recv_bytes()
{
return protocol->get_recv_bytes();
}
int64_t SrsRtmp::get_send_bytes()
{
return protocol->get_send_bytes();
}
int SrsRtmp::get_recv_kbps()
{
return protocol->get_recv_kbps();
}
int SrsRtmp::get_send_kbps()
{
return protocol->get_send_kbps();
}
int SrsRtmp::recv_message(SrsCommonMessage** pmsg)
{
return protocol->recv_message(pmsg);
}
int SrsRtmp::send_message(ISrsMessage* msg)
{
return protocol->send_message(msg);
}
int SrsRtmp::handshake()
{
int ret = ERROR_SUCCESS;
SrsSocket skt(stfd);
SrsComplexHandshake complex_hs;
SrsSimpleHandshake simple_hs;
if ((ret = simple_hs.handshake_with_client(skt, complex_hs)) != ERROR_SUCCESS) {
return ret;
}
return ret;
}
int SrsRtmp::connect_app(SrsRequest* req)
{
int ret = ERROR_SUCCESS;
SrsCommonMessage* msg = NULL;
SrsConnectAppPacket* pkt = NULL;
if ((ret = srs_rtmp_expect_message<SrsConnectAppPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
srs_error("expect connect app message failed. ret=%d", ret);
return ret;
}
SrsAutoFree(SrsCommonMessage, msg, false);
srs_info("get connect app message");
SrsAmf0Any* prop = NULL;
if ((prop = pkt->command_object->ensure_property_string("tcUrl")) == NULL) {
ret = ERROR_RTMP_REQ_CONNECT;
srs_error("invalid request, must specifies the tcUrl. ret=%d", ret);
return ret;
}
req->tcUrl = srs_amf0_convert<SrsAmf0String>(prop)->value;
if ((prop = pkt->command_object->ensure_property_string("pageUrl")) != NULL) {
req->pageUrl = srs_amf0_convert<SrsAmf0String>(prop)->value;
}
if ((prop = pkt->command_object->ensure_property_string("swfUrl")) != NULL) {
req->swfUrl = srs_amf0_convert<SrsAmf0String>(prop)->value;
}
if ((prop = pkt->command_object->ensure_property_number("objectEncoding")) != NULL) {
req->objectEncoding = srs_amf0_convert<SrsAmf0Number>(prop)->value;
}
srs_info("get connect app message params success.");
return req->discovery_app();
}
int SrsRtmp::set_window_ack_size(int ack_size)
{
int ret = ERROR_SUCCESS;
SrsCommonMessage* msg = new SrsCommonMessage();
SrsSetWindowAckSizePacket* pkt = new SrsSetWindowAckSizePacket();
pkt->ackowledgement_window_size = ack_size;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send ack size message failed. ret=%d", ret);
return ret;
}
srs_info("send ack size message success. ack_size=%d", ack_size);
return ret;
}
int SrsRtmp::set_peer_bandwidth(int bandwidth, int type)
{
int ret = ERROR_SUCCESS;
SrsCommonMessage* msg = new SrsCommonMessage();
SrsSetPeerBandwidthPacket* pkt = new SrsSetPeerBandwidthPacket();
pkt->bandwidth = bandwidth;
pkt->type = type;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send set bandwidth message failed. ret=%d", ret);
return ret;
}
srs_info("send set bandwidth message "
"success. bandwidth=%d, type=%d", bandwidth, type);
return ret;
}
int SrsRtmp::response_connect_app(SrsRequest* req)
{
int ret = ERROR_SUCCESS;
SrsCommonMessage* msg = new SrsCommonMessage();
SrsConnectAppResPacket* pkt = new SrsConnectAppResPacket();
pkt->props->set("fmsVer", new SrsAmf0String("FMS/"RTMP_SIG_FMS_VER));
pkt->props->set("capabilities", new SrsAmf0Number(127));
pkt->props->set("mode", new SrsAmf0Number(1));
pkt->info->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->info->set(StatusCode, new SrsAmf0String(StatusCodeConnectSuccess));
pkt->info->set(StatusDescription, new SrsAmf0String("Connection succeeded"));
pkt->info->set("objectEncoding", new SrsAmf0Number(req->objectEncoding));
SrsASrsAmf0EcmaArray* data = new SrsASrsAmf0EcmaArray();
pkt->info->set("data", data);
data->set("srs_version", new SrsAmf0String(RTMP_SIG_FMS_VER));
data->set("srs_server", new SrsAmf0String(RTMP_SIG_SRS_NAME));
data->set("srs_license", new SrsAmf0String(RTMP_SIG_SRS_LICENSE));
data->set("srs_role", new SrsAmf0String(RTMP_SIG_SRS_ROLE));
data->set("srs_url", new SrsAmf0String(RTMP_SIG_SRS_URL));
data->set("srs_version", new SrsAmf0String(RTMP_SIG_SRS_VERSION));
data->set("srs_site", new SrsAmf0String(RTMP_SIG_SRS_WEB));
data->set("srs_email", new SrsAmf0String(RTMP_SIG_SRS_EMAIL));
data->set("srs_copyright", new SrsAmf0String(RTMP_SIG_SRS_COPYRIGHT));
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send connect app response message failed. ret=%d", ret);
return ret;
}
srs_info("send connect app response message success.");
return ret;
}
int SrsRtmp::on_bw_done()
{
int ret = ERROR_SUCCESS;
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnBWDonePacket* pkt = new SrsOnBWDonePacket();
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onBWDone message failed. ret=%d", ret);
return ret;
}
srs_info("send onBWDone message success.");
return ret;
}
int SrsRtmp::identify_client(int stream_id, SrsClientType& type, std::string& stream_name)
{
type = SrsClientUnknown;
int ret = ERROR_SUCCESS;
while (true) {
SrsCommonMessage* msg = NULL;
if ((ret = protocol->recv_message(&msg)) != ERROR_SUCCESS) {
srs_error("recv identify client message failed. ret=%d", ret);
return ret;
}
SrsAutoFree(SrsCommonMessage, msg, false);
if (!msg->header.is_amf0_command() && !msg->header.is_amf3_command()) {
srs_trace("identify ignore messages except "
"AMF0/AMF3 command message. type=%#x", msg->header.message_type);
continue;
}
if ((ret = msg->decode_packet(protocol)) != ERROR_SUCCESS) {
srs_error("identify decode message failed. ret=%d", ret);
return ret;
}
SrsPacket* pkt = msg->get_packet();
if (dynamic_cast<SrsCreateStreamPacket*>(pkt)) {
srs_info("identify client by create stream, play or flash publish.");
return identify_create_stream_client(
dynamic_cast<SrsCreateStreamPacket*>(pkt), stream_id, type, stream_name);
}
if (dynamic_cast<SrsFMLEStartPacket*>(pkt)) {
srs_info("identify client by releaseStream, fmle publish.");
return identify_fmle_publish_client(
dynamic_cast<SrsFMLEStartPacket*>(pkt), type, stream_name);
}
srs_trace("ignore AMF0/AMF3 command message.");
}
return ret;
}
int SrsRtmp::set_chunk_size(int chunk_size)
{
int ret = ERROR_SUCCESS;
SrsCommonMessage* msg = new SrsCommonMessage();
SrsSetChunkSizePacket* pkt = new SrsSetChunkSizePacket();
pkt->chunk_size = chunk_size;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send set chunk size message failed. ret=%d", ret);
return ret;
}
srs_info("send set chunk size message success. chunk_size=%d", chunk_size);
return ret;
}
int SrsRtmp::start_play(int stream_id)
{
int ret = ERROR_SUCCESS;
// StreamBegin
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsUserControlPacket* pkt = new SrsUserControlPacket();
pkt->event_type = SrcPCUCStreamBegin;
pkt->event_data = stream_id;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send PCUC(StreamBegin) message failed. ret=%d", ret);
return ret;
}
srs_info("send PCUC(StreamBegin) message success.");
}
// onStatus(NetStream.Play.Reset)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeStreamReset));
pkt->data->set(StatusDescription, new SrsAmf0String("Playing and resetting stream."));
pkt->data->set(StatusDetails, new SrsAmf0String("stream"));
pkt->data->set(StatusClientId, new SrsAmf0String(RTMP_SIG_CLIENT_ID));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Play.Reset) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Play.Reset) message success.");
}
// onStatus(NetStream.Play.Start)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeStreamStart));
pkt->data->set(StatusDescription, new SrsAmf0String("Started playing stream."));
pkt->data->set(StatusDetails, new SrsAmf0String("stream"));
pkt->data->set(StatusClientId, new SrsAmf0String(RTMP_SIG_CLIENT_ID));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Play.Reset) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Play.Reset) message success.");
}
// |RtmpSampleAccess(false, false)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsSampleAccessPacket* pkt = new SrsSampleAccessPacket();
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send |RtmpSampleAccess(false, false) message failed. ret=%d", ret);
return ret;
}
srs_info("send |RtmpSampleAccess(false, false) message success.");
}
// onStatus(NetStream.Data.Start)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusDataPacket* pkt = new SrsOnStatusDataPacket();
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeDataStart));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Data.Start) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Data.Start) message success.");
}
srs_info("start play success.");
return ret;
}
int SrsRtmp::on_play_client_pause(int stream_id, bool is_pause)
{
int ret = ERROR_SUCCESS;
if (is_pause) {
// onStatus(NetStream.Pause.Notify)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeStreamPause));
pkt->data->set(StatusDescription, new SrsAmf0String("Paused stream."));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Pause.Notify) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Pause.Notify) message success.");
}
// StreamEOF
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsUserControlPacket* pkt = new SrsUserControlPacket();
pkt->event_type = SrcPCUCStreamEOF;
pkt->event_data = stream_id;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send PCUC(StreamEOF) message failed. ret=%d", ret);
return ret;
}
srs_info("send PCUC(StreamEOF) message success.");
}
} else {
// onStatus(NetStream.Unpause.Notify)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeStreamUnpause));
pkt->data->set(StatusDescription, new SrsAmf0String("Unpaused stream."));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Unpause.Notify) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Unpause.Notify) message success.");
}
// StreanBegin
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsUserControlPacket* pkt = new SrsUserControlPacket();
pkt->event_type = SrcPCUCStreamBegin;
pkt->event_data = stream_id;
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send PCUC(StreanBegin) message failed. ret=%d", ret);
return ret;
}
srs_info("send PCUC(StreanBegin) message success.");
}
}
return ret;
}
int SrsRtmp::start_fmle_publish(int stream_id)
{
int ret = ERROR_SUCCESS;
// FCPublish
double fc_publish_tid = 0;
if (true) {
SrsCommonMessage* msg = NULL;
SrsFMLEStartPacket* pkt = NULL;
if ((ret = srs_rtmp_expect_message<SrsFMLEStartPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
srs_error("recv FCPublish message failed. ret=%d", ret);
return ret;
}
srs_info("recv FCPublish request message success.");
SrsAutoFree(SrsCommonMessage, msg, false);
fc_publish_tid = pkt->transaction_id;
}
// FCPublish response
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsFMLEStartResPacket* pkt = new SrsFMLEStartResPacket(fc_publish_tid);
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send FCPublish response message failed. ret=%d", ret);
return ret;
}
srs_info("send FCPublish response message success.");
}
// createStream
double create_stream_tid = 0;
if (true) {
SrsCommonMessage* msg = NULL;
SrsCreateStreamPacket* pkt = NULL;
if ((ret = srs_rtmp_expect_message<SrsCreateStreamPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
srs_error("recv createStream message failed. ret=%d", ret);
return ret;
}
srs_info("recv createStream request message success.");
SrsAutoFree(SrsCommonMessage, msg, false);
create_stream_tid = pkt->transaction_id;
}
// createStream response
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsCreateStreamResPacket* pkt = new SrsCreateStreamResPacket(create_stream_tid, stream_id);
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send createStream response message failed. ret=%d", ret);
return ret;
}
srs_info("send createStream response message success.");
}
// publish
if (true) {
SrsCommonMessage* msg = NULL;
SrsPublishPacket* pkt = NULL;
if ((ret = srs_rtmp_expect_message<SrsPublishPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
srs_error("recv publish message failed. ret=%d", ret);
return ret;
}
srs_info("recv publish request message success.");
SrsAutoFree(SrsCommonMessage, msg, false);
}
// publish response onFCPublish(NetStream.Publish.Start)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->command_name = RTMP_AMF0_COMMAND_ON_FC_PUBLISH;
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodePublishStart));
pkt->data->set(StatusDescription, new SrsAmf0String("Started publishing stream."));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onFCPublish(NetStream.Publish.Start) message failed. ret=%d", ret);
return ret;
}
srs_info("send onFCPublish(NetStream.Publish.Start) message success.");
}
// publish response onStatus(NetStream.Publish.Start)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodePublishStart));
pkt->data->set(StatusDescription, new SrsAmf0String("Started publishing stream."));
pkt->data->set(StatusClientId, new SrsAmf0String(RTMP_SIG_CLIENT_ID));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Publish.Start) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Publish.Start) message success.");
}
srs_info("FMLE publish success.");
return ret;
}
int SrsRtmp::fmle_unpublish(int stream_id, double unpublish_tid)
{
int ret = ERROR_SUCCESS;
// publish response onFCUnpublish(NetStream.unpublish.Success)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->command_name = RTMP_AMF0_COMMAND_ON_FC_UNPUBLISH;
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeUnpublishSuccess));
pkt->data->set(StatusDescription, new SrsAmf0String("Stop publishing stream."));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onFCUnpublish(NetStream.unpublish.Success) message failed. ret=%d", ret);
return ret;
}
srs_info("send onFCUnpublish(NetStream.unpublish.Success) message success.");
}
// FCUnpublish response
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsFMLEStartResPacket* pkt = new SrsFMLEStartResPacket(unpublish_tid);
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send FCUnpublish response message failed. ret=%d", ret);
return ret;
}
srs_info("send FCUnpublish response message success.");
}
// publish response onStatus(NetStream.Unpublish.Success)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodeUnpublishSuccess));
pkt->data->set(StatusDescription, new SrsAmf0String("Stream is now unpublished"));
pkt->data->set(StatusClientId, new SrsAmf0String(RTMP_SIG_CLIENT_ID));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Unpublish.Success) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Unpublish.Success) message success.");
}
srs_info("FMLE unpublish success.");
return ret;
}
int SrsRtmp::start_flash_publish(int stream_id)
{
int ret = ERROR_SUCCESS;
// publish response onStatus(NetStream.Publish.Start)
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
pkt->data->set(StatusLevel, new SrsAmf0String(StatusLevelStatus));
pkt->data->set(StatusCode, new SrsAmf0String(StatusCodePublishStart));
pkt->data->set(StatusDescription, new SrsAmf0String("Started publishing stream."));
pkt->data->set(StatusClientId, new SrsAmf0String(RTMP_SIG_CLIENT_ID));
msg->set_packet(pkt, stream_id);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send onStatus(NetStream.Publish.Start) message failed. ret=%d", ret);
return ret;
}
srs_info("send onStatus(NetStream.Publish.Start) message success.");
}
srs_info("flash publish success.");
return ret;
}
int SrsRtmp::identify_create_stream_client(SrsCreateStreamPacket* req, int stream_id, SrsClientType& type, std::string& stream_name)
{
int ret = ERROR_SUCCESS;
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsCreateStreamResPacket* pkt = new SrsCreateStreamResPacket(req->transaction_id, stream_id);
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send createStream response message failed. ret=%d", ret);
return ret;
}
srs_info("send createStream response message success.");
}
while (true) {
SrsCommonMessage* msg = NULL;
if ((ret = protocol->recv_message(&msg)) != ERROR_SUCCESS) {
srs_error("recv identify client message failed. ret=%d", ret);
return ret;
}
SrsAutoFree(SrsCommonMessage, msg, false);
if (!msg->header.is_amf0_command() && !msg->header.is_amf3_command()) {
srs_trace("identify ignore messages except "
"AMF0/AMF3 command message. type=%#x", msg->header.message_type);
continue;
}
if ((ret = msg->decode_packet(protocol)) != ERROR_SUCCESS) {
srs_error("identify decode message failed. ret=%d", ret);
return ret;
}
SrsPacket* pkt = msg->get_packet();
if (dynamic_cast<SrsPlayPacket*>(pkt)) {
SrsPlayPacket* play = dynamic_cast<SrsPlayPacket*>(pkt);
type = SrsClientPlay;
stream_name = play->stream_name;
srs_trace("identity client type=play, stream_name=%s", stream_name.c_str());
return ret;
}
if (dynamic_cast<SrsPublishPacket*>(pkt)) {
srs_info("identify client by publish, falsh publish.");
return identify_flash_publish_client(
dynamic_cast<SrsPublishPacket*>(pkt), type, stream_name);
}
srs_trace("ignore AMF0/AMF3 command message.");
}
return ret;
}
int SrsRtmp::identify_fmle_publish_client(SrsFMLEStartPacket* req, SrsClientType& type, std::string& stream_name)
{
int ret = ERROR_SUCCESS;
type = SrsClientFMLEPublish;
stream_name = req->stream_name;
// releaseStream response
if (true) {
SrsCommonMessage* msg = new SrsCommonMessage();
SrsFMLEStartResPacket* pkt = new SrsFMLEStartResPacket(req->transaction_id);
msg->set_packet(pkt, 0);
if ((ret = protocol->send_message(msg)) != ERROR_SUCCESS) {
srs_error("send releaseStream response message failed. ret=%d", ret);
return ret;
}
srs_info("send releaseStream response message success.");
}
return ret;
}
int SrsRtmp::identify_flash_publish_client(SrsPublishPacket* req, SrsClientType& type, std::string& stream_name)
{
int ret = ERROR_SUCCESS;
type = SrsClientFlashPublish;
stream_name = req->stream_name;
return ret;
}
... ...
... ... @@ -32,8 +32,6 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <string>
#include <st.h>
class SrsProtocol;
class ISrsMessage;
class SrsCommonMessage;
... ...
... ... @@ -30,8 +30,6 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <algorithm>
#include <st.h>
#include <srs_core_log.hpp>
#include <srs_core_error.hpp>
#include <srs_core_client.hpp>
... ... @@ -48,24 +46,16 @@ SrsListener::SrsListener(SrsServer* _server, SrsListenerType _type)
port = 0;
server = _server;
type = _type;
tid = NULL;
loop = false;
pthread = new SrsThread(this, 0);
}
SrsListener::~SrsListener()
{
if (stfd) {
st_netfd_close(stfd);
stfd = NULL;
}
srs_close_stfd(stfd);
if (tid) {
loop = false;
st_thread_interrupt(tid);
st_thread_join(tid, NULL);
tid = NULL;
}
pthread->stop();
srs_freep(pthread);
// st does not close it sometimes,
// close it manually.
... ... @@ -118,8 +108,7 @@ int SrsListener::listen(int _port)
}
srs_verbose("st open socket success. fd=%d", fd);
if ((tid = st_thread_create(listen_thread, this, 1, 0)) == NULL) {
ret = ERROR_ST_CREATE_LISTEN_THREAD;
if ((ret = pthread->start()) != ERROR_SUCCESS) {
srs_error("st_thread_create listen thread error. ret=%d", ret);
return ret;
}
... ... @@ -130,41 +119,32 @@ int SrsListener::listen(int _port)
return ret;
}
void SrsListener::listen_cycle()
void SrsListener::on_enter_loop()
{
int ret = ERROR_SUCCESS;
log_context->generate_id();
srs_trace("listen cycle start, port=%d, type=%d, fd=%d", port, type, fd);
while (loop) {
st_netfd_t client_stfd = st_accept(stfd, NULL, NULL, ST_UTIME_NO_TIMEOUT);
if(client_stfd == NULL){
// ignore error.
srs_warn("ignore accept thread stoppped for accept client error");
continue;
}
srs_verbose("get a client. fd=%d", st_netfd_fileno(client_stfd));
if ((ret = server->accept_client(type, client_stfd)) != ERROR_SUCCESS) {
srs_warn("accept client error. ret=%d", ret);
continue;
}
srs_verbose("accept client finished. conns=%d, ret=%d", (int)conns.size(), ret);
}
}
void* SrsListener::listen_thread(void* arg)
int SrsListener::cycle()
{
SrsListener* obj = (SrsListener*)arg;
srs_assert(obj != NULL);
int ret = ERROR_SUCCESS;
obj->loop = true;
obj->listen_cycle();
st_netfd_t client_stfd = st_accept(stfd, NULL, NULL, ST_UTIME_NO_TIMEOUT);
if(client_stfd == NULL){
// ignore error.
srs_warn("ignore accept thread stoppped for accept client error");
return ret;
}
srs_verbose("get a client. fd=%d", st_netfd_fileno(client_stfd));
return NULL;
if ((ret = server->accept_client(type, client_stfd)) != ERROR_SUCCESS) {
srs_warn("accept client error. ret=%d", ret);
return ret;
}
srs_verbose("accept client finished. conns=%d, ret=%d", (int)conns.size(), ret);
return ret;
}
SrsServer::SrsServer()
... ... @@ -312,8 +292,7 @@ int SrsServer::accept_client(SrsListenerType type, st_netfd_t client_stfd)
srs_error("exceed the max connections, drop client: "
"clients=%d, max=%d, fd=%d", (int)conns.size(), max_connections, fd);
st_netfd_close(client_stfd);
::close(fd);
srs_close_stfd(client_stfd);
return ret;
}
... ...
... ... @@ -32,9 +32,8 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <vector>
#include <st.h>
#include <srs_core_reload.hpp>
#include <srs_core_thread.hpp>
class SrsServer;
class SrsConnection;
... ... @@ -45,7 +44,7 @@ enum SrsListenerType
SrsListenerApi
};
class SrsListener
class SrsListener : public ISrsThreadHandler
{
public:
SrsListenerType type;
... ... @@ -54,16 +53,16 @@ private:
st_netfd_t stfd;
int port;
SrsServer* server;
st_thread_t tid;
bool loop;
SrsThread* pthread;
public:
SrsListener(SrsServer* _server, SrsListenerType _type);
virtual ~SrsListener();
public:
virtual int listen(int port);
private:
virtual void listen_cycle();
static void* listen_thread(void* arg);
// interface ISrsThreadHandler.
public:
virtual void on_enter_loop();
virtual int cycle();
};
class SrsServer : public SrsReloadHandler
... ...
... ... @@ -30,8 +30,6 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <srs_core.hpp>
#include <st.h>
/**
* the socket provides TCP socket over st,
* that is, the sync socket mechanism.
... ...