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