整體上對最簡單RtspServer的介紹
int main()
{
TaskScheduler* scheduler;
UsageEnvironment* env ;
RTSPServer* rtspServer;
ServerMediaSession* sms;
//建立任務調用器
scheduler = BasicTaskScheduler::createNew();
//建立互動環境
env = BasicUsageEnvironment::createNew(*scheduler);
//建立RTSP伺服器
rtspServer = RTSPServer::createNew(*env,554); //使用554端口
if(rtspServer == NULL)
{
rtspServer = RTSPServer::createNew(*env,8554); //554端口被占用,就使用8554端口
}
//列印伺服器位址
*env << "Play streams from this server using the URL\n\t"
<< rtspServer->rtspURLPrefix() << "<filename>.\n";
//建立session
sms = createNewSMS(*env, "test.mpg");
rtspServer->addServerMediaSession(sms);
//添加其它檔案對應的session...
//進行事件循環
env->taskScheduler().doEventLoop(); // does not return
return 0;
}
介紹一下用到的四個類:
1、UsageEnvironment
UsageEnvironment 代表了整個系統運作的環境,它提供了錯誤記錄和錯誤報告的功能,無論哪一個類要輸出錯誤,就需要儲存UsageEnvironment 的指針.
2、TaskScheduler
TaskScheduler 則提供了任務排程功能.整個程式的運作發動機就是它,它排程任務,執行任務(任務就是一個函數).TaskScheduler 由于在全局中隻有一個,是以儲存在了UsageEnvironment 中.而所有的類又都儲存了UsageEnvironment 的指針,是以誰想把自己的任務加入排程中,那是很容易的.
3、RTSPServer
livemedia庫中的RTSPServer類(繼承自基類Medium)用于建構一個RTSP伺服器,該類同時在其内部定義了一個RTSPClientSession類,用于處理單獨的客戶會話。
4、ServerMediaSession
livemedia庫中的ServerMediaSession類(繼承自基類Medium)用來處理會話中描述,它包含多個(音頻或視訊)的子會話描述(ServerMediaSubsession)。
任務循環體介紹
函數 env->taskScheduler().doEventLoop()中,看名字很明顯是一個消息循壞,執行到裡面後不停地轉圈,生命不息,轉圈不止。
函數原型
void BasicTaskScheduler0::doEventLoop(char* watchVariable) {
// Repeatedly loop, handling readble sockets and timed events:
while (1) {
if (watchVariable != NULL && *watchVariable != 0) break;
SingleStep();
}
}
現在我們的疑問是SingleStep();到底幹了什麼?
void BasicTaskScheduler::SingleStep(unsigned maxDelayTime)
{
fd_set readSet = fReadSet; // make a copy for this select() call
fd_set writeSet = fWriteSet; // ditto
fd_set exceptionSet = fExceptionSet; // ditto
//設定select時間
DelayInterval const& timeToDelay = fDelayQueue.timeToNextAlarm();
struct timeval tv_timeToDelay;
tv_timeToDelay.tv_sec = timeToDelay.seconds();
tv_timeToDelay.tv_usec = timeToDelay.useconds();
// Very large "tv_sec" values cause select() to fail.
// Don't make it any larger than 1 million seconds (11.5 days)
const long MAX_TV_SEC = MILLION;
if (tv_timeToDelay.tv_sec > MAX_TV_SEC) {
tv_timeToDelay.tv_sec = MAX_TV_SEC;
}
// Also check our "maxDelayTime" parameter (if it's > 0):
if (maxDelayTime > 0 &&
(tv_timeToDelay.tv_sec > (long)maxDelayTime/MILLION ||
(tv_timeToDelay.tv_sec == (long)maxDelayTime/MILLION &&
tv_timeToDelay.tv_usec > (long)maxDelayTime%MILLION))) {
tv_timeToDelay.tv_sec = maxDelayTime/MILLION;
tv_timeToDelay.tv_usec = maxDelayTime%MILLION;
}
//執行socket 的select 操作,以确定哪些socket 任務(handler)需要執行。
int selectResult = select(fMaxNumSockets, &readSet, &writeSet, &exceptionSet, &tv_timeToDelay);
if (selectResult < 0) {
#if defined(__WIN32__) || defined(_WIN32)
int err = WSAGetLastError();
// For some unknown reason, select() in Windoze sometimes fails with WSAEINVAL if
// it was called with no entries set in "readSet". If this happens, ignore it:
if (err == WSAEINVAL && readSet.fd_count == 0) {
err = EINTR;
// To stop this from happening again, create a dummy socket:
int dummySocketNum = socket(AF_INET, SOCK_DGRAM, 0);
FD_SET((unsigned)dummySocketNum, &fReadSet);
}
if (err != EINTR) {
#else
if (errno != EINTR && errno != EAGAIN) {
#endif
// Unexpected error - treat this as fatal:
#if !defined(_WIN32_WCE)
perror("BasicTaskScheduler::SingleStep(): select() fails");
#endif
internalError();
}
}
// Call the handler function for one readable socket:
HandlerIterator iter(*fHandlers);
HandlerDescriptor* handler;
// To ensure forward progress through the handlers, begin past the last
// socket number that we handled: //找到上次執行的SocketNum
if (fLastHandledSocketNum >= 0) {
while ((handler = iter.next()) != NULL) {
if (handler->socketNum == fLastHandledSocketNum) break;
}
if (handler == NULL) {
fLastHandledSocketNum = -1;
iter.reset(); // start from the beginning instead
}
} //從找到的 handler 開始,找一個可以執行的 handler,不論其狀态是可讀,可寫,還是出錯,執行之。
while ((handler = iter.next()) != NULL) {
int sock = handler->socketNum; // alias
int resultConditionSet = 0;
if (FD_ISSET(sock, &readSet) && FD_ISSET(sock, &fReadSet)/*sanity check*/) resultConditionSet |= SOCKET_READABLE;
if (FD_ISSET(sock, &writeSet) && FD_ISSET(sock, &fWriteSet)/*sanity check*/) resultConditionSet |= SOCKET_WRITABLE;
if (FD_ISSET(sock, &exceptionSet) && FD_ISSET(sock, &fExceptionSet)/*sanity check*/) resultConditionSet |= SOCKET_EXCEPTION;
if ((resultConditionSet&handler->conditionSet) != 0 && handler->handlerProc != NULL) {
fLastHandledSocketNum = sock;
// Note: we set "fLastHandledSocketNum" before calling the handler,
// in case the handler calls "doEventLoop()" reentrantly.
(*handler->handlerProc)(handler->clientData, resultConditionSet);
break;
}
}
//如果尋找完了依然沒有執行任何 handle ,則從頭再找。
if (handler == NULL && fLastHandledSocketNum >= 0) {
// We didn't call a handler, but we didn't get to check all of them,
// so try again from the beginning:
iter.reset();
while ((handler = iter.next()) != NULL) {
int sock = handler->socketNum; // alias
int resultConditionSet = 0;
if (FD_ISSET(sock, &readSet) && FD_ISSET(sock, &fReadSet)/*sanity check*/) resultConditionSet |= SOCKET_READABLE;
if (FD_ISSET(sock, &writeSet) && FD_ISSET(sock, &fWriteSet)/*sanity check*/) resultConditionSet |= SOCKET_WRITABLE;
if (FD_ISSET(sock, &exceptionSet) && FD_ISSET(sock, &fExceptionSet)/*sanity check*/) resultConditionSet |= SOCKET_EXCEPTION;
if ((resultConditionSet&handler->conditionSet) != 0 && handler->handlerProc != NULL) {
fLastHandledSocketNum = sock;
// Note: we set "fLastHandledSocketNum" before calling the handler,
// in case the handler calls "doEventLoop()" reentrantly.
(*handler->handlerProc)(handler->clientData, resultConditionSet);
break;
}
}
if (handler == NULL) fLastHandledSocketNum = -1;//because we didn't call a handler
}
// Also handle any newly-triggered event (Note that we do this *after* calling a socket handler,
// in case the triggered event handler modifies The set of readable sockets.) //響應事件
if (fTriggersAwaitingHandling != 0) {
if (fTriggersAwaitingHandling == fLastUsedTriggerMask) {
// Common-case optimization for a single event trigger:
fTriggersAwaitingHandling = 0;
if (fTriggeredEventHandlers[fLastUsedTriggerNum] != NULL) { // 執行一個事件處理函數
(*fTriggeredEventHandlers[fLastUsedTriggerNum])(fTriggeredEventClientDatas[fLastUsedTriggerNum]);
}
} else {
// Look for an event trigger that needs handling (making sure that we make forward progress through all possible triggers): //尋找一個執行的事件
unsigned i = fLastUsedTriggerNum;
EventTriggerId mask = fLastUsedTriggerMask;
do {
i = (i+1)%MAX_NUM_EVENT_TRIGGERS;
mask >>= 1;
if (mask == 0) mask = 0x80000000;
if ((fTriggersAwaitingHandling&mask) != 0) {
fTriggersAwaitingHandling &=~ mask;
if (fTriggeredEventHandlers[i] != NULL) { //執行一個事件處理函數
(*fTriggeredEventHandlers[i])(fTriggeredEventClientDatas[i]);
}
fLastUsedTriggerMask = mask;
fLastUsedTriggerNum = i;
break;
}
} while (i != fLastUsedTriggerNum);
}
}
//執行一個最迫切的延遲任務。
// Also handle any delayed event that may have come due.
fDelayQueue.handleAlarm();
}
由上面代碼可知,SingleStep()執行以下四步:
1為所有需要操作的socket 執行select 。
2找出第一個應執行的socket 任務(handler) 并執行之。
3找到第一個應響應的事件,并執行之。
4找到第一個應執行的延遲任務并執行之。
換言之,它隻是任務排程的一個方法,該方法找到最需要執行的任務并執行之。