sh4: dsputil: remove duplicate of ff_gmc_c()
[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
5d471b73
MS
33/* TODO:
34 * - add RTCP statistics reporting (should be optional).
35 *
36 * - add support for H.263/MPEG-4 packetized output: IDEA: send a
37 * buffer to 'rtp_write_packet' contains all the packets for ONE
38 * frame. Each packet should have a four byte header containing
39 * the length in big-endian format (same trick as
40 * 'ffio_open_dyn_packet_buf').
41 */
8eb793c4 42
69673138 43static RTPDynamicProtocolHandler realmedia_mp3_dynamic_handler = {
5d471b73
MS
44 .enc_name = "X-MP3-draft-00",
45 .codec_type = AVMEDIA_TYPE_AUDIO,
46 .codec_id = AV_CODEC_ID_MP3ADU,
2eeefe20
MS
47};
48
b6bf1490 49static RTPDynamicProtocolHandler speex_dynamic_handler = {
5d471b73
MS
50 .enc_name = "speex",
51 .codec_type = AVMEDIA_TYPE_AUDIO,
52 .codec_id = AV_CODEC_ID_SPEEX,
b6bf1490
DS
53};
54
c136a813 55static RTPDynamicProtocolHandler opus_dynamic_handler = {
5d471b73
MS
56 .enc_name = "opus",
57 .codec_type = AVMEDIA_TYPE_AUDIO,
58 .codec_id = AV_CODEC_ID_OPUS,
c136a813
MS
59};
60
8eb793c4 61/* statistics functions */
5d471b73 62static RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler = NULL;
8eb793c4 63
0369d2b0 64void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
8eb793c4 65{
5d471b73
MS
66 handler->next = RTPFirstDynamicPayloadHandler;
67 RTPFirstDynamicPayloadHandler = handler;
8eb793c4
LA
68}
69
70void av_register_rtp_dynamic_payload_handlers(void)
71{
9b3788ef
JA
72 ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
73 ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
556aa7a1
RB
74 ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
75 ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
45aa9080
RB
76 ff_register_dynamic_payload_handler(&ff_h263_1998_dynamic_handler);
77 ff_register_dynamic_payload_handler(&ff_h263_2000_dynamic_handler);
08bddfcd 78 ff_register_dynamic_payload_handler(&ff_h263_rfc2190_dynamic_handler);
0369d2b0 79 ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
89c39605 80 ff_register_dynamic_payload_handler(&ff_ilbc_dynamic_handler);
3c198154 81 ff_register_dynamic_payload_handler(&ff_jpeg_dynamic_handler);
e6327fba 82 ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
887af2aa 83 ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
a59096e4 84 ff_register_dynamic_payload_handler(&ff_qdm2_dynamic_handler);
4449df6b 85 ff_register_dynamic_payload_handler(&ff_svq3_dynamic_handler);
1ddc176e 86 ff_register_dynamic_payload_handler(&ff_mp4a_latm_dynamic_handler);
51291e60 87 ff_register_dynamic_payload_handler(&ff_vp8_dynamic_handler);
35014efc 88 ff_register_dynamic_payload_handler(&ff_qcelp_dynamic_handler);
69673138 89 ff_register_dynamic_payload_handler(&realmedia_mp3_dynamic_handler);
b6bf1490 90 ff_register_dynamic_payload_handler(&speex_dynamic_handler);
c136a813 91 ff_register_dynamic_payload_handler(&opus_dynamic_handler);
e9fce261
RB
92
93 ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
94 ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
3ece3e4c
MS
95
96 ff_register_dynamic_payload_handler(&ff_qt_rtp_aud_handler);
97 ff_register_dynamic_payload_handler(&ff_qt_rtp_vid_handler);
98 ff_register_dynamic_payload_handler(&ff_quicktime_rtp_aud_handler);
99 ff_register_dynamic_payload_handler(&ff_quicktime_rtp_vid_handler);
06d7325a
MS
100
101 ff_register_dynamic_payload_handler(&ff_g726_16_dynamic_handler);
102 ff_register_dynamic_payload_handler(&ff_g726_24_dynamic_handler);
103 ff_register_dynamic_payload_handler(&ff_g726_32_dynamic_handler);
104 ff_register_dynamic_payload_handler(&ff_g726_40_dynamic_handler);
8eb793c4
LA
105}
106
1e515c42 107RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
5d471b73 108 enum AVMediaType codec_type)
1e515c42
MS
109{
110 RTPDynamicProtocolHandler *handler;
111 for (handler = RTPFirstDynamicPayloadHandler;
112 handler; handler = handler->next)
bb3244de 113 if (!av_strcasecmp(name, handler->enc_name) &&
1e515c42
MS
114 codec_type == handler->codec_type)
115 return handler;
116 return NULL;
117}
118
119RTPDynamicProtocolHandler *ff_rtp_handler_find_by_id(int id,
5d471b73 120 enum AVMediaType codec_type)
1e515c42
MS
121{
122 RTPDynamicProtocolHandler *handler;
123 for (handler = RTPFirstDynamicPayloadHandler;
124 handler; handler = handler->next)
125 if (handler->static_payload_id && handler->static_payload_id == id &&
126 codec_type == handler->codec_type)
127 return handler;
128 return NULL;
129}
130
5d471b73
MS
131static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf,
132 int len)
8eb793c4 133{
ff328c02 134 int payload_len;
07b77fe3
JB
135 while (len >= 4) {
136 payload_len = FFMIN(len, (AV_RB16(buf + 2) + 1) * 4);
137
ff328c02
JA
138 switch (buf[1]) {
139 case RTCP_SR:
07b77fe3 140 if (payload_len < 20) {
5d471b73
MS
141 av_log(NULL, AV_LOG_ERROR,
142 "Invalid length for RTCP SR packet\n");
ff328c02
JA
143 return AVERROR_INVALIDDATA;
144 }
ff328c02 145
5d471b73 146 s->last_rtcp_ntp_time = AV_RB64(buf + 8);
682d28a9 147 s->last_rtcp_timestamp = AV_RB32(buf + 16);
3a1cdcc7
MS
148 if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
149 s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
150 if (!s->base_timestamp)
151 s->base_timestamp = s->last_rtcp_timestamp;
152 s->rtcp_ts_offset = s->last_rtcp_timestamp - s->base_timestamp;
153 }
ff328c02 154
ff328c02 155 break;
b20359f5
JA
156 case RTCP_BYE:
157 return -RTCP_BYE;
ff328c02 158 }
07b77fe3
JB
159
160 buf += payload_len;
161 len -= payload_len;
ff328c02 162 }
b20359f5 163 return -1;
8eb793c4
LA
164}
165
5d471b73 166#define RTP_SEQ_MOD (1 << 16)
8eb793c4 167
48f01398 168static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
8eb793c4
LA
169{
170 memset(s, 0, sizeof(RTPStatistics));
48f01398
MS
171 s->max_seq = base_sequence;
172 s->probation = 1;
8eb793c4
LA
173}
174
48f01398 175/*
5d471b73
MS
176 * Called whenever there is a large jump in sequence numbers,
177 * or when they get out of probation...
178 */
8eb793c4
LA
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
5d471b73 192/* Returns 1 if we should handle this packet. */
8eb793c4
LA
193static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
194{
48f01398
MS
195 uint16_t udelta = seq - s->max_seq;
196 const int MAX_DROPOUT = 3000;
197 const int MAX_MISORDER = 100;
8eb793c4
LA
198 const int MIN_SEQUENTIAL = 2;
199
5d471b73
MS
200 /* source not valid until MIN_SEQUENTIAL packets with sequence
201 * seq. numbers have been received */
48f01398
MS
202 if (s->probation) {
203 if (seq == s->max_seq + 1) {
8eb793c4 204 s->probation--;
48f01398
MS
205 s->max_seq = seq;
206 if (s->probation == 0) {
8eb793c4
LA
207 rtp_init_sequence(s, seq);
208 s->received++;
209 return 1;
210 }
211 } else {
48f01398 212 s->probation = MIN_SEQUENTIAL - 1;
5d471b73 213 s->max_seq = seq;
8eb793c4
LA
214 }
215 } else if (udelta < MAX_DROPOUT) {
216 // in order, with permissible gap
48f01398
MS
217 if (seq < s->max_seq) {
218 // sequence number wrapped; count another 64k cycles
8eb793c4
LA
219 s->cycles += RTP_SEQ_MOD;
220 }
48f01398 221 s->max_seq = seq;
8eb793c4
LA
222 } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
223 // sequence made a large jump...
48f01398 224 if (seq == s->bad_seq) {
5d471b73
MS
225 /* two sequential packets -- assume that the other side
226 * restarted without telling us; just resync. */
8eb793c4
LA
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 */
5d471b73 259 /* XXX: MPEG pts hardcoded. RTCP send every 0.5 seconds */
8eb793c4
LA
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
5d471b73
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;
48f01398 285 stats->expected_prior = expected;
5d471b73 286 received_interval = stats->received - stats->received_prior;
48f01398 287 stats->received_prior = stats->received;
5d471b73 288 lost_interval = expected_interval - received_interval;
48f01398
MS
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 {
5d471b73 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?
48f01398 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 320 // padding
5d471b73 321 for (len = (6 + len) % 4; len % 4; len++)
77eb5504 322 avio_w8(pb, 0);
8eb793c4 323
b7f2fdde 324 avio_flush(pb);
6dc7d80d 325 len = avio_close_dyn_buf(pb, &buf);
8eb793c4 326 if ((len > 0) && buf) {
5e1166b3 327 int av_unused result;
dfd2a005 328 av_dlog(s->ic, "sending %d bytes of RR\n", len);
5d471b73 329 result = ffurl_write(s->rtp_ctx, buf, len);
925e908b 330 av_dlog(s->ic, "result from ffurl_write: %d\n", result);
8eb793c4
LA
331 av_free(buf);
332 }
333 return 0;
334}
335
5d471b73 336void ff_rtp_send_punch_packets(URLContext *rtp_handle)
9c8fa20d 337{
ae628ec1 338 AVIOContext *pb;
9c8fa20d
MS
339 uint8_t *buf;
340 int len;
341
342 /* Send a small RTP packet */
b92c5452 343 if (avio_open_dyn_buf(&pb) < 0)
9c8fa20d
MS
344 return;
345
77eb5504
AK
346 avio_w8(pb, (RTP_VERSION << 6));
347 avio_w8(pb, 0); /* Payload type */
348 avio_wb16(pb, 0); /* Seq */
349 avio_wb32(pb, 0); /* Timestamp */
350 avio_wb32(pb, 0); /* SSRC */
9c8fa20d 351
b7f2fdde 352 avio_flush(pb);
6dc7d80d 353 len = avio_close_dyn_buf(pb, &buf);
9c8fa20d 354 if ((len > 0) && buf)
925e908b 355 ffurl_write(rtp_handle, buf, len);
9c8fa20d
MS
356 av_free(buf);
357
358 /* Send a minimal RTCP RR */
b92c5452 359 if (avio_open_dyn_buf(&pb) < 0)
9c8fa20d
MS
360 return;
361
77eb5504
AK
362 avio_w8(pb, (RTP_VERSION << 6));
363 avio_w8(pb, RTCP_RR); /* receiver report */
364 avio_wb16(pb, 1); /* length in words - 1 */
365 avio_wb32(pb, 0); /* our own SSRC */
9c8fa20d 366
b7f2fdde 367 avio_flush(pb);
6dc7d80d 368 len = avio_close_dyn_buf(pb, &buf);
9c8fa20d 369 if ((len > 0) && buf)
925e908b 370 ffurl_write(rtp_handle, buf, len);
9c8fa20d
MS
371 av_free(buf);
372}
373
8eb793c4
LA
374/**
375 * open a new RTP parse context for stream 'st'. 'st' can be NULL for
5d471b73 376 * MPEG2-TS streams to indicate that they should be demuxed inside the
36ef5369 377 * rtp demux (otherwise AV_CODEC_ID_MPEG2TS packets are returned)
8eb793c4 378 */
5d471b73
MS
379RTPDemuxContext *ff_rtp_parse_open(AVFormatContext *s1, AVStream *st,
380 URLContext *rtpc, int payload_type,
381 int queue_size)
8eb793c4
LA
382{
383 RTPDemuxContext *s;
384
385 s = av_mallocz(sizeof(RTPDemuxContext));
386 if (!s)
387 return NULL;
5d471b73
MS
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;
5d471b73
MS
391 s->ic = s1;
392 s->st = st;
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) {
5d471b73 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;
5d471b73 435 s->parse_packet = handler->parse_packet;
99a1d191
RB
436}
437
8eb793c4 438/**
5d471b73
MS
439 * This was the second switch in rtp_parse packet.
440 * Normalizes time, if required, sets stream_index, etc.
8eb793c4
LA
441 */
442static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
443{
79d482b1
MS
444 if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
445 return; /* Timestamp already set by depacketizer */
b8a1b880
JB
446 if (timestamp == RTP_NOTS_VALUE)
447 return;
448
525c5b08 449 if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
fba7815d
LA
450 int64_t addend;
451 int delta_timestamp;
452
453 /* compute pts from timestamp with received ntp_time */
454 delta_timestamp = timestamp - s->last_rtcp_timestamp;
455 /* convert to the PTS timebase */
5d471b73
MS
456 addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time,
457 s->st->time_base.den,
458 (uint64_t) s->st->time_base.num << 32);
3a1cdcc7
MS
459 pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
460 delta_timestamp;
461 return;
fba7815d 462 }
b8a1b880 463
3a1cdcc7
MS
464 if (!s->base_timestamp)
465 s->base_timestamp = timestamp;
5d471b73
MS
466 /* assume that the difference is INT32_MIN < x < INT32_MAX,
467 * but allow the first timestamp to exceed INT32_MAX */
12348ca2
JB
468 if (!s->timestamp)
469 s->unwrapped_timestamp += timestamp;
470 else
471 s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
472 s->timestamp = timestamp;
5d471b73
MS
473 pkt->pts = s->unwrapped_timestamp + s->range_start_offset -
474 s->base_timestamp;
8eb793c4
LA
475}
476
02607418
MS
477static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
478 const uint8_t *buf, int len)
8eb793c4
LA
479{
480 unsigned int ssrc, h;
f841a0fc 481 int payload_type, seq, ret, flags = 0;
9446b4bb 482 int ext;
8eb793c4
LA
483 AVStream *st;
484 uint32_t timestamp;
5d471b73 485 int rv = 0;
8eb793c4 486
5d471b73 487 ext = buf[0] & 0x10;
8eb793c4 488 payload_type = buf[1] & 0x7f;
144ae29d
RB
489 if (buf[1] & 0x80)
490 flags |= RTP_FLAG_MARKER;
5d471b73 491 seq = AV_RB16(buf + 2);
8eb793c4 492 timestamp = AV_RB32(buf + 4);
5d471b73 493 ssrc = AV_RB32(buf + 8);
8eb793c4
LA
494 /* store the ssrc in the RTPDemuxContext */
495 s->ssrc = ssrc;
496
497 /* NOTE: we can handle only one payload type */
498 if (s->payload_type != payload_type)
499 return -1;
500
501 st = s->st;
502 // only do something with this if all the rtp checks pass...
5d471b73
MS
503 if (!rtp_valid_packet_in_sequence(&s->statistics, seq)) {
504 av_log(st ? st->codec : NULL, AV_LOG_ERROR,
505 "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
8eb793c4
LA
506 payload_type, seq, ((s->seq + 1) & 0xffff));
507 return -1;
508 }
509
4838cdab
MS
510 if (buf[0] & 0x20) {
511 int padding = buf[len - 1];
512 if (len >= 12 + padding)
513 len -= padding;
514 }
515
8eb793c4 516 s->seq = seq;
5d471b73
MS
517 len -= 12;
518 buf += 12;
8eb793c4 519
9446b4bb
RS
520 /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
521 if (ext) {
522 if (len < 4)
523 return -1;
524 /* calculate the header extension length (stored as number
525 * of 32-bit words) */
526 ext = (AV_RB16(buf + 2) + 1) << 2;
527
528 if (len < ext)
529 return -1;
530 // skip past RTP header extension
531 len -= ext;
532 buf += ext;
533 }
534
8eb793c4 535 if (!st) {
5d471b73 536 /* specific MPEG2-TS demux support */
9125806e 537 ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
946df059
MS
538 /* The only error that can be returned from ff_mpegts_parse_packet
539 * is "no more data to return from the provided buffer", so return
540 * AVERROR(EAGAIN) for all errors */
4ffff367 541 if (ret < 0)
946df059 542 return AVERROR(EAGAIN);
8eb793c4
LA
543 if (ret < len) {
544 s->read_buf_size = len - ret;
545 memcpy(s->buf, buf + ret, s->read_buf_size);
546 s->read_buf_index = 0;
547 return 1;
548 }
f3e71942 549 return 0;
b4e3330c 550 } else if (s->parse_packet) {
1a45a9f4 551 rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
9b932b8a 552 s->st, pkt, &timestamp, buf, len, flags);
8eb793c4 553 } else {
5d471b73
MS
554 /* At this point, the RTP header has been stripped;
555 * This is ASSUMING that there is only 1 CSRC, which isn't wise. */
556 switch (st->codec->codec_id) {
36ef5369
AK
557 case AV_CODEC_ID_MP2:
558 case AV_CODEC_ID_MP3:
5d471b73 559 /* better than nothing: skip MPEG audio RTP header */
8eb793c4
LA
560 if (len <= 4)
561 return -1;
5d471b73 562 h = AV_RB32(buf);
8eb793c4
LA
563 len -= 4;
564 buf += 4;
565 av_new_packet(pkt, len);
566 memcpy(pkt->data, buf, len);
567 break;
36ef5369
AK
568 case AV_CODEC_ID_MPEG1VIDEO:
569 case AV_CODEC_ID_MPEG2VIDEO:
5d471b73 570 /* better than nothing: skip MPEG video RTP header */
8eb793c4
LA
571 if (len <= 4)
572 return -1;
5d471b73 573 h = AV_RB32(buf);
8eb793c4
LA
574 buf += 4;
575 len -= 4;
576 if (h & (1 << 26)) {
5d471b73 577 /* MPEG-2 */
8eb793c4
LA
578 if (len <= 4)
579 return -1;
580 buf += 4;
581 len -= 4;
582 }
583 av_new_packet(pkt, len);
584 memcpy(pkt->data, buf, len);
585 break;
8eb793c4 586 default:
f739b36d
RB
587 av_new_packet(pkt, len);
588 memcpy(pkt->data, buf, len);
8eb793c4
LA
589 break;
590 }
eafb17d1
RB
591
592 pkt->stream_index = st->index;
f3e71942 593 }
8eb793c4 594
95f03cf3
RB
595 // now perform timestamp things....
596 finalize_packet(s, pkt, timestamp);
f3e71942 597
8eb793c4
LA
598 return rv;
599}
600
58ee0991
MS
601void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
602{
603 while (s->queue) {
604 RTPPacket *next = s->queue->next;
605 av_free(s->queue->buf);
606 av_free(s->queue);
607 s->queue = next;
608 }
609 s->seq = 0;
610 s->queue_len = 0;
611 s->prev_ret = 0;
612}
613
614static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
615{
5d471b73 616 uint16_t seq = AV_RB16(buf + 2);
58ee0991
MS
617 RTPPacket *cur = s->queue, *prev = NULL, *packet;
618
619 /* Find the correct place in the queue to insert the packet */
620 while (cur) {
621 int16_t diff = seq - cur->seq;
622 if (diff < 0)
623 break;
624 prev = cur;
5d471b73 625 cur = cur->next;
58ee0991
MS
626 }
627
628 packet = av_mallocz(sizeof(*packet));
629 if (!packet)
630 return;
631 packet->recvtime = av_gettime();
5d471b73
MS
632 packet->seq = seq;
633 packet->len = len;
634 packet->buf = buf;
635 packet->next = cur;
58ee0991
MS
636 if (prev)
637 prev->next = packet;
638 else
639 s->queue = packet;
640 s->queue_len++;
641}
642
643static int has_next_packet(RTPDemuxContext *s)
644{
ddcf8411 645 return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
58ee0991
MS
646}
647
648int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
649{
650 return s->queue ? s->queue->recvtime : 0;
651}
652
653static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
654{
655 int rv;
656 RTPPacket *next;
657
658 if (s->queue_len <= 0)
659 return -1;
660
661 if (!has_next_packet(s))
662 av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
663 "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
664
665 /* Parse the first packet in the queue, and dequeue it */
5d471b73 666 rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
58ee0991
MS
667 next = s->queue->next;
668 av_free(s->queue->buf);
669 av_free(s->queue);
670 s->queue = next;
671 s->queue_len--;
4ffff367 672 return rv;
58ee0991
MS
673}
674
4ffff367 675static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
48f01398 676 uint8_t **bufptr, int len)
02607418 677{
5d471b73 678 uint8_t *buf = bufptr ? *bufptr : NULL;
02607418
MS
679 int ret, flags = 0;
680 uint32_t timestamp;
5d471b73 681 int rv = 0;
02607418
MS
682
683 if (!buf) {
f6e138b4
MS
684 /* If parsing of the previous packet actually returned 0 or an error,
685 * there's nothing more to be parsed from that packet, but we may have
58ee0991 686 * indicated that we can return the next enqueued packet. */
f6e138b4 687 if (s->prev_ret <= 0)
58ee0991 688 return rtp_parse_queued_packet(s, pkt);
02607418 689 /* return the next packets, if any */
5d471b73 690 if (s->st && s->parse_packet) {
02607418
MS
691 /* timestamp should be overwritten by parse_packet, if not,
692 * the packet is left with pts == AV_NOPTS_VALUE */
693 timestamp = RTP_NOTS_VALUE;
5d471b73
MS
694 rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
695 s->st, pkt, &timestamp, NULL, 0, flags);
02607418 696 finalize_packet(s, pkt, timestamp);
4ffff367 697 return rv;
02607418
MS
698 } else {
699 // TODO: Move to a dynamic packet handler (like above)
4ffff367 700 if (s->read_buf_index >= s->read_buf_size)
91ec7aea 701 return AVERROR(EAGAIN);
02607418 702 ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
5d471b73 703 s->read_buf_size - s->read_buf_index);
4ffff367 704 if (ret < 0)
946df059 705 return AVERROR(EAGAIN);
02607418
MS
706 s->read_buf_index += ret;
707 if (s->read_buf_index < s->read_buf_size)
708 return 1;
4ffff367
MS
709 else
710 return 0;
02607418
MS
711 }
712 }
713
714 if (len < 12)
715 return -1;
716
717 if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
718 return -1;
298a587f 719 if (RTP_PT_IS_RTCP(buf[1])) {
02607418
MS
720 return rtcp_parse_packet(s, buf, len);
721 }
722
65cdee9c 723 if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
58ee0991
MS
724 /* First packet, or no reordering */
725 return rtp_parse_packet_internal(s, pkt, buf, len);
726 } else {
727 uint16_t seq = AV_RB16(buf + 2);
728 int16_t diff = seq - s->seq;
729 if (diff < 0) {
730 /* Packet older than the previously emitted one, drop */
731 av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
732 "RTP: dropping old packet received too late\n");
733 return -1;
734 } else if (diff <= 1) {
735 /* Correct packet */
736 rv = rtp_parse_packet_internal(s, pkt, buf, len);
4ffff367 737 return rv;
58ee0991
MS
738 } else {
739 /* Still missing some packet, enqueue this one. */
740 enqueue_packet(s, buf, len);
741 *bufptr = NULL;
742 /* Return the first enqueued packet if the queue is full,
743 * even if we're missing something */
744 if (s->queue_len >= s->queue_size)
745 return rtp_parse_queued_packet(s, pkt);
746 return -1;
747 }
748 }
02607418
MS
749}
750
4ffff367
MS
751/**
752 * Parse an RTP or RTCP packet directly sent as a buffer.
753 * @param s RTP parse context.
754 * @param pkt returned packet
755 * @param bufptr pointer to the input buffer or NULL to read the next packets
756 * @param len buffer len
757 * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
758 * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
759 */
bfc6db44
MS
760int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
761 uint8_t **bufptr, int len)
4ffff367
MS
762{
763 int rv = rtp_parse_one_packet(s, pkt, bufptr, len);
764 s->prev_ret = rv;
d678a6fd
MS
765 while (rv == AVERROR(EAGAIN) && has_next_packet(s))
766 rv = rtp_parse_queued_packet(s, pkt);
4ffff367
MS
767 return rv ? rv : has_next_packet(s);
768}
769
bfc6db44 770void ff_rtp_parse_close(RTPDemuxContext *s)
8eb793c4 771{
58ee0991 772 ff_rtp_reset_packet_queue(s);
8eb793c4 773 if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
9125806e 774 ff_mpegts_parse_close(s->ts);
8eb793c4
LA
775 }
776 av_free(s);
777}
016bc031
JA
778
779int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
780 int (*parse_fmtp)(AVStream *stream,
781 PayloadContext *data,
782 char *attr, char *value))
783{
784 char attr[256];
824535e3 785 char *value;
016bc031 786 int res;
824535e3
JA
787 int value_size = strlen(p) + 1;
788
789 if (!(value = av_malloc(value_size))) {
c3e15f7b 790 av_log(NULL, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
824535e3
JA
791 return AVERROR(ENOMEM);
792 }
016bc031
JA
793
794 // remove protocol identifier
5d471b73
MS
795 while (*p && *p == ' ')
796 p++; // strip spaces
797 while (*p && *p != ' ')
798 p++; // eat protocol identifier
799 while (*p && *p == ' ')
800 p++; // strip trailing spaces
016bc031
JA
801
802 while (ff_rtsp_next_attr_and_value(&p,
803 attr, sizeof(attr),
824535e3 804 value, value_size)) {
016bc031 805 res = parse_fmtp(stream, data, attr, value);
824535e3
JA
806 if (res < 0 && res != AVERROR_PATCHWELCOME) {
807 av_free(value);
016bc031 808 return res;
824535e3 809 }
016bc031 810 }
824535e3 811 av_free(value);
016bc031
JA
812 return 0;
813}
179a5c37
AK
814
815int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
816{
817 av_init_packet(pkt);
818
5d471b73 819 pkt->size = avio_close_dyn_buf(*dyn_buf, &pkt->data);
179a5c37
AK
820 pkt->stream_index = stream_idx;
821 pkt->destruct = av_destruct_packet;
5d471b73 822 *dyn_buf = NULL;
179a5c37
AK
823 return pkt->size;
824}