You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1852 lines
65KB

  1. /*
  2. * RTSP/SDP client
  3. * Copyright (c) 2002 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/base64.h"
  22. #include "libavutil/avstring.h"
  23. #include "libavutil/intreadwrite.h"
  24. #include "libavutil/random_seed.h"
  25. #include "avformat.h"
  26. #include <sys/time.h>
  27. #if HAVE_SYS_SELECT_H
  28. #include <sys/select.h>
  29. #endif
  30. #include <strings.h>
  31. #include "internal.h"
  32. #include "network.h"
  33. #include "os_support.h"
  34. #include "http.h"
  35. #include "rtsp.h"
  36. #include "rtpdec.h"
  37. #include "rdt.h"
  38. #include "rtpdec_formats.h"
  39. #include "rtpenc_chain.h"
  40. //#define DEBUG
  41. //#define DEBUG_RTP_TCP
  42. /* Timeout values for socket select, in ms,
  43. * and read_packet(), in seconds */
  44. #define SELECT_TIMEOUT_MS 100
  45. #define READ_PACKET_TIMEOUT_S 10
  46. #define MAX_TIMEOUTS READ_PACKET_TIMEOUT_S * 1000 / SELECT_TIMEOUT_MS
  47. #define SDP_MAX_SIZE 16384
  48. #define RECVBUF_SIZE 10 * RTP_MAX_PACKET_LENGTH
  49. static void get_word_until_chars(char *buf, int buf_size,
  50. const char *sep, const char **pp)
  51. {
  52. const char *p;
  53. char *q;
  54. p = *pp;
  55. p += strspn(p, SPACE_CHARS);
  56. q = buf;
  57. while (!strchr(sep, *p) && *p != '\0') {
  58. if ((q - buf) < buf_size - 1)
  59. *q++ = *p;
  60. p++;
  61. }
  62. if (buf_size > 0)
  63. *q = '\0';
  64. *pp = p;
  65. }
  66. static void get_word_sep(char *buf, int buf_size, const char *sep,
  67. const char **pp)
  68. {
  69. if (**pp == '/') (*pp)++;
  70. get_word_until_chars(buf, buf_size, sep, pp);
  71. }
  72. static void get_word(char *buf, int buf_size, const char **pp)
  73. {
  74. get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
  75. }
  76. /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
  77. * and end time.
  78. * Used for seeking in the rtp stream.
  79. */
  80. static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
  81. {
  82. char buf[256];
  83. p += strspn(p, SPACE_CHARS);
  84. if (!av_stristart(p, "npt=", &p))
  85. return;
  86. *start = AV_NOPTS_VALUE;
  87. *end = AV_NOPTS_VALUE;
  88. get_word_sep(buf, sizeof(buf), "-", &p);
  89. *start = parse_date(buf, 1);
  90. if (*p == '-') {
  91. p++;
  92. get_word_sep(buf, sizeof(buf), "-", &p);
  93. *end = parse_date(buf, 1);
  94. }
  95. // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
  96. // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
  97. }
  98. static int get_sockaddr(const char *buf, struct sockaddr_storage *sock)
  99. {
  100. struct addrinfo hints, *ai = NULL;
  101. memset(&hints, 0, sizeof(hints));
  102. hints.ai_flags = AI_NUMERICHOST;
  103. if (getaddrinfo(buf, NULL, &hints, &ai))
  104. return -1;
  105. memcpy(sock, ai->ai_addr, FFMIN(sizeof(*sock), ai->ai_addrlen));
  106. freeaddrinfo(ai);
  107. return 0;
  108. }
  109. #if CONFIG_RTPDEC
  110. static void init_rtp_handler(RTPDynamicProtocolHandler *handler,
  111. RTSPStream *rtsp_st, AVCodecContext *codec)
  112. {
  113. if (!handler)
  114. return;
  115. codec->codec_id = handler->codec_id;
  116. rtsp_st->dynamic_handler = handler;
  117. if (handler->open)
  118. rtsp_st->dynamic_protocol_context = handler->open();
  119. }
  120. /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
  121. static int sdp_parse_rtpmap(AVFormatContext *s,
  122. AVStream *st, RTSPStream *rtsp_st,
  123. int payload_type, const char *p)
  124. {
  125. AVCodecContext *codec = st->codec;
  126. char buf[256];
  127. int i;
  128. AVCodec *c;
  129. const char *c_name;
  130. /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
  131. * see if we can handle this kind of payload.
  132. * The space should normally not be there but some Real streams or
  133. * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
  134. * have a trailing space. */
  135. get_word_sep(buf, sizeof(buf), "/ ", &p);
  136. if (payload_type >= RTP_PT_PRIVATE) {
  137. RTPDynamicProtocolHandler *handler =
  138. ff_rtp_handler_find_by_name(buf, codec->codec_type);
  139. init_rtp_handler(handler, rtsp_st, codec);
  140. /* If no dynamic handler was found, check with the list of standard
  141. * allocated types, if such a stream for some reason happens to
  142. * use a private payload type. This isn't handled in rtpdec.c, since
  143. * the format name from the rtpmap line never is passed into rtpdec. */
  144. if (!rtsp_st->dynamic_handler)
  145. codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
  146. } else {
  147. /* We are in a standard case
  148. * (from http://www.iana.org/assignments/rtp-parameters). */
  149. /* search into AVRtpPayloadTypes[] */
  150. codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
  151. }
  152. c = avcodec_find_decoder(codec->codec_id);
  153. if (c && c->name)
  154. c_name = c->name;
  155. else
  156. c_name = "(null)";
  157. get_word_sep(buf, sizeof(buf), "/", &p);
  158. i = atoi(buf);
  159. switch (codec->codec_type) {
  160. case AVMEDIA_TYPE_AUDIO:
  161. av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
  162. codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
  163. codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
  164. if (i > 0) {
  165. codec->sample_rate = i;
  166. av_set_pts_info(st, 32, 1, codec->sample_rate);
  167. get_word_sep(buf, sizeof(buf), "/", &p);
  168. i = atoi(buf);
  169. if (i > 0)
  170. codec->channels = i;
  171. // TODO: there is a bug here; if it is a mono stream, and
  172. // less than 22000Hz, faad upconverts to stereo and twice
  173. // the frequency. No problem, but the sample rate is being
  174. // set here by the sdp line. Patch on its way. (rdm)
  175. }
  176. av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
  177. codec->sample_rate);
  178. av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
  179. codec->channels);
  180. break;
  181. case AVMEDIA_TYPE_VIDEO:
  182. av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
  183. if (i > 0)
  184. av_set_pts_info(st, 32, 1, i);
  185. break;
  186. default:
  187. break;
  188. }
  189. return 0;
  190. }
  191. /* parse the attribute line from the fmtp a line of an sdp response. This
  192. * is broken out as a function because it is used in rtp_h264.c, which is
  193. * forthcoming. */
  194. int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
  195. char *value, int value_size)
  196. {
  197. *p += strspn(*p, SPACE_CHARS);
  198. if (**p) {
  199. get_word_sep(attr, attr_size, "=", p);
  200. if (**p == '=')
  201. (*p)++;
  202. get_word_sep(value, value_size, ";", p);
  203. if (**p == ';')
  204. (*p)++;
  205. return 1;
  206. }
  207. return 0;
  208. }
  209. typedef struct SDPParseState {
  210. /* SDP only */
  211. struct sockaddr_storage default_ip;
  212. int default_ttl;
  213. int skip_media; ///< set if an unknown m= line occurs
  214. } SDPParseState;
  215. static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
  216. int letter, const char *buf)
  217. {
  218. RTSPState *rt = s->priv_data;
  219. char buf1[64], st_type[64];
  220. const char *p;
  221. enum AVMediaType codec_type;
  222. int payload_type, i;
  223. AVStream *st;
  224. RTSPStream *rtsp_st;
  225. struct sockaddr_storage sdp_ip;
  226. int ttl;
  227. dprintf(s, "sdp: %c='%s'\n", letter, buf);
  228. p = buf;
  229. if (s1->skip_media && letter != 'm')
  230. return;
  231. switch (letter) {
  232. case 'c':
  233. get_word(buf1, sizeof(buf1), &p);
  234. if (strcmp(buf1, "IN") != 0)
  235. return;
  236. get_word(buf1, sizeof(buf1), &p);
  237. if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))
  238. return;
  239. get_word_sep(buf1, sizeof(buf1), "/", &p);
  240. if (get_sockaddr(buf1, &sdp_ip))
  241. return;
  242. ttl = 16;
  243. if (*p == '/') {
  244. p++;
  245. get_word_sep(buf1, sizeof(buf1), "/", &p);
  246. ttl = atoi(buf1);
  247. }
  248. if (s->nb_streams == 0) {
  249. s1->default_ip = sdp_ip;
  250. s1->default_ttl = ttl;
  251. } else {
  252. st = s->streams[s->nb_streams - 1];
  253. rtsp_st = st->priv_data;
  254. rtsp_st->sdp_ip = sdp_ip;
  255. rtsp_st->sdp_ttl = ttl;
  256. }
  257. break;
  258. case 's':
  259. av_metadata_set2(&s->metadata, "title", p, 0);
  260. break;
  261. case 'i':
  262. if (s->nb_streams == 0) {
  263. av_metadata_set2(&s->metadata, "comment", p, 0);
  264. break;
  265. }
  266. break;
  267. case 'm':
  268. /* new stream */
  269. s1->skip_media = 0;
  270. get_word(st_type, sizeof(st_type), &p);
  271. if (!strcmp(st_type, "audio")) {
  272. codec_type = AVMEDIA_TYPE_AUDIO;
  273. } else if (!strcmp(st_type, "video")) {
  274. codec_type = AVMEDIA_TYPE_VIDEO;
  275. } else if (!strcmp(st_type, "application")) {
  276. codec_type = AVMEDIA_TYPE_DATA;
  277. } else {
  278. s1->skip_media = 1;
  279. return;
  280. }
  281. rtsp_st = av_mallocz(sizeof(RTSPStream));
  282. if (!rtsp_st)
  283. return;
  284. rtsp_st->stream_index = -1;
  285. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  286. rtsp_st->sdp_ip = s1->default_ip;
  287. rtsp_st->sdp_ttl = s1->default_ttl;
  288. get_word(buf1, sizeof(buf1), &p); /* port */
  289. rtsp_st->sdp_port = atoi(buf1);
  290. get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
  291. /* XXX: handle list of formats */
  292. get_word(buf1, sizeof(buf1), &p); /* format list */
  293. rtsp_st->sdp_payload_type = atoi(buf1);
  294. if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
  295. /* no corresponding stream */
  296. } else {
  297. st = av_new_stream(s, 0);
  298. if (!st)
  299. return;
  300. st->priv_data = rtsp_st;
  301. rtsp_st->stream_index = st->index;
  302. st->codec->codec_type = codec_type;
  303. if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
  304. RTPDynamicProtocolHandler *handler;
  305. /* if standard payload type, we can find the codec right now */
  306. ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
  307. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  308. st->codec->sample_rate > 0)
  309. av_set_pts_info(st, 32, 1, st->codec->sample_rate);
  310. /* Even static payload types may need a custom depacketizer */
  311. handler = ff_rtp_handler_find_by_id(
  312. rtsp_st->sdp_payload_type, st->codec->codec_type);
  313. init_rtp_handler(handler, rtsp_st, st->codec);
  314. }
  315. }
  316. /* put a default control url */
  317. av_strlcpy(rtsp_st->control_url, rt->control_uri,
  318. sizeof(rtsp_st->control_url));
  319. break;
  320. case 'a':
  321. if (av_strstart(p, "control:", &p)) {
  322. if (s->nb_streams == 0) {
  323. if (!strncmp(p, "rtsp://", 7))
  324. av_strlcpy(rt->control_uri, p,
  325. sizeof(rt->control_uri));
  326. } else {
  327. char proto[32];
  328. /* get the control url */
  329. st = s->streams[s->nb_streams - 1];
  330. rtsp_st = st->priv_data;
  331. /* XXX: may need to add full url resolution */
  332. av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
  333. NULL, NULL, 0, p);
  334. if (proto[0] == '\0') {
  335. /* relative control URL */
  336. if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
  337. av_strlcat(rtsp_st->control_url, "/",
  338. sizeof(rtsp_st->control_url));
  339. av_strlcat(rtsp_st->control_url, p,
  340. sizeof(rtsp_st->control_url));
  341. } else
  342. av_strlcpy(rtsp_st->control_url, p,
  343. sizeof(rtsp_st->control_url));
  344. }
  345. } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
  346. /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
  347. get_word(buf1, sizeof(buf1), &p);
  348. payload_type = atoi(buf1);
  349. st = s->streams[s->nb_streams - 1];
  350. rtsp_st = st->priv_data;
  351. sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);
  352. } else if (av_strstart(p, "fmtp:", &p) ||
  353. av_strstart(p, "framesize:", &p)) {
  354. /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
  355. // let dynamic protocol handlers have a stab at the line.
  356. get_word(buf1, sizeof(buf1), &p);
  357. payload_type = atoi(buf1);
  358. for (i = 0; i < s->nb_streams; i++) {
  359. st = s->streams[i];
  360. rtsp_st = st->priv_data;
  361. if (rtsp_st->sdp_payload_type == payload_type &&
  362. rtsp_st->dynamic_handler &&
  363. rtsp_st->dynamic_handler->parse_sdp_a_line)
  364. rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
  365. rtsp_st->dynamic_protocol_context, buf);
  366. }
  367. } else if (av_strstart(p, "range:", &p)) {
  368. int64_t start, end;
  369. // this is so that seeking on a streamed file can work.
  370. rtsp_parse_range_npt(p, &start, &end);
  371. s->start_time = start;
  372. /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
  373. s->duration = (end == AV_NOPTS_VALUE) ?
  374. AV_NOPTS_VALUE : end - start;
  375. } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
  376. if (atoi(p) == 1)
  377. rt->transport = RTSP_TRANSPORT_RDT;
  378. } else if (av_strstart(p, "SampleRate:integer;", &p) &&
  379. s->nb_streams > 0) {
  380. st = s->streams[s->nb_streams - 1];
  381. st->codec->sample_rate = atoi(p);
  382. } else {
  383. if (rt->server_type == RTSP_SERVER_WMS)
  384. ff_wms_parse_sdp_a_line(s, p);
  385. if (s->nb_streams > 0) {
  386. if (rt->server_type == RTSP_SERVER_REAL)
  387. ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
  388. rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
  389. if (rtsp_st->dynamic_handler &&
  390. rtsp_st->dynamic_handler->parse_sdp_a_line)
  391. rtsp_st->dynamic_handler->parse_sdp_a_line(s,
  392. s->nb_streams - 1,
  393. rtsp_st->dynamic_protocol_context, buf);
  394. }
  395. }
  396. break;
  397. }
  398. }
  399. int ff_sdp_parse(AVFormatContext *s, const char *content)
  400. {
  401. const char *p;
  402. int letter;
  403. /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
  404. * contain long SDP lines containing complete ASF Headers (several
  405. * kB) or arrays of MDPR (RM stream descriptor) headers plus
  406. * "rulebooks" describing their properties. Therefore, the SDP line
  407. * buffer is large.
  408. *
  409. * The Vorbis FMTP line can be up to 16KB - see xiph_parse_sdp_line
  410. * in rtpdec_xiph.c. */
  411. char buf[16384], *q;
  412. SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
  413. memset(s1, 0, sizeof(SDPParseState));
  414. p = content;
  415. for (;;) {
  416. p += strspn(p, SPACE_CHARS);
  417. letter = *p;
  418. if (letter == '\0')
  419. break;
  420. p++;
  421. if (*p != '=')
  422. goto next_line;
  423. p++;
  424. /* get the content */
  425. q = buf;
  426. while (*p != '\n' && *p != '\r' && *p != '\0') {
  427. if ((q - buf) < sizeof(buf) - 1)
  428. *q++ = *p;
  429. p++;
  430. }
  431. *q = '\0';
  432. sdp_parse_line(s, s1, letter, buf);
  433. next_line:
  434. while (*p != '\n' && *p != '\0')
  435. p++;
  436. if (*p == '\n')
  437. p++;
  438. }
  439. return 0;
  440. }
  441. #endif /* CONFIG_RTPDEC */
  442. /* close and free RTSP streams */
  443. void ff_rtsp_close_streams(AVFormatContext *s)
  444. {
  445. RTSPState *rt = s->priv_data;
  446. int i;
  447. RTSPStream *rtsp_st;
  448. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  449. rtsp_st = rt->rtsp_streams[i];
  450. if (rtsp_st) {
  451. if (rtsp_st->transport_priv) {
  452. if (s->oformat) {
  453. AVFormatContext *rtpctx = rtsp_st->transport_priv;
  454. av_write_trailer(rtpctx);
  455. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  456. uint8_t *ptr;
  457. url_close_dyn_buf(rtpctx->pb, &ptr);
  458. av_free(ptr);
  459. } else {
  460. url_fclose(rtpctx->pb);
  461. }
  462. av_metadata_free(&rtpctx->streams[0]->metadata);
  463. av_metadata_free(&rtpctx->metadata);
  464. av_free(rtpctx->streams[0]);
  465. av_free(rtpctx);
  466. } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
  467. ff_rdt_parse_close(rtsp_st->transport_priv);
  468. else if (CONFIG_RTPDEC)
  469. rtp_parse_close(rtsp_st->transport_priv);
  470. }
  471. if (rtsp_st->rtp_handle)
  472. url_close(rtsp_st->rtp_handle);
  473. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  474. rtsp_st->dynamic_handler->close(
  475. rtsp_st->dynamic_protocol_context);
  476. }
  477. }
  478. av_free(rt->rtsp_streams);
  479. if (rt->asf_ctx) {
  480. av_close_input_stream (rt->asf_ctx);
  481. rt->asf_ctx = NULL;
  482. }
  483. av_free(rt->recvbuf);
  484. }
  485. static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  486. {
  487. RTSPState *rt = s->priv_data;
  488. AVStream *st = NULL;
  489. /* open the RTP context */
  490. if (rtsp_st->stream_index >= 0)
  491. st = s->streams[rtsp_st->stream_index];
  492. if (!st)
  493. s->ctx_flags |= AVFMTCTX_NOHEADER;
  494. if (s->oformat && CONFIG_RTSP_MUXER) {
  495. rtsp_st->transport_priv = ff_rtp_chain_mux_open(s, st,
  496. rtsp_st->rtp_handle,
  497. RTSP_TCP_MAX_PACKET_SIZE);
  498. /* Ownership of rtp_handle is passed to the rtp mux context */
  499. rtsp_st->rtp_handle = NULL;
  500. } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)
  501. rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
  502. rtsp_st->dynamic_protocol_context,
  503. rtsp_st->dynamic_handler);
  504. else if (CONFIG_RTPDEC)
  505. rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
  506. rtsp_st->sdp_payload_type,
  507. (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)
  508. ? 0 : RTP_REORDER_QUEUE_DEFAULT_SIZE);
  509. if (!rtsp_st->transport_priv) {
  510. return AVERROR(ENOMEM);
  511. } else if (rt->transport != RTSP_TRANSPORT_RDT && CONFIG_RTPDEC) {
  512. if (rtsp_st->dynamic_handler) {
  513. rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
  514. rtsp_st->dynamic_protocol_context,
  515. rtsp_st->dynamic_handler);
  516. }
  517. }
  518. return 0;
  519. }
  520. #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
  521. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  522. {
  523. const char *p;
  524. int v;
  525. p = *pp;
  526. p += strspn(p, SPACE_CHARS);
  527. v = strtol(p, (char **)&p, 10);
  528. if (*p == '-') {
  529. p++;
  530. *min_ptr = v;
  531. v = strtol(p, (char **)&p, 10);
  532. *max_ptr = v;
  533. } else {
  534. *min_ptr = v;
  535. *max_ptr = v;
  536. }
  537. *pp = p;
  538. }
  539. /* XXX: only one transport specification is parsed */
  540. static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
  541. {
  542. char transport_protocol[16];
  543. char profile[16];
  544. char lower_transport[16];
  545. char parameter[16];
  546. RTSPTransportField *th;
  547. char buf[256];
  548. reply->nb_transports = 0;
  549. for (;;) {
  550. p += strspn(p, SPACE_CHARS);
  551. if (*p == '\0')
  552. break;
  553. th = &reply->transports[reply->nb_transports];
  554. get_word_sep(transport_protocol, sizeof(transport_protocol),
  555. "/", &p);
  556. if (!strcasecmp (transport_protocol, "rtp")) {
  557. get_word_sep(profile, sizeof(profile), "/;,", &p);
  558. lower_transport[0] = '\0';
  559. /* rtp/avp/<protocol> */
  560. if (*p == '/') {
  561. get_word_sep(lower_transport, sizeof(lower_transport),
  562. ";,", &p);
  563. }
  564. th->transport = RTSP_TRANSPORT_RTP;
  565. } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
  566. !strcasecmp (transport_protocol, "x-real-rdt")) {
  567. /* x-pn-tng/<protocol> */
  568. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  569. profile[0] = '\0';
  570. th->transport = RTSP_TRANSPORT_RDT;
  571. }
  572. if (!strcasecmp(lower_transport, "TCP"))
  573. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  574. else
  575. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  576. if (*p == ';')
  577. p++;
  578. /* get each parameter */
  579. while (*p != '\0' && *p != ',') {
  580. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  581. if (!strcmp(parameter, "port")) {
  582. if (*p == '=') {
  583. p++;
  584. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  585. }
  586. } else if (!strcmp(parameter, "client_port")) {
  587. if (*p == '=') {
  588. p++;
  589. rtsp_parse_range(&th->client_port_min,
  590. &th->client_port_max, &p);
  591. }
  592. } else if (!strcmp(parameter, "server_port")) {
  593. if (*p == '=') {
  594. p++;
  595. rtsp_parse_range(&th->server_port_min,
  596. &th->server_port_max, &p);
  597. }
  598. } else if (!strcmp(parameter, "interleaved")) {
  599. if (*p == '=') {
  600. p++;
  601. rtsp_parse_range(&th->interleaved_min,
  602. &th->interleaved_max, &p);
  603. }
  604. } else if (!strcmp(parameter, "multicast")) {
  605. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  606. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  607. } else if (!strcmp(parameter, "ttl")) {
  608. if (*p == '=') {
  609. p++;
  610. th->ttl = strtol(p, (char **)&p, 10);
  611. }
  612. } else if (!strcmp(parameter, "destination")) {
  613. if (*p == '=') {
  614. p++;
  615. get_word_sep(buf, sizeof(buf), ";,", &p);
  616. get_sockaddr(buf, &th->destination);
  617. }
  618. } else if (!strcmp(parameter, "source")) {
  619. if (*p == '=') {
  620. p++;
  621. get_word_sep(buf, sizeof(buf), ";,", &p);
  622. av_strlcpy(th->source, buf, sizeof(th->source));
  623. }
  624. }
  625. while (*p != ';' && *p != '\0' && *p != ',')
  626. p++;
  627. if (*p == ';')
  628. p++;
  629. }
  630. if (*p == ',')
  631. p++;
  632. reply->nb_transports++;
  633. }
  634. }
  635. void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf,
  636. RTSPState *rt, const char *method)
  637. {
  638. const char *p;
  639. /* NOTE: we do case independent match for broken servers */
  640. p = buf;
  641. if (av_stristart(p, "Session:", &p)) {
  642. int t;
  643. get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
  644. if (av_stristart(p, ";timeout=", &p) &&
  645. (t = strtol(p, NULL, 10)) > 0) {
  646. reply->timeout = t;
  647. }
  648. } else if (av_stristart(p, "Content-Length:", &p)) {
  649. reply->content_length = strtol(p, NULL, 10);
  650. } else if (av_stristart(p, "Transport:", &p)) {
  651. rtsp_parse_transport(reply, p);
  652. } else if (av_stristart(p, "CSeq:", &p)) {
  653. reply->seq = strtol(p, NULL, 10);
  654. } else if (av_stristart(p, "Range:", &p)) {
  655. rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
  656. } else if (av_stristart(p, "RealChallenge1:", &p)) {
  657. p += strspn(p, SPACE_CHARS);
  658. av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
  659. } else if (av_stristart(p, "Server:", &p)) {
  660. p += strspn(p, SPACE_CHARS);
  661. av_strlcpy(reply->server, p, sizeof(reply->server));
  662. } else if (av_stristart(p, "Notice:", &p) ||
  663. av_stristart(p, "X-Notice:", &p)) {
  664. reply->notice = strtol(p, NULL, 10);
  665. } else if (av_stristart(p, "Location:", &p)) {
  666. p += strspn(p, SPACE_CHARS);
  667. av_strlcpy(reply->location, p , sizeof(reply->location));
  668. } else if (av_stristart(p, "WWW-Authenticate:", &p) && rt) {
  669. p += strspn(p, SPACE_CHARS);
  670. ff_http_auth_handle_header(&rt->auth_state, "WWW-Authenticate", p);
  671. } else if (av_stristart(p, "Authentication-Info:", &p) && rt) {
  672. p += strspn(p, SPACE_CHARS);
  673. ff_http_auth_handle_header(&rt->auth_state, "Authentication-Info", p);
  674. } else if (av_stristart(p, "Content-Base:", &p) && rt) {
  675. p += strspn(p, SPACE_CHARS);
  676. if (method && !strcmp(method, "DESCRIBE"))
  677. av_strlcpy(rt->control_uri, p , sizeof(rt->control_uri));
  678. }
  679. }
  680. /* skip a RTP/TCP interleaved packet */
  681. void ff_rtsp_skip_packet(AVFormatContext *s)
  682. {
  683. RTSPState *rt = s->priv_data;
  684. int ret, len, len1;
  685. uint8_t buf[1024];
  686. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  687. if (ret != 3)
  688. return;
  689. len = AV_RB16(buf + 1);
  690. dprintf(s, "skipping RTP packet len=%d\n", len);
  691. /* skip payload */
  692. while (len > 0) {
  693. len1 = len;
  694. if (len1 > sizeof(buf))
  695. len1 = sizeof(buf);
  696. ret = url_read_complete(rt->rtsp_hd, buf, len1);
  697. if (ret != len1)
  698. return;
  699. len -= len1;
  700. }
  701. }
  702. int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
  703. unsigned char **content_ptr,
  704. int return_on_interleaved_data, const char *method)
  705. {
  706. RTSPState *rt = s->priv_data;
  707. char buf[4096], buf1[1024], *q;
  708. unsigned char ch;
  709. const char *p;
  710. int ret, content_length, line_count = 0;
  711. unsigned char *content = NULL;
  712. memset(reply, 0, sizeof(*reply));
  713. /* parse reply (XXX: use buffers) */
  714. rt->last_reply[0] = '\0';
  715. for (;;) {
  716. q = buf;
  717. for (;;) {
  718. ret = url_read_complete(rt->rtsp_hd, &ch, 1);
  719. #ifdef DEBUG_RTP_TCP
  720. dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  721. #endif
  722. if (ret != 1)
  723. return AVERROR_EOF;
  724. if (ch == '\n')
  725. break;
  726. if (ch == '$') {
  727. /* XXX: only parse it if first char on line ? */
  728. if (return_on_interleaved_data) {
  729. return 1;
  730. } else
  731. ff_rtsp_skip_packet(s);
  732. } else if (ch != '\r') {
  733. if ((q - buf) < sizeof(buf) - 1)
  734. *q++ = ch;
  735. }
  736. }
  737. *q = '\0';
  738. dprintf(s, "line='%s'\n", buf);
  739. /* test if last line */
  740. if (buf[0] == '\0')
  741. break;
  742. p = buf;
  743. if (line_count == 0) {
  744. /* get reply code */
  745. get_word(buf1, sizeof(buf1), &p);
  746. get_word(buf1, sizeof(buf1), &p);
  747. reply->status_code = atoi(buf1);
  748. av_strlcpy(reply->reason, p, sizeof(reply->reason));
  749. } else {
  750. ff_rtsp_parse_line(reply, p, rt, method);
  751. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  752. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  753. }
  754. line_count++;
  755. }
  756. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  757. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  758. content_length = reply->content_length;
  759. if (content_length > 0) {
  760. /* leave some room for a trailing '\0' (useful for simple parsing) */
  761. content = av_malloc(content_length + 1);
  762. (void)url_read_complete(rt->rtsp_hd, content, content_length);
  763. content[content_length] = '\0';
  764. }
  765. if (content_ptr)
  766. *content_ptr = content;
  767. else
  768. av_free(content);
  769. if (rt->seq != reply->seq) {
  770. av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
  771. rt->seq, reply->seq);
  772. }
  773. /* EOS */
  774. if (reply->notice == 2101 /* End-of-Stream Reached */ ||
  775. reply->notice == 2104 /* Start-of-Stream Reached */ ||
  776. reply->notice == 2306 /* Continuous Feed Terminated */) {
  777. rt->state = RTSP_STATE_IDLE;
  778. } else if (reply->notice >= 4400 && reply->notice < 5500) {
  779. return AVERROR(EIO); /* data or server error */
  780. } else if (reply->notice == 2401 /* Ticket Expired */ ||
  781. (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
  782. return AVERROR(EPERM);
  783. return 0;
  784. }
  785. int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
  786. const char *method, const char *url,
  787. const char *headers,
  788. const unsigned char *send_content,
  789. int send_content_length)
  790. {
  791. RTSPState *rt = s->priv_data;
  792. char buf[4096], *out_buf;
  793. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  794. /* Add in RTSP headers */
  795. out_buf = buf;
  796. rt->seq++;
  797. snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
  798. if (headers)
  799. av_strlcat(buf, headers, sizeof(buf));
  800. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
  801. if (rt->session_id[0] != '\0' && (!headers ||
  802. !strstr(headers, "\nIf-Match:"))) {
  803. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
  804. }
  805. if (rt->auth[0]) {
  806. char *str = ff_http_auth_create_response(&rt->auth_state,
  807. rt->auth, url, method);
  808. if (str)
  809. av_strlcat(buf, str, sizeof(buf));
  810. av_free(str);
  811. }
  812. if (send_content_length > 0 && send_content)
  813. av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
  814. av_strlcat(buf, "\r\n", sizeof(buf));
  815. /* base64 encode rtsp if tunneling */
  816. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  817. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  818. out_buf = base64buf;
  819. }
  820. dprintf(s, "Sending:\n%s--\n", buf);
  821. url_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
  822. if (send_content_length > 0 && send_content) {
  823. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  824. av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
  825. "with content data not supported\n");
  826. return AVERROR_PATCHWELCOME;
  827. }
  828. url_write(rt->rtsp_hd_out, send_content, send_content_length);
  829. }
  830. rt->last_cmd_time = av_gettime();
  831. return 0;
  832. }
  833. int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
  834. const char *url, const char *headers)
  835. {
  836. return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
  837. }
  838. int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
  839. const char *headers, RTSPMessageHeader *reply,
  840. unsigned char **content_ptr)
  841. {
  842. return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
  843. content_ptr, NULL, 0);
  844. }
  845. int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
  846. const char *method, const char *url,
  847. const char *header,
  848. RTSPMessageHeader *reply,
  849. unsigned char **content_ptr,
  850. const unsigned char *send_content,
  851. int send_content_length)
  852. {
  853. RTSPState *rt = s->priv_data;
  854. HTTPAuthType cur_auth_type;
  855. int ret;
  856. retry:
  857. cur_auth_type = rt->auth_state.auth_type;
  858. if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
  859. send_content,
  860. send_content_length)))
  861. return ret;
  862. if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0, method) ) < 0)
  863. return ret;
  864. if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
  865. rt->auth_state.auth_type != HTTP_AUTH_NONE)
  866. goto retry;
  867. if (reply->status_code > 400){
  868. av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
  869. method,
  870. reply->status_code,
  871. reply->reason);
  872. av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
  873. }
  874. return 0;
  875. }
  876. /**
  877. * @return 0 on success, <0 on error, 1 if protocol is unavailable.
  878. */
  879. static int make_setup_request(AVFormatContext *s, const char *host, int port,
  880. int lower_transport, const char *real_challenge)
  881. {
  882. RTSPState *rt = s->priv_data;
  883. int rtx, j, i, err, interleave = 0;
  884. RTSPStream *rtsp_st;
  885. RTSPMessageHeader reply1, *reply = &reply1;
  886. char cmd[2048];
  887. const char *trans_pref;
  888. if (rt->transport == RTSP_TRANSPORT_RDT)
  889. trans_pref = "x-pn-tng";
  890. else
  891. trans_pref = "RTP/AVP";
  892. /* default timeout: 1 minute */
  893. rt->timeout = 60;
  894. /* for each stream, make the setup request */
  895. /* XXX: we assume the same server is used for the control of each
  896. * RTSP stream */
  897. for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  898. char transport[2048];
  899. /**
  900. * WMS serves all UDP data over a single connection, the RTX, which
  901. * isn't necessarily the first in the SDP but has to be the first
  902. * to be set up, else the second/third SETUP will fail with a 461.
  903. */
  904. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  905. rt->server_type == RTSP_SERVER_WMS) {
  906. if (i == 0) {
  907. /* rtx first */
  908. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  909. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  910. if (len >= 4 &&
  911. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
  912. "/rtx"))
  913. break;
  914. }
  915. if (rtx == rt->nb_rtsp_streams)
  916. return -1; /* no RTX found */
  917. rtsp_st = rt->rtsp_streams[rtx];
  918. } else
  919. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  920. } else
  921. rtsp_st = rt->rtsp_streams[i];
  922. /* RTP/UDP */
  923. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  924. char buf[256];
  925. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  926. port = reply->transports[0].client_port_min;
  927. goto have_port;
  928. }
  929. /* first try in specified port range */
  930. if (RTSP_RTP_PORT_MIN != 0) {
  931. while (j <= RTSP_RTP_PORT_MAX) {
  932. ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
  933. "?localport=%d", j);
  934. /* we will use two ports per rtp stream (rtp and rtcp) */
  935. j += 2;
  936. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
  937. goto rtp_opened;
  938. }
  939. }
  940. #if 0
  941. /* then try on any port */
  942. if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  943. err = AVERROR_INVALIDDATA;
  944. goto fail;
  945. }
  946. #endif
  947. rtp_opened:
  948. port = rtp_get_local_rtp_port(rtsp_st->rtp_handle);
  949. have_port:
  950. snprintf(transport, sizeof(transport) - 1,
  951. "%s/UDP;", trans_pref);
  952. if (rt->server_type != RTSP_SERVER_REAL)
  953. av_strlcat(transport, "unicast;", sizeof(transport));
  954. av_strlcatf(transport, sizeof(transport),
  955. "client_port=%d", port);
  956. if (rt->transport == RTSP_TRANSPORT_RTP &&
  957. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  958. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  959. }
  960. /* RTP/TCP */
  961. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  962. /** For WMS streams, the application streams are only used for
  963. * UDP. When trying to set it up for TCP streams, the server
  964. * will return an error. Therefore, we skip those streams. */
  965. if (rt->server_type == RTSP_SERVER_WMS &&
  966. s->streams[rtsp_st->stream_index]->codec->codec_type ==
  967. AVMEDIA_TYPE_DATA)
  968. continue;
  969. snprintf(transport, sizeof(transport) - 1,
  970. "%s/TCP;", trans_pref);
  971. if (rt->server_type == RTSP_SERVER_WMS)
  972. av_strlcat(transport, "unicast;", sizeof(transport));
  973. av_strlcatf(transport, sizeof(transport),
  974. "interleaved=%d-%d",
  975. interleave, interleave + 1);
  976. interleave += 2;
  977. }
  978. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  979. snprintf(transport, sizeof(transport) - 1,
  980. "%s/UDP;multicast", trans_pref);
  981. }
  982. if (s->oformat) {
  983. av_strlcat(transport, ";mode=receive", sizeof(transport));
  984. } else if (rt->server_type == RTSP_SERVER_REAL ||
  985. rt->server_type == RTSP_SERVER_WMS)
  986. av_strlcat(transport, ";mode=play", sizeof(transport));
  987. snprintf(cmd, sizeof(cmd),
  988. "Transport: %s\r\n",
  989. transport);
  990. if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
  991. char real_res[41], real_csum[9];
  992. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  993. real_challenge);
  994. av_strlcatf(cmd, sizeof(cmd),
  995. "If-Match: %s\r\n"
  996. "RealChallenge2: %s, sd=%s\r\n",
  997. rt->session_id, real_res, real_csum);
  998. }
  999. ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
  1000. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  1001. err = 1;
  1002. goto fail;
  1003. } else if (reply->status_code != RTSP_STATUS_OK ||
  1004. reply->nb_transports != 1) {
  1005. err = AVERROR_INVALIDDATA;
  1006. goto fail;
  1007. }
  1008. /* XXX: same protocol for all streams is required */
  1009. if (i > 0) {
  1010. if (reply->transports[0].lower_transport != rt->lower_transport ||
  1011. reply->transports[0].transport != rt->transport) {
  1012. err = AVERROR_INVALIDDATA;
  1013. goto fail;
  1014. }
  1015. } else {
  1016. rt->lower_transport = reply->transports[0].lower_transport;
  1017. rt->transport = reply->transports[0].transport;
  1018. }
  1019. /* Fail if the server responded with another lower transport mode
  1020. * than what we requested. */
  1021. if (reply->transports[0].lower_transport != lower_transport) {
  1022. av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
  1023. err = AVERROR_INVALIDDATA;
  1024. goto fail;
  1025. }
  1026. switch(reply->transports[0].lower_transport) {
  1027. case RTSP_LOWER_TRANSPORT_TCP:
  1028. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1029. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1030. break;
  1031. case RTSP_LOWER_TRANSPORT_UDP: {
  1032. char url[1024];
  1033. /* Use source address if specified */
  1034. if (reply->transports[0].source[0]) {
  1035. ff_url_join(url, sizeof(url), "rtp", NULL,
  1036. reply->transports[0].source,
  1037. reply->transports[0].server_port_min, NULL);
  1038. } else {
  1039. ff_url_join(url, sizeof(url), "rtp", NULL, host,
  1040. reply->transports[0].server_port_min, NULL);
  1041. }
  1042. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1043. rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1044. err = AVERROR_INVALIDDATA;
  1045. goto fail;
  1046. }
  1047. /* Try to initialize the connection state in a
  1048. * potential NAT router by sending dummy packets.
  1049. * RTP/RTCP dummy packets are used for RDT, too.
  1050. */
  1051. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
  1052. CONFIG_RTPDEC)
  1053. rtp_send_punch_packets(rtsp_st->rtp_handle);
  1054. break;
  1055. }
  1056. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
  1057. char url[1024], namebuf[50];
  1058. struct sockaddr_storage addr;
  1059. int port, ttl;
  1060. if (reply->transports[0].destination.ss_family) {
  1061. addr = reply->transports[0].destination;
  1062. port = reply->transports[0].port_min;
  1063. ttl = reply->transports[0].ttl;
  1064. } else {
  1065. addr = rtsp_st->sdp_ip;
  1066. port = rtsp_st->sdp_port;
  1067. ttl = rtsp_st->sdp_ttl;
  1068. }
  1069. getnameinfo((struct sockaddr*) &addr, sizeof(addr),
  1070. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1071. ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
  1072. port, "?ttl=%d", ttl);
  1073. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1074. err = AVERROR_INVALIDDATA;
  1075. goto fail;
  1076. }
  1077. break;
  1078. }
  1079. }
  1080. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1081. goto fail;
  1082. }
  1083. if (reply->timeout > 0)
  1084. rt->timeout = reply->timeout;
  1085. if (rt->server_type == RTSP_SERVER_REAL)
  1086. rt->need_subscription = 1;
  1087. return 0;
  1088. fail:
  1089. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1090. if (rt->rtsp_streams[i]->rtp_handle) {
  1091. url_close(rt->rtsp_streams[i]->rtp_handle);
  1092. rt->rtsp_streams[i]->rtp_handle = NULL;
  1093. }
  1094. }
  1095. return err;
  1096. }
  1097. void ff_rtsp_close_connections(AVFormatContext *s)
  1098. {
  1099. RTSPState *rt = s->priv_data;
  1100. if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
  1101. url_close(rt->rtsp_hd);
  1102. rt->rtsp_hd = rt->rtsp_hd_out = NULL;
  1103. }
  1104. int ff_rtsp_connect(AVFormatContext *s)
  1105. {
  1106. RTSPState *rt = s->priv_data;
  1107. char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
  1108. char *option_list, *option, *filename;
  1109. int port, err, tcp_fd;
  1110. RTSPMessageHeader reply1 = {0}, *reply = &reply1;
  1111. int lower_transport_mask = 0;
  1112. char real_challenge[64];
  1113. struct sockaddr_storage peer;
  1114. socklen_t peer_len = sizeof(peer);
  1115. if (!ff_network_init())
  1116. return AVERROR(EIO);
  1117. redirect:
  1118. rt->control_transport = RTSP_MODE_PLAIN;
  1119. /* extract hostname and port */
  1120. av_url_split(NULL, 0, auth, sizeof(auth),
  1121. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1122. if (*auth) {
  1123. av_strlcpy(rt->auth, auth, sizeof(rt->auth));
  1124. }
  1125. if (port < 0)
  1126. port = RTSP_DEFAULT_PORT;
  1127. /* search for options */
  1128. option_list = strrchr(path, '?');
  1129. if (option_list) {
  1130. /* Strip out the RTSP specific options, write out the rest of
  1131. * the options back into the same string. */
  1132. filename = option_list;
  1133. while (option_list) {
  1134. /* move the option pointer */
  1135. option = ++option_list;
  1136. option_list = strchr(option_list, '&');
  1137. if (option_list)
  1138. *option_list = 0;
  1139. /* handle the options */
  1140. if (!strcmp(option, "udp")) {
  1141. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
  1142. } else if (!strcmp(option, "multicast")) {
  1143. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1144. } else if (!strcmp(option, "tcp")) {
  1145. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1146. } else if(!strcmp(option, "http")) {
  1147. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1148. rt->control_transport = RTSP_MODE_TUNNEL;
  1149. } else {
  1150. /* Write options back into the buffer, using memmove instead
  1151. * of strcpy since the strings may overlap. */
  1152. int len = strlen(option);
  1153. memmove(++filename, option, len);
  1154. filename += len;
  1155. if (option_list) *filename = '&';
  1156. }
  1157. }
  1158. *filename = 0;
  1159. }
  1160. if (!lower_transport_mask)
  1161. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1162. if (s->oformat) {
  1163. /* Only UDP or TCP - UDP multicast isn't supported. */
  1164. lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
  1165. (1 << RTSP_LOWER_TRANSPORT_TCP);
  1166. if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
  1167. av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
  1168. "only UDP and TCP are supported for output.\n");
  1169. err = AVERROR(EINVAL);
  1170. goto fail;
  1171. }
  1172. }
  1173. /* Construct the URI used in request; this is similar to s->filename,
  1174. * but with authentication credentials removed and RTSP specific options
  1175. * stripped out. */
  1176. ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
  1177. host, port, "%s", path);
  1178. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1179. /* set up initial handshake for tunneling */
  1180. char httpname[1024];
  1181. char sessioncookie[17];
  1182. char headers[1024];
  1183. ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
  1184. snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
  1185. av_get_random_seed(), av_get_random_seed());
  1186. /* GET requests */
  1187. if (url_alloc(&rt->rtsp_hd, httpname, URL_RDONLY) < 0) {
  1188. err = AVERROR(EIO);
  1189. goto fail;
  1190. }
  1191. /* generate GET headers */
  1192. snprintf(headers, sizeof(headers),
  1193. "x-sessioncookie: %s\r\n"
  1194. "Accept: application/x-rtsp-tunnelled\r\n"
  1195. "Pragma: no-cache\r\n"
  1196. "Cache-Control: no-cache\r\n",
  1197. sessioncookie);
  1198. ff_http_set_headers(rt->rtsp_hd, headers);
  1199. /* complete the connection */
  1200. if (url_connect(rt->rtsp_hd)) {
  1201. err = AVERROR(EIO);
  1202. goto fail;
  1203. }
  1204. /* POST requests */
  1205. if (url_alloc(&rt->rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
  1206. err = AVERROR(EIO);
  1207. goto fail;
  1208. }
  1209. /* generate POST headers */
  1210. snprintf(headers, sizeof(headers),
  1211. "x-sessioncookie: %s\r\n"
  1212. "Content-Type: application/x-rtsp-tunnelled\r\n"
  1213. "Pragma: no-cache\r\n"
  1214. "Cache-Control: no-cache\r\n"
  1215. "Content-Length: 32767\r\n"
  1216. "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
  1217. sessioncookie);
  1218. ff_http_set_headers(rt->rtsp_hd_out, headers);
  1219. ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
  1220. /* Initialize the authentication state for the POST session. The HTTP
  1221. * protocol implementation doesn't properly handle multi-pass
  1222. * authentication for POST requests, since it would require one of
  1223. * the following:
  1224. * - implementing Expect: 100-continue, which many HTTP servers
  1225. * don't support anyway, even less the RTSP servers that do HTTP
  1226. * tunneling
  1227. * - sending the whole POST data until getting a 401 reply specifying
  1228. * what authentication method to use, then resending all that data
  1229. * - waiting for potential 401 replies directly after sending the
  1230. * POST header (waiting for some unspecified time)
  1231. * Therefore, we copy the full auth state, which works for both basic
  1232. * and digest. (For digest, we would have to synchronize the nonce
  1233. * count variable between the two sessions, if we'd do more requests
  1234. * with the original session, though.)
  1235. */
  1236. ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
  1237. /* complete the connection */
  1238. if (url_connect(rt->rtsp_hd_out)) {
  1239. err = AVERROR(EIO);
  1240. goto fail;
  1241. }
  1242. } else {
  1243. /* open the tcp connection */
  1244. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
  1245. if (url_open(&rt->rtsp_hd, tcpname, URL_RDWR) < 0) {
  1246. err = AVERROR(EIO);
  1247. goto fail;
  1248. }
  1249. rt->rtsp_hd_out = rt->rtsp_hd;
  1250. }
  1251. rt->seq = 0;
  1252. tcp_fd = url_get_file_handle(rt->rtsp_hd);
  1253. if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
  1254. getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
  1255. NULL, 0, NI_NUMERICHOST);
  1256. }
  1257. /* request options supported by the server; this also detects server
  1258. * type */
  1259. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1260. cmd[0] = 0;
  1261. if (rt->server_type == RTSP_SERVER_REAL)
  1262. av_strlcat(cmd,
  1263. /**
  1264. * The following entries are required for proper
  1265. * streaming from a Realmedia server. They are
  1266. * interdependent in some way although we currently
  1267. * don't quite understand how. Values were copied
  1268. * from mplayer SVN r23589.
  1269. * @param CompanyID is a 16-byte ID in base64
  1270. * @param ClientChallenge is a 16-byte ID in hex
  1271. */
  1272. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1273. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1274. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1275. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1276. sizeof(cmd));
  1277. ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
  1278. if (reply->status_code != RTSP_STATUS_OK) {
  1279. err = AVERROR_INVALIDDATA;
  1280. goto fail;
  1281. }
  1282. /* detect server type if not standard-compliant RTP */
  1283. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1284. rt->server_type = RTSP_SERVER_REAL;
  1285. continue;
  1286. } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
  1287. rt->server_type = RTSP_SERVER_WMS;
  1288. } else if (rt->server_type == RTSP_SERVER_REAL)
  1289. strcpy(real_challenge, reply->real_challenge);
  1290. break;
  1291. }
  1292. if (s->iformat && CONFIG_RTSP_DEMUXER)
  1293. err = ff_rtsp_setup_input_streams(s, reply);
  1294. else if (CONFIG_RTSP_MUXER)
  1295. err = ff_rtsp_setup_output_streams(s, host);
  1296. if (err)
  1297. goto fail;
  1298. do {
  1299. int lower_transport = ff_log2_tab[lower_transport_mask &
  1300. ~(lower_transport_mask - 1)];
  1301. err = make_setup_request(s, host, port, lower_transport,
  1302. rt->server_type == RTSP_SERVER_REAL ?
  1303. real_challenge : NULL);
  1304. if (err < 0)
  1305. goto fail;
  1306. lower_transport_mask &= ~(1 << lower_transport);
  1307. if (lower_transport_mask == 0 && err == 1) {
  1308. err = FF_NETERROR(EPROTONOSUPPORT);
  1309. goto fail;
  1310. }
  1311. } while (err);
  1312. rt->state = RTSP_STATE_IDLE;
  1313. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1314. return 0;
  1315. fail:
  1316. ff_rtsp_close_streams(s);
  1317. ff_rtsp_close_connections(s);
  1318. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1319. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1320. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1321. reply->status_code,
  1322. s->filename);
  1323. goto redirect;
  1324. }
  1325. ff_network_close();
  1326. return err;
  1327. }
  1328. #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
  1329. #if CONFIG_RTPDEC
  1330. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1331. uint8_t *buf, int buf_size, int64_t wait_end)
  1332. {
  1333. RTSPState *rt = s->priv_data;
  1334. RTSPStream *rtsp_st;
  1335. fd_set rfds;
  1336. int fd, fd_rtcp, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
  1337. struct timeval tv;
  1338. for (;;) {
  1339. if (url_interrupt_cb())
  1340. return AVERROR(EINTR);
  1341. if (wait_end && wait_end - av_gettime() < 0)
  1342. return AVERROR(EAGAIN);
  1343. FD_ZERO(&rfds);
  1344. if (rt->rtsp_hd) {
  1345. tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
  1346. FD_SET(tcp_fd, &rfds);
  1347. } else {
  1348. fd_max = 0;
  1349. tcp_fd = -1;
  1350. }
  1351. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1352. rtsp_st = rt->rtsp_streams[i];
  1353. if (rtsp_st->rtp_handle) {
  1354. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1355. fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
  1356. if (FFMAX(fd, fd_rtcp) > fd_max)
  1357. fd_max = FFMAX(fd, fd_rtcp);
  1358. FD_SET(fd, &rfds);
  1359. FD_SET(fd_rtcp, &rfds);
  1360. }
  1361. }
  1362. tv.tv_sec = 0;
  1363. tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
  1364. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1365. if (n > 0) {
  1366. timeout_cnt = 0;
  1367. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1368. rtsp_st = rt->rtsp_streams[i];
  1369. if (rtsp_st->rtp_handle) {
  1370. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1371. fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
  1372. if (FD_ISSET(fd_rtcp, &rfds) || FD_ISSET(fd, &rfds)) {
  1373. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1374. if (ret > 0) {
  1375. *prtsp_st = rtsp_st;
  1376. return ret;
  1377. }
  1378. }
  1379. }
  1380. }
  1381. #if CONFIG_RTSP_DEMUXER
  1382. if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
  1383. RTSPMessageHeader reply;
  1384. ret = ff_rtsp_read_reply(s, &reply, NULL, 0, NULL);
  1385. if (ret < 0)
  1386. return ret;
  1387. /* XXX: parse message */
  1388. if (rt->state != RTSP_STATE_STREAMING)
  1389. return 0;
  1390. }
  1391. #endif
  1392. } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
  1393. return FF_NETERROR(ETIMEDOUT);
  1394. } else if (n < 0 && errno != EINTR)
  1395. return AVERROR(errno);
  1396. }
  1397. }
  1398. int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1399. {
  1400. RTSPState *rt = s->priv_data;
  1401. int ret, len;
  1402. RTSPStream *rtsp_st, *first_queue_st = NULL;
  1403. int64_t wait_end = 0;
  1404. if (rt->nb_byes == rt->nb_rtsp_streams)
  1405. return AVERROR_EOF;
  1406. /* get next frames from the same RTP packet */
  1407. if (rt->cur_transport_priv) {
  1408. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1409. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1410. } else
  1411. ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1412. if (ret == 0) {
  1413. rt->cur_transport_priv = NULL;
  1414. return 0;
  1415. } else if (ret == 1) {
  1416. return 0;
  1417. } else
  1418. rt->cur_transport_priv = NULL;
  1419. }
  1420. if (rt->transport == RTSP_TRANSPORT_RTP) {
  1421. int i;
  1422. int64_t first_queue_time = 0;
  1423. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1424. RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
  1425. int64_t queue_time;
  1426. if (!rtpctx)
  1427. continue;
  1428. queue_time = ff_rtp_queued_packet_time(rtpctx);
  1429. if (queue_time && (queue_time - first_queue_time < 0 ||
  1430. !first_queue_time)) {
  1431. first_queue_time = queue_time;
  1432. first_queue_st = rt->rtsp_streams[i];
  1433. }
  1434. }
  1435. if (first_queue_time)
  1436. wait_end = first_queue_time + s->max_delay;
  1437. }
  1438. /* read next RTP packet */
  1439. redo:
  1440. if (!rt->recvbuf) {
  1441. rt->recvbuf = av_malloc(RECVBUF_SIZE);
  1442. if (!rt->recvbuf)
  1443. return AVERROR(ENOMEM);
  1444. }
  1445. switch(rt->lower_transport) {
  1446. default:
  1447. #if CONFIG_RTSP_DEMUXER
  1448. case RTSP_LOWER_TRANSPORT_TCP:
  1449. len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
  1450. break;
  1451. #endif
  1452. case RTSP_LOWER_TRANSPORT_UDP:
  1453. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1454. len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
  1455. if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1456. rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1457. break;
  1458. }
  1459. if (len == AVERROR(EAGAIN) && first_queue_st &&
  1460. rt->transport == RTSP_TRANSPORT_RTP) {
  1461. rtsp_st = first_queue_st;
  1462. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
  1463. goto end;
  1464. }
  1465. if (len < 0)
  1466. return len;
  1467. if (len == 0)
  1468. return AVERROR_EOF;
  1469. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1470. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1471. } else {
  1472. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1473. if (ret < 0) {
  1474. /* Either bad packet, or a RTCP packet. Check if the
  1475. * first_rtcp_ntp_time field was initialized. */
  1476. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1477. if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
  1478. /* first_rtcp_ntp_time has been initialized for this stream,
  1479. * copy the same value to all other uninitialized streams,
  1480. * in order to map their timestamp origin to the same ntp time
  1481. * as this one. */
  1482. int i;
  1483. AVStream *st = NULL;
  1484. if (rtsp_st->stream_index >= 0)
  1485. st = s->streams[rtsp_st->stream_index];
  1486. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1487. RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
  1488. AVStream *st2 = NULL;
  1489. if (rt->rtsp_streams[i]->stream_index >= 0)
  1490. st2 = s->streams[rt->rtsp_streams[i]->stream_index];
  1491. if (rtpctx2 && st && st2 &&
  1492. rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
  1493. rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
  1494. rtpctx2->rtcp_ts_offset = av_rescale_q(
  1495. rtpctx->rtcp_ts_offset, st->time_base,
  1496. st2->time_base);
  1497. }
  1498. }
  1499. }
  1500. if (ret == -RTCP_BYE) {
  1501. rt->nb_byes++;
  1502. av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
  1503. rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
  1504. if (rt->nb_byes == rt->nb_rtsp_streams)
  1505. return AVERROR_EOF;
  1506. }
  1507. }
  1508. }
  1509. end:
  1510. if (ret < 0)
  1511. goto redo;
  1512. if (ret == 1)
  1513. /* more packets may follow, so we save the RTP context */
  1514. rt->cur_transport_priv = rtsp_st->transport_priv;
  1515. return ret;
  1516. }
  1517. #endif /* CONFIG_RTPDEC */
  1518. #if CONFIG_SDP_DEMUXER
  1519. static int sdp_probe(AVProbeData *p1)
  1520. {
  1521. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1522. /* we look for a line beginning "c=IN IP" */
  1523. while (p < p_end && *p != '\0') {
  1524. if (p + sizeof("c=IN IP") - 1 < p_end &&
  1525. av_strstart(p, "c=IN IP", NULL))
  1526. return AVPROBE_SCORE_MAX / 2;
  1527. while (p < p_end - 1 && *p != '\n') p++;
  1528. if (++p >= p_end)
  1529. break;
  1530. if (*p == '\r')
  1531. p++;
  1532. }
  1533. return 0;
  1534. }
  1535. static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1536. {
  1537. RTSPState *rt = s->priv_data;
  1538. RTSPStream *rtsp_st;
  1539. int size, i, err;
  1540. char *content;
  1541. char url[1024];
  1542. if (!ff_network_init())
  1543. return AVERROR(EIO);
  1544. /* read the whole sdp file */
  1545. /* XXX: better loading */
  1546. content = av_malloc(SDP_MAX_SIZE);
  1547. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1548. if (size <= 0) {
  1549. av_free(content);
  1550. return AVERROR_INVALIDDATA;
  1551. }
  1552. content[size] ='\0';
  1553. ff_sdp_parse(s, content);
  1554. av_free(content);
  1555. /* open each RTP stream */
  1556. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1557. char namebuf[50];
  1558. rtsp_st = rt->rtsp_streams[i];
  1559. getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
  1560. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1561. ff_url_join(url, sizeof(url), "rtp", NULL,
  1562. namebuf, rtsp_st->sdp_port,
  1563. "?localport=%d&ttl=%d", rtsp_st->sdp_port,
  1564. rtsp_st->sdp_ttl);
  1565. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1566. err = AVERROR_INVALIDDATA;
  1567. goto fail;
  1568. }
  1569. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1570. goto fail;
  1571. }
  1572. return 0;
  1573. fail:
  1574. ff_rtsp_close_streams(s);
  1575. ff_network_close();
  1576. return err;
  1577. }
  1578. static int sdp_read_close(AVFormatContext *s)
  1579. {
  1580. ff_rtsp_close_streams(s);
  1581. ff_network_close();
  1582. return 0;
  1583. }
  1584. AVInputFormat sdp_demuxer = {
  1585. "sdp",
  1586. NULL_IF_CONFIG_SMALL("SDP"),
  1587. sizeof(RTSPState),
  1588. sdp_probe,
  1589. sdp_read_header,
  1590. ff_rtsp_fetch_packet,
  1591. sdp_read_close,
  1592. };
  1593. #endif /* CONFIG_SDP_DEMUXER */
  1594. #if CONFIG_RTP_DEMUXER
  1595. static int rtp_probe(AVProbeData *p)
  1596. {
  1597. if (av_strstart(p->filename, "rtp:", NULL))
  1598. return AVPROBE_SCORE_MAX;
  1599. return 0;
  1600. }
  1601. static int rtp_read_header(AVFormatContext *s,
  1602. AVFormatParameters *ap)
  1603. {
  1604. uint8_t recvbuf[1500];
  1605. char host[500], sdp[500];
  1606. int ret, port;
  1607. URLContext* in = NULL;
  1608. int payload_type;
  1609. AVCodecContext codec;
  1610. struct sockaddr_storage addr;
  1611. ByteIOContext pb;
  1612. socklen_t addrlen = sizeof(addr);
  1613. if (!ff_network_init())
  1614. return AVERROR(EIO);
  1615. ret = url_open(&in, s->filename, URL_RDONLY);
  1616. if (ret)
  1617. goto fail;
  1618. while (1) {
  1619. ret = url_read(in, recvbuf, sizeof(recvbuf));
  1620. if (ret == AVERROR(EAGAIN))
  1621. continue;
  1622. if (ret < 0)
  1623. goto fail;
  1624. if (ret < 12) {
  1625. av_log(s, AV_LOG_WARNING, "Received too short packet\n");
  1626. continue;
  1627. }
  1628. if ((recvbuf[0] & 0xc0) != 0x80) {
  1629. av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
  1630. "received\n");
  1631. continue;
  1632. }
  1633. payload_type = recvbuf[1] & 0x7f;
  1634. break;
  1635. }
  1636. getsockname(url_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
  1637. url_close(in);
  1638. in = NULL;
  1639. memset(&codec, 0, sizeof(codec));
  1640. if (ff_rtp_get_codec_info(&codec, payload_type)) {
  1641. av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
  1642. "without an SDP file describing it\n",
  1643. payload_type);
  1644. goto fail;
  1645. }
  1646. if (codec.codec_type != AVMEDIA_TYPE_DATA) {
  1647. av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
  1648. "properly you need an SDP file "
  1649. "describing it\n");
  1650. }
  1651. av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
  1652. NULL, 0, s->filename);
  1653. snprintf(sdp, sizeof(sdp),
  1654. "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
  1655. addr.ss_family == AF_INET ? 4 : 6, host,
  1656. codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
  1657. codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
  1658. port, payload_type);
  1659. av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
  1660. init_put_byte(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
  1661. s->pb = &pb;
  1662. /* sdp_read_header initializes this again */
  1663. ff_network_close();
  1664. ret = sdp_read_header(s, ap);
  1665. s->pb = NULL;
  1666. return ret;
  1667. fail:
  1668. if (in)
  1669. url_close(in);
  1670. ff_network_close();
  1671. return ret;
  1672. }
  1673. AVInputFormat rtp_demuxer = {
  1674. "rtp",
  1675. NULL_IF_CONFIG_SMALL("RTP input format"),
  1676. sizeof(RTSPState),
  1677. rtp_probe,
  1678. rtp_read_header,
  1679. ff_rtsp_fetch_packet,
  1680. sdp_read_close,
  1681. .flags = AVFMT_NOFILE,
  1682. };
  1683. #endif /* CONFIG_RTP_DEMUXER */