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