In the analysis of MPG file processing in the previous article, there was a serious error because some important details were not noticed. MPG files are audio/video staggered. What should I do if I want to read video data but the current file location is audio data? In the previous analysis, the audio data will be stored in the cache until the video data is read. This is not the case in live555.
First, briefly describe the functions of several classes involved in the MPG processing process.
Mpeg1or2demux corresponds to a session, which completes file de-multiplexing. The process of reading files is implemented through bytestreamfilesource.
Mpeg1or2demuxedelementarystream, as the source, corresponds to a stream, one or more instances correspond to one mpeg1or2demux
Mpeg1or2demuxedservermediasubsession, as a subsession
Mpeg1or2fileserverdemux, a service class, the entire program has only one instance, mpeg1or2demux, mpeg1or2demuxedelementarystream, mpeg1or2demuxedservermediasubsession three classes will be linked through this class. The completed work is as follows:
1) create a subsession instance (mpeg1or2demuxedservermediasubsession );
2) create an mpeg1or2demux instance for each session for demultiplexing.
3) create a source instance (mpeg1or2demuxedelementarystream) in subsession
Let's take a look at an important struct outputdescriptor, which is defined in the mpeg1or2demux class. Each stream in the file corresponds to an outputdescriptor instance.
// A descriptor for each possible stream id tag: typedef struct OutputDescriptor { // input parameters unsigned char* to; unsigned maxSize; FramedSource::afterGettingFunc* fAfterGettingFunc; void* afterGettingClientData; FramedSource::onCloseFunc* fOnCloseFunc; void* onCloseClientData; // output parameters unsigned frameSize; struct timeval presentationTime; class SavedData; // forward SavedData* savedDataHead; SavedData* savedDataTail; unsigned savedDataTotalSize; // status parameters Boolean isPotentiallyReadable; Boolean isCurrentlyActive; Boolean isCurrentlyAwaitingData; } OutputDescriptor_t; OutputDescriptor_t fOutput[256];
Note the following three members:
Ispotentiallyreadable: The corresponding stream exists, that is, the mpeg1or2demuxedelementarystream instance of the corresponding stream exists.
Iscurrentlyactive: The corresponding stream is active. Set this parameter to true when data is read from this stream for the first time and false when data is read when the stream is stopped.
Iscurrentlyawaitingdata. Currently, you need to read data from the corresponding stream. After reading and analyzing data from a file, use this flag to determine whether the read data is the streaming data currently required. If not, the data needs to exist in the cache.
Let's take a look at the mpeg1or2demux: getnextframe function.
Void metadata: getnextframe (writable streamidtag, unsigned char * To, unsigned maxsize, framedsource: writable * handle, void * handle, framedsource: onclosefunc * onclosefunc, void * handle) {// first, check whether we have saved data for this stream ID: // read data from the cache if (usesaveddata (streamidtag, to, maxsize, aftergettingfunc, aftergettingclientdata )) {return;} // Save the parameters of the specified stream ID: // Save the information to the registerreadinterest (streamidtag, to, maxsize, aftergettingfunc, numeric, onclosefunc, oncloseclientdata); // next, if we're the only currently pending read, continue looking for data: // for further processing, reads data from the file if (fnumpendingreads = 1 | records) {records = 0; continuereadprocessing () ;}// otherwise the continued read processing has already been taken care}
The usesaveddata function reads data from the cache. Let's take a look at the registerreadinterest function.
Void identifier: registerreadinterest (optional streamidtag, unsigned char * To, unsigned maxsize, framedsource: Optional * signature, void * signature, framedsource: onclosefunc * onclosefunc, void * signature) {struct outputdescriptor & out = foutput [streamidtag]; // make sure this stream is not already being read: If (Out. iscurrentlyawaitingdata) {envir () <"MP Eg1or2demux: registerreadinterest (): attempt to read Stream ID "<(void *) streamidtag <" more than once! \ N "; envir (). internalerror ();} Out. to = to; out. maxsize = maxsize; out. faftergettingfunc = aftergettingfunc; out. aftergettingclientdata = aftergettingclientdata; out. fonclosefunc = onclosefunc; out. oncloseclientdata = oncloseclientdata; out. iscurrentlyactive = true; // out of the current stream processing activity. iscurrentlyawaitingdata = true; // The current stream needs to read data // out. framesize and out. presentationtime will be set when a frame's read ++ fnumpendingreads; // stream count awaiting Data Reading}
Note the last three statements in the registerreadinterest function. If iscurrentlyawaitingdata is set to true, it indicates that data needs to be read from the corresponding stream, and fnumpendingreads indicates the stream count of data read.
Now let's take a look at the if condition statement following the mpeg1or2demux: getnextframe function.
if (fNumPendingReads == 1 || fHaveUndeliveredData) { fHaveUndeliveredData = 0; continueReadProcessing(); }
Condition 1: fnumpendingreads = 1. fnumpendingreads indicates the number of streams that have not read the data. Why is there more than one stream that reads data at the same time? For an MPG file, the current file location may be a video package when you need to read the audio. If you cannot read the required data, the variable fnumpendingreads is incremented. Condition 2 fhaveundelivereddata indicates that a stream failed to read the required data during the previous processing.
I think there is a problem with the two conditions above. fnumpendingreads = 0 is impossible. When fnumpendingreads> 1, it indicates that a stream failed to read the required data during the previous processing, in this case, fhaveundelivereddata should be set to true. Is the if statement always true? This question is to be confirmed.
Let's continue to see the implementation of the mpeg1or2demux: continuereadprocessing function.
void MPEG1or2Demux::continueReadProcessing() { while (fNumPendingReads > 0) { unsigned char acquiredStreamIdTag = fParser->parse(); if (acquiredStreamIdTag != 0) { // We were able to acquire a frame from the input. struct OutputDescriptor& newOut = fOutput[acquiredStreamIdTag]; newOut.isCurrentlyAwaitingData = False; // indicates that we can be read again // (This needs to be set before the 'after getting' call below, // in case it tries to read another frame) // Call our own 'after getting' function. Because we're not a 'leaf' // source, we can call this directly, without risking infinite recursion. if (newOut.fAfterGettingFunc != NULL) {(*newOut.fAfterGettingFunc)(newOut.afterGettingClientData, newOut.frameSize, 0 /* numTruncatedBytes */, newOut.presentationTime, 0 /* durationInMicroseconds ?????#####*/); --fNumPendingReads; } } else { // We were unable to parse a complete frame from the input, because: // - we had to read more data from the source stream, or // - we found a frame for a stream that was being read, but whose // reader is not ready to get the frame right now, or // - the source stream has ended. break; } }}
This function has a while loop. fparser-> parse () returns the stream Number of the currently read data. The returned value of the first loop process must be the currently required stream data, the returned value of the second loop is the previously unread stream data. After all the streams that need to read the data have read the data, the fnumpendingreads value decreases to 0 and the loop ends.
Let's take a look at the mpegprogramstreamparser: parse function.
unsigned char MPEGProgramStreamParser::parse() { unsigned char acquiredStreamTagId = 0; try { do { switch (fCurrentParseState) { case PARSING_PACK_HEADER: {parsePackHeader();break; } case PARSING_SYSTEM_HEADER: {parseSystemHeader();break; } case PARSING_PES_PACKET: {acquiredStreamTagId = parsePESPacket();break; } } } while(acquiredStreamTagId == 0); return acquiredStreamTagId; } catch (int /*e*/) {#ifdef DEBUG fprintf(stderr, "MPEGProgramStreamParser::parse() EXCEPTION (This is normal behavior - *not* an error)\n"); fflush(stderr);#endif return 0; // the parsing got interrupted }}
The above functions have the most catch statements, so the previous function call will certainly throw an exception. The parsepespacket function returns the stream ID as a loop condition, so this function is the most important
Unsigned char mpegprogramstreamparser: parsepespacket (){... // check whether our using source is interested in this stream type. // If so, deliver the frame to him: mpeg1or2demux: outputdescriptor_t & out = fusingdemux-> foutput [stream_id]; If (Out. iscurrentlyawaitingdata) {// The current stream is waiting for data unsigned numbytestocopy; If (pes_packet_length> out. maxsize) {fusingdemux-> envir () <"mpegprogramstreamparser: parsepespacket () error: pes_packet_length (" <pes_packet_length <") exceeds Max frame size asked for ("<out. maxsize <") \ n"; numbytestocopy = out. maxsize;} else {numbytestocopy = pes_packet_length;} getbytes (Out. to, numbytestocopy); out. framesize = numbytestocopy; // set out. presentationtime later ##### acquiredstreamidtag = stream_id; pes_packet_length-= numbytestocopy;} else if (Out. iscurrentlyactive) {// The current stream is active // someone has been reading this stream, but isn' t right now. // We can't deliver this frame until he asks for it, so punt for now. // The next time he asks for a frame, he'll get it. restoresavedparserstate (); // so we read from the beginning next time fusingdemux-> fhaveundelivereddata = true; // throw the unshipped data throw reader_not_ready; // directly throws an exception ,} else if (Out. ispotentiallyreadable & // The current stream needs to read data out. saveddatatotalsize + pes_packet_length <1000000/* limit */) {// someone is interested in this stream, but hasn' t begun reading it yet. // save this data, so that the reader will get it when he later asks for it. //// the data read from the file, which is not required currently. Therefore, save it to the existing file. // unsigned char * Buf = new unsigned char [pes_packet_length]; getbytes (BUF, pes_packet_length); mpeg1or2demux: outputdescriptor: saveddata * saveddata = new partition: outputdescriptor: saveddata (BUF, pes_packet_length); If (Out. saveddatahead = NULL) {out. saveddatahead = out. saveddatatail = saveddata;} else {out. saveddatatail-> next = saveddata; out. saveddatatail = saveddata;} Out. saveddatatotalsize + = pes_packet_length; pes_packet_length = 0;} skipbytes (pes_packet_length);} // check for another PES packet next: setparsestate (expiration); Return acquiredstreamidtag ;}
Let me see the if structure with Chinese comments on it,
When the first condition out. iscurrentlyawaitingdata is true, it indicates that the data to be read is exactly what needs to be read. This should be normal.
When the second condition out. iscurrentlyactive is true, this condition indicates that the corresponding stream is active, but data reading is not required currently. This condition is true until the stream has been played. In this condition processing, the fhaveundelivereddata of the response stream is marked as true, and an exception is thrown. This exception is handled in mpegprogramstreamparser: parse.
When the third condition out. ispotentiallyreadable is true, save the data to the cache. Ispotentiallyreadable is set to true in the mpeg1or2demuxedelementarystream class constructor.
According to the above analysis, when the stream is playing, the data will not be saved to the buffer in any case, and it will only be executed when the stream stops playing.
From the above analysis, we can also find other things, which are described here. When the stream data cannot be read, The after function is not called for processing, but an important function is completed in the after function, each after call registers the next data processing task to the task manager. If you do not call the after function stream, will the processing be interrupted? Of course not. For example, the video data is not read during the current processing process, but the video data is also read during the next processing and the after function of video processing is called, this is the function of loop in mpeg1or2demux: continuereadprocessing.
A question that requires further consideration:
1 ). according to the above method, the data to be processed will be postponed (until other streams read data). Will this lead to a longer delay than normal, resulting in slower sending?
2) When. Out. iscurrentlyactive is true, it is better to save the data to the cache?