庖丁解牛-----Live555源碼徹底解密(根據MediaServer講解Rtsp的建立過程)

live555MediaServer.cpp服務端源碼講解(testRelay.cpp,http://blog.csdn.net/smilestone_322/article/details/18923139)

int main(int argc, char** argv) {

???? // Begin by setting up our usage environment:

???? TaskScheduler* scheduler = BasicTaskScheduler::createNew();

???? UsageEnvironment* env = BasicUsageEnvironment::createNew(*scheduler);

?

???? UserAuthenticationDatabase* authDB = NULL;

????

???? // Create the RTSP server.? Try first with the default port number (554),

???? // and then with the alternative port number (8554):

???? RTSPServer* rtspServer;

???? portNumBits rtspServerPortNum = 554;

???? //先使用554默認端口建立Rtsp Server

???? rtspServer = DynamicRTSPServer::createNew(*env, rtspServerPortNum, authDB);

???? //如果建立不成功,使用8554建立rtsp server

???? if (rtspServer == NULL) {

???????? rtspServerPortNum = 8554;

???????? rtspServer = DynamicRTSPServer::createNew(*env, rtspServerPortNum, authDB);

???? }

???? if (rtspServer == NULL) {

???????? *env << "Failed to create RTSP server: " << env->getResultMsg() << "\n";

???????? // exit(1);

???????? return -1;

???? }

????

???? env->taskScheduler().doEventLoop(); // does not return

?

???? return 0; // only to prevent compiler warning

}

?

跟蹤進入CreateNew函數;

DynamicRTSPServer*

DynamicRTSPServer::createNew(UsageEnvironment&env,PortourPort,

????????????? ???? UserAuthenticationDatabase*authDatabase,

????????????? ???? unsigned reclamationTestSeconds) {

? int ourSocket = setUpOurSocket(env,ourPort);?//建立tcp socket

? if (ourSocket == -1)returnNULL;

?

? return new DynamicRTSPServer(env,ourSocket,ourPort,authDatabase,reclamationTestSeconds);

}

?

?

DynamicRTSPServer::DynamicRTSPServer(UsageEnvironment&env,intourSocket,

?????????????????? ???? Port ourPort,

?????????????????? ???? UserAuthenticationDatabase*authDatabase,unsignedreclamationTestSeconds)

? : RTSPServerSupportingHTTPStreaming(env,ourSocket,ourPort,authDatabase,reclamationTestSeconds) {

}

?

首先建立socket,然后在調用DynamicRtspServer的構造函數,DynamicRtspServer繼承RTSPServerSupportingHTTPStreaming類; RTSPServerSupportingHTTPStreaming類又繼承RTSPServer類;

RTSPServerSupportingHTTPStreaming類的主要作用是支持Http

?

接著看setUpOurSocket函數在前面已經講過;就是建立socket;最后我們跟蹤進入RTSPServer類的構造函數:

?

RTSPServer::RTSPServer(UsageEnvironment& env,

???????? ?????? int ourSocket, Port ourPort,

???????? ?????? UserAuthenticationDatabase* authDatabase,

???????? ?????? unsigned reclamationTestSeconds)

? : Medium(env),

??? fRTSPServerPort(ourPort), fRTSPServerSocket(ourSocket), fHTTPServerSocket(-1), fHTTPServerPort(0),

??? fServerMediaSessions(HashTable::create(STRING_HASH_KEYS)),

??? fClientConnections(HashTable::create(ONE_WORD_HASH_KEYS)),

??? fClientConnectionsForHTTPTunneling(NULL), // will get created if needed

??? fClientSessions(HashTable::create(STRING_HASH_KEYS)),

??? fPendingRegisterRequests(HashTable::create(ONE_WORD_HASH_KEYS)),

??? fAuthDB(authDatabase), fReclamationTestSeconds(reclamationTestSeconds) {

? ignoreSigPipeOnSocket(ourSocket); // so that clients on the same host that are killed don't also kill us

?

? // Arrange to handle connections from others:

? env.taskScheduler().turnOnBackgroundReadHandling(fRTSPServerSocket,

??????????????????????????? ?? (TaskScheduler::BackgroundHandlerProc*)&incomingConnectionHandlerRTSP,this);

}

?

當fRTSPServerSocket收到數據時,調用incomingConnectionHandlerRTSP回調函數,繼續跟進到incomingConnectionHandlerRTSP函數,源碼如下:

?

void RTSPServer::incomingConnectionHandlerRTSP(void* instance,int/*mask*/) {

? RTSPServer* server = (RTSPServer*)instance;

? server->incomingConnectionHandlerRTSP1();

}

?

?

void RTSPServer::incomingConnectionHandler(int serverSocket) {

? struct sockaddr_in clientAddr;

? SOCKLEN_T clientAddrLen = sizeof clientAddr;

? int clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen);

? if (clientSocket < 0) {

??? int err = envir().getErrno();

??? if (err != EWOULDBLOCK) {

??????? envir().setResultErrMsg("accept() failed: ");

??? }

??? return;

? }

? makeSocketNonBlocking(clientSocket);

? increaseSendBufferTo(envir(), clientSocket, 50*1024);

?

#ifdef DEBUG

? envir() << "accept()ed connection from " << AddressString(clientAddr).val() << "\n";

#endif

?

? // Create a new object for handling this RTSP connection:

? (void)createNewClientConnection(clientSocket, clientAddr);

}

?

當收到客戶的連接時需保存下代表客戶端的新socket,以后用這個socket與這個客戶通訊。每個客戶將來會對應一個rtp會話,而且各客戶的RTSP請求只控制自己的rtp會話;

?

incomingConnectionHandler函數的作用是accept接受客戶端的socket連接,然后設置clientSocket的屬性,這里需要注意,我們在建立服務端socket時已經對服務端socket設置了非阻塞屬性,這個地方又要設置accept后的clientSecket的屬性;

?

incomingConnectionHandler函數最后調用createNewClientConnection函數,源碼如下:

RTSPServer::RTSPClientConnection*

RTSPServer::createNewClientConnection(int clientSocket,struct sockaddr_in clientAddr) {

? return new RTSPClientConnection(*this, clientSocket, clientAddr);

}

?

對于每個新建立的客戶端連接請求,new RTSPClientConnection的對象進行管理;

RTSPServer::RTSPClientConnection

::RTSPClientConnection(RTSPServer& ourServer, int clientSocket, struct sockaddr_in clientAddr)

? : fOurServer(ourServer), fIsActive(True),

??? fClientInputSocket(clientSocket), fClientOutputSocket(clientSocket), fClientAddr(clientAddr),

??? fRecursionCount(0), fOurSessionCookie(NULL) {

? // Add ourself to our 'client connections' table:

? fOurServer.fClientConnections->Add((charconst*)this,this);

?

? // Arrange to handle incoming requests:

? resetRequestBuffer();

? envir().taskScheduler().setBackgroundHandling(fClientInputSocket, SOCKET_READABLE|SOCKET_EXCEPTION,

??????????????????????????? (TaskScheduler::BackgroundHandlerProc*)&incomingRequestHandler,this);

}

?

在該函數中首先對RTSPServer的成員變量進行賦值:

fOurServer= ourServer;

fClientInputSocket= clientSocket;

fClientOutputSocket= clientSocket;

fClientAddr= clientAddr;

?

setBackgroundHandling函數用來處理fClientInputSocket socket上收到數據,或異常時,調用incomingRequestHandler回調函數;

?

下面在跟進到incomingRequestHandler函數:

void RTSPServer::RTSPClientConnection::incomingRequestHandler(void* instance,int/*mask*/) {

? RTSPClientConnection* session = (RTSPClientConnection*)instance;

? session->incomingRequestHandler1();

}

?

Session 為剛才new的RTSPClientConnection 對象,這個地方需要調試驗證下;調用成員函數incomingRequestHandler1;跟進到該成員函數的代碼:

?

void RTSPServer::RTSPClientConnection::incomingRequestHandler1() {

? struct sockaddr_in dummy; // 'from' address, meaningless in this case

?

? int bytesRead = readSocket(envir(), fClientInputSocket, &fRequestBuffer[fRequestBytesAlreadySeen], fRequestBufferBytesLeft, dummy);

? handleRequestBytes(bytesRead);

}

?

該函數調用ReadSocket從fClientInputSocket上讀取數據;讀到的數據保存在fRequestBuffer中,readSocket的返回值為實際讀到的數據的長度;源碼如下:

int readSocket(UsageEnvironment& env,

???? ?????? int socket, unsigned char* buffer, unsigned bufferSize,

???? ?????? struct sockaddr_in& fromAddress) {

? SOCKLEN_T addressSize = sizeof fromAddress;

? int bytesRead = recvfrom(socket, (char*)buffer, bufferSize, 0,

????????????? ?? (struct sockaddr*)&fromAddress,

????????????? ?? &addressSize);

? if (bytesRead < 0) {

??? //##### HACK to work around bugs in Linux and Windows:

??? int err = env.getErrno();

??? if (err == 111 /*ECONNREFUSED (Linux)*/

#if defined(__WIN32__) ||defined(_WIN32)

???? // What a piece of crap Windows is.?Sometimes

???? // recvfrom() returns -1, but with an 'errno' of 0.

???? // This appears not to be a real error; just treat

???? // it as if it were a read of zero bytes, and hope

???? // we don't have to do anything else to 'reset'

???? // this alleged error:

???? || err == 0 || err == EWOULDBLOCK

#else

???? || err == EAGAIN

#endif

???? || err == 113 /*EHOSTUNREACH (Linux)*/) {// Why does Linux return this for datagram sock?

????? fromAddress.sin_addr.s_addr = 0;

????? return 0;

??? }

??? //##### END HACK

??? socketErr(env, "recvfrom() error: ");

? } else if (bytesRead == 0) {

??? // "recvfrom()" on a stream socket can return 0 if the remote end has closed the connection.?Treat this as an error:

??? return -1;

? }

?

? return bytesRead;

}

?

從socket中讀到數據后必須對數據進行解析,解析的源碼如下:

void RTSPServer::RTSPClientConnection::handleRequestBytes(int newBytesRead) {

? int numBytesRemaining = 0;

? ++fRecursionCount;

?

? do {

??? RTSPServer::RTSPClientSession* clientSession = NULL;

?

??? if (newBytesRead < 0 || (unsigned)newBytesRead >= fRequestBufferBytesLeft) {

????? // Either the client socket has died, or the request was too big for us.

????? // Terminate this connection:

#ifdef DEBUG

????? fprintf(stderr, "RTSPClientConnection[%p]::handleRequestBytes() read %d new bytes (of %d); terminating connection!\n", this, newBytesRead, fRequestBufferBytesLeft);

#endif

????? fIsActive = False;

????? break;

??? }

???

??? Boolean endOfMsg = False;

??? unsigned char* ptr = &fRequestBuffer[fRequestBytesAlreadySeen];

#ifdef DEBUG

??? ptr[newBytesRead] = '\0';

??? fprintf(stderr, "RTSPClientConnection[%p]::handleRequestBytes() %s %d new bytes:%s\n",

???? ??? this, numBytesRemaining > 0 ? "processing" : "read", newBytesRead, ptr);

#endif

???

??? if (fClientOutputSocket != fClientInputSocket) {

????? // We're doing RTSP-over-HTTP tunneling, and input commands are assumed to have been Base64-encoded.

????? // We therefore Base64-decode as much of this new data as we can (i.e., up to a multiple of 4 bytes).

?

????? // But first, we remove any whitespace that may be in the input data:

????? unsigned toIndex = 0;

????? for (int fromIndex = 0; fromIndex < newBytesRead; ++fromIndex) {

???? char c = ptr[fromIndex];

???? if (!(c == ' ' || c == '\t' || c == '\r' || c == '\n')) { // not 'whitespace': space,tab,CR,NL

???? ? ptr[toIndex++] = c;

???? }

????? }

????? newBytesRead = toIndex;

?

????? unsigned numBytesToDecode = fBase64RemainderCount + newBytesRead;

????? unsigned newBase64RemainderCount = numBytesToDecode%4;

????? numBytesToDecode -= newBase64RemainderCount;

????? if (numBytesToDecode > 0) {

???? ptr[newBytesRead] = '\0';

???? unsigned decodedSize;

???? unsigned char* decodedBytes = base64Decode((char const*)(ptr-fBase64RemainderCount), numBytesToDecode, decodedSize);

#ifdef DEBUG

???? fprintf(stderr, "Base64-decoded %d input bytes into %d new bytes:", numBytesToDecode, decodedSize);

???? for (unsigned k = 0; k < decodedSize; ++k) fprintf(stderr, "%c", decodedBytes[k]);

???? fprintf(stderr, "\n");

#endif

????

???? // Copy the new decoded bytes in place of the old ones (we can do this because there are fewer decoded bytes than original):

???? unsigned char* to = ptr-fBase64RemainderCount;

???? for (unsigned i = 0; i < decodedSize; ++i) *to++ = decodedBytes[i];

????

???? // Then copy any remaining (undecoded) bytes to the end:

???? for (unsigned j = 0; j < newBase64RemainderCount; ++j) *to++ = (ptr-fBase64RemainderCount+numBytesToDecode)[j];

????

???? newBytesRead = decodedSize + newBase64RemainderCount; // adjust to allow for the size of the new decoded data (+ remainder)

???? delete[] decodedBytes;

????? }

????? fBase64RemainderCount = newBase64RemainderCount;

????? if (fBase64RemainderCount > 0)break;// because we know that we have more input bytes still to receive

??? }

???

??? // Look for the end of the message: <CR><LF><CR><LF>

??? unsigned char *tmpPtr = fLastCRLF + 2;

??? if (tmpPtr < fRequestBuffer) tmpPtr = fRequestBuffer;

??? while (tmpPtr < &ptr[newBytesRead-1]) {

????? if (*tmpPtr == '\r' && *(tmpPtr+1) == '\n') {

???? if (tmpPtr - fLastCRLF == 2) {// This is it:

???? ? endOfMsg = True;

???? ? break;

???? }

???? fLastCRLF = tmpPtr;

????? }

????? ++tmpPtr;

??? }

???

??? fRequestBufferBytesLeft -= newBytesRead;

??? fRequestBytesAlreadySeen += newBytesRead;

???

??? if (!endOfMsg) break; // subsequent reads will be needed to complete the request

???

??? // Parse the request string into command name and 'CSeq', then handle the command:

??? fRequestBuffer[fRequestBytesAlreadySeen] = '\0';

??? char cmdName[RTSP_PARAM_STRING_MAX];

??? char urlPreSuffix[RTSP_PARAM_STRING_MAX];

??? char urlSuffix[RTSP_PARAM_STRING_MAX];

??? char cseq[RTSP_PARAM_STRING_MAX];

??? char sessionIdStr[RTSP_PARAM_STRING_MAX];

??? unsigned contentLength = 0;

fLastCRLF[2] = '\0'; // temporarily, for parsing

?

//解析Rtsp請求字符串

??? Boolean parseSucceeded = parseRTSPRequestString((char*)fRequestBuffer, fLastCRLF+2 - fRequestBuffer,

??????????????????????????? ??? cmdName, sizeof cmdName,

??????????????????????????? ??? urlPreSuffix, sizeof urlPreSuffix,

??????????????????????????? ??? urlSuffix, sizeof urlSuffix,

??????????????????????????? ??? cseq, sizeof cseq,

??????????????????????????? ??? sessionIdStr, sizeof sessionIdStr,

??????????????????????????? ??? contentLength);

??? fLastCRLF[2] = '\r'; // restore its value

??? if (parseSucceeded) {

#ifdef DEBUG

????? fprintf(stderr, "parseRTSPRequestString() succeeded, returning cmdName \"%s\", urlPreSuffix \"%s\", urlSuffix \"%s\", CSeq \"%s\", Content-Length %u, with %d bytes following the message.\n", cmdName, urlPreSuffix, urlSuffix, cseq, contentLength, ptr + newBytesRead - (tmpPtr + 2));

#endif

????? // If there was a "Content-Length:" header, then make sure we've received all of the data that it specified:

????? if (ptr + newBytesRead < tmpPtr + 2 + contentLength)break;// we still need more data; subsequent reads will give it to us

?????

????? // We now have a complete RTSP request.

????? // Handle the specified command (beginning by checking those that don't require session ids):

????? fCurrentCSeq = cseq;

???? //收到客戶端的OPTIONS請求

????? if (strcmp(cmdName, "OPTIONS") == 0) {

???? // If the request included a "Session:" id, and it refers to a client session that's current ongoing, then use this

???? // command to indicate 'liveness' on that client session:

???? if (sessionIdStr[0] != '\0') {

???? ? clientSession = (RTSPServer::RTSPClientSession*)(fOurServer.fClientSessions->Lookup(sessionIdStr));

???? //根據sessionIdStr查表,看該客戶端的會話是否存在,存在會話,調用noteLiveness函數

???? ? if (clientSession != NULL) clientSession->noteLiveness();

???? }

???? //處理Opinion請求,構建應答包

???? handleCmd_OPTIONS();

????? } else if (urlPreSuffix[0] == '\0' && urlSuffix[0] =='*' && urlSuffix[1] =='\0') {

???? // The special "*" URL means: an operation on the entire server.?This works only for GET_PARAMETER and SET_PARAMETER:

???? if (strcmp(cmdName, "GET_PARAMETER") == 0) {

???? ? handleCmd_GET_PARAMETER((charconst*)fRequestBuffer);

???? } else if (strcmp(cmdName, "SET_PARAMETER") == 0) {

???? ? handleCmd_SET_PARAMETER((charconst*)fRequestBuffer);

???? } else {

???? ? handleCmd_notSupported();

???? }

????? } else if (strcmp(cmdName, "DESCRIBE") == 0) {

???? //收到客戶端的Describe請求,處理該請求,構建應答包

???? handleCmd_DESCRIBE(urlPreSuffix, urlSuffix, (charconst*)fRequestBuffer);

????? } else if (strcmp(cmdName, "SETUP") == 0) {

???? //收到客戶端的Setup請求,如果是第一次Setup,那么就需要調用createNewClientSession函數進行會話,然后將sessionIdStr和clientSession關聯起來

???? if (sessionIdStr[0] == '\0') {

???? ? // No session id was present in the request.?So create a new "RTSPClientSession" object for this request.

???? ? // Choose a random (unused) 32-bit integer for the session id (it will be encoded as a 8-digit hex number).

???? ? // (We avoid choosing session id 0, because that has a special use (by "OnDemandServerMediaSubsession").)

???? ? u_int32_t sessionId;

???? ? do {

???? ??? sessionId = (u_int32_t)our_random32();

???? ??? sprintf(sessionIdStr, "%08X", sessionId);

???? ? } while (sessionId == 0 || fOurServer.fClientSessions->Lookup(sessionIdStr) != NULL);

???? ? clientSession = fOurServer.createNewClientSession(sessionId);

???? ? fOurServer.fClientSessions->Add(sessionIdStr, clientSession);

???? } else {

???? ? // The request included a session id.?Make sure it's one that we have already set up:

???? ? //如果存在會話,直接查找原來的會話;

???? ? clientSession = (RTSPServer::RTSPClientSession*)(fOurServer.fClientSessions->Lookup(sessionIdStr));

?

???? ? if (clientSession == NULL) {

???? ??? handleCmd_sessionNotFound();

???? ? }

???? }

???? //構建Setup應答包

???? if (clientSession != NULL) clientSession->handleCmd_SETUP(this, urlPreSuffix, urlSuffix, (charconst*)fRequestBuffer);

????? } else if (strcmp(cmdName, "TEARDOWN") == 0

???????? ?|| strcmp(cmdName, "PLAY") == 0

???????? ?|| strcmp(cmdName, "PAUSE") == 0

???????? ?|| strcmp(cmdName, "GET_PARAMETER") == 0

???????? ?|| strcmp(cmdName, "SET_PARAMETER") == 0) {

???? RTSPServer::RTSPClientSession* clientSession

???? ? = sessionIdStr[0] == '\0' ? NULL : (RTSPServer::RTSPClientSession*)(fOurServer.fClientSessions->Lookup(sessionIdStr));

???? if (clientSession == NULL) {

???? ? handleCmd_sessionNotFound();

???? } else {

???? ? clientSession->handleCmd_withinSession(this, cmdName, urlPreSuffix, urlSuffix, (charconst*)fRequestBuffer);

???? }

????? } else if (strcmp(cmdName, "REGISTER") == 0 || strcmp(cmdName,"REGISTER_REMOTE") == 0) {

???? // Because - unlike other commands - an implementation of these commands needs the entire URL, we re-parse the

???? // command to get it:

???? char* url = strDupSize((char*)fRequestBuffer);

???? if (sscanf((char*)fRequestBuffer,"%*s %s", url) == 1) {

???? ? handleCmd_REGISTER(url, urlSuffix, strcmp(cmdName, "REGISTER_REMOTE") == 0);

???? } else {

???? ? handleCmd_bad();

???? }

???? delete[] url;

????? } else {

???? // The command is one that we don't handle:

???? handleCmd_notSupported();

????? }

??? } else {

#ifdef DEBUG

????? fprintf(stderr, "parseRTSPRequestString() failed; checking now for HTTP commands (for RTSP-over-HTTP tunneling)...\n");

#endif

????? // The request was not (valid) RTSP, but check for a special case: HTTP commands (for setting up RTSP-over-HTTP tunneling):

????? char sessionCookie[RTSP_PARAM_STRING_MAX];

????? char acceptStr[RTSP_PARAM_STRING_MAX];

????? *fLastCRLF = '\0'; // temporarily, for parsing

????? parseSucceeded = parseHTTPRequestString(cmdName, sizeof cmdName,

?????????????????????? ????? urlSuffix, sizeof urlPreSuffix,

?????????????????????? ????? sessionCookie, sizeof sessionCookie,

?????????????????????? ????? acceptStr, sizeof acceptStr);

????? *fLastCRLF = '\r';

????? if (parseSucceeded) {

#ifdef DEBUG

???? fprintf(stderr, "parseHTTPRequestString() succeeded, returning cmdName \"%s\", urlSuffix \"%s\", sessionCookie \"%s\", acceptStr \"%s\"\n", cmdName, urlSuffix, sessionCookie, acceptStr);

#endif

???? // Check that the HTTP command is valid for RTSP-over-HTTP tunneling: There must be a 'session cookie'.

???? Boolean isValidHTTPCmd = True;

???? if (sessionCookie[0] == '\0') {

???? ? // There was no "x-sessioncookie:" header.?If there was an "Accept: application/x-rtsp-tunnelled" header,

???? ? // then this is a bad tunneling request.?Otherwise, assume that it's an attempt to access the stream via HTTP.

???? ? if (strcmp(acceptStr, "application/x-rtsp-tunnelled") == 0) {

???? ??? isValidHTTPCmd = False;

???? ? } else {

???? ??? handleHTTPCmd_StreamingGET(urlSuffix, (charconst*)fRequestBuffer);

???? ? }

???? } else if (strcmp(cmdName, "GET") == 0) {

???? ? handleHTTPCmd_TunnelingGET(sessionCookie);

???? } else if (strcmp(cmdName, "POST") == 0) {

???? ? // We might have received additional data following the HTTP "POST" command - i.e., the first Base64-encoded RTSP command.

???? ? // Check for this, and handle it if it exists:

???? ? unsigned char const* extraData = fLastCRLF+4;

???? ? unsigned extraDataSize = &fRequestBuffer[fRequestBytesAlreadySeen] - extraData;

???? ? if (handleHTTPCmd_TunnelingPOST(sessionCookie, extraData, extraDataSize)) {

???? ??? // We don't respond to the "POST" command, and we go away:

???? ??? fIsActive = False;

???? ??? break;

???? ? }

???? } else {

???? ? isValidHTTPCmd = False;

???? }

???? if (!isValidHTTPCmd) {

???? ? handleHTTPCmd_notSupported();

???? }

????? } else {

#ifdef DEBUG

???? fprintf(stderr, "parseHTTPRequestString() failed!\n");

#endif

???? handleCmd_bad();

????? }

??? }

???

#ifdef DEBUG

??? fprintf(stderr, "sending response: %s", fResponseBuffer);

#endif

???? //發送應答包

??? send(fClientOutputSocket, (charconst*)fResponseBuffer, strlen((char*)fResponseBuffer), 0);

???

??? if (clientSession != NULL && clientSession->fStreamAfterSETUP && strcmp(cmdName,"SETUP") == 0) {

????? // The client has asked for streaming to commence now, rather than after a

????? // subsequent "PLAY" command.? So, simulate the effect of a "PLAY" command:

????? clientSession->handleCmd_withinSession(this,"PLAY", urlPreSuffix, urlSuffix, (charconst*)fRequestBuffer);

??? }

???

??? // Check whether there are extra bytes remaining in the buffer, after the end of the request (a rare case).

??? // If so, move them to the front of our buffer, and keep processing it, because it might be a following, pipelined request.

??? unsigned requestSize = (fLastCRLF+4-fRequestBuffer) + contentLength;

??? numBytesRemaining = fRequestBytesAlreadySeen - requestSize;

??? resetRequestBuffer(); // to prepare for any subsequent request

?

??? if (numBytesRemaining > 0) {

????? memmove(fRequestBuffer, &fRequestBuffer[requestSize], numBytesRemaining);

????? newBytesRead = numBytesRemaining;

??? }

? } while (numBytesRemaining > 0);

?

? --fRecursionCount;

? if (!fIsActive) {

??? if (fRecursionCount > 0) closeSockets();elsedeletethis;

??? // Note: The "fRecursionCount" test is for a pathological situation where we reenter the event loop and get called recursively

??? // while handling a command (e.g., while handling a "DESCRIBE", to get a SDP description).

??? // In such a case we don't want to actually delete ourself until we leave the outermost call.

? }

}

?

void RTSPServer::RTSPClientSession::noteLiveness() {

? if (fOurServer.fReclamationTestSeconds > 0) {

??? envir().taskScheduler()

????? .rescheduleDelayedTask(fLivenessCheckTask,

????????????? ???? fOurServer.fReclamationTestSeconds*1000000,

????????????? ???? (TaskFunc*)livenessTimeoutTask, this);

? }

}

?

noteLiveness該函數可以用來判斷流是不是斷開;這個相當重要,我們可以使用它判斷網絡是否斷開,尤其在客戶端可以使用這樣的方法來判斷網絡是否斷開,然后實現斷網重連的功能。

?

RTSPClientSession要提供什么功能呢,可以想象:需要監聽客戶端的rtsp請求并回應它,需要在DESCRIBE請求中返回所請求的流的信息,需要在SETUP請求中建立起RTP會話,需要在TEARDOWN請求中關閉RTP會話,等等;

?

下面在接著跟進到createNewClientSession會話的函數:

RTSPServer::RTSPClientSession*

RTSPServer::createNewClientSession(u_int32_t sessionId) {

? return new RTSPClientSession(*this, sessionId);

}

?

RTSPServer::RTSPClientSession

::RTSPClientSession(RTSPServer& ourServer, u_int32_t sessionId)

? : fOurServer(ourServer), fOurSessionId(sessionId), fOurServerMediaSession(NULL), fIsMulticast(False), fStreamAfterSETUP(False),

??? fTCPStreamIdCount(0), fLivenessCheckTask(NULL), fNumStreamStates(0), fStreamStates(NULL) {

? noteLiveness();

}

這個構造函數舊版本的live555和v0.78版本是不同的,舊版本的live555,在accept后就建立了rtsp會話,而新版本的是在收到setup請求后才建立的會話,所以這些地方都不同,在舊版本中RTSPClientSession會有一個回調函數,新版本中沒有,該回調函數在收到客戶端的Connect命令時設置;

?

下面在分析下服務端對Opinion各種命令的請求的處理的代碼;首先還是分析Opinion,該命令請求的作用是客戶端請求服務端支持哪些命令;Describe請求是得到會話描述信息,包括h264的sps,pps信息也可以在Describe的應答中發送;Setup命令是用來建立會話,服務端收到Setup請求后,建立會話,new 一個RTSPClientSession對象,該對象用來處理客戶端的各種Rtsp命令請求;同時服務端保存會話Id和會話對象,每次可以從表中取出RTSPClientSession對象;響應客戶端的請求;在收到Setup命令后;沒有等到客戶端的Play命令,就開始視頻流;

?

?? if (clientSession != NULL && clientSession->fStreamAfterSETUP && strcmp(cmdName,"SETUP") == 0) {

????? // The client has asked for streaming to commence now, rather than after a

????? // subsequent "PLAY" command.? So, simulate the effect of a "PLAY" command:

????? clientSession->handleCmd_withinSession(this,"PLAY", urlPreSuffix, urlSuffix, (charconst*)fRequestBuffer);

??? }

???

1)服務端對Opinion命令的處理;跟蹤源碼:

?

void RTSPServer::RTSPClientConnection::handleCmd_OPTIONS() {

? snprintf((char*)fResponseBuffer,sizeof fResponseBuffer,

???? ?? "RTSP/1.0 200 OK\r\nCSeq: %s\r\n%sPublic: %s\r\n\r\n",

???? ?? fCurrentCSeq, dateHeader(), fOurServer.allowedCommandNames());

}

?

1)????? 服務端對Describe命令的處理

void RTSPServer::RTSPClientConnection

::handleCmd_DESCRIBE(char const* urlPreSuffix, char const* urlSuffix, char const* fullRequestStr) {

? char* sdpDescription = NULL;

? char* rtspURL = NULL;

? do {

//整理一下下RTSP地址

??? char urlTotalSuffix[RTSP_PARAM_STRING_MAX];

??? if (strlen(urlPreSuffix) + strlen(urlSuffix) + 2 >sizeof urlTotalSuffix) {

????? handleCmd_bad();

????? break;

??? }

??? urlTotalSuffix[0] = '\0';

??? if (urlPreSuffix[0] != '\0') {

????? strcat(urlTotalSuffix, urlPreSuffix);

????? strcat(urlTotalSuffix, "/");

??? }

??? strcat(urlTotalSuffix, urlSuffix);

??? ?//鑒權

??? if (!authenticationOK("DESCRIBE", urlTotalSuffix, fullRequestStr))break;

???

??? // We should really check that the request contains an "Accept:" #####

??? // for "application/sdp", because that's what we're sending back #####

???

// Begin by looking up the "ServerMediaSession" object for the specified "urlTotalSuffix":

//跟據流的名字查找ServerMediaSession

??? ServerMediaSession* session = fOurServer.lookupServerMediaSession(urlTotalSuffix);

??? if (session == NULL) {

????? handleCmd_notFound();

????? break;

??? }

???

??? // Then, assemble a SDP description for this session:

??? sdpDescription = session->generateSDPDescription();

??? if (sdpDescription == NULL) {

????? // This usually means that a file name that was specified for a

????? // "ServerMediaSubsession" does not exist.

????? setRTSPResponse("404 File Not Found, Or In Incorrect Format");

????? break;

??? }

??? unsigned sdpDescriptionSize = strlen(sdpDescription);

???

??? // Also, generate our RTSP URL, for the "Content-Base:" header

??? // (which is necessary to ensure that the correct URL gets used in subsequent "SETUP" requests).

??? rtspURL = fOurServer.rtspURL(session, fClientInputSocket);

???

??? snprintf((char*)fResponseBuffer,sizeof fResponseBuffer,

???? ???? "RTSP/1.0 200 OK\r\nCSeq: %s\r\n"

???? ???? "%s"

???? ???? "Content-Base: %s/\r\n"

???? ???? "Content-Type: application/sdp\r\n"

???? ???? "Content-Length: %d\r\n\r\n"

???? ???? "%s",

???? ???? fCurrentCSeq,

???? ???? dateHeader(),

???? ???? rtspURL,

???? ???? sdpDescriptionSize,

???? ???? sdpDescription);

? } while (0);

?

? delete[] sdpDescription;

? delete[] rtspURL;

}

?

ServerMediaSession*

DynamicRTSPServer::lookupServerMediaSession(charconst* streamName) {

? // First, check whether the specified "streamName" exists as a local file:

? FILE* fid = fopen(streamName, "rb");

? Boolean fileExists = fid != NULL;

?

? // Next, check whether we already have a "ServerMediaSession" for this file:

?//查找是否已經存在一個ServerMediaSession

? ServerMediaSession* sms = RTSPServer::lookupServerMediaSession(streamName);

? Boolean smsExists = sms != NULL;

?

? // Handle the four possibilities for "fileExists" and "smsExists":

??

? if (!fileExists) {

??? //文件不存在

??? if (smsExists) {

????? // "sms" was created for a file that no longer exists. Remove it:

???? //刪除ServerMediaSession

????? removeServerMediaSession(sms);

??? }

??? return NULL;

? } else {

??? if (!smsExists) {

????? // Create a new "ServerMediaSession" object for streaming from the named file.

????? //如果ServerMediaSession不存在,新建一個ServerMediaSession

????? sms = createNewSMS(envir(), streamName, fid);

???? //將ServerMediaSession和會話關聯起來

????? addServerMediaSession(sms);

??? }

??? fclose(fid);

??? return sms;

? }

}

?

?

void RTSPServer::addServerMediaSession(ServerMediaSession* serverMediaSession) {

? if (serverMediaSession == NULL)return;

?

? char const* sessionName = serverMediaSession->streamName();

? if (sessionName == NULL) sessionName ="";

? removeServerMediaSession(sessionName); // in case an existing "ServerMediaSession" with this name already exists

?

? fServerMediaSessions->Add(sessionName, (void*)serverMediaSession);

}

2)????? 服務端對Setup命令的處理

?

void RTSPServer::RTSPClientSession

::handleCmd_SETUP(RTSPServer::RTSPClientConnection* ourClientConnection,

???????? ? char const* urlPreSuffix, char const* urlSuffix, char const* fullRequestStr) {

? // Normally, "urlPreSuffix" should be the session (stream) name, and "urlSuffix" should be the subsession (track) name.

? // However (being "liberal in what we accept"), we also handle 'aggregate' SETUP requests (i.e., without a track name),

? // in the special case where we have only a single track.?I.e., in this case, we also handle:

? //??? "urlPreSuffix" is empty and "urlSuffix" is the session (stream) name, or

? //??? "urlPreSuffix" concatenated with "urlSuffix" (with "/" inbetween) is the session (stream) name.

? char const* streamName = urlPreSuffix;// in the normal case

? char const* trackId = urlSuffix;// in the normal case

? char* concatenatedStreamName = NULL;// in the normal case

?

? noteLiveness();

? do {

// First, make sure the specified stream name exists:

//下面的注釋參數參考:

http://blog.csdn.net/niu_gao/article/details/6911130

每個ServerMediaSession中至少要包含一個?//ServerMediaSubsession。一個ServerMediaSession對應一個媒體,可以認為是Server上的一個文件,或一個實時獲取設備。其包含的每個ServerMediaSubSession代表媒體中的一個Track。所以一個ServerMediaSession對應一個媒體,如果客戶請求的媒體名相同,就使用已存在的ServerMediaSession,如果不同,就創建一個新的。一個流對應一個StreamState,StreamState與ServerMediaSubsession相關,但代表的是動態的,而ServerMediaSubsession代表靜態的。??

fOurServer.lookupServerMediaSession(streamName)中會在找不到同名ServerMediaSession時新建一個,代表一個RTP流的ServerMediaSession們是被RTSPServer管理的,而不是被RTSPClientSession擁有。為什么呢?因為ServerMediaSession代表的是一個靜態的流,也就是可以從它里面獲取一個流的各種信息,但不能獲取傳輸狀態。不同客戶可能連接到同一個流,所以ServerMediaSession應被RTSPServer所擁有。

?

??? ServerMediaSession* sms = fOurServer.lookupServerMediaSession(streamName);

??? if (sms == NULL) {

????? // Check for the special case (noted above), before we give up:

????? if (urlPreSuffix[0] == '\0') {

???? streamName = urlSuffix;

????? } else {

???? concatenatedStreamName = newchar[strlen(urlPreSuffix) + strlen(urlSuffix) + 2];// allow for the "/" and the trailing '\0'

???? sprintf(concatenatedStreamName, "%s/%s", urlPreSuffix, urlSuffix);

???? streamName = concatenatedStreamName;

????? }

????? trackId = NULL;

?

????? // Check again:

????? sms = fOurServer.lookupServerMediaSession(streamName);

??? }

??? if (sms == NULL) {

????? if (fOurServerMediaSession == NULL) {

???? // The client asked for a stream that doesn't exist (and this session descriptor has not been used before):

???? ourClientConnection->handleCmd_notFound();

????? } else {

???? // The client asked for a stream that doesn't exist, but using a stream id for a stream that does exist. Bad request:

???? ourClientConnection->handleCmd_bad();

????? }

????? break;

??? } else {

????? if (fOurServerMediaSession == NULL) {

???? // We're accessing the "ServerMediaSession" for the first time.

???? fOurServerMediaSession = sms;

???? fOurServerMediaSession->incrementReferenceCount();

????? } else if (sms != fOurServerMediaSession) {

???? // The client asked for a stream that's different from the one originally requested for this stream id.?Bad request:

???? ourClientConnection->handleCmd_bad();

???? break;

????? }

??? }

?

??? if (fStreamStates == NULL) {

????? // This is the first "SETUP" for this session.?Set up our array of states for all of this session's subsessions (tracks):

????? ServerMediaSubsessionIterator iter(*fOurServerMediaSession);

????? for (fNumStreamStates = 0; iter.next() != NULL; ++fNumStreamStates) {}// begin by counting the number of subsessions (tracks)

?

????? fStreamStates = new struct streamState[fNumStreamStates];

?

????? iter.reset();

????? ServerMediaSubsession* subsession;

????? for (unsigned i = 0; i < fNumStreamStates; ++i) {

???? subsession = iter.next();

???? fStreamStates[i].subsession = subsession;

???? fStreamStates[i].streamToken = NULL; // for now; it may be changed by the "getStreamParameters()" call that comes later

?? ???}

??? }

?

??? // Look up information for the specified subsession (track):

??? ServerMediaSubsession* subsession = NULL;

??? unsigned streamNum;

??? if (trackId != NULL && trackId[0] !='\0') {// normal case

????? for (streamNum = 0; streamNum < fNumStreamStates; ++streamNum) {

???? subsession = fStreamStates[streamNum].subsession;

???? if (subsession != NULL && strcmp(trackId, subsession->trackId()) == 0)break;

????? }

????? if (streamNum >= fNumStreamStates) {

???? // The specified track id doesn't exist, so this request fails:

???? ourClientConnection->handleCmd_notFound();

???? break;

????? }

??? } else {

????? // Weird case: there was no track id in the URL.

????? // This works only if we have only one subsession:

????? if (fNumStreamStates != 1 || fStreamStates[0].subsession == NULL) {

???? ourClientConnection->handleCmd_bad();

???? break;

????? }

????? streamNum = 0;

????? subsession = fStreamStates[streamNum].subsession;

??? }

??? // ASSERT: subsession != NULL

?

??? // Look for a "Transport:" header in the request string, to extract client parameters:

??? StreamingMode streamingMode;

??? char* streamingModeString = NULL;// set when RAW_UDP streaming is specified

??? char* clientsDestinationAddressStr;

??? u_int8_t clientsDestinationTTL;

??? portNumBits clientRTPPortNum, clientRTCPPortNum;

??? unsigned char rtpChannelId, rtcpChannelId;

??? parseTransportHeader(fullRequestStr, streamingMode, streamingModeString,

????????????? ?clientsDestinationAddressStr, clientsDestinationTTL,

????????????? ?clientRTPPortNum, clientRTCPPortNum,

????????????? ?rtpChannelId, rtcpChannelId);

??? if ((streamingMode == RTP_TCP && rtpChannelId == 0xFF) ||

???? (streamingMode != RTP_TCP && ourClientConnection->fClientOutputSocket != ourClientConnection->fClientInputSocket)) {

????? // An anomolous situation, caused by a buggy client.?Either:

????? //???? 1/ TCP streaming was requested, but with no "interleaving=" fields.? (QuickTime Player sometimes does this.), or

????? //???? 2/ TCP streaming was not requested, but we're doing RTSP-over-HTTP tunneling (which implies TCP streaming).

?? ???// In either case, we assume TCP streaming, and set the RTP and RTCP channel ids to proper values:

????? streamingMode = RTP_TCP;

????? rtpChannelId = fTCPStreamIdCount; rtcpChannelId = fTCPStreamIdCount+1;

??? }

??? if (streamingMode == RTP_TCP) fTCPStreamIdCount += 2;

?

??? Port clientRTPPort(clientRTPPortNum);

??? Port clientRTCPPort(clientRTCPPortNum);

?

??? // Next, check whether a "Range:" or "x-playNow:" header is present in the request.

??? // This isn't legal, but some clients do this to combine "SETUP" and "PLAY":

??? double rangeStart = 0.0, rangeEnd = 0.0;

??? char* absStart = NULL; char* absEnd = NULL;

??? if (parseRangeHeader(fullRequestStr, rangeStart, rangeEnd, absStart, absEnd)) {

????? delete[] absStart; delete[] absEnd;

????? fStreamAfterSETUP = True;

??? } else if (parsePlayNowHeader(fullRequestStr)) {

????? fStreamAfterSETUP = True;

??? } else {

????? fStreamAfterSETUP = False;

??? }

?

??? // Then, get server parameters from the 'subsession':

??? int tcpSocketNum = streamingMode == RTP_TCP ? ourClientConnection->fClientOutputSocket : -1;

??? netAddressBits destinationAddress = 0;

??? u_int8_t destinationTTL = 255;

#ifdef RTSP_ALLOW_CLIENT_DESTINATION_SETTING

??? if (clientsDestinationAddressStr != NULL) {

????? // Use the client-provided "destination" address.

????? // Note: This potentially allows the server to be used in denial-of-service

????? // attacks, so don't enable this code unless you're sure that clients are

????? // trusted.

????? destinationAddress = our_inet_addr(clientsDestinationAddressStr);

??? }

??? // Also use the client-provided TTL.

??? destinationTTL = clientsDestinationTTL;

#endif

??? delete[] clientsDestinationAddressStr;

??? Port serverRTPPort(0);

??? Port serverRTCPPort(0);

?

??? // Make sure that we transmit on the same interface that's used by the client (in case we're a multi-homed server):

??? struct sockaddr_in sourceAddr; SOCKLEN_T namelen =sizeof sourceAddr;

??? getsockname(ourClientConnection->fClientInputSocket, (struct sockaddr*)&sourceAddr, &namelen);

??? netAddressBits origSendingInterfaceAddr = SendingInterfaceAddr;

??? netAddressBits origReceivingInterfaceAddr = ReceivingInterfaceAddr;

??? // NOTE: The following might not work properly, so we ifdef it out for now:

#ifdef HACK_FOR_MULTIHOMED_SERVERS

??? ReceivingInterfaceAddr = SendingInterfaceAddr = sourceAddr.sin_addr.s_addr;

#endif

?

??? subsession->getStreamParameters(fOurSessionId, ourClientConnection->fClientAddr.sin_addr.s_addr,

?????????????????? ??? clientRTPPort, clientRTCPPort,

?????????????????? ??? tcpSocketNum, rtpChannelId, rtcpChannelId,

?????????????????? ??? destinationAddress, destinationTTL, fIsMulticast,

?????????????????? ??? serverRTPPort, serverRTCPPort,

?????????????????? ??? fStreamStates[streamNum].streamToken);

??? SendingInterfaceAddr = origSendingInterfaceAddr;

??? ReceivingInterfaceAddr = origReceivingInterfaceAddr;

???

??? AddressString destAddrStr(destinationAddress);

??? AddressString sourceAddrStr(sourceAddr);

??? if (fIsMulticast) {

????? switch (streamingMode) {

??????? case RTP_UDP:

???? ? snprintf((char*)ourClientConnection->fResponseBuffer,sizeof ourClientConnection->fResponseBuffer,

???????? ?? "RTSP/1.0 200 OK\r\n"

???????? ?? "CSeq: %s\r\n"

???????? ?? "%s"

???????? ?? "Transport: RTP/AVP;multicast;destination=%s;source=%s;port=%d-%d;ttl=%d\r\n"

???????? ?? "Session: %08X\r\n\r\n",

???????? ?? ourClientConnection->fCurrentCSeq,

???????? ?? dateHeader(),

???????? ?? destAddrStr.val(), sourceAddrStr.val(), ntohs(serverRTPPort.num()), ntohs(serverRTCPPort.num()), destinationTTL,

???????? ?? fOurSessionId);

???? ? break;

??????? case RTP_TCP:

???? ? // multicast streams can't be sent via TCP

???? ? ourClientConnection->handleCmd_unsupportedTransport();

???? ? break;

??????? case RAW_UDP:

???? ? snprintf((char*)ourClientConnection->fResponseBuffer,sizeof ourClientConnection->fResponseBuffer,

???????? ?? "RTSP/1.0 200 OK\r\n"

???????? ?? "CSeq: %s\r\n"

???????? ?? "%s"

???????? ?? "Transport: %s;multicast;destination=%s;source=%s;port=%d;ttl=%d\r\n"

???????? ?? "Session: %08X\r\n\r\n",

???????? ?? ourClientConnection->fCurrentCSeq,

???????? ?? dateHeader(),

???????? ?? streamingModeString, destAddrStr.val(), sourceAddrStr.val(), ntohs(serverRTPPort.num()), destinationTTL,

???????? ?? fOurSessionId);

???? ? break;

????? }

??? } else {

????? switch (streamingMode) {

??????? case RTP_UDP: {

???? ? snprintf((char*)ourClientConnection->fResponseBuffer,sizeof ourClientConnection->fResponseBuffer,

???????? ?? "RTSP/1.0 200 OK\r\n"

???????? ?? "CSeq: %s\r\n"

???????? ?? "%s"

???????? ?? "Transport: RTP/AVP;unicast;destination=%s;source=%s;client_port=%d-%d;server_port=%d-%d\r\n"

???????? ?? "Session: %08X\r\n\r\n",

???????? ?? ourClientConnection->fCurrentCSeq,

???????? ?? dateHeader(),

???????? ?? destAddrStr.val(), sourceAddrStr.val(), ntohs(clientRTPPort.num()), ntohs(clientRTCPPort.num()), ntohs(serverRTPPort.num()), ntohs(serverRTCPPort.num()),

???????? ?? fOurSessionId);

???? ? break;

???? }

??????? case RTP_TCP: {

???? ? snprintf((char*)ourClientConnection->fResponseBuffer,sizeof ourClientConnection->fResponseBuffer,

???????? ?? "RTSP/1.0 200 OK\r\n"

???????? ?? "CSeq: %s\r\n"

???????? ?? "%s"

???????? ?? "Transport: RTP/AVP/TCP;unicast;destination=%s;source=%s;interleaved=%d-%d\r\n"

???????? ?? "Session: %08X\r\n\r\n",

???????? ?? ourClientConnection->fCurrentCSeq,

???????? ?? dateHeader(),

???????? ?? destAddrStr.val(), sourceAddrStr.val(), rtpChannelId, rtcpChannelId,

???????? ?? fOurSessionId);

???? ? break;

???? }

??????? case RAW_UDP: {

???? ? snprintf((char*)ourClientConnection->fResponseBuffer,sizeof ourClientConnection->fResponseBuffer,

???????? ?? "RTSP/1.0 200 OK\r\n"

???????? ?? "CSeq: %s\r\n"

???????? ?? "%s"

???????? ?? "Transport: %s;unicast;destination=%s;source=%s;client_port=%d;server_port=%d\r\n"

???????? ?? "Session: %08X\r\n\r\n",

???????? ?? ourClientConnection->fCurrentCSeq,

???????? ?? dateHeader(),

???????? ?? streamingModeString, destAddrStr.val(), sourceAddrStr.val(), ntohs(clientRTPPort.num()), ntohs(serverRTPPort.num()),

???????? ?? fOurSessionId);

???? ? break;

???? }

????? }

??? }

??? delete[] streamingModeString;

? } while (0);

?

? delete[] concatenatedStreamName;

}

?

//新建ServerMediaSession的源代碼如下:

static ServerMediaSession* createNewSMS(UsageEnvironment& env,

?????????????????????? char const* fileName, FILE* /*fid*/) {

? // Use the file name extension to determine the type of "ServerMediaSession":

? char const* extension = strrchr(fileName,'.');

? if (extension == NULL) return NULL;

?

? ServerMediaSession* sms = NULL;

? Boolean const reuseSource = False;

? if (strcmp(extension, ".aac") == 0) {

??? // Assumed to be an AAC Audio (ADTS format) file:

??? NEW_SMS("AAC Audio");

??? sms->addSubsession(ADTSAudioFileServerMediaSubsession::createNew(env, fileName, reuseSource));

? } else if (strcmp(extension, ".amr") == 0) {

??? // Assumed to be an AMR Audio file:

??? NEW_SMS("AMR Audio");

??? sms->addSubsession(AMRAudioFileServerMediaSubsession::createNew(env, fileName, reuseSource));

? } else if (strcmp(extension, ".ac3") == 0) {

??? // Assumed to be an AC-3 Audio file:

??? NEW_SMS("AC-3 Audio");

??? sms->addSubsession(AC3AudioFileServerMediaSubsession::createNew(env, fileName, reuseSource));

? } else if (strcmp(extension, ".m4e") == 0) {

??? // Assumed to be a MPEG-4 Video Elementary Stream file:

??? NEW_SMS("MPEG-4 Video");

??? sms->addSubsession(MPEG4VideoFileServerMediaSubsession::createNew(env, fileName, reuseSource));

? } else if (strcmp(extension, ".264") == 0) {

??? // Assumed to be a H.264 Video Elementary Stream file:

??? NEW_SMS("H.264 Video");

??? OutPacketBuffer::maxSize = 100000; // allow for some possibly large H.264 frames

??? sms->addSubsession(H264VideoFileServerMediaSubsession::createNew(env, fileName, reuseSource));

? } else if (strcmp(extension, ".mp3") == 0) {

??? // Assumed to be a MPEG-1 or 2 Audio file:

??? NEW_SMS("MPEG-1 or 2 Audio");

??? // To stream using 'ADUs' rather than raw MP3 frames, uncomment the following:

//#define STREAM_USING_ADUS 1

??? // To also reorder ADUs before streaming, uncomment the following:

//#define INTERLEAVE_ADUS 1

??? // (For more information about ADUs and interleaving,

??? //? see <http://www.live555.com/rtp-mp3/>)

??? Boolean useADUs = False;

??? Interleaving* interleaving = NULL;

#ifdef STREAM_USING_ADUS

??? useADUs = True;

#ifdef INTERLEAVE_ADUS

??? unsigned char interleaveCycle[] = {0,2,1,3}; // or choose your own...

??? unsigned const interleaveCycleSize

????? = (sizeof interleaveCycle)/(sizeof (unsigned char));

??? interleaving = new Interleaving(interleaveCycleSize, interleaveCycle);

#endif

#endif

??? sms->addSubsession(MP3AudioFileServerMediaSubsession::createNew(env, fileName, reuseSource, useADUs, interleaving));

? } else if (strcmp(extension, ".mpg") == 0) {

??? // Assumed to be a MPEG-1 or 2 Program Stream (audio+video) file:

??? NEW_SMS("MPEG-1 or 2 Program Stream");

??? MPEG1or2FileServerDemux* demux

????? = MPEG1or2FileServerDemux::createNew(env, fileName, reuseSource);

??? sms->addSubsession(demux->newVideoServerMediaSubsession());

??? sms->addSubsession(demux->newAudioServerMediaSubsession());

? } else if (strcmp(extension, ".vob") == 0) {

??? // Assumed to be a VOB (MPEG-2 Program Stream, with AC-3 audio) file:

??? NEW_SMS("VOB (MPEG-2 video with AC-3 audio)");

??? MPEG1or2FileServerDemux* demux

????? = MPEG1or2FileServerDemux::createNew(env, fileName, reuseSource);

??? sms->addSubsession(demux->newVideoServerMediaSubsession());

??? sms->addSubsession(demux->newAC3AudioServerMediaSubsession());

? } else if (strcmp(extension, ".ts") == 0) {

??? // Assumed to be a MPEG Transport Stream file:

??? // Use an index file name that's the same as the TS file name, except with ".tsx":

??? unsigned indexFileNameLen = strlen(fileName) + 2;// allow for trailing "x\0"

??? char* indexFileName = new char[indexFileNameLen];

??? sprintf(indexFileName, "%sx", fileName);

??? NEW_SMS("MPEG Transport Stream");

??? sms->addSubsession(MPEG2TransportFileServerMediaSubsession::createNew(env, fileName, indexFileName, reuseSource));

??? delete[] indexFileName;

? } else if (strcmp(extension, ".wav") == 0) {

??? // Assumed to be a WAV Audio file:

??? NEW_SMS("WAV Audio Stream");

??? // To convert 16-bit PCM data to 8-bit u-law, prior to streaming,

??? // change the following to True:

??? Boolean convertToULaw = False;

??? sms->addSubsession(WAVAudioFileServerMediaSubsession::createNew(env, fileName, reuseSource, convertToULaw));

? } else if (strcmp(extension, ".dv") == 0) {

??? // Assumed to be a DV Video file

??? // First, make sure that the RTPSinks' buffers will be large enough to handle the huge size of DV frames (as big as 288000).

??? OutPacketBuffer::maxSize = 300000;

?

??? NEW_SMS("DV Video");

??? sms->addSubsession(DVVideoFileServerMediaSubsession::createNew(env, fileName, reuseSource));

? } else if (strcmp(extension, ".mkv") == 0 || strcmp(extension,".webm") == 0) {

??? // Assumed to be a Matroska file (note that WebM ('.webm') files are also Matroska files)

??? NEW_SMS("Matroska video+audio+(optional)subtitles");

?

??? // Create a Matroska file server demultiplexor for the specified file.?(We enter the event loop to wait for this to complete.)

??? newMatroskaDemuxWatchVariable = 0;

??? MatroskaFileServerDemux::createNew(env, fileName, onMatroskaDemuxCreation, NULL);

??? env.taskScheduler().doEventLoop(&newMatroskaDemuxWatchVariable);

?

??? ServerMediaSubsession* smss;

??? while ((smss = demux->newServerMediaSubsession()) != NULL) {

????? sms->addSubsession(smss);

??? }

? }

?

? return sms;

}

?

?

?

3)????? 服務端對Play命令的處理

?

?

void RTSPServer::RTSPClientSession

::handleCmd_withinSession(RTSPServer::RTSPClientConnection* ourClientConnection,

????????????? ? char const* cmdName,

????????????? ? char const* urlPreSuffix, char const* urlSuffix,

????????????? ? char const* fullRequestStr) {

? // This will either be:

? // - a non-aggregated operation, if "urlPreSuffix" is the session (stream)

? //?? name and "urlSuffix" is the subsession (track) name, or

? // - an aggregated operation, if "urlSuffix" is the session (stream) name,

? //?? or "urlPreSuffix" is the session (stream) name, and "urlSuffix" is empty,

? //?? or "urlPreSuffix" and "urlSuffix" are both nonempty, but when concatenated, (with "/") form the session (stream) name.

? // Begin by figuring out which of these it is:

? ServerMediaSubsession* subsession;

?

? noteLiveness();

? if (fOurServerMediaSession == NULL) {// There wasn't a previous SETUP!

??? ourClientConnection->handleCmd_notSupported();

??? return;

? } else if (urlSuffix[0] != '\0' && strcmp(fOurServerMediaSession->streamName(), urlPreSuffix) == 0) {

??? // Non-aggregated operation.

??? // Look up the media subsession whose track id is "urlSuffix":

??? ServerMediaSubsessionIterator iter(*fOurServerMediaSession);

??? while ((subsession = iter.next()) != NULL) {

????? if (strcmp(subsession->trackId(), urlSuffix) == 0)break;// success

??? }

??? if (subsession == NULL) { // no such track!

????? ourClientConnection->handleCmd_notFound();

????? return;

??? }

? } else if (strcmp(fOurServerMediaSession->streamName(), urlSuffix) == 0 ||

???? ???? (urlSuffix[0] == '\0' && strcmp(fOurServerMediaSession->streamName(), urlPreSuffix) == 0)) {

??? // Aggregated operation

??? subsession = NULL;

? } else if (urlPreSuffix[0] != '\0' && urlSuffix[0] !='\0') {

??? // Aggregated operation, if <urlPreSuffix>/<urlSuffix> is the session (stream) name:

??? unsigned const urlPreSuffixLen = strlen(urlPreSuffix);

??? if (strncmp(fOurServerMediaSession->streamName(), urlPreSuffix, urlPreSuffixLen) == 0 &&

???? fOurServerMediaSession->streamName()[urlPreSuffixLen] == '/' &&

???? strcmp(&(fOurServerMediaSession->streamName())[urlPreSuffixLen+1], urlSuffix) == 0) {

????? subsession = NULL;

??? } else {

????? ourClientConnection->handleCmd_notFound();

????? return;

??? }

? } else { // the request doesn't match a known stream and/or track at all!

??? ourClientConnection->handleCmd_notFound();

??? return;

? }

?

? if (strcmp(cmdName, "TEARDOWN") == 0) {

??? handleCmd_TEARDOWN(ourClientConnection, subsession);

? } else if (strcmp(cmdName, "PLAY") == 0) {

??? handleCmd_PLAY(ourClientConnection, subsession, fullRequestStr);

? } else if (strcmp(cmdName, "PAUSE") == 0) {

??? handleCmd_PAUSE(ourClientConnection, subsession);

? } else if (strcmp(cmdName, "GET_PARAMETER") == 0) {

??? handleCmd_GET_PARAMETER(ourClientConnection, subsession, fullRequestStr);

? } else if (strcmp(cmdName, "SET_PARAMETER") == 0) {

??? handleCmd_SET_PARAMETER(ourClientConnection, subsession, fullRequestStr);

? }

}

?

?

void RTSPServer::RTSPClientSession

::handleCmd_PLAY(RTSPServer::RTSPClientConnection* ourClientConnection,

???????? ?ServerMediaSubsession* subsession, char const* fullRequestStr) {

? char* rtspURL = fOurServer.rtspURL(fOurServerMediaSession, ourClientConnection->fClientInputSocket);

? unsigned rtspURLSize = strlen(rtspURL);

?

? // Parse the client's "Scale:" header, if any:

? float scale;

? Boolean sawScaleHeader = parseScaleHeader(fullRequestStr, scale);

?

? // Try to set the stream's scale factor to this value:

? if (subsession == NULL /*aggregate op*/) {

??? fOurServerMediaSession->testScaleFactor(scale);

? } else {

??? subsession->testScaleFactor(scale);

? }

?

? char buf[100];

? char* scaleHeader;

? if (!sawScaleHeader) {

??? buf[0] = '\0'; // Because we didn't see a Scale: header, don't send one back

? } else {

??? sprintf(buf, "Scale: %f\r\n", scale);

? }

? scaleHeader = strDup(buf);

?

? // Parse the client's "Range:" header, if any:

? float duration = 0.0;

? double rangeStart = 0.0, rangeEnd = 0.0;

? char* absStart = NULL; char* absEnd = NULL;

? Boolean sawRangeHeader = parseRangeHeader(fullRequestStr, rangeStart, rangeEnd, absStart, absEnd);

?

? if (sawRangeHeader && absStart == NULL/*not seeking by 'absolute' time*/) {

??? // Use this information, plus the stream's duration (if known), to create our own "Range:" header, for the response:

??? duration = subsession == NULL /*aggregate op*/

????? ? fOurServerMediaSession->duration() : subsession->duration();

??? if (duration < 0.0) {

????? // We're an aggregate PLAY, but the subsessions have different durations.

????? // Use the largest of these durations in our header

????? duration = -duration;

??? }

?

??? // Make sure that "rangeStart" and "rangeEnd" (from the client's "Range:" header) have sane values

??? // before we send back our own "Range:" header in our response:

??? if (rangeStart < 0.0) rangeStart = 0.0;

??? else if (rangeStart > duration) rangeStart = duration;

??? if (rangeEnd < 0.0) rangeEnd = 0.0;

??? else if (rangeEnd > duration) rangeEnd = duration;

??? if ((scale > 0.0 && rangeStart > rangeEnd && rangeEnd > 0.0) ||

???? (scale < 0.0 && rangeStart < rangeEnd)) {

????? // "rangeStart" and "rangeEnd" were the wrong way around; swap them:

????? double tmp = rangeStart;

????? rangeStart = rangeEnd;

????? rangeEnd = tmp;

??? }

? }

?

? // Create a "RTP-Info:" line.? It will get filled in from each subsession's state:

? char const* rtpInfoFmt =

??? "%s" // "RTP-Info:", plus any preceding rtpInfo items

? ??"%s" // comma separator, if needed

??? "url=%s/%s"

??? ";seq=%d"

??? ";rtptime=%u"

??? ;

? unsigned rtpInfoFmtSize = strlen(rtpInfoFmt);

? char* rtpInfo = strDup("RTP-Info: ");

? unsigned i, numRTPInfoItems = 0;

?

? // Do any required seeking/scaling on each subsession, before starting streaming.

? // (However, we don't do this if the "PLAY" request was for just a single subsession of a multiple-subsession stream;

? //? for such streams, seeking/scaling can be done only with an aggregate "PLAY".)

? for (i = 0; i < fNumStreamStates; ++i) {

??? if (subsession == NULL /* means: aggregated operation */ || fNumStreamStates == 1) {

????? if (sawScaleHeader) {

???? if (fStreamStates[i].subsession != NULL) {

???? ? fStreamStates[i].subsession->setStreamScale(fOurSessionId, fStreamStates[i].streamToken, scale);

???? }

????? }

????? if (sawRangeHeader) {

???? if (absStart != NULL) {

???? ? // Special case handling for seeking by 'absolute' time:

?

???? ? if (fStreamStates[i].subsession != NULL) {

???? ??? fStreamStates[i].subsession->seekStream(fOurSessionId, fStreamStates[i].streamToken, absStart, absEnd);

???? ? }

???? } else {

???? ? // Seeking by relative (NPT) time:

?

???? ? double streamDuration = 0.0;// by default; means: stream until the end of the media

???? ? if (rangeEnd > 0.0 && (rangeEnd+0.001) < duration) {// the 0.001 is because we limited the values to 3 decimal places

???? ??? // We want the stream to end early.?Set the duration we want:

???? ??? streamDuration = rangeEnd - rangeStart;

???? ??? if (streamDuration < 0.0) streamDuration = -streamDuration;// should happen only if scale < 0.0

???? ? }

???? ? if (fStreamStates[i].subsession != NULL) {

???? ??? u_int64_t numBytes;

???????? //查找流

???? ??? fStreamStates[i].subsession->seekStream(fOurSessionId, fStreamStates[i].streamToken,

??????????????????????????? ??? rangeStart, streamDuration, numBytes);

???? ? }

???? }

????? } else {

???? // No "Range:" header was specified in the "PLAY", so we do a 'null' seek (i.e., we don't seek at all):

???? if (fStreamStates[i].subsession != NULL) {

???? ? fStreamStates[i].subsession->nullSeekStream(fOurSessionId, fStreamStates[i].streamToken);

???? }

????? }

??? }

? }

?

? // Create the "Range:" header that we'll send back in our response.

? // (Note that we do this after seeking, in case the seeking operation changed the range start time.)

? char* rangeHeader;

? if (!sawRangeHeader) {

??? // There wasn't a "Range:" header in the request, so, in our response, begin the range with the current NPT (normal play time):

??? float curNPT = 0.0;

??? for (i = 0; i < fNumStreamStates; ++i) {

????? if (subsession == NULL /* means: aggregated operation */

???? ? || subsession == fStreamStates[i].subsession) {

???? if (fStreamStates[i].subsession == NULL)continue;

???? float npt = fStreamStates[i].subsession->getCurrentNPT(fStreamStates[i].streamToken);

???? if (npt > curNPT) curNPT = npt;

???? // Note: If this is an aggregate "PLAY" on a multi-subsession stream, then it's conceivable that the NPTs of each subsession

???? // may differ (if there has been a previous seek on just one subsession).?In this (unusual) case, we just return the

???? // largest NPT; I hope that turns out OK...

????? }

??? }

?

??? sprintf(buf, "Range: npt=%.3f-\r\n", curNPT);

? } else if (absStart != NULL) {

??? // We're seeking by 'absolute' time:

??? if (absEnd == NULL) {

????? sprintf(buf, "Range: clock=%s-\r\n", absStart);

??? } else {

????? sprintf(buf, "Range: clock=%s-%s\r\n", absStart, absEnd);

??? }

??? delete[] absStart; delete[] absEnd;

? } else {

??? // We're seeking by relative (NPT) time:

??? if (rangeEnd == 0.0 && scale >= 0.0) {

????? sprintf(buf, "Range: npt=%.3f-\r\n", rangeStart);

??? } else {

????? sprintf(buf, "Range: npt=%.3f-%.3f\r\n", rangeStart, rangeEnd);

??? }

? }

? rangeHeader = strDup(buf);

?

? // Now, start streaming:

? for (i = 0; i < fNumStreamStates; ++i) {

??? if (subsession == NULL /* means: aggregated operation */

???? || subsession == fStreamStates[i].subsession) {

????? unsigned short rtpSeqNum = 0;

????? unsigned rtpTimestamp = 0;

????? if (fStreamStates[i].subsession == NULL)continue;

????? fStreamStates[i].subsession->startStream(fOurSessionId,

?????????????????????? ?????? fStreamStates[i].streamToken,

?????????????????????? ?????? (TaskFunc*)noteClientLiveness, this,

?????????????????????? ?????? rtpSeqNum, rtpTimestamp,

???? ?????????????????? ?????? RTSPServer::RTSPClientConnection::handleAlternativeRequestByte, ourClientConnection);

????? const char *urlSuffix = fStreamStates[i].subsession->trackId();

????? char* prevRTPInfo = rtpInfo;

????? unsigned rtpInfoSize = rtpInfoFmtSize

???? + strlen(prevRTPInfo)

???? + 1

???? + rtspURLSize + strlen(urlSuffix)

???? + 5 /*max unsigned short len*/

???? + 10 /*max unsigned (32-bit) len*/

???? + 2 /*allows for trailing \r\n at final end of string*/;

????? rtpInfo = new char[rtpInfoSize];

????? sprintf(rtpInfo, rtpInfoFmt,

???? ? ????prevRTPInfo,

???? ????? numRTPInfoItems++ == 0 ? "" :",",

???? ????? rtspURL, urlSuffix,

???? ????? rtpSeqNum,

???? ????? rtpTimestamp

???? ????? );

????? delete[] prevRTPInfo;

??? }

? }

? if (numRTPInfoItems == 0) {

??? rtpInfo[0] = '\0';

? } else {

??? unsigned rtpInfoLen = strlen(rtpInfo);

??? rtpInfo[rtpInfoLen] = '\r';

??? rtpInfo[rtpInfoLen+1] = '\n';

??? rtpInfo[rtpInfoLen+2] = '\0';

? }

?

? // Fill in the response:

? snprintf((char*)ourClientConnection->fResponseBuffer,sizeof ourClientConnection->fResponseBuffer,

???? ?? "RTSP/1.0 200 OK\r\n"

???? ?? "CSeq: %s\r\n"

???? ?? "%s"

???? ?? "%s"

???? ?? "%s"

???? ?? "Session: %08X\r\n"

???? ?? "%s\r\n",

???? ?? ourClientConnection->fCurrentCSeq,

???? ?? dateHeader(),

???? ?? scaleHeader,

???? ?? rangeHeader,

???? ?? fOurSessionId,

???? ?? rtpInfo);

? delete[] rtpInfo; delete[] rangeHeader;

? delete[] scaleHeader; delete[] rtspURL;

}

?

Live555 RTP建立流程

?

RTP的建立流程在客戶端發送Setup請求開始建立,客戶端發送Setup請求時,會將RTP/RTCP的端口號告訴服務端,也會將Rtp over tcp還是udp的方式告訴到服務端,服務端收到Setup請求時,根據端口號建立socket,在收到客戶端的Play命令時,啟動流傳輸;啟動流傳輸的代碼如下:

?

void OnDemandServerMediaSubsession::startStream(unsigned clientSessionId,

??????????????????????????? void* streamToken,

??????????????????????????? TaskFunc* rtcpRRHandler,

??????????????????????????? void* rtcpRRHandlerClientData,

??????????????????????????? unsignedshort& rtpSeqNum,

??????????????????????????? unsigned& rtpTimestamp,

??????????????????????????? ServerRequestAlternativeByteHandler* serverRequestAlternativeByteHandler,

??????????????????????????? void* serverRequestAlternativeByteHandlerClientData) {

? StreamState* streamState = (StreamState*)streamToken;

? Destinations* destinations

??? = (Destinations*)(fDestinationsHashTable->Lookup((charconst*)clientSessionId));

? if (streamState != NULL) {

??? streamState->startPlaying(destinations,

????????????? ????? rtcpRRHandler, rtcpRRHandlerClientData,

????????????? ????? serverRequestAlternativeByteHandler, serverRequestAlternativeByteHandlerClientData);

??? RTPSink* rtpSink = streamState->rtpSink(); // alias

??? if (rtpSink != NULL) {

????? rtpSeqNum = rtpSink->currentSeqNo();

????? rtpTimestamp = rtpSink->presetNextTimestamp();

??? }

? }

}

?

//

Live555 rtsp/rtp是同一個socket,但端口號不同嗎?

看源碼:

?

void OnDemandServerMediaSubsession

::getStreamParameters(unsigned clientSessionId,

???????? ????? netAddressBits clientAddress,

???????? ????? Port const& clientRTPPort,

???????? ????? Port const& clientRTCPPort,

???????? ????? int tcpSocketNum,

???????? ????? unsigned char rtpChannelId,

???????? ????? unsigned char rtcpChannelId,

???????? ????? netAddressBits& destinationAddress,

???????? ????? u_int8_t& /*destinationTTL*/,

???????? ????? Boolean& isMulticast,

???????? ????? Port& serverRTPPort,

???????? ????? Port& serverRTCPPort,

???????? ????? void*& streamToken) {

? if (destinationAddress == 0) destinationAddress = clientAddress;

? struct in_addr destinationAddr; destinationAddr.s_addr = destinationAddress;

? isMulticast = False;

?

? if (fLastStreamToken != NULL && fReuseFirstSource) {

??? // Special case: Rather than creating a new 'StreamState',

??? // we reuse the one that we've already created:

??? serverRTPPort = ((StreamState*)fLastStreamToken)->serverRTPPort();

??? serverRTCPPort = ((StreamState*)fLastStreamToken)->serverRTCPPort();

??? ++((StreamState*)fLastStreamToken)->referenceCount();

??? streamToken = fLastStreamToken;

? } else {

??? // Normal case: Create a new media source:

??? unsigned streamBitrate;

??? FramedSource* mediaSource

????? = createNewStreamSource(clientSessionId, streamBitrate);

?

??? // Create 'groupsock' and 'sink' objects for the destination,

??? // using previously unused server port numbers:

??? RTPSink* rtpSink;

??? BasicUDPSink* udpSink;

??? Groupsock* rtpGroupsock;

??? Groupsock* rtcpGroupsock;

??? portNumBits serverPortNum;

?? ?if (clientRTCPPort.num() == 0) {

????? // We're streaming raw UDP (not RTP). Create a single groupsock:

????? NoReuse dummy(envir()); // ensures that we skip over ports that are already in use

????? for (serverPortNum = fInitialPortNum; ; ++serverPortNum) {

???? struct in_addr dummyAddr; dummyAddr.s_addr = 0;

?

???? serverRTPPort = serverPortNum;

???? rtpGroupsock = new Groupsock(envir(), dummyAddr, serverRTPPort, 255);

???? if (rtpGroupsock->socketNum() >= 0)break;// success

????? }

?

????? rtcpGroupsock = NULL;

????? rtpSink = NULL;

????? udpSink = BasicUDPSink::createNew(envir(), rtpGroupsock);

??? } else {

????? // Normal case: We're streaming RTP (over UDP or TCP).?Create a pair of

????? // groupsocks (RTP and RTCP), with adjacent port numbers (RTP port number even):

????? NoReuse dummy(envir()); // ensures that we skip over ports that are already in use

????? for (portNumBits serverPortNum = fInitialPortNum; ; serverPortNum += 2) {

???? struct in_addr dummyAddr; dummyAddr.s_addr = 0;

?

???? serverRTPPort = serverPortNum;

?

???? //建立RTPsocket

???? rtpGroupsock = new Groupsock(envir(), dummyAddr, serverRTPPort, 255);

???? if (rtpGroupsock->socketNum() < 0) {

???? ? delete rtpGroupsock;

???? ? continue; // try again

???? }

????

? ???//建立Rtcp socket

???? serverRTCPPort = serverPortNum+1;

???? rtcpGroupsock = new Groupsock(envir(), dummyAddr, serverRTCPPort, 255);

???? if (rtcpGroupsock->socketNum() < 0) {

???? ? delete rtpGroupsock;

???? ? delete rtcpGroupsock;

???? ? continue; // try again

???? }

?

???? break; // success

????? }

?

????? unsigned char rtpPayloadType = 96 + trackNumber()-1; // if dynamic

????? rtpSink = createNewRTPSink(rtpGroupsock, rtpPayloadType, mediaSource);

????? udpSink = NULL;

??? }

?

??? // Turn off the destinations for each groupsock.?They'll get set later

??? // (unless TCP is used instead):

??? if (rtpGroupsock != NULL) rtpGroupsock->removeAllDestinations();

??? if (rtcpGroupsock != NULL) rtcpGroupsock->removeAllDestinations();

?

??? if (rtpGroupsock != NULL) {

????? // Try to use a big send buffer for RTP -?at least 0.1 second of

????? // specified bandwidth and at least 50 KB

????? unsigned rtpBufSize = streamBitrate * 25 / 2;// 1 kbps * 0.1 s = 12.5 bytes

????? if (rtpBufSize < 50 * 1024) rtpBufSize = 50 * 1024;

????? increaseSendBufferTo(envir(), rtpGroupsock->socketNum(), rtpBufSize);

??? }

?

??? // Set up the state of the stream.?The stream will get started later:

??? streamToken = fLastStreamToken

????? = new StreamState(*this, serverRTPPort, serverRTCPPort, rtpSink, udpSink,

????????????? streamBitrate, mediaSource,

????????????? rtpGroupsock, rtcpGroupsock);

? }

?

? // Record these destinations as being for this client session id:

? Destinations* destinations;

? if (tcpSocketNum < 0) { // UDP

??? destinations = new Destinations(destinationAddr, clientRTPPort, clientRTCPPort);

? } else { // TCP

??? destinations = new Destinations(tcpSocketNum, rtpChannelId, rtcpChannelId);

? }

? fDestinationsHashTable->Add((charconst*)clientSessionId, destinations);

}

?

//從這段代碼中可以看到rtsp,rtp,rtcp的socket是不同的;同時分析了客戶端的源碼,socket也是不一樣的,初始化subsession時,在其中會建立RTP/RTCP?socket以及RTPSource。對于每個subsession都會建立不同的socket。

?

?

3)MediaSession和socket的關系?一個MediaSession包括多個連接,關聯到多個socket嗎?

MediaSession 包括多個MediaSubSession,每個MediaSubSession對應相應的socket,source和sink,形成一個數據流!

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/253146.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/253146.shtml
英文地址,請注明出處:http://en.pswp.cn/news/253146.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

運放搭建主動濾波電路

主動低通濾波電路 R1R216K R3R4100K C1C20.01uF 放大倍數AvR4/(R3R4) Freq1KHz 主動高通濾波電路 C12*C20.02uF,C20.01uF R1R2110K 6dBLow-cutFreq100Hz

deployd使用

安裝node,用npm 安裝deployd , npm install deployd -g。 cd進入文件夾&#xff0c;輸入 dpd create deploydDemo&#xff0c;然后 dpd -p 5500 deploydDemo\app.dpd&#xff08;5500是你開啟的mongodb創建的服務&#xff09;&#xff0c;接著在瀏覽器中輸入 http://localhost:…

android自定義布局實現優惠券效果

最近需要實現一個凹凸效果的擬物化優惠券效果&#xff0c;我一看&#xff0c;本來想用.9圖片做背景實現的&#xff0c;雖說圖片做背景實現省事兒方便&#xff0c;但是能用代碼實現最好不過了&#xff0c;最終我還是選擇了用代碼來實現&#xff0c;于是有了下文。 最終效果圖 de…

郵件實現詳解(四)------JavaMail 發送(帶圖片和附件)和接收郵件

好了&#xff0c;進入這個系列教程最主要的步驟了&#xff0c;前面郵件的理論知識我們都了解了&#xff0c;那么這篇博客我們將用代碼完成郵件的發送。這在實際項目中應用的非常廣泛&#xff0c;比如注冊需要發送郵件進行賬號激活&#xff0c;再比如OA項目中利用郵件進行任務提…

運放搭建電壓電流轉換電路分析

如下圖電路&#xff0c;電流可以轉換成電壓&#xff0c;電壓也可以轉換成電流&#xff1b; 根據虛斷&#xff1a;(Vi–V1)/R2 (V1–V4)/R6 &#xff08;a&#xff09; 同理 (V3–V2)/R5V2/R4 &#xff08;b&#xff09; 根據虛短&#xff1a; V1V2 &#xff08;c&#xff09…

centos7裝完chrome無法使用yum問題解決

2019獨角獸企業重金招聘Python工程師標準>>> 續前文裝好chrome后&#xff0c;yum居然用不了&#xff0c;提示錯誤“Basic XLib functionality test failed!” 呵呵。。。呵呵了.... 【題外話~個人真心覺得pythonseleniumchrome在linux環境下開發和使用 簡直蛋疼無比…

實驗二第二部分

第二部分 FTP協議分析 1. 兩個同學一組&#xff0c;A和B。 2.A同學架設FTP服務器&#xff0c;并設置用戶名和密碼&#xff0c;例如gao / gao 3.B同學在機器中安裝Wireshark&#xff0c;并將其打開&#xff1b;之后用用戶名和密碼登陸A同學的FTP服務器&#xff0c;并上傳一張圖片…

運放搭建的跟隨電路作用與分析

電壓跟隨器&#xff0c;顧名思義就是輸出電壓與輸入電壓是相同的&#xff0c;就是說電壓跟隨器的電壓放大倍數恒小于且接近1。 電壓跟隨器的顯著特點就是&#xff0c;輸入阻抗高&#xff0c;而輸出阻抗低。 根據其顯著特點&#xff0c;常見的作用如下&#xff1a; 1- 緩沖 在…

Spring Boot(十二)單元測試JUnit

一、介紹 JUnit是一款優秀的開源Java單元測試框架&#xff0c;也是目前使用率最高最流行的測試框架&#xff0c;開發工具Eclipse和IDEA對JUnit都有很好的支持&#xff0c;JUnit主要用于白盒測試和回歸測試。 白盒測試&#xff1a;把測試對象看作一個打開的盒子&#xff0c;程序…

介紹TCP/udp比較好的博客

http://blog.csdn.net/nana_93/article/details/8743525

Kubernetes容器上下文環境

目錄貼&#xff1a;Kubernetes學習系列 下面我們將主要介紹運行在Kubernetes集群中的容器所能夠感知到的上下文環境&#xff0c;以及容器是如何獲知這些信息的。 首先&#xff0c;Kubernetes提供了一個能夠讓容器感知到集群中正在發生的事情的方法&#xff1a;環境變量。作為容…

Shell-腳本只能運行1次

用空文件進行判斷 pathpwd if [ -f ${path}/.runned ]; then {echo "This script can only execute once! You have runned it!"exit } elsetouch ${path}/.runned fi 轉載于:https://www.cnblogs.com/music378/p/7677648.html

運放電壓跟隨電路應用

電壓跟隨器的顯著特點&#xff1a;輸入阻抗高&#xff0c;輸出阻抗低。 如下所示為利用放大器搭建的電壓跟隨電路&#xff0c;方便測量電壓大小&#xff1a; 此電路目的是測量電池電壓&#xff0c;電池電壓范圍&#xff08;3~4.2V&#xff09;分壓后最大電壓為2.1V 屬于3.3V電…

Mac與Phy組成原理的簡單分析

Mac與Phy組成原理的簡單分析 2011-12-28 15:30:43 //http://blog.chinaunix.net/uid-20528014-id-3050217.html 本文乃fireaxe原創&#xff0c;使用GPL發布&#xff0c;可以自由拷貝&#xff0c;轉載。但轉載請保持文檔的完整性&#xff0c;并注明原作者及原鏈接。內容可任意使…

[BZOJ3994][SDOI2015]約數個數和

3994: [SDOI2015]約數個數和 Time Limit: 20 Sec Memory Limit: 128 MB Submit: 1104 Solved: 762 [Submit][Status][Discuss]Description 設d(x)為x的約數個數&#xff0c;給定N、M&#xff0c;求 Input 輸入文件包含多組測試數據。 第一行&#xff0c;一個整數T&#xff0…

月蝕動漫獲快看漫畫600萬元A輪戰略投資,走國漫精品化路線

11月5日消息&#xff0c;月蝕動漫宣布獲得快看漫畫600萬元A輪戰略投資。 據了解&#xff0c;月蝕動漫曾于2017年1月獲得原力創投的百萬級種子輪投資&#xff0c;2018年1月獲得英諾天使基金的百萬級天使輪投資。 據月蝕動漫創始人賀小桐透露&#xff0c;團隊能在行業寒冬期獲得…

大力智能臺燈T6 結構拆解

近幾年教育硬件產品層出不窮&#xff0c;教育硬件賽道布局時間較長的有網易、訊飛、步步高系等公司&#xff0c;2020年10月&#xff0c;字節跳動旗下大力教育經過兩年多的調研和研發&#xff0c;高調推出首款智能硬件產品“大力智能作業臺燈” T5。 上市一年取得不錯的銷售成績…

C++靜態庫與動態庫

http://www.cnblogs.com/skynet/p/3372855.html

第5章 IDA Pro

5.1 加載一個可執行文件 默認情況下IDA Pro的反匯編代碼中不包含PE頭或資源節&#xff0c;可以手動指定加載。 5.2 IDA Pro接口 5.2.1 反匯編窗口模式 二進制模式/圖形模式&#xff1a; 圖形模式&#xff1a;紅色表示一個條件跳轉沒有被采用&#xff0c;綠色表示這個條件跳轉被…

樹鏈剖分(模板)

luogu題庫 題目描述 如題&#xff0c;已知一棵包含N個結點的樹&#xff08;連通且無環&#xff09;&#xff0c;每個節點上包含一個數值&#xff0c;需要支持以下操作&#xff1a; 操作1&#xff1a; 格式&#xff1a; 1 x y z 表示將樹從x到y結點最短路徑上所有節點的值都加上…