liveMedia/WAVAudioFileSource.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-2012 Live Networks, Inc.  All rights reserved.
00018 // A WAV audio file source
00019 // Implementation
00020 
00021 #include "WAVAudioFileSource.hh"
00022 #include "InputFile.hh"
00023 #include "GroupsockHelper.hh"
00024 
00026 
00027 WAVAudioFileSource*
00028 WAVAudioFileSource::createNew(UsageEnvironment& env, char const* fileName) {
00029   do {
00030     FILE* fid = OpenInputFile(env, fileName);
00031     if (fid == NULL) break;
00032 
00033     WAVAudioFileSource* newSource = new WAVAudioFileSource(env, fid);
00034     if (newSource != NULL && newSource->bitsPerSample() == 0) {
00035       // The WAV file header was apparently invalid.
00036       Medium::close(newSource);
00037       break;
00038     }
00039 
00040     newSource->fFileSize = (unsigned)GetFileSize(fileName, fid);
00041 
00042     return newSource;
00043   } while (0);
00044 
00045   return NULL;
00046 }
00047 
00048 unsigned WAVAudioFileSource::numPCMBytes() const {
00049   if (fFileSize < fWAVHeaderSize) return 0;
00050   return fFileSize - fWAVHeaderSize;
00051 }
00052 
00053 void WAVAudioFileSource::setScaleFactor(int scale) {
00054   if (!fFidIsSeekable) return; // we can't do 'trick play' operations on non-seekable files
00055 
00056   fScaleFactor = scale;
00057 
00058   if (fScaleFactor < 0 && TellFile64(fFid) > 0) {
00059     // Because we're reading backwards, seek back one sample, to ensure that
00060     // (i)  we start reading the last sample before the start point, and
00061     // (ii) we don't hit end-of-file on the first read.
00062     int bytesPerSample = (fNumChannels*fBitsPerSample)/8;
00063     if (bytesPerSample == 0) bytesPerSample = 1;
00064     SeekFile64(fFid, -bytesPerSample, SEEK_CUR);
00065   }
00066 }
00067 
00068 void WAVAudioFileSource::seekToPCMByte(unsigned byteNumber, unsigned numBytesToStream) {
00069   byteNumber += fWAVHeaderSize;
00070   if (byteNumber > fFileSize) byteNumber = fFileSize;
00071 
00072   SeekFile64(fFid, byteNumber, SEEK_SET);
00073 
00074   fNumBytesToStream = numBytesToStream;
00075   fLimitNumBytesToStream = fNumBytesToStream > 0;
00076 }
00077 
00078 unsigned char WAVAudioFileSource::getAudioFormat() {
00079   return fAudioFormat;
00080 }
00081 
00082 
00083 #define nextc fgetc(fid)
00084 
00085 static Boolean get4Bytes(FILE* fid, unsigned& result) { // little-endian
00086   int c0, c1, c2, c3;
00087   if ((c0 = nextc) == EOF || (c1 = nextc) == EOF ||
00088       (c2 = nextc) == EOF || (c3 = nextc) == EOF) return False;
00089   result = (c3<<24)|(c2<<16)|(c1<<8)|c0;
00090   return True;
00091 }
00092 
00093 static Boolean get2Bytes(FILE* fid, unsigned short& result) {//little-endian
00094   int c0, c1;
00095   if ((c0 = nextc) == EOF || (c1 = nextc) == EOF) return False;
00096   result = (c1<<8)|c0;
00097   return True;
00098 }
00099 
00100 static Boolean skipBytes(FILE* fid, int num) {
00101   while (num-- > 0) {
00102     if (nextc == EOF) return False;
00103   }
00104   return True;
00105 }
00106 
00107 WAVAudioFileSource::WAVAudioFileSource(UsageEnvironment& env, FILE* fid)
00108   : AudioInputDevice(env, 0, 0, 0, 0)/* set the real parameters later */,
00109     fFid(fid), fFidIsSeekable(False), fLastPlayTime(0), fHaveStartedReading(False), fWAVHeaderSize(0), fFileSize(0),
00110     fScaleFactor(1), fLimitNumBytesToStream(False), fNumBytesToStream(0), fAudioFormat(WA_UNKNOWN) {
00111   // Check the WAV file header for validity.
00112   // Note: The following web pages contain info about the WAV format:
00113   // http://www.ringthis.com/dev/wave_format.htm
00114   // http://www.lightlink.com/tjweber/StripWav/Canon.html
00115   // http://www.wotsit.org/list.asp?al=W
00116 
00117   Boolean success = False; // until we learn otherwise
00118   do {
00119     // RIFF Chunk:
00120     if (nextc != 'R' || nextc != 'I' || nextc != 'F' || nextc != 'F') break;
00121     if (!skipBytes(fid, 4)) break;
00122     if (nextc != 'W' || nextc != 'A' || nextc != 'V' || nextc != 'E') break;
00123 
00124     // FORMAT Chunk:
00125     if (nextc != 'f' || nextc != 'm' || nextc != 't' || nextc != ' ') break;
00126     unsigned formatLength;
00127     if (!get4Bytes(fid, formatLength)) break;
00128     unsigned short audioFormat;
00129     if (!get2Bytes(fid, audioFormat)) break;
00130 
00131     fAudioFormat = (unsigned char)audioFormat;
00132     if (fAudioFormat != WA_PCM && fAudioFormat != WA_PCMA && fAudioFormat != WA_PCMU && fAudioFormat != WA_IMA_ADPCM) {
00133       // It's a format that we don't (yet) understand
00134       env.setResultMsg("Audio format is not one that we handle (PCM/PCMU/PCMA or IMA ADPCM)");
00135       break;
00136     }
00137     unsigned short numChannels;
00138     if (!get2Bytes(fid, numChannels)) break;
00139     fNumChannels = (unsigned char)numChannels;
00140     if (fNumChannels < 1 || fNumChannels > 2) { // invalid # channels
00141       char errMsg[100];
00142       sprintf(errMsg, "Bad # channels: %d", fNumChannels);
00143       env.setResultMsg(errMsg);
00144       break;
00145     }
00146     if (!get4Bytes(fid, fSamplingFrequency)) break;
00147     if (fSamplingFrequency == 0) {
00148       env.setResultMsg("Bad sampling frequency: 0");
00149       break;
00150     }
00151     if (!skipBytes(fid, 6)) break; // "nAvgBytesPerSec" (4 bytes) + "nBlockAlign" (2 bytes)
00152     unsigned short bitsPerSample;
00153     if (!get2Bytes(fid, bitsPerSample)) break;
00154     fBitsPerSample = (unsigned char)bitsPerSample;
00155     if (fBitsPerSample == 0) {
00156       env.setResultMsg("Bad bits-per-sample: 0");
00157       break;
00158     }
00159     if (!skipBytes(fid, formatLength - 16)) break;
00160 
00161     // FACT chunk (optional):
00162     int c = nextc;
00163     if (c == 'f') {
00164       if (nextc != 'a' || nextc != 'c' || nextc != 't') break;
00165       unsigned factLength;
00166       if (!get4Bytes(fid, factLength)) break;
00167       if (!skipBytes(fid, factLength)) break;
00168       c = nextc;
00169     }
00170 
00171     // DATA Chunk:
00172     if (c != 'd' || nextc != 'a' || nextc != 't' || nextc != 'a') break;
00173     if (!skipBytes(fid, 4)) break;
00174 
00175     // The header is good; the remaining data are the sample bytes.
00176     fWAVHeaderSize = (unsigned)TellFile64(fid);
00177     success = True;
00178   } while (0);
00179 
00180   if (!success) {
00181     env.setResultMsg("Bad WAV file format");
00182     // Set "fBitsPerSample" to zero, to indicate failure:
00183     fBitsPerSample = 0;
00184     return;
00185   }
00186 
00187   fPlayTimePerSample = 1e6/(double)fSamplingFrequency;
00188 
00189   // Although PCM is a sample-based format, we group samples into
00190   // 'frames' for efficient delivery to clients.  Set up our preferred
00191   // frame size to be close to 20 ms, if possible, but always no greater
00192   // than 1400 bytes (to ensure that it will fit in a single RTP packet)
00193   unsigned maxSamplesPerFrame = (1400*8)/(fNumChannels*fBitsPerSample);
00194   unsigned desiredSamplesPerFrame = (unsigned)(0.02*fSamplingFrequency);
00195   unsigned samplesPerFrame = desiredSamplesPerFrame < maxSamplesPerFrame ? desiredSamplesPerFrame : maxSamplesPerFrame;
00196   fPreferredFrameSize = (samplesPerFrame*fNumChannels*fBitsPerSample)/8;
00197 
00198   fFidIsSeekable = FileIsSeekable(fFid);
00199 #ifndef READ_FROM_FILES_SYNCHRONOUSLY
00200   // Now that we've finished reading the WAV header, all future reads (of audio samples) from the file will be asynchronous:
00201   makeSocketNonBlocking(fileno(fFid));
00202 #endif
00203 }
00204 
00205 WAVAudioFileSource::~WAVAudioFileSource() {
00206   if (fFid == NULL) return;
00207 
00208 #ifndef READ_FROM_FILES_SYNCHRONOUSLY
00209   envir().taskScheduler().turnOffBackgroundReadHandling(fileno(fFid));
00210 #endif
00211 
00212   CloseInputFile(fFid);
00213 }
00214 
00215 void WAVAudioFileSource::doGetNextFrame() {
00216   if (feof(fFid) || ferror(fFid) || (fLimitNumBytesToStream && fNumBytesToStream == 0)) {
00217     handleClosure(this);
00218     return;
00219   }
00220 
00221   fFrameSize = 0; // until it's set later
00222 #ifdef READ_FROM_FILES_SYNCHRONOUSLY
00223   doReadFromFile();
00224 #else
00225   if (!fHaveStartedReading) {
00226     // Await readable data from the file:
00227     envir().taskScheduler().turnOnBackgroundReadHandling(fileno(fFid),
00228                                                          (TaskScheduler::BackgroundHandlerProc*)&fileReadableHandler, this);
00229     fHaveStartedReading = True;
00230   }
00231 #endif
00232 }
00233 
00234 void WAVAudioFileSource::doStopGettingFrames() {
00235 #ifndef READ_FROM_FILES_SYNCHRONOUSLY
00236   envir().taskScheduler().turnOffBackgroundReadHandling(fileno(fFid));
00237   fHaveStartedReading = False;
00238 #endif
00239 }
00240 
00241 void WAVAudioFileSource::fileReadableHandler(WAVAudioFileSource* source, int /*mask*/) {
00242   if (!source->isCurrentlyAwaitingData()) {
00243     source->doStopGettingFrames(); // we're not ready for the data yet
00244     return;
00245   }
00246   source->doReadFromFile();
00247 }
00248 
00249 static Boolean const readFromFilesSynchronously
00250 #ifdef READ_FROM_FILES_SYNCHRONOUSLY
00251 = True;
00252 #else
00253 = False;
00254 #endif
00255 
00256 void WAVAudioFileSource::doReadFromFile() {
00257   // Try to read as many bytes as will fit in the buffer provided (or "fPreferredFrameSize" if less)
00258   if (fLimitNumBytesToStream && fNumBytesToStream < fMaxSize) {
00259     fMaxSize = fNumBytesToStream;
00260   }
00261   if (fPreferredFrameSize < fMaxSize) {
00262     fMaxSize = fPreferredFrameSize;
00263   }
00264   unsigned bytesPerSample = (fNumChannels*fBitsPerSample)/8;
00265   if (bytesPerSample == 0) bytesPerSample = 1; // because we can't read less than a byte at a time
00266 
00267   // For 'trick play', read one sample at a time; otherwise (normal case) read samples in bulk:
00268   unsigned bytesToRead = fScaleFactor == 1 ? fMaxSize - fMaxSize%bytesPerSample : bytesPerSample;
00269   unsigned numBytesRead;
00270   while (1) { // loop for 'trick play' only
00271     if (readFromFilesSynchronously || fFidIsSeekable) {
00272       numBytesRead = fread(fTo, 1, bytesToRead, fFid);
00273    } else {
00274       // For non-seekable files (e.g., pipes), call "read()" rather than "fread()", to ensure that the read doesn't block:
00275       numBytesRead = read(fileno(fFid), fTo, bytesToRead);
00276     }
00277     if (numBytesRead == 0) {
00278      handleClosure(this);
00279       return;
00280     }
00281     fFrameSize += numBytesRead;
00282     fTo += numBytesRead;
00283     fMaxSize -= numBytesRead;
00284     fNumBytesToStream -= numBytesRead;
00285 
00286     // If we did an asynchronous read, and didn't read an integral number of samples, then we need to wait for another read:
00287     if (!readFromFilesSynchronously && fFrameSize%bytesPerSample > 0) return;
00288     
00289     // If we're doing 'trick play', then seek to the appropriate place for reading the next sample,
00290     // and keep reading until we fill the provided buffer:
00291     if (fScaleFactor != 1) {
00292       SeekFile64(fFid, (fScaleFactor-1)*bytesPerSample, SEEK_CUR);
00293       if (fMaxSize < bytesPerSample) break;
00294     } else {
00295       break; // from the loop (normal case)
00296     }
00297   }
00298 
00299   // Set the 'presentation time' and 'duration' of this frame:
00300   if (fPresentationTime.tv_sec == 0 && fPresentationTime.tv_usec == 0) {
00301     // This is the first frame, so use the current time:
00302     gettimeofday(&fPresentationTime, NULL);
00303   } else {
00304     // Increment by the play time of the previous data:
00305     unsigned uSeconds   = fPresentationTime.tv_usec + fLastPlayTime;
00306     fPresentationTime.tv_sec += uSeconds/1000000;
00307     fPresentationTime.tv_usec = uSeconds%1000000;
00308   }
00309 
00310   // Remember the play time of this data:
00311   fDurationInMicroseconds = fLastPlayTime
00312     = (unsigned)((fPlayTimePerSample*fFrameSize)/bytesPerSample);
00313 
00314   // Inform the reader that he has data:
00315 #ifdef READ_FROM_FILES_SYNCHRONOUSLY
00316   // To avoid possible infinite recursion, we need to return to the event loop to do this:
00317   nextTask() = envir().taskScheduler().scheduleDelayedTask(0,
00318                                 (TaskFunc*)FramedSource::afterGetting, this);
00319 #else
00320   // Because the file read was done from the event loop, we can call the
00321   // 'after getting' function directly, without risk of infinite recursion:
00322   FramedSource::afterGetting(this);
00323 #endif
00324 }
00325 
00326 Boolean WAVAudioFileSource::setInputPort(int /*portIndex*/) {
00327   return True;
00328 }
00329 
00330 double WAVAudioFileSource::getAverageLevel() const {
00331   return 0.0;//##### fix this later
00332 }

Generated on Thu May 17 07:11:47 2012 for live by  doxygen 1.5.2