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