liveMedia/MPEG2TransportStreamFramer.cpp

Go to the documentation of this file.
00001 /**********
00002 This library is free software; you can redistribute it and/or modify it under
00003 the terms of the GNU Lesser General Public License as published by the
00004 Free Software Foundation; either version 2.1 of the License, or (at your
00005 option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
00006 
00007 This library is distributed in the hope that it will be useful, but WITHOUT
00008 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
00009 FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
00010 more details.
00011 
00012 You should have received a copy of the GNU Lesser General Public License
00013 along with this library; if not, write to the Free Software Foundation, Inc.,
00014 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
00015 **********/
00016 // "liveMedia"
00017 // Copyright (c) 1996-2010 Live Networks, Inc.  All rights reserved.
00018 // A filter that passes through (unchanged) chunks that contain an integral number
00019 // of MPEG-2 Transport Stream packets, but returning (in "fDurationInMicroseconds")
00020 // an updated estimate of the time gap between chunks.
00021 // Implementation
00022 
00023 #include "MPEG2TransportStreamFramer.hh"
00024 #include <GroupsockHelper.hh> // for "gettimeofday()"
00025 
00026 #define TRANSPORT_PACKET_SIZE 188
00027 
00029 
00030 #if !defined(NEW_DURATION_WEIGHT)
00031 #define NEW_DURATION_WEIGHT 0.5
00032   // How much weight to give to the latest duration measurement (must be <= 1)
00033 #endif
00034 
00035 #if !defined(TIME_ADJUSTMENT_FACTOR)
00036 #define TIME_ADJUSTMENT_FACTOR 0.8
00037   // A factor by which to adjust the duration estimate to ensure that the overall
00038   // packet transmission times remains matched with the PCR times (which will be the
00039   // times that we expect receivers to play the incoming packets).
00040   // (must be <= 1)
00041 #endif
00042 
00043 #if !defined(MAX_PLAYOUT_BUFFER_DURATION)
00044 #define MAX_PLAYOUT_BUFFER_DURATION 0.1 // (seconds)
00045 #endif
00046 
00047 #if !defined(PCR_PERIOD_VARIATION_RATIO)
00048 #define PCR_PERIOD_VARIATION_RATIO 0.5
00049 #endif
00050 
00052 
00053 class PIDStatus {
00054 public:
00055   PIDStatus(double _firstClock, double _firstRealTime)
00056     : firstClock(_firstClock), lastClock(_firstClock),
00057       firstRealTime(_firstRealTime), lastRealTime(_firstRealTime),
00058       lastPacketNum(0) {
00059   }
00060 
00061   double firstClock, lastClock, firstRealTime, lastRealTime;
00062   unsigned lastPacketNum;
00063 };
00064 
00065 
00067 
00068 MPEG2TransportStreamFramer* MPEG2TransportStreamFramer
00069 ::createNew(UsageEnvironment& env, FramedSource* inputSource) {
00070   return new MPEG2TransportStreamFramer(env, inputSource);
00071 }
00072 
00073 MPEG2TransportStreamFramer
00074 ::MPEG2TransportStreamFramer(UsageEnvironment& env, FramedSource* inputSource)
00075   : FramedFilter(env, inputSource),
00076     fTSPacketCount(0), fTSPacketDurationEstimate(0.0), fTSPCRCount(0) {
00077   fPIDStatusTable = HashTable::create(ONE_WORD_HASH_KEYS);
00078 }
00079 
00080 MPEG2TransportStreamFramer::~MPEG2TransportStreamFramer() {
00081   clearPIDStatusTable();
00082   delete fPIDStatusTable;
00083 }
00084 
00085 void MPEG2TransportStreamFramer::clearPIDStatusTable() {
00086   PIDStatus* pidStatus;
00087   while ((pidStatus = (PIDStatus*)fPIDStatusTable->RemoveNext()) != NULL) {
00088     delete pidStatus;
00089   }
00090 }
00091 
00092 void MPEG2TransportStreamFramer::doGetNextFrame() {
00093   // Read directly from our input source into our client's buffer:
00094   fFrameSize = 0;
00095   fInputSource->getNextFrame(fTo, fMaxSize,
00096                              afterGettingFrame, this,
00097                              FramedSource::handleClosure, this);
00098 }
00099 
00100 void MPEG2TransportStreamFramer::doStopGettingFrames() {
00101   FramedFilter::doStopGettingFrames();
00102   fTSPacketCount = 0;
00103   fTSPCRCount = 0;
00104 
00105   clearPIDStatusTable();
00106 }
00107 
00108 void MPEG2TransportStreamFramer
00109 ::afterGettingFrame(void* clientData, unsigned frameSize,
00110                     unsigned /*numTruncatedBytes*/,
00111                     struct timeval presentationTime,
00112                     unsigned /*durationInMicroseconds*/) {
00113   MPEG2TransportStreamFramer* framer = (MPEG2TransportStreamFramer*)clientData;
00114   framer->afterGettingFrame1(frameSize, presentationTime);
00115 }
00116 
00117 #define TRANSPORT_SYNC_BYTE 0x47
00118 
00119 void MPEG2TransportStreamFramer::afterGettingFrame1(unsigned frameSize,
00120                                                     struct timeval presentationTime) {
00121   fFrameSize += frameSize;
00122   unsigned const numTSPackets = fFrameSize/TRANSPORT_PACKET_SIZE;
00123   fFrameSize = numTSPackets*TRANSPORT_PACKET_SIZE; // an integral # of TS packets
00124   if (fFrameSize == 0) {
00125     // We didn't read a complete TS packet; assume that the input source has closed.
00126     handleClosure(this);
00127     return;
00128   }
00129 
00130   // Make sure the data begins with a sync byte:
00131   unsigned syncBytePosition;
00132   for (syncBytePosition = 0; syncBytePosition < fFrameSize; ++syncBytePosition) {
00133     if (fTo[syncBytePosition] == TRANSPORT_SYNC_BYTE) break;
00134   }
00135   if (syncBytePosition == fFrameSize) {
00136     envir() << "No Transport Stream sync byte in data.";
00137     handleClosure(this);
00138     return;
00139   } else if (syncBytePosition > 0) {
00140     // There's a sync byte, but not at the start of the data.  Move the good data
00141     // to the start of the buffer, then read more to fill it up again:
00142     memmove(fTo, &fTo[syncBytePosition], fFrameSize - syncBytePosition);
00143     fFrameSize -= syncBytePosition;
00144     fInputSource->getNextFrame(&fTo[fFrameSize], syncBytePosition,
00145                                afterGettingFrame, this,
00146                                FramedSource::handleClosure, this);
00147     return;
00148   } // else normal case: the data begins with a sync byte
00149 
00150   fPresentationTime = presentationTime;
00151 
00152   // Scan through the TS packets that we read, and update our estimate of
00153   // the duration of each packet:
00154   struct timeval tvNow;
00155   gettimeofday(&tvNow, NULL);
00156   double timeNow = tvNow.tv_sec + tvNow.tv_usec/1000000.0;
00157   for (unsigned i = 0; i < numTSPackets; ++i) {
00158     updateTSPacketDurationEstimate(&fTo[i*TRANSPORT_PACKET_SIZE], timeNow);
00159   }
00160 
00161   fDurationInMicroseconds
00162     = numTSPackets * (unsigned)(fTSPacketDurationEstimate*1000000);
00163 
00164   // Complete the delivery to our client:
00165   afterGetting(this);
00166 }
00167 
00168 void MPEG2TransportStreamFramer
00169 ::updateTSPacketDurationEstimate(unsigned char* pkt, double timeNow) {
00170   // Sanity check: Make sure we start with the sync byte:
00171   if (pkt[0] != TRANSPORT_SYNC_BYTE) {
00172     envir() << "Missing sync byte!\n";
00173     return;
00174   }
00175 
00176   ++fTSPacketCount;
00177 
00178   // If this packet doesn't contain a PCR, then we're not interested in it:
00179   u_int8_t const adaptation_field_control = (pkt[3]&0x30)>>4;
00180   if (adaptation_field_control != 2 && adaptation_field_control != 3) return;
00181       // there's no adaptation_field
00182 
00183   u_int8_t const adaptation_field_length = pkt[4];
00184   if (adaptation_field_length == 0) return;
00185 
00186   u_int8_t const discontinuity_indicator = pkt[5]&0x80;
00187   u_int8_t const pcrFlag = pkt[5]&0x10;
00188   if (pcrFlag == 0) return; // no PCR
00189 
00190   // There's a PCR.  Get it, and the PID:
00191   ++fTSPCRCount;
00192   u_int32_t pcrBaseHigh = (pkt[6]<<24)|(pkt[7]<<16)|(pkt[8]<<8)|pkt[9];
00193   double clock = pcrBaseHigh/45000.0;
00194   if ((pkt[10]&0x80) != 0) clock += 1/90000.0; // add in low-bit (if set)
00195   unsigned short pcrExt = ((pkt[10]&0x01)<<8) | pkt[11];
00196   clock += pcrExt/27000000.0;
00197 
00198   unsigned pid = ((pkt[1]&0x1F)<<8) | pkt[2];
00199 
00200   // Check whether we already have a record of a PCR for this PID:
00201   PIDStatus* pidStatus = (PIDStatus*)(fPIDStatusTable->Lookup((char*)pid));
00202 
00203   if (pidStatus == NULL) {
00204     // We're seeing this PID's PCR for the first time:
00205     pidStatus = new PIDStatus(clock, timeNow);
00206     fPIDStatusTable->Add((char*)pid, pidStatus);
00207 #ifdef DEBUG_PCR
00208     fprintf(stderr, "PID 0x%x, FIRST PCR 0x%08x+%d:%03x == %f @ %f, pkt #%lu\n", pid, pcrBaseHigh, pkt[10]>>7, pcrExt, clock, timeNow, fTSPacketCount);
00209 #endif
00210   } else {
00211     // We've seen this PID's PCR before; update our per-packet duration estimate:
00212     double durationPerPacket
00213       = (clock - pidStatus->lastClock)/(fTSPacketCount - pidStatus->lastPacketNum);
00214 
00215     // Hack (suggested by "Romain"): Don't update our estimate if this PCR appeared unusually quickly.
00216     // (This can produce more accurate estimates for wildly VBR streams.)
00217     double meanPCRPeriod = 0.0;
00218     if (fTSPCRCount > 0) {
00219       meanPCRPeriod=(double)fTSPacketCount/fTSPCRCount;
00220       if (fTSPacketCount - pidStatus->lastPacketNum < meanPCRPeriod*PCR_PERIOD_VARIATION_RATIO) return;
00221     }
00222 
00223     if (fTSPacketDurationEstimate == 0.0) { // we've just started
00224       fTSPacketDurationEstimate = durationPerPacket;
00225     } else if (discontinuity_indicator == 0 && durationPerPacket >= 0.0) {
00226       fTSPacketDurationEstimate
00227         = durationPerPacket*NEW_DURATION_WEIGHT
00228         + fTSPacketDurationEstimate*(1-NEW_DURATION_WEIGHT);
00229 
00230       // Also adjust the duration estimate to try to ensure that the transmission
00231       // rate matches the playout rate:
00232       double transmitDuration = timeNow - pidStatus->firstRealTime;
00233       double playoutDuration = clock - pidStatus->firstClock;
00234       if (transmitDuration > playoutDuration) {
00235         fTSPacketDurationEstimate *= TIME_ADJUSTMENT_FACTOR; // reduce estimate
00236       } else if (transmitDuration + MAX_PLAYOUT_BUFFER_DURATION < playoutDuration) {
00237         fTSPacketDurationEstimate /= TIME_ADJUSTMENT_FACTOR; // increase estimate
00238       }
00239     } else {
00240       // the PCR has a discontinuity from its previous value; don't use it now,
00241       // but reset our PCR and real-time values to compensate:
00242       pidStatus->firstClock = clock;
00243       pidStatus->firstRealTime = timeNow;
00244     }
00245 #ifdef DEBUG_PCR
00246     fprintf(stderr, "PID 0x%x, PCR 0x%08x+%d:%03x == %f @ %f (diffs %f @ %f), pkt #%lu, discon %d => this duration %f, new estimate %f, mean PCR period=%f\n", pid, pcrBaseHigh, pkt[10]>>7, pcrExt, clock, timeNow, clock - pidStatus->firstClock, timeNow - pidStatus->firstRealTime, fTSPacketCount, discontinuity_indicator != 0, durationPerPacket, fTSPacketDurationEstimate, meanPCRPeriod );
00247 #endif
00248   }
00249 
00250   pidStatus->lastClock = clock;
00251   pidStatus->lastRealTime = timeNow;
00252   pidStatus->lastPacketNum = fTSPacketCount;
00253 }

Generated on Fri Sep 3 02:35:41 2010 for live by  doxygen 1.5.2