live555之打包和發送

轉自:http://xingyunbaijunwei.blog.163.com/blog/static/7653806720122212429948/

這裏主要分析一下,live555中關於RTP打包發送的部分。在處理完PLAY命令之後,就開始發送RTP數據包了(其實在發送PLAY命令的response包之前,就會發送一個RTP包,這裏傳輸就已經開始了)
        RTP包的發送是從MediaSink::startPlaying函數調用開始的,應是sink跟source要數據,所以從sink上調用startplaying。

  1. Boolean MediaSink::startPlaying(MediaSource& source,   afterPlayingFunc* afterFunc, void* afterClientData)  
  2. {  
  3.     //參數afterFunc是在播放結束時才被調用。   
  4.     // Make sure we're not already being played:   
  5.     if (fSource != NULL) {  
  6.         envir().setResultMsg("This sink is already being played");  
  7.         return False;  
  8.     }  
  9.   
  10.   
  11.     // Make sure our source is compatible:   
  12.     if (!sourceIsCompatibleWithUs(source)) {  
  13.         envir().setResultMsg(  
  14.                 "MediaSink::startPlaying(): source is not compatible!");  
  15.         return False;  
  16.     }  
  17.     //記下一些要使用的對象   
  18.     fSource = (FramedSource*) &source;  
  19.   
  20.   
  21.     fAfterFunc = afterFunc;  
  22.     fAfterClientData = afterClientData;  
  23.     return continuePlaying();  
  24. }  

        這個函數只有最後一句最重要,即continuePlaying函數的調用。continuePlaying函數是定義在MediaSink類中的純虛函數,需要到特定媒體的sink子類中實現,對於H264來講是在H264VideoRTPSink中實現的。
       H264VideoRTPSink繼承關係:H264VideoRTPSink->VideoRTPSink->MultiFramedRTPSink->RTPSink->MediaSink。

 
  1. Boolean H264VideoRTPSink::continuePlaying() {  
  2.   // First, check whether we have a 'fragmenter' class set up yet.   
  3.   // If not, create it now:   
  4.   if (fOurFragmenter == NULL) {  
  5.     //創建一個輔助類H264FUAFragmenter,用於H264的RTP打包     
  6.   
  7.     fOurFragmenter = new H264FUAFragmenter(envir(), fSource, OutPacketBuffer::maxSize,  
  8.                        ourMaxPacketSize() - 12/*RTP hdr size*/);  
  9.     fSource = fOurFragmenter;  
  10.   }  
  11.   
  12.   // Then call the parent class's implementation:   
  13.   return MultiFramedRTPSink::continuePlaying();  


        上面的代碼中創建了一個輔助類H264FUAFragmenter,因爲H264的RTP包,有些特殊需要進一步處理,可以參考RFC3986。接着調用MultiFramedRTPSink類的continuePlaying實現。
        MultiFramedRTPSink是與幀有關的類,其實它要求每次必須從source獲得一個幀的數據,所以才叫這個name。可以看到continuePlaying()完全被buildAndSendPacket()代替。看一下buildAndSendPacket():

 
  1. Boolean MultiFramedRTPSink::continuePlaying() {  
  2.   // Send the first packet.   
  3.   // (This will also schedule any future sends.)   
  4.   buildAndSendPacket(True);  
  5.   return True;  
  6. }  

     這時調用buildAndSendPacket函數時,看名字就知道其中將完成打包併發送工作。傳遞了一個True參數,表示這是第一個packet。繼續看buildAndSendPacket函數定義  


  1. void MultiFramedRTPSink::buildAndSendPacket(Boolean isFirstPacket) {  
  2.   fIsFirstPacket = isFirstPacket;  
  3.     // 此函數中主要是準備rtp包的頭,爲一些需要跟據實際數據改變的字段留出位置。
  4.     //設置RTP頭,注意,接收端需要根據RTP包的序號fSeqNo來重新排序   
  5.     //   
  6.   // Set up the RTP header:   
  7.   unsigned rtpHdr = 0x80000000; // RTP version 2; marker ('M') bit not set (by default; it can be set later)   
  8.   rtpHdr |= (fRTPPayloadType<<16);  
  9.   rtpHdr |= fSeqNo; // sequence number   
  10.   fOutBuf->enqueueWord(rtpHdr);  //向包中加入一個字
  11.   
  12.   
  13.   //保留一個4 bytes空間,用於設置time stamp   
  14.   // Note where the RTP timestamp will go.   
  15.   // (We can't fill this in until we start packing payload frames.)   
  16.   fTimestampPosition = fOutBuf->curPacketSize();  
  17.   fOutBuf->skipBytes(4); // leave a hole for the timestamp   
  18.   
  19.   fOutBuf->enqueueWord(SSRC());     //跟RTCP相關   
  20.       
  21.     //在RTP頭後面,添加一個payload-format-specific頭,   
  22. // Allow for a special, payload-format-specific header following the   
  23.   // RTP header:   
  24.   fSpecialHeaderPosition = fOutBuf->curPacketSize();  
  25.     //   
  26.     //specialHeaderSize在MultiFramedRTPSink中的默認實現返回0,對於H264的實現不需要處理這個字段   
  27.     //   
  28.   fSpecialHeaderSize = specialHeaderSize();  
  29.   fOutBuf->skipBytes(fSpecialHeaderSize);   //預留空間   
  30.   
  31.   
  32.    //填充儘可能多的frames到packet中   
  33.   // Begin packing as many (complete) frames into the packet as we can:   
  34.   fTotalFrameSpecificHeaderSizes = 0;  
  35.   fNoFramesLeft = False;  
  36.   fNumFramesUsedSoFar = 0;   // 一個包中已打入的幀數。    
        //頭準備好了,再打包幀數據   
  37.   packFrame();  
  38. }  

        buildAndSendPacket函數中,完成RTP頭的準備工作。可以看到RTP頭是非常簡單的,RTP頭中的序號非常重要,客戶端需要據此進行RTP包的重排序操作。RTP包內容存放在一個OutPacketBuffer類型的fOutBuf成員變量中,OutPacketBuffer類的細節在文章的最後還會討論。在RTP頭中預留了一些空間沒有進行實際的填充,這個工作將在doSpecialFrameHandling中進行,後面會有討論。進一步的工作,在packFrame函數中進行,它將爲RTP包填充數據。

 
  1. void MultiFramedRTPSink::packFrame()  
  2. {  
  3.     // First, see if we have an overflow frame that was too big for the last pkt   
  4.     if (fOutBuf->haveOverflowData()) {  
  5.         //如果有幀數據,則使用之。OverflowData是指上次打包時剩下的幀數據,因爲一個包可能容納不了一個幀。   
  6.         // Use this frame before reading a new one from the source   
  7.         unsigned frameSize = fOutBuf->overflowDataSize();  
  8.         struct timeval presentationTime = fOutBuf->overflowPresentationTime();  
  9.         unsigned durationInMicroseconds =fOutBuf->overflowDurationInMicroseconds();  
  10.         fOutBuf->useOverflowData();    
  11.   
  12.         afterGettingFrame1(frameSize, 0, presentationTime,durationInMicroseconds);  
  13.     } else {  
  14.         //一點幀數據都沒有,跟source要吧。   
  15.         // Normal case: we need to read a new frame from the source   
  16.         if (fSource == NULL)  
  17.             return;    
  18.   
  19.         //更新緩衝中的一些位置   
  20.         fCurFrameSpecificHeaderPosition = fOutBuf->curPacketSize();  
  21.         fCurFrameSpecificHeaderSize = frameSpecificHeaderSize();  
  22.         fOutBuf->skipBytes(fCurFrameSpecificHeaderSize);  
  23.         fTotalFrameSpecificHeaderSizes += fCurFrameSpecificHeaderSize;  
  24.   
  25.         //從source獲取下一幀   
  26.        fSource->getNextFrame(fOutBuf->curPtr(),//新數據存放開始的位置   
  27.                 fOutBuf->totalBytesAvailable(),//緩衝中空餘的空間大小   
  28.                 afterGettingFrame,  //因爲可能source中的讀數據函數會被放在任務調度中,所以把獲取幀後應調用的函數傳給source   
  29.                 this,  
  30.                 ourHandleClosure, //這個是source結束時(比如文件讀完了)要調用的函數。   
  31.                 this);  
  32.     }  

        packFrame函數需要處理兩種情況:
       1).buffer中存在未發送的數據(overflow data),這時可以將調用afterGettingFrame1函數進行後續處理工作。
       2).buffer不存在數據,這時需要調用source上的getNextFrame函數獲取數據。getNextFrame調用時,參數中有兩個回調用函數:afterGettingFrame函數將在獲取到數據後調用,其中只是簡單的調用了afterGettingFrame1函數而已,這是因爲C++中是不充許類成員函數作爲回調用函數的;ourHandleClosure函數將在數據已經處理完畢時調用,如文件結束。
     

        可以想像下面就是source從文件(或某個設備)中讀取一幀數據,讀完後返回給sink,當然不是從函數返回了,而是以調用afterGettingFrame這個回調函數的方式。所以下面看一下afterGettingFrame():

 
  1. void MultiFramedRTPSink::afterGettingFrame(void* clientData,  
  2.         unsigned numBytesRead, unsigned numTruncatedBytes,  
  3.         struct timeval presentationTime, unsigned durationInMicroseconds)  
  4. {  
  5.     MultiFramedRTPSink* sink = (MultiFramedRTPSink*) clientData;  
  6.     sink->afterGettingFrame1(numBytesRead, numTruncatedBytes, presentationTime,  
  7.             durationInMicroseconds);  
  8. }  

   
      可以看出,它只是過度爲調用成員函數,所以afterGettingFrame1()纔是重點:

 
  1. void MultiFramedRTPSink::afterGettingFrame1(  
  2.         unsigned frameSize,  
  3.         unsigned numTruncatedBytes,  
  4.         struct timeval presentationTime,  
  5.         unsigned durationInMicroseconds)  
  6. {  
  7.     if (fIsFirstPacket) {  
  8.         // Record the fact that we're starting to play now:   第一個packet,則記錄下當前時間  
  9.         gettimeofday(&fNextSendTime, NULL);  
  10.     }  
  11.   
  12.   //這裏的處理要注意了,當一個Frame大於OutPacketBuffer::maxSize(默認值爲60000)時,則會丟棄剩下的部分,numTruncatedBytes即爲超出部分的大小。   
  13.     //如果給予一幀的緩衝不夠大,就會發生截斷一幀數據的現象。但也只能提示一下用戶   
  14.     if (numTruncatedBytes > 0) {    
  15.   
  16.         unsigned const bufferSize = fOutBuf->totalBytesAvailable();  
  17.         envir()  
  18.                 << "MultiFramedRTPSink::afterGettingFrame1(): The input frame data was too large for our buffer size ("  
  19.                 << bufferSize  
  20.                 << ").  "  
  21.                 << numTruncatedBytes  
  22.                 << " bytes of trailing data was dropped!  Correct this by increasing \"OutPacketBuffer::maxSize\" to at least "  
  23.                 << OutPacketBuffer::maxSize + numTruncatedBytes  
  24.                 << ", *before* creating this 'RTPSink'.  (Current value is "  
  25.                 << OutPacketBuffer::maxSize << ".)\n";  
  26.     }  
  27.     unsigned curFragmentationOffset = fCurFragmentationOffset;  
  28.     unsigned numFrameBytesToUse = frameSize;  
  29.     unsigned overflowBytes = 0;  
  30.   
  31.   
  32.     //如果包只已經打入幀數據了,並且不能再向這個包中加數據了,則把新獲得的幀數據保存下來。   
  33.     // If we have already packed one or more frames into this packet,   
  34.     // check whether this new frame is eligible to be packed after them.   
  35.     // (This is independent of whether the packet has enough room for this   
  36.     // new frame; that check comes later.)   
  37.     // fNumFramesUsedSoFar>0 表示packet已經存在frame,需要檢查是否充許在packet中加入新的frame
  38.     if (fNumFramesUsedSoFar > 0) {  
  39.         //如果包中已有了一個幀,並且不允許再打入新的幀了,則只記錄下新的幀。   
  40.         if ((fPreviousFrameEndedFragmentation 
  41.                && !allowOtherFramesAfterLastFragment())  //不充許在前一個分片之後,跟隨一個frame
  42.                 || !frameCanAppearAfterPacketStart(fOutBuf->curPtr(), frameSize))  //frame不能出現在非packet的開始位置      
  43.         {  
  44.             // Save away this frame for next time:   
  45.             numFrameBytesToUse = 0;  
  46.             //不充許添加新的frame,則保存爲溢出數據,下次處理   
  47.             fOutBuf->setOverflowData(fOutBuf->curPacketSize(), frameSize,  
  48.                     presentationTime, durationInMicroseconds);  
  49.         }  
  50.     }  
  51.       
  52.     //表示當前打入的是否是上一個幀的最後一塊數據。   
  53.     fPreviousFrameEndedFragmentation = False;  
  54.   
  55.   
  56.     //下面是計算獲取的幀中有多少數據可以打到當前包中,剩下的數據就作爲overflow數據保存下來。   
  57.     if (numFrameBytesToUse > 0) {  
  58.         // Check whether this frame overflows the packet   
  59.         if (fOutBuf->wouldOverflow(frameSize)) {  
  60.             // Don't use this frame now; instead, save it as overflow data, and   
  61.             // send it in the next packet instead.  However, if the frame is too   
  62.             // big to fit in a packet by itself, then we need to fragment it (and   
  63.             // use some of it in this packet, if the payload format permits this.)   
  64.     //若frame將導致packet溢出,應該將其保存到packet的溢出數據中,在下一個packet中發送。   
        //如果frame本身大於pakcet 的max size, 就需要對frame進行分片操作。不過需要調用allowFragmentationAfterStart 函數以確定是否充許分片
  65.             if (isTooBigForAPacket(frameSize)  
  66.                     && (fNumFramesUsedSoFar == 0 || allowFragmentationAfterStart())) {  
  67.                 // We need to fragment this frame, and use some of it now:   
  68.                 overflowBytes = computeOverflowForNewFrame(frameSize);  
  69.                 numFrameBytesToUse -= overflowBytes;  
  70.                 fCurFragmentationOffset += numFrameBytesToUse;  
  71.             } else {  
  72.                 // We don't use any of this frame now:   
  73.                 overflowBytes = frameSize;  
  74.                 numFrameBytesToUse = 0;  
  75.             }  
  76.             fOutBuf->setOverflowData(fOutBuf->curPacketSize() + numFrameBytesToUse,  
  77.                     overflowBytes, presentationTime, durationInMicroseconds);  
  78.         } else if (fCurFragmentationOffset > 0) {  
  79.             // This is the last fragment of a frame that was fragmented over   
  80.             // more than one packet.  Do any special handling for this case:   
  81.             fCurFragmentationOffset = 0;  
  82.             fPreviousFrameEndedFragmentation = True;  
  83.         }  
  84.     }  
  85.   
  86.       
  87.     if (numFrameBytesToUse == 0 && frameSize > 0) {  
  88.         //如果包中有數據並且沒有新數據了,則發送之。(這種情況好像很難發生啊!)   
  89.         // Send our packet now, because we have filled it up:   
  90.         sendPacketIfNecessary();  
  91.     } else {  
  92.         //需要向包中打入數據。   
  93.           
  94.         // Use this frame in our outgoing packet:   
  95.         unsigned char* frameStart = fOutBuf->curPtr();  
  96.         fOutBuf->increment(numFrameBytesToUse);  
  97.         // do this now, in case "doSpecialFrameHandling()" calls "setFramePadding()" to append padding bytes   
  98.   
  99.         //還記得RTP頭中序留的空間嗎,將在這個函數中進行填充
  100.         // Here's where any payload format specific processing gets done:   
  101.         doSpecialFrameHandling(curFragmentationOffset, frameStart,  
  102.                 numFrameBytesToUse, presentationTime, overflowBytes);  
  103.   
  104.   
  105.         ++fNumFramesUsedSoFar;  
  106.   
  107.         //設置下一個packet的時間信息,這裏若存在overflow數據,就不需要更新時間,因爲這是同一個frame的不同分片,需要保證時間一致  
  108.         // Update the time at which the next packet should be sent, based   
  109.         // on the duration of the frame that we just packed into it.   
  110.         // However, if this frame has overflow data remaining, then don't   
  111.         // count its duration yet.   
  112.         if (overflowBytes == 0) {  
  113.             fNextSendTime.tv_usec += durationInMicroseconds;  
  114.             fNextSendTime.tv_sec += fNextSendTime.tv_usec / 1000000;  
  115.             fNextSendTime.tv_usec %= 1000000;  
  116.         }  
  117.   
  118.   
  119.         //如果需要,就發出包,否則繼續打入數據。   
  120.         // Send our packet now if (i) it's already at our preferred size, or   
  121.         // (ii) (heuristic) another frame of the same size as the one we just   
  122.         //      read would overflow the packet, or   
  123.         // (iii) it contains the last fragment of a fragmented frame, and we   
  124.         //      don't allow anything else to follow this or   
  125.         // (iv) one frame per packet is allowed:   
  126.         if (fOutBuf->isPreferredSize()  
  127.                 || fOutBuf->wouldOverflow(numFrameBytesToUse)  
  128.                 || (fPreviousFrameEndedFragmentation  
  129.                         && !allowOtherFramesAfterLastFragment())  
  130.                 || !frameCanAppearAfterPacketStart(  
  131.                         fOutBuf->curPtr() - frameSize, frameSize)) {  
  132.             // The packet is ready to be sent now   
  133.             sendPacketIfNecessary();  //發送RTP包   
  134.         } else {              
  135.            // There's room for more frames; try getting another:   
  136.             packFrame();    //packet中還可以容納frame,這裏將形成遞歸調用 
  137.         }  
  138.     }  
  139. }  

         afterGettingFrame1的複雜之處在於處理frame的分片,若一個frame大於TCP/UDP有效載荷(程序中定義爲1448個字節),就必需分片了。最簡單的情況就是一個packet(RTP包)中最多隻充許一個frame,即一個RTP包中存在一個frame或者frame的一個分片,H264就是這樣處理的。,方法是將剩餘的數據記錄爲buffer的溢出部分。下次調用packFrame函數時,直接從溢出部分複製到packet中。不過應該注意,一個frame的大小不能超過buffer的大小(默認爲60000),否則會真的溢出, 那就應該考慮增加buffer大小了。
      上面的代碼中還調用了doSpecialFrameHandling,子類需要重新實現進行一些特殊處理,文章最後還會討論這個問題。
       在packet中充許出現多個frame的情況下(大多數情況下應該沒必要用到),採用了遞歸來實現,可以看到afterGettingFrame1函數的最後有調用packFrame的代碼。

      再來看RTP的發送函數sendPacketIfNecessary
 
  1. void MultiFramedRTPSink::sendPacketIfNecessary() {  
  2.     //   
  3.     //packet中存在frame,則發送出去   
  4.     //   
  5.   if (fNumFramesUsedSoFar > 0) {  
  6.     // Send the packet:   
  7.     //   
  8.     //可以通過TEST_LOSS宏,模擬10%丟包   
  9.     //   
  10. #ifdef TEST_LOSS   
  11.     if ((our_random()%10) != 0) // simulate 10% packet loss #####   
  12. #endif   
  13.     //   
  14.     //現在通過調用RTPInterface::sendPacket函數發送packet   
  15.     //        
  16.  if (!fRTPInterface.sendPacket(fOutBuf->packet(), fOutBuf->curPacketSize())) {  
  17.     // if failure handler has been specified, call it   
  18.     if (fOnSendErrorFunc != NULL) (*fOnSendErrorFunc)(fOnSendErrorData);    //錯誤處理   
  19.       }  
  20.     ++fPacketCount;  
  21.     fTotalOctetCount += fOutBuf->curPacketSize();  
  22.     fOctetCount += fOutBuf->curPacketSize()  
  23.       - rtpHeaderSize - fSpecialHeaderSize - fTotalFrameSpecificHeaderSizes;  
  24.   
  25.   
  26.     ++fSeqNo; // for next time   
  27.   }  
  28.   
  29.    //如果還有剩餘數據,則調整緩衝區
  30.   if (fOutBuf->haveOverflowData()  
  31.       && fOutBuf->totalBytesAvailable() > fOutBuf->totalBufferSize()/2) {  
  32.     //   
  33.     //爲了提高效率,可以直接重置buffer中的packet開始位置,這樣就不需要拷貝一遍overflow數據了。   
  34.     //在一個packet只能包含一個frame的情況下,是不是可以考慮修改這裏的判斷條件呢?   
  35.     //       
  36.     // Efficiency hack: Reset the packet start pointer to just in front of   
  37.     // the overflow data (allowing for the RTP header and special headers),   
  38.     // so that we probably don't have to "memmove()" the overflow data   
  39.     // into place when building the next packet:   
  40.     unsigned newPacketStart = fOutBuf->curPacketSize()  
  41.       - (rtpHeaderSize + fSpecialHeaderSize + frameSpecificHeaderSize());  
  42.     fOutBuf->adjustPacketStart(newPacketStart); //調整buffer中的packet 開始位置   
  43.   } else {  
  44.     // Normal case: Reset the packet start pointer back to the start:   
  45.     fOutBuf->resetPacketStart();    //這種情況,若存在overflow data,就需要進行copy操作了   
  46.   }  
  47.   fOutBuf->resetOffset();   //packet已經發送了,可以重置buffer中的數據offset了   
  48.   fNumFramesUsedSoFar = 0;  //清零packet中的frame數   
  49.     //   
  50.     //數據已經發送完畢(例如文件傳輸完畢),可以關閉了
  51.     //     
  52.   if (fNoFramesLeft) {  
  53.     // We're done:   
  54.     onSourceClosure(this);  
  55.   } else {  //如果還有數據,則在下一次需要發送的時間再次打包發送
  56.     //   
  57.     //準備下一次發送任務   
  58.     //   
  59.     // We have more frames left to send.  Figure out when the next frame   
  60.     // is due to start playing, then make sure that we wait this long before   
  61.     // sending the next packet.   
  62.     struct timeval timeNow;  
  63.     gettimeofday(&timeNow, NULL);  
  64.     int secsDiff = fNextSendTime.tv_sec - timeNow.tv_sec;   //若是同一個frame的不同分片,這個值將爲0   
  65.     int64_t uSecondsToGo = secsDiff*1000000 + (fNextSendTime.tv_usec - timeNow.tv_usec);  
  66.     if (uSecondsToGo < 0 || secsDiff < 0) { // sanity check: Make sure that the time-to-delay is non-negative:  
  67.       uSecondsToGo = 0;       
  68.     }  
  69.     //   
  70.     //作延時時間,處理函數,將入到任務調試器中,以便進行下一次發送操作   
  71.     //       
  72. // Delay this amount of time:   
  73.     nextTask() = envir().taskScheduler().scheduleDelayedTask(uSecondsToGo, (TaskFunc*)sendNext, this);  
  74.   }  
   
      sendPacketIfNecessary函數處理一些發送的細節,我們來看最重要的兩點。
      1)RTP包還是轉交給了RTPInterface::sendPacket函數,等下再看其具體實現。
      2)將下一次RTP的發送操作加入到任務調度器中,參數中傳遞了sendNext函數指針,其實現比較簡單,如下
  1. void MultiFramedRTPSink::sendNext(void* firstArg) {  
  2.   MultiFramedRTPSink* sink = (MultiFramedRTPSink*)firstArg;  
  3.   sink->buildAndSendPacket(False);  //現在已經不是第一次調用了   
       可以看到爲了延遲包的發送,使用了delay task來執行下次打包發送任務。sendNext()中又調用了buildAndSendPacket()函數,輪迴了。。。

總結一下調用過程:

總結一下調用過程:

live555學習(十) --RTP的打包與發送 - 白楊 - 白楊

 

最後,再說明一下包緩衝區的使用:

        MultiFramedRTPSink中的幀數據和包緩衝區共用一個,只是用一些額外的變量指明緩衝區中屬於包的部分以及屬於幀數據的部分(包以外的數據叫做overflow data)。它有時會把overflow data以mem move的方式移到包開始的位置,有時把包的開始位置直接設置到overflow data開始的地方。那麼這個緩衝的大小是怎樣確定的呢?是跟據調用者指定的的一個最大的包的大小+60000算出的。這個地方把我搞胡塗了:如果一次從source獲取一個幀的話,那這個緩衝應設爲不小於最大的一個幀的大小纔是,爲何是按包的大小設置呢?可以看到,當緩衝不夠時只是提示一下.當然此時不會出錯,但有可能導致時間戳計算不準,或增加時間戳計算與source端處理的複雜性(因爲一次取一幀時間戳是很好計算的)。

現在來看RTPInterface::sendPacket函數

  1. Boolean RTPInterface::sendPacket(unsigned char* packet, unsigned packetSize) {  
  2.   Boolean success = True; // we'll return False instead if any of the sends fail   
  3.   
  4.    //一般情況下,使用UDP發送   
  5.   // Normal case: Send as a UDP packet:   
  6.   if (!fGS->output(envir(), fGS->ttl(), packet, packetSize)) success = False;  
  7.   
  8.   //使用TCP發送   
  9.   // Also, send over each of our TCP sockets:   
  10.   for (tcpStreamRecord* streams = fTCPStreams; streams != NULL;  
  11.        streams = streams->fNext) {  
  12.     if (!sendRTPOverTCP(packet, packetSize,  
  13.             streams->fStreamSocketNum, streams->fStreamChannelId)) {  
  14.       success = False;  
  15.     }  
  16.   }  
  17.   
  18.   
  19.   return success;  
  20. }  

         若是使用UDP方式發送,將調用Groupsock::output函數,可以實現組播功能。groupsock只實現了UDP發送功能,當用TCP方式傳送時調用sendRTPOverTcP函數,這個函數中直接調用socket的send函數。
        現在RTP的發送終於結束了,groupsock的實現留待下次分析。現在再來看一個遺留的問題,MultiFramedRTPSink::doSpecialFrameHandling的實現。它是定義在MultiFramedRTPSink中的虛函數,先來看其默認的實現.

  1. void MultiFramedRTPSink::doSpecialFrameHandling(unsigned /*fragmentationOffset*/,  
  2.              unsigned char* /*frameStart*/,  
  3.              unsigned /*numBytesInFrame*/,  
  4.              struct timeval framePresentationTime,  
  5.              unsigned /*numRemainingBytes*/) {  
  6.   // default implementation: If this is the first frame in the packet,   
  7.   // use its presentationTime for the RTP timestamp:   
  8.   if (isFirstFrameInPacket()) {  
  9.     setTimestamp(framePresentationTime);  
  10.   }  
       可以看到默認實現中只是在第一次調用時,設置RTP包中的的時間信息,下面來看H264VideoRTPSink上的實現
  1. void H264VideoRTPSink::doSpecialFrameHandling(unsigned /*fragmentationOffset*/,  
  2.                           unsigned char* /*frameStart*/,  
  3.                           unsigned /*numBytesInFrame*/,  
  4.                           struct timeval framePresentationTime,  
  5.                           unsigned /*numRemainingBytes*/) {  
  6.     //   
  7.     //設置RTP頭中的M位   
  8.     //   
  9.   // Set the RTP 'M' (marker) bit iff   
  10.   // 1/ The most recently delivered fragment was the end of (or the only fragment of) an NAL unit, and   
  11.   // 2/ This NAL unit was the last NAL unit of an 'access unit' (i.e. video frame).   
  12.   if (fOurFragmenter != NULL) {  
  13.     H264VideoStreamFramer* framerSource  
  14.       = (H264VideoStreamFramer*)(fOurFragmenter->inputSource());  
  15.     // This relies on our fragmenter's source being a "H264VideoStreamFramer".   
  16.     if (fOurFragmenter->lastFragmentCompletedNALUnit()  
  17.     && framerSource != NULL && framerSource->pictureEndMarker()) {  
  18.       setMarkerBit();  
  19.       framerSource->pictureEndMarker() = False;  
  20.     }  
  21.   }  
  22.     //   
  23.     //設置時間戳   
  24.     //   
  25.   setTimestamp(framePresentationTime);  
  26. }  
         解釋一下RTP頭中的M位,H264圖像可能被封裝成多個NALU,這些NALU就擁有相同的同時間。根據RFC3984的定義,當RTP中封裝的是同一圖像的最後一個NALU時,就需要設置M位
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章