Initial commit of Arduino libraries

This commit is contained in:
Sam
2025-05-23 10:47:41 +10:00
commit 5bfce5fc3e
2476 changed files with 1108481 additions and 0 deletions

4
Micro-RTSP/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
testserver
octo.jpg
*.exe
*.o

7
Micro-RTSP/LICENSE Normal file
View File

@@ -0,0 +1,7 @@
Copyright 2018 S. Kevin Hester-Chow, kevinh@geeksville.com (MIT License)
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.

99
Micro-RTSP/README.md Normal file
View File

@@ -0,0 +1,99 @@
# Micro-RTSP
This is a small library which can be used to serve up RTSP streams from
resource constrained MCUs. It lets you trivially make a $10 open source
RTSP video stream camera.
# Usage
This library works for ESP32/arduino targets but also for most any posixish platform.
## Example arduino/ESP32 usage
This library will work standalone, but it is _super_ easy to use if your app is platform.io based.
Just "pio lib install Micro-RTSP" to pull the latest version from their library server. If you want to use the OV2640
camera support you'll need to be targeting the espressif32 platform in your project.
See the [example platform.io app](/examples). It should build and run on virtually any of the $10
ESP32-CAM boards (such as M5CAM). The relevant bit of the code is included below. In short:
1. Listen for a TCP connection on the RTSP port with accept()
2. When a connection comes in, create a CRtspSession and OV2640Streamer camera streamer objects.
3. While the connection remains, call session->handleRequests(0) to handle any incoming client requests.
4. Every 100ms or so call session->broadcastCurrentFrame() to send new frames to any clients.
```
void loop()
{
uint32_t msecPerFrame = 100;
static uint32_t lastimage = millis();
// If we have an active client connection, just service that until gone
// (FIXME - support multiple simultaneous clients)
if(session) {
session->handleRequests(0); // we don't use a timeout here,
// instead we send only if we have new enough frames
uint32_t now = millis();
if(now > lastimage + msecPerFrame || now < lastimage) { // handle clock rollover
session->broadcastCurrentFrame(now);
lastimage = now;
// check if we are overrunning our max frame rate
now = millis();
if(now > lastimage + msecPerFrame)
printf("warning exceeding max frame rate of %d ms\n", now - lastimage);
}
if(session->m_stopped) {
delete session;
delete streamer;
session = NULL;
streamer = NULL;
}
}
else {
client = rtspServer.accept();
if(client) {
//streamer = new SimStreamer(&client, true); // our streamer for UDP/TCP based RTP transport
streamer = new OV2640Streamer(&client, cam); // our streamer for UDP/TCP based RTP transport
session = new CRtspSession(&client, streamer); // our threads RTSP session and state
}
}
}
```
## Example posix/linux usage
There is a small standalone example [here](/test/RTSPTestServer.cpp). You can build it by following [these](/test/README.md) directions. The usage of the two key classes (CRtspSession and SimStreamer) are very similar to to the ESP32 usage.
## Supporting new camera devices
Supporting new camera devices is quite simple. See OV2640Streamer for an example and implement streamImage()
by reading a frame from your camera.
# Structure and design notes
# Known Issues
## Video is delayed
Most players do a buffering. For example VLC by default sets a cache to 1000ms, resulting in a noticable delay. If you want to remove the delay set the `:network-caching=0` - in the UI it's hidden under `Show more options`.
# Issues and sending pull requests
Please report issues and send pull requests. I'll happily reply. ;-)
# Credits
The server code was initially based on a great 2013 [tutorial](https://www.medialan.de/usecase0001.html) by Medialan.
# License
Copyright 2018 S. Kevin Hester-Chow, kevinh@geeksville.com (MIT License)
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.

18
Micro-RTSP/TODO.md Normal file
View File

@@ -0,0 +1,18 @@
* add instructions for example app
* push RTSP streams to other servers ( https://github.com/ant-media/Ant-Media-Server/wiki/Getting-Started )
* make stack larger so that the various scratch buffers (currently in bss) can be shared
* cleanup code to a less ugly unified coding standard
* support multiple simultaneous clients on the device
* make octocat test image work again (by changing encoding type from 1 to 0 (422 vs 420))
DONE:
* serve real jpegs (use correct quantization & huffman tables)
* test that both TCP and UDP clients work
* change framerate to something slow
* test remote access
* select a licence and put license into github
* find cause of new mystery pause when starting up in sim mode
* split sim code from real code via inheritence
* use device camera
* package the ESP32-CAM stuff as a library so I can depend on it
* package as a library https://docs.platformio.org/en/latest/librarymanager/creating.html#library-creating-examples

3
Micro-RTSP/examples/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
wifikeys.h
.pioenvs
.piolibdeps

View File

@@ -0,0 +1,223 @@
#include "OV2640.h"
#include <WiFi.h>
#include <WebServer.h>
#include <WiFiClient.h>
#include "SimStreamer.h"
#include "OV2640Streamer.h"
#include "CRtspSession.h"
#define ENABLE_OLED //if want use oled ,turn on thi macro
// #define SOFTAP_MODE // If you want to run our own softap turn this on
#define ENABLE_WEBSERVER
#define ENABLE_RTSPSERVER
#ifdef ENABLE_OLED
#include "SSD1306.h"
#define OLED_ADDRESS 0x3c
#define I2C_SDA 14
#define I2C_SCL 13
SSD1306Wire display(OLED_ADDRESS, I2C_SDA, I2C_SCL, GEOMETRY_128_32);
bool hasDisplay; // we probe for the device at runtime
#endif
OV2640 cam;
#ifdef ENABLE_WEBSERVER
WebServer server(80);
#endif
#ifdef ENABLE_RTSPSERVER
WiFiServer rtspServer(8554);
#endif
#ifdef SOFTAP_MODE
IPAddress apIP = IPAddress(192, 168, 1, 1);
#else
#include "wifikeys.h"
#endif
#ifdef ENABLE_WEBSERVER
void handle_jpg_stream(void)
{
WiFiClient client = server.client();
String response = "HTTP/1.1 200 OK\r\n";
response += "Content-Type: multipart/x-mixed-replace; boundary=frame\r\n\r\n";
server.sendContent(response);
while (1)
{
cam.run();
if (!client.connected())
break;
response = "--frame\r\n";
response += "Content-Type: image/jpeg\r\n\r\n";
server.sendContent(response);
client.write((char *)cam.getfb(), cam.getSize());
server.sendContent("\r\n");
if (!client.connected())
break;
}
}
void handle_jpg(void)
{
WiFiClient client = server.client();
cam.run();
if (!client.connected())
{
return;
}
String response = "HTTP/1.1 200 OK\r\n";
response += "Content-disposition: inline; filename=capture.jpg\r\n";
response += "Content-type: image/jpeg\r\n\r\n";
server.sendContent(response);
client.write((char *)cam.getfb(), cam.getSize());
}
void handleNotFound()
{
String message = "Server is running!\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
server.send(200, "text/plain", message);
}
#endif
#ifdef ENABLE_OLED
#define LCD_MESSAGE(msg) lcdMessage(msg)
#else
#define LCD_MESSAGE(msg)
#endif
#ifdef ENABLE_OLED
void lcdMessage(String msg)
{
if(hasDisplay) {
display.clear();
display.drawString(128 / 2, 32 / 2, msg);
display.display();
}
}
#endif
CStreamer *streamer;
void setup()
{
#ifdef ENABLE_OLED
hasDisplay = display.init();
if(hasDisplay) {
display.flipScreenVertically();
display.setFont(ArialMT_Plain_16);
display.setTextAlignment(TEXT_ALIGN_CENTER);
}
#endif
LCD_MESSAGE("booting");
Serial.begin(115200);
while (!Serial)
{
;
}
cam.init(esp32cam_config);
IPAddress ip;
#ifdef SOFTAP_MODE
const char *hostname = "devcam";
// WiFi.hostname(hostname); // FIXME - find out why undefined
LCD_MESSAGE("starting softAP");
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
bool result = WiFi.softAP(hostname, "12345678", 1, 0);
if (!result)
{
Serial.println("AP Config failed.");
return;
}
else
{
Serial.println("AP Config Success.");
Serial.print("AP MAC: ");
Serial.println(WiFi.softAPmacAddress());
ip = WiFi.softAPIP();
}
#else
LCD_MESSAGE(String("join ") + ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(F("."));
}
ip = WiFi.localIP();
Serial.println(F("WiFi connected"));
Serial.println("");
Serial.println(ip);
#endif
LCD_MESSAGE(ip.toString());
#ifdef ENABLE_WEBSERVER
server.on("/", HTTP_GET, handle_jpg_stream);
server.on("/jpg", HTTP_GET, handle_jpg);
server.onNotFound(handleNotFound);
server.begin();
#endif
#ifdef ENABLE_RTSPSERVER
rtspServer.begin();
//streamer = new SimStreamer(true); // our streamer for UDP/TCP based RTP transport
streamer = new OV2640Streamer(cam); // our streamer for UDP/TCP based RTP transport
#endif
}
void loop()
{
#ifdef ENABLE_WEBSERVER
server.handleClient();
#endif
#ifdef ENABLE_RTSPSERVER
uint32_t msecPerFrame = 100;
static uint32_t lastimage = millis();
// If we have an active client connection, just service that until gone
streamer->handleRequests(0); // we don't use a timeout here,
// instead we send only if we have new enough frames
uint32_t now = millis();
if(streamer->anySessions()) {
if(now > lastimage + msecPerFrame || now < lastimage) { // handle clock rollover
streamer->streamImage(now);
lastimage = now;
// check if we are overrunning our max frame rate
now = millis();
if(now > lastimage + msecPerFrame) {
printf("warning exceeding max frame rate of %d ms\n", now - lastimage);
}
}
}
WiFiClient rtspClient = rtspServer.accept();
if(rtspClient) {
Serial.print("client: ");
Serial.print(rtspClient.remoteIP());
Serial.println();
streamer->addSession(rtspClient);
}
#endif
}

View File

@@ -0,0 +1,15 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:m5stack-core-esp32]
platform = espressif32@>=1.6.0
board = m5stack-core-esp32
framework = arduino
lib_deps = Micro-RTSP

View File

@@ -0,0 +1,3 @@
// copy this file to wifikeys.h and edit
const char *ssid = "YOURNETHERE"; // Put your SSID here
const char *password = "YOURPASSWORDHERE"; // Put your PASSWORD here

22
Micro-RTSP/library.json Normal file
View File

@@ -0,0 +1,22 @@
{
"name": "Micro-RTSP",
"keywords": "esp32, camera, esp32-cam, rtsp",
"description": "A small/efficient RTSP server for ESP32 and other micros",
"repository":
{
"type": "git",
"url": "https://github.com/geeksville/Micro-RTSP.git"
},
"authors":
[
{
"name": "Kevin Hester",
"email": "kevinh@geeksville.com",
"url": "https://github.com/geeksville",
"maintainer": true
}
],
"version": "0.1.6",
"frameworks": "arduino",
"platforms": "*"
}

View File

@@ -0,0 +1,9 @@
name=Micro-RTSP
version=0.1.6
author=Kevin Hester
maintainer=Kevin Hester <kevinh@geeksville.com>
sentence=Mikro RTSP server for mikros
paragraph=A small/efficient RTSP server for ESP32 and other micros
category=Data Storage
url=https://github.com/geeksville/Micro-RTSP.git
architectures=*

View File

@@ -0,0 +1,614 @@
#include "CRtspSession.h"
#include <cctype>
#include <cstdio>
#include <cstring>
#include <ctime>
//===========================================================
//===========================================================
//===========================================================
CRtspSession::CRtspSession(SOCKET aClient, CStreamer * aStreamer) : LinkedListElement(aStreamer->getClientsListHead()),
m_Client(aClient),
m_Streamer(aStreamer)
{
printf("Creating RTSP session\n");
newCommandInit();
m_RtspClient = m_Client;
m_RtspSessionID = getRandom(); // create a session ID
m_RtspSessionID |= 0x80000000;
m_StreamID = -1;
m_ClientRTPPort = 0;
m_ClientRTCPPort = 0;
m_TcpTransport = false;
m_streaming = false;
m_stopped = false;
m_RtpClientPort = 0;
m_RtcpClientPort = 0;
m_CSeq = 0; // CSeq sequense must be kept through the whole session
m_RtspCmdType = RTSP_UNKNOWN;
debug = false;
}
CRtspSession::~CRtspSession()
{
m_Streamer->ReleaseUdpTransport();
closesocket(m_RtspClient);
}
/*! @brief Initialize stuff for processing new client's command */
void CRtspSession::newCommandInit()
{
memset( m_CommandPresentationPart, 0x00, sizeof( m_CommandPresentationPart ) );
memset( m_CommandStreamPart, 0x00, sizeof( m_CommandStreamPart ) );
memset( m_CommandHostPort, 0x00, sizeof( m_CommandHostPort ) );
m_ContentLength = 0;
}
/*! @brief read numeric stuff after header name and check all possible sanity
@param buf source buffer
@param number the number
@param max_length length of buf
@return NULL if error or pointer to the rest of line
*/
static char * parse_numeric_header( char *buf, unsigned int *number, int max_length )
{
int count = max_length;
while ( *buf && count > 0 && ( *buf == ' ' || *buf == '\t' ) ) // skipping space after ':'
{
++buf;
--count;
}
if ( ! *buf || ! isdigit( *buf ) || ! count )
return NULL;
char *number_start = buf;
while( *buf && isdigit( *buf ) && count > 0 )
{
++buf;
--count;
}
if ( count == 0 )
return NULL;
char c = *buf;
*buf = '\0';
*number = atoi( number_start );
*buf = c;
return buf;
}
/*! @brief Called internally to fully parse new command from the client */
bool CRtspSession::ParseRtspRequest( char * aRequest, unsigned aRequestSize )
{
static char CmdName[20]; // used for reporting only. longest cmd is like GET_PARAMETER == 13 char
newCommandInit();
/* now our typical command will be like:
[CRLF]
SETUP rtsp://server.example.com/mjpeg/1 RTSP/1.0
CSeq: 2
Transport: RTP/AVP;unicast;something;
client_port=7000-7001;somethingelse
CRLF
but we will use a required subset from rfc2326 as per Table 2 (https://tools.ietf.org/html/rfc2326#section-10)
*/
char *cur_pos = aRequest;
int dst_pos = 0; // will reuse this to copy some parts into internal variables
// 1st doing basic sanity check and URI parsing
while ( dst_pos < 19 && *cur_pos != ' ' && *cur_pos != '\t' ) // skip possible CRLF and command name as we alredy got it in the handleRequests()
{
CmdName[ dst_pos++ ] = *(cur_pos++);
}
CmdName[ dst_pos ] = '\0';
while ( *cur_pos && isspace( *cur_pos ) )
++cur_pos;
if ( ! *cur_pos || 0 != strncasecmp( "rtsp://", cur_pos, 7 ) )
return false;
cur_pos += 7;
// getting host:port
for( dst_pos = 0; *cur_pos && ! isspace ( *cur_pos ) && *cur_pos != '/'; ++cur_pos, ++dst_pos )
{
if ( dst_pos == MAX_HOSTNAME_LEN )
return false;
m_CommandHostPort[ dst_pos ] = *cur_pos;
}
if ( *cur_pos != '/' ) // no next part
return false;
m_CommandHostPort[ dst_pos ] = '\0';
if ( debug ) printf( "host-port: %s\n", m_CommandHostPort );
while ( *cur_pos == '/' )
++cur_pos;
// getting presentation part
for( dst_pos = 0; *cur_pos && ! isspace ( *cur_pos ) && *cur_pos != '/'; ++cur_pos, ++dst_pos )
{
if ( dst_pos == RTSP_PARAM_STRING_MAX )
return false;
m_CommandPresentationPart[ dst_pos ] = *cur_pos;
}
if ( *cur_pos != '/' ) // no next part
return false;
m_CommandPresentationPart[ dst_pos ] = '\0';
if ( debug ) printf( "+ pres: %s\n", m_CommandPresentationPart );
while ( *cur_pos == '/' )
++cur_pos;
// getting stream part
for( dst_pos = 0; *cur_pos && ! isspace ( *cur_pos ) && *cur_pos != '/'; ++cur_pos, ++dst_pos )
{
if ( dst_pos == RTSP_PARAM_STRING_MAX )
return false;
m_CommandStreamPart[ dst_pos ] = *cur_pos;
}
m_CommandStreamPart[ dst_pos ] = '\0';
while ( *cur_pos == '/' ) // vlc sometimes put extra / after session name on setup
++cur_pos;
if ( *cur_pos != ' ' && *cur_pos != '\t' ) // no final RTSP/x.x
return false;
if ( debug ) printf( "+ stream: %s\n", m_CommandStreamPart );
while ( isspace( *cur_pos ) )
++cur_pos;
if ( 0 != strncmp( "RTSP/", cur_pos, 5 ) )
return false;
cur_pos += 5;
if ( ! isdigit( *cur_pos ) || cur_pos[ 1 ] != '.' || ! isdigit( cur_pos[ 2 ] ) )
return false;
cur_pos += 3;
// now looping through header lines and picking up what matter to us
int left; // rough estimate of buffer space left to examine.
// note that initial reader already put \0 mark in the buffer somewhere, so we only need to carefully check for it
if ( debug ) printf( "### analyzing headers\n" );
for(;;)
{
// skipping leftovers from previous line
while ( *cur_pos && *cur_pos != '\r' && cur_pos[ 1 ] != '\n' )
++cur_pos;
// at the end of headers block there must be CR,LF,CR,LF always, then either the body or \0
if ( ! *cur_pos || ( *cur_pos != '\r' && cur_pos[ 1 ] != '\n' ) ) // still some unexpected garbage?
return false;
cur_pos += 2; // skip CRLF
if ( ! *cur_pos ) // we're done with headers
break;
left = aRequestSize - ( cur_pos - aRequest );
// we're at the begin of the next header line now
if ( debug ) // a little window to our current line beginning
{
printf( "* left: %d: '", left );
for( char *s = cur_pos; *s && (s - cur_pos) < 20; ++s)
if( *s == '\r' )
printf ( "<CR>" );
else if( *s == '\n' )
printf ( "<LF>" );
else if ( isprint( *s ) )
putchar( *s );
else
printf( "<0x%x>", *s );
puts( "'" );
}
// now we're at the start of another header's line
if ( 0 == strncmp( "CSeq:", cur_pos, 5) )
{
unsigned new_cseq;
left -= 5;
cur_pos = parse_numeric_header( cur_pos + 5, &new_cseq, left );
if( cur_pos == NULL )
return false;
m_CSeq = new_cseq; // we may check something here or later maybe...
if ( debug ) printf( "+ got cseq: %u\n", new_cseq );
continue; // loop to next line
}
if ( 0 == strncmp( "Content-Length:", cur_pos, 15) )
{
left -= 15;
cur_pos = parse_numeric_header( cur_pos + 15, &m_ContentLength, left );
if( cur_pos == NULL )
return false;
if ( debug ) printf( "+ got cont-len: %u\n", m_ContentLength );
continue; // loop to next line
}
// for other headers we gluing continued strings together to simplify analysis
for ( char *p = cur_pos; *p; ++p )
{
// peeking past CRLF: if there is space - it is continued header line
if ( *p == '\r' && p[ 1 ] == '\n' )
{
if ( p[ 2 ] != ' ' && p[ 2 ] != '\t' ) // no space. ending search
break;
// clearing and looking for another continuation
*p = ' ';
++p;
*p = ' ';
}
}
// transport settings: proto, ports, etc
if ( m_RtspCmdType == RTSP_SETUP && 0 == strncmp( "Transport:", cur_pos, 10 ) )
{
cur_pos += 10;
while( *cur_pos && isspace( *cur_pos ) )
++cur_pos;
if ( 0 != strncmp( cur_pos, "RTP/AVP", 7) ) // std says this is mandatory part
return false;
cur_pos += 7;
if ( 0 == strncmp( cur_pos, "/TCP", 4 ) ) // TCP is also good?
{
m_TcpTransport = true;
cur_pos += 4;
}
else
m_TcpTransport = false;
if ( debug ) printf( "+ Transport is %s\n", (m_TcpTransport ? "TCP" : "UDP") );
m_ClientRTPPort = 0;
// now looking for sub-params like clent_port=
char *next_part, last_char;
for(;;)
{
while( *cur_pos == ';' || *cur_pos == ' ' || *cur_pos == '\t' )
++cur_pos;
if ( ! *cur_pos )
return false;
if ( *cur_pos == '\r' && cur_pos[ 1 ] == '\n' )
break;
next_part = strpbrk( cur_pos, ";\r" ); // gettin pointer to the next sub-param if any
if( ! next_part )
return false;
last_char = *next_part; // in case we'll need to put \0 here
if ( 0 == strncmp( cur_pos, "client_port=", 12 ) ) // "client_port" "=" port [ "-" port ]
{
char *p = ( cur_pos += 12 );
while( isdigit( *p ) )
++p;
if ( p == cur_pos )
return false;
*p = '\0';
m_ClientRTPPort = atoi( cur_pos );
m_ClientRTCPPort = m_ClientRTPPort + 1;
if ( debug ) printf( "+ got client port: %u\n", m_ClientRTPPort );
}
*next_part = last_char; // restoring if changed
cur_pos = next_part;
}
} // Transport:
if ( debug && *cur_pos != '\r' ) printf( "? unknown header ?\n" );
// ignored headers are skipped. we left current position at the CRLF so next loop is going smoothly
while ( *cur_pos && *cur_pos != '\r' )
++cur_pos;
} // loop though headers
printf( "\n+ RTSP command: %s\n", CmdName );
return true;
}
RTSP_CMD_TYPES CRtspSession::Handle_RtspRequest( char *aRequest, unsigned aRequestSize )
{
if ( ParseRtspRequest( aRequest, aRequestSize ) )
{
switch ( m_RtspCmdType )
{
case RTSP_OPTIONS: Handle_RtspOPTION(); break;
case RTSP_DESCRIBE: Handle_RtspDESCRIBE(); break;
case RTSP_SETUP: Handle_RtspSETUP(); break;
case RTSP_PLAY: Handle_RtspPLAY(); break;
default: break;
}
}
return m_RtspCmdType;
}
void CRtspSession::Handle_RtspOPTION()
{
static char Response[1024]; // Note: we assume single threaded, this large buf we keep off of the tiny stack
snprintf(Response,sizeof(Response),
"RTSP/1.0 200 OK\r\nCSeq: %u\r\n"
"Public: DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE\r\n\r\n", m_CSeq);
socketsend(m_RtspClient,Response,strlen(Response));
}
void CRtspSession::Handle_RtspDESCRIBE() // FIXME: too much redundancy. should eliminate intermediate buffers.
{
static char Response[1024]; // Note: we assume single threaded, this large buf we keep off of the tiny stack
static char SDPBuf[1024];
static char URLBuf[1024];
// check whether we know a stream with the URL which is requested
m_StreamID = -1; // invalid URL
if ( m_Streamer->getURIPresentation() == m_CommandPresentationPart &&
m_Streamer->getURIStream() == m_CommandStreamPart )
m_StreamID = 0;
if ( m_StreamID == -1 )
{ // Stream not available
snprintf( Response, sizeof(Response),
"RTSP/1.0 404 Stream Not Found\r\nCSeq: %u\r\n%s\r\n",
m_CSeq,
DateHeader());
socketsend( m_RtspClient, Response, strlen(Response) );
return;
}
// simulate DESCRIBE server response
static char OBuf[256];
char * ColonPtr;
strcpy( OBuf, m_CommandHostPort );
ColonPtr = strstr( OBuf, ":" );
if (ColonPtr != nullptr) ColonPtr[0] = 0x00;
snprintf( SDPBuf, sizeof(SDPBuf),
"v=0\r\n"
"o=- %d 1 IN IP4 %s\r\n"
"s=\r\n"
"t=0 0\r\n" // start / stop - 0 -> unbounded and permanent session
"m=video 0 RTP/AVP 26\r\n" // currently we just handle UDP sessions (??????)
// "a=x-dimensions: 640,480\r\n"
"c=IN IP4 0.0.0.0\r\n",
rand(),
OBuf );
snprintf( URLBuf, sizeof(URLBuf),
"rtsp://%s/%s/%s", m_CommandHostPort, m_CommandPresentationPart, m_CommandStreamPart );
snprintf( Response, sizeof(Response),
"RTSP/1.0 200 OK\r\nCSeq: %u\r\n"
"%s\r\n"
"Content-Base: %s/\r\n"
"Content-Type: application/sdp\r\n"
"Content-Length: %d\r\n\r\n"
"%s",
m_CSeq,
DateHeader(),
URLBuf,
(int) strlen(SDPBuf),
SDPBuf);
socketsend( m_RtspClient, Response, strlen(Response) );
}
void CRtspSession::InitTransport(u_short aRtpPort, u_short aRtcpPort)
{
m_RtpClientPort = aRtpPort;
m_RtcpClientPort = aRtcpPort;
if (!m_TcpTransport)
{ // allocate port pairs for RTP/RTCP ports in UDP transport mode
m_Streamer->InitUdpTransport();
};
};
void CRtspSession::Handle_RtspSETUP()
{
static char Response[1024];
static char Transport[255];
// init RTSP Session transport type (UDP or TCP) and ports for UDP transport
InitTransport(m_ClientRTPPort,m_ClientRTCPPort);
// simulate SETUP server response
if (m_TcpTransport)
snprintf(Transport,sizeof(Transport),"RTP/AVP/TCP;unicast;interleaved=0-1");
else
snprintf(Transport,sizeof(Transport),
"RTP/AVP;unicast;destination=127.0.0.1;source=127.0.0.1;client_port=%i-%i;server_port=%i-%i",
m_ClientRTPPort,
m_ClientRTCPPort,
m_Streamer->GetRtpServerPort(),
m_Streamer->GetRtcpServerPort());
snprintf(Response,sizeof(Response),
"RTSP/1.0 200 OK\r\nCSeq: %u\r\n"
"%s\r\n"
"Transport: %s\r\n"
"Session: %i\r\n\r\n",
m_CSeq,
DateHeader(),
Transport,
m_RtspSessionID);
socketsend(m_RtspClient,Response,strlen(Response));
}
void CRtspSession::Handle_RtspPLAY()
{
static char Response[1024];
// simulate SETUP server response
snprintf( Response, sizeof(Response),
"RTSP/1.0 200 OK\r\nCSeq: %u\r\n"
"%s\r\n"
"Range: npt=0.000-\r\n"
"Session: %i\r\n"
"RTP-Info: url=rtsp://127.0.0.1:8554/mjpeg/1/track1\r\n\r\n", // FIXME
m_CSeq,
DateHeader(),
m_RtspSessionID);
socketsend(m_RtspClient,Response,strlen(Response));
}
char const * CRtspSession::DateHeader()
{
static char buf[200];
time_t tt = time(NULL);
strftime(buf, sizeof buf, "Date: %a, %b %d %Y %H:%M:%S GMT", gmtime(&tt));
return buf;
}
int CRtspSession::GetStreamID()
{
return m_StreamID;
};
/**
Read from our socket, parsing commands as possible.
*/
bool CRtspSession::handleRequests( uint32_t readTimeoutMs )
{
if ( m_stopped )
return false; // Already closed down
static unsigned bufPos = 0; // current position into receiving buffer. used to glue split requests.
static enum { hdrStateUnknown, hdrStateGotMethod, hdrStateInvalid } state = hdrStateUnknown;
static char RecvBuf[RTSP_BUFFER_SIZE]; // Note: we assume single threaded, this large buf we keep off of the tiny stack
if ( bufPos == 0 || bufPos >= sizeof( RecvBuf ) - 1 ) // in case of bad client
{
memset( RecvBuf, 0x00, sizeof( RecvBuf ) );
bufPos = 0;
state = hdrStateUnknown;
}
// we always read 1 byte less than the buffer length, so all string ops here will not panic
int res = socketread( m_RtspClient, RecvBuf + bufPos, sizeof( RecvBuf ) - bufPos - 1, readTimeoutMs );
if ( res > 0 )
{
bufPos += res;
RecvBuf[ bufPos ] = '\0';
if ( debug ) printf( "+ read %d bytes\n", res );
if ( state == hdrStateUnknown && bufPos >= 6 ) // we need at least 4-letter at the line start with optional heading CRLF
{
if( NULL != strstr( RecvBuf, "\r\n" ) ) // got a full line
{
char *s = RecvBuf;
if ( *s == '\r' && *(s + 1) == '\n' ) // skip allowed empty line at front
s += 2;
newCommandInit();
// find out the command type
m_RtspCmdType = RTSP_UNKNOWN;
if ( strncmp( s, "OPTIONS ", 8 ) == 0 ) m_RtspCmdType = RTSP_OPTIONS;
else if ( strncmp( s, "DESCRIBE ", 9 ) == 0 ) m_RtspCmdType = RTSP_DESCRIBE;
else if ( strncmp( s, "SETUP ", 6 ) == 0 ) m_RtspCmdType = RTSP_SETUP;
else if ( strncmp( s, "PLAY ", 5 ) == 0 ) m_RtspCmdType = RTSP_PLAY;
else if ( strncmp( s, "TEARDOWN ", 9 ) == 0 ) m_RtspCmdType = RTSP_TEARDOWN;
if( m_RtspCmdType != RTSP_UNKNOWN ) // got some
state = hdrStateGotMethod;
else
state = hdrStateInvalid;
}
} // if state == hdrStateUnknown
if ( state != hdrStateUnknown ) // in all cases we need to slurp the whole header before answering
{
// per https://tools.ietf.org/html/rfc2326 we need to look for an empty line
// to be sure that we got the correctly formed header. Also starting CRLF should be ignored.
char *s = strstr( bufPos > 4 ? RecvBuf + bufPos - 4 : RecvBuf, "\r\n\r\n" ); // try to save cycles by searching in the new data only
if ( s == NULL ) // no end of header seen yet
return true;
if ( state == hdrStateInvalid ) // tossing some immediate answer, so client don't fall into endless stupor
{
// not sure which code is more appropriate and if CSeq is needed here?
int l = snprintf( RecvBuf, sizeof(RecvBuf), "RTSP/1.0 400 Bad Request\r\nCSeq: %u\r\n\r\n", m_CSeq );
socketsend( m_RtspClient, RecvBuf, l );
bufPos = 0;
return false;
}
}
RTSP_CMD_TYPES C = Handle_RtspRequest( RecvBuf, res );
if ( C == RTSP_PLAY )
m_streaming = true;
else if ( C == RTSP_TEARDOWN )
m_stopped = true;
// cleaning up
state = hdrStateUnknown;
bufPos = 0;
return true;
} // res > 0
else if ( res == 0 )
{
printf("client closed socket, exiting\n");
m_stopped = true;
return true;
}
else
{
// Timeout on read
return false;
}
}

View File

@@ -0,0 +1,80 @@
#pragma once
#include "LinkedListElement.h"
#include "CStreamer.h"
#include "platglue.h"
// supported command types
enum RTSP_CMD_TYPES
{
RTSP_OPTIONS,
RTSP_DESCRIBE,
RTSP_SETUP,
RTSP_PLAY,
RTSP_TEARDOWN,
RTSP_UNKNOWN
};
#define RTSP_BUFFER_SIZE 10000 // for incoming requests, and outgoing responses
#define RTSP_PARAM_STRING_MAX 200
#define MAX_HOSTNAME_LEN 256
class CRtspSession : public LinkedListElement
{
public:
CRtspSession( SOCKET aRtspClient, CStreamer * aStreamer );
~CRtspSession();
RTSP_CMD_TYPES Handle_RtspRequest( char *aRequest, unsigned aRequestSize );
int GetStreamID();
/**
Read from our socket, parsing commands as possible.
return false if the read timed out
*/
bool handleRequests(uint32_t readTimeoutMs);
bool m_streaming;
bool m_stopped;
void InitTransport(u_short aRtpPort, u_short aRtcpPort);
bool isTcpTransport() { return m_TcpTransport; }
SOCKET& getClient() { return m_RtspClient; }
uint16_t getRtpClientPort() { return m_RtpClientPort; }
bool debug; /// set to true to get a load of output
private:
void newCommandInit();
bool ParseRtspRequest( char * aRequest, unsigned aRequestSize );
char const * DateHeader();
// RTSP request command handlers
void Handle_RtspOPTION();
void Handle_RtspDESCRIBE();
void Handle_RtspSETUP();
void Handle_RtspPLAY();
// global session state parameters
int m_RtspSessionID;
SOCKET m_Client;
SOCKET m_RtspClient; /// RTSP socket of that session
int m_StreamID; /// number of simulated stream of that session
IPPORT m_ClientRTPPort; /// client port for UDP based RTP transport
IPPORT m_ClientRTCPPort; /// client port for UDP based RTCP transport
bool m_TcpTransport; /// if Tcp based streaming was activated
CStreamer * m_Streamer; /// the UDP or TCP streamer of that session
// parameters of the last received RTSP request
RTSP_CMD_TYPES m_RtspCmdType; /// command type (if any) of the current request
char m_CommandPresentationPart[RTSP_PARAM_STRING_MAX]; /// stream name pre suffix
char m_CommandStreamPart[RTSP_PARAM_STRING_MAX]; /// stream name suffix
char m_CommandHostPort[MAX_HOSTNAME_LEN]; /// host:port part of the URL
unsigned m_CSeq; /// RTSP command sequence number
unsigned m_ContentLength; /// SDP string size
uint16_t m_RtpClientPort; // RTP receiver port on client (in host byte order!)
uint16_t m_RtcpClientPort; // RTCP receiver port on client (in host byte order!)
};

View File

@@ -0,0 +1,427 @@
#include "CStreamer.h"
#include "CRtspSession.h"
#include <stdio.h>
CStreamer::CStreamer(u_short width, u_short height) : m_Clients()
{
printf("Creating TSP streamer\n");
m_RtpServerPort = 0;
m_RtcpServerPort = 0;
m_SequenceNumber = 0;
m_Timestamp = 0;
m_SendIdx = 0;
m_RtpSocket = NULLSOCKET;
m_RtcpSocket = NULLSOCKET;
m_width = width;
m_height = height;
m_prevMsec = 0;
m_udpRefCount = 0;
debug = false;
m_URIHost = "127.0.0.1:554";
m_URIPresentation = "mjpeg";
m_URIStream = "1";
}
CStreamer::~CStreamer()
{
LinkedListElement* element = m_Clients.m_Next;
CRtspSession* session = NULL;
while (element != &m_Clients)
{
session = static_cast<CRtspSession*>(element);
element = element->m_Next;
delete session;
}
};
CRtspSession* CStreamer::addSession( SOCKET aClient )
{
// if ( debug ) printf("CStreamer::addSession\n");
CRtspSession* session = new CRtspSession( aClient, this ); // our threads RTSP session and state
// we have it stored in m_Clients
session->debug = debug;
return session;
}
void CStreamer::setURI( String hostport, String pres, String stream ) // set URI parts for sessions to use.
{
m_URIHost = hostport;
m_URIPresentation = pres;
m_URIStream = stream;
}
int CStreamer::SendRtpPacket(unsigned const char * jpeg, int jpegLen, int fragmentOffset, BufPtr quant0tbl, BufPtr quant1tbl)
{
// if ( debug ) printf("CStreamer::SendRtpPacket offset:%d - begin\n", fragmentOffset);
#define KRtpHeaderSize 12 // size of the RTP header
#define KJpegHeaderSize 8 // size of the special JPEG payload header
#define MAX_FRAGMENT_SIZE 1100 // FIXME, pick more carefully
int fragmentLen = MAX_FRAGMENT_SIZE;
if(fragmentLen + fragmentOffset > jpegLen) // Shrink last fragment if needed
fragmentLen = jpegLen - fragmentOffset;
bool isLastFragment = (fragmentOffset + fragmentLen) == jpegLen;
if (!m_Clients.NotEmpty())
{
return isLastFragment ? 0 : fragmentOffset;
}
// Do we have custom quant tables? If so include them per RFC
bool includeQuantTbl = quant0tbl && quant1tbl && fragmentOffset == 0;
uint8_t q = includeQuantTbl ? 128 : 0x5e;
static char RtpBuf[2048]; // Note: we assume single threaded, this large buf we keep off of the tiny stack
int RtpPacketSize = fragmentLen + KRtpHeaderSize + KJpegHeaderSize + (includeQuantTbl ? (4 + 64 * 2) : 0);
memset(RtpBuf,0x00,sizeof(RtpBuf));
// Prepare the first 4 byte of the packet. This is the Rtp over Rtsp header in case of TCP based transport
RtpBuf[0] = '$'; // magic number
RtpBuf[1] = 0; // number of multiplexed subchannel on RTPS connection - here the RTP channel
RtpBuf[2] = (RtpPacketSize & 0x0000FF00) >> 8;
RtpBuf[3] = (RtpPacketSize & 0x000000FF);
// Prepare the 12 byte RTP header
RtpBuf[4] = 0x80; // RTP version
RtpBuf[5] = 0x1a | (isLastFragment ? 0x80 : 0x00); // JPEG payload (26) and marker bit
RtpBuf[7] = m_SequenceNumber & 0x0FF; // each packet is counted with a sequence counter
RtpBuf[6] = m_SequenceNumber >> 8;
RtpBuf[8] = (m_Timestamp & 0xFF000000) >> 24; // each image gets a timestamp
RtpBuf[9] = (m_Timestamp & 0x00FF0000) >> 16;
RtpBuf[10] = (m_Timestamp & 0x0000FF00) >> 8;
RtpBuf[11] = (m_Timestamp & 0x000000FF);
RtpBuf[12] = 0x13; // 4 byte SSRC (sychronization source identifier)
RtpBuf[13] = 0xf9; // we just an arbitrary number here to keep it simple
RtpBuf[14] = 0x7e;
RtpBuf[15] = 0x67;
// Prepare the 8 byte payload JPEG header
RtpBuf[16] = 0x00; // type specific
RtpBuf[17] = (fragmentOffset & 0x00FF0000) >> 16; // 3 byte fragmentation offset for fragmented images
RtpBuf[18] = (fragmentOffset & 0x0000FF00) >> 8;
RtpBuf[19] = (fragmentOffset & 0x000000FF);
/* These sampling factors indicate that the chrominance components of
type 0 video is downsampled horizontally by 2 (often called 4:2:2)
while the chrominance components of type 1 video are downsampled both
horizontally and vertically by 2 (often called 4:2:0). */
RtpBuf[20] = 0x00; // type (fixme might be wrong for camera data) https://tools.ietf.org/html/rfc2435
RtpBuf[21] = q; // quality scale factor was 0x5e
RtpBuf[22] = m_width / 8; // width / 8
RtpBuf[23] = m_height / 8; // height / 8
int headerLen = 24; // Inlcuding jpeg header but not qant table header
if(includeQuantTbl) { // we need a quant header - but only in first packet of the frame
//if ( debug ) printf("inserting quanttbl\n");
RtpBuf[24] = 0; // MBZ
RtpBuf[25] = 0; // 8 bit precision
RtpBuf[26] = 0; // MSB of lentgh
int numQantBytes = 64; // Two 64 byte tables
RtpBuf[27] = 2 * numQantBytes; // LSB of length
headerLen += 4;
memcpy(RtpBuf + headerLen, quant0tbl, numQantBytes);
headerLen += numQantBytes;
memcpy(RtpBuf + headerLen, quant1tbl, numQantBytes);
headerLen += numQantBytes;
}
// if ( debug ) printf("Sending timestamp %d, seq %d, fragoff %d, fraglen %d, jpegLen %d\n", m_Timestamp, m_SequenceNumber, fragmentOffset, fragmentLen, jpegLen);
// append the JPEG scan data to the RTP buffer
memcpy(RtpBuf + headerLen,jpeg + fragmentOffset, fragmentLen);
fragmentOffset += fragmentLen;
m_SequenceNumber++; // prepare the packet counter for the next packet
IPADDRESS otherip;
IPPORT otherport;
// RTP marker bit must be set on last fragment
LinkedListElement* element = m_Clients.m_Next;
CRtspSession* session = NULL;
while (element != &m_Clients)
{
session = static_cast<CRtspSession*>(element);
if (session->m_streaming && !session->m_stopped) {
if (session->isTcpTransport()) // RTP over RTSP - we send the buffer + 4 byte additional header
socketsend(session->getClient(),RtpBuf,RtpPacketSize + 4);
else // UDP - we send just the buffer by skipping the 4 byte RTP over RTSP header
{
socketpeeraddr(session->getClient(), &otherip, &otherport);
udpsocketsend(m_RtpSocket,&RtpBuf[4],RtpPacketSize, otherip, session->getRtpClientPort());
}
}
element = element->m_Next;
}
// if ( debug ) printf("CStreamer::SendRtpPacket offset:%d - end\n", fragmentOffset);
return isLastFragment ? 0 : fragmentOffset;
};
u_short CStreamer::GetRtpServerPort()
{
return m_RtpServerPort;
};
u_short CStreamer::GetRtcpServerPort()
{
return m_RtcpServerPort;
};
bool CStreamer::InitUdpTransport(void)
{
if (m_udpRefCount != 0)
{
++m_udpRefCount;
return true;
}
for (u_short P = 6970; P < 0xFFFE; P += 2)
{
m_RtpSocket = udpsocketcreate(P);
if (m_RtpSocket)
{ // Rtp socket was bound successfully. Lets try to bind the consecutive Rtsp socket
m_RtcpSocket = udpsocketcreate(P + 1);
if (m_RtcpSocket)
{
m_RtpServerPort = P;
m_RtcpServerPort = P+1;
break;
}
else
{
udpsocketclose(m_RtpSocket);
udpsocketclose(m_RtcpSocket);
};
}
};
++m_udpRefCount;
return true;
}
void CStreamer::ReleaseUdpTransport(void)
{
--m_udpRefCount;
if (m_udpRefCount == 0)
{
m_RtpServerPort = 0;
m_RtcpServerPort = 0;
udpsocketclose(m_RtpSocket);
udpsocketclose(m_RtcpSocket);
m_RtpSocket = NULLSOCKET;
m_RtcpSocket = NULLSOCKET;
}
}
/**
Call handleRequests on all sessions
*/
bool CStreamer::handleRequests(uint32_t readTimeoutMs)
{
bool retVal = true;
LinkedListElement* element = m_Clients.m_Next;
while(element != &m_Clients)
{
CRtspSession* session = static_cast<CRtspSession*>(element);
retVal &= session->handleRequests(readTimeoutMs);
element = element->m_Next;
if (session->m_stopped)
{
// remove session here, so we wont have to send to it
delete session;
}
}
return retVal;
}
void CStreamer::streamFrame(unsigned const char *data, uint32_t dataLen, uint32_t curMsec)
{
if(m_prevMsec == 0) // first frame init our timestamp
m_prevMsec = curMsec;
// compute deltat (being careful to handle clock rollover with a little lie)
uint32_t deltams = (curMsec >= m_prevMsec) ? curMsec - m_prevMsec : 100;
m_prevMsec = curMsec;
// locate quant tables if possible
BufPtr qtable0, qtable1;
if(!decodeJPEGfile(&data, &dataLen, &qtable0, &qtable1)) {
printf("can't decode jpeg data\n");
return;
}
int offset = 0;
do {
offset = SendRtpPacket(data, dataLen, offset, qtable0, qtable1);
} while(offset != 0);
// Increment ONLY after a full frame
uint32_t units = 90000; // Hz per RFC 2435
m_Timestamp += (units * deltams / 1000); // fixed timestamp increment for a frame rate of 25fps
m_SendIdx++;
if (m_SendIdx > 1) m_SendIdx = 0;
};
#include <assert.h>
// search for a particular JPEG marker, moves *start to just after that marker
// This function fixes up the provided start ptr to point to the
// actual JPEG stream data and returns the number of bytes skipped
// APP0 e0
// DQT db
// DQT db
// DHT c4
// DHT c4
// DHT c4
// DHT c4
// SOF0 c0 baseline (not progressive) 3 color 0x01 Y, 0x21 2h1v, 0x00 tbl0
// - 0x02 Cb, 0x11 1h1v, 0x01 tbl1 - 0x03 Cr, 0x11 1h1v, 0x01 tbl1
// therefore 4:2:2, with two separate quant tables (0 and 1)
// SOS da
// EOI d9 (no need to strip data after this RFC says client will discard)
bool findJPEGheader(BufPtr *start, uint32_t *len, uint8_t marker) {
// per https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format
unsigned const char *bytes = *start;
// kinda skanky, will break if unlucky and the headers inxlucde 0xffda
// might fall off array if jpeg is invalid
// FIXME - return false instead
while(bytes - *start < *len) {
uint8_t framing = *bytes++; // better be 0xff
if(framing != 0xff) {
printf("malformed jpeg, framing=%x\n", framing);
return false;
}
uint8_t typecode = *bytes++;
if(typecode == marker) {
unsigned skipped = bytes - *start;
//if ( debug ) printf("found marker 0x%x, skipped %d\n", marker, skipped);
*start = bytes;
// shrink len for the bytes we just skipped
*len -= skipped;
return true;
}
else {
// not the section we were looking for, skip the entire section
switch(typecode) {
case 0xd8: // start of image
{
break; // no data to skip
}
case 0xe0: // app0
case 0xdb: // dqt
case 0xc4: // dht
case 0xc0: // sof0
case 0xda: // sos
{
// standard format section with 2 bytes for len. skip that many bytes
uint32_t len = bytes[0] * 256 + bytes[1];
//if ( debug ) printf("skipping section 0x%x, %d bytes\n", typecode, len);
bytes += len;
break;
}
default:
printf("unexpected jpeg typecode 0x%x\n", typecode);
break;
}
}
}
printf("failed to find jpeg marker 0x%x", marker);
return false;
}
// the scan data uses byte stuffing to guarantee anything that starts with 0xff
// followed by something not zero, is a new section. Look for that marker and return the ptr
// pointing there
void skipScanBytes(BufPtr *start) {
BufPtr bytes = *start;
while(true) { // FIXME, check against length
while(*bytes++ != 0xff);
if(*bytes++ != 0) {
*start = bytes - 2; // back up to the 0xff marker we just found
return;
}
}
}
void nextJpegBlock(BufPtr *bytes) {
uint32_t len = (*bytes)[0] * 256 + (*bytes)[1];
//if ( debug ) printf("going to next jpeg block %d bytes\n", len);
*bytes += len;
}
// When JPEG is stored as a file it is wrapped in a container
// This function fixes up the provided start ptr to point to the
// actual JPEG stream data and returns the number of bytes skipped
bool decodeJPEGfile(BufPtr *start, uint32_t *len, BufPtr *qtable0, BufPtr *qtable1) {
// per https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format
unsigned const char *bytes = *start;
if(!findJPEGheader(&bytes, len, 0xd8)) // better at least look like a jpeg file
return false; // FAILED!
// Look for quant tables if they are present
*qtable0 = NULL;
*qtable1 = NULL;
BufPtr quantstart = *start;
uint32_t quantlen = *len;
if(!findJPEGheader(&quantstart, &quantlen, 0xdb)) {
printf("error can't find quant table 0\n");
}
else {
// if ( debug ) printf("found quant table %x\n", quantstart[2]);
*qtable0 = quantstart + 3; // 3 bytes of header skipped
nextJpegBlock(&quantstart);
if(!findJPEGheader(&quantstart, &quantlen, 0xdb)) {
printf("error can't find quant table 1\n");
}
else {
// if ( debug ) printf("found quant table %x\n", quantstart[2]);
}
*qtable1 = quantstart + 3;
nextJpegBlock(&quantstart);
}
if(!findJPEGheader(start, len, 0xda))
return false; // FAILED!
// Skip the header bytes of the SOS marker FIXME why doesn't this work?
uint32_t soslen = (*start)[0] * 256 + (*start)[1];
*start += soslen;
*len -= soslen;
// start scanning the data portion of the scan to find the end marker
BufPtr endmarkerptr = *start;
uint32_t endlen = *len;
skipScanBytes(&endmarkerptr);
if(!findJPEGheader(&endmarkerptr, &endlen, 0xd9))
return false; // FAILED!
// endlen must now be the # of bytes between the start of our scan and
// the end marker, tell the caller to ignore bytes afterwards
*len = endmarkerptr - *start;
return true;
}

View File

@@ -0,0 +1,77 @@
#pragma once
#include "platglue.h"
#include "LinkedListElement.h"
typedef unsigned const char *BufPtr;
class CRtspSession;
class CStreamer
{
public:
CStreamer( u_short width, u_short height );
virtual ~CStreamer();
CRtspSession *addSession( SOCKET aClient );
LinkedListElement* getClientsListHead() { return &m_Clients; }
int anySessions() { return m_Clients.NotEmpty(); }
bool handleRequests(uint32_t readTimeoutMs);
u_short GetRtpServerPort();
u_short GetRtcpServerPort();
virtual void streamImage(uint32_t curMsec) = 0; // send a new image to the client
bool InitUdpTransport(void);
void ReleaseUdpTransport(void);
bool debug;
void setURI( String hostport, String pres = "mjpeg", String stream = "1" ); // set URI parts for sessions to use.
String getURIHost(){ return m_URIHost; }; // for getting things back by sessions
String getURIPresentation(){ return m_URIPresentation; };
String getURIStream(){ return m_URIStream; };
protected:
void streamFrame(unsigned const char *data, uint32_t dataLen, uint32_t curMsec);
String m_URIHost; // Host:port URI part that client should use to connect. also it is reported in session answers where appropriate.
String m_URIPresentation; // name of presentation part of URI. sessions will check if client used correct one
String m_URIStream; // stream part of the URI.
private:
int SendRtpPacket(unsigned const char *jpeg, int jpegLen, int fragmentOffset, BufPtr quant0tbl = NULL, BufPtr quant1tbl = NULL);// returns new fragmentOffset or 0 if finished with frame
UDPSOCKET m_RtpSocket; // RTP socket for streaming RTP packets to client
UDPSOCKET m_RtcpSocket; // RTCP socket for sending/receiving RTCP packages
IPPORT m_RtpServerPort; // RTP sender port on server
IPPORT m_RtcpServerPort; // RTCP sender port on server
u_short m_SequenceNumber;
uint32_t m_Timestamp;
int m_SendIdx;
LinkedListElement m_Clients;
uint32_t m_prevMsec;
int m_udpRefCount;
u_short m_width; // image data info
u_short m_height;
};
// When JPEG is stored as a file it is wrapped in a container
// This function fixes up the provided start ptr to point to the
// actual JPEG stream data and returns the number of bytes skipped
// returns true if the file seems to be valid jpeg
// If quant tables can be found they will be stored in qtable0/1
bool decodeJPEGfile(BufPtr *start, uint32_t *len, BufPtr *qtable0, BufPtr *qtable1);
bool findJPEGheader(BufPtr *start, uint32_t *len, uint8_t marker);
// Given a jpeg ptr pointing to a pair of length bytes, advance the pointer to
// the next 0xff marker byte
void nextJpegBlock(BufPtr *start);

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
#pragma once
#ifndef ARDUINO_ARCH_ESP32
#define INCLUDE_SIMDATA
#endif
#ifdef INCLUDE_SIMDATA
extern unsigned const char capture_jpg[];
extern unsigned const char octo_jpg[];
extern unsigned int octo_jpg_len, capture_jpg_len;
#endif

View File

@@ -0,0 +1,43 @@
#pragma once
#include "platglue.h"
#include <stdio.h>
class LinkedListElement
{
public:
LinkedListElement* m_Next;
LinkedListElement* m_Prev;
LinkedListElement(void)
{
m_Next = this;
m_Prev = this;
printf("LinkedListElement (%p)->(%p)->(%p)\n", m_Prev, this, m_Next);
}
int NotEmpty(void)
{
return (m_Next != this);
}
LinkedListElement(LinkedListElement* linkedList)
{
// add to the end of list
m_Prev = linkedList->m_Prev;
linkedList->m_Prev = this;
m_Prev->m_Next = this;
m_Next = linkedList;
printf("LinkedListElement (%p)->(%p)->(%p)\n", m_Prev, this, m_Next);
}
~LinkedListElement()
{
printf("~LinkedListElement(%p)->(%p)->(%p)\n", m_Prev, this, m_Next);
if (m_Next)
m_Next->m_Prev = m_Prev;
if (m_Prev)
m_Prev->m_Next = m_Next;
printf("~LinkedListElement after: (%p)->(%p)", m_Prev, m_Prev->m_Next);
}
};

201
Micro-RTSP/src/OV2640.cpp Normal file
View File

@@ -0,0 +1,201 @@
#include "OV2640.h"
#define TAG "OV2640"
// definitions appropriate for the ESP32-CAM devboard (and most clones)
camera_config_t esp32cam_config{
.pin_pwdn = -1, // FIXME: on the TTGO T-Journal I think this is GPIO 0
.pin_reset = 15,
.pin_xclk = 27,
.pin_sscb_sda = 25,
.pin_sscb_scl = 23,
.pin_d7 = 19,
.pin_d6 = 36,
.pin_d5 = 18,
.pin_d4 = 39,
.pin_d3 = 5,
.pin_d2 = 34,
.pin_d1 = 35,
.pin_d0 = 17,
.pin_vsync = 22,
.pin_href = 26,
.pin_pclk = 21,
.xclk_freq_hz = 20000000,
.ledc_timer = LEDC_TIMER_0,
.ledc_channel = LEDC_CHANNEL_0,
.pixel_format = PIXFORMAT_JPEG,
// .frame_size = FRAMESIZE_UXGA, // needs 234K of framebuffer space
// .frame_size = FRAMESIZE_SXGA, // needs 160K for framebuffer
// .frame_size = FRAMESIZE_XGA, // needs 96K or even smaller FRAMESIZE_SVGA - can work if using only 1 fb
.frame_size = FRAMESIZE_SVGA,
.jpeg_quality = 12, //0-63 lower numbers are higher quality
.fb_count = 2 // if more than one i2s runs in continous mode. Use only with jpeg
};
camera_config_t esp32cam_aithinker_config{
.pin_pwdn = 32,
.pin_reset = -1,
.pin_xclk = 0,
.pin_sscb_sda = 26,
.pin_sscb_scl = 27,
// Note: LED GPIO is apparently 4 not sure where that goes
// per https://github.com/donny681/ESP32_CAMERA_QR/blob/e4ef44549876457cd841f33a0892c82a71f35358/main/led.c
.pin_d7 = 35,
.pin_d6 = 34,
.pin_d5 = 39,
.pin_d4 = 36,
.pin_d3 = 21,
.pin_d2 = 19,
.pin_d1 = 18,
.pin_d0 = 5,
.pin_vsync = 25,
.pin_href = 23,
.pin_pclk = 22,
.xclk_freq_hz = 20000000,
.ledc_timer = LEDC_TIMER_1,
.ledc_channel = LEDC_CHANNEL_1,
.pixel_format = PIXFORMAT_JPEG,
// .frame_size = FRAMESIZE_UXGA, // needs 234K of framebuffer space
// .frame_size = FRAMESIZE_SXGA, // needs 160K for framebuffer
// .frame_size = FRAMESIZE_XGA, // needs 96K or even smaller FRAMESIZE_SVGA - can work if using only 1 fb
.frame_size = FRAMESIZE_SVGA,
.jpeg_quality = 12, //0-63 lower numbers are higher quality
.fb_count = 2 // if more than one i2s runs in continous mode. Use only with jpeg
};
camera_config_t esp32cam_ttgo_t_config{
.pin_pwdn = 26,
.pin_reset = -1,
.pin_xclk = 32,
.pin_sscb_sda = 13,
.pin_sscb_scl = 12,
.pin_d7 = 39,
.pin_d6 = 36,
.pin_d5 = 23,
.pin_d4 = 18,
.pin_d3 = 15,
.pin_d2 = 4,
.pin_d1 = 14,
.pin_d0 = 5,
.pin_vsync = 27,
.pin_href = 25,
.pin_pclk = 19,
.xclk_freq_hz = 20000000,
.ledc_timer = LEDC_TIMER_0,
.ledc_channel = LEDC_CHANNEL_0,
.pixel_format = PIXFORMAT_JPEG,
.frame_size = FRAMESIZE_SVGA,
.jpeg_quality = 12, //0-63 lower numbers are higher quality
.fb_count = 2 // if more than one i2s runs in continous mode. Use only with jpeg
};
void OV2640::done(void)
{
if (fb) {
//return the frame buffer back to the driver for reuse
esp_camera_fb_return(fb);
fb = NULL;
}
}
void OV2640::run(void)
{
if (fb)
//return the frame buffer back to the driver for reuse
esp_camera_fb_return(fb);
fb = esp_camera_fb_get();
}
void OV2640::runIfNeeded(void)
{
if (!fb)
run();
}
int OV2640::getWidth(void)
{
runIfNeeded();
return fb->width;
}
int OV2640::getHeight(void)
{
runIfNeeded();
return fb->height;
}
size_t OV2640::getSize(void)
{
runIfNeeded();
if (!fb)
return 0; // FIXME - this shouldn't be possible but apparently the new cam board returns null sometimes?
return fb->len;
}
uint8_t *OV2640::getfb(void)
{
runIfNeeded();
if (!fb)
return NULL; // FIXME - this shouldn't be possible but apparently the new cam board returns null sometimes?
return fb->buf;
}
framesize_t OV2640::getFrameSize(void)
{
return _cam_config.frame_size;
}
void OV2640::setFrameSize(framesize_t size)
{
_cam_config.frame_size = size;
}
pixformat_t OV2640::getPixelFormat(void)
{
return _cam_config.pixel_format;
}
void OV2640::setPixelFormat(pixformat_t format)
{
switch (format)
{
case PIXFORMAT_RGB565:
case PIXFORMAT_YUV422:
case PIXFORMAT_GRAYSCALE:
case PIXFORMAT_JPEG:
_cam_config.pixel_format = format;
break;
default:
_cam_config.pixel_format = PIXFORMAT_GRAYSCALE;
break;
}
}
esp_err_t OV2640::init(camera_config_t config)
{
memset(&_cam_config, 0, sizeof(_cam_config));
memcpy(&_cam_config, &config, sizeof(config));
esp_err_t err = esp_camera_init(&_cam_config);
if (err != ESP_OK)
{
printf("Camera probe failed with error 0x%x", err);
return err;
}
// ESP_ERROR_CHECK(gpio_install_isr_service(0));
return ESP_OK;
}

44
Micro-RTSP/src/OV2640.h Normal file
View File

@@ -0,0 +1,44 @@
#ifndef OV2640_H_
#define OV2640_H_
#include <Arduino.h>
#include <pgmspace.h>
#include <stdio.h>
#include "esp_log.h"
#include "esp_attr.h"
#include "esp_camera.h"
extern camera_config_t esp32cam_config, esp32cam_aithinker_config, esp32cam_ttgo_t_config;
class OV2640
{
public:
OV2640(){
fb = NULL;
};
~OV2640(){
};
esp_err_t init(camera_config_t config);
void done(void);
void run(void);
size_t getSize(void);
uint8_t *getfb(void);
int getWidth(void);
int getHeight(void);
framesize_t getFrameSize(void);
pixformat_t getPixelFormat(void);
void setFrameSize(framesize_t size);
void setPixelFormat(pixformat_t format);
private:
void runIfNeeded(); // grab a frame if we don't already have one
// camera_framesize_t _frame_size;
// camera_pixelformat_t _pixel_format;
camera_config_t _cam_config;
camera_fb_t *fb;
};
#endif //OV2640_H_

View File

@@ -0,0 +1,19 @@
#include "OV2640Streamer.h"
#include <assert.h>
OV2640Streamer::OV2640Streamer(OV2640 *cam) : CStreamer(cam->getWidth(), cam->getHeight()), m_cam(cam)
{
printf("Created streamer width=%d, height=%d\n", cam->getWidth(), cam->getHeight());
}
void OV2640Streamer::streamImage(uint32_t curMsec)
{
m_cam->run();// queue up a read for next time
BufPtr bytes = m_cam->getfb();
streamFrame(bytes, m_cam->getSize(), curMsec);
m_cam->done();
}

View File

@@ -0,0 +1,15 @@
#pragma once
#include "CStreamer.h"
#include "OV2640.h"
class OV2640Streamer : public CStreamer
{
bool m_showBig;
OV2640 *m_cam;
public:
OV2640Streamer(OV2640 *cam);
virtual void streamImage(uint32_t curMsec);
};

View File

@@ -0,0 +1,28 @@
#include "SimStreamer.h"
#include "JPEGSamples.h"
#ifdef INCLUDE_SIMDATA
SimStreamer::SimStreamer(bool showBig) : CStreamer(showBig ? 800 : 640, showBig ? 600 : 480)
{
m_showBig = showBig;
}
void SimStreamer::streamImage(uint32_t curMsec)
{
if(m_showBig) {
BufPtr bytes = capture_jpg;
uint32_t len = capture_jpg_len;
streamFrame(bytes, len, curMsec);
}
else {
BufPtr bytes = octo_jpg;
uint32_t len = octo_jpg_len;
streamFrame(bytes, len, curMsec);
}
}
#endif

View File

@@ -0,0 +1,15 @@
#pragma once
#include "JPEGSamples.h"
#include "CStreamer.h"
#ifdef INCLUDE_SIMDATA
class SimStreamer : public CStreamer
{
bool m_showBig;
public:
SimStreamer(bool showBig);
virtual void streamImage(uint32_t curMsec);
};
#endif

View File

@@ -0,0 +1,107 @@
#pragma once
#include <Arduino.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include <sys/socket.h>
#include <netinet/in.h>
//#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
typedef WiFiClient *SOCKET;
typedef WiFiUDP *UDPSOCKET;
typedef IPAddress IPADDRESS; // On linux use uint32_t in network byte order (per getpeername)
typedef uint16_t IPPORT; // on linux use network byte order
#define NULLSOCKET NULL
inline void closesocket(SOCKET s) {
printf("closing TCP socket\n");
if(s) {
s->stop();
// delete s; TDP WiFiClients are never on the heap in arduino land?
}
}
#define getRandom() random(65536)
inline void socketpeeraddr(SOCKET s, IPADDRESS *addr, IPPORT *port) {
*addr = s->remoteIP();
*port = s->remotePort();
}
inline void udpsocketclose(UDPSOCKET s) {
printf("closing UDP socket\n");
if(s) {
s->stop();
delete s;
}
}
inline UDPSOCKET udpsocketcreate(unsigned short portNum)
{
UDPSOCKET s = new WiFiUDP();
if(!s->begin(portNum)) {
printf("Can't bind port %d\n", portNum);
delete s;
return NULL;
}
return s;
}
// TCP sending
inline ssize_t socketsend(SOCKET sockfd, const void *buf, size_t len)
{
return sockfd->write((uint8_t *) buf, len);
}
inline ssize_t udpsocketsend(UDPSOCKET sockfd, const void *buf, size_t len,
IPADDRESS destaddr, IPPORT destport)
{
sockfd->beginPacket(destaddr, destport);
sockfd->write((const uint8_t *) buf, len);
if(!sockfd->endPacket())
printf("error sending udp packet\n");
return len;
}
/**
Read from a socket with a timeout.
Return 0=socket was closed by client, -1=timeout, >0 number of bytes read
*/
inline int socketread(SOCKET sock, char *buf, size_t buflen, int timeoutmsec)
{
if(!sock->connected()) {
printf("client has closed the socket\n");
return 0;
}
int numAvail = sock->available();
if(numAvail == 0 && timeoutmsec != 0) {
// sleep and hope for more
delay(timeoutmsec);
numAvail = sock->available();
}
if(numAvail == 0) {
// printf("timeout on read\n");
return -1;
}
else {
// int numRead = sock->readBytesUntil('\n', buf, buflen);
int numRead = sock->readBytes(buf, buflen);
// printf("bytes avail %d, read %d: %s", numAvail, numRead, buf);
return numRead;
}
}

View File

@@ -0,0 +1,94 @@
/**
* @author Marco Garzola
*/
#pragma once
#include "mbed.h"
typedef TCPSocket* SOCKET;
typedef UDPSocket* UDPSOCKET;
typedef SocketAddress IPADDRESS;
typedef uint16_t IPPORT;
#define SEND_TMEOUT_MS 1000
#define NULLSOCKET NULL
inline void closesocket(SOCKET s)
{
if (s)
{
s->close();
}
}
#define getRandom() rand()
inline void socketpeeraddr(SOCKET s, IPADDRESS* addr, IPPORT* port)
{
s->getpeername(addr);
*port = addr->get_port();
}
inline UDPSOCKET udpsocketcreate(unsigned short portNum)
{
UDPSOCKET s = new UDPSocket();
if (s->open(NetworkInterface::get_default_instance()) != 0 && s->bind(portNum) != 0)
{
printf("Can't bind port %d\n", portNum);
delete s;
return nullptr;
}
return s;
}
inline void udpsocketclose(UDPSOCKET s)
{
if (s)
{
s->close();
delete s;
}
}
inline ssize_t
udpsocketsend(UDPSOCKET sockfd, const void* buf, size_t len, IPADDRESS destaddr, uint16_t destport)
{
if (sockfd)
{
return sockfd->sendto(destaddr.get_ip_address(), destport, buf, len);
}
else
{
return 0;
}
}
// TCP sending
inline ssize_t socketsend(SOCKET sockfd, const void* buf, size_t len)
{
if (sockfd && buf)
{
sockfd->set_blocking(true);
sockfd->set_timeout(SEND_TMEOUT_MS);
return sockfd->send(buf, len);
}
else
{
return 0;
}
}
inline int socketread(SOCKET sock, char* buf, size_t buflen, int timeoutmsec)
{
if (sock && buf)
{
sock->set_blocking(true);
sock->set_timeout(timeoutmsec);
return sock->recv(buf, buflen);
}
else
{
return -1;
}
}

View File

@@ -0,0 +1,114 @@
#pragma once
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <string>
typedef std::string String;
typedef int SOCKET;
typedef int UDPSOCKET;
typedef uint32_t IPADDRESS; // On linux use uint32_t in network byte order (per getpeername)
typedef uint16_t IPPORT; // on linux use network byte order
#define NULLSOCKET 0
inline void closesocket(SOCKET s) {
close(s);
}
#define getRandom() rand()
inline void socketpeeraddr(SOCKET s, IPADDRESS *addr, IPPORT *port) {
sockaddr_in r;
socklen_t len = sizeof(r);
if(getpeername(s,(struct sockaddr*)&r,&len) < 0) {
printf("getpeername failed\n");
*addr = 0;
*port = 0;
}
else {
//htons
*port = r.sin_port;
*addr = r.sin_addr.s_addr;
}
}
inline void udpsocketclose(UDPSOCKET s) {
close(s);
}
inline UDPSOCKET udpsocketcreate(unsigned short portNum)
{
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
int s = socket(AF_INET, SOCK_DGRAM, 0);
addr.sin_port = htons(portNum);
if (bind(s,(sockaddr*)&addr,sizeof(addr)) != 0) {
printf("Error, can't bind\n");
close(s);
s = 0;
}
return s;
}
// TCP sending
inline ssize_t socketsend(SOCKET sockfd, const void *buf, size_t len)
{
// printf("TCP send\n");
return send(sockfd, buf, len, 0);
}
inline ssize_t udpsocketsend(UDPSOCKET sockfd, const void *buf, size_t len,
IPADDRESS destaddr, uint16_t destport)
{
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = destaddr;
addr.sin_port = htons(destport);
//printf("UDP send to 0x%0x:%0x\n", destaddr, destport);
return sendto(sockfd, buf, len, 0, (sockaddr *) &addr, sizeof(addr));
}
/**
Read from a socket with a timeout.
Return 0=socket was closed by client, -1=timeout, >0 number of bytes read
*/
inline int socketread(SOCKET sock, char *buf, size_t buflen, int timeoutmsec)
{
// Use a timeout on our socket read to instead serve frames
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = timeoutmsec * 1000; // send a new frame ever
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
int res = recv(sock,buf,buflen,0);
if(res > 0) {
return res;
}
else if(res == 0) {
return 0; // client dropped connection
}
else {
if (errno == EWOULDBLOCK || errno == EAGAIN)
return -1;
else
return 0; // unknown error, just claim client dropped it
};
}

View File

@@ -0,0 +1,7 @@
#pragma once
#ifdef ARDUINO_ARCH_ESP32
#include "platglue-esp32.h"
#else
#include "platglue-posix.h"
#endif

7
Micro-RTSP/test/Makefile Normal file
View File

@@ -0,0 +1,7 @@
SRCS = ../src/CRtspSession.cpp ../src/CStreamer.cpp ../src/JPEGSamples.cpp ../src/SimStreamer.cpp
run: *.cpp ../src/*
#skill testerver
g++ -Wall -o testserver -I ../src -I . *.cpp $(SRCS)
#./testserver

15
Micro-RTSP/test/README.md Normal file
View File

@@ -0,0 +1,15 @@
# Testserver
This is a standalone Linux/cygwin test application to allow development of this
library without going through the slow process of always testing on the ESP32.
Almost all of the code is the same - only platglue-posix.h differs from
platglue-esp32.h (thus serving as a crude HAL).
RESPTestServer.cpp also serves as a small example of how this library could
be used on Poxix systems.
# Usage
Run "make" to build and run the server. Run "runvlc.sh" to fire up a VLC client
that talks to that server. If all is working you should see a static image
of my office that I captured using a ESP32-CAM.

View File

@@ -0,0 +1,70 @@
#include "platglue.h"
#include "SimStreamer.h"
#include "CRtspSession.h"
#include "JPEGSamples.h"
#include <assert.h>
#include <sys/time.h>
void workerThread( SOCKET s )
{
SimStreamer streamer( true ); // our streamer for UDP/TCP based RTP transport. true == use bigger resolution
streamer.addSession( s )->debug = true; // our threads RTSP session and state
while ( streamer.anySessions() )
{
uint32_t timeout = 400;
if( ! streamer.handleRequests( timeout ) )
{
struct timeval now;
gettimeofday( &now, NULL ); // crufty msecish timer
uint32_t msec = now.tv_sec * 1000 + now.tv_usec / 1000;
streamer.streamImage( msec );
}
}
}
int main()
{
SOCKET MasterSocket; // our masterSocket(socket that listens for RTSP client connections)
SOCKET ClientSocket; // RTSP socket to handle an client
sockaddr_in ServerAddr; // server address parameters
sockaddr_in ClientAddr; // address parameters of a new RTSP client
socklen_t ClientAddrLen = sizeof(ClientAddr);
printf( "running test RTSP server\n" );
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_addr.s_addr = INADDR_ANY;
ServerAddr.sin_port = htons(8554); // listen on RTSP port 8554
MasterSocket = socket(AF_INET,SOCK_STREAM,0);
int enable = 1;
if (setsockopt(MasterSocket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {
printf("setsockopt(SO_REUSEADDR) failed");
return 0;
}
// bind our master socket to the RTSP port and listen for a client connection
if (bind(MasterSocket,(sockaddr*)&ServerAddr,sizeof(ServerAddr)) != 0) {
printf("error can't bind port errno=%d\n", errno);
return 0;
}
if (listen(MasterSocket,5) != 0) return 0;
while ( true )
{ // loop forever to accept client connections
ClientSocket = accept(MasterSocket,(struct sockaddr*)&ClientAddr,&ClientAddrLen);
printf("Client connected. Client address: %s\r\n",inet_ntoa(ClientAddr.sin_addr));
if(fork() == 0)
workerThread(ClientSocket);
}
closesocket(MasterSocket);
return 0;
}

View File

@@ -0,0 +1,2 @@
# for testing
vlc -v rtsp://192.168.86.215:8554/mjpeg/1

111
Micro-RTSP/test/rfccode.cpp Normal file
View File

@@ -0,0 +1,111 @@
#include "platglue.h"
#include "SimStreamer.h"
#include "CRtspSession.h"
#include "JPEGSamples.h"
// From RFC2435 generates standard quantization tables
/*
* Table K.1 from JPEG spec.
*/
static const int jpeg_luma_quantizer[64] = {
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68, 109, 103, 77,
24, 35, 55, 64, 81, 104, 113, 92,
49, 64, 78, 87, 103, 121, 120, 101,
72, 92, 95, 98, 112, 100, 103, 99
};
/*
* Table K.2 from JPEG spec.
*/
static const int jpeg_chroma_quantizer[64] = {
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
};
/*
* Call MakeTables with the Q factor and two u_char[64] return arrays
*/
void
MakeTables(int q, u_char *lqt, u_char *cqt)
{
int i;
int factor = q;
if (q < 1) factor = 1;
if (q > 99) factor = 99;
if (q < 50)
q = 5000 / factor;
else
q = 200 - factor*2;
for (i=0; i < 64; i++) {
int lq = (jpeg_luma_quantizer[i] * q + 50) / 100;
int cq = (jpeg_chroma_quantizer[i] * q + 50) / 100;
/* Limit the quantizers to 1 <= q <= 255 */
if (lq < 1) lq = 1;
else if (lq > 255) lq = 255;
lqt[i] = lq;
if (cq < 1) cq = 1;
else if (cq > 255) cq = 255;
cqt[i] = cq;
}
}
// analyze an imge from our camera to find which quant table it is using...
// Used to see if our camera is spitting out standard RTP tables (it isn't)
// So we have to use Q of 255 to indicate that each frame has unique quant tables
// use 0 for precision in the qant header, 64 for length
void findCameraQuant()
{
BufPtr bytes = capture_jpg;
uint32_t len = capture_jpg_len;
if(!findJPEGheader(&bytes, &len, 0xdb)) {
printf("error can't find quant table 0\n");
return;
}
else {
printf("found quant table %x (len %d)\n", bytes[2], bytes[1]);
}
BufPtr qtable0 = bytes + 3; // 3 bytes of header skipped
nextJpegBlock(&bytes);
if(!findJPEGheader(&bytes, &len, 0xdb)) {
printf("error can't find quant table 1\n");
return;
}
else {
printf("found quant table %x\n", bytes[2]);
}
BufPtr qtable1 = bytes + 3;
nextJpegBlock(&bytes);
for(int q = 0; q < 128; q++) {
uint8_t lqt[64], cqt[64];
MakeTables(q, lqt, cqt);
if(memcmp(qtable0, lqt, sizeof(lqt)) == 0 && memcmp(qtable1, cqt, sizeof(cqt)) == 0) {
printf("Found matching quant table %d\n", q);
}
}
printf("No matching quant table found!\n");
}

View File

@@ -0,0 +1,2 @@
# for testing
vlc -v rtsp://127.0.0.1:8554/mjpeg/1