FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
rtpdec.c
Go to the documentation of this file.
1 /*
2  * RTP input format
3  * Copyright (c) 2002 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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/intreadwrite.h"
25 #include "libavutil/time.h"
26 
27 #include "avformat.h"
28 #include "network.h"
29 #include "srtp.h"
30 #include "url.h"
31 #include "rtpdec.h"
32 #include "rtpdec_formats.h"
33 
34 #define MIN_FEEDBACK_INTERVAL 200000 /* 200 ms in us */
35 
37  .enc_name = "GSM",
38  .codec_type = AVMEDIA_TYPE_AUDIO,
39  .codec_id = AV_CODEC_ID_GSM,
40 };
41 
43  .enc_name = "X-MP3-draft-00",
44  .codec_type = AVMEDIA_TYPE_AUDIO,
45  .codec_id = AV_CODEC_ID_MP3ADU,
46 };
47 
49  .enc_name = "speex",
50  .codec_type = AVMEDIA_TYPE_AUDIO,
51  .codec_id = AV_CODEC_ID_SPEEX,
52 };
53 
55  .enc_name = "opus",
56  .codec_type = AVMEDIA_TYPE_AUDIO,
57  .codec_id = AV_CODEC_ID_OPUS,
58 };
59 
61  .enc_name = "t140",
62  .codec_type = AVMEDIA_TYPE_SUBTITLE,
63  .codec_id = AV_CODEC_ID_TEXT,
64 };
65 
67 
69 {
71  rtp_first_dynamic_payload_handler = handler;
72 }
73 
75 {
117  ff_register_dynamic_payload_handler(&gsm_dynamic_handler);
118  ff_register_dynamic_payload_handler(&opus_dynamic_handler);
119  ff_register_dynamic_payload_handler(&realmedia_mp3_dynamic_handler);
120  ff_register_dynamic_payload_handler(&speex_dynamic_handler);
121  ff_register_dynamic_payload_handler(&t140_dynamic_handler);
122 }
123 
125  enum AVMediaType codec_type)
126 {
128  for (handler = rtp_first_dynamic_payload_handler;
129  handler; handler = handler->next)
130  if (handler->enc_name &&
131  !av_strcasecmp(name, handler->enc_name) &&
132  codec_type == handler->codec_type)
133  return handler;
134  return NULL;
135 }
136 
138  enum AVMediaType codec_type)
139 {
141  for (handler = rtp_first_dynamic_payload_handler;
142  handler; handler = handler->next)
143  if (handler->static_payload_id && handler->static_payload_id == id &&
144  codec_type == handler->codec_type)
145  return handler;
146  return NULL;
147 }
148 
149 static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf,
150  int len)
151 {
152  int payload_len;
153  while (len >= 4) {
154  payload_len = FFMIN(len, (AV_RB16(buf + 2) + 1) * 4);
155 
156  switch (buf[1]) {
157  case RTCP_SR:
158  if (payload_len < 20) {
159  av_log(s->ic, AV_LOG_ERROR, "Invalid RTCP SR packet length\n");
160  return AVERROR_INVALIDDATA;
161  }
162 
164  s->last_rtcp_ntp_time = AV_RB64(buf + 8);
165  s->last_rtcp_timestamp = AV_RB32(buf + 16);
168  if (!s->base_timestamp)
171  }
172 
173  break;
174  case RTCP_BYE:
175  return -RTCP_BYE;
176  }
177 
178  buf += payload_len;
179  len -= payload_len;
180  }
181  return -1;
182 }
183 
184 #define RTP_SEQ_MOD (1 << 16)
185 
186 static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
187 {
188  memset(s, 0, sizeof(RTPStatistics));
189  s->max_seq = base_sequence;
190  s->probation = 1;
191 }
192 
193 /*
194  * Called whenever there is a large jump in sequence numbers,
195  * or when they get out of probation...
196  */
197 static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
198 {
199  s->max_seq = seq;
200  s->cycles = 0;
201  s->base_seq = seq - 1;
202  s->bad_seq = RTP_SEQ_MOD + 1;
203  s->received = 0;
204  s->expected_prior = 0;
205  s->received_prior = 0;
206  s->jitter = 0;
207  s->transit = 0;
208 }
209 
210 /* Returns 1 if we should handle this packet. */
211 static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
212 {
213  uint16_t udelta = seq - s->max_seq;
214  const int MAX_DROPOUT = 3000;
215  const int MAX_MISORDER = 100;
216  const int MIN_SEQUENTIAL = 2;
217 
218  /* source not valid until MIN_SEQUENTIAL packets with sequence
219  * seq. numbers have been received */
220  if (s->probation) {
221  if (seq == s->max_seq + 1) {
222  s->probation--;
223  s->max_seq = seq;
224  if (s->probation == 0) {
225  rtp_init_sequence(s, seq);
226  s->received++;
227  return 1;
228  }
229  } else {
230  s->probation = MIN_SEQUENTIAL - 1;
231  s->max_seq = seq;
232  }
233  } else if (udelta < MAX_DROPOUT) {
234  // in order, with permissible gap
235  if (seq < s->max_seq) {
236  // sequence number wrapped; count another 64k cycles
237  s->cycles += RTP_SEQ_MOD;
238  }
239  s->max_seq = seq;
240  } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
241  // sequence made a large jump...
242  if (seq == s->bad_seq) {
243  /* two sequential packets -- assume that the other side
244  * restarted without telling us; just resync. */
245  rtp_init_sequence(s, seq);
246  } else {
247  s->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1);
248  return 0;
249  }
250  } else {
251  // duplicate or reordered packet...
252  }
253  s->received++;
254  return 1;
255 }
256 
257 static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp,
258  uint32_t arrival_timestamp)
259 {
260  // Most of this is pretty straight from RFC 3550 appendix A.8
261  uint32_t transit = arrival_timestamp - sent_timestamp;
262  uint32_t prev_transit = s->transit;
263  int32_t d = transit - prev_transit;
264  // Doing the FFABS() call directly on the "transit - prev_transit"
265  // expression doesn't work, since it's an unsigned expression. Doing the
266  // transit calculation in unsigned is desired though, since it most
267  // probably will need to wrap around.
268  d = FFABS(d);
269  s->transit = transit;
270  if (!prev_transit)
271  return;
272  s->jitter += d - (int32_t) ((s->jitter + 8) >> 4);
273 }
274 
276  AVIOContext *avio, int count)
277 {
278  AVIOContext *pb;
279  uint8_t *buf;
280  int len;
281  int rtcp_bytes;
283  uint32_t lost;
284  uint32_t extended_max;
285  uint32_t expected_interval;
286  uint32_t received_interval;
287  int32_t lost_interval;
288  uint32_t expected;
289  uint32_t fraction;
290 
291  if ((!fd && !avio) || (count < 1))
292  return -1;
293 
294  /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
295  /* XXX: MPEG pts hardcoded. RTCP send every 0.5 seconds */
296  s->octet_count += count;
297  rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
299  rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
300  if (rtcp_bytes < 28)
301  return -1;
303 
304  if (!fd)
305  pb = avio;
306  else if (avio_open_dyn_buf(&pb) < 0)
307  return -1;
308 
309  // Receiver Report
310  avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
311  avio_w8(pb, RTCP_RR);
312  avio_wb16(pb, 7); /* length in words - 1 */
313  // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
314  avio_wb32(pb, s->ssrc + 1);
315  avio_wb32(pb, s->ssrc); // server SSRC
316  // some placeholders we should really fill...
317  // RFC 1889/p64
318  extended_max = stats->cycles + stats->max_seq;
319  expected = extended_max - stats->base_seq;
320  lost = expected - stats->received;
321  lost = FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
322  expected_interval = expected - stats->expected_prior;
323  stats->expected_prior = expected;
324  received_interval = stats->received - stats->received_prior;
325  stats->received_prior = stats->received;
326  lost_interval = expected_interval - received_interval;
327  if (expected_interval == 0 || lost_interval <= 0)
328  fraction = 0;
329  else
330  fraction = (lost_interval << 8) / expected_interval;
331 
332  fraction = (fraction << 24) | lost;
333 
334  avio_wb32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
335  avio_wb32(pb, extended_max); /* max sequence received */
336  avio_wb32(pb, stats->jitter >> 4); /* jitter */
337 
339  avio_wb32(pb, 0); /* last SR timestamp */
340  avio_wb32(pb, 0); /* delay since last SR */
341  } else {
342  uint32_t middle_32_bits = s->last_rtcp_ntp_time >> 16; // this is valid, right? do we need to handle 64 bit values special?
343  uint32_t delay_since_last = av_rescale(av_gettime_relative() - s->last_rtcp_reception_time,
344  65536, AV_TIME_BASE);
345 
346  avio_wb32(pb, middle_32_bits); /* last SR timestamp */
347  avio_wb32(pb, delay_since_last); /* delay since last SR */
348  }
349 
350  // CNAME
351  avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
352  avio_w8(pb, RTCP_SDES);
353  len = strlen(s->hostname);
354  avio_wb16(pb, (7 + len + 3) / 4); /* length in words - 1 */
355  avio_wb32(pb, s->ssrc + 1);
356  avio_w8(pb, 0x01);
357  avio_w8(pb, len);
358  avio_write(pb, s->hostname, len);
359  avio_w8(pb, 0); /* END */
360  // padding
361  for (len = (7 + len) % 4; len % 4; len++)
362  avio_w8(pb, 0);
363 
364  avio_flush(pb);
365  if (!fd)
366  return 0;
367  len = avio_close_dyn_buf(pb, &buf);
368  if ((len > 0) && buf) {
369  int av_unused result;
370  av_log(s->ic, AV_LOG_TRACE, "sending %d bytes of RR\n", len);
371  result = ffurl_write(fd, buf, len);
372  av_log(s->ic, AV_LOG_TRACE, "result from ffurl_write: %d\n", result);
373  av_free(buf);
374  }
375  return 0;
376 }
377 
379 {
380  AVIOContext *pb;
381  uint8_t *buf;
382  int len;
383 
384  /* Send a small RTP packet */
385  if (avio_open_dyn_buf(&pb) < 0)
386  return;
387 
388  avio_w8(pb, (RTP_VERSION << 6));
389  avio_w8(pb, 0); /* Payload type */
390  avio_wb16(pb, 0); /* Seq */
391  avio_wb32(pb, 0); /* Timestamp */
392  avio_wb32(pb, 0); /* SSRC */
393 
394  avio_flush(pb);
395  len = avio_close_dyn_buf(pb, &buf);
396  if ((len > 0) && buf)
397  ffurl_write(rtp_handle, buf, len);
398  av_free(buf);
399 
400  /* Send a minimal RTCP RR */
401  if (avio_open_dyn_buf(&pb) < 0)
402  return;
403 
404  avio_w8(pb, (RTP_VERSION << 6));
405  avio_w8(pb, RTCP_RR); /* receiver report */
406  avio_wb16(pb, 1); /* length in words - 1 */
407  avio_wb32(pb, 0); /* our own SSRC */
408 
409  avio_flush(pb);
410  len = avio_close_dyn_buf(pb, &buf);
411  if ((len > 0) && buf)
412  ffurl_write(rtp_handle, buf, len);
413  av_free(buf);
414 }
415 
416 static int find_missing_packets(RTPDemuxContext *s, uint16_t *first_missing,
417  uint16_t *missing_mask)
418 {
419  int i;
420  uint16_t next_seq = s->seq + 1;
421  RTPPacket *pkt = s->queue;
422 
423  if (!pkt || pkt->seq == next_seq)
424  return 0;
425 
426  *missing_mask = 0;
427  for (i = 1; i <= 16; i++) {
428  uint16_t missing_seq = next_seq + i;
429  while (pkt) {
430  int16_t diff = pkt->seq - missing_seq;
431  if (diff >= 0)
432  break;
433  pkt = pkt->next;
434  }
435  if (!pkt)
436  break;
437  if (pkt->seq == missing_seq)
438  continue;
439  *missing_mask |= 1 << (i - 1);
440  }
441 
442  *first_missing = next_seq;
443  return 1;
444 }
445 
447  AVIOContext *avio)
448 {
449  int len, need_keyframe, missing_packets;
450  AVIOContext *pb;
451  uint8_t *buf;
452  int64_t now;
453  uint16_t first_missing = 0, missing_mask = 0;
454 
455  if (!fd && !avio)
456  return -1;
457 
458  need_keyframe = s->handler && s->handler->need_keyframe &&
460  missing_packets = find_missing_packets(s, &first_missing, &missing_mask);
461 
462  if (!need_keyframe && !missing_packets)
463  return 0;
464 
465  /* Send new feedback if enough time has elapsed since the last
466  * feedback packet. */
467 
468  now = av_gettime_relative();
469  if (s->last_feedback_time &&
471  return 0;
472  s->last_feedback_time = now;
473 
474  if (!fd)
475  pb = avio;
476  else if (avio_open_dyn_buf(&pb) < 0)
477  return -1;
478 
479  if (need_keyframe) {
480  avio_w8(pb, (RTP_VERSION << 6) | 1); /* PLI */
481  avio_w8(pb, RTCP_PSFB);
482  avio_wb16(pb, 2); /* length in words - 1 */
483  // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
484  avio_wb32(pb, s->ssrc + 1);
485  avio_wb32(pb, s->ssrc); // server SSRC
486  }
487 
488  if (missing_packets) {
489  avio_w8(pb, (RTP_VERSION << 6) | 1); /* NACK */
490  avio_w8(pb, RTCP_RTPFB);
491  avio_wb16(pb, 3); /* length in words - 1 */
492  avio_wb32(pb, s->ssrc + 1);
493  avio_wb32(pb, s->ssrc); // server SSRC
494 
495  avio_wb16(pb, first_missing);
496  avio_wb16(pb, missing_mask);
497  }
498 
499  avio_flush(pb);
500  if (!fd)
501  return 0;
502  len = avio_close_dyn_buf(pb, &buf);
503  if (len > 0 && buf) {
504  ffurl_write(fd, buf, len);
505  av_free(buf);
506  }
507  return 0;
508 }
509 
510 /**
511  * open a new RTP parse context for stream 'st'. 'st' can be NULL for
512  * MPEG-2 TS streams.
513  */
515  int payload_type, int queue_size)
516 {
518 
519  s = av_mallocz(sizeof(RTPDemuxContext));
520  if (!s)
521  return NULL;
522  s->payload_type = payload_type;
525  s->ic = s1;
526  s->st = st;
527  s->queue_size = queue_size;
528 
529  av_log(s->ic, AV_LOG_VERBOSE, "setting jitter buffer size to %d\n",
530  s->queue_size);
531 
533  if (st) {
534  switch (st->codecpar->codec_id) {
536  /* According to RFC 3551, the stream clock rate is 8000
537  * even if the sample rate is 16000. */
538  if (st->codecpar->sample_rate == 8000)
539  st->codecpar->sample_rate = 16000;
540  break;
541  default:
542  break;
543  }
544  }
545  // needed to send back RTCP RR in RTSP sessions
546  gethostname(s->hostname, sizeof(s->hostname));
547  return s;
548 }
549 
552 {
554  s->handler = handler;
555 }
556 
557 void ff_rtp_parse_set_crypto(RTPDemuxContext *s, const char *suite,
558  const char *params)
559 {
560  if (!ff_srtp_set_crypto(&s->srtp, suite, params))
561  s->srtp_enabled = 1;
562 }
563 
564 /**
565  * This was the second switch in rtp_parse packet.
566  * Normalizes time, if required, sets stream_index, etc.
567  */
568 static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
569 {
570  if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
571  return; /* Timestamp already set by depacketizer */
572  if (timestamp == RTP_NOTS_VALUE)
573  return;
574 
575  if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
576  int64_t addend;
577  int delta_timestamp;
578 
579  /* compute pts from timestamp with received ntp_time */
580  delta_timestamp = timestamp - s->last_rtcp_timestamp;
581  /* convert to the PTS timebase */
583  s->st->time_base.den,
584  (uint64_t) s->st->time_base.num << 32);
585  pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
586  delta_timestamp;
587  return;
588  }
589 
590  if (!s->base_timestamp)
591  s->base_timestamp = timestamp;
592  /* assume that the difference is INT32_MIN < x < INT32_MAX,
593  * but allow the first timestamp to exceed INT32_MAX */
594  if (!s->timestamp)
595  s->unwrapped_timestamp += timestamp;
596  else
597  s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
598  s->timestamp = timestamp;
600  s->base_timestamp;
601 }
602 
604  const uint8_t *buf, int len)
605 {
606  unsigned int ssrc;
607  int payload_type, seq, flags = 0;
608  int ext, csrc;
609  AVStream *st;
610  uint32_t timestamp;
611  int rv = 0;
612 
613  csrc = buf[0] & 0x0f;
614  ext = buf[0] & 0x10;
615  payload_type = buf[1] & 0x7f;
616  if (buf[1] & 0x80)
617  flags |= RTP_FLAG_MARKER;
618  seq = AV_RB16(buf + 2);
619  timestamp = AV_RB32(buf + 4);
620  ssrc = AV_RB32(buf + 8);
621  /* store the ssrc in the RTPDemuxContext */
622  s->ssrc = ssrc;
623 
624  /* NOTE: we can handle only one payload type */
625  if (s->payload_type != payload_type)
626  return -1;
627 
628  st = s->st;
629  // only do something with this if all the rtp checks pass...
630  if (!rtp_valid_packet_in_sequence(&s->statistics, seq)) {
631  av_log(s->ic, AV_LOG_ERROR,
632  "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
633  payload_type, seq, ((s->seq + 1) & 0xffff));
634  return -1;
635  }
636 
637  if (buf[0] & 0x20) {
638  int padding = buf[len - 1];
639  if (len >= 12 + padding)
640  len -= padding;
641  }
642 
643  s->seq = seq;
644  len -= 12;
645  buf += 12;
646 
647  len -= 4 * csrc;
648  buf += 4 * csrc;
649  if (len < 0)
650  return AVERROR_INVALIDDATA;
651 
652  /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
653  if (ext) {
654  if (len < 4)
655  return -1;
656  /* calculate the header extension length (stored as number
657  * of 32-bit words) */
658  ext = (AV_RB16(buf + 2) + 1) << 2;
659 
660  if (len < ext)
661  return -1;
662  // skip past RTP header extension
663  len -= ext;
664  buf += ext;
665  }
666 
667  if (s->handler && s->handler->parse_packet) {
669  s->st, pkt, &timestamp, buf, len, seq,
670  flags);
671  } else if (st) {
672  if ((rv = av_new_packet(pkt, len)) < 0)
673  return rv;
674  memcpy(pkt->data, buf, len);
675  pkt->stream_index = st->index;
676  } else {
677  return AVERROR(EINVAL);
678  }
679 
680  // now perform timestamp things....
681  finalize_packet(s, pkt, timestamp);
682 
683  return rv;
684 }
685 
687 {
688  while (s->queue) {
689  RTPPacket *next = s->queue->next;
690  av_freep(&s->queue->buf);
691  av_freep(&s->queue);
692  s->queue = next;
693  }
694  s->seq = 0;
695  s->queue_len = 0;
696  s->prev_ret = 0;
697 }
698 
700 {
701  uint16_t seq = AV_RB16(buf + 2);
702  RTPPacket **cur = &s->queue, *packet;
703 
704  /* Find the correct place in the queue to insert the packet */
705  while (*cur) {
706  int16_t diff = seq - (*cur)->seq;
707  if (diff < 0)
708  break;
709  cur = &(*cur)->next;
710  }
711 
712  packet = av_mallocz(sizeof(*packet));
713  if (!packet)
714  return AVERROR(ENOMEM);
715  packet->recvtime = av_gettime_relative();
716  packet->seq = seq;
717  packet->len = len;
718  packet->buf = buf;
719  packet->next = *cur;
720  *cur = packet;
721  s->queue_len++;
722 
723  return 0;
724 }
725 
727 {
728  return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
729 }
730 
732 {
733  return s->queue ? s->queue->recvtime : 0;
734 }
735 
737 {
738  int rv;
739  RTPPacket *next;
740 
741  if (s->queue_len <= 0)
742  return -1;
743 
744  if (!has_next_packet(s))
746  "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
747 
748  /* Parse the first packet in the queue, and dequeue it */
749  rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
750  next = s->queue->next;
751  av_freep(&s->queue->buf);
752  av_freep(&s->queue);
753  s->queue = next;
754  s->queue_len--;
755  return rv;
756 }
757 
759  uint8_t **bufptr, int len)
760 {
761  uint8_t *buf = bufptr ? *bufptr : NULL;
762  int flags = 0;
763  uint32_t timestamp;
764  int rv = 0;
765 
766  if (!buf) {
767  /* If parsing of the previous packet actually returned 0 or an error,
768  * there's nothing more to be parsed from that packet, but we may have
769  * indicated that we can return the next enqueued packet. */
770  if (s->prev_ret <= 0)
771  return rtp_parse_queued_packet(s, pkt);
772  /* return the next packets, if any */
773  if (s->handler && s->handler->parse_packet) {
774  /* timestamp should be overwritten by parse_packet, if not,
775  * the packet is left with pts == AV_NOPTS_VALUE */
776  timestamp = RTP_NOTS_VALUE;
778  s->st, pkt, &timestamp, NULL, 0, 0,
779  flags);
780  finalize_packet(s, pkt, timestamp);
781  return rv;
782  }
783  }
784 
785  if (len < 12)
786  return -1;
787 
788  if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
789  return -1;
790  if (RTP_PT_IS_RTCP(buf[1])) {
791  return rtcp_parse_packet(s, buf, len);
792  }
793 
794  if (s->st) {
795  int64_t received = av_gettime_relative();
796  uint32_t arrival_ts = av_rescale_q(received, AV_TIME_BASE_Q,
797  s->st->time_base);
798  timestamp = AV_RB32(buf + 4);
799  // Calculate the jitter immediately, before queueing the packet
800  // into the reordering queue.
801  rtcp_update_jitter(&s->statistics, timestamp, arrival_ts);
802  }
803 
804  if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
805  /* First packet, or no reordering */
806  return rtp_parse_packet_internal(s, pkt, buf, len);
807  } else {
808  uint16_t seq = AV_RB16(buf + 2);
809  int16_t diff = seq - s->seq;
810  if (diff < 0) {
811  /* Packet older than the previously emitted one, drop */
813  "RTP: dropping old packet received too late\n");
814  return -1;
815  } else if (diff <= 1) {
816  /* Correct packet */
817  rv = rtp_parse_packet_internal(s, pkt, buf, len);
818  return rv;
819  } else {
820  /* Still missing some packet, enqueue this one. */
821  rv = enqueue_packet(s, buf, len);
822  if (rv < 0)
823  return rv;
824  *bufptr = NULL;
825  /* Return the first enqueued packet if the queue is full,
826  * even if we're missing something */
827  if (s->queue_len >= s->queue_size) {
828  av_log(s->ic, AV_LOG_WARNING, "jitter buffer full\n");
829  return rtp_parse_queued_packet(s, pkt);
830  }
831  return -1;
832  }
833  }
834 }
835 
836 /**
837  * Parse an RTP or RTCP packet directly sent as a buffer.
838  * @param s RTP parse context.
839  * @param pkt returned packet
840  * @param bufptr pointer to the input buffer or NULL to read the next packets
841  * @param len buffer len
842  * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
843  * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
844  */
846  uint8_t **bufptr, int len)
847 {
848  int rv;
849  if (s->srtp_enabled && bufptr && ff_srtp_decrypt(&s->srtp, *bufptr, &len) < 0)
850  return -1;
851  rv = rtp_parse_one_packet(s, pkt, bufptr, len);
852  s->prev_ret = rv;
853  while (rv < 0 && has_next_packet(s))
854  rv = rtp_parse_queued_packet(s, pkt);
855  return rv ? rv : has_next_packet(s);
856 }
857 
859 {
861  ff_srtp_free(&s->srtp);
862  av_free(s);
863 }
864 
866  AVStream *stream, PayloadContext *data, const char *p,
867  int (*parse_fmtp)(AVFormatContext *s,
868  AVStream *stream,
869  PayloadContext *data,
870  const char *attr, const char *value))
871 {
872  char attr[256];
873  char *value;
874  int res;
875  int value_size = strlen(p) + 1;
876 
877  if (!(value = av_malloc(value_size))) {
878  av_log(s, AV_LOG_ERROR, "Failed to allocate data for FMTP.\n");
879  return AVERROR(ENOMEM);
880  }
881 
882  // remove protocol identifier
883  while (*p && *p == ' ')
884  p++; // strip spaces
885  while (*p && *p != ' ')
886  p++; // eat protocol identifier
887  while (*p && *p == ' ')
888  p++; // strip trailing spaces
889 
890  while (ff_rtsp_next_attr_and_value(&p,
891  attr, sizeof(attr),
892  value, value_size)) {
893  res = parse_fmtp(s, stream, data, attr, value);
894  if (res < 0 && res != AVERROR_PATCHWELCOME) {
895  av_free(value);
896  return res;
897  }
898  }
899  av_free(value);
900  return 0;
901 }
902 
903 int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
904 {
905  int ret;
906  av_init_packet(pkt);
907 
908  pkt->size = avio_close_dyn_buf(*dyn_buf, &pkt->data);
909  pkt->stream_index = stream_idx;
910  *dyn_buf = NULL;
911  if ((ret = av_packet_from_data(pkt, pkt->data, pkt->size)) < 0) {
912  av_freep(&pkt->data);
913  return ret;
914  }
915  return pkt->size;
916 }
int queue_size
The size of queue, or 0 if reordering is disabled.
Definition: rtpdec.h:174
RTPDynamicProtocolHandler ff_g726le_24_dynamic_handler
#define NULL
Definition: coverity.c:32
void ff_rtp_parse_set_crypto(RTPDemuxContext *s, const char *suite, const char *params)
Definition: rtpdec.c:557
const char * s
Definition: avisynth_c.h:768
Bytestream IO Context.
Definition: avio.h:147
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
AVFormatContext * ic
Definition: rtpdec.h:150
uint16_t seq
Definition: rtpdec.h:154
RTPDynamicProtocolHandler ff_quicktime_rtp_aud_handler
void ff_rtp_send_punch_packets(URLContext *rtp_handle)
Send a dummy packet on both port pairs to set up the connection state in potential NAT routers...
Definition: rtpdec.c:378
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1280
ptrdiff_t const GLvoid * data
Definition: opengl_enc.c:101
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp, uint32_t arrival_timestamp)
Definition: rtpdec.c:257
int ffurl_write(URLContext *h, const unsigned char *buf, int size)
Write size bytes from buf to the resource accessed by h.
Definition: avio.c:421
int payload_type
Definition: rtpdec.h:152
int64_t range_start_offset
Definition: rtpdec.h:159
int prev_ret
Fields for packet reordering.
Definition: rtpdec.h:171
RTP/JPEG specific private data.
Definition: rdt.c:83
int64_t last_feedback_time
Definition: rtpdec.h:188
unsigned int last_octet_count
Definition: rtpdec.h:187
static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt, const uint8_t *buf, int len)
Definition: rtpdec.c:603
RTPPacket * queue
A sorted queue of buffered packets not yet returned.
Definition: rtpdec.h:172
#define RTP_VERSION
Definition: rtp.h:78
static int parse_fmtp(AVFormatContext *s, AVStream *stream, PayloadContext *data, const char *attr, const char *value)
Definition: rtpdec_latm.c:131
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3980
RTPDynamicProtocolHandler ff_mp4a_latm_dynamic_handler
Definition: rtpdec_latm.c:165
int num
Numerator.
Definition: rational.h:59
int index
stream index in AVFormatContext
Definition: avformat.h:890
int size
Definition: avcodec.h:1602
RTPDynamicProtocolHandler ff_ms_rtp_asf_pfa_handler
#define RTCP_TX_RATIO_NUM
Definition: rtp.h:82
const RTPDynamicProtocolHandler * handler
Definition: rtpdec.h:191
enum AVMediaType codec_type
Definition: rtp.c:37
static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
Definition: rtpdec.c:149
RTPDynamicProtocolHandler ff_jpeg_dynamic_handler
Definition: rtpdec_jpeg.c:382
RTPDynamicProtocolHandler ff_h263_1998_dynamic_handler
Definition: rtpdec_h263.c:92
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:252
static AVPacket pkt
RTPDynamicProtocolHandler ff_amr_wb_dynamic_handler
Definition: rtpdec_amr.c:195
uint64_t last_rtcp_ntp_time
Definition: rtpdec.h:178
uint32_t cycles
shifted count of sequence number cycles
Definition: rtpdec.h:81
#define RTCP_TX_RATIO_DEN
Definition: rtp.h:83
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_WB32 unsigned int_TMPL AV_WB24 unsigned int_TMPL AV_RB16
Definition: bytestream.h:87
static RTPDynamicProtocolHandler speex_dynamic_handler
Definition: rtpdec.c:48
RTPDynamicProtocolHandler ff_h263_2000_dynamic_handler
Definition: rtpdec_h263.c:100
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1268
static int find_missing_packets(RTPDemuxContext *s, uint16_t *first_missing, uint16_t *missing_mask)
Definition: rtpdec.c:416
enum AVMediaType codec_type
Definition: rtpdec.h:117
RTPDemuxContext * ff_rtp_parse_open(AVFormatContext *s1, AVStream *st, int payload_type, int queue_size)
open a new RTP parse context for stream 'st'.
Definition: rtpdec.c:514
PayloadContext * dynamic_protocol_context
Definition: rtpdec.h:192
Format I/O context.
Definition: avformat.h:1338
uint64_t first_rtcp_ntp_time
Definition: rtpdec.h:180
static RTPDynamicProtocolHandler gsm_dynamic_handler
Definition: rtpdec.c:36
uint32_t base_seq
base sequence number
Definition: rtpdec.h:82
void ff_srtp_free(struct SRTPContext *s)
Definition: srtp.c:31
uint8_t
#define av_malloc(s)
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:202
void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
Definition: rtpdec.c:686
RTPDynamicProtocolHandler ff_ilbc_dynamic_handler
Definition: rtpdec_ilbc.c:69
int len
Definition: rtpdec.h:144
int av_packet_from_data(AVPacket *pkt, uint8_t *data, int size)
Initialize a reference-counted packet from av_malloc()ed data.
Definition: avpacket.c:152
static void handler(vbi_event *ev, void *user_data)
RTPDynamicProtocolHandler ff_dv_dynamic_handler
Definition: rtpdec_dv.c:134
int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size)
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_RB32
Definition: bytestream.h:87
RTPDynamicProtocolHandler ff_theora_dynamic_handler
Definition: rtpdec_xiph.c:370
uint8_t * data
Definition: avcodec.h:1601
void ff_register_rtp_dynamic_payload_handlers(void)
Definition: rtpdec.c:74
Definition: rtp.h:99
static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
Definition: rtpdec.c:736
RTPDynamicProtocolHandler ff_mpeg_audio_robust_dynamic_handler
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
char hostname[256]
Definition: rtpdec.h:162
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:204
uint32_t expected_prior
packets expected in last interval
Definition: rtpdec.h:86
#define av_log(a,...)
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
int srtp_enabled
Definition: rtpdec.h:164
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition: avpacket.c:86
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
uint16_t seq
Definition: rtpdec.h:142
#define RTP_FLAG_MARKER
RTP marker bit was set for this packet.
Definition: rtpdec.h:93
#define AVERROR(e)
Definition: error.h:43
Definition: rtp.h:103
int probation
sequence packets till source is valid
Definition: rtpdec.h:84
static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
Definition: rtpdec.c:197
GLenum GLint * params
Definition: opengl_enc.c:114
#define RTP_SEQ_MOD
Definition: rtpdec.c:184
RTPDynamicProtocolHandler ff_vorbis_dynamic_handler
Definition: rtpdec_xiph.c:380
RTPDynamicProtocolHandler ff_ms_rtp_asf_pfv_handler
RTPDynamicProtocolHandler ff_ac3_dynamic_handler
Definition: rtpdec_ac3.c:125
RTPDynamicProtocolHandler ff_svq3_dynamic_handler
Definition: rtpdec_svq3.c:113
GLsizei count
Definition: opengl_enc.c:109
DynamicPayloadPacketHandlerProc parse_packet
Parse handler for this dynamic packet.
Definition: rtpdec.h:135
int64_t rtcp_ts_offset
Definition: rtpdec.h:182
RTPDynamicProtocolHandler * ff_rtp_handler_find_by_id(int id, enum AVMediaType codec_type)
Definition: rtpdec.c:137
uint32_t timestamp
Definition: rtpdec.h:155
uint32_t transit
relative transit time for previous packet
Definition: rtpdec.h:88
uint32_t jitter
estimated jitter.
Definition: rtpdec.h:89
int queue_len
The number of packets in queue.
Definition: rtpdec.h:173
RTPDynamicProtocolHandler ff_qt_rtp_vid_handler
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1394
int void avio_flush(AVIOContext *s)
Force flushing of buffered data.
Definition: aviobuf.c:224
int ff_srtp_decrypt(struct SRTPContext *s, uint8_t *buf, int *lenptr)
Definition: srtp.c:126
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:129
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:248
#define FFMIN(a, b)
Definition: common.h:96
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition: avstring.c:213
static RTPDynamicProtocolHandler * rtp_first_dynamic_payload_handler
Definition: rtpdec.c:66
RTPDynamicProtocolHandler ff_g726le_40_dynamic_handler
Definition: rtp.h:98
GLsizei GLboolean const GLfloat * value
Definition: opengl_enc.c:109
RTPDynamicProtocolHandler ff_g726le_16_dynamic_handler
RTPDynamicProtocolHandler ff_h263_rfc2190_dynamic_handler
int32_t
AVFormatContext * ctx
Definition: movenc.c:48
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition: common.h:72
void ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx, RTPDynamicProtocolHandler *handler)
Definition: rtpdec.c:550
int ff_rtp_send_rtcp_feedback(RTPDemuxContext *s, URLContext *fd, AVIOContext *avio)
Definition: rtpdec.c:446
Stream structure.
Definition: avformat.h:889
uint32_t received
packets received
Definition: rtpdec.h:85
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
RTPDynamicProtocolHandler ff_g726_16_dynamic_handler
int64_t last_rtcp_reception_time
Definition: rtpdec.h:179
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:254
Definition: rtp.h:100
static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt, uint8_t **bufptr, int len)
Definition: rtpdec.c:758
RTPDynamicProtocolHandler ff_vc2hq_dynamic_handler
Definition: rtpdec_vc2hq.c:219
int64_t unwrapped_timestamp
Definition: rtpdec.h:158
uint32_t last_rtcp_timestamp
Definition: rtpdec.h:181
static int has_next_packet(RTPDemuxContext *s)
Definition: rtpdec.c:726
void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
Definition: rtpdec.c:68
void avio_w8(AVIOContext *s, int b)
Definition: aviobuf.c:182
RTPDynamicProtocolHandler ff_mp4v_es_dynamic_handler
Definition: rtpdec_mpeg4.c:317
unsigned int octet_count
Definition: rtpdec.h:186
RTPDynamicProtocolHandler ff_h261_dynamic_handler
Definition: rtpdec_h261.c:165
void * buf
Definition: avisynth_c.h:690
Definition: url.h:38
RTPStatistics statistics
Statistics for this stream (used by RTCP receiver reports)
Definition: rtpdec.h:168
uint32_t received_prior
packets received in last interval
Definition: rtpdec.h:87
RTPDynamicProtocolHandler ff_qdm2_dynamic_handler
Definition: rtpdec_qdm2.c:301
uint32_t bad_seq
last bad sequence number + 1
Definition: rtpdec.h:83
AVMediaType
Definition: avutil.h:193
int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
Definition: rtpdec.c:731
int ff_rtp_check_and_send_back_rr(RTPDemuxContext *s, URLContext *fd, AVIOContext *avio, int count)
some rtp servers assume client is dead if they don't hear from them...
Definition: rtpdec.c:275
#define s1
Definition: regdef.h:38
int ff_parse_fmtp(AVFormatContext *s, AVStream *stream, PayloadContext *data, const char *p, int(*parse_fmtp)(AVFormatContext *s, AVStream *stream, PayloadContext *data, const char *attr, const char *value))
Definition: rtpdec.c:865
static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
This was the second switch in rtp_parse packet.
Definition: rtpdec.c:568
uint16_t max_seq
highest sequence number seen
Definition: rtpdec.h:80
RTPDynamicProtocolHandler ff_mpegts_dynamic_handler
Definition: rtpdec_mpegts.c:92
RTPDynamicProtocolHandler ff_g726le_32_dynamic_handler
RTPDynamicProtocolHandler ff_g726_32_dynamic_handler
RTPDynamicProtocolHandler ff_qt_rtp_aud_handler
const char * enc_name
Definition: rtpdec.h:116
uint8_t * buf
Definition: rtpdec.h:143
#define RTP_PT_IS_RTCP(x)
Definition: rtp.h:110
void avio_wb16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:452
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition: time.c:56
static int flags
Definition: cpu.c:47
RTPDynamicProtocolHandler ff_mpeg_audio_dynamic_handler
Definition: rtpdec_mpeg12.c:51
int sample_rate
Audio only.
Definition: avcodec.h:4090
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_RB64
Definition: bytestream.h:87
RTPDynamicProtocolHandler ff_mpeg_video_dynamic_handler
Definition: rtpdec_mpeg12.c:59
Main libavformat public API header.
struct RTPPacket * next
Definition: rtpdec.h:146
uint32_t ssrc
Definition: rtpdec.h:153
static RTPDynamicProtocolHandler realmedia_mp3_dynamic_handler
Definition: rtpdec.c:42
int64_t recvtime
Definition: rtpdec.h:145
RTPDynamicProtocolHandler * ff_rtp_handler_find_by_name(const char *name, enum AVMediaType codec_type)
Definition: rtpdec.c:124
RTPDynamicProtocolHandler ff_g726_40_dynamic_handler
raw UTF-8 text
Definition: avcodec.h:606
RTPDynamicProtocolHandler ff_qcelp_dynamic_handler
Definition: rtpdec_qcelp.c:212
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:33
int den
Denominator.
Definition: rational.h:60
RTPDynamicProtocolHandler ff_hevc_dynamic_handler
Definition: rtpdec_hevc.c:350
Definition: rtp.h:97
int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
Close the dynamic buffer and make a packet from it.
Definition: rtpdec.c:903
uint32_t base_timestamp
Definition: rtpdec.h:156
RTPDynamicProtocolHandler ff_g726_24_dynamic_handler
RTPDynamicProtocolHandler ff_h264_dynamic_handler
Definition: rtpdec_h264.c:411
static av_always_inline int diff(const uint32_t a, const uint32_t b)
#define av_free(p)
RTPDynamicProtocolHandler ff_vp9_dynamic_handler
Definition: rtpdec_vp9.c:333
as in Berlin toast format
Definition: avcodec.h:534
int len
int ff_srtp_set_crypto(struct SRTPContext *s, const char *suite, const char *params)
Definition: srtp.c:65
void ff_rtp_parse_close(RTPDemuxContext *s)
Definition: rtpdec.c:858
static RTPDynamicProtocolHandler t140_dynamic_handler
Definition: rtpdec.c:60
static void stats(const struct CachedBuf *in, int n_in, unsigned *_max, unsigned *_sum)
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1600
void avio_wb32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:354
#define RTP_NOTS_VALUE
Definition: rtpdec.h:40
static int enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
Definition: rtpdec.c:699
#define av_freep(p)
unbuffered private I/O API
static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
Definition: rtpdec.c:186
AVCodecParameters * codecpar
Definition: avformat.h:1241
int(* need_keyframe)(PayloadContext *context)
Definition: rtpdec.h:136
static RTPDynamicProtocolHandler opus_dynamic_handler
Definition: rtpdec.c:54
int stream_index
Definition: avcodec.h:1603
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:926
RTPDynamicProtocolHandler ff_quicktime_rtp_vid_handler
RTPDynamicProtocolHandler ff_mpeg4_generic_dynamic_handler
Definition: rtpdec_mpeg4.c:326
int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt, uint8_t **bufptr, int len)
Parse an RTP or RTCP packet directly sent as a buffer.
Definition: rtpdec.c:845
RTPDynamicProtocolHandler ff_amr_nb_dynamic_handler
Definition: rtpdec_amr.c:185
AVStream * st
Definition: rtpdec.h:151
This structure stores compressed data.
Definition: avcodec.h:1578
static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
Definition: rtpdec.c:211
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1594
RTPDynamicProtocolHandler ff_vp8_dynamic_handler
Definition: rtpdec_vp8.c:279
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:242
#define MIN_FEEDBACK_INTERVAL
Definition: rtpdec.c:34
#define av_unused
Definition: attributes.h:126
struct SRTPContext srtp
Definition: rtpdec.h:165
const char * name
Definition: opengl_enc.c:103
struct RTPDynamicProtocolHandler * next
Definition: rtpdec.h:138