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