libavformat/rtpdec.c
Go to the documentation of this file.
00001 /*
00002  * RTP input format
00003  * Copyright (c) 2002 Fabrice Bellard
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 #include "libavutil/mathematics.h"
00023 #include "libavutil/avstring.h"
00024 #include "libavcodec/get_bits.h"
00025 #include "avformat.h"
00026 #include "mpegts.h"
00027 #include "url.h"
00028 
00029 #include <unistd.h>
00030 #include "network.h"
00031 
00032 #include "rtpdec.h"
00033 #include "rtpdec_formats.h"
00034 
00035 //#define DEBUG
00036 
00037 /* TODO: - add RTCP statistics reporting (should be optional).
00038 
00039          - add support for h263/mpeg4 packetized output : IDEA: send a
00040          buffer to 'rtp_write_packet' contains all the packets for ONE
00041          frame. Each packet should have a four byte header containing
00042          the length in big endian format (same trick as
00043          'ffio_open_dyn_packet_buf')
00044 */
00045 
00046 static RTPDynamicProtocolHandler ff_realmedia_mp3_dynamic_handler = {
00047     .enc_name           = "X-MP3-draft-00",
00048     .codec_type         = AVMEDIA_TYPE_AUDIO,
00049     .codec_id           = CODEC_ID_MP3ADU,
00050 };
00051 
00052 /* statistics functions */
00053 static RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
00054 
00055 void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
00056 {
00057     handler->next= RTPFirstDynamicPayloadHandler;
00058     RTPFirstDynamicPayloadHandler= handler;
00059 }
00060 
00061 void av_register_rtp_dynamic_payload_handlers(void)
00062 {
00063     ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
00064     ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
00065     ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
00066     ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
00067     ff_register_dynamic_payload_handler(&ff_h263_1998_dynamic_handler);
00068     ff_register_dynamic_payload_handler(&ff_h263_2000_dynamic_handler);
00069     ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
00070     ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
00071     ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
00072     ff_register_dynamic_payload_handler(&ff_qdm2_dynamic_handler);
00073     ff_register_dynamic_payload_handler(&ff_svq3_dynamic_handler);
00074     ff_register_dynamic_payload_handler(&ff_mp4a_latm_dynamic_handler);
00075     ff_register_dynamic_payload_handler(&ff_vp8_dynamic_handler);
00076     ff_register_dynamic_payload_handler(&ff_qcelp_dynamic_handler);
00077     ff_register_dynamic_payload_handler(&ff_realmedia_mp3_dynamic_handler);
00078 
00079     ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
00080     ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
00081 
00082     ff_register_dynamic_payload_handler(&ff_qt_rtp_aud_handler);
00083     ff_register_dynamic_payload_handler(&ff_qt_rtp_vid_handler);
00084     ff_register_dynamic_payload_handler(&ff_quicktime_rtp_aud_handler);
00085     ff_register_dynamic_payload_handler(&ff_quicktime_rtp_vid_handler);
00086 
00087     ff_register_dynamic_payload_handler(&ff_g726_16_dynamic_handler);
00088     ff_register_dynamic_payload_handler(&ff_g726_24_dynamic_handler);
00089     ff_register_dynamic_payload_handler(&ff_g726_32_dynamic_handler);
00090     ff_register_dynamic_payload_handler(&ff_g726_40_dynamic_handler);
00091 }
00092 
00093 RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
00094                                                   enum AVMediaType codec_type)
00095 {
00096     RTPDynamicProtocolHandler *handler;
00097     for (handler = RTPFirstDynamicPayloadHandler;
00098          handler; handler = handler->next)
00099         if (!av_strcasecmp(name, handler->enc_name) &&
00100             codec_type == handler->codec_type)
00101             return handler;
00102     return NULL;
00103 }
00104 
00105 RTPDynamicProtocolHandler *ff_rtp_handler_find_by_id(int id,
00106                                                 enum AVMediaType codec_type)
00107 {
00108     RTPDynamicProtocolHandler *handler;
00109     for (handler = RTPFirstDynamicPayloadHandler;
00110          handler; handler = handler->next)
00111         if (handler->static_payload_id && handler->static_payload_id == id &&
00112             codec_type == handler->codec_type)
00113             return handler;
00114     return NULL;
00115 }
00116 
00117 static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
00118 {
00119     int payload_len;
00120     while (len >= 4) {
00121         payload_len = FFMIN(len, (AV_RB16(buf + 2) + 1) * 4);
00122 
00123         switch (buf[1]) {
00124         case RTCP_SR:
00125             if (payload_len < 20) {
00126                 av_log(NULL, AV_LOG_ERROR, "Invalid length for RTCP SR packet\n");
00127                 return AVERROR_INVALIDDATA;
00128             }
00129 
00130             s->last_rtcp_ntp_time = AV_RB64(buf + 8);
00131             s->last_rtcp_timestamp = AV_RB32(buf + 16);
00132             if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
00133                 s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
00134                 if (!s->base_timestamp)
00135                     s->base_timestamp = s->last_rtcp_timestamp;
00136                 s->rtcp_ts_offset = s->last_rtcp_timestamp - s->base_timestamp;
00137             }
00138 
00139             break;
00140         case RTCP_BYE:
00141             return -RTCP_BYE;
00142         }
00143 
00144         buf += payload_len;
00145         len -= payload_len;
00146     }
00147     return -1;
00148 }
00149 
00150 #define RTP_SEQ_MOD (1<<16)
00151 
00155 static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence) // called on parse open packet.
00156 {
00157     memset(s, 0, sizeof(RTPStatistics));
00158     s->max_seq= base_sequence;
00159     s->probation= 1;
00160 }
00161 
00165 static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
00166 {
00167     s->max_seq= seq;
00168     s->cycles= 0;
00169     s->base_seq= seq -1;
00170     s->bad_seq= RTP_SEQ_MOD + 1;
00171     s->received= 0;
00172     s->expected_prior= 0;
00173     s->received_prior= 0;
00174     s->jitter= 0;
00175     s->transit= 0;
00176 }
00177 
00181 static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
00182 {
00183     uint16_t udelta= seq - s->max_seq;
00184     const int MAX_DROPOUT= 3000;
00185     const int MAX_MISORDER = 100;
00186     const int MIN_SEQUENTIAL = 2;
00187 
00188     /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
00189     if(s->probation)
00190     {
00191         if(seq==s->max_seq + 1) {
00192             s->probation--;
00193             s->max_seq= seq;
00194             if(s->probation==0) {
00195                 rtp_init_sequence(s, seq);
00196                 s->received++;
00197                 return 1;
00198             }
00199         } else {
00200             s->probation= MIN_SEQUENTIAL - 1;
00201             s->max_seq = seq;
00202         }
00203     } else if (udelta < MAX_DROPOUT) {
00204         // in order, with permissible gap
00205         if(seq < s->max_seq) {
00206             //sequence number wrapped; count antother 64k cycles
00207             s->cycles += RTP_SEQ_MOD;
00208         }
00209         s->max_seq= seq;
00210     } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
00211         // sequence made a large jump...
00212         if(seq==s->bad_seq) {
00213             // two sequential packets-- assume that the other side restarted without telling us; just resync.
00214             rtp_init_sequence(s, seq);
00215         } else {
00216             s->bad_seq= (seq + 1) & (RTP_SEQ_MOD-1);
00217             return 0;
00218         }
00219     } else {
00220         // duplicate or reordered packet...
00221     }
00222     s->received++;
00223     return 1;
00224 }
00225 
00226 int ff_rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
00227 {
00228     AVIOContext *pb;
00229     uint8_t *buf;
00230     int len;
00231     int rtcp_bytes;
00232     RTPStatistics *stats= &s->statistics;
00233     uint32_t lost;
00234     uint32_t extended_max;
00235     uint32_t expected_interval;
00236     uint32_t received_interval;
00237     uint32_t lost_interval;
00238     uint32_t expected;
00239     uint32_t fraction;
00240     uint64_t ntp_time= s->last_rtcp_ntp_time; // TODO: Get local ntp time?
00241 
00242     if (!s->rtp_ctx || (count < 1))
00243         return -1;
00244 
00245     /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
00246     /* XXX: mpeg pts hardcoded. RTCP send every 0.5 seconds */
00247     s->octet_count += count;
00248     rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
00249         RTCP_TX_RATIO_DEN;
00250     rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
00251     if (rtcp_bytes < 28)
00252         return -1;
00253     s->last_octet_count = s->octet_count;
00254 
00255     if (avio_open_dyn_buf(&pb) < 0)
00256         return -1;
00257 
00258     // Receiver Report
00259     avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
00260     avio_w8(pb, RTCP_RR);
00261     avio_wb16(pb, 7); /* length in words - 1 */
00262     // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
00263     avio_wb32(pb, s->ssrc + 1);
00264     avio_wb32(pb, s->ssrc); // server SSRC
00265     // some placeholders we should really fill...
00266     // RFC 1889/p64
00267     extended_max= stats->cycles + stats->max_seq;
00268     expected= extended_max - stats->base_seq + 1;
00269     lost= expected - stats->received;
00270     lost= FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
00271     expected_interval= expected - stats->expected_prior;
00272     stats->expected_prior= expected;
00273     received_interval= stats->received - stats->received_prior;
00274     stats->received_prior= stats->received;
00275     lost_interval= expected_interval - received_interval;
00276     if (expected_interval==0 || lost_interval<=0) fraction= 0;
00277     else fraction = (lost_interval<<8)/expected_interval;
00278 
00279     fraction= (fraction<<24) | lost;
00280 
00281     avio_wb32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
00282     avio_wb32(pb, extended_max); /* max sequence received */
00283     avio_wb32(pb, stats->jitter>>4); /* jitter */
00284 
00285     if(s->last_rtcp_ntp_time==AV_NOPTS_VALUE)
00286     {
00287         avio_wb32(pb, 0); /* last SR timestamp */
00288         avio_wb32(pb, 0); /* delay since last SR */
00289     } else {
00290         uint32_t middle_32_bits= s->last_rtcp_ntp_time>>16; // this is valid, right? do we need to handle 64 bit values special?
00291         uint32_t delay_since_last= ntp_time - s->last_rtcp_ntp_time;
00292 
00293         avio_wb32(pb, middle_32_bits); /* last SR timestamp */
00294         avio_wb32(pb, delay_since_last); /* delay since last SR */
00295     }
00296 
00297     // CNAME
00298     avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
00299     avio_w8(pb, RTCP_SDES);
00300     len = strlen(s->hostname);
00301     avio_wb16(pb, (6 + len + 3) / 4); /* length in words - 1 */
00302     avio_wb32(pb, s->ssrc + 1);
00303     avio_w8(pb, 0x01);
00304     avio_w8(pb, len);
00305     avio_write(pb, s->hostname, len);
00306     // padding
00307     for (len = (6 + len) % 4; len % 4; len++) {
00308         avio_w8(pb, 0);
00309     }
00310 
00311     avio_flush(pb);
00312     len = avio_close_dyn_buf(pb, &buf);
00313     if ((len > 0) && buf) {
00314         int av_unused result;
00315         av_dlog(s->ic, "sending %d bytes of RR\n", len);
00316         result= ffurl_write(s->rtp_ctx, buf, len);
00317         av_dlog(s->ic, "result from ffurl_write: %d\n", result);
00318         av_free(buf);
00319     }
00320     return 0;
00321 }
00322 
00323 void ff_rtp_send_punch_packets(URLContext* rtp_handle)
00324 {
00325     AVIOContext *pb;
00326     uint8_t *buf;
00327     int len;
00328 
00329     /* Send a small RTP packet */
00330     if (avio_open_dyn_buf(&pb) < 0)
00331         return;
00332 
00333     avio_w8(pb, (RTP_VERSION << 6));
00334     avio_w8(pb, 0); /* Payload type */
00335     avio_wb16(pb, 0); /* Seq */
00336     avio_wb32(pb, 0); /* Timestamp */
00337     avio_wb32(pb, 0); /* SSRC */
00338 
00339     avio_flush(pb);
00340     len = avio_close_dyn_buf(pb, &buf);
00341     if ((len > 0) && buf)
00342         ffurl_write(rtp_handle, buf, len);
00343     av_free(buf);
00344 
00345     /* Send a minimal RTCP RR */
00346     if (avio_open_dyn_buf(&pb) < 0)
00347         return;
00348 
00349     avio_w8(pb, (RTP_VERSION << 6));
00350     avio_w8(pb, RTCP_RR); /* receiver report */
00351     avio_wb16(pb, 1); /* length in words - 1 */
00352     avio_wb32(pb, 0); /* our own SSRC */
00353 
00354     avio_flush(pb);
00355     len = avio_close_dyn_buf(pb, &buf);
00356     if ((len > 0) && buf)
00357         ffurl_write(rtp_handle, buf, len);
00358     av_free(buf);
00359 }
00360 
00361 
00367 RTPDemuxContext *ff_rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, int queue_size)
00368 {
00369     RTPDemuxContext *s;
00370 
00371     s = av_mallocz(sizeof(RTPDemuxContext));
00372     if (!s)
00373         return NULL;
00374     s->payload_type = payload_type;
00375     s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
00376     s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
00377     s->ic = s1;
00378     s->st = st;
00379     s->queue_size = queue_size;
00380     rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
00381     if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
00382         s->ts = ff_mpegts_parse_open(s->ic);
00383         if (s->ts == NULL) {
00384             av_free(s);
00385             return NULL;
00386         }
00387     } else {
00388         switch(st->codec->codec_id) {
00389         case CODEC_ID_MPEG1VIDEO:
00390         case CODEC_ID_MPEG2VIDEO:
00391         case CODEC_ID_MP2:
00392         case CODEC_ID_MP3:
00393         case CODEC_ID_MPEG4:
00394         case CODEC_ID_H263:
00395         case CODEC_ID_H264:
00396             st->need_parsing = AVSTREAM_PARSE_FULL;
00397             break;
00398         case CODEC_ID_ADPCM_G722:
00399             /* According to RFC 3551, the stream clock rate is 8000
00400              * even if the sample rate is 16000. */
00401             if (st->codec->sample_rate == 8000)
00402                 st->codec->sample_rate = 16000;
00403             break;
00404         default:
00405             break;
00406         }
00407     }
00408     // needed to send back RTCP RR in RTSP sessions
00409     s->rtp_ctx = rtpc;
00410     gethostname(s->hostname, sizeof(s->hostname));
00411     return s;
00412 }
00413 
00414 void
00415 ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
00416                                   RTPDynamicProtocolHandler *handler)
00417 {
00418     s->dynamic_protocol_context = ctx;
00419     s->parse_packet = handler->parse_packet;
00420 }
00421 
00425 static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
00426 {
00427     if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
00428         return; /* Timestamp already set by depacketizer */
00429     if (timestamp == RTP_NOTS_VALUE)
00430         return;
00431 
00432     if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
00433         int64_t addend;
00434         int delta_timestamp;
00435 
00436         /* compute pts from timestamp with received ntp_time */
00437         delta_timestamp = timestamp - s->last_rtcp_timestamp;
00438         /* convert to the PTS timebase */
00439         addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time, s->st->time_base.den, (uint64_t)s->st->time_base.num << 32);
00440         pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
00441                    delta_timestamp;
00442         return;
00443     }
00444 
00445     if (!s->base_timestamp)
00446         s->base_timestamp = timestamp;
00447     /* assume that the difference is INT32_MIN < x < INT32_MAX, but allow the first timestamp to exceed INT32_MAX */
00448     if (!s->timestamp)
00449         s->unwrapped_timestamp += timestamp;
00450     else
00451         s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
00452     s->timestamp = timestamp;
00453     pkt->pts = s->unwrapped_timestamp + s->range_start_offset - s->base_timestamp;
00454 }
00455 
00456 static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
00457                                      const uint8_t *buf, int len)
00458 {
00459     unsigned int ssrc, h;
00460     int payload_type, seq, ret, flags = 0;
00461     int ext;
00462     AVStream *st;
00463     uint32_t timestamp;
00464     int rv= 0;
00465 
00466     ext = buf[0] & 0x10;
00467     payload_type = buf[1] & 0x7f;
00468     if (buf[1] & 0x80)
00469         flags |= RTP_FLAG_MARKER;
00470     seq  = AV_RB16(buf + 2);
00471     timestamp = AV_RB32(buf + 4);
00472     ssrc = AV_RB32(buf + 8);
00473     /* store the ssrc in the RTPDemuxContext */
00474     s->ssrc = ssrc;
00475 
00476     /* NOTE: we can handle only one payload type */
00477     if (s->payload_type != payload_type)
00478         return -1;
00479 
00480     st = s->st;
00481     // only do something with this if all the rtp checks pass...
00482     if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
00483     {
00484         av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
00485                payload_type, seq, ((s->seq + 1) & 0xffff));
00486         return -1;
00487     }
00488 
00489     if (buf[0] & 0x20) {
00490         int padding = buf[len - 1];
00491         if (len >= 12 + padding)
00492             len -= padding;
00493     }
00494 
00495     s->seq = seq;
00496     len -= 12;
00497     buf += 12;
00498 
00499     /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
00500     if (ext) {
00501         if (len < 4)
00502             return -1;
00503         /* calculate the header extension length (stored as number
00504          * of 32-bit words) */
00505         ext = (AV_RB16(buf + 2) + 1) << 2;
00506 
00507         if (len < ext)
00508             return -1;
00509         // skip past RTP header extension
00510         len -= ext;
00511         buf += ext;
00512     }
00513 
00514     if (!st) {
00515         /* specific MPEG2TS demux support */
00516         ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
00517         /* The only error that can be returned from ff_mpegts_parse_packet
00518          * is "no more data to return from the provided buffer", so return
00519          * AVERROR(EAGAIN) for all errors */
00520         if (ret < 0)
00521             return AVERROR(EAGAIN);
00522         if (ret < len) {
00523             s->read_buf_size = len - ret;
00524             memcpy(s->buf, buf + ret, s->read_buf_size);
00525             s->read_buf_index = 0;
00526             return 1;
00527         }
00528         return 0;
00529     } else if (s->parse_packet) {
00530         rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
00531                              s->st, pkt, &timestamp, buf, len, flags);
00532     } else {
00533         // at this point, the RTP header has been stripped;  This is ASSUMING that there is only 1 CSRC, which in't wise.
00534         switch(st->codec->codec_id) {
00535         case CODEC_ID_MP2:
00536         case CODEC_ID_MP3:
00537             /* better than nothing: skip mpeg audio RTP header */
00538             if (len <= 4)
00539                 return -1;
00540             h = AV_RB32(buf);
00541             len -= 4;
00542             buf += 4;
00543             av_new_packet(pkt, len);
00544             memcpy(pkt->data, buf, len);
00545             break;
00546         case CODEC_ID_MPEG1VIDEO:
00547         case CODEC_ID_MPEG2VIDEO:
00548             /* better than nothing: skip mpeg video RTP header */
00549             if (len <= 4)
00550                 return -1;
00551             h = AV_RB32(buf);
00552             buf += 4;
00553             len -= 4;
00554             if (h & (1 << 26)) {
00555                 /* mpeg2 */
00556                 if (len <= 4)
00557                     return -1;
00558                 buf += 4;
00559                 len -= 4;
00560             }
00561             av_new_packet(pkt, len);
00562             memcpy(pkt->data, buf, len);
00563             break;
00564         default:
00565             av_new_packet(pkt, len);
00566             memcpy(pkt->data, buf, len);
00567             break;
00568         }
00569 
00570         pkt->stream_index = st->index;
00571     }
00572 
00573     // now perform timestamp things....
00574     finalize_packet(s, pkt, timestamp);
00575 
00576     return rv;
00577 }
00578 
00579 void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
00580 {
00581     while (s->queue) {
00582         RTPPacket *next = s->queue->next;
00583         av_free(s->queue->buf);
00584         av_free(s->queue);
00585         s->queue = next;
00586     }
00587     s->seq       = 0;
00588     s->queue_len = 0;
00589     s->prev_ret  = 0;
00590 }
00591 
00592 static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
00593 {
00594     uint16_t seq = AV_RB16(buf + 2);
00595     RTPPacket *cur = s->queue, *prev = NULL, *packet;
00596 
00597     /* Find the correct place in the queue to insert the packet */
00598     while (cur) {
00599         int16_t diff = seq - cur->seq;
00600         if (diff < 0)
00601             break;
00602         prev = cur;
00603         cur = cur->next;
00604     }
00605 
00606     packet = av_mallocz(sizeof(*packet));
00607     if (!packet)
00608         return;
00609     packet->recvtime = av_gettime();
00610     packet->seq = seq;
00611     packet->len = len;
00612     packet->buf = buf;
00613     packet->next = cur;
00614     if (prev)
00615         prev->next = packet;
00616     else
00617         s->queue = packet;
00618     s->queue_len++;
00619 }
00620 
00621 static int has_next_packet(RTPDemuxContext *s)
00622 {
00623     return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
00624 }
00625 
00626 int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
00627 {
00628     return s->queue ? s->queue->recvtime : 0;
00629 }
00630 
00631 static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
00632 {
00633     int rv;
00634     RTPPacket *next;
00635 
00636     if (s->queue_len <= 0)
00637         return -1;
00638 
00639     if (!has_next_packet(s))
00640         av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
00641                "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
00642 
00643     /* Parse the first packet in the queue, and dequeue it */
00644     rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
00645     next = s->queue->next;
00646     av_free(s->queue->buf);
00647     av_free(s->queue);
00648     s->queue = next;
00649     s->queue_len--;
00650     return rv;
00651 }
00652 
00653 static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
00654                      uint8_t **bufptr, int len)
00655 {
00656     uint8_t* buf = bufptr ? *bufptr : NULL;
00657     int ret, flags = 0;
00658     uint32_t timestamp;
00659     int rv= 0;
00660 
00661     if (!buf) {
00662         /* If parsing of the previous packet actually returned 0 or an error,
00663          * there's nothing more to be parsed from that packet, but we may have
00664          * indicated that we can return the next enqueued packet. */
00665         if (s->prev_ret <= 0)
00666             return rtp_parse_queued_packet(s, pkt);
00667         /* return the next packets, if any */
00668         if(s->st && s->parse_packet) {
00669             /* timestamp should be overwritten by parse_packet, if not,
00670              * the packet is left with pts == AV_NOPTS_VALUE */
00671             timestamp = RTP_NOTS_VALUE;
00672             rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
00673                                 s->st, pkt, &timestamp, NULL, 0, flags);
00674             finalize_packet(s, pkt, timestamp);
00675             return rv;
00676         } else {
00677             // TODO: Move to a dynamic packet handler (like above)
00678             if (s->read_buf_index >= s->read_buf_size)
00679                 return AVERROR(EAGAIN);
00680             ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
00681                                       s->read_buf_size - s->read_buf_index);
00682             if (ret < 0)
00683                 return AVERROR(EAGAIN);
00684             s->read_buf_index += ret;
00685             if (s->read_buf_index < s->read_buf_size)
00686                 return 1;
00687             else
00688                 return 0;
00689         }
00690     }
00691 
00692     if (len < 12)
00693         return -1;
00694 
00695     if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
00696         return -1;
00697     if (buf[1] >= RTCP_SR && buf[1] <= RTCP_APP) {
00698         return rtcp_parse_packet(s, buf, len);
00699     }
00700 
00701     if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
00702         /* First packet, or no reordering */
00703         return rtp_parse_packet_internal(s, pkt, buf, len);
00704     } else {
00705         uint16_t seq = AV_RB16(buf + 2);
00706         int16_t diff = seq - s->seq;
00707         if (diff < 0) {
00708             /* Packet older than the previously emitted one, drop */
00709             av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
00710                    "RTP: dropping old packet received too late\n");
00711             return -1;
00712         } else if (diff <= 1) {
00713             /* Correct packet */
00714             rv = rtp_parse_packet_internal(s, pkt, buf, len);
00715             return rv;
00716         } else {
00717             /* Still missing some packet, enqueue this one. */
00718             enqueue_packet(s, buf, len);
00719             *bufptr = NULL;
00720             /* Return the first enqueued packet if the queue is full,
00721              * even if we're missing something */
00722             if (s->queue_len >= s->queue_size)
00723                 return rtp_parse_queued_packet(s, pkt);
00724             return -1;
00725         }
00726     }
00727 }
00728 
00738 int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
00739                         uint8_t **bufptr, int len)
00740 {
00741     int rv = rtp_parse_one_packet(s, pkt, bufptr, len);
00742     s->prev_ret = rv;
00743     while (rv == AVERROR(EAGAIN) && has_next_packet(s))
00744         rv = rtp_parse_queued_packet(s, pkt);
00745     return rv ? rv : has_next_packet(s);
00746 }
00747 
00748 void ff_rtp_parse_close(RTPDemuxContext *s)
00749 {
00750     ff_rtp_reset_packet_queue(s);
00751     if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
00752         ff_mpegts_parse_close(s->ts);
00753     }
00754     av_free(s);
00755 }
00756 
00757 int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
00758                   int (*parse_fmtp)(AVStream *stream,
00759                                     PayloadContext *data,
00760                                     char *attr, char *value))
00761 {
00762     char attr[256];
00763     char *value;
00764     int res;
00765     int value_size = strlen(p) + 1;
00766 
00767     if (!(value = av_malloc(value_size))) {
00768         av_log(stream, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
00769         return AVERROR(ENOMEM);
00770     }
00771 
00772     // remove protocol identifier
00773     while (*p && *p == ' ') p++; // strip spaces
00774     while (*p && *p != ' ') p++; // eat protocol identifier
00775     while (*p && *p == ' ') p++; // strip trailing spaces
00776 
00777     while (ff_rtsp_next_attr_and_value(&p,
00778                                        attr, sizeof(attr),
00779                                        value, value_size)) {
00780 
00781         res = parse_fmtp(stream, data, attr, value);
00782         if (res < 0 && res != AVERROR_PATCHWELCOME) {
00783             av_free(value);
00784             return res;
00785         }
00786     }
00787     av_free(value);
00788     return 0;
00789 }