OSDN Git Service

rtpdec: K&R formatting and spelling cosmetics
[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 Libav.
6  *
7  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/mathematics.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/time.h"
25 #include "libavcodec/get_bits.h"
26 #include "avformat.h"
27 #include "mpegts.h"
28 #include "network.h"
29 #include "url.h"
30 #include "rtpdec.h"
31 #include "rtpdec_formats.h"
32
33 /* TODO:
34  * - add RTCP statistics reporting (should be optional).
35  *
36  * - add support for H.263/MPEG-4 packetized output: IDEA: send a
37  * buffer to 'rtp_write_packet' contains all the packets for ONE
38  * frame. Each packet should have a four byte header containing
39  * the length in big-endian format (same trick as
40  * 'ffio_open_dyn_packet_buf').
41  */
42
43 static RTPDynamicProtocolHandler realmedia_mp3_dynamic_handler = {
44     .enc_name   = "X-MP3-draft-00",
45     .codec_type = AVMEDIA_TYPE_AUDIO,
46     .codec_id   = AV_CODEC_ID_MP3ADU,
47 };
48
49 static RTPDynamicProtocolHandler speex_dynamic_handler = {
50     .enc_name   = "speex",
51     .codec_type = AVMEDIA_TYPE_AUDIO,
52     .codec_id   = AV_CODEC_ID_SPEEX,
53 };
54
55 static RTPDynamicProtocolHandler opus_dynamic_handler = {
56     .enc_name   = "opus",
57     .codec_type = AVMEDIA_TYPE_AUDIO,
58     .codec_id   = AV_CODEC_ID_OPUS,
59 };
60
61 /* statistics functions */
62 static RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler = NULL;
63
64 void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
65 {
66     handler->next = RTPFirstDynamicPayloadHandler;
67     RTPFirstDynamicPayloadHandler = handler;
68 }
69
70 void av_register_rtp_dynamic_payload_handlers(void)
71 {
72     ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
73     ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
74     ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
75     ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
76     ff_register_dynamic_payload_handler(&ff_h263_1998_dynamic_handler);
77     ff_register_dynamic_payload_handler(&ff_h263_2000_dynamic_handler);
78     ff_register_dynamic_payload_handler(&ff_h263_rfc2190_dynamic_handler);
79     ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
80     ff_register_dynamic_payload_handler(&ff_ilbc_dynamic_handler);
81     ff_register_dynamic_payload_handler(&ff_jpeg_dynamic_handler);
82     ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
83     ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
84     ff_register_dynamic_payload_handler(&ff_qdm2_dynamic_handler);
85     ff_register_dynamic_payload_handler(&ff_svq3_dynamic_handler);
86     ff_register_dynamic_payload_handler(&ff_mp4a_latm_dynamic_handler);
87     ff_register_dynamic_payload_handler(&ff_vp8_dynamic_handler);
88     ff_register_dynamic_payload_handler(&ff_qcelp_dynamic_handler);
89     ff_register_dynamic_payload_handler(&realmedia_mp3_dynamic_handler);
90     ff_register_dynamic_payload_handler(&speex_dynamic_handler);
91     ff_register_dynamic_payload_handler(&opus_dynamic_handler);
92
93     ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
94     ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
95
96     ff_register_dynamic_payload_handler(&ff_qt_rtp_aud_handler);
97     ff_register_dynamic_payload_handler(&ff_qt_rtp_vid_handler);
98     ff_register_dynamic_payload_handler(&ff_quicktime_rtp_aud_handler);
99     ff_register_dynamic_payload_handler(&ff_quicktime_rtp_vid_handler);
100
101     ff_register_dynamic_payload_handler(&ff_g726_16_dynamic_handler);
102     ff_register_dynamic_payload_handler(&ff_g726_24_dynamic_handler);
103     ff_register_dynamic_payload_handler(&ff_g726_32_dynamic_handler);
104     ff_register_dynamic_payload_handler(&ff_g726_40_dynamic_handler);
105 }
106
107 RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
108                                                        enum AVMediaType codec_type)
109 {
110     RTPDynamicProtocolHandler *handler;
111     for (handler = RTPFirstDynamicPayloadHandler;
112          handler; handler = handler->next)
113         if (!av_strcasecmp(name, handler->enc_name) &&
114             codec_type == handler->codec_type)
115             return handler;
116     return NULL;
117 }
118
119 RTPDynamicProtocolHandler *ff_rtp_handler_find_by_id(int id,
120                                                      enum AVMediaType codec_type)
121 {
122     RTPDynamicProtocolHandler *handler;
123     for (handler = RTPFirstDynamicPayloadHandler;
124          handler; handler = handler->next)
125         if (handler->static_payload_id && handler->static_payload_id == id &&
126             codec_type == handler->codec_type)
127             return handler;
128     return NULL;
129 }
130
131 static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf,
132                              int len)
133 {
134     int payload_len;
135     while (len >= 4) {
136         payload_len = FFMIN(len, (AV_RB16(buf + 2) + 1) * 4);
137
138         switch (buf[1]) {
139         case RTCP_SR:
140             if (payload_len < 20) {
141                 av_log(NULL, AV_LOG_ERROR,
142                        "Invalid length for RTCP SR packet\n");
143                 return AVERROR_INVALIDDATA;
144             }
145
146             s->last_rtcp_ntp_time  = AV_RB64(buf + 8);
147             s->last_rtcp_timestamp = AV_RB32(buf + 16);
148             if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
149                 s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
150                 if (!s->base_timestamp)
151                     s->base_timestamp = s->last_rtcp_timestamp;
152                 s->rtcp_ts_offset = s->last_rtcp_timestamp - s->base_timestamp;
153             }
154
155             break;
156         case RTCP_BYE:
157             return -RTCP_BYE;
158         }
159
160         buf += payload_len;
161         len -= payload_len;
162     }
163     return -1;
164 }
165
166 #define RTP_SEQ_MOD (1 << 16)
167
168 static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
169 {
170     memset(s, 0, sizeof(RTPStatistics));
171     s->max_seq   = base_sequence;
172     s->probation = 1;
173 }
174
175 /*
176  * Called whenever there is a large jump in sequence numbers,
177  * or when they get out of probation...
178  */
179 static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
180 {
181     s->max_seq        = seq;
182     s->cycles         = 0;
183     s->base_seq       = seq - 1;
184     s->bad_seq        = RTP_SEQ_MOD + 1;
185     s->received       = 0;
186     s->expected_prior = 0;
187     s->received_prior = 0;
188     s->jitter         = 0;
189     s->transit        = 0;
190 }
191
192 /* Returns 1 if we should handle this packet. */
193 static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
194 {
195     uint16_t udelta = seq - s->max_seq;
196     const int MAX_DROPOUT    = 3000;
197     const int MAX_MISORDER   = 100;
198     const int MIN_SEQUENTIAL = 2;
199
200     /* source not valid until MIN_SEQUENTIAL packets with sequence
201      * seq. numbers have been received */
202     if (s->probation) {
203         if (seq == s->max_seq + 1) {
204             s->probation--;
205             s->max_seq = seq;
206             if (s->probation == 0) {
207                 rtp_init_sequence(s, seq);
208                 s->received++;
209                 return 1;
210             }
211         } else {
212             s->probation = MIN_SEQUENTIAL - 1;
213             s->max_seq   = seq;
214         }
215     } else if (udelta < MAX_DROPOUT) {
216         // in order, with permissible gap
217         if (seq < s->max_seq) {
218             // sequence number wrapped; count another 64k cycles
219             s->cycles += RTP_SEQ_MOD;
220         }
221         s->max_seq = seq;
222     } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
223         // sequence made a large jump...
224         if (seq == s->bad_seq) {
225             /* two sequential packets -- assume that the other side
226              * restarted without telling us; just resync. */
227             rtp_init_sequence(s, seq);
228         } else {
229             s->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1);
230             return 0;
231         }
232     } else {
233         // duplicate or reordered packet...
234     }
235     s->received++;
236     return 1;
237 }
238
239 int ff_rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
240 {
241     AVIOContext *pb;
242     uint8_t *buf;
243     int len;
244     int rtcp_bytes;
245     RTPStatistics *stats = &s->statistics;
246     uint32_t lost;
247     uint32_t extended_max;
248     uint32_t expected_interval;
249     uint32_t received_interval;
250     uint32_t lost_interval;
251     uint32_t expected;
252     uint32_t fraction;
253     uint64_t ntp_time = s->last_rtcp_ntp_time; // TODO: Get local ntp time?
254
255     if (!s->rtp_ctx || (count < 1))
256         return -1;
257
258     /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
259     /* XXX: MPEG pts hardcoded. RTCP send every 0.5 seconds */
260     s->octet_count += count;
261     rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
262         RTCP_TX_RATIO_DEN;
263     rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
264     if (rtcp_bytes < 28)
265         return -1;
266     s->last_octet_count = s->octet_count;
267
268     if (avio_open_dyn_buf(&pb) < 0)
269         return -1;
270
271     // Receiver Report
272     avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
273     avio_w8(pb, RTCP_RR);
274     avio_wb16(pb, 7); /* length in words - 1 */
275     // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
276     avio_wb32(pb, s->ssrc + 1);
277     avio_wb32(pb, s->ssrc); // server SSRC
278     // some placeholders we should really fill...
279     // RFC 1889/p64
280     extended_max          = stats->cycles + stats->max_seq;
281     expected              = extended_max - stats->base_seq + 1;
282     lost                  = expected - stats->received;
283     lost                  = FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
284     expected_interval     = expected - stats->expected_prior;
285     stats->expected_prior = expected;
286     received_interval     = stats->received - stats->received_prior;
287     stats->received_prior = stats->received;
288     lost_interval         = expected_interval - received_interval;
289     if (expected_interval == 0 || lost_interval <= 0)
290         fraction = 0;
291     else
292         fraction = (lost_interval << 8) / expected_interval;
293
294     fraction = (fraction << 24) | lost;
295
296     avio_wb32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
297     avio_wb32(pb, extended_max); /* max sequence received */
298     avio_wb32(pb, stats->jitter >> 4); /* jitter */
299
300     if (s->last_rtcp_ntp_time == AV_NOPTS_VALUE) {
301         avio_wb32(pb, 0); /* last SR timestamp */
302         avio_wb32(pb, 0); /* delay since last SR */
303     } else {
304         uint32_t middle_32_bits   = s->last_rtcp_ntp_time >> 16; // this is valid, right? do we need to handle 64 bit values special?
305         uint32_t delay_since_last = ntp_time - s->last_rtcp_ntp_time;
306
307         avio_wb32(pb, middle_32_bits); /* last SR timestamp */
308         avio_wb32(pb, delay_since_last); /* delay since last SR */
309     }
310
311     // CNAME
312     avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
313     avio_w8(pb, RTCP_SDES);
314     len = strlen(s->hostname);
315     avio_wb16(pb, (6 + len + 3) / 4); /* length in words - 1 */
316     avio_wb32(pb, s->ssrc + 1);
317     avio_w8(pb, 0x01);
318     avio_w8(pb, len);
319     avio_write(pb, s->hostname, len);
320     // padding
321     for (len = (6 + len) % 4; len % 4; len++)
322         avio_w8(pb, 0);
323
324     avio_flush(pb);
325     len = avio_close_dyn_buf(pb, &buf);
326     if ((len > 0) && buf) {
327         int av_unused result;
328         av_dlog(s->ic, "sending %d bytes of RR\n", len);
329         result = ffurl_write(s->rtp_ctx, buf, len);
330         av_dlog(s->ic, "result from ffurl_write: %d\n", result);
331         av_free(buf);
332     }
333     return 0;
334 }
335
336 void ff_rtp_send_punch_packets(URLContext *rtp_handle)
337 {
338     AVIOContext *pb;
339     uint8_t *buf;
340     int len;
341
342     /* Send a small RTP packet */
343     if (avio_open_dyn_buf(&pb) < 0)
344         return;
345
346     avio_w8(pb, (RTP_VERSION << 6));
347     avio_w8(pb, 0); /* Payload type */
348     avio_wb16(pb, 0); /* Seq */
349     avio_wb32(pb, 0); /* Timestamp */
350     avio_wb32(pb, 0); /* SSRC */
351
352     avio_flush(pb);
353     len = avio_close_dyn_buf(pb, &buf);
354     if ((len > 0) && buf)
355         ffurl_write(rtp_handle, buf, len);
356     av_free(buf);
357
358     /* Send a minimal RTCP RR */
359     if (avio_open_dyn_buf(&pb) < 0)
360         return;
361
362     avio_w8(pb, (RTP_VERSION << 6));
363     avio_w8(pb, RTCP_RR); /* receiver report */
364     avio_wb16(pb, 1); /* length in words - 1 */
365     avio_wb32(pb, 0); /* our own SSRC */
366
367     avio_flush(pb);
368     len = avio_close_dyn_buf(pb, &buf);
369     if ((len > 0) && buf)
370         ffurl_write(rtp_handle, buf, len);
371     av_free(buf);
372 }
373
374 /**
375  * open a new RTP parse context for stream 'st'. 'st' can be NULL for
376  * MPEG2-TS streams to indicate that they should be demuxed inside the
377  * rtp demux (otherwise AV_CODEC_ID_MPEG2TS packets are returned)
378  */
379 RTPDemuxContext *ff_rtp_parse_open(AVFormatContext *s1, AVStream *st,
380                                    URLContext *rtpc, int payload_type,
381                                    int queue_size)
382 {
383     RTPDemuxContext *s;
384
385     s = av_mallocz(sizeof(RTPDemuxContext));
386     if (!s)
387         return NULL;
388     s->payload_type        = payload_type;
389     s->last_rtcp_ntp_time  = AV_NOPTS_VALUE;
390     s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
391     s->ic                  = s1;
392     s->st                  = st;
393     s->queue_size          = queue_size;
394     rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
395     if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
396         s->ts = ff_mpegts_parse_open(s->ic);
397         if (s->ts == NULL) {
398             av_free(s);
399             return NULL;
400         }
401     } else if (st) {
402         switch (st->codec->codec_id) {
403         case AV_CODEC_ID_MPEG1VIDEO:
404         case AV_CODEC_ID_MPEG2VIDEO:
405         case AV_CODEC_ID_MP2:
406         case AV_CODEC_ID_MP3:
407         case AV_CODEC_ID_MPEG4:
408         case AV_CODEC_ID_H263:
409         case AV_CODEC_ID_H264:
410             st->need_parsing = AVSTREAM_PARSE_FULL;
411             break;
412         case AV_CODEC_ID_VORBIS:
413             st->need_parsing = AVSTREAM_PARSE_HEADERS;
414             break;
415         case AV_CODEC_ID_ADPCM_G722:
416             /* According to RFC 3551, the stream clock rate is 8000
417              * even if the sample rate is 16000. */
418             if (st->codec->sample_rate == 8000)
419                 st->codec->sample_rate = 16000;
420             break;
421         default:
422             break;
423         }
424     }
425     // needed to send back RTCP RR in RTSP sessions
426     s->rtp_ctx = rtpc;
427     gethostname(s->hostname, sizeof(s->hostname));
428     return s;
429 }
430
431 void ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
432                                        RTPDynamicProtocolHandler *handler)
433 {
434     s->dynamic_protocol_context = ctx;
435     s->parse_packet             = handler->parse_packet;
436 }
437
438 /**
439  * This was the second switch in rtp_parse packet.
440  * Normalizes time, if required, sets stream_index, etc.
441  */
442 static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
443 {
444     if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
445         return; /* Timestamp already set by depacketizer */
446     if (timestamp == RTP_NOTS_VALUE)
447         return;
448
449     if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
450         int64_t addend;
451         int delta_timestamp;
452
453         /* compute pts from timestamp with received ntp_time */
454         delta_timestamp = timestamp - s->last_rtcp_timestamp;
455         /* convert to the PTS timebase */
456         addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time,
457                             s->st->time_base.den,
458                             (uint64_t) s->st->time_base.num << 32);
459         pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
460                    delta_timestamp;
461         return;
462     }
463
464     if (!s->base_timestamp)
465         s->base_timestamp = timestamp;
466     /* assume that the difference is INT32_MIN < x < INT32_MAX,
467      * but allow the first timestamp to exceed INT32_MAX */
468     if (!s->timestamp)
469         s->unwrapped_timestamp += timestamp;
470     else
471         s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
472     s->timestamp = timestamp;
473     pkt->pts     = s->unwrapped_timestamp + s->range_start_offset -
474                    s->base_timestamp;
475 }
476
477 static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
478                                      const uint8_t *buf, int len)
479 {
480     unsigned int ssrc, h;
481     int payload_type, seq, ret, flags = 0;
482     int ext;
483     AVStream *st;
484     uint32_t timestamp;
485     int rv = 0;
486
487     ext          = buf[0] & 0x10;
488     payload_type = buf[1] & 0x7f;
489     if (buf[1] & 0x80)
490         flags |= RTP_FLAG_MARKER;
491     seq       = AV_RB16(buf + 2);
492     timestamp = AV_RB32(buf + 4);
493     ssrc      = AV_RB32(buf + 8);
494     /* store the ssrc in the RTPDemuxContext */
495     s->ssrc = ssrc;
496
497     /* NOTE: we can handle only one payload type */
498     if (s->payload_type != payload_type)
499         return -1;
500
501     st = s->st;
502     // only do something with this if all the rtp checks pass...
503     if (!rtp_valid_packet_in_sequence(&s->statistics, seq)) {
504         av_log(st ? st->codec : NULL, AV_LOG_ERROR,
505                "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
506                payload_type, seq, ((s->seq + 1) & 0xffff));
507         return -1;
508     }
509
510     if (buf[0] & 0x20) {
511         int padding = buf[len - 1];
512         if (len >= 12 + padding)
513             len -= padding;
514     }
515
516     s->seq = seq;
517     len   -= 12;
518     buf   += 12;
519
520     /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
521     if (ext) {
522         if (len < 4)
523             return -1;
524         /* calculate the header extension length (stored as number
525          * of 32-bit words) */
526         ext = (AV_RB16(buf + 2) + 1) << 2;
527
528         if (len < ext)
529             return -1;
530         // skip past RTP header extension
531         len -= ext;
532         buf += ext;
533     }
534
535     if (!st) {
536         /* specific MPEG2-TS demux support */
537         ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
538         /* The only error that can be returned from ff_mpegts_parse_packet
539          * is "no more data to return from the provided buffer", so return
540          * AVERROR(EAGAIN) for all errors */
541         if (ret < 0)
542             return AVERROR(EAGAIN);
543         if (ret < len) {
544             s->read_buf_size = len - ret;
545             memcpy(s->buf, buf + ret, s->read_buf_size);
546             s->read_buf_index = 0;
547             return 1;
548         }
549         return 0;
550     } else if (s->parse_packet) {
551         rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
552                              s->st, pkt, &timestamp, buf, len, flags);
553     } else {
554         /* At this point, the RTP header has been stripped;
555          * This is ASSUMING that there is only 1 CSRC, which isn't wise. */
556         switch (st->codec->codec_id) {
557         case AV_CODEC_ID_MP2:
558         case AV_CODEC_ID_MP3:
559             /* better than nothing: skip MPEG audio RTP header */
560             if (len <= 4)
561                 return -1;
562             h    = AV_RB32(buf);
563             len -= 4;
564             buf += 4;
565             av_new_packet(pkt, len);
566             memcpy(pkt->data, buf, len);
567             break;
568         case AV_CODEC_ID_MPEG1VIDEO:
569         case AV_CODEC_ID_MPEG2VIDEO:
570             /* better than nothing: skip MPEG video RTP header */
571             if (len <= 4)
572                 return -1;
573             h    = AV_RB32(buf);
574             buf += 4;
575             len -= 4;
576             if (h & (1 << 26)) {
577                 /* MPEG-2 */
578                 if (len <= 4)
579                     return -1;
580                 buf += 4;
581                 len -= 4;
582             }
583             av_new_packet(pkt, len);
584             memcpy(pkt->data, buf, len);
585             break;
586         default:
587             av_new_packet(pkt, len);
588             memcpy(pkt->data, buf, len);
589             break;
590         }
591
592         pkt->stream_index = st->index;
593     }
594
595     // now perform timestamp things....
596     finalize_packet(s, pkt, timestamp);
597
598     return rv;
599 }
600
601 void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
602 {
603     while (s->queue) {
604         RTPPacket *next = s->queue->next;
605         av_free(s->queue->buf);
606         av_free(s->queue);
607         s->queue = next;
608     }
609     s->seq       = 0;
610     s->queue_len = 0;
611     s->prev_ret  = 0;
612 }
613
614 static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
615 {
616     uint16_t seq   = AV_RB16(buf + 2);
617     RTPPacket *cur = s->queue, *prev = NULL, *packet;
618
619     /* Find the correct place in the queue to insert the packet */
620     while (cur) {
621         int16_t diff = seq - cur->seq;
622         if (diff < 0)
623             break;
624         prev = cur;
625         cur  = cur->next;
626     }
627
628     packet = av_mallocz(sizeof(*packet));
629     if (!packet)
630         return;
631     packet->recvtime = av_gettime();
632     packet->seq      = seq;
633     packet->len      = len;
634     packet->buf      = buf;
635     packet->next     = cur;
636     if (prev)
637         prev->next = packet;
638     else
639         s->queue = packet;
640     s->queue_len++;
641 }
642
643 static int has_next_packet(RTPDemuxContext *s)
644 {
645     return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
646 }
647
648 int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
649 {
650     return s->queue ? s->queue->recvtime : 0;
651 }
652
653 static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
654 {
655     int rv;
656     RTPPacket *next;
657
658     if (s->queue_len <= 0)
659         return -1;
660
661     if (!has_next_packet(s))
662         av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
663                "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
664
665     /* Parse the first packet in the queue, and dequeue it */
666     rv   = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
667     next = s->queue->next;
668     av_free(s->queue->buf);
669     av_free(s->queue);
670     s->queue = next;
671     s->queue_len--;
672     return rv;
673 }
674
675 static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
676                                 uint8_t **bufptr, int len)
677 {
678     uint8_t *buf = bufptr ? *bufptr : NULL;
679     int ret, flags = 0;
680     uint32_t timestamp;
681     int rv = 0;
682
683     if (!buf) {
684         /* If parsing of the previous packet actually returned 0 or an error,
685          * there's nothing more to be parsed from that packet, but we may have
686          * indicated that we can return the next enqueued packet. */
687         if (s->prev_ret <= 0)
688             return rtp_parse_queued_packet(s, pkt);
689         /* return the next packets, if any */
690         if (s->st && s->parse_packet) {
691             /* timestamp should be overwritten by parse_packet, if not,
692              * the packet is left with pts == AV_NOPTS_VALUE */
693             timestamp = RTP_NOTS_VALUE;
694             rv        = s->parse_packet(s->ic, s->dynamic_protocol_context,
695                                         s->st, pkt, &timestamp, NULL, 0, flags);
696             finalize_packet(s, pkt, timestamp);
697             return rv;
698         } else {
699             // TODO: Move to a dynamic packet handler (like above)
700             if (s->read_buf_index >= s->read_buf_size)
701                 return AVERROR(EAGAIN);
702             ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
703                                          s->read_buf_size - s->read_buf_index);
704             if (ret < 0)
705                 return AVERROR(EAGAIN);
706             s->read_buf_index += ret;
707             if (s->read_buf_index < s->read_buf_size)
708                 return 1;
709             else
710                 return 0;
711         }
712     }
713
714     if (len < 12)
715         return -1;
716
717     if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
718         return -1;
719     if (RTP_PT_IS_RTCP(buf[1])) {
720         return rtcp_parse_packet(s, buf, len);
721     }
722
723     if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
724         /* First packet, or no reordering */
725         return rtp_parse_packet_internal(s, pkt, buf, len);
726     } else {
727         uint16_t seq = AV_RB16(buf + 2);
728         int16_t diff = seq - s->seq;
729         if (diff < 0) {
730             /* Packet older than the previously emitted one, drop */
731             av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
732                    "RTP: dropping old packet received too late\n");
733             return -1;
734         } else if (diff <= 1) {
735             /* Correct packet */
736             rv = rtp_parse_packet_internal(s, pkt, buf, len);
737             return rv;
738         } else {
739             /* Still missing some packet, enqueue this one. */
740             enqueue_packet(s, buf, len);
741             *bufptr = NULL;
742             /* Return the first enqueued packet if the queue is full,
743              * even if we're missing something */
744             if (s->queue_len >= s->queue_size)
745                 return rtp_parse_queued_packet(s, pkt);
746             return -1;
747         }
748     }
749 }
750
751 /**
752  * Parse an RTP or RTCP packet directly sent as a buffer.
753  * @param s RTP parse context.
754  * @param pkt returned packet
755  * @param bufptr pointer to the input buffer or NULL to read the next packets
756  * @param len buffer len
757  * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
758  * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
759  */
760 int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
761                         uint8_t **bufptr, int len)
762 {
763     int rv = rtp_parse_one_packet(s, pkt, bufptr, len);
764     s->prev_ret = rv;
765     while (rv == AVERROR(EAGAIN) && has_next_packet(s))
766         rv = rtp_parse_queued_packet(s, pkt);
767     return rv ? rv : has_next_packet(s);
768 }
769
770 void ff_rtp_parse_close(RTPDemuxContext *s)
771 {
772     ff_rtp_reset_packet_queue(s);
773     if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
774         ff_mpegts_parse_close(s->ts);
775     }
776     av_free(s);
777 }
778
779 int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
780                   int (*parse_fmtp)(AVStream *stream,
781                                     PayloadContext *data,
782                                     char *attr, char *value))
783 {
784     char attr[256];
785     char *value;
786     int res;
787     int value_size = strlen(p) + 1;
788
789     if (!(value = av_malloc(value_size))) {
790         av_log(NULL, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
791         return AVERROR(ENOMEM);
792     }
793
794     // remove protocol identifier
795     while (*p && *p == ' ')
796         p++;                     // strip spaces
797     while (*p && *p != ' ')
798         p++;                     // eat protocol identifier
799     while (*p && *p == ' ')
800         p++;                     // strip trailing spaces
801
802     while (ff_rtsp_next_attr_and_value(&p,
803                                        attr, sizeof(attr),
804                                        value, value_size)) {
805         res = parse_fmtp(stream, data, attr, value);
806         if (res < 0 && res != AVERROR_PATCHWELCOME) {
807             av_free(value);
808             return res;
809         }
810     }
811     av_free(value);
812     return 0;
813 }
814
815 int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
816 {
817     av_init_packet(pkt);
818
819     pkt->size         = avio_close_dyn_buf(*dyn_buf, &pkt->data);
820     pkt->stream_index = stream_idx;
821     pkt->destruct     = av_destruct_packet;
822     *dyn_buf          = NULL;
823     return pkt->size;
824 }