ao_pulse: support native mute control
[mplayer.git] / libmpdemux / demux_rtp.cpp
blob7b9ebbe256eeb75c28bc0486739617c881678e53
1 /*
2 * routines (with C-linkage) that interface between MPlayer
3 * and the "LIVE555 Streaming Media" libraries
5 * This file is part of MPlayer.
7 * MPlayer is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * MPlayer is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 extern "C" {
23 // on MinGW, we must include windows.h before the things it conflicts
24 #ifdef __MINGW32__ // with. they are each protected from
25 #include <windows.h> // windows.h, but not the other way around.
26 #endif
27 #include "demux_rtp.h"
28 #include "stream/stream.h"
29 #include "stheader.h"
30 #include "options.h"
31 #include "config.h"
33 #include "demux_rtp_internal.h"
35 #include "BasicUsageEnvironment.hh"
36 #include "liveMedia.hh"
37 #include "GroupsockHelper.hh"
38 #include <unistd.h>
40 // A data structure representing input data for each stream:
41 class ReadBufferQueue {
42 public:
43 ReadBufferQueue(MediaSubsession* subsession, demuxer_t* demuxer,
44 char const* tag);
45 virtual ~ReadBufferQueue();
47 FramedSource* readSource() const { return fReadSource; }
48 RTPSource* rtpSource() const { return fRTPSource; }
49 demuxer_t* ourDemuxer() const { return fOurDemuxer; }
50 char const* tag() const { return fTag; }
52 char blockingFlag; // used to implement synchronous reads
54 // For A/V synchronization:
55 Boolean prevPacketWasSynchronized;
56 float prevPacketPTS;
57 ReadBufferQueue** otherQueue;
59 // The 'queue' actually consists of just a single "demux_packet_t"
60 // (because the underlying OS does the actual queueing/buffering):
61 demux_packet_t* dp;
63 // However, we sometimes inspect buffers before delivering them.
64 // For this, we maintain a queue of pending buffers:
65 void savePendingBuffer(demux_packet_t* dp);
66 demux_packet_t* getPendingBuffer();
68 // For H264 over rtsp using AVParser, the next packet has to be saved
69 demux_packet_t* nextpacket;
71 private:
72 demux_packet_t* pendingDPHead;
73 demux_packet_t* pendingDPTail;
75 FramedSource* fReadSource;
76 RTPSource* fRTPSource;
77 demuxer_t* fOurDemuxer;
78 char const* fTag; // used for debugging
81 // A structure of RTP-specific state, kept so that we can cleanly
82 // reclaim it:
83 struct RTPState {
84 char const* sdpDescription;
85 RTSPClient* rtspClient;
86 SIPClient* sipClient;
87 MediaSession* mediaSession;
88 ReadBufferQueue* audioBufferQueue;
89 ReadBufferQueue* videoBufferQueue;
90 unsigned flags;
91 struct timeval firstSyncTime;
94 extern "C" char* network_username;
95 extern "C" char* network_password;
96 static char* openURL_rtsp(RTSPClient* client, char const* url) {
97 // If we were given a user name (and optional password), then use them:
98 if (network_username != NULL) {
99 char const* password = network_password == NULL ? "" : network_password;
100 return client->describeWithPassword(url, network_username, password);
101 } else {
102 return client->describeURL(url);
106 static char* openURL_sip(SIPClient* client, char const* url) {
107 // If we were given a user name (and optional password), then use them:
108 if (network_username != NULL) {
109 char const* password = network_password == NULL ? "" : network_password;
110 return client->inviteWithPassword(url, network_username, password);
111 } else {
112 return client->invite(url);
116 #ifdef CONFIG_LIBNEMESI
117 extern int rtsp_transport_tcp;
118 extern int rtsp_transport_http;
119 #else
120 int rtsp_transport_tcp = 0;
121 int rtsp_transport_http = 0;
122 #endif
124 extern int rtsp_port;
125 extern AVCodecContext *avcctx;
127 extern "C" demuxer_t* demux_open_rtp(demuxer_t* demuxer) {
128 struct MPOpts *opts = demuxer->opts;
129 Boolean success = False;
130 do {
131 TaskScheduler* scheduler = BasicTaskScheduler::createNew();
132 if (scheduler == NULL) break;
133 UsageEnvironment* env = BasicUsageEnvironment::createNew(*scheduler);
134 if (env == NULL) break;
136 RTSPClient* rtspClient = NULL;
137 SIPClient* sipClient = NULL;
139 if (demuxer == NULL || demuxer->stream == NULL) break; // shouldn't happen
140 demuxer->stream->eof = 0; // just in case
142 // Look at the stream's 'priv' field to see if we were initiated
143 // via a SDP description:
144 char* sdpDescription = (char*)(demuxer->stream->priv);
145 if (sdpDescription == NULL) {
146 // We weren't given a SDP description directly, so assume that
147 // we were given a RTSP or SIP URL:
148 char const* protocol = demuxer->stream->streaming_ctrl->url->protocol;
149 char const* url = demuxer->stream->streaming_ctrl->url->url;
150 extern int verbose;
151 if (strcmp(protocol, "rtsp") == 0) {
152 if (rtsp_transport_http == 1) {
153 rtsp_transport_http = demuxer->stream->streaming_ctrl->url->port;
154 rtsp_transport_tcp = 1;
156 rtspClient = RTSPClient::createNew(*env, verbose, "MPlayer", rtsp_transport_http);
157 if (rtspClient == NULL) {
158 fprintf(stderr, "Failed to create RTSP client: %s\n",
159 env->getResultMsg());
160 break;
162 sdpDescription = openURL_rtsp(rtspClient, url);
163 } else { // SIP
164 unsigned char desiredAudioType = 0; // PCMU (use 3 for GSM)
165 sipClient = SIPClient::createNew(*env, desiredAudioType, NULL,
166 verbose, "MPlayer");
167 if (sipClient == NULL) {
168 fprintf(stderr, "Failed to create SIP client: %s\n",
169 env->getResultMsg());
170 break;
172 sipClient->setClientStartPortNum(8000);
173 sdpDescription = openURL_sip(sipClient, url);
176 if (sdpDescription == NULL) {
177 fprintf(stderr, "Failed to get a SDP description from URL \"%s\": %s\n",
178 url, env->getResultMsg());
179 break;
183 // Now that we have a SDP description, create a MediaSession from it:
184 MediaSession* mediaSession = MediaSession::createNew(*env, sdpDescription);
185 if (mediaSession == NULL) break;
188 // Create a 'RTPState' structure containing the state that we just created,
189 // and store it in the demuxer's 'priv' field, for future reference:
190 RTPState* rtpState = new RTPState;
191 rtpState->sdpDescription = sdpDescription;
192 rtpState->rtspClient = rtspClient;
193 rtpState->sipClient = sipClient;
194 rtpState->mediaSession = mediaSession;
195 rtpState->audioBufferQueue = rtpState->videoBufferQueue = NULL;
196 rtpState->flags = 0;
197 rtpState->firstSyncTime.tv_sec = rtpState->firstSyncTime.tv_usec = 0;
198 demuxer->priv = rtpState;
200 int audiofound = 0, videofound = 0;
201 // Create RTP receivers (sources) for each subsession:
202 MediaSubsessionIterator iter(*mediaSession);
203 MediaSubsession* subsession;
204 unsigned desiredReceiveBufferSize;
205 while ((subsession = iter.next()) != NULL) {
206 // Ignore any subsession that's not audio or video:
207 if (strcmp(subsession->mediumName(), "audio") == 0) {
208 if (audiofound) {
209 fprintf(stderr, "Additional subsession \"audio/%s\" skipped\n", subsession->codecName());
210 continue;
212 desiredReceiveBufferSize = 100000;
213 } else if (strcmp(subsession->mediumName(), "video") == 0) {
214 if (videofound) {
215 fprintf(stderr, "Additional subsession \"video/%s\" skipped\n", subsession->codecName());
216 continue;
218 desiredReceiveBufferSize = 2000000;
219 } else {
220 continue;
223 if (rtsp_port)
224 subsession->setClientPortNum (rtsp_port);
226 if (!subsession->initiate()) {
227 fprintf(stderr, "Failed to initiate \"%s/%s\" RTP subsession: %s\n", subsession->mediumName(), subsession->codecName(), env->getResultMsg());
228 } else {
229 fprintf(stderr, "Initiated \"%s/%s\" RTP subsession on port %d\n", subsession->mediumName(), subsession->codecName(), subsession->clientPortNum());
231 // Set the OS's socket receive buffer sufficiently large to avoid
232 // incoming packets getting dropped between successive reads from this
233 // subsession's demuxer. Depending on the bitrate(s) that you expect,
234 // you may wish to tweak the "desiredReceiveBufferSize" values above.
235 int rtpSocketNum = subsession->rtpSource()->RTPgs()->socketNum();
236 int receiveBufferSize
237 = increaseReceiveBufferTo(*env, rtpSocketNum,
238 desiredReceiveBufferSize);
239 if (verbose > 0) {
240 fprintf(stderr, "Increased %s socket receive buffer to %d bytes \n",
241 subsession->mediumName(), receiveBufferSize);
244 if (rtspClient != NULL) {
245 // Issue a RTSP "SETUP" command on the chosen subsession:
246 if (!rtspClient->setupMediaSubsession(*subsession, False,
247 rtsp_transport_tcp)) break;
248 if (!strcmp(subsession->mediumName(), "audio"))
249 audiofound = 1;
250 if (!strcmp(subsession->mediumName(), "video"))
251 videofound = 1;
256 if (rtspClient != NULL) {
257 // Issue a RTSP aggregate "PLAY" command on the whole session:
258 if (!rtspClient->playMediaSession(*mediaSession)) break;
259 } else if (sipClient != NULL) {
260 sipClient->sendACK(); // to start the stream flowing
263 // Now that the session is ready to be read, do additional
264 // MPlayer codec-specific initialization on each subsession:
265 iter.reset();
266 while ((subsession = iter.next()) != NULL) {
267 if (subsession->readSource() == NULL) continue; // not reading this
269 unsigned flags = 0;
270 if (strcmp(subsession->mediumName(), "audio") == 0) {
271 rtpState->audioBufferQueue
272 = new ReadBufferQueue(subsession, demuxer, "audio");
273 rtpState->audioBufferQueue->otherQueue = &(rtpState->videoBufferQueue);
274 rtpCodecInitialize_audio(demuxer, subsession, flags);
275 } else if (strcmp(subsession->mediumName(), "video") == 0) {
276 rtpState->videoBufferQueue
277 = new ReadBufferQueue(subsession, demuxer, "video");
278 rtpState->videoBufferQueue->otherQueue = &(rtpState->audioBufferQueue);
279 rtpCodecInitialize_video(demuxer, subsession, flags);
281 rtpState->flags |= flags;
283 success = True;
284 } while (0);
285 if (!success) return NULL; // an error occurred
287 // Hack: If audio and video are demuxed together on a single RTP stream,
288 // then create a new "demuxer_t" structure to allow the higher-level
289 // code to recognize this:
290 if (demux_is_multiplexed_rtp_stream(demuxer)) {
291 stream_t* s = new_ds_stream(demuxer->video);
292 demuxer_t* od = demux_open(opts, s, DEMUXER_TYPE_UNKNOWN,
293 opts->audio_id, opts->video_id, opts->sub_id,
294 NULL);
295 demuxer = new_demuxers_demuxer(od, od, od);
298 return demuxer;
301 extern "C" int demux_is_mpeg_rtp_stream(demuxer_t* demuxer) {
302 // Get the RTP state that was stored in the demuxer's 'priv' field:
303 RTPState* rtpState = (RTPState*)(demuxer->priv);
305 return (rtpState->flags&RTPSTATE_IS_MPEG12_VIDEO) != 0;
308 extern "C" int demux_is_multiplexed_rtp_stream(demuxer_t* demuxer) {
309 // Get the RTP state that was stored in the demuxer's 'priv' field:
310 RTPState* rtpState = (RTPState*)(demuxer->priv);
312 return (rtpState->flags&RTPSTATE_IS_MULTIPLEXED) != 0;
315 static demux_packet_t* getBuffer(demuxer_t* demuxer, demux_stream_t* ds,
316 Boolean mustGetNewData,
317 float& ptsBehind); // forward
319 extern "C" int demux_rtp_fill_buffer(demuxer_t* demuxer, demux_stream_t* ds) {
320 // Get a filled-in "demux_packet" from the RTP source, and deliver it.
321 // Note that this is called as a synchronous read operation, so it needs
322 // to block in the (hopefully infrequent) case where no packet is
323 // immediately available.
325 while (1) {
326 float ptsBehind;
327 demux_packet_t* dp = getBuffer(demuxer, ds, False, ptsBehind); // blocking
328 if (dp == NULL) return 0;
330 if (demuxer->stream->eof) return 0; // source stream has closed down
332 // Before using this packet, check to make sure that its presentation
333 // time is not far behind the other stream (if any). If it is,
334 // then we discard this packet, and get another instead. (The rest of
335 // MPlayer doesn't always do a good job of synchronizing when the
336 // audio and video streams get this far apart.)
337 // (We don't do this when streaming over TCP, because then the audio and
338 // video streams are interleaved.)
339 // (Also, if the stream is *excessively* far behind, then we allow
340 // the packet, because in this case it probably means that there was
341 // an error in the source's timestamp synchronization.)
342 const float ptsBehindThreshold = 1.0; // seconds
343 const float ptsBehindLimit = 60.0; // seconds
344 if (ptsBehind < ptsBehindThreshold ||
345 ptsBehind > ptsBehindLimit ||
346 rtsp_transport_tcp) { // packet's OK
347 ds_add_packet(ds, dp);
348 break;
351 #ifdef DEBUG_PRINT_DISCARDED_PACKETS
352 RTPState* rtpState = (RTPState*)(demuxer->priv);
353 ReadBufferQueue* bufferQueue = ds == demuxer->video ? rtpState->videoBufferQueue : rtpState->audioBufferQueue;
354 fprintf(stderr, "Discarding %s packet (%fs behind)\n", bufferQueue->tag(), ptsBehind);
355 #endif
356 free_demux_packet(dp); // give back this packet, and get another one
359 return 1;
362 Boolean awaitRTPPacket(demuxer_t* demuxer, demux_stream_t* ds,
363 unsigned char*& packetData, unsigned& packetDataLen,
364 float& pts) {
365 // Similar to "demux_rtp_fill_buffer()", except that the "demux_packet"
366 // is not delivered to the "demux_stream".
367 float ptsBehind;
368 demux_packet_t* dp = getBuffer(demuxer, ds, True, ptsBehind); // blocking
369 if (dp == NULL) return False;
371 packetData = dp->buffer;
372 packetDataLen = dp->len;
373 pts = dp->pts;
375 return True;
378 static void teardownRTSPorSIPSession(RTPState* rtpState); // forward
380 extern "C" void demux_close_rtp(demuxer_t* demuxer) {
381 // Reclaim all RTP-related state:
383 // Get the RTP state that was stored in the demuxer's 'priv' field:
384 RTPState* rtpState = (RTPState*)(demuxer->priv);
385 if (rtpState == NULL) return;
387 teardownRTSPorSIPSession(rtpState);
389 UsageEnvironment* env = NULL;
390 TaskScheduler* scheduler = NULL;
391 if (rtpState->mediaSession != NULL) {
392 env = &(rtpState->mediaSession->envir());
393 scheduler = &(env->taskScheduler());
395 Medium::close(rtpState->mediaSession);
396 Medium::close(rtpState->rtspClient);
397 Medium::close(rtpState->sipClient);
398 delete rtpState->audioBufferQueue;
399 delete rtpState->videoBufferQueue;
400 delete[] rtpState->sdpDescription;
401 delete rtpState;
402 av_freep(&avcctx);
404 env->reclaim(); delete scheduler;
407 ////////// Extra routines that help implement the above interface functions:
409 #define MAX_RTP_FRAME_SIZE 5000000
410 // >= the largest conceivable frame composed from one or more RTP packets
412 static void afterReading(void* clientData, unsigned frameSize,
413 unsigned /*numTruncatedBytes*/,
414 struct timeval presentationTime,
415 unsigned /*durationInMicroseconds*/) {
416 int headersize = 0;
417 if (frameSize >= MAX_RTP_FRAME_SIZE) {
418 fprintf(stderr, "Saw an input frame too large (>=%d). Increase MAX_RTP_FRAME_SIZE in \"demux_rtp.cpp\".\n",
419 MAX_RTP_FRAME_SIZE);
421 ReadBufferQueue* bufferQueue = (ReadBufferQueue*)clientData;
422 demuxer_t* demuxer = bufferQueue->ourDemuxer();
423 RTPState* rtpState = (RTPState*)(demuxer->priv);
425 if (frameSize > 0) demuxer->stream->eof = 0;
427 demux_packet_t* dp = bufferQueue->dp;
429 if (bufferQueue->readSource()->isAMRAudioSource())
430 headersize = 1;
431 else if (bufferQueue == rtpState->videoBufferQueue &&
432 ((sh_video_t*)demuxer->video->sh)->format == mmioFOURCC('H','2','6','4')) {
433 dp->buffer[0]=0x00;
434 dp->buffer[1]=0x00;
435 dp->buffer[2]=0x01;
436 headersize = 3;
439 resize_demux_packet(dp, frameSize + headersize);
441 // Set the packet's presentation time stamp, depending on whether or
442 // not our RTP source's timestamps have been synchronized yet:
443 Boolean hasBeenSynchronized
444 = bufferQueue->rtpSource()->hasBeenSynchronizedUsingRTCP();
445 if (hasBeenSynchronized) {
446 if (verbose > 0 && !bufferQueue->prevPacketWasSynchronized) {
447 fprintf(stderr, "%s stream has been synchronized using RTCP \n",
448 bufferQueue->tag());
451 struct timeval* fst = &(rtpState->firstSyncTime); // abbrev
452 if (fst->tv_sec == 0 && fst->tv_usec == 0) {
453 *fst = presentationTime;
456 // For the "pts" field, use the time differential from the first
457 // synchronized time, rather than absolute time, in order to avoid
458 // round-off errors when converting to a float:
459 dp->pts = presentationTime.tv_sec - fst->tv_sec
460 + (presentationTime.tv_usec - fst->tv_usec)/1000000.0;
461 bufferQueue->prevPacketPTS = dp->pts;
462 } else {
463 if (verbose > 0 && bufferQueue->prevPacketWasSynchronized) {
464 fprintf(stderr, "%s stream is no longer RTCP-synchronized \n",
465 bufferQueue->tag());
468 // use the previous packet's "pts" once again:
469 dp->pts = bufferQueue->prevPacketPTS;
471 bufferQueue->prevPacketWasSynchronized = hasBeenSynchronized;
473 dp->pos = demuxer->filepos;
474 demuxer->filepos += frameSize + headersize;
476 // Signal any pending 'doEventLoop()' call on this queue:
477 bufferQueue->blockingFlag = ~0;
480 static void onSourceClosure(void* clientData) {
481 ReadBufferQueue* bufferQueue = (ReadBufferQueue*)clientData;
482 demuxer_t* demuxer = bufferQueue->ourDemuxer();
484 demuxer->stream->eof = 1;
486 // Signal any pending 'doEventLoop()' call on this queue:
487 bufferQueue->blockingFlag = ~0;
490 static demux_packet_t* getBuffer(demuxer_t* demuxer, demux_stream_t* ds,
491 Boolean mustGetNewData,
492 float& ptsBehind) {
493 // Begin by finding the buffer queue that we want to read from:
494 // (Get this from the RTP state, which we stored in
495 // the demuxer's 'priv' field)
496 RTPState* rtpState = (RTPState*)(demuxer->priv);
497 ReadBufferQueue* bufferQueue = NULL;
498 int headersize = 0;
499 int waitboth = 0;
500 TaskToken task, task2;
502 if (demuxer->stream->eof) return NULL;
504 if (ds == demuxer->video) {
505 bufferQueue = rtpState->audioBufferQueue;
506 // HACK: for the latest versions we must also receive audio
507 // when probing for video FPS, otherwise the stream just hangs
508 // and times out
509 if (mustGetNewData &&
510 bufferQueue &&
511 bufferQueue->readSource() &&
512 !bufferQueue->nextpacket) {
513 headersize = bufferQueue->readSource()->isAMRAudioSource() ? 1 : 0;
514 demux_packet_t *dp = new_demux_packet(MAX_RTP_FRAME_SIZE);
515 bufferQueue->dp = dp;
516 bufferQueue->blockingFlag = 0;
517 bufferQueue->readSource()->getNextFrame(
518 &dp->buffer[headersize], MAX_RTP_FRAME_SIZE - headersize,
519 afterReading, bufferQueue,
520 onSourceClosure, bufferQueue);
521 task2 = bufferQueue->readSource()->envir().taskScheduler().
522 scheduleDelayedTask(10000000, onSourceClosure, bufferQueue);
523 waitboth = 1;
525 bufferQueue = rtpState->videoBufferQueue;
526 if (((sh_video_t*)ds->sh)->format == mmioFOURCC('H','2','6','4'))
527 headersize = 3;
528 } else if (ds == demuxer->audio) {
529 bufferQueue = rtpState->audioBufferQueue;
530 if (bufferQueue->readSource()->isAMRAudioSource())
531 headersize = 1;
532 } else {
533 fprintf(stderr, "(demux_rtp)getBuffer: internal error: unknown stream\n");
534 return NULL;
537 if (bufferQueue == NULL || bufferQueue->readSource() == NULL) {
538 fprintf(stderr, "(demux_rtp)getBuffer failed: no appropriate RTP subsession has been set up\n");
539 return NULL;
542 demux_packet_t* dp = NULL;
543 if (!mustGetNewData) {
544 // Check whether we have a previously-saved buffer that we can use:
545 dp = bufferQueue->getPendingBuffer();
546 if (dp != NULL) {
547 ptsBehind = 0.0; // so that we always accept this data
548 return dp;
552 // Allocate a new packet buffer, and arrange to read into it:
553 if (!bufferQueue->nextpacket) {
554 dp = new_demux_packet(MAX_RTP_FRAME_SIZE);
555 bufferQueue->dp = dp;
556 if (dp == NULL) return NULL;
559 extern AVCodecParserContext * h264parserctx;
560 int consumed, poutbuf_size = 1;
561 const uint8_t *poutbuf = NULL;
562 float lastpts = 0.0;
564 do {
565 if (!bufferQueue->nextpacket) {
566 // Schedule the read operation:
567 bufferQueue->blockingFlag = 0;
568 bufferQueue->readSource()->getNextFrame(&dp->buffer[headersize], MAX_RTP_FRAME_SIZE - headersize,
569 afterReading, bufferQueue,
570 onSourceClosure, bufferQueue);
571 // Block ourselves until data becomes available:
572 TaskScheduler& scheduler
573 = bufferQueue->readSource()->envir().taskScheduler();
574 int delay = 10000000;
575 if (bufferQueue->prevPacketPTS * 1.05 > rtpState->mediaSession->playEndTime())
576 delay /= 10;
577 task = scheduler.scheduleDelayedTask(delay, onSourceClosure, bufferQueue);
578 scheduler.doEventLoop(&bufferQueue->blockingFlag);
579 scheduler.unscheduleDelayedTask(task);
580 if (waitboth) {
581 scheduler.doEventLoop(&rtpState->audioBufferQueue->blockingFlag);
582 scheduler.unscheduleDelayedTask(task2);
584 if (demuxer->stream->eof) {
585 free_demux_packet(dp);
586 return NULL;
589 if (headersize == 1) // amr
590 dp->buffer[0] =
591 ((AMRAudioSource*)bufferQueue->readSource())->lastFrameHeader();
592 } else {
593 bufferQueue->dp = dp = bufferQueue->nextpacket;
594 bufferQueue->nextpacket = NULL;
596 if (headersize == 3 && h264parserctx) { // h264
597 consumed = h264parserctx->parser->parser_parse(h264parserctx,
598 avcctx,
599 &poutbuf, &poutbuf_size,
600 dp->buffer, dp->len);
602 if (!consumed && !poutbuf_size)
603 return NULL;
605 if (!poutbuf_size) {
606 lastpts=dp->pts;
607 free_demux_packet(dp);
608 bufferQueue->dp = dp = new_demux_packet(MAX_RTP_FRAME_SIZE);
609 } else {
610 bufferQueue->nextpacket = dp;
611 bufferQueue->dp = dp = new_demux_packet(poutbuf_size);
612 memcpy(dp->buffer, poutbuf, poutbuf_size);
613 dp->pts=lastpts;
616 } while (!poutbuf_size);
618 // Set the "ptsBehind" result parameter:
619 if (bufferQueue->prevPacketPTS != 0.0
620 && bufferQueue->prevPacketWasSynchronized
621 && *(bufferQueue->otherQueue) != NULL
622 && (*(bufferQueue->otherQueue))->prevPacketPTS != 0.0
623 && (*(bufferQueue->otherQueue))->prevPacketWasSynchronized) {
624 ptsBehind = (*(bufferQueue->otherQueue))->prevPacketPTS
625 - bufferQueue->prevPacketPTS;
626 } else {
627 ptsBehind = 0.0;
630 if (mustGetNewData) {
631 // Save this buffer for future reads:
632 bufferQueue->savePendingBuffer(dp);
635 return dp;
638 static void teardownRTSPorSIPSession(RTPState* rtpState) {
639 MediaSession* mediaSession = rtpState->mediaSession;
640 if (mediaSession == NULL) return;
641 if (rtpState->rtspClient != NULL) {
642 rtpState->rtspClient->teardownMediaSession(*mediaSession);
643 } else if (rtpState->sipClient != NULL) {
644 rtpState->sipClient->sendBYE();
648 ////////// "ReadBuffer" and "ReadBufferQueue" implementation:
650 ReadBufferQueue::ReadBufferQueue(MediaSubsession* subsession,
651 demuxer_t* demuxer, char const* tag)
652 : prevPacketWasSynchronized(False), prevPacketPTS(0.0), otherQueue(NULL),
653 dp(NULL), nextpacket(NULL),
654 pendingDPHead(NULL), pendingDPTail(NULL),
655 fReadSource(subsession == NULL ? NULL : subsession->readSource()),
656 fRTPSource(subsession == NULL ? NULL : subsession->rtpSource()),
657 fOurDemuxer(demuxer), fTag(strdup(tag)) {
660 ReadBufferQueue::~ReadBufferQueue() {
661 free((void *)fTag);
663 // Free any pending buffers (that never got delivered):
664 demux_packet_t* dp = pendingDPHead;
665 while (dp != NULL) {
666 demux_packet_t* dpNext = dp->next;
667 dp->next = NULL;
668 free_demux_packet(dp);
669 dp = dpNext;
673 void ReadBufferQueue::savePendingBuffer(demux_packet_t* dp) {
674 // Keep this buffer around, until MPlayer asks for it later:
675 if (pendingDPTail == NULL) {
676 pendingDPHead = pendingDPTail = dp;
677 } else {
678 pendingDPTail->next = dp;
679 pendingDPTail = dp;
681 dp->next = NULL;
684 demux_packet_t* ReadBufferQueue::getPendingBuffer() {
685 demux_packet_t* dp = pendingDPHead;
686 if (dp != NULL) {
687 pendingDPHead = dp->next;
688 if (pendingDPHead == NULL) pendingDPTail = NULL;
690 dp->next = NULL;
693 return dp;
696 static int demux_rtp_control(struct demuxer *demuxer, int cmd, void *arg) {
697 double endpts = ((RTPState*)demuxer->priv)->mediaSession->playEndTime();
699 switch(cmd) {
700 case DEMUXER_CTRL_GET_TIME_LENGTH:
701 if (endpts <= 0)
702 return DEMUXER_CTRL_DONTKNOW;
703 *((double *)arg) = endpts;
704 return DEMUXER_CTRL_OK;
706 case DEMUXER_CTRL_GET_PERCENT_POS:
707 if (endpts <= 0)
708 return DEMUXER_CTRL_DONTKNOW;
709 *((int *)arg) = (int)(((RTPState*)demuxer->priv)->videoBufferQueue->prevPacketPTS*100/endpts);
710 return DEMUXER_CTRL_OK;
712 default:
713 return DEMUXER_CTRL_NOTIMPL;
717 demuxer_desc_t demuxer_desc_rtp = {
718 "LIVE555 RTP demuxer",
719 "live555",
721 "Ross Finlayson",
722 "requires LIVE555 Streaming Media library",
723 DEMUXER_TYPE_RTP,
724 0, // no autodetect
725 NULL,
726 demux_rtp_fill_buffer,
727 demux_open_rtp,
728 demux_close_rtp,
729 NULL,
730 demux_rtp_control