rtsp.cpp 14.1 KB
Newer Older
1
/**
2 3 4
 * @file rtsp.cpp
 * @brief RTSP server implementation
 * @copyright Copyright (C) 2017 Elphel Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * @author AUTHOR <EMAIL>
 *
 * @par License:
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

22 23 24 25 26 27 28 29
#include "rtsp.h"
#include "helpers.h"

#include <string.h>
#include <vector>

using namespace std;

30 31 32 33
//#undef RTSP_DEBUG
//#undef RTSP_DEBUG_2
#define RTSP_DEBUG
#define RTSP_DEBUG_2
34 35 36 37 38 39 40 41 42 43 44 45 46

#ifdef RTSP_DEBUG
	#define D(a) a
#else
	#define D(a)
#endif

#ifdef RTSP_DEBUG_2
	#define D2(a) a
#else
	#define D2(a)
#endif

47 48 49
#define RTSP_SIGN	              "rtsp://"
#define RTSP_PRIMARY_PORT	      554
#define RTSP_SECONDARY_PORT	      8554
50
//#define RTSP_PORT_3	7070
51 52
/** Maximun number of pending connections for a socket */
#define MAX_CONNECTIONS           2
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

// TODO
_Request::_Request(const string &request) {
	string s;
	int prev = 0;
	int i = 0;
	int len = request.length();
	const char *c = request.c_str();
	bool first = true;
	string name, value;

	while(i < len) {
		s = "";
		for(; i < len && c[i] != '\n' && c[i] != '\r' && c[i] != '\0'; i++);
		if(c[i] == '\n' || c[i] == '\r') {
			if(i == prev) {
				i++;
				prev = i;
				continue;
			}
			s.insert(0, request, prev, i - prev);
//			cerr << "prev == " << prev << "; i == " << i << ";--> " << "\trequest string: \"" << s << "\"" << endl;
			if(first) {
				int x = s.find(" ");
				method.insert(0, s, 0, x);
				int y = s.find(" ", x + 1);
				uri.insert(0, s, x + 1, y - x - 1);
//				cerr  << "method == |" << method << "|; uri == |" << uri << "|" << endl;
				first = false;
			} else {
				name = "";
				value = "";
				int x = s.find(": ");
				name.insert(0, s, 0, x);
				value.insert(0, s, x + 2, s.length() - x - 1);
				fields[name] = value;
//				cerr << "pair: name == |" << name << "|; value == |" << value << "|" << endl;
			}
		}
		if(c[i] == '\0')
			break;
		i++;
		prev = i;
	}
}

void _Responce::add_field(const string &name, const string &value) {
	fields[name] = value;
}

void _Responce::add_include(const string &_include) {
	include = _include;
}

string _Responce::serialize() {
	string rez;
109
	switch (_status) {
110 111 112 113 114 115 116 117 118 119
	case STATUS_OK:
		rez = "RTSP/1.0 200 OK\r\n";
		break;
	case STATUS_BUSY:
		rez = "RTSP/1.0 455 Server is busy\r\n";
		break;
	case STATUS_EMPTY:
		rez = "";
		return rez;
	}
120
	for (map<string, string>::iterator it = fields.begin(); it != fields.end(); it++) {
121 122 123
		rez += (*it).first + ": " + (*it).second + "\r\n";
	}
	rez += "\r\n";
124
	if (include.length() != 0) {
125 126 127 128 129
		rez += include;
	}
	return rez;
}

130
RTSP_Server::RTSP_Server(int (*h)(void *, RTSP_Server *, RTSP_Server::event), void *handler_data, Parameters *pars, Session *_session) {
131 132 133 134 135 136
	socket_main_1 = NULL;
	socket_main_2 = NULL;
//	socket_main_3 = NULL;
	handler_f = h;
	this->handler_data = handler_data;
	session = _session;
137
	params = pars;
138 139 140 141
//	_busy = NULL;
}

void RTSP_Server::main(void) {
142
	int port_num;
143 144 145 146 147 148
	list<Socket *> s;
	// create listen socket...

	// once opened socket to listen can be closed and reopen again by Socket's implementation:
	// opened port assigned to process id and is keeped all time while process is alive
	// so, keep this socket
149
	if (socket_main_1 == NULL) {
150 151 152
		port_num = RTSP_PRIMARY_PORT + 2 * params->get_port_num();
		socket_main_1 = new Socket("", port_num);
		socket_main_1->listen(MAX_CONNECTIONS);
153
	}
154
	if (socket_main_2 == NULL) {
155 156 157
		port_num = RTSP_SECONDARY_PORT + 2 * params->get_port_num();
		socket_main_2 = new Socket("", port_num);
		socket_main_2->listen(MAX_CONNECTIONS);
158
	}
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
	/*
	 if(socket_main_3 == NULL) {
	 socket_main_3 = new Socket("", RTSP_PORT_3);
	 socket_main_3->listen(2);
	 }
	 */
	/*
	 if(socket_main == NULL) {
	 //		socket_main = new Socket("", 554);
	 //cerr << "create socket to listen port" << endl;
	 socket_main = new Socket("", RTSP_PORT);
	 //		Socket *socket_1 = new Socket("", 554);
	 //		Socket *socket_2 = new Socket("", 8554);
	 //		Socket *socket_3 = new Socket("", 7070);
	 socket_main->listen(2);
	 } else {
	 //cerr << "main socket already exist" << endl;
	 }
	 */
178 179 180 181
	s.push_back(socket_main_1);
	s.push_back(socket_main_2);
//	s.push_back(socket_main_3);

182
	D(static int count = 0;)
183 184
	bool to_poll = true;
//	Parameters *params = Parameters::instance();
185 186
	while (true) {
		if (to_poll) {
187
			int poll_rez = Socket::poll(s, 500);
188 189 190 191 192
			D( {if (count < 5) {
					cerr << "poll..." << endl;
					count++;
				}
			});
193 194 195
			// TODO here:
			// if client connected - check for changes of all possible parameters
			// if client not connected - check only about enable/disable bit to prevent overhead
196
			if (handler(PARAMS_WAS_CHANGED)) {
197 198 199 200
				// stop all sessions, and restart streamer
				handler(RESET);
				break;
			}
201
			if (poll_rez == 0) {
202 203 204 205 206 207
				/// poll was finished with timeout, not socket event
				to_poll = true;
				continue;
			}
		}
		to_poll = true;
208
		for (list<Socket *>::iterator it = s.begin(); it != s.end(); it++) {
209
			Socket::state state = (*it)->state_refresh();
210 211 212
			if (state == Socket::STATE_IN || state == Socket::STATE_DISCONNECT) {
				D2(cerr << endl << "something happen on the socket!" << endl;)
				if (*it == socket_main_1 || *it == socket_main_2) {	// || *it == socket_main_3) {
213 214
//					Socket *in = socket_main->accept();
					Socket *in = (*it)->accept();
215
					if (in) {
216
						in->set_so_keepalive(1);
217 218
						D2(cerr << "processed - s.push_back(in)" << endl;)
						D2(fprintf(stderr, "added : 0x%p\n", in);)
219 220 221 222
						s.push_back(in);
					}
				} else {
					// check for remove closed socket !
223 224 225 226
					D2(cerr << "was with non-main socket" << endl;)
					if (!process(*it)) {
						D2(cerr << "process failed - remove it!" << endl;)
						D2(fprintf(stderr, "delete: 0x%p\n", *it);)
227 228 229 230 231 232 233 234 235 236 237
						delete *it;
						s.remove(*it);
						// check about counters etc...
						to_poll = false;
						break;
					}
				}
			}
		}
	}
	// stop all - by TEARDOWN command
238
	for (list<Socket *>::iterator it = s.begin(); it != s.end(); it++) {
239
		// keep the 'main' i.e. server socket
240 241
		if (*it != socket_main_1 && *it != socket_main_2) {			// && *it != socket_main_3) {
			D2(fprintf(stderr, "delete: 0x%p\n", *it);)
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
			delete *it;
		}
	}
	// reset sockets IDs and state
//	_busy = NULL;
	active_sockets.erase(active_sockets.begin(), active_sockets.end());
}

bool RTSP_Server::process_teardown(Socket *s) {
//			if(!session->rtp_out.multicast)
//				_busy = s;
	for(list<Socket *>::iterator it = active_sockets.begin(); it != active_sockets.end(); it++)
		if(*it == s) {
//			if(*it != socket_main)
//				delete *it;
			active_sockets.erase(it);
			return true;
		}
	return false;
}

bool RTSP_Server::process_play(Socket *s, bool add) {
	// discard unicast client if client already exist
	if(!session->rtp_out.multicast)
		if(active_sockets.size() != 0)
			return false;
	if(add)
		active_sockets.push_back(s);
	return true;
}

bool RTSP_Server::process(Socket *s) {
	string req;
	_Request *request;
	_Responce *responce = NULL;
	bool r = true;
	_Responce::status status = _Responce::STATUS_EMPTY;

D(cerr << "RTSP_Server::process()" << endl;)
	bool to_teardown = false;
	// recv failed - socket error - should close socket and check teardown
	if(!s->recv(req))
		to_teardown = true;
	// empty request mean connection closed (behavior of Socket)
	if(req == "")
		to_teardown = true;
	// decrement active clients, and stop stream if no clients
	if(to_teardown) {
		if(process_teardown(s))
			handler(TEARDOWN);
		return false;
	}
D(cerr << __FILE__<< ":"<< __FUNCTION__ << ":" <<__LINE__ << " part_REQUEST: " << endl << "\"" << req << "\"" << endl;)
	// check for partial request...
	part_of_request += req;
	req = part_of_request;
	const char *c = req.c_str();
	string end;
	int e = req.length();
	e -= 4;
	if(e <= 0)
		e = 0;
	for(int i = req.length() - 1; i >= e; i--) {
		end += c[i];
	}
	if(end.find("\n\n") != 0 && end.find("\n\r\n\r") != 0) {
		return true;
	} else {
		part_of_request = "";
	}
	// process...
	request = new _Request(req);

315
//	Parameters *params = Parameters::instance();
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
	responce = new _Responce();
//	responce->add_field("CSeq", (*request->get_fields().find("CSeq")).second);
	responce->add_field("CSeq", (request->get_fields())["CSeq"]);
	if(request->get_method() == "OPTIONS") {
		if(params->daemon_enabled()) {
			status = _Responce::STATUS_OK;
			responce->add_field("Public", "DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
			// check transport...
			if(!session->rtp_out.multicast)
				session->rtp_out.ip = s->source_ip();
		} else {
			status = _Responce::STATUS_BUSY;
		}
	}
	if(request->get_method() == "DESCRIBE") {
		if(params->daemon_enabled() && process_play(s, false)) {
			handler(DESCRIBE); /// Streamer should update session data (width, height, fps)
			status = _Responce::STATUS_OK;
			char buf[8];
			string sdp = make_sdp(request->get_uri());
			responce->add_field("Content-Type", "application/sdp");
			sprintf(buf, "%d", (int)sdp.length());
			responce->add_field("Content-Length", buf);
			responce->add_include(sdp);
		} else {
			status = _Responce::STATUS_BUSY;
		}
	}
	if(request->get_method() == "SETUP") {
		if(params->daemon_enabled() && process_play(s, false)) {
			status = _Responce::STATUS_OK;
			// TODO: random session number
			responce->add_field("Session", "47112344");
//			responce->add_field("Transport", make_transport((*request->get_fields().find("Transport")).second));
			responce->add_field("Transport", make_transport(request->get_fields()["Transport"]));
		} else {
			status = _Responce::STATUS_BUSY;
		}
	}
	if(request->get_method() == "TEARDOWN") {
		status = _Responce::STATUS_OK;
		process_teardown(s);
		handler(TEARDOWN);
	}
	if(request->get_method() == "PLAY") {
		if(params->daemon_enabled() && (process_play(s))) {
			status = _Responce::STATUS_OK;
			handler(PLAY);
		} else {
			status = _Responce::STATUS_BUSY;
		}
	}
	if(request->get_method() == "PAUSE") {
		status = _Responce::STATUS_OK;
		handler(PAUSE);
	}
	delete request;
	responce->set_status(status);
D(	cerr << "\tRESPONSE: " << endl << "\"" << responce->serialize() << "\"" << endl;)
	r = s->send(responce->serialize());
	delete responce;
	return r;
}

string RTSP_Server::make_sdp(string uri) {
	char buf[256];

D(cerr << "make SDP" << endl;)
	// make video description
	// m = - port + PAYLOAD
	string rez;
///*
	rez += "m=video ";
	sprintf(buf, "%d", session->rtp_out.port_video);
	if(session->process_audio == false) {
		if(session->rtp_out.multicast) {
			rez += buf;
		} else {
			rez += "0";
		}
	} else {
		rez += buf;
	}
	rez += " RTP/AVP ";
	sprintf(buf, "%d", session->video.type);
	rez += buf;
	rez += "\r\n";	// port
	if(session->rtp_out.multicast) {
		rez += "a=type:multicast\r\n";
		rez += "c=IN IP4 " + session->rtp_out.ip + "/" + session->rtp_out.ttl + "\r\n";	// IP + TTL
	} else {
		rez += "a=type:unicast\r\n";
		rez += "c=IN IP4 0.0.0.0\r\n";	// IP + TTL
	}
	sprintf(buf, "%.4f", session->video.fps);
//	rez += "a=framerate:";
//	rez += buf;
	rez += "\r\na=x-framerate:";
	rez += buf;
//cerr << "x-framerate == " << buf << endl;
	if(session->video.width > 0) {
		sprintf(buf, "%d", session->video.width);
//		rez += "\r\na=width:";
//		rez += buf;
		rez += "\r\na=x-width:";
		rez += buf;
	}
	if(session->video.height > 0) {
		sprintf(buf, "%d", session->video.height);
//		rez += "\r\na=height:";
//		rez += buf;
		rez += "\r\na=x-height:";
		rez += buf;
	}
	if(session->video.width > 0 && session->video.height > 0) {
		sprintf(buf, "%d,%d", session->video.width, session->video.height);
		rez += "\r\na=x-dimensions:";
		rez += buf;
	}
	rez += "\r\n";
//*/
	// make audio description, if present
	if(session->process_audio) {
//		sprintf(buf, "m=audio %d RTP/AVP %d\r\n", atoi(session->rtp_out.port.c_str()) + 2, session->audio.type);
		sprintf(buf, "m=audio %d RTP/AVP %d\r\n", session->rtp_out.port_audio, session->audio.type);
		rez += buf;
		sprintf(buf, "a=rtpmap:%d L16/%d/%d\r\n", session->audio.type, session->audio.sample_rate, session->audio.channels);
//cerr << "SDP: " << buf << endl;
		rez += buf;
	}
/*
	if(session->rtp_out.multicast) {
		rez += "a=type:multicast\r\n";
		rez += "c=IN IP4 " + session->rtp_out.ip + "/" + session->rtp_out.ttl + "\r\n";	// IP + TTL
	} else {
		rez += "a=type:unicast\r\n";
		rez += "c=IN IP4 0.0.0.0\r\n";	// IP + TTL
	}
*/
	rez += "a=control:" + uri + "\r\n";
D(cerr << "make SDP - ok!" << endl;)
	return rez;
}

string RTSP_Server::make_transport(string req) {
	if(req == "")
		return "";
	map<string, string> m = String::split_list_to_map(String::split_to_list(req, ';'), '=');
	string client_port = m["client_port"];
	int port_req = session->rtp_out.port_video;
//D(cerr << "client_port == " << client_port << endl;)
	if(client_port != "") {
		string first, second;
		String::split(client_port, '-', first, second);
		port_req = atol(first.c_str());
471
		D(cerr << "client_port == |" << client_port << "|; first == |" << first << "|; second == |" << second << "|" << endl;)
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
//		session->rtp_out.port = first;
	}

	if(!session->rtp_out.multicast) {
		if(!session->process_audio) {
			session->rtp_out.port_video = port_req;
		}
	}

	string rez = "RTP/AVP;";

	char buf[128];
	sprintf(buf, "%d", port_req);

	if(session->rtp_out.multicast)
		rez += "multicast;destination=" + session->rtp_out.ip + ";port=" + buf;
    else
		rez += "unicast;destination=" + session->rtp_out.ip + ";server_port=" + buf;

    if(session->process_audio) {
		sprintf(buf, "-%d", port_req + 1);
//		rez += "-";
//		long p = atol(session->rtp_out.port.c_str());
//		p++;
//		sprintf(buf, "%d", p);
		rez += buf;
	}
	if(session->rtp_out.multicast)
		rez += ";ttl=" + session->rtp_out.ttl;
//	rez += "destination=" + transport.ip + ";port=" + transport.port;
//	if(transport.multicast)
//		rez += ";ttl=" + transport.ttl;
	return rez;

}

RTSP_Server::~RTSP_Server() {
//	cerr << "destroy RTSP_Server object" << endl;
//	delete socket_main;
//	if (request)  delete request;
//	if (responce) delete responce;
}