Libav
rtsp.c
Go to the documentation of this file.
1 /*
2  * RTSP/SDP client
3  * Copyright (c) 2002 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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/base64.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/parseutils.h"
27 #include "libavutil/random_seed.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/time.h"
31 #include "avformat.h"
32 #include "avio_internal.h"
33 
34 #if HAVE_POLL_H
35 #include <poll.h>
36 #endif
37 #include "internal.h"
38 #include "network.h"
39 #include "os_support.h"
40 #include "http.h"
41 #include "rtsp.h"
42 
43 #include "rtpdec.h"
44 #include "rtpproto.h"
45 #include "rdt.h"
46 #include "rtpdec_formats.h"
47 #include "rtpenc_chain.h"
48 #include "url.h"
49 #include "rtpenc.h"
50 #include "mpegts.h"
51 
52 /* Timeout values for socket poll, in ms,
53  * and read_packet(), in seconds */
54 #define POLL_TIMEOUT_MS 100
55 #define READ_PACKET_TIMEOUT_S 10
56 #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / POLL_TIMEOUT_MS
57 #define SDP_MAX_SIZE 16384
58 #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
59 #define DEFAULT_REORDERING_DELAY 100000
60 
61 #define OFFSET(x) offsetof(RTSPState, x)
62 #define DEC AV_OPT_FLAG_DECODING_PARAM
63 #define ENC AV_OPT_FLAG_ENCODING_PARAM
64 
65 #define RTSP_FLAG_OPTS(name, longname) \
66  { name, longname, OFFSET(rtsp_flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, DEC, "rtsp_flags" }, \
67  { "filter_src", "Only receive packets from the negotiated peer IP", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_FILTER_SRC}, 0, 0, DEC, "rtsp_flags" }
68 
69 #define RTSP_MEDIATYPE_OPTS(name, longname) \
70  { name, longname, OFFSET(media_type_mask), AV_OPT_TYPE_FLAGS, { .i64 = (1 << (AVMEDIA_TYPE_DATA+1)) - 1 }, INT_MIN, INT_MAX, DEC, "allowed_media_types" }, \
71  { "video", "Video", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_VIDEO}, 0, 0, DEC, "allowed_media_types" }, \
72  { "audio", "Audio", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_AUDIO}, 0, 0, DEC, "allowed_media_types" }, \
73  { "data", "Data", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << AVMEDIA_TYPE_DATA}, 0, 0, DEC, "allowed_media_types" }
74 
75 #define COMMON_OPTS() \
76  { "reorder_queue_size", "Number of packets to buffer for handling of reordered packets", OFFSET(reordering_queue_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, DEC }, \
77  { "buffer_size", "Underlying protocol send/receive buffer size", OFFSET(buffer_size), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, DEC|ENC } \
78 
79 
81  { "initial_pause", "Don't start playing the stream immediately", OFFSET(initial_pause), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
82  FF_RTP_FLAG_OPTS(RTSPState, rtp_muxer_flags),
83  { "rtsp_transport", "RTSP transport protocols", OFFSET(lower_transport_mask), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, DEC|ENC, "rtsp_transport" }, \
84  { "udp", "UDP", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_UDP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
85  { "tcp", "TCP", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_TCP}, 0, 0, DEC|ENC, "rtsp_transport" }, \
86  { "udp_multicast", "UDP multicast", 0, AV_OPT_TYPE_CONST, {.i64 = 1 << RTSP_LOWER_TRANSPORT_UDP_MULTICAST}, 0, 0, DEC, "rtsp_transport" },
87  { "http", "HTTP tunneling", 0, AV_OPT_TYPE_CONST, {.i64 = (1 << RTSP_LOWER_TRANSPORT_HTTP)}, 0, 0, DEC, "rtsp_transport" },
88  RTSP_FLAG_OPTS("rtsp_flags", "RTSP flags"),
89  { "listen", "Wait for incoming connections", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_LISTEN}, 0, 0, DEC, "rtsp_flags" },
90  RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
91  { "min_port", "Minimum local UDP port", OFFSET(rtp_port_min), AV_OPT_TYPE_INT, {.i64 = RTSP_RTP_PORT_MIN}, 0, 65535, DEC|ENC },
92  { "max_port", "Maximum local UDP port", OFFSET(rtp_port_max), AV_OPT_TYPE_INT, {.i64 = RTSP_RTP_PORT_MAX}, 0, 65535, DEC|ENC },
93  { "timeout", "Maximum timeout (in seconds) to wait for incoming connections. -1 is infinite. Implies flag listen", OFFSET(initial_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, DEC },
94  COMMON_OPTS(),
95  { NULL },
96 };
97 
98 static const AVOption sdp_options[] = {
99  RTSP_FLAG_OPTS("sdp_flags", "SDP flags"),
100  { "custom_io", "Use custom IO", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_CUSTOM_IO}, 0, 0, DEC, "rtsp_flags" },
101  { "rtcp_to_source", "Send RTCP packets to the source address of received packets", 0, AV_OPT_TYPE_CONST, {.i64 = RTSP_FLAG_RTCP_TO_SOURCE}, 0, 0, DEC, "rtsp_flags" },
102  RTSP_MEDIATYPE_OPTS("allowed_media_types", "Media types to accept from the server"),
103  COMMON_OPTS(),
104  { NULL },
105 };
106 
107 static const AVOption rtp_options[] = {
108  RTSP_FLAG_OPTS("rtp_flags", "RTP flags"),
109  COMMON_OPTS(),
110  { NULL },
111 };
112 
113 
115 {
117  char buf[256];
118 
119  snprintf(buf, sizeof(buf), "%d", rt->buffer_size);
120  av_dict_set(&opts, "buffer_size", buf, 0);
121 
122  return opts;
123 }
124 
125 static void get_word_until_chars(char *buf, int buf_size,
126  const char *sep, const char **pp)
127 {
128  const char *p;
129  char *q;
130 
131  p = *pp;
132  p += strspn(p, SPACE_CHARS);
133  q = buf;
134  while (!strchr(sep, *p) && *p != '\0') {
135  if ((q - buf) < buf_size - 1)
136  *q++ = *p;
137  p++;
138  }
139  if (buf_size > 0)
140  *q = '\0';
141  *pp = p;
142 }
143 
144 static void get_word_sep(char *buf, int buf_size, const char *sep,
145  const char **pp)
146 {
147  if (**pp == '/') (*pp)++;
148  get_word_until_chars(buf, buf_size, sep, pp);
149 }
150 
151 static void get_word(char *buf, int buf_size, const char **pp)
152 {
153  get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
154 }
155 
160 static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
161 {
162  char buf[256];
163 
164  p += strspn(p, SPACE_CHARS);
165  if (!av_stristart(p, "npt=", &p))
166  return;
167 
168  *start = AV_NOPTS_VALUE;
169  *end = AV_NOPTS_VALUE;
170 
171  get_word_sep(buf, sizeof(buf), "-", &p);
172  if (av_parse_time(start, buf, 1) < 0)
173  return;
174  if (*p == '-') {
175  p++;
176  get_word_sep(buf, sizeof(buf), "-", &p);
177  av_parse_time(end, buf, 1);
178  }
179 }
180 
182  const char *buf, struct sockaddr_storage *sock)
183 {
184  struct addrinfo hints = { 0 }, *ai = NULL;
185  int ret;
186 
187  hints.ai_flags = AI_NUMERICHOST;
188  if ((ret = getaddrinfo(buf, NULL, &hints, &ai))) {
189  av_log(s, AV_LOG_ERROR, "getaddrinfo(%s): %s\n",
190  buf,
191  gai_strerror(ret));
192  return -1;
193  }
194  memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
195  freeaddrinfo(ai);
196  return 0;
197 }
198 
199 #if CONFIG_RTPDEC
200 static void init_rtp_handler(RTPDynamicProtocolHandler *handler,
201  RTSPStream *rtsp_st, AVStream *st)
202 {
203  AVCodecParameters *par = st ? st->codecpar : NULL;
204  if (!handler)
205  return;
206  if (par)
207  par->codec_id = handler->codec_id;
208  rtsp_st->dynamic_handler = handler;
209  if (st)
210  st->need_parsing = handler->need_parsing;
211  if (handler->priv_data_size) {
213  if (!rtsp_st->dynamic_protocol_context)
214  rtsp_st->dynamic_handler = NULL;
215  }
216 }
217 
218 static void finalize_rtp_handler_init(AVFormatContext *s, RTSPStream *rtsp_st,
219  AVStream *st)
220 {
221  if (rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->init) {
222  int ret = rtsp_st->dynamic_handler->init(s, st ? st->index : -1,
223  rtsp_st->dynamic_protocol_context);
224  if (ret < 0) {
225  if (rtsp_st->dynamic_protocol_context) {
226  if (rtsp_st->dynamic_handler->close)
227  rtsp_st->dynamic_handler->close(
228  rtsp_st->dynamic_protocol_context);
230  }
231  rtsp_st->dynamic_protocol_context = NULL;
232  rtsp_st->dynamic_handler = NULL;
233  }
234  }
235 }
236 
237 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
238 static int sdp_parse_rtpmap(AVFormatContext *s,
239  AVStream *st, RTSPStream *rtsp_st,
240  int payload_type, const char *p)
241 {
242  AVCodecParameters *par = st->codecpar;
243  char buf[256];
244  int i;
245  const AVCodecDescriptor *desc;
246  const char *c_name;
247 
248  /* See if we can handle this kind of payload.
249  * The space should normally not be there but some Real streams or
250  * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
251  * have a trailing space. */
252  get_word_sep(buf, sizeof(buf), "/ ", &p);
253  if (payload_type < RTP_PT_PRIVATE) {
254  /* We are in a standard case
255  * (from http://www.iana.org/assignments/rtp-parameters). */
256  par->codec_id = ff_rtp_codec_id(buf, par->codec_type);
257  }
258 
259  if (par->codec_id == AV_CODEC_ID_NONE) {
260  RTPDynamicProtocolHandler *handler =
262  init_rtp_handler(handler, rtsp_st, st);
263  /* If no dynamic handler was found, check with the list of standard
264  * allocated types, if such a stream for some reason happens to
265  * use a private payload type. This isn't handled in rtpdec.c, since
266  * the format name from the rtpmap line never is passed into rtpdec. */
267  if (!rtsp_st->dynamic_handler)
268  par->codec_id = ff_rtp_codec_id(buf, par->codec_type);
269  }
270 
271  desc = avcodec_descriptor_get(par->codec_id);
272  if (desc && desc->name)
273  c_name = desc->name;
274  else
275  c_name = "(null)";
276 
277  get_word_sep(buf, sizeof(buf), "/", &p);
278  i = atoi(buf);
279  switch (par->codec_type) {
280  case AVMEDIA_TYPE_AUDIO:
281  av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
284  if (i > 0) {
285  par->sample_rate = i;
286  avpriv_set_pts_info(st, 32, 1, par->sample_rate);
287  get_word_sep(buf, sizeof(buf), "/", &p);
288  i = atoi(buf);
289  if (i > 0)
290  par->channels = i;
291  }
292  av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
293  par->sample_rate);
294  av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
295  par->channels);
296  break;
297  case AVMEDIA_TYPE_VIDEO:
298  av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
299  if (i > 0)
300  avpriv_set_pts_info(st, 32, 1, i);
301  break;
302  default:
303  break;
304  }
305  finalize_rtp_handler_init(s, rtsp_st, st);
306  return 0;
307 }
308 
309 /* parse the attribute line from the fmtp a line of an sdp response. This
310  * is broken out as a function because it is used in rtp_h264.c, which is
311  * forthcoming. */
312 int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
313  char *value, int value_size)
314 {
315  *p += strspn(*p, SPACE_CHARS);
316  if (**p) {
317  get_word_sep(attr, attr_size, "=", p);
318  if (**p == '=')
319  (*p)++;
320  get_word_sep(value, value_size, ";", p);
321  if (**p == ';')
322  (*p)++;
323  return 1;
324  }
325  return 0;
326 }
327 
328 typedef struct SDPParseState {
329  /* SDP only */
330  struct sockaddr_storage default_ip;
331  int default_ttl;
332  int skip_media;
333  int nb_default_include_source_addrs;
334  struct RTSPSource **default_include_source_addrs;
335  int nb_default_exclude_source_addrs;
336  struct RTSPSource **default_exclude_source_addrs;
337  int seen_rtpmap;
338  int seen_fmtp;
339  char delayed_fmtp[2048];
340 } SDPParseState;
341 
342 static void copy_default_source_addrs(struct RTSPSource **addrs, int count,
343  struct RTSPSource ***dest, int *dest_count)
344 {
345  RTSPSource *rtsp_src, *rtsp_src2;
346  int i;
347  for (i = 0; i < count; i++) {
348  rtsp_src = addrs[i];
349  rtsp_src2 = av_malloc(sizeof(*rtsp_src2));
350  if (!rtsp_src2)
351  continue;
352  memcpy(rtsp_src2, rtsp_src, sizeof(*rtsp_src));
353  dynarray_add(dest, dest_count, rtsp_src2);
354  }
355 }
356 
357 static void parse_fmtp(AVFormatContext *s, RTSPState *rt,
358  int payload_type, const char *line)
359 {
360  int i;
361 
362  for (i = 0; i < rt->nb_rtsp_streams; i++) {
363  RTSPStream *rtsp_st = rt->rtsp_streams[i];
364  if (rtsp_st->sdp_payload_type == payload_type &&
365  rtsp_st->dynamic_handler &&
366  rtsp_st->dynamic_handler->parse_sdp_a_line) {
367  rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
368  rtsp_st->dynamic_protocol_context, line);
369  }
370  }
371 }
372 
373 static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
374  int letter, const char *buf)
375 {
376  RTSPState *rt = s->priv_data;
377  char buf1[64], st_type[64];
378  const char *p;
379  enum AVMediaType codec_type;
380  int payload_type;
381  AVStream *st;
382  RTSPStream *rtsp_st;
383  RTSPSource *rtsp_src;
384  struct sockaddr_storage sdp_ip;
385  int ttl;
386 
387  av_log(s, AV_LOG_TRACE, "sdp: %c='%s'\n", letter, buf);
388 
389  p = buf;
390  if (s1->skip_media && letter != 'm')
391  return;
392  switch (letter) {
393  case 'c':
394  get_word(buf1, sizeof(buf1), &p);
395  if (strcmp(buf1, "IN") != 0)
396  return;
397  get_word(buf1, sizeof(buf1), &p);
398  if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
399  return;
400  get_word_sep(buf1, sizeof(buf1), "/", &p);
401  if (get_sockaddr(s, buf1, &sdp_ip))
402  return;
403  ttl = 16;
404  if (*p == '/') {
405  p++;
406  get_word_sep(buf1, sizeof(buf1), "/", &p);
407  ttl = atoi(buf1);
408  }
409  if (s->nb_streams == 0) {
410  s1->default_ip = sdp_ip;
411  s1->default_ttl = ttl;
412  } else {
413  rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
414  rtsp_st->sdp_ip = sdp_ip;
415  rtsp_st->sdp_ttl = ttl;
416  }
417  break;
418  case 's':
419  av_dict_set(&s->metadata, "title", p, 0);
420  break;
421  case 'i':
422  if (s->nb_streams == 0) {
423  av_dict_set(&s->metadata, "comment", p, 0);
424  break;
425  }
426  break;
427  case 'm':
428  /* new stream */
429  s1->skip_media = 0;
430  s1->seen_fmtp = 0;
431  s1->seen_rtpmap = 0;
432  codec_type = AVMEDIA_TYPE_UNKNOWN;
433  get_word(st_type, sizeof(st_type), &p);
434  if (!strcmp(st_type, "audio")) {
435  codec_type = AVMEDIA_TYPE_AUDIO;
436  } else if (!strcmp(st_type, "video")) {
437  codec_type = AVMEDIA_TYPE_VIDEO;
438  } else if (!strcmp(st_type, "application") || !strcmp(st_type, "text")) {
439  codec_type = AVMEDIA_TYPE_DATA;
440  }
441  if (codec_type == AVMEDIA_TYPE_UNKNOWN || !(rt->media_type_mask & (1 << codec_type))) {
442  s1->skip_media = 1;
443  return;
444  }
445  rtsp_st = av_mallocz(sizeof(RTSPStream));
446  if (!rtsp_st)
447  return;
448  rtsp_st->stream_index = -1;
449  dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
450 
451  rtsp_st->sdp_ip = s1->default_ip;
452  rtsp_st->sdp_ttl = s1->default_ttl;
453 
454  copy_default_source_addrs(s1->default_include_source_addrs,
455  s1->nb_default_include_source_addrs,
456  &rtsp_st->include_source_addrs,
457  &rtsp_st->nb_include_source_addrs);
458  copy_default_source_addrs(s1->default_exclude_source_addrs,
459  s1->nb_default_exclude_source_addrs,
460  &rtsp_st->exclude_source_addrs,
461  &rtsp_st->nb_exclude_source_addrs);
462 
463  get_word(buf1, sizeof(buf1), &p); /* port */
464  rtsp_st->sdp_port = atoi(buf1);
465 
466  get_word(buf1, sizeof(buf1), &p); /* protocol */
467  if (!strcmp(buf1, "udp"))
469  else if (strstr(buf1, "/AVPF") || strstr(buf1, "/SAVPF"))
470  rtsp_st->feedback = 1;
471 
472  /* XXX: handle list of formats */
473  get_word(buf1, sizeof(buf1), &p); /* format list */
474  rtsp_st->sdp_payload_type = atoi(buf1);
475 
476  if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
477  /* no corresponding stream */
478  if (rt->transport == RTSP_TRANSPORT_RAW) {
479  if (CONFIG_RTPDEC && !rt->ts)
480  rt->ts = ff_mpegts_parse_open(s);
481  } else {
482  RTPDynamicProtocolHandler *handler;
483  handler = ff_rtp_handler_find_by_id(
485  init_rtp_handler(handler, rtsp_st, NULL);
486  finalize_rtp_handler_init(s, rtsp_st, NULL);
487  }
488  } else if (rt->server_type == RTSP_SERVER_WMS &&
489  codec_type == AVMEDIA_TYPE_DATA) {
490  /* RTX stream, a stream that carries all the other actual
491  * audio/video streams. Don't expose this to the callers. */
492  } else {
493  st = avformat_new_stream(s, NULL);
494  if (!st)
495  return;
496  st->id = rt->nb_rtsp_streams - 1;
497  rtsp_st->stream_index = st->index;
499  if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
500  RTPDynamicProtocolHandler *handler;
501  /* if standard payload type, we can find the codec right now */
503  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
504  st->codecpar->sample_rate > 0)
505  avpriv_set_pts_info(st, 32, 1, st->codecpar->sample_rate);
506  /* Even static payload types may need a custom depacketizer */
507  handler = ff_rtp_handler_find_by_id(
508  rtsp_st->sdp_payload_type, st->codecpar->codec_type);
509  init_rtp_handler(handler, rtsp_st, st);
510  finalize_rtp_handler_init(s, rtsp_st, st);
511  }
512  if (rt->default_lang[0])
513  av_dict_set(&st->metadata, "language", rt->default_lang, 0);
514  }
515  /* put a default control url */
516  av_strlcpy(rtsp_st->control_url, rt->control_uri,
517  sizeof(rtsp_st->control_url));
518  break;
519  case 'a':
520  if (av_strstart(p, "control:", &p)) {
521  if (s->nb_streams == 0) {
522  if (!strncmp(p, "rtsp://", 7))
523  av_strlcpy(rt->control_uri, p,
524  sizeof(rt->control_uri));
525  } else {
526  char proto[32];
527  /* get the control url */
528  rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
529 
530  /* XXX: may need to add full url resolution */
531  av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
532  NULL, NULL, 0, p);
533  if (proto[0] == '\0') {
534  /* relative control URL */
535  if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
536  av_strlcat(rtsp_st->control_url, "/",
537  sizeof(rtsp_st->control_url));
538  av_strlcat(rtsp_st->control_url, p,
539  sizeof(rtsp_st->control_url));
540  } else
541  av_strlcpy(rtsp_st->control_url, p,
542  sizeof(rtsp_st->control_url));
543  }
544  } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
545  /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
546  get_word(buf1, sizeof(buf1), &p);
547  payload_type = atoi(buf1);
548  rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
549  if (rtsp_st->stream_index >= 0) {
550  st = s->streams[rtsp_st->stream_index];
551  sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);
552  }
553  s1->seen_rtpmap = 1;
554  if (s1->seen_fmtp) {
555  parse_fmtp(s, rt, payload_type, s1->delayed_fmtp);
556  }
557  } else if (av_strstart(p, "fmtp:", &p) ||
558  av_strstart(p, "framesize:", &p)) {
559  // let dynamic protocol handlers have a stab at the line.
560  get_word(buf1, sizeof(buf1), &p);
561  payload_type = atoi(buf1);
562  if (s1->seen_rtpmap) {
563  parse_fmtp(s, rt, payload_type, buf);
564  } else {
565  s1->seen_fmtp = 1;
566  av_strlcpy(s1->delayed_fmtp, buf, sizeof(s1->delayed_fmtp));
567  }
568  } else if (av_strstart(p, "ssrc:", &p) && s->nb_streams > 0) {
569  rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
570  get_word(buf1, sizeof(buf1), &p);
571  rtsp_st->ssrc = strtoll(buf1, NULL, 10);
572  } else if (av_strstart(p, "range:", &p)) {
573  int64_t start, end;
574 
575  // this is so that seeking on a streamed file can work.
576  rtsp_parse_range_npt(p, &start, &end);
577  s->start_time = start;
578  /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
579  s->duration = (end == AV_NOPTS_VALUE) ?
580  AV_NOPTS_VALUE : end - start;
581  } else if (av_strstart(p, "lang:", &p)) {
582  if (s->nb_streams > 0) {
583  get_word(buf1, sizeof(buf1), &p);
584  rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
585  if (rtsp_st->stream_index >= 0) {
586  st = s->streams[rtsp_st->stream_index];
587  av_dict_set(&st->metadata, "language", buf1, 0);
588  }
589  } else
590  get_word(rt->default_lang, sizeof(rt->default_lang), &p);
591  } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
592  if (atoi(p) == 1)
594  } else if (av_strstart(p, "SampleRate:integer;", &p) &&
595  s->nb_streams > 0) {
596  st = s->streams[s->nb_streams - 1];
597  st->codecpar->sample_rate = atoi(p);
598  } else if (av_strstart(p, "crypto:", &p) && s->nb_streams > 0) {
599  // RFC 4568
600  rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
601  get_word(buf1, sizeof(buf1), &p); // ignore tag
602  get_word(rtsp_st->crypto_suite, sizeof(rtsp_st->crypto_suite), &p);
603  p += strspn(p, SPACE_CHARS);
604  if (av_strstart(p, "inline:", &p))
605  get_word(rtsp_st->crypto_params, sizeof(rtsp_st->crypto_params), &p);
606  } else if (av_strstart(p, "source-filter:", &p)) {
607  int exclude = 0;
608  get_word(buf1, sizeof(buf1), &p);
609  if (strcmp(buf1, "incl") && strcmp(buf1, "excl"))
610  return;
611  exclude = !strcmp(buf1, "excl");
612 
613  get_word(buf1, sizeof(buf1), &p);
614  if (strcmp(buf1, "IN") != 0)
615  return;
616  get_word(buf1, sizeof(buf1), &p);
617  if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6") && strcmp(buf1, "*"))
618  return;
619  // not checking that the destination address actually matches or is wildcard
620  get_word(buf1, sizeof(buf1), &p);
621 
622  while (*p != '\0') {
623  rtsp_src = av_mallocz(sizeof(*rtsp_src));
624  if (!rtsp_src)
625  return;
626  get_word(rtsp_src->addr, sizeof(rtsp_src->addr), &p);
627  if (exclude) {
628  if (s->nb_streams == 0) {
629  dynarray_add(&s1->default_exclude_source_addrs, &s1->nb_default_exclude_source_addrs, rtsp_src);
630  } else {
631  rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
632  dynarray_add(&rtsp_st->exclude_source_addrs, &rtsp_st->nb_exclude_source_addrs, rtsp_src);
633  }
634  } else {
635  if (s->nb_streams == 0) {
636  dynarray_add(&s1->default_include_source_addrs, &s1->nb_default_include_source_addrs, rtsp_src);
637  } else {
638  rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
639  dynarray_add(&rtsp_st->include_source_addrs, &rtsp_st->nb_include_source_addrs, rtsp_src);
640  }
641  }
642  }
643  } else {
644  if (rt->server_type == RTSP_SERVER_WMS)
646  if (s->nb_streams > 0) {
647  rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];
648 
649  if (rt->server_type == RTSP_SERVER_REAL)
650  ff_real_parse_sdp_a_line(s, rtsp_st->stream_index, p);
651 
652  if (rtsp_st->dynamic_handler &&
654  rtsp_st->dynamic_handler->parse_sdp_a_line(s,
655  rtsp_st->stream_index,
656  rtsp_st->dynamic_protocol_context, buf);
657  }
658  }
659  break;
660  }
661 }
662 
663 int ff_sdp_parse(AVFormatContext *s, const char *content)
664 {
665  RTSPState *rt = s->priv_data;
666  const char *p;
667  int letter, i;
668  /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
669  * contain long SDP lines containing complete ASF Headers (several
670  * kB) or arrays of MDPR (RM stream descriptor) headers plus
671  * "rulebooks" describing their properties. Therefore, the SDP line
672  * buffer is large.
673  *
674  * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
675  * in rtpdec_xiph.c. */
676  char buf[16384], *q;
677  SDPParseState sdp_parse_state = { { 0 } }, *s1 = &sdp_parse_state;
678 
679  p = content;
680  for (;;) {
681  p += strspn(p, SPACE_CHARS);
682  letter = *p;
683  if (letter == '\0')
684  break;
685  p++;
686  if (*p != '=')
687  goto next_line;
688  p++;
689  /* get the content */
690  q = buf;
691  while (*p != '\n' && *p != '\r' && *p != '\0') {
692  if ((q - buf) < sizeof(buf) - 1)
693  *q++ = *p;
694  p++;
695  }
696  *q = '\0';
697  sdp_parse_line(s, s1, letter, buf);
698  next_line:
699  while (*p != '\n' && *p != '\0')
700  p++;
701  if (*p == '\n')
702  p++;
703  }
704 
705  for (i = 0; i < s1->nb_default_include_source_addrs; i++)
706  av_free(s1->default_include_source_addrs[i]);
707  av_freep(&s1->default_include_source_addrs);
708  for (i = 0; i < s1->nb_default_exclude_source_addrs; i++)
709  av_free(s1->default_exclude_source_addrs[i]);
710  av_freep(&s1->default_exclude_source_addrs);
711 
712  rt->p = av_malloc(sizeof(struct pollfd)*2*(rt->nb_rtsp_streams+1));
713  if (!rt->p) return AVERROR(ENOMEM);
714  return 0;
715 }
716 #endif /* CONFIG_RTPDEC */
717 
718 void ff_rtsp_undo_setup(AVFormatContext *s, int send_packets)
719 {
720  RTSPState *rt = s->priv_data;
721  int i;
722 
723  for (i = 0; i < rt->nb_rtsp_streams; i++) {
724  RTSPStream *rtsp_st = rt->rtsp_streams[i];
725  if (!rtsp_st)
726  continue;
727  if (rtsp_st->transport_priv) {
728  if (s->oformat) {
729  AVFormatContext *rtpctx = rtsp_st->transport_priv;
730  av_write_trailer(rtpctx);
732  if (CONFIG_RTSP_MUXER && rtpctx->pb && send_packets)
733  ff_rtsp_tcp_write_packet(s, rtsp_st);
734  ffio_free_dyn_buf(&rtpctx->pb);
735  } else {
736  avio_close(rtpctx->pb);
737  }
738  avformat_free_context(rtpctx);
739  } else if (CONFIG_RTPDEC && rt->transport == RTSP_TRANSPORT_RDT)
741  else if (CONFIG_RTPDEC && rt->transport == RTSP_TRANSPORT_RTP)
743  }
744  rtsp_st->transport_priv = NULL;
745  if (rtsp_st->rtp_handle)
746  ffurl_close(rtsp_st->rtp_handle);
747  rtsp_st->rtp_handle = NULL;
748  }
749 }
750 
751 /* close and free RTSP streams */
753 {
754  RTSPState *rt = s->priv_data;
755  int i, j;
756  RTSPStream *rtsp_st;
757 
758  ff_rtsp_undo_setup(s, 0);
759  for (i = 0; i < rt->nb_rtsp_streams; i++) {
760  rtsp_st = rt->rtsp_streams[i];
761  if (rtsp_st) {
762  if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context) {
763  if (rtsp_st->dynamic_handler->close)
764  rtsp_st->dynamic_handler->close(
765  rtsp_st->dynamic_protocol_context);
767  }
768  for (j = 0; j < rtsp_st->nb_include_source_addrs; j++)
769  av_free(rtsp_st->include_source_addrs[j]);
770  av_freep(&rtsp_st->include_source_addrs);
771  for (j = 0; j < rtsp_st->nb_exclude_source_addrs; j++)
772  av_free(rtsp_st->exclude_source_addrs[j]);
773  av_freep(&rtsp_st->exclude_source_addrs);
774 
775  av_free(rtsp_st);
776  }
777  }
778  av_free(rt->rtsp_streams);
779  if (rt->asf_ctx) {
781  }
782  if (CONFIG_RTPDEC && rt->ts)
784  av_freep(&rt->protocols);
785  av_free(rt->p);
786  av_free(rt->recvbuf);
787 }
788 
790 {
791  RTSPState *rt = s->priv_data;
792  AVStream *st = NULL;
793  int reordering_queue_size = rt->reordering_queue_size;
794  if (reordering_queue_size < 0) {
796  reordering_queue_size = 0;
797  else
798  reordering_queue_size = RTP_REORDER_QUEUE_DEFAULT_SIZE;
799  }
800 
801  /* open the RTP context */
802  if (rtsp_st->stream_index >= 0)
803  st = s->streams[rtsp_st->stream_index];
804  if (!st)
806 
807  if (CONFIG_RTSP_MUXER && s->oformat) {
808  int ret = ff_rtp_chain_mux_open((AVFormatContext **)&rtsp_st->transport_priv,
809  s, st, rtsp_st->rtp_handle,
811  rtsp_st->stream_index);
812  /* Ownership of rtp_handle is passed to the rtp mux context */
813  rtsp_st->rtp_handle = NULL;
814  if (ret < 0)
815  return ret;
816  st->time_base = ((AVFormatContext*)rtsp_st->transport_priv)->streams[0]->time_base;
817  } else if (rt->transport == RTSP_TRANSPORT_RAW) {
818  return 0; // Don't need to open any parser here
819  } else if (CONFIG_RTPDEC && rt->transport == RTSP_TRANSPORT_RDT)
820  rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
821  rtsp_st->dynamic_protocol_context,
822  rtsp_st->dynamic_handler);
823  else if (CONFIG_RTPDEC)
824  rtsp_st->transport_priv = ff_rtp_parse_open(s, st,
825  rtsp_st->sdp_payload_type,
826  reordering_queue_size);
827 
828  if (!rtsp_st->transport_priv) {
829  return AVERROR(ENOMEM);
830  } else if (CONFIG_RTPDEC && rt->transport == RTSP_TRANSPORT_RTP &&
831  s->iformat) {
832  RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
833  rtpctx->ssrc = rtsp_st->ssrc;
834  if (rtsp_st->dynamic_handler) {
836  rtsp_st->dynamic_protocol_context,
837  rtsp_st->dynamic_handler);
838  }
839  if (rtsp_st->crypto_suite[0])
841  rtsp_st->crypto_suite,
842  rtsp_st->crypto_params);
843  }
844 
845  return 0;
846 }
847 
848 #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
849 static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
850 {
851  const char *q;
852  char *p;
853  int v;
854 
855  q = *pp;
856  q += strspn(q, SPACE_CHARS);
857  v = strtol(q, &p, 10);
858  if (*p == '-') {
859  p++;
860  *min_ptr = v;
861  v = strtol(p, &p, 10);
862  *max_ptr = v;
863  } else {
864  *min_ptr = v;
865  *max_ptr = v;
866  }
867  *pp = p;
868 }
869 
870 /* XXX: only one transport specification is parsed */
871 static void rtsp_parse_transport(AVFormatContext *s,
872  RTSPMessageHeader *reply, const char *p)
873 {
874  char transport_protocol[16];
875  char profile[16];
876  char lower_transport[16];
877  char parameter[16];
878  RTSPTransportField *th;
879  char buf[256];
880 
881  reply->nb_transports = 0;
882 
883  for (;;) {
884  p += strspn(p, SPACE_CHARS);
885  if (*p == '\0')
886  break;
887 
888  th = &reply->transports[reply->nb_transports];
889 
890  get_word_sep(transport_protocol, sizeof(transport_protocol),
891  "/", &p);
892  if (!av_strcasecmp (transport_protocol, "rtp")) {
893  get_word_sep(profile, sizeof(profile), "/;,", &p);
894  lower_transport[0] = '\0';
895  /* rtp/avp/<protocol> */
896  if (*p == '/') {
897  get_word_sep(lower_transport, sizeof(lower_transport),
898  ";,", &p);
899  }
901  } else if (!av_strcasecmp (transport_protocol, "x-pn-tng") ||
902  !av_strcasecmp (transport_protocol, "x-real-rdt")) {
903  /* x-pn-tng/<protocol> */
904  get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
905  profile[0] = '\0';
907  } else if (!av_strcasecmp(transport_protocol, "raw")) {
908  get_word_sep(profile, sizeof(profile), "/;,", &p);
909  lower_transport[0] = '\0';
910  /* raw/raw/<protocol> */
911  if (*p == '/') {
912  get_word_sep(lower_transport, sizeof(lower_transport),
913  ";,", &p);
914  }
916  }
917  if (!av_strcasecmp(lower_transport, "TCP"))
919  else
921 
922  if (*p == ';')
923  p++;
924  /* get each parameter */
925  while (*p != '\0' && *p != ',') {
926  get_word_sep(parameter, sizeof(parameter), "=;,", &p);
927  if (!strcmp(parameter, "port")) {
928  if (*p == '=') {
929  p++;
930  rtsp_parse_range(&th->port_min, &th->port_max, &p);
931  }
932  } else if (!strcmp(parameter, "client_port")) {
933  if (*p == '=') {
934  p++;
935  rtsp_parse_range(&th->client_port_min,
936  &th->client_port_max, &p);
937  }
938  } else if (!strcmp(parameter, "server_port")) {
939  if (*p == '=') {
940  p++;
941  rtsp_parse_range(&th->server_port_min,
942  &th->server_port_max, &p);
943  }
944  } else if (!strcmp(parameter, "interleaved")) {
945  if (*p == '=') {
946  p++;
947  rtsp_parse_range(&th->interleaved_min,
948  &th->interleaved_max, &p);
949  }
950  } else if (!strcmp(parameter, "multicast")) {
953  } else if (!strcmp(parameter, "ttl")) {
954  if (*p == '=') {
955  char *end;
956  p++;
957  th->ttl = strtol(p, &end, 10);
958  p = end;
959  }
960  } else if (!strcmp(parameter, "destination")) {
961  if (*p == '=') {
962  p++;
963  get_word_sep(buf, sizeof(buf), ";,", &p);
964  get_sockaddr(s, buf, &th->destination);
965  }
966  } else if (!strcmp(parameter, "source")) {
967  if (*p == '=') {
968  p++;
969  get_word_sep(buf, sizeof(buf), ";,", &p);
970  av_strlcpy(th->source, buf, sizeof(th->source));
971  }
972  } else if (!strcmp(parameter, "mode")) {
973  if (*p == '=') {
974  p++;
975  get_word_sep(buf, sizeof(buf), ";, ", &p);
976  if (!strcmp(buf, "record") ||
977  !strcmp(buf, "receive"))
978  th->mode_record = 1;
979  }
980  }
981 
982  while (*p != ';' && *p != '\0' && *p != ',')
983  p++;
984  if (*p == ';')
985  p++;
986  }
987  if (*p == ',')
988  p++;
989 
990  reply->nb_transports++;
991  if (reply->nb_transports >= RTSP_MAX_TRANSPORTS)
992  break;
993  }
994 }
995 
996 static void handle_rtp_info(RTSPState *rt, const char *url,
997  uint32_t seq, uint32_t rtptime)
998 {
999  int i;
1000  if (!rtptime || !url[0])
1001  return;
1002  if (rt->transport != RTSP_TRANSPORT_RTP)
1003  return;
1004  for (i = 0; i < rt->nb_rtsp_streams; i++) {
1005  RTSPStream *rtsp_st = rt->rtsp_streams[i];
1006  RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
1007  if (!rtpctx)
1008  continue;
1009  if (!strcmp(rtsp_st->control_url, url)) {
1010  rtpctx->base_timestamp = rtptime;
1011  break;
1012  }
1013  }
1014 }
1015 
1016 static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)
1017 {
1018  int read = 0;
1019  char key[20], value[1024], url[1024] = "";
1020  uint32_t seq = 0, rtptime = 0;
1021 
1022  for (;;) {
1023  p += strspn(p, SPACE_CHARS);
1024  if (!*p)
1025  break;
1026  get_word_sep(key, sizeof(key), "=", &p);
1027  if (*p != '=')
1028  break;
1029  p++;
1030  get_word_sep(value, sizeof(value), ";, ", &p);
1031  read++;
1032  if (!strcmp(key, "url"))
1033  av_strlcpy(url, value, sizeof(url));
1034  else if (!strcmp(key, "seq"))
1035  seq = strtoul(value, NULL, 10);
1036  else if (!strcmp(key, "rtptime"))
1037  rtptime = strtoul(value, NULL, 10);
1038  if (*p == ',') {
1039  handle_rtp_info(rt, url, seq, rtptime);
1040  url[0] = '\0';
1041  seq = rtptime = 0;
1042  read = 0;
1043  }
1044  if (*p)
1045  p++;
1046  }
1047  if (read > 0)
1048  handle_rtp_info(rt, url, seq, rtptime);
1049 }
1050 
1052  RTSPMessageHeader *reply, const char *buf,
1053  RTSPState *rt, const char *method)
1054 {
1055  const char *p;
1056 
1057  /* NOTE: we do case independent match for broken servers */
1058  p = buf;
1059  if (av_stristart(p, "Session:", &p)) {
1060  int t;
1061  get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
1062  if (av_stristart(p, ";timeout=", &p) &&
1063  (t = strtol(p, NULL, 10)) > 0) {
1064  reply->timeout = t;
1065  }
1066  } else if (av_stristart(p, "Content-Length:", &p)) {
1067  reply->content_length = strtol(p, NULL, 10);
1068  } else if (av_stristart(p, "Transport:", &p)) {
1069  rtsp_parse_transport(s, reply, p);
1070  } else if (av_stristart(p, "CSeq:", &p)) {
1071  reply->seq = strtol(p, NULL, 10);
1072  } else if (av_stristart(p, "Range:", &p)) {
1073  rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
1074  } else if (av_stristart(p, "RealChallenge1:", &p)) {
1075  p += strspn(p, SPACE_CHARS);
1076  av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
1077  } else if (av_stristart(p, "Server:", &p)) {
1078  p += strspn(p, SPACE_CHARS);
1079  av_strlcpy(reply->server, p, sizeof(reply->server));
1080  } else if (av_stristart(p, "Notice:", &p) ||
1081  av_stristart(p, "X-Notice:", &p)) {
1082  reply->notice = strtol(p, NULL, 10);
1083  } else if (av_stristart(p, "Location:", &p)) {
1084  p += strspn(p, SPACE_CHARS);
1085  av_strlcpy(reply->location, p , sizeof(reply->location));
1086  } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
1087  p += strspn(p, SPACE_CHARS);
1088  ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
1089  } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
1090  p += strspn(p, SPACE_CHARS);
1091  ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
1092  } else if (av_stristart(p, "Content-Base:", &p) && rt) {
1093  p += strspn(p, SPACE_CHARS);
1094  if (method && !strcmp(method, "DESCRIBE"))
1095  av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
1096  } else if (av_stristart(p, "RTP-Info:", &p) && rt) {
1097  p += strspn(p, SPACE_CHARS);
1098  if (method && !strcmp(method, "PLAY"))
1099  rtsp_parse_rtp_info(rt, p);
1100  } else if (av_stristart(p, "Public:", &p) && rt) {
1101  if (strstr(p, "GET_PARAMETER") &&
1102  method && !strcmp(method, "OPTIONS"))
1103  rt->get_parameter_supported = 1;
1104  } else if (av_stristart(p, "x-Accept-Dynamic-Rate:", &p) && rt) {
1105  p += strspn(p, SPACE_CHARS);
1106  rt->accept_dynamic_rate = atoi(p);
1107  } else if (av_stristart(p, "Content-Type:", &p)) {
1108  p += strspn(p, SPACE_CHARS);
1109  av_strlcpy(reply->content_type, p, sizeof(reply->content_type));
1110  }
1111 }
1112 
1113 /* skip a RTP/TCP interleaved packet */
1115 {
1116  RTSPState *rt = s->priv_data;
1117  int ret, len, len1;
1118  uint8_t buf[1024];
1119 
1120  ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
1121  if (ret != 3)
1122  return;
1123  len = AV_RB16(buf + 1);
1124 
1125  av_log(s, AV_LOG_TRACE, "skipping RTP packet len=%d\n", len);
1126 
1127  /* skip payload */
1128  while (len > 0) {
1129  len1 = len;
1130  if (len1 > sizeof(buf))
1131  len1 = sizeof(buf);
1132  ret = ffurl_read_complete(rt->rtsp_hd, buf, len1);
1133  if (ret != len1)
1134  return;
1135  len -= len1;
1136  }
1137 }
1138 
1140  unsigned char **content_ptr,
1141  int return_on_interleaved_data, const char *method)
1142 {
1143  RTSPState *rt = s->priv_data;
1144  char buf[4096], buf1[1024], *q;
1145  unsigned char ch;
1146  const char *p;
1147  int ret, content_length, line_count = 0, request = 0;
1148  unsigned char *content = NULL;
1149 
1150 start:
1151  line_count = 0;
1152  request = 0;
1153  content = NULL;
1154  memset(reply, 0, sizeof(*reply));
1155 
1156  /* parse reply (XXX: use buffers) */
1157  rt->last_reply[0] = '\0';
1158  for (;;) {
1159  q = buf;
1160  for (;;) {
1161  ret = ffurl_read_complete(rt->rtsp_hd, &ch, 1);
1162  av_log(s, AV_LOG_TRACE, "ret=%d c=%02x [%c]\n", ret, ch, ch);
1163  if (ret != 1)
1164  return AVERROR_EOF;
1165  if (ch == '\n')
1166  break;
1167  if (ch == '$' && q == buf) {
1168  if (return_on_interleaved_data) {
1169  return 1;
1170  } else
1172  } else if (ch != '\r') {
1173  if ((q - buf) < sizeof(buf) - 1)
1174  *q++ = ch;
1175  }
1176  }
1177  *q = '\0';
1178 
1179  av_log(s, AV_LOG_TRACE, "line='%s'\n", buf);
1180 
1181  /* test if last line */
1182  if (buf[0] == '\0')
1183  break;
1184  p = buf;
1185  if (line_count == 0) {
1186  /* get reply code */
1187  get_word(buf1, sizeof(buf1), &p);
1188  if (!strncmp(buf1, "RTSP/", 5)) {
1189  get_word(buf1, sizeof(buf1), &p);
1190  reply->status_code = atoi(buf1);
1191  av_strlcpy(reply->reason, p, sizeof(reply->reason));
1192  } else {
1193  av_strlcpy(reply->reason, buf1, sizeof(reply->reason)); // method
1194  get_word(buf1, sizeof(buf1), &p); // object
1195  request = 1;
1196  }
1197  } else {
1198  ff_rtsp_parse_line(s, reply, p, rt, method);
1199  av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
1200  av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
1201  }
1202  line_count++;
1203  }
1204 
1205  if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0' && !request)
1206  av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
1207 
1208  content_length = reply->content_length;
1209  if (content_length > 0) {
1210  /* leave some room for a trailing '\0' (useful for simple parsing) */
1211  content = av_malloc(content_length + 1);
1212  if (!content)
1213  return AVERROR(ENOMEM);
1214  ffurl_read_complete(rt->rtsp_hd, content, content_length);
1215  content[content_length] = '\0';
1216  }
1217  if (content_ptr)
1218  *content_ptr = content;
1219  else
1220  av_free(content);
1221 
1222  if (request) {
1223  char buf[1024];
1224  char base64buf[AV_BASE64_SIZE(sizeof(buf))];
1225  const char* ptr = buf;
1226 
1227  if (!strcmp(reply->reason, "OPTIONS")) {
1228  snprintf(buf, sizeof(buf), "RTSP/1.0 200 OK\r\n");
1229  if (reply->seq)
1230  av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", reply->seq);
1231  if (reply->session_id[0])
1232  av_strlcatf(buf, sizeof(buf), "Session: %s\r\n",
1233  reply->session_id);
1234  } else {
1235  snprintf(buf, sizeof(buf), "RTSP/1.0 501 Not Implemented\r\n");
1236  }
1237  av_strlcat(buf, "\r\n", sizeof(buf));
1238 
1239  if (rt->control_transport == RTSP_MODE_TUNNEL) {
1240  av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1241  ptr = base64buf;
1242  }
1243  ffurl_write(rt->rtsp_hd_out, ptr, strlen(ptr));
1244 
1246  /* Even if the request from the server had data, it is not the data
1247  * that the caller wants or expects. The memory could also be leaked
1248  * if the actual following reply has content data. */
1249  if (content_ptr)
1250  av_freep(content_ptr);
1251  /* If method is set, this is called from ff_rtsp_send_cmd,
1252  * where a reply to exactly this request is awaited. For
1253  * callers from within packet receiving, we just want to
1254  * return to the caller and go back to receiving packets. */
1255  if (method)
1256  goto start;
1257  return 0;
1258  }
1259 
1260  if (rt->seq != reply->seq) {
1261  av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
1262  rt->seq, reply->seq);
1263  }
1264 
1265  /* EOS */
1266  if (reply->notice == 2101 /* End-of-Stream Reached */ ||
1267  reply->notice == 2104 /* Start-of-Stream Reached */ ||
1268  reply->notice == 2306 /* Continuous Feed Terminated */) {
1269  rt->state = RTSP_STATE_IDLE;
1270  } else if (reply->notice >= 4400 && reply->notice < 5500) {
1271  return AVERROR(EIO); /* data or server error */
1272  } else if (reply->notice == 2401 /* Ticket Expired */ ||
1273  (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
1274  return AVERROR(EPERM);
1275 
1276  return 0;
1277 }
1278 
1292 static int rtsp_send_cmd_with_content_async(AVFormatContext *s,
1293  const char *method, const char *url,
1294  const char *headers,
1295  const unsigned char *send_content,
1296  int send_content_length)
1297 {
1298  RTSPState *rt = s->priv_data;
1299  char buf[4096], *out_buf;
1300  char base64buf[AV_BASE64_SIZE(sizeof(buf))];
1301 
1302  /* Add in RTSP headers */
1303  out_buf = buf;
1304  rt->seq++;
1305  snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
1306  if (headers)
1307  av_strlcat(buf, headers, sizeof(buf));
1308  av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
1309  av_strlcatf(buf, sizeof(buf), "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
1310  if (rt->session_id[0] != '\0' && (!headers ||
1311  !strstr(headers, "\nIf-Match:"))) {
1312  av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
1313  }
1314  if (rt->auth[0]) {
1315  char *str = ff_http_auth_create_response(&rt->auth_state,
1316  rt->auth, url, method);
1317  if (str)
1318  av_strlcat(buf, str, sizeof(buf));
1319  av_free(str);
1320  }
1321  if (send_content_length > 0 && send_content)
1322  av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
1323  av_strlcat(buf, "\r\n", sizeof(buf));
1324 
1325  /* base64 encode rtsp if tunneling */
1326  if (rt->control_transport == RTSP_MODE_TUNNEL) {
1327  av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
1328  out_buf = base64buf;
1329  }
1330 
1331  av_log(s, AV_LOG_TRACE, "Sending:\n%s--\n", buf);
1332 
1333  ffurl_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
1334  if (send_content_length > 0 && send_content) {
1335  if (rt->control_transport == RTSP_MODE_TUNNEL) {
1336  av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
1337  "with content data not supported\n");
1338  return AVERROR_PATCHWELCOME;
1339  }
1340  ffurl_write(rt->rtsp_hd_out, send_content, send_content_length);
1341  }
1343 
1344  return 0;
1345 }
1346 
1347 int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
1348  const char *url, const char *headers)
1349 {
1350  return rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
1351 }
1352 
1353 int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
1354  const char *headers, RTSPMessageHeader *reply,
1355  unsigned char **content_ptr)
1356 {
1357  return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
1358  content_ptr, NULL, 0);
1359 }
1360 
1362  const char *method, const char *url,
1363  const char *header,
1364  RTSPMessageHeader *reply,
1365  unsigned char **content_ptr,
1366  const unsigned char *send_content,
1367  int send_content_length)
1368 {
1369  RTSPState *rt = s->priv_data;
1370  HTTPAuthType cur_auth_type;
1371  int ret, attempts = 0;
1372 
1373 retry:
1374  cur_auth_type = rt->auth_state.auth_type;
1375  if ((ret = rtsp_send_cmd_with_content_async(s, method, url, header,
1376  send_content,
1377  send_content_length)))
1378  return ret;
1379 
1380  if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
1381  return ret;
1382  attempts++;
1383 
1384  if (reply->status_code == 401 &&
1385  (cur_auth_type == HTTP_AUTH_NONE || rt->auth_state.stale) &&
1386  rt->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2)
1387  goto retry;
1388 
1389  if (reply->status_code > 400){
1390  av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
1391  method,
1392  reply->status_code,
1393  reply->reason);
1394  av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
1395  }
1396 
1397  return 0;
1398 }
1399 
1400 int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
1401  int lower_transport, const char *real_challenge)
1402 {
1403  RTSPState *rt = s->priv_data;
1404  int rtx = 0, j, i, err, interleave = 0, port_off;
1405  RTSPStream *rtsp_st;
1406  RTSPMessageHeader reply1, *reply = &reply1;
1407  char cmd[2048];
1408  const char *trans_pref;
1409 
1410  if (rt->transport == RTSP_TRANSPORT_RDT)
1411  trans_pref = "x-pn-tng";
1412  else if (rt->transport == RTSP_TRANSPORT_RAW)
1413  trans_pref = "RAW/RAW";
1414  else
1415  trans_pref = "RTP/AVP";
1416 
1417  /* default timeout: 1 minute */
1418  rt->timeout = 60;
1419 
1420  /* for each stream, make the setup request */
1421  /* XXX: we assume the same server is used for the control of each
1422  * RTSP stream */
1423 
1424  /* Choose a random starting offset within the first half of the
1425  * port range, to allow for a number of ports to try even if the offset
1426  * happens to be at the end of the random range. */
1427  port_off = av_get_random_seed() % ((rt->rtp_port_max - rt->rtp_port_min)/2);
1428  /* even random offset */
1429  port_off -= port_off & 0x01;
1430 
1431  for (j = rt->rtp_port_min + port_off, i = 0; i < rt->nb_rtsp_streams; ++i) {
1432  char transport[2048];
1433 
1434  /*
1435  * WMS serves all UDP data over a single connection, the RTX, which
1436  * isn't necessarily the first in the SDP but has to be the first
1437  * to be set up, else the second/third SETUP will fail with a 461.
1438  */
1439  if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
1440  rt->server_type == RTSP_SERVER_WMS) {
1441  if (i == 0) {
1442  /* rtx first */
1443  for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
1444  int len = strlen(rt->rtsp_streams[rtx]->control_url);
1445  if (len >= 4 &&
1446  !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
1447  "/rtx"))
1448  break;
1449  }
1450  if (rtx == rt->nb_rtsp_streams)
1451  return -1; /* no RTX found */
1452  rtsp_st = rt->rtsp_streams[rtx];
1453  } else
1454  rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
1455  } else
1456  rtsp_st = rt->rtsp_streams[i];
1457 
1458  /* RTP/UDP */
1459  if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
1460  char buf[256];
1461 
1462  if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
1463  port = reply->transports[0].client_port_min;
1464  goto have_port;
1465  }
1466 
1467  /* first try in specified port range */
1468  while (j <= rt->rtp_port_max) {
1469  AVDictionary *opts = map_to_opts(rt);
1470 
1471  ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
1472  "?localport=%d", j);
1473  /* we will use two ports per rtp stream (rtp and rtcp) */
1474  j += 2;
1475  err = ffurl_open(&rtsp_st->rtp_handle, buf, AVIO_FLAG_READ_WRITE,
1476  &s->interrupt_callback, &opts, rt->protocols, NULL);
1477 
1478  av_dict_free(&opts);
1479 
1480  if (!err)
1481  goto rtp_opened;
1482  }
1483 
1484  av_log(s, AV_LOG_ERROR, "Unable to open an input RTP port\n");
1485  err = AVERROR(EIO);
1486  goto fail;
1487 
1488  rtp_opened:
1489  port = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
1490  have_port:
1491  snprintf(transport, sizeof(transport) - 1,
1492  "%s/UDP;", trans_pref);
1493  if (rt->server_type != RTSP_SERVER_REAL)
1494  av_strlcat(transport, "unicast;", sizeof(transport));
1495  av_strlcatf(transport, sizeof(transport),
1496  "client_port=%d", port);
1497  if (rt->transport == RTSP_TRANSPORT_RTP &&
1498  !(rt->server_type == RTSP_SERVER_WMS && i > 0))
1499  av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
1500  }
1501 
1502  /* RTP/TCP */
1503  else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
1504  /* For WMS streams, the application streams are only used for
1505  * UDP. When trying to set it up for TCP streams, the server
1506  * will return an error. Therefore, we skip those streams. */
1507  if (rt->server_type == RTSP_SERVER_WMS &&
1508  (rtsp_st->stream_index < 0 ||
1509  s->streams[rtsp_st->stream_index]->codecpar->codec_type ==
1511  continue;
1512  snprintf(transport, sizeof(transport) - 1,
1513  "%s/TCP;", trans_pref);
1514  if (rt->transport != RTSP_TRANSPORT_RDT)
1515  av_strlcat(transport, "unicast;", sizeof(transport));
1516  av_strlcatf(transport, sizeof(transport),
1517  "interleaved=%d-%d",
1518  interleave, interleave + 1);
1519  interleave += 2;
1520  }
1521 
1522  else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
1523  snprintf(transport, sizeof(transport) - 1,
1524  "%s/UDP;multicast", trans_pref);
1525  }
1526  if (s->oformat) {
1527  av_strlcat(transport, ";mode=record", sizeof(transport));
1528  } else if (rt->server_type == RTSP_SERVER_REAL ||
1530  av_strlcat(transport, ";mode=play", sizeof(transport));
1531  snprintf(cmd, sizeof(cmd),
1532  "Transport: %s\r\n",
1533  transport);
1534  if (rt->accept_dynamic_rate)
1535  av_strlcat(cmd, "x-Dynamic-Rate: 0\r\n", sizeof(cmd));
1536  if (CONFIG_RTPDEC && i == 0 && rt->server_type == RTSP_SERVER_REAL) {
1537  char real_res[41], real_csum[9];
1538  ff_rdt_calc_response_and_checksum(real_res, real_csum,
1539  real_challenge);
1540  av_strlcatf(cmd, sizeof(cmd),
1541  "If-Match: %s\r\n"
1542  "RealChallenge2: %s, sd=%s\r\n",
1543  rt->session_id, real_res, real_csum);
1544  }
1545  ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
1546  if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
1547  err = 1;
1548  goto fail;
1549  } else if (reply->status_code != RTSP_STATUS_OK ||
1550  reply->nb_transports != 1) {
1551  err = AVERROR_INVALIDDATA;
1552  goto fail;
1553  }
1554 
1555  /* XXX: same protocol for all streams is required */
1556  if (i > 0) {
1557  if (reply->transports[0].lower_transport != rt->lower_transport ||
1558  reply->transports[0].transport != rt->transport) {
1559  err = AVERROR_INVALIDDATA;
1560  goto fail;
1561  }
1562  } else {
1563  rt->lower_transport = reply->transports[0].lower_transport;
1564  rt->transport = reply->transports[0].transport;
1565  }
1566 
1567  /* Fail if the server responded with another lower transport mode
1568  * than what we requested. */
1569  if (reply->transports[0].lower_transport != lower_transport) {
1570  av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
1571  err = AVERROR_INVALIDDATA;
1572  goto fail;
1573  }
1574 
1575  switch(reply->transports[0].lower_transport) {
1577  rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
1578  rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
1579  break;
1580 
1581  case RTSP_LOWER_TRANSPORT_UDP: {
1582  char url[1024], options[30] = "";
1583  const char *peer = host;
1584 
1585  if (rt->rtsp_flags & RTSP_FLAG_FILTER_SRC)
1586  av_strlcpy(options, "?connect=1", sizeof(options));
1587  /* Use source address if specified */
1588  if (reply->transports[0].source[0])
1589  peer = reply->transports[0].source;
1590  ff_url_join(url, sizeof(url), "rtp", NULL, peer,
1591  reply->transports[0].server_port_min, "%s", options);
1592  if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
1593  ff_rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
1594  err = AVERROR_INVALIDDATA;
1595  goto fail;
1596  }
1597  break;
1598  }
1600  char url[1024], namebuf[50], optbuf[20] = "";
1601  struct sockaddr_storage addr;
1602  int port, ttl;
1603 
1604  if (reply->transports[0].destination.ss_family) {
1605  addr = reply->transports[0].destination;
1606  port = reply->transports[0].port_min;
1607  ttl = reply->transports[0].ttl;
1608  } else {
1609  addr = rtsp_st->sdp_ip;
1610  port = rtsp_st->sdp_port;
1611  ttl = rtsp_st->sdp_ttl;
1612  }
1613  if (ttl > 0)
1614  snprintf(optbuf, sizeof(optbuf), "?ttl=%d", ttl);
1615  getnameinfo((struct sockaddr*) &addr, sizeof(addr),
1616  namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
1617  ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
1618  port, "%s", optbuf);
1619  if (ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
1620  &s->interrupt_callback, NULL, rt->protocols, NULL) < 0) {
1621  err = AVERROR_INVALIDDATA;
1622  goto fail;
1623  }
1624  break;
1625  }
1626  }
1627 
1628  if ((err = ff_rtsp_open_transport_ctx(s, rtsp_st)))
1629  goto fail;
1630  }
1631 
1632  if (rt->nb_rtsp_streams && reply->timeout > 0)
1633  rt->timeout = reply->timeout;
1634 
1635  if (rt->server_type == RTSP_SERVER_REAL)
1636  rt->need_subscription = 1;
1637 
1638  return 0;
1639 
1640 fail:
1641  ff_rtsp_undo_setup(s, 0);
1642  return err;
1643 }
1644 
1646 {
1647  RTSPState *rt = s->priv_data;
1648  if (rt->rtsp_hd_out != rt->rtsp_hd) ffurl_close(rt->rtsp_hd_out);
1649  ffurl_close(rt->rtsp_hd);
1650  rt->rtsp_hd = rt->rtsp_hd_out = NULL;
1651 }
1652 
1654 {
1655  RTSPState *rt = s->priv_data;
1656  char proto[128], host[1024], path[1024];
1657  char tcpname[1024], cmd[2048], auth[128];
1658  const char *lower_rtsp_proto = "tcp";
1659  int port, err, tcp_fd;
1660  RTSPMessageHeader reply1 = {0}, *reply = &reply1;
1661  int lower_transport_mask = 0;
1662  int default_port = RTSP_DEFAULT_PORT;
1663  char real_challenge[64] = "";
1664  struct sockaddr_storage peer;
1665  socklen_t peer_len = sizeof(peer);
1666 
1667  if (rt->rtp_port_max < rt->rtp_port_min) {
1668  av_log(s, AV_LOG_ERROR, "Invalid UDP port range, max port %d less "
1669  "than min port %d\n", rt->rtp_port_max,
1670  rt->rtp_port_min);
1671  return AVERROR(EINVAL);
1672  }
1673 
1674  if (!ff_network_init())
1675  return AVERROR(EIO);
1676 
1677  if (!rt->protocols) {
1679  s->protocol_blacklist);
1680  if (!rt->protocols)
1681  return AVERROR(ENOMEM);
1682  }
1683 
1684  if (s->max_delay < 0) /* Not set by the caller */
1686 
1691  }
1692  /* Only pass through valid flags from here */
1694 
1695 redirect:
1696  /* extract hostname and port */
1697  av_url_split(proto, sizeof(proto), auth, sizeof(auth),
1698  host, sizeof(host), &port, path, sizeof(path), s->filename);
1699 
1700  if (!strcmp(proto, "rtsps")) {
1701  lower_rtsp_proto = "tls";
1702  default_port = RTSPS_DEFAULT_PORT;
1704  }
1705 
1706  if (*auth) {
1707  av_strlcpy(rt->auth, auth, sizeof(rt->auth));
1708  }
1709  if (port < 0)
1710  port = default_port;
1711 
1712  lower_transport_mask = rt->lower_transport_mask;
1713 
1714  if (!lower_transport_mask)
1715  lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
1716 
1717  if (s->oformat) {
1718  /* Only UDP or TCP - UDP multicast isn't supported. */
1719  lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
1720  (1 << RTSP_LOWER_TRANSPORT_TCP);
1721  if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
1722  av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
1723  "only UDP and TCP are supported for output.\n");
1724  err = AVERROR(EINVAL);
1725  goto fail;
1726  }
1727  }
1728 
1729  /* Construct the URI used in request; this is similar to s->filename,
1730  * but with authentication credentials removed and RTSP specific options
1731  * stripped out. */
1732  ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL,
1733  host, port, "%s", path);
1734 
1735  if (rt->control_transport == RTSP_MODE_TUNNEL) {
1736  /* set up initial handshake for tunneling */
1737  char httpname[1024];
1738  char sessioncookie[17];
1739  char headers[1024];
1740 
1741  ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
1742  snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
1744 
1745  /* GET requests */
1746  if (ffurl_alloc(&rt->rtsp_hd, httpname, AVIO_FLAG_READ,
1747  &s->interrupt_callback, rt->protocols) < 0) {
1748  err = AVERROR(EIO);
1749  goto fail;
1750  }
1751 
1752  /* generate GET headers */
1753  snprintf(headers, sizeof(headers),
1754  "x-sessioncookie: %s\r\n"
1755  "Accept: application/x-rtsp-tunnelled\r\n"
1756  "Pragma: no-cache\r\n"
1757  "Cache-Control: no-cache\r\n",
1758  sessioncookie);
1759  av_opt_set(rt->rtsp_hd->priv_data, "headers", headers, 0);
1760 
1761  /* complete the connection */
1762  if (ffurl_connect(rt->rtsp_hd, NULL)) {
1763  err = AVERROR(EIO);
1764  goto fail;
1765  }
1766 
1767  /* POST requests */
1768  if (ffurl_alloc(&rt->rtsp_hd_out, httpname, AVIO_FLAG_WRITE,
1769  &s->interrupt_callback, rt->protocols) < 0 ) {
1770  err = AVERROR(EIO);
1771  goto fail;
1772  }
1773 
1774  /* generate POST headers */
1775  snprintf(headers, sizeof(headers),
1776  "x-sessioncookie: %s\r\n"
1777  "Content-Type: application/x-rtsp-tunnelled\r\n"
1778  "Pragma: no-cache\r\n"
1779  "Cache-Control: no-cache\r\n"
1780  "Content-Length: 32767\r\n"
1781  "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
1782  sessioncookie);
1783  av_opt_set(rt->rtsp_hd_out->priv_data, "headers", headers, 0);
1784  av_opt_set(rt->rtsp_hd_out->priv_data, "chunked_post", "0", 0);
1785 
1786  /* Initialize the authentication state for the POST session. The HTTP
1787  * protocol implementation doesn't properly handle multi-pass
1788  * authentication for POST requests, since it would require one of
1789  * the following:
1790  * - implementing Expect: 100-continue, which many HTTP servers
1791  * don't support anyway, even less the RTSP servers that do HTTP
1792  * tunneling
1793  * - sending the whole POST data until getting a 401 reply specifying
1794  * what authentication method to use, then resending all that data
1795  * - waiting for potential 401 replies directly after sending the
1796  * POST header (waiting for some unspecified time)
1797  * Therefore, we copy the full auth state, which works for both basic
1798  * and digest. (For digest, we would have to synchronize the nonce
1799  * count variable between the two sessions, if we'd do more requests
1800  * with the original session, though.)
1801  */
1803 
1804  /* complete the connection */
1805  if (ffurl_connect(rt->rtsp_hd_out, NULL)) {
1806  err = AVERROR(EIO);
1807  goto fail;
1808  }
1809  } else {
1810  /* open the tcp connection */
1811  ff_url_join(tcpname, sizeof(tcpname), lower_rtsp_proto, NULL,
1812  host, port, NULL);
1813  if (ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
1814  &s->interrupt_callback, NULL, rt->protocols, NULL) < 0) {
1815  err = AVERROR(EIO);
1816  goto fail;
1817  }
1818  rt->rtsp_hd_out = rt->rtsp_hd;
1819  }
1820  rt->seq = 0;
1821 
1822  tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
1823  if (tcp_fd < 0) {
1824  err = tcp_fd;
1825  goto fail;
1826  }
1827  if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
1828  getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
1829  NULL, 0, NI_NUMERICHOST);
1830  }
1831 
1832  /* request options supported by the server; this also detects server
1833  * type */
1834  for (rt->server_type = RTSP_SERVER_RTP;;) {
1835  cmd[0] = 0;
1836  if (rt->server_type == RTSP_SERVER_REAL)
1837  av_strlcat(cmd,
1838  /*
1839  * The following entries are required for proper
1840  * streaming from a Realmedia server. They are
1841  * interdependent in some way although we currently
1842  * don't quite understand how. Values were copied
1843  * from mplayer SVN r23589.
1844  * ClientChallenge is a 16-byte ID in hex
1845  * CompanyID is a 16-byte ID in base64
1846  */
1847  "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
1848  "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
1849  "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
1850  "GUID: 00000000-0000-0000-0000-000000000000\r\n",
1851  sizeof(cmd));
1852  ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
1853  if (reply->status_code != RTSP_STATUS_OK) {
1854  err = AVERROR_INVALIDDATA;
1855  goto fail;
1856  }
1857 
1858  /* detect server type if not standard-compliant RTP */
1859  if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
1861  continue;
1862  } else if (!av_strncasecmp(reply->server, "WMServer/", 9)) {
1864  } else if (rt->server_type == RTSP_SERVER_REAL)
1865  strcpy(real_challenge, reply->real_challenge);
1866  break;
1867  }
1868 
1869  if (CONFIG_RTSP_DEMUXER && s->iformat)
1870  err = ff_rtsp_setup_input_streams(s, reply);
1871  else if (CONFIG_RTSP_MUXER)
1872  err = ff_rtsp_setup_output_streams(s, host);
1873  if (err)
1874  goto fail;
1875 
1876  do {
1877  int lower_transport = ff_log2_tab[lower_transport_mask &
1878  ~(lower_transport_mask - 1)];
1879 
1880  err = ff_rtsp_make_setup_request(s, host, port, lower_transport,
1881  rt->server_type == RTSP_SERVER_REAL ?
1882  real_challenge : NULL);
1883  if (err < 0)
1884  goto fail;
1885  lower_transport_mask &= ~(1 << lower_transport);
1886  if (lower_transport_mask == 0 && err == 1) {
1887  err = AVERROR(EPROTONOSUPPORT);
1888  goto fail;
1889  }
1890  } while (err);
1891 
1892  rt->lower_transport_mask = lower_transport_mask;
1893  av_strlcpy(rt->real_challenge, real_challenge, sizeof(rt->real_challenge));
1894  rt->state = RTSP_STATE_IDLE;
1895  rt->seek_timestamp = 0; /* default is to start stream at position zero */
1896  return 0;
1897  fail:
1900  if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
1901  av_strlcpy(s->filename, reply->location, sizeof(s->filename));
1902  rt->session_id[0] = '\0';
1903  av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
1904  reply->status_code,
1905  s->filename);
1906  goto redirect;
1907  }
1908  ff_network_close();
1909  return err;
1910 }
1911 #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
1912 
1913 #if CONFIG_RTPDEC
1914 static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
1915  uint8_t *buf, int buf_size, int64_t wait_end)
1916 {
1917  RTSPState *rt = s->priv_data;
1918  RTSPStream *rtsp_st;
1919  int n, i, ret, tcp_fd, timeout_cnt = 0;
1920  int max_p = 0;
1921  struct pollfd *p = rt->p;
1922  int *fds = NULL, fdsnum, fdsidx;
1923 
1924  for (;;) {
1926  return AVERROR_EXIT;
1927  if (wait_end && wait_end - av_gettime_relative() < 0)
1928  return AVERROR(EAGAIN);
1929  max_p = 0;
1930  if (rt->rtsp_hd) {
1931  tcp_fd = ffurl_get_file_handle(rt->rtsp_hd);
1932  p[max_p].fd = tcp_fd;
1933  p[max_p++].events = POLLIN;
1934  } else {
1935  tcp_fd = -1;
1936  }
1937  for (i = 0; i < rt->nb_rtsp_streams; i++) {
1938  rtsp_st = rt->rtsp_streams[i];
1939  if (rtsp_st->rtp_handle) {
1940  if (ret = ffurl_get_multi_file_handle(rtsp_st->rtp_handle,
1941  &fds, &fdsnum)) {
1942  av_log(s, AV_LOG_ERROR, "Unable to recover rtp ports\n");
1943  return ret;
1944  }
1945  if (fdsnum != 2) {
1946  av_log(s, AV_LOG_ERROR,
1947  "Number of fds %d not supported\n", fdsnum);
1948  return AVERROR_INVALIDDATA;
1949  }
1950  for (fdsidx = 0; fdsidx < fdsnum; fdsidx++) {
1951  p[max_p].fd = fds[fdsidx];
1952  p[max_p++].events = POLLIN;
1953  }
1954  av_free(fds);
1955  }
1956  }
1957  n = poll(p, max_p, POLL_TIMEOUT_MS);
1958  if (n > 0) {
1959  int j = 1 - (tcp_fd == -1);
1960  timeout_cnt = 0;
1961  for (i = 0; i < rt->nb_rtsp_streams; i++) {
1962  rtsp_st = rt->rtsp_streams[i];
1963  if (rtsp_st->rtp_handle) {
1964  if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {
1965  ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);
1966  if (ret > 0) {
1967  *prtsp_st = rtsp_st;
1968  return ret;
1969  }
1970  }
1971  j+=2;
1972  }
1973  }
1974 #if CONFIG_RTSP_DEMUXER
1975  if (tcp_fd != -1 && p[0].revents & POLLIN) {
1976  if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
1977  if (rt->state == RTSP_STATE_STREAMING) {
1979  return AVERROR_EOF;
1980  else
1982  "Unable to answer to TEARDOWN\n");
1983  } else
1984  return 0;
1985  } else {
1986  RTSPMessageHeader reply;
1987  ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
1988  if (ret < 0)
1989  return ret;
1990  /* XXX: parse message */
1991  if (rt->state != RTSP_STATE_STREAMING)
1992  return 0;
1993  }
1994  }
1995 #endif
1996  } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
1997  return AVERROR(ETIMEDOUT);
1998  } else if (n < 0 && errno != EINTR)
1999  return AVERROR(errno);
2000  }
2001 }
2002 
2003 static int pick_stream(AVFormatContext *s, RTSPStream **rtsp_st,
2004  const uint8_t *buf, int len)
2005 {
2006  RTSPState *rt = s->priv_data;
2007  int i;
2008  if (len < 0)
2009  return len;
2010  if (rt->nb_rtsp_streams == 1) {
2011  *rtsp_st = rt->rtsp_streams[0];
2012  return len;
2013  }
2014  if (len >= 8 && rt->transport == RTSP_TRANSPORT_RTP) {
2015  if (RTP_PT_IS_RTCP(rt->recvbuf[1])) {
2016  int no_ssrc = 0;
2017  for (i = 0; i < rt->nb_rtsp_streams; i++) {
2018  RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
2019  if (!rtpctx)
2020  continue;
2021  if (rtpctx->ssrc == AV_RB32(&buf[4])) {
2022  *rtsp_st = rt->rtsp_streams[i];
2023  return len;
2024  }
2025  if (!rtpctx->ssrc)
2026  no_ssrc = 1;
2027  }
2028  if (no_ssrc) {
2030  "Unable to pick stream for packet - SSRC not known for "
2031  "all streams\n");
2032  return AVERROR(EAGAIN);
2033  }
2034  } else {
2035  for (i = 0; i < rt->nb_rtsp_streams; i++) {
2036  if ((buf[1] & 0x7f) == rt->rtsp_streams[i]->sdp_payload_type) {
2037  *rtsp_st = rt->rtsp_streams[i];
2038  return len;
2039  }
2040  }
2041  }
2042  }
2043  av_log(s, AV_LOG_WARNING, "Unable to pick stream for packet\n");
2044  return AVERROR(EAGAIN);
2045 }
2046 
2048 {
2049  RTSPState *rt = s->priv_data;
2050  int ret, len;
2051  RTSPStream *rtsp_st, *first_queue_st = NULL;
2052  int64_t wait_end = 0;
2053 
2054  if (rt->nb_byes == rt->nb_rtsp_streams)
2055  return AVERROR_EOF;
2056 
2057  /* get next frames from the same RTP packet */
2058  if (rt->cur_transport_priv) {
2059  if (rt->transport == RTSP_TRANSPORT_RDT) {
2060  ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
2061  } else if (rt->transport == RTSP_TRANSPORT_RTP) {
2062  ret = ff_rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
2063  } else if (CONFIG_RTPDEC && rt->ts) {
2064  ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf + rt->recvbuf_pos, rt->recvbuf_len - rt->recvbuf_pos);
2065  if (ret >= 0) {
2066  rt->recvbuf_pos += ret;
2067  ret = rt->recvbuf_pos < rt->recvbuf_len;
2068  }
2069  } else
2070  ret = -1;
2071  if (ret == 0) {
2072  rt->cur_transport_priv = NULL;
2073  return 0;
2074  } else if (ret == 1) {
2075  return 0;
2076  } else
2077  rt->cur_transport_priv = NULL;
2078  }
2079 
2080 redo:
2081  if (rt->transport == RTSP_TRANSPORT_RTP) {
2082  int i;
2083  int64_t first_queue_time = 0;
2084  for (i = 0; i < rt->nb_rtsp_streams; i++) {
2085  RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
2086  int64_t queue_time;
2087  if (!rtpctx)
2088  continue;
2089  queue_time = ff_rtp_queued_packet_time(rtpctx);
2090  if (queue_time && (queue_time - first_queue_time < 0 ||
2091  !first_queue_time)) {
2092  first_queue_time = queue_time;
2093  first_queue_st = rt->rtsp_streams[i];
2094  }
2095  }
2096  if (first_queue_time) {
2097  wait_end = first_queue_time + s->max_delay;
2098  } else {
2099  wait_end = 0;
2100  first_queue_st = NULL;
2101  }
2102  }
2103 
2104  /* read next RTP packet */
2105  if (!rt->recvbuf) {
2107  if (!rt->recvbuf)
2108  return AVERROR(ENOMEM);
2109  }
2110 
2111  switch(rt->lower_transport) {
2112  default:
2113 #if CONFIG_RTSP_DEMUXER
2115  len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
2116  break;
2117 #endif
2120  len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
2121  if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
2122  ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, rtsp_st->rtp_handle, NULL, len);
2123  break;
2125  if (first_queue_st && rt->transport == RTSP_TRANSPORT_RTP &&
2126  wait_end && wait_end < av_gettime_relative())
2127  len = AVERROR(EAGAIN);
2128  else
2129  len = ffio_read_partial(s->pb, rt->recvbuf, RECVBUF_SIZE);
2130  len = pick_stream(s, &rtsp_st, rt->recvbuf, len);
2131  if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
2133  break;
2134  }
2135  if (len == AVERROR(EAGAIN) && first_queue_st &&
2136  rt->transport == RTSP_TRANSPORT_RTP) {
2138  "max delay reached. need to consume packet\n");
2139  rtsp_st = first_queue_st;
2140  ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
2141  goto end;
2142  }
2143  if (len < 0)
2144  return len;
2145  if (len == 0)
2146  return AVERROR_EOF;
2147  if (rt->transport == RTSP_TRANSPORT_RDT) {
2148  ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
2149  } else if (rt->transport == RTSP_TRANSPORT_RTP) {
2150  ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
2151  if (rtsp_st->feedback) {
2152  AVIOContext *pb = NULL;
2154  pb = s->pb;
2155  ff_rtp_send_rtcp_feedback(rtsp_st->transport_priv, rtsp_st->rtp_handle, pb);
2156  }
2157  if (ret < 0) {
2158  /* Either bad packet, or a RTCP packet. Check if the
2159  * first_rtcp_ntp_time field was initialized. */
2160  RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
2161  if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
2162  /* first_rtcp_ntp_time has been initialized for this stream,
2163  * copy the same value to all other uninitialized streams,
2164  * in order to map their timestamp origin to the same ntp time
2165  * as this one. */
2166  int i;
2167  AVStream *st = NULL;
2168  if (rtsp_st->stream_index >= 0)
2169  st = s->streams[rtsp_st->stream_index];
2170  for (i = 0; i < rt->nb_rtsp_streams; i++) {
2171  RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
2172  AVStream *st2 = NULL;
2173  if (rt->rtsp_streams[i]->stream_index >= 0)
2174  st2 = s->streams[rt->rtsp_streams[i]->stream_index];
2175  if (rtpctx2 && st && st2 &&
2176  rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
2177  rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
2178  rtpctx2->rtcp_ts_offset = av_rescale_q(
2179  rtpctx->rtcp_ts_offset, st->time_base,
2180  st2->time_base);
2181  }
2182  }
2183  }
2184  if (ret == -RTCP_BYE) {
2185  rt->nb_byes++;
2186 
2187  av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
2188  rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
2189 
2190  if (rt->nb_byes == rt->nb_rtsp_streams)
2191  return AVERROR_EOF;
2192  }
2193  }
2194  } else if (CONFIG_RTPDEC && rt->ts) {
2195  ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf, len);
2196  if (ret >= 0) {
2197  if (ret < len) {
2198  rt->recvbuf_len = len;
2199  rt->recvbuf_pos = ret;
2200  rt->cur_transport_priv = rt->ts;
2201  return 1;
2202  } else {
2203  ret = 0;
2204  }
2205  }
2206  } else {
2207  return AVERROR_INVALIDDATA;
2208  }
2209 end:
2210  if (ret < 0)
2211  goto redo;
2212  if (ret == 1)
2213  /* more packets may follow, so we save the RTP context */
2214  rt->cur_transport_priv = rtsp_st->transport_priv;
2215 
2216  return ret;
2217 }
2218 #endif /* CONFIG_RTPDEC */
2219 
2220 #if CONFIG_SDP_DEMUXER
2221 static int sdp_probe(AVProbeData *p1)
2222 {
2223  const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
2224 
2225  /* we look for a line beginning "c=IN IP" */
2226  while (p < p_end && *p != '\0') {
2227  if (p + sizeof("c=IN IP") - 1 < p_end &&
2228  av_strstart(p, "c=IN IP", NULL))
2229  return AVPROBE_SCORE_EXTENSION;
2230 
2231  while (p < p_end - 1 && *p != '\n') p++;
2232  if (++p >= p_end)
2233  break;
2234  if (*p == '\r')
2235  p++;
2236  }
2237  return 0;
2238 }
2239 
2240 static void append_source_addrs(char *buf, int size, const char *name,
2241  int count, struct RTSPSource **addrs)
2242 {
2243  int i;
2244  if (!count)
2245  return;
2246  av_strlcatf(buf, size, "&%s=%s", name, addrs[0]->addr);
2247  for (i = 1; i < count; i++)
2248  av_strlcatf(buf, size, ",%s", addrs[i]->addr);
2249 }
2250 
2251 static int sdp_read_header(AVFormatContext *s)
2252 {
2253  RTSPState *rt = s->priv_data;
2254  RTSPStream *rtsp_st;
2255  int size, i, err;
2256  char *content;
2257  char url[1024];
2258 
2259  if (!ff_network_init())
2260  return AVERROR(EIO);
2261 
2262  if (!rt->protocols) {
2264  s->protocol_blacklist);
2265  if (!rt->protocols)
2266  return AVERROR(ENOMEM);
2267  }
2268 
2269  if (s->max_delay < 0) /* Not set by the caller */
2271  if (rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)
2273 
2274  /* read the whole sdp file */
2275  /* XXX: better loading */
2276  content = av_malloc(SDP_MAX_SIZE);
2277  if (!content)
2278  return AVERROR(ENOMEM);
2279  size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);
2280  if (size <= 0) {
2281  av_free(content);
2282  return AVERROR_INVALIDDATA;
2283  }
2284  content[size] ='\0';
2285 
2286  err = ff_sdp_parse(s, content);
2287  av_free(content);
2288  if (err) goto fail;
2289 
2290  /* open each RTP stream */
2291  for (i = 0; i < rt->nb_rtsp_streams; i++) {
2292  char namebuf[50];
2293  rtsp_st = rt->rtsp_streams[i];
2294 
2295  if (!(rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)) {
2296  AVDictionary *opts = map_to_opts(rt);
2297 
2298  err = getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip,
2299  sizeof(rtsp_st->sdp_ip),
2300  namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
2301  if (err) {
2302  av_log(s, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(err));
2303  err = AVERROR(EIO);
2304  av_dict_free(&opts);
2305  goto fail;
2306  }
2307  ff_url_join(url, sizeof(url), "rtp", NULL,
2308  namebuf, rtsp_st->sdp_port,
2309  "?localport=%d&ttl=%d&connect=%d&write_to_source=%d",
2310  rtsp_st->sdp_port, rtsp_st->sdp_ttl,
2311  rt->rtsp_flags & RTSP_FLAG_FILTER_SRC ? 1 : 0,
2312  rt->rtsp_flags & RTSP_FLAG_RTCP_TO_SOURCE ? 1 : 0);
2313 
2314  append_source_addrs(url, sizeof(url), "sources",
2315  rtsp_st->nb_include_source_addrs,
2316  rtsp_st->include_source_addrs);
2317  append_source_addrs(url, sizeof(url), "block",
2318  rtsp_st->nb_exclude_source_addrs,
2319  rtsp_st->exclude_source_addrs);
2320  err = ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
2321  &s->interrupt_callback, &opts, rt->protocols, NULL);
2322 
2323  av_dict_free(&opts);
2324 
2325  if (err < 0) {
2326  err = AVERROR_INVALIDDATA;
2327  goto fail;
2328  }
2329  }
2330  if ((err = ff_rtsp_open_transport_ctx(s, rtsp_st)))
2331  goto fail;
2332  }
2333  return 0;
2334 fail:
2336  ff_network_close();
2337  return err;
2338 }
2339 
2340 static int sdp_read_close(AVFormatContext *s)
2341 {
2343  ff_network_close();
2344  return 0;
2345 }
2346 
2347 static const AVClass sdp_demuxer_class = {
2348  .class_name = "SDP demuxer",
2349  .item_name = av_default_item_name,
2350  .option = sdp_options,
2351  .version = LIBAVUTIL_VERSION_INT,
2352 };
2353 
2354 AVInputFormat ff_sdp_demuxer = {
2355  .name = "sdp",
2356  .long_name = NULL_IF_CONFIG_SMALL("SDP"),
2357  .priv_data_size = sizeof(RTSPState),
2358  .read_probe = sdp_probe,
2359  .read_header = sdp_read_header,
2361  .read_close = sdp_read_close,
2362  .priv_class = &sdp_demuxer_class,
2363 };
2364 #endif /* CONFIG_SDP_DEMUXER */
2365 
2366 #if CONFIG_RTP_DEMUXER
2367 static int rtp_probe(AVProbeData *p)
2368 {
2369  if (av_strstart(p->filename, "rtp:", NULL))
2370  return AVPROBE_SCORE_MAX;
2371  return 0;
2372 }
2373 
2374 static int rtp_read_header(AVFormatContext *s)
2375 {
2376  uint8_t recvbuf[RTP_MAX_PACKET_LENGTH];
2377  char host[500], sdp[500];
2378  int ret, port;
2379  URLContext* in = NULL;
2380  int payload_type;
2381  AVCodecParameters *par = NULL;
2382  struct sockaddr_storage addr;
2383  AVIOContext pb;
2384  socklen_t addrlen = sizeof(addr);
2385  RTSPState *rt = s->priv_data;
2386 
2387  if (!ff_network_init())
2388  return AVERROR(EIO);
2389 
2390  if (!rt->protocols) {
2392  s->protocol_blacklist);
2393  if (!rt->protocols)
2394  return AVERROR(ENOMEM);
2395  }
2396 
2397  ret = ffurl_open(&in, s->filename, AVIO_FLAG_READ,
2398  &s->interrupt_callback, NULL, rt->protocols, NULL);
2399  if (ret)
2400  goto fail;
2401 
2402  while (1) {
2403  ret = ffurl_read(in, recvbuf, sizeof(recvbuf));
2404  if (ret == AVERROR(EAGAIN))
2405  continue;
2406  if (ret < 0)
2407  goto fail;
2408  if (ret < 12) {
2409  av_log(s, AV_LOG_WARNING, "Received too short packet\n");
2410  continue;
2411  }
2412 
2413  if ((recvbuf[0] & 0xc0) != 0x80) {
2414  av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
2415  "received\n");
2416  continue;
2417  }
2418 
2419  if (RTP_PT_IS_RTCP(recvbuf[1]))
2420  continue;
2421 
2422  payload_type = recvbuf[1] & 0x7f;
2423  break;
2424  }
2425  getsockname(ffurl_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
2426  ffurl_close(in);
2427  in = NULL;
2428 
2429  par = avcodec_parameters_alloc();
2430  if (!par) {
2431  ret = AVERROR(ENOMEM);
2432  goto fail;
2433  }
2434 
2435  if (ff_rtp_get_codec_info(par, payload_type)) {
2436  av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
2437  "without an SDP file describing it\n",
2438  payload_type);
2439  goto fail;
2440  }
2441  if (par->codec_type != AVMEDIA_TYPE_DATA) {
2442  av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
2443  "properly you need an SDP file "
2444  "describing it\n");
2445  }
2446 
2447  av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
2448  NULL, 0, s->filename);
2449 
2450  snprintf(sdp, sizeof(sdp),
2451  "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
2452  addr.ss_family == AF_INET ? 4 : 6, host,
2453  par->codec_type == AVMEDIA_TYPE_DATA ? "application" :
2454  par->codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
2455  port, payload_type);
2456  av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
2458 
2459  ffio_init_context(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
2460  s->pb = &pb;
2461 
2462  /* sdp_read_header initializes this again */
2463  ff_network_close();
2464 
2465  rt->media_type_mask = (1 << (AVMEDIA_TYPE_DATA+1)) - 1;
2466 
2467  ret = sdp_read_header(s);
2468  s->pb = NULL;
2469  return ret;
2470 
2471 fail:
2473  if (in)
2474  ffurl_close(in);
2475  ff_network_close();
2476  return ret;
2477 }
2478 
2479 static const AVClass rtp_demuxer_class = {
2480  .class_name = "RTP demuxer",
2481  .item_name = av_default_item_name,
2482  .option = rtp_options,
2483  .version = LIBAVUTIL_VERSION_INT,
2484 };
2485 
2486 AVInputFormat ff_rtp_demuxer = {
2487  .name = "rtp",
2488  .long_name = NULL_IF_CONFIG_SMALL("RTP input"),
2489  .priv_data_size = sizeof(RTSPState),
2490  .read_probe = rtp_probe,
2491  .read_header = rtp_read_header,
2493  .read_close = sdp_read_close,
2494  .flags = AVFMT_NOFILE,
2495  .priv_class = &rtp_demuxer_class,
2496 };
2497 #endif /* CONFIG_RTP_DEMUXER */
char auth[128]
plaintext authorization line (username:password)
Definition: rtsp.h:273
int interleaved_min
interleave ids, if TCP transport; each TCP/RTSP data packet starts with a &#39;$&#39;, stream length and stre...
Definition: rtsp.h:93
void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url)
Split a URL string into components.
Definition: utils.c:2870
char crypto_suite[40]
Definition: rtsp.h:466
void ff_rtsp_skip_packet(AVFormatContext *s)
Skip a RTP/TCP interleaved packet.
int rtp_port_min
Minimum and maximum local UDP ports.
Definition: rtsp.h:387
int ff_wms_parse_sdp_a_line(AVFormatContext *s, const char *p)
Parse a Windows Media Server-specific SDP line.
Definition: rtpdec_asf.c:96
void ff_rtp_parse_set_crypto(RTPDemuxContext *s, const char *suite, const char *params)
Definition: rtpdec.c:545
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:62
Bytestream IO Context.
Definition: avio.h:104
Realmedia Data Transport.
Definition: rtsp.h:58
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:54
int ff_rtp_get_local_rtp_port(URLContext *h)
Return the local rtp port used by the RTP connection.
Definition: rtpproto.c:541
int size
#define RTP_MAX_PACKET_LENGTH
Definition: rtpdec.h:36
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1181
AVOption.
Definition: opt.h:234
char source[INET6_ADDRSTRLEN+1]
source IP address
Definition: rtsp.h:115
HTTPAuthType
Authentication types, ordered from weakest to strongest.
Definition: httpauth.h:28
char content_type[64]
Content type header.
Definition: rtsp.h:187
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:130
const char * filename
Definition: avformat.h:399
static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
Parse a string p in the form of Range:npt=xx-xx, and determine the start and end time.
Definition: rtsp.c:160
char control_uri[1024]
some MS RTSP streams contain a URL in the SDP that we need to use for all subsequent RTSP requests...
Definition: rtsp.h:317
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:2986
int av_parse_time(int64_t *timeval, const char *timestr, int duration)
Parse timestr and return in *time a corresponding number of microseconds.
Definition: parseutils.c:495
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:257
const char * desc
Definition: nvenc.c:101
#define RTSP_DEFAULT_PORT
Definition: rtsp.h:72
#define CONFIG_RTPDEC
Definition: config.h:495
Windows Media server.
Definition: rtsp.h:209
struct pollfd * p
Polling array for udp.
Definition: rtsp.h:354
int ff_rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
Open RTSP transport context.
Definition: rtsp.c:789
int ffurl_connect(URLContext *uc, AVDictionary **options)
Connect an URLContext that has been allocated by ffurl_alloc.
Definition: avio.c:119
static int parse_fmtp(AVFormatContext *s, AVStream *stream, PayloadContext *data, const char *attr, const char *value)
Definition: rtpdec_latm.c:134
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3483
int ff_rdt_parse_packet(RDTDemuxContext *s, AVPacket *pkt, uint8_t **bufptr, int len)
Parse RDT-style packet data (header + media data).
Definition: rdt.c:335
int index
stream index in AVFormatContext
Definition: avformat.h:706
av_log(ac->avr, AV_LOG_TRACE, "%d samples - audio_convert: %s to %s (%s)\, len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt), use_generic ? ac->func_descr_generic :ac->func_descr)
#define AVIO_FLAG_READ
read-only
Definition: avio.h:368
char location[4096]
the "Location:" field.
Definition: rtsp.h:152
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:369
int mode_record
transport set to record data
Definition: rtsp.h:112
enum AVMediaType codec_type
Definition: rtp.c:36
int av_strncasecmp(const char *a, const char *b, size_t n)
Locale-independent case-insensitive compare.
Definition: avstring.c:166
void ff_network_close(void)
Definition: network.c:77
UDP/unicast.
Definition: rtsp.h:38
int seq
sequence number
Definition: rtsp.h:144
initialized and sending/receiving data
Definition: rtsp.h:197
char real_challenge[64]
the "RealChallenge1:" field from the server
Definition: rtsp.h:270
#define RTSP_FLAG_RTCP_TO_SOURCE
Send RTCP packets to the source address of received packets.
Definition: rtsp.h:412
#define RTSP_RTP_PORT_MAX
Definition: rtsp.h:79
#define freeaddrinfo
Definition: network.h:187
int nb_include_source_addrs
Number of source-specific multicast include source IP addresses (from SDP content) ...
Definition: rtsp.h:443
int ctx_flags
Flags signalling stream properties.
Definition: avformat.h:989
#define RTSP_FLAG_LISTEN
Wait for incoming connections.
Definition: rtsp.h:410
char session_id[512]
copy of RTSPMessageHeader->session_id, i.e.
Definition: rtsp.h:245
int64_t seek_timestamp
the seek value requested when calling av_seek_frame().
Definition: rtsp.h:239
const char * ff_rtp_enc_name(int payload_type)
Return the encoding name (as defined in http://www.iana.org/assignments/rtp-parameters) for a given p...
Definition: rtp.c:131
#define AI_NUMERICHOST
Definition: network.h:156
This struct describes the properties of an encoded stream.
Definition: avcodec.h:3475
int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port, int lower_transport, const char *real_challenge)
Do the SETUP requests for each stream for the chosen lower transport mode.
enum RTSPLowerTransport lower_transport
network layer transport protocol; e.g.
Definition: rtsp.h:121
This describes the server response to each RTSP command.
Definition: rtsp.h:127
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:502
#define RECVBUF_SIZE
Definition: rtsp.c:58
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:202
RTSPTransportField transports[RTSP_MAX_TRANSPORTS]
describes the complete "Transport:" line of the server in response to a SETUP RTSP command by the cli...
Definition: rtsp.h:142
Format I/O context.
Definition: avformat.h:940
#define RTP_PT_PRIVATE
Definition: rtp.h:77
#define COMMON_OPTS()
Definition: rtsp.c:75
enum AVCodecID ff_rtp_codec_id(const char *buf, enum AVMediaType codec_type)
Return the codec id for the given encoding name and codec type.
Definition: rtp.c:142
int ff_rtsp_connect(AVFormatContext *s)
Connect to the RTSP server and set up the individual media streams.
Standards-compliant RTP-server.
Definition: rtsp.h:207
int reordering_queue_size
Size of RTP packet reordering queue.
Definition: rtsp.h:397
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:39
int recvbuf_len
Definition: rtsp.h:323
Public dictionary API.
int av_stristart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str independent of case.
Definition: avstring.c:43
int get_parameter_supported
Whether the server supports the GET_PARAMETER method.
Definition: rtsp.h:359
#define CONFIG_RTSP_DEMUXER
Definition: config.h:1003
Standards-compliant RTP.
Definition: rtsp.h:57
uint8_t
char session_id[512]
the "Session:" field.
Definition: rtsp.h:148
#define RTSP_MAX_TRANSPORTS
Definition: rtsp.h:74
Opaque data information usually continuous.
Definition: avutil.h:196
int ttl
time-to-live value (required for multicast); the amount of HOPs that packets will be allowed to make ...
Definition: rtsp.h:109
static int get_sockaddr(AVFormatContext *s, const char *buf, struct sockaddr_storage *sock)
Definition: rtsp.c:181
int ff_network_init(void)
Definition: network.c:50
#define AVFMTCTX_NOHEADER
signal that no header is present (streams are added dynamically)
Definition: avformat.h:919
AVOptions.
AVCodecParameters * avcodec_parameters_alloc(void)
Allocate a new AVCodecParameters and set its fields to default values (unknown/invalid/0).
Definition: utils.c:2798
miscellaneous OS support macros and functions.
int feedback
Enable sending RTCP feedback messages according to RFC 4585.
Definition: rtsp.h:461
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:150
#define AV_RB32
Definition: intreadwrite.h:130
uint16_t ss_family
Definition: network.h:93
int id
Format-specific stream ID.
Definition: avformat.h:712
enum AVStreamParseType need_parsing
Definition: avformat.h:879
#define POLL_TIMEOUT_MS
Definition: rtsp.c:54
#define DEFAULT_REORDERING_DELAY
Definition: rtsp.c:59
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2648
int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size)
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1008
int accept_dynamic_rate
Whether the server accepts the x-Dynamic-Rate header.
Definition: rtsp.h:372
URLContext * rtsp_hd_out
Additional output handle, used when input and output are done separately, eg for HTTP tunneling...
Definition: rtsp.h:328
int ff_rtp_get_codec_info(AVCodecParameters *par, int payload_type)
Initialize a codec context based on the payload type.
Definition: rtp.c:70
Describe a single stream, as identified by a single m= line block in the SDP content.
Definition: rtsp.h:426
Custom IO - not a public option for lower_transport_mask, but set in the SDP demuxer based on a flag...
Definition: rtsp.h:45
char * protocol_whitelist
A comma-separated list of protocol names that can be used internally by libavformat.
Definition: avformat.h:1294
static int flags
Definition: log.c:50
#define CONFIG_RTSP_MUXER
Definition: config.h:1406
enum RTSPStatusCode status_code
response code from server
Definition: rtsp.h:131
#define AVERROR_EOF
End of file.
Definition: error.h:51
void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
Initialize the authentication state based on another HTTP URLContext.
Definition: http.c:127
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:140
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
const uint8_t ff_log2_tab[256]
Definition: log2_tab.c:21
int ffurl_open(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options, const URLProtocol **protocols, URLContext *parent)
Create an URLContext for accessing to the resource indicated by url, and open it. ...
Definition: avio.c:175
int ff_rtsp_parse_streaming_commands(AVFormatContext *s)
Parse RTSP commands (OPTIONS, PAUSE and TEARDOWN) during streaming in listen mode.
Definition: rtspdec.c:462
int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url, const char *headers, RTSPMessageHeader *reply, unsigned char **content_ptr)
Send a command to the RTSP server and wait for the reply.
Normal RTSP.
Definition: rtsp.h:68
int nb_transports
number of items in the &#39;transports&#39; variable below
Definition: rtsp.h:134
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:545
void ff_rtsp_parse_line(AVFormatContext *s, RTSPMessageHeader *reply, const char *buf, RTSPState *rt, const char *method)
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:959
int notice
The "Notice" or "X-Notice" field value.
Definition: rtsp.h:177
const OptionDef options[]
Definition: avconv_opt.c:2447
#define RTSP_DEFAULT_AUDIO_SAMPLERATE
Definition: rtsp.h:77
void ff_rdt_parse_close(RDTDemuxContext *s)
Definition: rdt.c:78
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:99
int ff_sdp_parse(AVFormatContext *s, const char *content)
Parse an SDP description of streams by populating an RTSPState struct within the AVFormatContext; als...
struct RTSPSource ** exclude_source_addrs
Source-specific multicast exclude source IP addresses (from SDP content)
Definition: rtsp.h:446
Private data for the RTSP demuxer.
Definition: rtsp.h:218
int64_t last_cmd_time
timestamp of the last RTSP command that we sent to the RTSP server.
Definition: rtsp.h:255
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:124
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1148
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:190
int ffurl_get_multi_file_handle(URLContext *h, int **handles, int *numhandles)
Return the file descriptors associated with this URL.
Definition: avio.c:352
int timeout
copy of RTSPMessageHeader->timeout, i.e.
Definition: rtsp.h:250
#define AV_RB16
Definition: intreadwrite.h:53
#define AVERROR(e)
Definition: error.h:43
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:148
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition: aviobuf.c:983
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:145
const AVOption ff_rtsp_options[]
Definition: rtsp.c:80
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:175
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3479
char reason[256]
The "reason" is meant to specify better the meaning of the error code returned.
Definition: rtsp.h:182
Definition: graph2dot.c:48
URLContext * rtsp_hd
Definition: rtsp.h:220
enum RTSPControlTransport control_transport
RTSP transport mode, such as plain or tunneled.
Definition: rtsp.h:331
struct RTSPSource ** include_source_addrs
Source-specific multicast include source IP addresses (from SDP content)
Definition: rtsp.h:444
int ffio_read_partial(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:612
int ffurl_alloc(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb, const URLProtocol **protocols)
Create a URLContext for accessing to the resource indicated by url, but do not initiate the connectio...
Definition: avio.c:143
char * av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size)
Encode data to base64 and null-terminate.
Definition: base64.c:72
void avcodec_parameters_free(AVCodecParameters **par)
Free an AVCodecParameters instance and everything associated with it and write NULL to the supplied p...
Definition: utils.c:2808
int64_t rtcp_ts_offset
Definition: rtpdec.h:182
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:81
#define fail()
Definition: checkasm.h:80
RTPDynamicProtocolHandler * ff_rtp_handler_find_by_id(int id, enum AVMediaType codec_type)
Definition: rtpdec.c:125
struct RTSPStream ** rtsp_streams
streams in this session
Definition: rtsp.h:225
char server[64]
the "Server: field, which can be used to identify some special-case servers that are not 100% standar...
Definition: rtsp.h:164
const AVCodecDescriptor * avcodec_descriptor_get(enum AVCodecID id)
Definition: codec_desc.c:2462
int stream_index
corresponding stream index, if any.
Definition: rtsp.h:431
MpegTSContext * ff_mpegts_parse_open(AVFormatContext *s)
Definition: mpegts.c:2331
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:401
int seq
RTSP command sequence number.
Definition: rtsp.h:241
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:400
uint8_t * recvbuf
Reusable buffer for receiving packets.
Definition: rtsp.h:339
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:996
#define RTSP_FLAG_CUSTOM_IO
Do all IO via the AVIOContext.
Definition: rtsp.h:411
AVDictionary * opts
Definition: movenc.c:50
#define NI_NUMERICHOST
Definition: network.h:164
#define LIBAVFORMAT_IDENT
Definition: version.h:44
AVFormatContext * asf_ctx
The following are used for RTP/ASF streams.
Definition: rtsp.h:307
int(* init)(AVFormatContext *s, int st_index, PayloadContext *priv_data)
Initialize dynamic protocol handler, called after the full rtpmap line is parsed, may be null...
Definition: rtpdec.h:126
const char * name
Definition: qsvenc.c:44
int recvbuf_pos
Definition: rtsp.h:322
#define dynarray_add(tab, nb_ptr, elem)
Definition: internal.h:134
char filename[1024]
input or output filename
Definition: avformat.h:1016
int nb_rtsp_streams
number of items in the &#39;rtsp_streams&#39; variable
Definition: rtsp.h:223
int64_t first_rtcp_ntp_time
Definition: rtpdec.h:180
#define AV_BASE64_SIZE(x)
Calculate the output size needed to base64-encode x bytes.
Definition: base64.h:59
#define FFMIN(a, b)
Definition: common.h:66
void * cur_transport_priv
RTSPStream->transport_priv of the last stream that we read a packet from.
Definition: rtsp.h:283
int av_strcasecmp(const char *a, const char *b)
Definition: avstring.c:156
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:55
int content_length
length of the data following this header
Definition: rtsp.h:129
int timeout
The "timeout" comes as part of the server response to the "SETUP" command, in the "Session: <xyz>[;ti...
Definition: rtsp.h:172
#define RTSP_TCP_MAX_PACKET_SIZE
Definition: rtsp.h:75
enum AVStreamParseType need_parsing
Definition: rtpdec.h:119
HTTP tunneled - not a proper transport mode as such, only for use via AVOptions.
Definition: rtsp.h:42
This describes a single item in the "Transport:" line of one stream as negotiated by the SETUP RTSP c...
Definition: rtsp.h:88
RTSP over HTTP (tunneling)
Definition: rtsp.h:69
static void get_word_until_chars(char *buf, int buf_size, const char *sep, const char **pp)
Definition: rtsp.c:125
const URLProtocol ** protocols
Definition: rtsp.h:402
int ff_rtsp_tcp_write_packet(AVFormatContext *s, RTSPStream *rtsp_st)
Send buffered packets over TCP.
Definition: rtspenc.c:139
static void get_word(char *buf, int buf_size, const char **pp)
Definition: rtsp.c:151
AVDictionary * metadata
Definition: avformat.h:772
char crypto_params[100]
Definition: rtsp.h:467
Usually treated as AVMEDIA_TYPE_DATA.
Definition: avutil.h:193
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition: avio.c:345
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition: error.h:52
#define ENC
Definition: rtsp.c:63
int sdp_port
The following are used only in SDP, not RTSP.
Definition: rtsp.h:441
int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt, const uint8_t *buf, int len)
Definition: mpegts.c:2347
Raw data (over UDP)
Definition: rtsp.h:59
LIBAVUTIL_VERSION_INT
Definition: eval.c:55
struct MpegTSContext * ts
The following are used for parsing raw mpegts in udp.
Definition: rtsp.h:321
int stale
Auth ok, but needs to be resent with a new nonce.
Definition: httpauth.h:71
void(* close)(PayloadContext *protocol_data)
Free any data needed by the rtp parsing for this dynamic data.
Definition: rtpdec.h:133
int sdp_payload_type
payload type
Definition: rtsp.h:448
void ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx, RTPDynamicProtocolHandler *handler)
Definition: rtpdec.c:538
int nb_exclude_source_addrs
Number of source-specific multicast exclude source IP addresses (from SDP content) ...
Definition: rtsp.h:445
void ffio_free_dyn_buf(AVIOContext **s)
Free a dynamic buffer.
Definition: aviobuf.c:1183
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:546
int ff_rtp_send_rtcp_feedback(RTPDemuxContext *s, URLContext *fd, AVIOContext *avio)
Definition: rtpdec.c:434
Stream structure.
Definition: avformat.h:705
#define AVERROR_PATCHWELCOME
Not yet implemented in Libav, patches welcome.
Definition: error.h:57
int ff_url_join(char *str, int size, const char *proto, const char *authorization, const char *hostname, int port, const char *fmt,...)
Definition: url.c:36
int nb_byes
Definition: rtsp.h:336
enum RTSPLowerTransport lower_transport
the negotiated network layer transport protocol; e.g.
Definition: rtsp.h:262
NULL
Definition: eval.c:55
char addr[128]
Source-specific multicast include source IP address (from SDP content)
Definition: rtsp.h:417
#define AV_LOG_INFO
Standard information.
Definition: log.h:135
struct sockaddr_storage sdp_ip
IP address (from SDP content)
Definition: rtsp.h:442
void ff_rtsp_undo_setup(AVFormatContext *s, int send_packets)
Undo the effect of ff_rtsp_make_setup_request, close the transport_priv and rtp_handle fields...
Definition: rtsp.c:718
int ff_check_interrupt(AVIOInterruptCB *cb)
Check if the user has requested to interrupt a blocking function associated with cb.
Definition: avio.c:374
int rtp_port_max
Definition: rtsp.h:387
Definition: rtp.h:100
AVIOContext * pb
I/O context.
Definition: avformat.h:982
int media_type_mask
Mask of all requested media types.
Definition: rtsp.h:382
av_default_item_name
Definition: dnxhdenc.c:55
int server_port_max
Definition: rtsp.h:105
#define FF_RTP_FLAG_OPTS(ctx, fieldname)
Definition: rtpenc.h:74
#define RTSP_FLAG_OPTS(name, longname)
Definition: rtsp.c:65
RDTDemuxContext * ff_rdt_parse_open(AVFormatContext *ic, int first_stream_of_set_idx, void *priv_data, RTPDynamicProtocolHandler *handler)
Allocate and init the RDT parsing context.
Definition: rdt.c:55
uint32_t ssrc
SSRC for this stream, to allow identifying RTCP packets before the first RTP packet.
Definition: rtsp.h:464
#define RTSP_FLAG_FILTER_SRC
Filter incoming UDP packets - receive packets only from the right source address and port...
Definition: rtsp.h:405
enum AVCodecID codec_id
Definition: rtpdec.h:118
enum RTSPTransport transport
the negotiated data/packet transport protocol; e.g.
Definition: rtsp.h:258
Definition: url.h:38
int(* parse_sdp_a_line)(AVFormatContext *s, int st_index, PayloadContext *priv_data, const char *line)
Parse the a= line from the sdp field.
Definition: rtpdec.h:128
#define RTSPS_DEFAULT_PORT
Definition: rtsp.h:73
int ff_rtsp_setup_output_streams(AVFormatContext *s, const char *addr)
Announce the stream to the server and set up the RTSPStream child objects for each media stream...
Definition: rtspenc.c:46
static int read_packet(AVFormatContext *ctx, AVPacket *pkt)
Definition: libcdio.c:114
#define AVIO_FLAG_READ_WRITE
read-write pseudo flag
Definition: avio.h:370
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:68
int rtsp_flags
Various option flags for the RTSP muxer/demuxer.
Definition: rtsp.h:377
uint8_t pi<< 24) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8, uint8_t,(*(const uint8_t *) pi - 0x80) *(1.0f/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8, uint8_t,(*(const uint8_t *) pi - 0x80) *(1.0/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16, int16_t,(*(const int16_t *) pi >> 8)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16, int16_t, *(const int16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16, int16_t, *(const int16_t *) pi *(1.0/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32, int32_t,(*(const int32_t *) pi >> 24)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32, int32_t, *(const int32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32, int32_t, *(const int32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, float, av_clip_uint8(lrintf(*(const float *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, float, av_clip_int16(lrintf(*(const float *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, float, av_clipl_int32(llrintf(*(const float *) pi *(1U<< 31)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, double, av_clip_uint8(lrint(*(const double *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, double, av_clip_int16(lrint(*(const double *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, double, av_clipl_int32(llrint(*(const double *) pi *(1U<< 31)))) #define SET_CONV_FUNC_GROUP(ofmt, ifmt) static void set_generic_function(AudioConvert *ac) { } void ff_audio_convert_free(AudioConvert **ac) { if(! *ac) return;ff_dither_free(&(*ac) ->dc);av_freep(ac);} AudioConvert *ff_audio_convert_alloc(AVAudioResampleContext *avr, enum AVSampleFormat out_fmt, enum AVSampleFormat in_fmt, int channels, int sample_rate, int apply_map) { AudioConvert *ac;int in_planar, out_planar;ac=av_mallocz(sizeof(*ac));if(!ac) return NULL;ac->avr=avr;ac->out_fmt=out_fmt;ac->in_fmt=in_fmt;ac->channels=channels;ac->apply_map=apply_map;if(avr->dither_method !=AV_RESAMPLE_DITHER_NONE &&av_get_packed_sample_fmt(out_fmt)==AV_SAMPLE_FMT_S16 &&av_get_bytes_per_sample(in_fmt) > 2) { ac->dc=ff_dither_alloc(avr, out_fmt, in_fmt, channels, sample_rate, apply_map);if(!ac->dc) { av_free(ac);return NULL;} return ac;} in_planar=ff_sample_fmt_is_planar(in_fmt, channels);out_planar=ff_sample_fmt_is_planar(out_fmt, channels);if(in_planar==out_planar) { ac->func_type=CONV_FUNC_TYPE_FLAT;ac->planes=in_planar ? ac->channels :1;} else if(in_planar) ac->func_type=CONV_FUNC_TYPE_INTERLEAVE;else ac->func_type=CONV_FUNC_TYPE_DEINTERLEAVE;set_generic_function(ac);if(ARCH_AARCH64) ff_audio_convert_init_aarch64(ac);if(ARCH_ARM) ff_audio_convert_init_arm(ac);if(ARCH_X86) ff_audio_convert_init_x86(ac);return ac;} int ff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in) { int use_generic=1;int len=in->nb_samples;int p;if(ac->dc) { av_log(ac->avr, AV_LOG_TRACE, "%d samples - audio_convert: %s to %s (dithered)\", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt));return ff_convert_dither(ac-> in
int client_port_max
Definition: rtsp.h:101
Describe the class of an AVClass context structure.
Definition: log.h:34
#define SDP_MAX_SIZE
Definition: rtsp.c:57
void ff_real_parse_sdp_a_line(AVFormatContext *s, int stream_index, const char *line)
Parse a server-related SDP line.
Definition: rdt.c:515
#define SPACE_CHARS
Definition: internal.h:230
void * priv_data
Definition: url.h:45
PayloadContext * dynamic_protocol_context
private data associated with the dynamic protocol
Definition: rtsp.h:457
char last_reply[2048]
The last reply of the server to a RTSP command.
Definition: rtsp.h:279
#define gai_strerror
Definition: network.h:194
not initialized
Definition: rtsp.h:196
int64_t range_end
Definition: rtsp.h:138
enum RTSPTransport transport
data/packet transport protocol; e.g.
Definition: rtsp.h:118
char real_challenge[64]
the "RealChallenge1:" field from the server
Definition: rtsp.h:155
AVMediaType
Definition: avutil.h:192
size_t av_strlcatf(char *dst, size_t size, const char *fmt,...)
Definition: avstring.c:99
#define RTSP_MEDIATYPE_OPTS(name, longname)
Definition: rtsp.c:69
int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
Definition: rtpdec.c:719
int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st, uint8_t *buf, int buf_size)
Receive one RTP packet from an TCP interleaved RTSP stream.
Definition: rtspdec.c:754
void ff_rtsp_close_streams(AVFormatContext *s)
Close and free all streams within the RTSP (de)muxer.
Definition: rtsp.c:752
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:263
const char * name
Name of the codec described by this descriptor.
Definition: avcodec.h:588
#define AVPROBE_SCORE_EXTENSION
score for file extension
Definition: avformat.h:405
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:2594
int buffer_size
Definition: rtsp.h:400
This structure contains the data a format has to probe a file.
Definition: avformat.h:398
#define RTSP_DEFAULT_NB_AUDIO_CHANNELS
Definition: rtsp.h:76
misc parsing utilities
char * ff_http_auth_create_response(HTTPAuthState *state, const char *auth, const char *path, const char *method)
Definition: httpauth.c:243
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes...
Definition: avstring.c:91
int interleaved_max
Definition: rtsp.h:93
#define RTP_PT_IS_RTCP(x)
Definition: rtp.h:110
mfxU16 profile
Definition: qsvenc.c:43
This struct describes the properties of a single codec described by an AVCodecID. ...
Definition: avcodec.h:580
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition: time.c:57
enum RTSPServerType server_type
brand of server that we&#39;re talking to; e.g.
Definition: rtsp.h:267
int ffurl_close(URLContext *h)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition: avio.c:280
int64_t range_start
Time range of the streams that the server will stream.
Definition: rtsp.h:138
int64_t start_time
Position of the first frame of the component, in AV_TIME_BASE fractional seconds. ...
Definition: avformat.h:1025
enum RTSPClientState state
indicator of whether we are currently receiving data from the server.
Definition: rtsp.h:231
int sample_rate
Audio only.
Definition: avcodec.h:3564
#define DEC
Definition: rtsp.c:62
int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
Receive one packet from the RTSPStreams set up in the AVFormatContext (which should contain a RTSPSta...
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:407
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
Definition: avstring.c:32
int ff_rtsp_send_cmd_with_content(AVFormatContext *s, const char *method, const char *url, const char *headers, RTSPMessageHeader *reply, unsigned char **content_ptr, const unsigned char *send_content, int send_content_length)
Send a command to the RTSP server and wait for the reply.
#define getaddrinfo
Definition: network.h:186
Main libavformat public API header.
static const AVOption sdp_options[]
Definition: rtsp.c:98
void ff_mpegts_parse_close(MpegTSContext *ts)
Definition: mpegts.c:2372
int ff_rtp_chain_mux_open(AVFormatContext **out, AVFormatContext *s, AVStream *st, URLContext *handle, int packet_size, int idx)
Definition: rtpenc_chain.c:29
uint32_t ssrc
Definition: rtpdec.h:153
static AVDictionary * map_to_opts(RTSPState *rt)
Definition: rtsp.c:114
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:412
RTPDynamicProtocolHandler * ff_rtp_handler_find_by_name(const char *name, enum AVMediaType codec_type)
Definition: rtpdec.c:112
int ffio_init_context(AVIOContext *s, unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Definition: aviobuf.c:109
int need_subscription
The following are used for Real stream selection.
Definition: rtsp.h:288
RTPDynamicProtocolHandler * dynamic_handler
The following are used for dynamic protocols (rtpdec_*.c/rdt.c)
Definition: rtsp.h:454
int ffurl_read_complete(URLContext *h, unsigned char *buf, int size)
Read as many bytes as possible (up to size), calling the read function multiple times if necessary...
Definition: avio.c:250
void ff_rdt_calc_response_and_checksum(char response[41], char chksum[9], const char *challenge)
Calculate the response (RealChallenge2 in the RTSP header) to the challenge (RealChallenge1 in the RT...
Definition: rdt.c:94
char default_lang[4]
Definition: rtsp.h:399
struct AVInputFormat * iformat
The input container format.
Definition: avformat.h:952
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:2626
void ff_http_auth_handle_header(HTTPAuthState *state, const char *key, const char *value)
Definition: httpauth.c:90
uint32_t base_timestamp
Definition: rtpdec.h:156
int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply, unsigned char **content_ptr, int return_on_interleaved_data, const char *method)
Read a RTSP message from the server, or prepare to read data packets if we&#39;re reading data interleave...
#define getnameinfo
Definition: network.h:188
int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method, const char *url, const char *headers)
Send a command to the RTSP server without waiting for the reply.
static void get_word_sep(char *buf, int buf_size, const char *sep, const char **pp)
Definition: rtsp.c:144
TCP; interleaved in RTSP.
Definition: rtsp.h:39
HTTPAuthState auth_state
authentication state
Definition: rtsp.h:276
int len
#define RTSP_RTP_PORT_MIN
Definition: rtsp.h:78
char control_url[1024]
url for this stream (from SDP)
Definition: rtsp.h:437
void * priv_data
Format private data.
Definition: avformat.h:968
int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
Get the description of the stream and set up the RTSPStream child objects.
Definition: rtspdec.c:590
void ff_rtp_parse_close(RTPDemuxContext *s)
Definition: rtpdec.c:846
int channels
Audio only.
Definition: avcodec.h:3560
int sdp_ttl
IP Time-To-Live (from SDP content)
Definition: rtsp.h:447
#define MAX_TIMEOUTS
Definition: rtsp.c:56
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:714
char * protocol_blacklist
A comma-separated list of protocol names that will not be used internally by libavformat.
Definition: avformat.h:1285
int ai_flags
Definition: network.h:107
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1035
HTTPAuthType auth_type
The currently chosen auth type.
Definition: httpauth.h:59
Realmedia-style server.
Definition: rtsp.h:208
int lower_transport_mask
A mask with all requested transport methods.
Definition: rtsp.h:344
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:529
unbuffered private I/O API
uint32_t av_get_random_seed(void)
Get random data.
Definition: random_seed.c:95
AVCodecParameters * codecpar
Definition: avformat.h:831
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:742
int interleaved_max
Definition: rtsp.h:435
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:833
struct sockaddr_storage destination
destination IP address
Definition: rtsp.h:114
int ff_rtp_set_remote_url(URLContext *h, const char *uri)
If no filename is given to av_open_input_file because you want to get the local port first...
Definition: rtpproto.c:96
#define RTP_REORDER_QUEUE_DEFAULT_SIZE
Definition: rtpdec.h:38
const URLProtocol ** ffurl_get_protocols(const char *whitelist, const char *blacklist)
Construct a list of protocols matching a given whitelist and/or blacklist.
Definition: protocols.c:98
int interleaved_min
interleave IDs; copies of RTSPTransportField->interleaved_min/max for the selected transport...
Definition: rtsp.h:435
This structure stores compressed data.
Definition: avcodec.h:1323
int server_port_min
UDP unicast server port range; the ports to which we should connect to receive unicast UDP RTP/RTCP d...
Definition: rtsp.h:105
void ff_rtsp_close_connections(AVFormatContext *s)
Close all connection handles within the RTSP (de)muxer.
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:247
static const AVOption rtp_options[]
Definition: rtsp.c:107
int ffurl_read(URLContext *h, unsigned char *buf, int size)
Read up to size bytes from the resource accessed by h, and store the read bytes in buf...
Definition: avio.c:243
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:211
URLContext * rtp_handle
RTP stream handle (if UDP)
Definition: rtsp.h:427
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:235
#define OFFSET(x)
Definition: rtsp.c:61
int port_min
UDP multicast port range; the ports to which we should connect to receive multicast UDP data...
Definition: rtsp.h:97
void * transport_priv
RTP/RDT parse context if input, RTP AVFormatContext if output.
Definition: rtsp.h:428
No authentication specified.
Definition: httpauth.h:29
int client_port_min
UDP client ports; these should be the local ports of the UDP RTP (and RTCP) sockets over which we rec...
Definition: rtsp.h:101