cosmetics: Fix dropable --> droppable typo
[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"
925e908b 28#include "url.h"
8eb793c4 29
8eb793c4
LA
30#include "network.h"
31
302879cb 32#include "rtpdec.h"
965a3ddb 33#include "rtpdec_formats.h"
8eb793c4
LA
34
35//#define DEBUG
36
37/* TODO: - add RTCP statistics reporting (should be optional).
38
39 - add support for h263/mpeg4 packetized output : IDEA: send a
40 buffer to 'rtp_write_packet' contains all the packets for ONE
41 frame. Each packet should have a four byte header containing
42 the length in big endian format (same trick as
403ee835 43 'ffio_open_dyn_packet_buf')
8eb793c4
LA
44*/
45
69673138 46static RTPDynamicProtocolHandler realmedia_mp3_dynamic_handler = {
2eeefe20
MS
47 .enc_name = "X-MP3-draft-00",
48 .codec_type = AVMEDIA_TYPE_AUDIO,
36ef5369 49 .codec_id = AV_CODEC_ID_MP3ADU,
2eeefe20
MS
50};
51
b6bf1490
DS
52static RTPDynamicProtocolHandler speex_dynamic_handler = {
53 .enc_name = "speex",
54 .codec_type = AVMEDIA_TYPE_AUDIO,
55 .codec_id = AV_CODEC_ID_SPEEX,
56};
57
c136a813
MS
58static RTPDynamicProtocolHandler opus_dynamic_handler = {
59 .enc_name = "opus",
60 .codec_type = AVMEDIA_TYPE_AUDIO,
61 .codec_id = AV_CODEC_ID_OPUS,
62};
63
8eb793c4 64/* statistics functions */
119cc033 65static RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
8eb793c4 66
0369d2b0 67void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
8eb793c4
LA
68{
69 handler->next= RTPFirstDynamicPayloadHandler;
70 RTPFirstDynamicPayloadHandler= handler;
71}
72
73void av_register_rtp_dynamic_payload_handlers(void)
74{
9b3788ef
JA
75 ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
76 ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
556aa7a1
RB
77 ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
78 ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
45aa9080
RB
79 ff_register_dynamic_payload_handler(&ff_h263_1998_dynamic_handler);
80 ff_register_dynamic_payload_handler(&ff_h263_2000_dynamic_handler);
08bddfcd 81 ff_register_dynamic_payload_handler(&ff_h263_rfc2190_dynamic_handler);
0369d2b0 82 ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
89c39605 83 ff_register_dynamic_payload_handler(&ff_ilbc_dynamic_handler);
3c198154 84 ff_register_dynamic_payload_handler(&ff_jpeg_dynamic_handler);
e6327fba 85 ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
887af2aa 86 ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
a59096e4 87 ff_register_dynamic_payload_handler(&ff_qdm2_dynamic_handler);
4449df6b 88 ff_register_dynamic_payload_handler(&ff_svq3_dynamic_handler);
1ddc176e 89 ff_register_dynamic_payload_handler(&ff_mp4a_latm_dynamic_handler);
51291e60 90 ff_register_dynamic_payload_handler(&ff_vp8_dynamic_handler);
35014efc 91 ff_register_dynamic_payload_handler(&ff_qcelp_dynamic_handler);
69673138 92 ff_register_dynamic_payload_handler(&realmedia_mp3_dynamic_handler);
b6bf1490 93 ff_register_dynamic_payload_handler(&speex_dynamic_handler);
c136a813 94 ff_register_dynamic_payload_handler(&opus_dynamic_handler);
e9fce261
RB
95
96 ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
97 ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
3ece3e4c
MS
98
99 ff_register_dynamic_payload_handler(&ff_qt_rtp_aud_handler);
100 ff_register_dynamic_payload_handler(&ff_qt_rtp_vid_handler);
101 ff_register_dynamic_payload_handler(&ff_quicktime_rtp_aud_handler);
102 ff_register_dynamic_payload_handler(&ff_quicktime_rtp_vid_handler);
06d7325a
MS
103
104 ff_register_dynamic_payload_handler(&ff_g726_16_dynamic_handler);
105 ff_register_dynamic_payload_handler(&ff_g726_24_dynamic_handler);
106 ff_register_dynamic_payload_handler(&ff_g726_32_dynamic_handler);
107 ff_register_dynamic_payload_handler(&ff_g726_40_dynamic_handler);
8eb793c4
LA
108}
109
1e515c42
MS
110RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
111 enum AVMediaType codec_type)
112{
113 RTPDynamicProtocolHandler *handler;
114 for (handler = RTPFirstDynamicPayloadHandler;
115 handler; handler = handler->next)
bb3244de 116 if (!av_strcasecmp(name, handler->enc_name) &&
1e515c42
MS
117 codec_type == handler->codec_type)
118 return handler;
119 return NULL;
120}
121
122RTPDynamicProtocolHandler *ff_rtp_handler_find_by_id(int id,
123 enum AVMediaType codec_type)
124{
125 RTPDynamicProtocolHandler *handler;
126 for (handler = RTPFirstDynamicPayloadHandler;
127 handler; handler = handler->next)
128 if (handler->static_payload_id && handler->static_payload_id == id &&
129 codec_type == handler->codec_type)
130 return handler;
131 return NULL;
132}
133
8eb793c4
LA
134static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
135{
ff328c02 136 int payload_len;
07b77fe3
JB
137 while (len >= 4) {
138 payload_len = FFMIN(len, (AV_RB16(buf + 2) + 1) * 4);
139
ff328c02
JA
140 switch (buf[1]) {
141 case RTCP_SR:
07b77fe3 142 if (payload_len < 20) {
ff328c02
JA
143 av_log(NULL, AV_LOG_ERROR, "Invalid length for RTCP SR packet\n");
144 return AVERROR_INVALIDDATA;
145 }
ff328c02 146
682d28a9 147 s->last_rtcp_ntp_time = AV_RB64(buf + 8);
682d28a9 148 s->last_rtcp_timestamp = AV_RB32(buf + 16);
3a1cdcc7
MS
149 if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
150 s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
151 if (!s->base_timestamp)
152 s->base_timestamp = s->last_rtcp_timestamp;
153 s->rtcp_ts_offset = s->last_rtcp_timestamp - s->base_timestamp;
154 }
ff328c02 155
ff328c02 156 break;
b20359f5
JA
157 case RTCP_BYE:
158 return -RTCP_BYE;
ff328c02 159 }
07b77fe3
JB
160
161 buf += payload_len;
162 len -= payload_len;
ff328c02 163 }
b20359f5 164 return -1;
8eb793c4
LA
165}
166
167#define RTP_SEQ_MOD (1<<16)
168
48f01398 169static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
8eb793c4
LA
170{
171 memset(s, 0, sizeof(RTPStatistics));
48f01398
MS
172 s->max_seq = base_sequence;
173 s->probation = 1;
8eb793c4
LA
174}
175
48f01398 176/*
8eb793c4
LA
177* called whenever there is a large jump in sequence numbers, or when they get out of probation...
178*/
179static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
180{
48f01398
MS
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;
8eb793c4
LA
190}
191
48f01398 192/*
8eb793c4
LA
193* returns 1 if we should handle this packet.
194*/
195static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
196{
48f01398
MS
197 uint16_t udelta = seq - s->max_seq;
198 const int MAX_DROPOUT = 3000;
199 const int MAX_MISORDER = 100;
8eb793c4
LA
200 const int MIN_SEQUENTIAL = 2;
201
202 /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
48f01398
MS
203 if (s->probation) {
204 if (seq == s->max_seq + 1) {
8eb793c4 205 s->probation--;
48f01398
MS
206 s->max_seq = seq;
207 if (s->probation == 0) {
8eb793c4
LA
208 rtp_init_sequence(s, seq);
209 s->received++;
210 return 1;
211 }
212 } else {
48f01398 213 s->probation = MIN_SEQUENTIAL - 1;
8eb793c4
LA
214 s->max_seq = seq;
215 }
216 } else if (udelta < MAX_DROPOUT) {
217 // in order, with permissible gap
48f01398
MS
218 if (seq < s->max_seq) {
219 // sequence number wrapped; count another 64k cycles
8eb793c4
LA
220 s->cycles += RTP_SEQ_MOD;
221 }
48f01398 222 s->max_seq = seq;
8eb793c4
LA
223 } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
224 // sequence made a large jump...
48f01398 225 if (seq == s->bad_seq) {
8eb793c4
LA
226 // two sequential packets-- assume that the other side restarted without telling us; just resync.
227 rtp_init_sequence(s, seq);
228 } else {
48f01398 229 s->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1);
8eb793c4
LA
230 return 0;
231 }
232 } else {
233 // duplicate or reordered packet...
234 }
235 s->received++;
236 return 1;
237}
238
bfc6db44 239int ff_rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
8eb793c4 240{
ae628ec1 241 AVIOContext *pb;
8eb793c4
LA
242 uint8_t *buf;
243 int len;
244 int rtcp_bytes;
48f01398 245 RTPStatistics *stats = &s->statistics;
8eb793c4
LA
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;
48f01398 253 uint64_t ntp_time = s->last_rtcp_ntp_time; // TODO: Get local ntp time?
8eb793c4
LA
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
b92c5452 268 if (avio_open_dyn_buf(&pb) < 0)
8eb793c4
LA
269 return -1;
270
271 // Receiver Report
77eb5504
AK
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 */
952139a3 275 // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
77eb5504
AK
276 avio_wb32(pb, s->ssrc + 1);
277 avio_wb32(pb, s->ssrc); // server SSRC
8eb793c4
LA
278 // some placeholders we should really fill...
279 // RFC 1889/p64
48f01398
MS
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;
8eb793c4 295
77eb5504
AK
296 avio_wb32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
297 avio_wb32(pb, extended_max); /* max sequence received */
48f01398 298 avio_wb32(pb, stats->jitter >> 4); /* jitter */
8eb793c4 299
48f01398 300 if (s->last_rtcp_ntp_time == AV_NOPTS_VALUE) {
77eb5504
AK
301 avio_wb32(pb, 0); /* last SR timestamp */
302 avio_wb32(pb, 0); /* delay since last SR */
8eb793c4 303 } else {
48f01398
MS
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;
8eb793c4 306
77eb5504
AK
307 avio_wb32(pb, middle_32_bits); /* last SR timestamp */
308 avio_wb32(pb, delay_since_last); /* delay since last SR */
8eb793c4
LA
309 }
310
311 // CNAME
77eb5504
AK
312 avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
313 avio_w8(pb, RTCP_SDES);
8eb793c4 314 len = strlen(s->hostname);
77eb5504 315 avio_wb16(pb, (6 + len + 3) / 4); /* length in words - 1 */
ad7beb2c 316 avio_wb32(pb, s->ssrc + 1);
77eb5504
AK
317 avio_w8(pb, 0x01);
318 avio_w8(pb, len);
319 avio_write(pb, s->hostname, len);
8eb793c4
LA
320 // padding
321 for (len = (6 + len) % 4; len % 4; len++) {
77eb5504 322 avio_w8(pb, 0);
8eb793c4
LA
323 }
324
b7f2fdde 325 avio_flush(pb);
6dc7d80d 326 len = avio_close_dyn_buf(pb, &buf);
8eb793c4 327 if ((len > 0) && buf) {
5e1166b3 328 int av_unused result;
dfd2a005 329 av_dlog(s->ic, "sending %d bytes of RR\n", len);
925e908b
AK
330 result= ffurl_write(s->rtp_ctx, buf, len);
331 av_dlog(s->ic, "result from ffurl_write: %d\n", result);
8eb793c4
LA
332 av_free(buf);
333 }
334 return 0;
335}
336
bfc6db44 337void ff_rtp_send_punch_packets(URLContext* rtp_handle)
9c8fa20d 338{
ae628ec1 339 AVIOContext *pb;
9c8fa20d
MS
340 uint8_t *buf;
341 int len;
342
343 /* Send a small RTP packet */
b92c5452 344 if (avio_open_dyn_buf(&pb) < 0)
9c8fa20d
MS
345 return;
346
77eb5504
AK
347 avio_w8(pb, (RTP_VERSION << 6));
348 avio_w8(pb, 0); /* Payload type */
349 avio_wb16(pb, 0); /* Seq */
350 avio_wb32(pb, 0); /* Timestamp */
351 avio_wb32(pb, 0); /* SSRC */
9c8fa20d 352
b7f2fdde 353 avio_flush(pb);
6dc7d80d 354 len = avio_close_dyn_buf(pb, &buf);
9c8fa20d 355 if ((len > 0) && buf)
925e908b 356 ffurl_write(rtp_handle, buf, len);
9c8fa20d
MS
357 av_free(buf);
358
359 /* Send a minimal RTCP RR */
b92c5452 360 if (avio_open_dyn_buf(&pb) < 0)
9c8fa20d
MS
361 return;
362
77eb5504
AK
363 avio_w8(pb, (RTP_VERSION << 6));
364 avio_w8(pb, RTCP_RR); /* receiver report */
365 avio_wb16(pb, 1); /* length in words - 1 */
366 avio_wb32(pb, 0); /* our own SSRC */
9c8fa20d 367
b7f2fdde 368 avio_flush(pb);
6dc7d80d 369 len = avio_close_dyn_buf(pb, &buf);
9c8fa20d 370 if ((len > 0) && buf)
925e908b 371 ffurl_write(rtp_handle, buf, len);
9c8fa20d
MS
372 av_free(buf);
373}
374
375
8eb793c4
LA
376/**
377 * open a new RTP parse context for stream 'st'. 'st' can be NULL for
378 * MPEG2TS streams to indicate that they should be demuxed inside the
36ef5369 379 * rtp demux (otherwise AV_CODEC_ID_MPEG2TS packets are returned)
8eb793c4 380 */
bfc6db44 381RTPDemuxContext *ff_rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, int queue_size)
8eb793c4
LA
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;
2cab6b48 390 s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
8eb793c4
LA
391 s->ic = s1;
392 s->st = st;
58ee0991 393 s->queue_size = queue_size;
8eb793c4
LA
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")) {
9125806e 396 s->ts = ff_mpegts_parse_open(s->ic);
8eb793c4
LA
397 if (s->ts == NULL) {
398 av_free(s);
399 return NULL;
400 }
45600148 401 } else if (st) {
8eb793c4 402 switch(st->codec->codec_id) {
36ef5369
AK
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:
8eb793c4
LA
410 st->need_parsing = AVSTREAM_PARSE_FULL;
411 break;
36ef5369 412 case AV_CODEC_ID_VORBIS:
5602a464
JR
413 st->need_parsing = AVSTREAM_PARSE_HEADERS;
414 break;
36ef5369 415 case AV_CODEC_ID_ADPCM_G722:
0048a2a8
MS
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;
8eb793c4
LA
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
48f01398
MS
431void ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
432 RTPDynamicProtocolHandler *handler)
99a1d191
RB
433{
434 s->dynamic_protocol_context = ctx;
435 s->parse_packet = handler->parse_packet;
436}
437
8eb793c4
LA
438/**
439 * This was the second switch in rtp_parse packet. Normalizes time, if required, sets stream_index, etc.
440 */
441static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
442{
79d482b1
MS
443 if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
444 return; /* Timestamp already set by depacketizer */
b8a1b880
JB
445 if (timestamp == RTP_NOTS_VALUE)
446 return;
447
525c5b08 448 if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
fba7815d
LA
449 int64_t addend;
450 int delta_timestamp;
451
452 /* compute pts from timestamp with received ntp_time */
453 delta_timestamp = timestamp - s->last_rtcp_timestamp;
454 /* convert to the PTS timebase */
2cab6b48 455 addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time, s->st->time_base.den, (uint64_t)s->st->time_base.num << 32);
3a1cdcc7
MS
456 pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
457 delta_timestamp;
458 return;
fba7815d 459 }
b8a1b880 460
3a1cdcc7
MS
461 if (!s->base_timestamp)
462 s->base_timestamp = timestamp;
12348ca2
JB
463 /* assume that the difference is INT32_MIN < x < INT32_MAX, but allow the first timestamp to exceed INT32_MAX */
464 if (!s->timestamp)
465 s->unwrapped_timestamp += timestamp;
466 else
467 s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
468 s->timestamp = timestamp;
469 pkt->pts = s->unwrapped_timestamp + s->range_start_offset - s->base_timestamp;
8eb793c4
LA
470}
471
02607418
MS
472static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
473 const uint8_t *buf, int len)
8eb793c4
LA
474{
475 unsigned int ssrc, h;
f841a0fc 476 int payload_type, seq, ret, flags = 0;
9446b4bb 477 int ext;
8eb793c4
LA
478 AVStream *st;
479 uint32_t timestamp;
480 int rv= 0;
481
9446b4bb 482 ext = buf[0] & 0x10;
8eb793c4 483 payload_type = buf[1] & 0x7f;
144ae29d
RB
484 if (buf[1] & 0x80)
485 flags |= RTP_FLAG_MARKER;
8eb793c4
LA
486 seq = AV_RB16(buf + 2);
487 timestamp = AV_RB32(buf + 4);
488 ssrc = AV_RB32(buf + 8);
489 /* store the ssrc in the RTPDemuxContext */
490 s->ssrc = ssrc;
491
492 /* NOTE: we can handle only one payload type */
493 if (s->payload_type != payload_type)
494 return -1;
495
496 st = s->st;
497 // only do something with this if all the rtp checks pass...
498 if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
499 {
500 av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
501 payload_type, seq, ((s->seq + 1) & 0xffff));
502 return -1;
503 }
504
4838cdab
MS
505 if (buf[0] & 0x20) {
506 int padding = buf[len - 1];
507 if (len >= 12 + padding)
508 len -= padding;
509 }
510
8eb793c4
LA
511 s->seq = seq;
512 len -= 12;
513 buf += 12;
514
9446b4bb
RS
515 /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
516 if (ext) {
517 if (len < 4)
518 return -1;
519 /* calculate the header extension length (stored as number
520 * of 32-bit words) */
521 ext = (AV_RB16(buf + 2) + 1) << 2;
522
523 if (len < ext)
524 return -1;
525 // skip past RTP header extension
526 len -= ext;
527 buf += ext;
528 }
529
8eb793c4
LA
530 if (!st) {
531 /* specific MPEG2TS demux support */
9125806e 532 ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
946df059
MS
533 /* The only error that can be returned from ff_mpegts_parse_packet
534 * is "no more data to return from the provided buffer", so return
535 * AVERROR(EAGAIN) for all errors */
4ffff367 536 if (ret < 0)
946df059 537 return AVERROR(EAGAIN);
8eb793c4
LA
538 if (ret < len) {
539 s->read_buf_size = len - ret;
540 memcpy(s->buf, buf + ret, s->read_buf_size);
541 s->read_buf_index = 0;
542 return 1;
543 }
f3e71942 544 return 0;
b4e3330c 545 } else if (s->parse_packet) {
1a45a9f4 546 rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
9b932b8a 547 s->st, pkt, &timestamp, buf, len, flags);
8eb793c4
LA
548 } else {
549 // at this point, the RTP header has been stripped; This is ASSUMING that there is only 1 CSRC, which in't wise.
550 switch(st->codec->codec_id) {
36ef5369
AK
551 case AV_CODEC_ID_MP2:
552 case AV_CODEC_ID_MP3:
8eb793c4
LA
553 /* better than nothing: skip mpeg audio RTP header */
554 if (len <= 4)
555 return -1;
556 h = AV_RB32(buf);
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:
8eb793c4
LA
564 /* better than nothing: skip mpeg video RTP header */
565 if (len <= 4)
566 return -1;
567 h = AV_RB32(buf);
568 buf += 4;
569 len -= 4;
570 if (h & (1 << 26)) {
571 /* mpeg2 */
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{
610 uint16_t seq = AV_RB16(buf + 2);
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;
619 cur = cur->next;
620 }
621
622 packet = av_mallocz(sizeof(*packet));
623 if (!packet)
624 return;
625 packet->recvtime = av_gettime();
626 packet->seq = seq;
627 packet->len = len;
628 packet->buf = buf;
629 packet->next = cur;
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 */
660 rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
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
MS
671{
672 uint8_t* buf = bufptr ? *bufptr : NULL;
673 int ret, flags = 0;
674 uint32_t timestamp;
675 int rv= 0;
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
MS
683 /* return the next packets, if any */
684 if(s->st && s->parse_packet) {
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;
688 rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
689 s->st, pkt, &timestamp, NULL, 0, flags);
690 finalize_packet(s, pkt, timestamp);
4ffff367 691 return rv;
02607418
MS
692 } else {
693 // TODO: Move to a dynamic packet handler (like above)
4ffff367 694 if (s->read_buf_index >= s->read_buf_size)
91ec7aea 695 return AVERROR(EAGAIN);
02607418
MS
696 ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
697 s->read_buf_size - s->read_buf_index);
4ffff367 698 if (ret < 0)
946df059 699 return AVERROR(EAGAIN);
02607418
MS
700 s->read_buf_index += ret;
701 if (s->read_buf_index < s->read_buf_size)
702 return 1;
4ffff367
MS
703 else
704 return 0;
02607418
MS
705 }
706 }
707
708 if (len < 12)
709 return -1;
710
711 if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
712 return -1;
298a587f 713 if (RTP_PT_IS_RTCP(buf[1])) {
02607418
MS
714 return rtcp_parse_packet(s, buf, len);
715 }
716
65cdee9c 717 if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
58ee0991
MS
718 /* First packet, or no reordering */
719 return rtp_parse_packet_internal(s, pkt, buf, len);
720 } else {
721 uint16_t seq = AV_RB16(buf + 2);
722 int16_t diff = seq - s->seq;
723 if (diff < 0) {
724 /* Packet older than the previously emitted one, drop */
725 av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
726 "RTP: dropping old packet received too late\n");
727 return -1;
728 } else if (diff <= 1) {
729 /* Correct packet */
730 rv = rtp_parse_packet_internal(s, pkt, buf, len);
4ffff367 731 return rv;
58ee0991
MS
732 } else {
733 /* Still missing some packet, enqueue this one. */
734 enqueue_packet(s, buf, len);
735 *bufptr = NULL;
736 /* Return the first enqueued packet if the queue is full,
737 * even if we're missing something */
738 if (s->queue_len >= s->queue_size)
739 return rtp_parse_queued_packet(s, pkt);
740 return -1;
741 }
742 }
02607418
MS
743}
744
4ffff367
MS
745/**
746 * Parse an RTP or RTCP packet directly sent as a buffer.
747 * @param s RTP parse context.
748 * @param pkt returned packet
749 * @param bufptr pointer to the input buffer or NULL to read the next packets
750 * @param len buffer len
751 * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
752 * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
753 */
bfc6db44
MS
754int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
755 uint8_t **bufptr, int len)
4ffff367
MS
756{
757 int rv = rtp_parse_one_packet(s, pkt, bufptr, len);
758 s->prev_ret = rv;
d678a6fd
MS
759 while (rv == AVERROR(EAGAIN) && has_next_packet(s))
760 rv = rtp_parse_queued_packet(s, pkt);
4ffff367
MS
761 return rv ? rv : has_next_packet(s);
762}
763
bfc6db44 764void ff_rtp_parse_close(RTPDemuxContext *s)
8eb793c4 765{
58ee0991 766 ff_rtp_reset_packet_queue(s);
8eb793c4 767 if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
9125806e 768 ff_mpegts_parse_close(s->ts);
8eb793c4
LA
769 }
770 av_free(s);
771}
016bc031
JA
772
773int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
774 int (*parse_fmtp)(AVStream *stream,
775 PayloadContext *data,
776 char *attr, char *value))
777{
778 char attr[256];
824535e3 779 char *value;
016bc031 780 int res;
824535e3
JA
781 int value_size = strlen(p) + 1;
782
783 if (!(value = av_malloc(value_size))) {
c3e15f7b 784 av_log(NULL, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
824535e3
JA
785 return AVERROR(ENOMEM);
786 }
016bc031
JA
787
788 // remove protocol identifier
789 while (*p && *p == ' ') p++; // strip spaces
790 while (*p && *p != ' ') p++; // eat protocol identifier
791 while (*p && *p == ' ') p++; // strip trailing spaces
792
793 while (ff_rtsp_next_attr_and_value(&p,
794 attr, sizeof(attr),
824535e3 795 value, value_size)) {
016bc031
JA
796
797 res = parse_fmtp(stream, data, attr, value);
824535e3
JA
798 if (res < 0 && res != AVERROR_PATCHWELCOME) {
799 av_free(value);
016bc031 800 return res;
824535e3 801 }
016bc031 802 }
824535e3 803 av_free(value);
016bc031
JA
804 return 0;
805}
179a5c37
AK
806
807int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
808{
809 av_init_packet(pkt);
810
811 pkt->size = avio_close_dyn_buf(*dyn_buf, &pkt->data);
812 pkt->stream_index = stream_idx;
813 pkt->destruct = av_destruct_packet;
814 *dyn_buf = NULL;
815 return pkt->size;
816}