OSDN Git Service

Add RTP depacketization of the X-QT QuickTime format
[android-x86/external-ffmpeg.git] / libavformat / rtpdec.c
1 /*
2  * RTP input format
3  * Copyright (c) 2002 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg 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 GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /* needed for gethostname() */
23 #define _XOPEN_SOURCE 600
24
25 #include "libavcodec/get_bits.h"
26 #include "avformat.h"
27 #include "mpegts.h"
28
29 #include <unistd.h>
30 #include "network.h"
31
32 #include "rtpdec.h"
33 #include "rtpdec_formats.h"
34
35 //#define DEBUG
36
37 /* TODO: - add RTCP statistics reporting (should be optional).
38
39          - add support for h263/mpeg4 packetized output : IDEA: send a
40          buffer to 'rtp_write_packet' contains all the packets for ONE
41          frame. Each packet should have a four byte header containing
42          the length in big endian format (same trick as
43          'url_open_dyn_packet_buf')
44 */
45
46 /* statistics functions */
47 RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
48
49 void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
50 {
51     handler->next= RTPFirstDynamicPayloadHandler;
52     RTPFirstDynamicPayloadHandler= handler;
53 }
54
55 void av_register_rtp_dynamic_payload_handlers(void)
56 {
57     ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
58     ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
59     ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
60     ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
61     ff_register_dynamic_payload_handler(&ff_h263_1998_dynamic_handler);
62     ff_register_dynamic_payload_handler(&ff_h263_2000_dynamic_handler);
63     ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
64     ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
65     ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
66     ff_register_dynamic_payload_handler(&ff_qdm2_dynamic_handler);
67     ff_register_dynamic_payload_handler(&ff_svq3_dynamic_handler);
68     ff_register_dynamic_payload_handler(&ff_mp4a_latm_dynamic_handler);
69     ff_register_dynamic_payload_handler(&ff_vp8_dynamic_handler);
70
71     ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
72     ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
73
74     ff_register_dynamic_payload_handler(&ff_qt_rtp_aud_handler);
75     ff_register_dynamic_payload_handler(&ff_qt_rtp_vid_handler);
76     ff_register_dynamic_payload_handler(&ff_quicktime_rtp_aud_handler);
77     ff_register_dynamic_payload_handler(&ff_quicktime_rtp_vid_handler);
78 }
79
80 static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
81 {
82     int payload_len;
83     while (len >= 2) {
84         switch (buf[1]) {
85         case RTCP_SR:
86             if (len < 16) {
87                 av_log(NULL, AV_LOG_ERROR, "Invalid length for RTCP SR packet\n");
88                 return AVERROR_INVALIDDATA;
89             }
90             payload_len = (AV_RB16(buf + 2) + 1) * 4;
91
92             s->last_rtcp_ntp_time = AV_RB64(buf + 8);
93             if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE)
94                 s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
95             s->last_rtcp_timestamp = AV_RB32(buf + 16);
96
97             buf += payload_len;
98             len -= payload_len;
99             break;
100         case RTCP_BYE:
101             return -RTCP_BYE;
102         default:
103             return -1;
104         }
105     }
106     return -1;
107 }
108
109 #define RTP_SEQ_MOD (1<<16)
110
111 /**
112 * called on parse open packet
113 */
114 static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence) // called on parse open packet.
115 {
116     memset(s, 0, sizeof(RTPStatistics));
117     s->max_seq= base_sequence;
118     s->probation= 1;
119 }
120
121 /**
122 * called whenever there is a large jump in sequence numbers, or when they get out of probation...
123 */
124 static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
125 {
126     s->max_seq= seq;
127     s->cycles= 0;
128     s->base_seq= seq -1;
129     s->bad_seq= RTP_SEQ_MOD + 1;
130     s->received= 0;
131     s->expected_prior= 0;
132     s->received_prior= 0;
133     s->jitter= 0;
134     s->transit= 0;
135 }
136
137 /**
138 * returns 1 if we should handle this packet.
139 */
140 static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
141 {
142     uint16_t udelta= seq - s->max_seq;
143     const int MAX_DROPOUT= 3000;
144     const int MAX_MISORDER = 100;
145     const int MIN_SEQUENTIAL = 2;
146
147     /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
148     if(s->probation)
149     {
150         if(seq==s->max_seq + 1) {
151             s->probation--;
152             s->max_seq= seq;
153             if(s->probation==0) {
154                 rtp_init_sequence(s, seq);
155                 s->received++;
156                 return 1;
157             }
158         } else {
159             s->probation= MIN_SEQUENTIAL - 1;
160             s->max_seq = seq;
161         }
162     } else if (udelta < MAX_DROPOUT) {
163         // in order, with permissible gap
164         if(seq < s->max_seq) {
165             //sequence number wrapped; count antother 64k cycles
166             s->cycles += RTP_SEQ_MOD;
167         }
168         s->max_seq= seq;
169     } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
170         // sequence made a large jump...
171         if(seq==s->bad_seq) {
172             // two sequential packets-- assume that the other side restarted without telling us; just resync.
173             rtp_init_sequence(s, seq);
174         } else {
175             s->bad_seq= (seq + 1) & (RTP_SEQ_MOD-1);
176             return 0;
177         }
178     } else {
179         // duplicate or reordered packet...
180     }
181     s->received++;
182     return 1;
183 }
184
185 #if 0
186 /**
187 * This function is currently unused; without a valid local ntp time, I don't see how we could calculate the
188 * difference between the arrival and sent timestamp.  As a result, the jitter and transit statistics values
189 * never change.  I left this in in case someone else can see a way. (rdm)
190 */
191 static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp, uint32_t arrival_timestamp)
192 {
193     uint32_t transit= arrival_timestamp - sent_timestamp;
194     int d;
195     s->transit= transit;
196     d= FFABS(transit - s->transit);
197     s->jitter += d - ((s->jitter + 8)>>4);
198 }
199 #endif
200
201 int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
202 {
203     ByteIOContext *pb;
204     uint8_t *buf;
205     int len;
206     int rtcp_bytes;
207     RTPStatistics *stats= &s->statistics;
208     uint32_t lost;
209     uint32_t extended_max;
210     uint32_t expected_interval;
211     uint32_t received_interval;
212     uint32_t lost_interval;
213     uint32_t expected;
214     uint32_t fraction;
215     uint64_t ntp_time= s->last_rtcp_ntp_time; // TODO: Get local ntp time?
216
217     if (!s->rtp_ctx || (count < 1))
218         return -1;
219
220     /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
221     /* XXX: mpeg pts hardcoded. RTCP send every 0.5 seconds */
222     s->octet_count += count;
223     rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
224         RTCP_TX_RATIO_DEN;
225     rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
226     if (rtcp_bytes < 28)
227         return -1;
228     s->last_octet_count = s->octet_count;
229
230     if (url_open_dyn_buf(&pb) < 0)
231         return -1;
232
233     // Receiver Report
234     put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
235     put_byte(pb, RTCP_RR);
236     put_be16(pb, 7); /* length in words - 1 */
237     // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
238     put_be32(pb, s->ssrc + 1);
239     put_be32(pb, s->ssrc); // server SSRC
240     // some placeholders we should really fill...
241     // RFC 1889/p64
242     extended_max= stats->cycles + stats->max_seq;
243     expected= extended_max - stats->base_seq + 1;
244     lost= expected - stats->received;
245     lost= FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
246     expected_interval= expected - stats->expected_prior;
247     stats->expected_prior= expected;
248     received_interval= stats->received - stats->received_prior;
249     stats->received_prior= stats->received;
250     lost_interval= expected_interval - received_interval;
251     if (expected_interval==0 || lost_interval<=0) fraction= 0;
252     else fraction = (lost_interval<<8)/expected_interval;
253
254     fraction= (fraction<<24) | lost;
255
256     put_be32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
257     put_be32(pb, extended_max); /* max sequence received */
258     put_be32(pb, stats->jitter>>4); /* jitter */
259
260     if(s->last_rtcp_ntp_time==AV_NOPTS_VALUE)
261     {
262         put_be32(pb, 0); /* last SR timestamp */
263         put_be32(pb, 0); /* delay since last SR */
264     } else {
265         uint32_t middle_32_bits= s->last_rtcp_ntp_time>>16; // this is valid, right? do we need to handle 64 bit values special?
266         uint32_t delay_since_last= ntp_time - s->last_rtcp_ntp_time;
267
268         put_be32(pb, middle_32_bits); /* last SR timestamp */
269         put_be32(pb, delay_since_last); /* delay since last SR */
270     }
271
272     // CNAME
273     put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
274     put_byte(pb, RTCP_SDES);
275     len = strlen(s->hostname);
276     put_be16(pb, (6 + len + 3) / 4); /* length in words - 1 */
277     put_be32(pb, s->ssrc);
278     put_byte(pb, 0x01);
279     put_byte(pb, len);
280     put_buffer(pb, s->hostname, len);
281     // padding
282     for (len = (6 + len) % 4; len % 4; len++) {
283         put_byte(pb, 0);
284     }
285
286     put_flush_packet(pb);
287     len = url_close_dyn_buf(pb, &buf);
288     if ((len > 0) && buf) {
289         int result;
290         dprintf(s->ic, "sending %d bytes of RR\n", len);
291         result= url_write(s->rtp_ctx, buf, len);
292         dprintf(s->ic, "result from url_write: %d\n", result);
293         av_free(buf);
294     }
295     return 0;
296 }
297
298 void rtp_send_punch_packets(URLContext* rtp_handle)
299 {
300     ByteIOContext *pb;
301     uint8_t *buf;
302     int len;
303
304     /* Send a small RTP packet */
305     if (url_open_dyn_buf(&pb) < 0)
306         return;
307
308     put_byte(pb, (RTP_VERSION << 6));
309     put_byte(pb, 0); /* Payload type */
310     put_be16(pb, 0); /* Seq */
311     put_be32(pb, 0); /* Timestamp */
312     put_be32(pb, 0); /* SSRC */
313
314     put_flush_packet(pb);
315     len = url_close_dyn_buf(pb, &buf);
316     if ((len > 0) && buf)
317         url_write(rtp_handle, buf, len);
318     av_free(buf);
319
320     /* Send a minimal RTCP RR */
321     if (url_open_dyn_buf(&pb) < 0)
322         return;
323
324     put_byte(pb, (RTP_VERSION << 6));
325     put_byte(pb, RTCP_RR); /* receiver report */
326     put_be16(pb, 1); /* length in words - 1 */
327     put_be32(pb, 0); /* our own SSRC */
328
329     put_flush_packet(pb);
330     len = url_close_dyn_buf(pb, &buf);
331     if ((len > 0) && buf)
332         url_write(rtp_handle, buf, len);
333     av_free(buf);
334 }
335
336
337 /**
338  * open a new RTP parse context for stream 'st'. 'st' can be NULL for
339  * MPEG2TS streams to indicate that they should be demuxed inside the
340  * rtp demux (otherwise CODEC_ID_MPEG2TS packets are returned)
341  */
342 RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, int queue_size)
343 {
344     RTPDemuxContext *s;
345
346     s = av_mallocz(sizeof(RTPDemuxContext));
347     if (!s)
348         return NULL;
349     s->payload_type = payload_type;
350     s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
351     s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
352     s->ic = s1;
353     s->st = st;
354     s->queue_size = queue_size;
355     rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
356     if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
357         s->ts = ff_mpegts_parse_open(s->ic);
358         if (s->ts == NULL) {
359             av_free(s);
360             return NULL;
361         }
362     } else {
363         av_set_pts_info(st, 32, 1, 90000);
364         switch(st->codec->codec_id) {
365         case CODEC_ID_MPEG1VIDEO:
366         case CODEC_ID_MPEG2VIDEO:
367         case CODEC_ID_MP2:
368         case CODEC_ID_MP3:
369         case CODEC_ID_MPEG4:
370         case CODEC_ID_H263:
371         case CODEC_ID_H264:
372             st->need_parsing = AVSTREAM_PARSE_FULL;
373             break;
374         case CODEC_ID_ADPCM_G722:
375             av_set_pts_info(st, 32, 1, st->codec->sample_rate);
376             /* According to RFC 3551, the stream clock rate is 8000
377              * even if the sample rate is 16000. */
378             if (st->codec->sample_rate == 8000)
379                 st->codec->sample_rate = 16000;
380             break;
381         default:
382             if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
383                 av_set_pts_info(st, 32, 1, st->codec->sample_rate);
384             }
385             break;
386         }
387     }
388     // needed to send back RTCP RR in RTSP sessions
389     s->rtp_ctx = rtpc;
390     gethostname(s->hostname, sizeof(s->hostname));
391     return s;
392 }
393
394 void
395 rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
396                                RTPDynamicProtocolHandler *handler)
397 {
398     s->dynamic_protocol_context = ctx;
399     s->parse_packet = handler->parse_packet;
400 }
401
402 /**
403  * This was the second switch in rtp_parse packet.  Normalizes time, if required, sets stream_index, etc.
404  */
405 static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
406 {
407     if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && timestamp != RTP_NOTS_VALUE) {
408         int64_t addend;
409         int delta_timestamp;
410
411         /* compute pts from timestamp with received ntp_time */
412         delta_timestamp = timestamp - s->last_rtcp_timestamp;
413         /* convert to the PTS timebase */
414         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);
415         pkt->pts = s->range_start_offset + addend + delta_timestamp;
416     }
417 }
418
419 static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
420                                      const uint8_t *buf, int len)
421 {
422     unsigned int ssrc, h;
423     int payload_type, seq, ret, flags = 0;
424     AVStream *st;
425     uint32_t timestamp;
426     int rv= 0;
427
428     payload_type = buf[1] & 0x7f;
429     if (buf[1] & 0x80)
430         flags |= RTP_FLAG_MARKER;
431     seq  = AV_RB16(buf + 2);
432     timestamp = AV_RB32(buf + 4);
433     ssrc = AV_RB32(buf + 8);
434     /* store the ssrc in the RTPDemuxContext */
435     s->ssrc = ssrc;
436
437     /* NOTE: we can handle only one payload type */
438     if (s->payload_type != payload_type)
439         return -1;
440
441     st = s->st;
442     // only do something with this if all the rtp checks pass...
443     if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
444     {
445         av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
446                payload_type, seq, ((s->seq + 1) & 0xffff));
447         return -1;
448     }
449
450     s->seq = seq;
451     len -= 12;
452     buf += 12;
453
454     if (!st) {
455         /* specific MPEG2TS demux support */
456         ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
457         if (ret < 0)
458             return -1;
459         if (ret < len) {
460             s->read_buf_size = len - ret;
461             memcpy(s->buf, buf + ret, s->read_buf_size);
462             s->read_buf_index = 0;
463             return 1;
464         }
465         return 0;
466     } else if (s->parse_packet) {
467         rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
468                              s->st, pkt, &timestamp, buf, len, flags);
469     } else {
470         // at this point, the RTP header has been stripped;  This is ASSUMING that there is only 1 CSRC, which in't wise.
471         switch(st->codec->codec_id) {
472         case CODEC_ID_MP2:
473         case CODEC_ID_MP3:
474             /* better than nothing: skip mpeg audio RTP header */
475             if (len <= 4)
476                 return -1;
477             h = AV_RB32(buf);
478             len -= 4;
479             buf += 4;
480             av_new_packet(pkt, len);
481             memcpy(pkt->data, buf, len);
482             break;
483         case CODEC_ID_MPEG1VIDEO:
484         case CODEC_ID_MPEG2VIDEO:
485             /* better than nothing: skip mpeg video RTP header */
486             if (len <= 4)
487                 return -1;
488             h = AV_RB32(buf);
489             buf += 4;
490             len -= 4;
491             if (h & (1 << 26)) {
492                 /* mpeg2 */
493                 if (len <= 4)
494                     return -1;
495                 buf += 4;
496                 len -= 4;
497             }
498             av_new_packet(pkt, len);
499             memcpy(pkt->data, buf, len);
500             break;
501         default:
502             av_new_packet(pkt, len);
503             memcpy(pkt->data, buf, len);
504             break;
505         }
506
507         pkt->stream_index = st->index;
508     }
509
510     // now perform timestamp things....
511     finalize_packet(s, pkt, timestamp);
512
513     s->prev_ret = rv;
514     return rv;
515 }
516
517 void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
518 {
519     while (s->queue) {
520         RTPPacket *next = s->queue->next;
521         av_free(s->queue->buf);
522         av_free(s->queue);
523         s->queue = next;
524     }
525     s->seq       = 0;
526     s->queue_len = 0;
527     s->prev_ret  = 0;
528 }
529
530 static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
531 {
532     uint16_t seq = AV_RB16(buf + 2);
533     RTPPacket *cur = s->queue, *prev = NULL, *packet;
534
535     /* Find the correct place in the queue to insert the packet */
536     while (cur) {
537         int16_t diff = seq - cur->seq;
538         if (diff < 0)
539             break;
540         prev = cur;
541         cur = cur->next;
542     }
543
544     packet = av_mallocz(sizeof(*packet));
545     if (!packet)
546         return;
547     packet->recvtime = av_gettime();
548     packet->seq = seq;
549     packet->len = len;
550     packet->buf = buf;
551     packet->next = cur;
552     if (prev)
553         prev->next = packet;
554     else
555         s->queue = packet;
556     s->queue_len++;
557 }
558
559 static int has_next_packet(RTPDemuxContext *s)
560 {
561     return s->queue && s->queue->seq == s->seq + 1;
562 }
563
564 int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
565 {
566     return s->queue ? s->queue->recvtime : 0;
567 }
568
569 static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
570 {
571     int rv;
572     RTPPacket *next;
573
574     if (s->queue_len <= 0)
575         return -1;
576
577     if (!has_next_packet(s))
578         av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
579                "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
580
581     /* Parse the first packet in the queue, and dequeue it */
582     rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
583     next = s->queue->next;
584     av_free(s->queue->buf);
585     av_free(s->queue);
586     s->queue = next;
587     s->queue_len--;
588     return rv ? rv : has_next_packet(s);
589 }
590
591 /**
592  * Parse an RTP or RTCP packet directly sent as a buffer.
593  * @param s RTP parse context.
594  * @param pkt returned packet
595  * @param bufptr pointer to the input buffer or NULL to read the next packets
596  * @param len buffer len
597  * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
598  * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
599  */
600 int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
601                      uint8_t **bufptr, int len)
602 {
603     uint8_t* buf = bufptr ? *bufptr : NULL;
604     int ret, flags = 0;
605     uint32_t timestamp;
606     int rv= 0;
607
608     if (!buf) {
609         /* If parsing of the previous packet actually returned 0, there's
610          * nothing more to be parsed from that packet, but we may have
611          * indicated that we can return the next enqueued packet. */
612         if (!s->prev_ret)
613             return rtp_parse_queued_packet(s, pkt);
614         /* return the next packets, if any */
615         if(s->st && s->parse_packet) {
616             /* timestamp should be overwritten by parse_packet, if not,
617              * the packet is left with pts == AV_NOPTS_VALUE */
618             timestamp = RTP_NOTS_VALUE;
619             rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
620                                 s->st, pkt, &timestamp, NULL, 0, flags);
621             finalize_packet(s, pkt, timestamp);
622             s->prev_ret = rv;
623             return rv ? rv : has_next_packet(s);
624         } else {
625             // TODO: Move to a dynamic packet handler (like above)
626             if (s->read_buf_index >= s->read_buf_size)
627                 return -1;
628             ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
629                                       s->read_buf_size - s->read_buf_index);
630             if (ret < 0)
631                 return -1;
632             s->read_buf_index += ret;
633             if (s->read_buf_index < s->read_buf_size)
634                 return 1;
635             else {
636                 s->prev_ret = 0;
637                 return has_next_packet(s);
638             }
639         }
640     }
641
642     if (len < 12)
643         return -1;
644
645     if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
646         return -1;
647     if (buf[1] >= RTCP_SR && buf[1] <= RTCP_APP) {
648         return rtcp_parse_packet(s, buf, len);
649     }
650
651     if (s->seq == 0 || s->queue_size <= 1) {
652         /* First packet, or no reordering */
653         return rtp_parse_packet_internal(s, pkt, buf, len);
654     } else {
655         uint16_t seq = AV_RB16(buf + 2);
656         int16_t diff = seq - s->seq;
657         if (diff < 0) {
658             /* Packet older than the previously emitted one, drop */
659             av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
660                    "RTP: dropping old packet received too late\n");
661             return -1;
662         } else if (diff <= 1) {
663             /* Correct packet */
664             rv = rtp_parse_packet_internal(s, pkt, buf, len);
665             return rv ? rv : has_next_packet(s);
666         } else {
667             /* Still missing some packet, enqueue this one. */
668             enqueue_packet(s, buf, len);
669             *bufptr = NULL;
670             /* Return the first enqueued packet if the queue is full,
671              * even if we're missing something */
672             if (s->queue_len >= s->queue_size)
673                 return rtp_parse_queued_packet(s, pkt);
674             return -1;
675         }
676     }
677 }
678
679 void rtp_parse_close(RTPDemuxContext *s)
680 {
681     ff_rtp_reset_packet_queue(s);
682     if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
683         ff_mpegts_parse_close(s->ts);
684     }
685     av_free(s);
686 }
687
688 int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
689                   int (*parse_fmtp)(AVStream *stream,
690                                     PayloadContext *data,
691                                     char *attr, char *value))
692 {
693     char attr[256];
694     char *value;
695     int res;
696     int value_size = strlen(p) + 1;
697
698     if (!(value = av_malloc(value_size))) {
699         av_log(stream, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
700         return AVERROR(ENOMEM);
701     }
702
703     // remove protocol identifier
704     while (*p && *p == ' ') p++; // strip spaces
705     while (*p && *p != ' ') p++; // eat protocol identifier
706     while (*p && *p == ' ') p++; // strip trailing spaces
707
708     while (ff_rtsp_next_attr_and_value(&p,
709                                        attr, sizeof(attr),
710                                        value, value_size)) {
711
712         res = parse_fmtp(stream, data, attr, value);
713         if (res < 0 && res != AVERROR_PATCHWELCOME) {
714             av_free(value);
715             return res;
716         }
717     }
718     av_free(value);
719     return 0;
720 }