liveMedia/MP3StreamState.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 class encapsulating the state of a MP3 stream
00019 // Implementation
00020 
00021 #include "MP3StreamState.hh"
00022 #include "GroupsockHelper.hh"
00023 
00024 #if defined(__WIN32__) || defined(_WIN32)
00025 #define snprintf _snprintf
00026 #endif
00027 
00028 #define MILLION 1000000
00029 
00030 MP3StreamState::MP3StreamState(UsageEnvironment& env)
00031   : fEnv(env), fFid(NULL), fPresentationTimeScale(1) {
00032 }
00033 
00034 MP3StreamState::~MP3StreamState() {
00035   // Close our open file or socket:
00036   if (fFid != NULL && fFid != stdin) {
00037     if (fFidIsReallyASocket) {
00038       long fid_long = (long)fFid;
00039       closeSocket((int)fid_long);
00040     } else {
00041       fclose(fFid);
00042     }
00043   }
00044 }
00045 
00046 void MP3StreamState::assignStream(FILE* fid, unsigned fileSize) {
00047   fFid = fid;
00048 
00049   if (fileSize == (unsigned)(-1)) { /*HACK#####*/
00050     fFidIsReallyASocket = 1;
00051     fFileSize = 0;
00052   } else {
00053     fFidIsReallyASocket = 0;
00054     fFileSize = fileSize;
00055   }
00056   fNumFramesInFile = 0; // until we know otherwise
00057   fIsVBR = fHasXingTOC = False; // ditto
00058 
00059   // Set the first frame's 'presentation time' to the current wall time:
00060   gettimeofday(&fNextFramePresentationTime, NULL);
00061 }
00062 
00063 struct timeval MP3StreamState::currentFramePlayTime() const {
00064   unsigned const numSamples = 1152;
00065   unsigned const freq = fr().samplingFreq*(1 + fr().isMPEG2);
00066 
00067   // result is numSamples/freq
00068   unsigned const uSeconds
00069     = ((numSamples*2*MILLION)/freq + 1)/2; // rounds to nearest integer
00070 
00071   struct timeval result;
00072   result.tv_sec = uSeconds/MILLION;
00073   result.tv_usec = uSeconds%MILLION;
00074   return result;
00075 }
00076 
00077 float MP3StreamState::filePlayTime() const {
00078   unsigned numFramesInFile = fNumFramesInFile;
00079   if (numFramesInFile == 0) {
00080     // Estimate the number of frames from the file size, and the
00081     // size of the current frame:
00082     numFramesInFile = fFileSize/(4 + fCurrentFrame.frameSize);
00083   }
00084 
00085   struct timeval const pt = currentFramePlayTime();
00086   return numFramesInFile*(pt.tv_sec + pt.tv_usec/(float)MILLION);
00087 }
00088 
00089 void MP3StreamState::seekWithinFile(double seekNPT) {
00090   if (fFidIsReallyASocket) return; // it's not seekable
00091 
00092   float fileDuration = filePlayTime();
00093   if (seekNPT < 0.0) {
00094     seekNPT = 0.0;
00095   } else if (seekNPT > fileDuration) {
00096     seekNPT = fileDuration;
00097   }
00098   float seekFraction = (float)seekNPT/fileDuration;
00099 
00100   unsigned seekByteNumber;
00101   if (fHasXingTOC) {
00102     // The file is VBR, with a Xing TOC; use it to determine which byte to seek to:
00103     float percent = seekFraction*100.0f;
00104     unsigned a = (unsigned)percent;
00105     if (a > 99) a = 99;
00106 
00107     unsigned fa = fXingTOC[a];
00108     unsigned fb;
00109     if (a < 99) {
00110       fb = fXingTOC[a+1];
00111     } else {
00112       fb = 256;
00113     }
00114     float seekByteFraction = (fa + (fb-fa)*(percent-a))/256.0f;
00115 
00116     seekByteNumber = (unsigned)(seekByteFraction*fFileSize);
00117   } else {
00118     // Normal case: Treat the file as if it's CBR:
00119     seekByteNumber = (unsigned)(seekFraction*fFileSize);
00120   }
00121 
00122   fseek(fFid, seekByteNumber, SEEK_SET);
00123 }
00124 
00125 unsigned MP3StreamState::findNextHeader(struct timeval& presentationTime) {
00126   presentationTime = fNextFramePresentationTime;
00127 
00128   if (!findNextFrame()) return 0;
00129 
00130   // From this frame, figure out the *next* frame's presentation time:
00131   struct timeval framePlayTime = currentFramePlayTime();
00132   if (fPresentationTimeScale > 1) {
00133     // Scale this value
00134     unsigned secondsRem = framePlayTime.tv_sec % fPresentationTimeScale;
00135     framePlayTime.tv_sec -= secondsRem;
00136     framePlayTime.tv_usec += secondsRem*MILLION;
00137     framePlayTime.tv_sec /= fPresentationTimeScale;
00138     framePlayTime.tv_usec /= fPresentationTimeScale;
00139   }
00140   fNextFramePresentationTime.tv_usec += framePlayTime.tv_usec;
00141   fNextFramePresentationTime.tv_sec
00142     += framePlayTime.tv_sec + fNextFramePresentationTime.tv_usec/MILLION;
00143   fNextFramePresentationTime.tv_usec %= MILLION;
00144 
00145   return fr().hdr;
00146 }
00147 
00148 Boolean MP3StreamState::readFrame(unsigned char* outBuf, unsigned outBufSize,
00149                                   unsigned& resultFrameSize,
00150                                   unsigned& resultDurationInMicroseconds) {
00151   /* We assume that "mp3FindNextHeader()" has already been called */
00152 
00153   resultFrameSize = 4 + fr().frameSize;
00154 
00155   if (outBufSize < resultFrameSize) {
00156 #ifdef DEBUG_ERRORS
00157     fprintf(stderr, "Insufficient buffer size for reading input frame (%d, need %d)\n",
00158             outBufSize, resultFrameSize);
00159 #endif
00160     if (outBufSize < 4) outBufSize = 0;
00161     resultFrameSize = outBufSize;
00162 
00163     return False;
00164   }
00165 
00166   if (resultFrameSize >= 4) {
00167     unsigned& hdr = fr().hdr;
00168     *outBuf++ = (unsigned char)(hdr>>24);
00169     *outBuf++ = (unsigned char)(hdr>>16);
00170     *outBuf++ = (unsigned char)(hdr>>8);
00171     *outBuf++ = (unsigned char)(hdr);
00172 
00173     memmove(outBuf, fr().frameBytes, resultFrameSize-4);
00174   }
00175 
00176   struct timeval const pt = currentFramePlayTime();
00177   resultDurationInMicroseconds = pt.tv_sec*MILLION + pt.tv_usec;
00178 
00179   return True;
00180 }
00181 
00182 void MP3StreamState::getAttributes(char* buffer, unsigned bufferSize) const {
00183   char const* formatStr
00184     = "bandwidth %d MPEGnumber %d MPEGlayer %d samplingFrequency %d isStereo %d playTime %d isVBR %d";
00185   unsigned fpt = (unsigned)(filePlayTime() + 0.5); // rounds to nearest integer
00186 #if defined(IRIX) || defined(ALPHA) || defined(_QNX4) || defined(IMN_PIM) || defined(CRIS)
00187   /* snprintf() isn't defined, so just use sprintf() - ugh! */
00188   sprintf(buffer, formatStr,
00189           fr().bitrate, fr().isMPEG2 ? 2 : 1, fr().layer, fr().samplingFreq, fr().isStereo,
00190           fpt, fIsVBR);
00191 #else
00192   snprintf(buffer, bufferSize, formatStr,
00193           fr().bitrate, fr().isMPEG2 ? 2 : 1, fr().layer, fr().samplingFreq, fr().isStereo,
00194           fpt, fIsVBR);
00195 #endif
00196 }
00197 
00198 void MP3StreamState::writeGetCmd(char const* hostName,
00199                                  unsigned short portNum,
00200                                  char const* fileName) {
00201   char const* const getCmdFmt = "GET %s HTTP/1.1\r\nHost: %s:%d\r\n\r\n";
00202 
00203   if (fFidIsReallyASocket) {
00204     long fid_long = (long)fFid;
00205     int sock = (int)fid_long;
00206     char writeBuf[100];
00207 #if defined(IRIX) || defined(ALPHA) || defined(_QNX4) || defined(IMN_PIM) || defined(CRIS)
00208     /* snprintf() isn't defined, so just use sprintf() */
00209     /* This is a security risk if filename can come from an external user */
00210     sprintf(writeBuf, getCmdFmt, fileName, hostName, portNum);
00211 #else
00212     snprintf(writeBuf, sizeof writeBuf, getCmdFmt,
00213              fileName, hostName, portNum);
00214 #endif
00215     send(sock, writeBuf, strlen(writeBuf), 0);
00216   } else {
00217     fprintf(fFid, getCmdFmt, fileName, hostName, portNum);
00218     fflush(fFid);
00219   }
00220 }
00221 
00222 // This is crufty old code that needs to be cleaned up #####
00223 #define HDRCMPMASK 0xfffffd00
00224 
00225 Boolean MP3StreamState::findNextFrame() {
00226   unsigned char hbuf[8];
00227   unsigned l; int i;
00228   int attempt = 0;
00229 
00230  read_again:
00231   if (readFromStream(hbuf, 4) != 4) return False;
00232 
00233   fr().hdr =  ((unsigned long) hbuf[0] << 24)
00234             | ((unsigned long) hbuf[1] << 16)
00235             | ((unsigned long) hbuf[2] << 8)
00236             | (unsigned long) hbuf[3];
00237 
00238 #ifdef DEBUG_PARSE
00239   fprintf(stderr, "fr().hdr: 0x%08x\n", fr().hdr);
00240 #endif
00241   if (fr().oldHdr != fr().hdr || !fr().oldHdr) {
00242     i = 0;
00243   init_resync:
00244 #ifdef DEBUG_PARSE
00245     fprintf(stderr, "init_resync: fr().hdr: 0x%08x\n", fr().hdr);
00246 #endif
00247     if (   (fr().hdr & 0xffe00000) != 0xffe00000
00248         || (fr().hdr & 0x00060000) == 0 // undefined 'layer' field
00249         || (fr().hdr & 0x0000F000) == 0 // 'free format' bitrate index
00250         || (fr().hdr & 0x0000F000) == 0x0000F000 // undefined bitrate index
00251         || (fr().hdr & 0x00000C00) == 0x00000C00 // undefined frequency index
00252         || (fr().hdr & 0x00000003) != 0x00000000 // 'emphasis' field unexpectedly set
00253        ) {
00254       /* RSF: Do the following test even if we're not at the
00255          start of the file, in case we have two or more
00256          separate MP3 files cat'ed together:
00257       */
00258       /* Check for RIFF hdr */
00259       if (fr().hdr == ('R'<<24)+('I'<<16)+('F'<<8)+'F') {
00260         unsigned char buf[70 /*was: 40*/];
00261 #ifdef DEBUG_ERRORS
00262         fprintf(stderr,"Skipped RIFF header\n");
00263 #endif
00264         readFromStream(buf, 66); /* already read 4 */
00265         goto read_again;
00266       }
00267       /* Check for ID3 hdr */
00268       if ((fr().hdr&0xFFFFFF00) == ('I'<<24)+('D'<<16)+('3'<<8)) {
00269         unsigned tagSize, bytesToSkip;
00270         unsigned char buf[1000];
00271         readFromStream(buf, 6); /* already read 4 */
00272         tagSize = ((buf[2]&0x7F)<<21) + ((buf[3]&0x7F)<<14) + ((buf[4]&0x7F)<<7) + (buf[5]&0x7F);
00273         bytesToSkip = tagSize;
00274         while (bytesToSkip > 0) {
00275           unsigned bytesToRead = sizeof buf;
00276           if (bytesToRead > bytesToSkip) {
00277             bytesToRead = bytesToSkip;
00278           }
00279           readFromStream(buf, bytesToRead);
00280           bytesToSkip -= bytesToRead;
00281         }
00282 #ifdef DEBUG_ERRORS
00283         fprintf(stderr,"Skipped %d-byte ID3 header\n", tagSize);
00284 #endif
00285         goto read_again;
00286       }
00287       /* give up after 20,000 bytes */
00288       if (i++ < 20000/*4096*//*1024*/) {
00289         memmove (&hbuf[0], &hbuf[1], 3);
00290         if (readFromStream(hbuf+3,1) != 1) {
00291           return False;
00292         }
00293         fr().hdr <<= 8;
00294         fr().hdr |= hbuf[3];
00295         fr().hdr &= 0xffffffff;
00296 #ifdef DEBUG_PARSE
00297         fprintf(stderr, "calling init_resync %d\n", i);
00298 #endif
00299         goto init_resync;
00300       }
00301 #ifdef DEBUG_ERRORS
00302       fprintf(stderr,"Giving up searching valid MPEG header\n");
00303 #endif
00304       return False;
00305 
00306 #ifdef DEBUG_ERRORS
00307       fprintf(stderr,"Illegal Audio-MPEG-Header 0x%08lx at offset 0x%lx.\n",
00308               fr().hdr,tell_stream(str)-4);
00309 #endif
00310       /* Read more bytes until we find something that looks
00311          reasonably like a valid header.  This is not a
00312          perfect strategy, but it should get us back on the
00313          track within a short time (and hopefully without
00314          too much distortion in the audio output).  */
00315       do {
00316         attempt++;
00317         memmove (&hbuf[0], &hbuf[1], 7);
00318         if (readFromStream(&hbuf[3],1) != 1) {
00319           return False;
00320         }
00321 
00322         /* This is faster than combining fr().hdr from scratch */
00323         fr().hdr = ((fr().hdr << 8) | hbuf[3]) & 0xffffffff;
00324 
00325         if (!fr().oldHdr)
00326           goto init_resync;       /* "considered harmful", eh? */
00327 
00328       } while ((fr().hdr & HDRCMPMASK) != (fr().oldHdr & HDRCMPMASK)
00329                && (fr().hdr & HDRCMPMASK) != (fr().firstHdr & HDRCMPMASK));
00330 #ifdef DEBUG_ERRORS
00331       fprintf (stderr, "Skipped %d bytes in input.\n", attempt);
00332 #endif
00333     }
00334     if (!fr().firstHdr) {
00335       fr().firstHdr = fr().hdr;
00336     }
00337 
00338     fr().setParamsFromHeader();
00339     fr().setBytePointer(fr().frameBytes, fr().frameSize);
00340 
00341     fr().oldHdr = fr().hdr;
00342 
00343     if (fr().isFreeFormat) {
00344 #ifdef DEBUG_ERRORS
00345       fprintf(stderr,"Free format not supported.\n");
00346 #endif
00347       return False;
00348     }
00349 
00350 #ifdef MP3_ONLY
00351     if (fr().layer != 3) {
00352 #ifdef DEBUG_ERRORS
00353       fprintf(stderr, "MPEG layer %d is not supported!\n", fr().layer);
00354 #endif
00355       return False;
00356     }
00357 #endif
00358   }
00359 
00360   if ((l = readFromStream(fr().frameBytes, fr().frameSize))
00361       != fr().frameSize) {
00362     if (l == 0) return False;
00363     memset(fr().frameBytes+1, 0, fr().frameSize-1);
00364   }
00365 
00366   return True;
00367 }
00368 
00369 static Boolean socketIsReadable(int socket) {
00370   const unsigned numFds = socket+1;
00371   fd_set rd_set;
00372   FD_ZERO(&rd_set);
00373   FD_SET((unsigned)socket, &rd_set);
00374   struct timeval timeout;
00375   timeout.tv_sec = timeout.tv_usec = 0;
00376 
00377   int result = select(numFds, &rd_set, NULL, NULL, &timeout);
00378   return result != 0; // not > 0, because windows can return -1 for file sockets
00379 }
00380 
00381 static char watchVariable;
00382 
00383 static void checkFunc(void* /*clientData*/) {
00384   watchVariable = ~0;
00385 }
00386 
00387 static void waitUntilSocketIsReadable(UsageEnvironment& env, int socket) {
00388   while (!socketIsReadable(socket)) {
00389     // Delay a short period of time before checking again.
00390     unsigned usecsToDelay = 1000; // 1 ms
00391     env.taskScheduler().scheduleDelayedTask(usecsToDelay,
00392                                             (TaskFunc*)checkFunc, (void*)NULL);
00393     watchVariable = 0;
00394     env.taskScheduler().doEventLoop(&watchVariable);
00395         // This allows other tasks to run while we're waiting:
00396   }
00397 }
00398 
00399 unsigned MP3StreamState::readFromStream(unsigned char* buf,
00400                                         unsigned numChars) {
00401   // Hack for doing socket I/O instead of file I/O (e.g., on Windows)
00402   if (fFidIsReallyASocket) {
00403     long fid_long = (long)fFid;
00404     int sock = (int)fid_long;
00405     unsigned totBytesRead = 0;
00406     do {
00407       waitUntilSocketIsReadable(fEnv, sock);
00408       int bytesRead
00409         = recv(sock, &((char*)buf)[totBytesRead], numChars-totBytesRead, 0);
00410       if (bytesRead < 0) return 0;
00411 
00412       totBytesRead += (unsigned)bytesRead;
00413     } while (totBytesRead < numChars);
00414 
00415     return totBytesRead;
00416   } else {
00417     waitUntilSocketIsReadable(fEnv, (int)fileno(fFid));
00418     return fread(buf, 1, numChars, fFid);
00419   }
00420 }
00421 
00422 #define XING_FRAMES_FLAG       0x0001
00423 #define XING_BYTES_FLAG        0x0002
00424 #define XING_TOC_FLAG          0x0004
00425 #define XING_VBR_SCALE_FLAG    0x0008
00426 
00427 void MP3StreamState::checkForXingHeader() {
00428   // Look for 'Xing' in the first 4 bytes after the 'side info':
00429   if (fr().frameSize < fr().sideInfoSize) return;
00430   unsigned bytesAvailable = fr().frameSize - fr().sideInfoSize;
00431   unsigned char* p = &(fr().frameBytes[fr().sideInfoSize]);
00432 
00433   if (bytesAvailable < 8) return;
00434   if (p[0] != 'X' || p[1] != 'i' || p[2] != 'n' || p[3] != 'g') return;
00435 
00436   // We found it.
00437   fIsVBR = True;
00438 
00439   u_int32_t flags = (p[4]<<24) | (p[5]<<16) | (p[6]<<8) | p[7];
00440   unsigned i = 8;
00441   bytesAvailable -= 8;
00442 
00443   if (flags&XING_FRAMES_FLAG) {
00444     // The next 4 bytes are the number of frames:
00445     if (bytesAvailable < 4) return;
00446     fNumFramesInFile = (p[i]<<24)|(p[i+1]<<16)|(p[i+2]<<8)|(p[i+3]);
00447     i += 4; bytesAvailable -= 4;
00448   }
00449 
00450   if (flags&XING_BYTES_FLAG) {
00451     // The next 4 bytes is the file size:
00452     if (bytesAvailable < 4) return;
00453     fFileSize = (p[i]<<24)|(p[i+1]<<16)|(p[i+2]<<8)|(p[i+3]);
00454     i += 4; bytesAvailable -= 4;
00455   }
00456 
00457   if (flags&XING_TOC_FLAG) {
00458     // Fill in the Xing 'table of contents':
00459     if (bytesAvailable < XING_TOC_LENGTH) return;
00460     fHasXingTOC = True;
00461     for (unsigned j = 0; j < XING_TOC_LENGTH; ++j) {
00462       fXingTOC[j] = p[i+j];
00463     }
00464     i += XING_TOC_FLAG; bytesAvailable -= XING_TOC_FLAG;
00465   }
00466 }

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