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