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.

1841 lines
64KB

  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. HTTPAuthState *auth_state)
  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) && auth_state) {
  669. p += strspn(p, SPACE_CHARS);
  670. ff_http_auth_handle_header(auth_state, "WWW-Authenticate", p);
  671. } else if (av_stristart(p, "Authentication-Info:", &p) && auth_state) {
  672. p += strspn(p, SPACE_CHARS);
  673. ff_http_auth_handle_header(auth_state, "Authentication-Info", p);
  674. } else if (av_stristart(p, "Content-Base:", &p)) {
  675. p += strspn(p, SPACE_CHARS);
  676. av_strlcpy(reply->content_base, p , sizeof(reply->content_base));
  677. }
  678. }
  679. /* skip a RTP/TCP interleaved packet */
  680. void ff_rtsp_skip_packet(AVFormatContext *s)
  681. {
  682. RTSPState *rt = s->priv_data;
  683. int ret, len, len1;
  684. uint8_t buf[1024];
  685. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  686. if (ret != 3)
  687. return;
  688. len = AV_RB16(buf + 1);
  689. dprintf(s, "skipping RTP packet len=%d\n", len);
  690. /* skip payload */
  691. while (len > 0) {
  692. len1 = len;
  693. if (len1 > sizeof(buf))
  694. len1 = sizeof(buf);
  695. ret = url_read_complete(rt->rtsp_hd, buf, len1);
  696. if (ret != len1)
  697. return;
  698. len -= len1;
  699. }
  700. }
  701. int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
  702. unsigned char **content_ptr,
  703. int return_on_interleaved_data)
  704. {
  705. RTSPState *rt = s->priv_data;
  706. char buf[4096], buf1[1024], *q;
  707. unsigned char ch;
  708. const char *p;
  709. int ret, content_length, line_count = 0;
  710. unsigned char *content = NULL;
  711. memset(reply, 0, sizeof(*reply));
  712. /* parse reply (XXX: use buffers) */
  713. rt->last_reply[0] = '\0';
  714. for (;;) {
  715. q = buf;
  716. for (;;) {
  717. ret = url_read_complete(rt->rtsp_hd, &ch, 1);
  718. #ifdef DEBUG_RTP_TCP
  719. dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  720. #endif
  721. if (ret != 1)
  722. return AVERROR_EOF;
  723. if (ch == '\n')
  724. break;
  725. if (ch == '$') {
  726. /* XXX: only parse it if first char on line ? */
  727. if (return_on_interleaved_data) {
  728. return 1;
  729. } else
  730. ff_rtsp_skip_packet(s);
  731. } else if (ch != '\r') {
  732. if ((q - buf) < sizeof(buf) - 1)
  733. *q++ = ch;
  734. }
  735. }
  736. *q = '\0';
  737. dprintf(s, "line='%s'\n", buf);
  738. /* test if last line */
  739. if (buf[0] == '\0')
  740. break;
  741. p = buf;
  742. if (line_count == 0) {
  743. /* get reply code */
  744. get_word(buf1, sizeof(buf1), &p);
  745. get_word(buf1, sizeof(buf1), &p);
  746. reply->status_code = atoi(buf1);
  747. av_strlcpy(reply->reason, p, sizeof(reply->reason));
  748. } else {
  749. ff_rtsp_parse_line(reply, p, &rt->auth_state);
  750. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  751. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  752. }
  753. line_count++;
  754. }
  755. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  756. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  757. content_length = reply->content_length;
  758. if (content_length > 0) {
  759. /* leave some room for a trailing '\0' (useful for simple parsing) */
  760. content = av_malloc(content_length + 1);
  761. (void)url_read_complete(rt->rtsp_hd, content, content_length);
  762. content[content_length] = '\0';
  763. }
  764. if (content_ptr)
  765. *content_ptr = content;
  766. else
  767. av_free(content);
  768. if (rt->seq != reply->seq) {
  769. av_log(s, AV_LOG_WARNING, "CSeq %d expected, %d received.\n",
  770. rt->seq, reply->seq);
  771. }
  772. /* EOS */
  773. if (reply->notice == 2101 /* End-of-Stream Reached */ ||
  774. reply->notice == 2104 /* Start-of-Stream Reached */ ||
  775. reply->notice == 2306 /* Continuous Feed Terminated */) {
  776. rt->state = RTSP_STATE_IDLE;
  777. } else if (reply->notice >= 4400 && reply->notice < 5500) {
  778. return AVERROR(EIO); /* data or server error */
  779. } else if (reply->notice == 2401 /* Ticket Expired */ ||
  780. (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
  781. return AVERROR(EPERM);
  782. return 0;
  783. }
  784. int ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
  785. const char *method, const char *url,
  786. const char *headers,
  787. const unsigned char *send_content,
  788. int send_content_length)
  789. {
  790. RTSPState *rt = s->priv_data;
  791. char buf[4096], *out_buf;
  792. char base64buf[AV_BASE64_SIZE(sizeof(buf))];
  793. /* Add in RTSP headers */
  794. out_buf = buf;
  795. rt->seq++;
  796. snprintf(buf, sizeof(buf), "%s %s RTSP/1.0\r\n", method, url);
  797. if (headers)
  798. av_strlcat(buf, headers, sizeof(buf));
  799. av_strlcatf(buf, sizeof(buf), "CSeq: %d\r\n", rt->seq);
  800. if (rt->session_id[0] != '\0' && (!headers ||
  801. !strstr(headers, "\nIf-Match:"))) {
  802. av_strlcatf(buf, sizeof(buf), "Session: %s\r\n", rt->session_id);
  803. }
  804. if (rt->auth[0]) {
  805. char *str = ff_http_auth_create_response(&rt->auth_state,
  806. rt->auth, url, method);
  807. if (str)
  808. av_strlcat(buf, str, sizeof(buf));
  809. av_free(str);
  810. }
  811. if (send_content_length > 0 && send_content)
  812. av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
  813. av_strlcat(buf, "\r\n", sizeof(buf));
  814. /* base64 encode rtsp if tunneling */
  815. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  816. av_base64_encode(base64buf, sizeof(base64buf), buf, strlen(buf));
  817. out_buf = base64buf;
  818. }
  819. dprintf(s, "Sending:\n%s--\n", buf);
  820. url_write(rt->rtsp_hd_out, out_buf, strlen(out_buf));
  821. if (send_content_length > 0 && send_content) {
  822. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  823. av_log(s, AV_LOG_ERROR, "tunneling of RTSP requests "
  824. "with content data not supported\n");
  825. return AVERROR_PATCHWELCOME;
  826. }
  827. url_write(rt->rtsp_hd_out, send_content, send_content_length);
  828. }
  829. rt->last_cmd_time = av_gettime();
  830. return 0;
  831. }
  832. int ff_rtsp_send_cmd_async(AVFormatContext *s, const char *method,
  833. const char *url, const char *headers)
  834. {
  835. return ff_rtsp_send_cmd_with_content_async(s, method, url, headers, NULL, 0);
  836. }
  837. int ff_rtsp_send_cmd(AVFormatContext *s, const char *method, const char *url,
  838. const char *headers, RTSPMessageHeader *reply,
  839. unsigned char **content_ptr)
  840. {
  841. return ff_rtsp_send_cmd_with_content(s, method, url, headers, reply,
  842. content_ptr, NULL, 0);
  843. }
  844. int ff_rtsp_send_cmd_with_content(AVFormatContext *s,
  845. const char *method, const char *url,
  846. const char *header,
  847. RTSPMessageHeader *reply,
  848. unsigned char **content_ptr,
  849. const unsigned char *send_content,
  850. int send_content_length)
  851. {
  852. RTSPState *rt = s->priv_data;
  853. HTTPAuthType cur_auth_type;
  854. int ret;
  855. retry:
  856. cur_auth_type = rt->auth_state.auth_type;
  857. if ((ret = ff_rtsp_send_cmd_with_content_async(s, method, url, header,
  858. send_content,
  859. send_content_length)))
  860. return ret;
  861. if ((ret = ff_rtsp_read_reply(s, reply, content_ptr, 0) ) < 0)
  862. return ret;
  863. if (reply->status_code == 401 && cur_auth_type == HTTP_AUTH_NONE &&
  864. rt->auth_state.auth_type != HTTP_AUTH_NONE)
  865. goto retry;
  866. if (reply->status_code > 400){
  867. av_log(s, AV_LOG_ERROR, "method %s failed: %d%s\n",
  868. method,
  869. reply->status_code,
  870. reply->reason);
  871. av_log(s, AV_LOG_DEBUG, "%s\n", rt->last_reply);
  872. }
  873. return 0;
  874. }
  875. /**
  876. * @return 0 on success, <0 on error, 1 if protocol is unavailable.
  877. */
  878. static int make_setup_request(AVFormatContext *s, const char *host, int port,
  879. int lower_transport, const char *real_challenge)
  880. {
  881. RTSPState *rt = s->priv_data;
  882. int rtx, j, i, err, interleave = 0;
  883. RTSPStream *rtsp_st;
  884. RTSPMessageHeader reply1, *reply = &reply1;
  885. char cmd[2048];
  886. const char *trans_pref;
  887. if (rt->transport == RTSP_TRANSPORT_RDT)
  888. trans_pref = "x-pn-tng";
  889. else
  890. trans_pref = "RTP/AVP";
  891. /* default timeout: 1 minute */
  892. rt->timeout = 60;
  893. /* for each stream, make the setup request */
  894. /* XXX: we assume the same server is used for the control of each
  895. * RTSP stream */
  896. for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  897. char transport[2048];
  898. /**
  899. * WMS serves all UDP data over a single connection, the RTX, which
  900. * isn't necessarily the first in the SDP but has to be the first
  901. * to be set up, else the second/third SETUP will fail with a 461.
  902. */
  903. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  904. rt->server_type == RTSP_SERVER_WMS) {
  905. if (i == 0) {
  906. /* rtx first */
  907. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  908. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  909. if (len >= 4 &&
  910. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
  911. "/rtx"))
  912. break;
  913. }
  914. if (rtx == rt->nb_rtsp_streams)
  915. return -1; /* no RTX found */
  916. rtsp_st = rt->rtsp_streams[rtx];
  917. } else
  918. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  919. } else
  920. rtsp_st = rt->rtsp_streams[i];
  921. /* RTP/UDP */
  922. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  923. char buf[256];
  924. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  925. port = reply->transports[0].client_port_min;
  926. goto have_port;
  927. }
  928. /* first try in specified port range */
  929. if (RTSP_RTP_PORT_MIN != 0) {
  930. while (j <= RTSP_RTP_PORT_MAX) {
  931. ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
  932. "?localport=%d", j);
  933. /* we will use two ports per rtp stream (rtp and rtcp) */
  934. j += 2;
  935. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
  936. goto rtp_opened;
  937. }
  938. }
  939. #if 0
  940. /* then try on any port */
  941. if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  942. err = AVERROR_INVALIDDATA;
  943. goto fail;
  944. }
  945. #endif
  946. rtp_opened:
  947. port = rtp_get_local_rtp_port(rtsp_st->rtp_handle);
  948. have_port:
  949. snprintf(transport, sizeof(transport) - 1,
  950. "%s/UDP;", trans_pref);
  951. if (rt->server_type != RTSP_SERVER_REAL)
  952. av_strlcat(transport, "unicast;", sizeof(transport));
  953. av_strlcatf(transport, sizeof(transport),
  954. "client_port=%d", port);
  955. if (rt->transport == RTSP_TRANSPORT_RTP &&
  956. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  957. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  958. }
  959. /* RTP/TCP */
  960. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  961. /** For WMS streams, the application streams are only used for
  962. * UDP. When trying to set it up for TCP streams, the server
  963. * will return an error. Therefore, we skip those streams. */
  964. if (rt->server_type == RTSP_SERVER_WMS &&
  965. s->streams[rtsp_st->stream_index]->codec->codec_type ==
  966. AVMEDIA_TYPE_DATA)
  967. continue;
  968. snprintf(transport, sizeof(transport) - 1,
  969. "%s/TCP;", trans_pref);
  970. if (rt->server_type == RTSP_SERVER_WMS)
  971. av_strlcat(transport, "unicast;", sizeof(transport));
  972. av_strlcatf(transport, sizeof(transport),
  973. "interleaved=%d-%d",
  974. interleave, interleave + 1);
  975. interleave += 2;
  976. }
  977. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  978. snprintf(transport, sizeof(transport) - 1,
  979. "%s/UDP;multicast", trans_pref);
  980. }
  981. if (s->oformat) {
  982. av_strlcat(transport, ";mode=receive", sizeof(transport));
  983. } else if (rt->server_type == RTSP_SERVER_REAL ||
  984. rt->server_type == RTSP_SERVER_WMS)
  985. av_strlcat(transport, ";mode=play", sizeof(transport));
  986. snprintf(cmd, sizeof(cmd),
  987. "Transport: %s\r\n",
  988. transport);
  989. if (i == 0 && rt->server_type == RTSP_SERVER_REAL && CONFIG_RTPDEC) {
  990. char real_res[41], real_csum[9];
  991. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  992. real_challenge);
  993. av_strlcatf(cmd, sizeof(cmd),
  994. "If-Match: %s\r\n"
  995. "RealChallenge2: %s, sd=%s\r\n",
  996. rt->session_id, real_res, real_csum);
  997. }
  998. ff_rtsp_send_cmd(s, "SETUP", rtsp_st->control_url, cmd, reply, NULL);
  999. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  1000. err = 1;
  1001. goto fail;
  1002. } else if (reply->status_code != RTSP_STATUS_OK ||
  1003. reply->nb_transports != 1) {
  1004. err = AVERROR_INVALIDDATA;
  1005. goto fail;
  1006. }
  1007. /* XXX: same protocol for all streams is required */
  1008. if (i > 0) {
  1009. if (reply->transports[0].lower_transport != rt->lower_transport ||
  1010. reply->transports[0].transport != rt->transport) {
  1011. err = AVERROR_INVALIDDATA;
  1012. goto fail;
  1013. }
  1014. } else {
  1015. rt->lower_transport = reply->transports[0].lower_transport;
  1016. rt->transport = reply->transports[0].transport;
  1017. }
  1018. /* Fail if the server responded with another lower transport mode
  1019. * than what we requested. */
  1020. if (reply->transports[0].lower_transport != lower_transport) {
  1021. av_log(s, AV_LOG_ERROR, "Nonmatching transport in server reply\n");
  1022. err = AVERROR_INVALIDDATA;
  1023. goto fail;
  1024. }
  1025. switch(reply->transports[0].lower_transport) {
  1026. case RTSP_LOWER_TRANSPORT_TCP:
  1027. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1028. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1029. break;
  1030. case RTSP_LOWER_TRANSPORT_UDP: {
  1031. char url[1024];
  1032. /* Use source address if specified */
  1033. if (reply->transports[0].source[0]) {
  1034. ff_url_join(url, sizeof(url), "rtp", NULL,
  1035. reply->transports[0].source,
  1036. reply->transports[0].server_port_min, NULL);
  1037. } else {
  1038. ff_url_join(url, sizeof(url), "rtp", NULL, host,
  1039. reply->transports[0].server_port_min, NULL);
  1040. }
  1041. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1042. rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1043. err = AVERROR_INVALIDDATA;
  1044. goto fail;
  1045. }
  1046. /* Try to initialize the connection state in a
  1047. * potential NAT router by sending dummy packets.
  1048. * RTP/RTCP dummy packets are used for RDT, too.
  1049. */
  1050. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat &&
  1051. CONFIG_RTPDEC)
  1052. rtp_send_punch_packets(rtsp_st->rtp_handle);
  1053. break;
  1054. }
  1055. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
  1056. char url[1024], namebuf[50];
  1057. struct sockaddr_storage addr;
  1058. int port, ttl;
  1059. if (reply->transports[0].destination.ss_family) {
  1060. addr = reply->transports[0].destination;
  1061. port = reply->transports[0].port_min;
  1062. ttl = reply->transports[0].ttl;
  1063. } else {
  1064. addr = rtsp_st->sdp_ip;
  1065. port = rtsp_st->sdp_port;
  1066. ttl = rtsp_st->sdp_ttl;
  1067. }
  1068. getnameinfo((struct sockaddr*) &addr, sizeof(addr),
  1069. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1070. ff_url_join(url, sizeof(url), "rtp", NULL, namebuf,
  1071. port, "?ttl=%d", ttl);
  1072. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1073. err = AVERROR_INVALIDDATA;
  1074. goto fail;
  1075. }
  1076. break;
  1077. }
  1078. }
  1079. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1080. goto fail;
  1081. }
  1082. if (reply->timeout > 0)
  1083. rt->timeout = reply->timeout;
  1084. if (rt->server_type == RTSP_SERVER_REAL)
  1085. rt->need_subscription = 1;
  1086. return 0;
  1087. fail:
  1088. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1089. if (rt->rtsp_streams[i]->rtp_handle) {
  1090. url_close(rt->rtsp_streams[i]->rtp_handle);
  1091. rt->rtsp_streams[i]->rtp_handle = NULL;
  1092. }
  1093. }
  1094. return err;
  1095. }
  1096. void ff_rtsp_close_connections(AVFormatContext *s)
  1097. {
  1098. RTSPState *rt = s->priv_data;
  1099. if (rt->rtsp_hd_out != rt->rtsp_hd) url_close(rt->rtsp_hd_out);
  1100. url_close(rt->rtsp_hd);
  1101. rt->rtsp_hd = rt->rtsp_hd_out = NULL;
  1102. }
  1103. int ff_rtsp_connect(AVFormatContext *s)
  1104. {
  1105. RTSPState *rt = s->priv_data;
  1106. char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
  1107. char *option_list, *option, *filename;
  1108. int port, err, tcp_fd;
  1109. RTSPMessageHeader reply1 = {0}, *reply = &reply1;
  1110. int lower_transport_mask = 0;
  1111. char real_challenge[64];
  1112. struct sockaddr_storage peer;
  1113. socklen_t peer_len = sizeof(peer);
  1114. if (!ff_network_init())
  1115. return AVERROR(EIO);
  1116. redirect:
  1117. rt->control_transport = RTSP_MODE_PLAIN;
  1118. /* extract hostname and port */
  1119. av_url_split(NULL, 0, auth, sizeof(auth),
  1120. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1121. if (*auth) {
  1122. av_strlcpy(rt->auth, auth, sizeof(rt->auth));
  1123. }
  1124. if (port < 0)
  1125. port = RTSP_DEFAULT_PORT;
  1126. /* search for options */
  1127. option_list = strrchr(path, '?');
  1128. if (option_list) {
  1129. /* Strip out the RTSP specific options, write out the rest of
  1130. * the options back into the same string. */
  1131. filename = option_list;
  1132. while (option_list) {
  1133. /* move the option pointer */
  1134. option = ++option_list;
  1135. option_list = strchr(option_list, '&');
  1136. if (option_list)
  1137. *option_list = 0;
  1138. /* handle the options */
  1139. if (!strcmp(option, "udp")) {
  1140. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);
  1141. } else if (!strcmp(option, "multicast")) {
  1142. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1143. } else if (!strcmp(option, "tcp")) {
  1144. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1145. } else if(!strcmp(option, "http")) {
  1146. lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);
  1147. rt->control_transport = RTSP_MODE_TUNNEL;
  1148. } else {
  1149. /* Write options back into the buffer, using memmove instead
  1150. * of strcpy since the strings may overlap. */
  1151. int len = strlen(option);
  1152. memmove(++filename, option, len);
  1153. filename += len;
  1154. if (option_list) *filename = '&';
  1155. }
  1156. }
  1157. *filename = 0;
  1158. }
  1159. if (!lower_transport_mask)
  1160. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1161. if (s->oformat) {
  1162. /* Only UDP or TCP - UDP multicast isn't supported. */
  1163. lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |
  1164. (1 << RTSP_LOWER_TRANSPORT_TCP);
  1165. if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {
  1166. av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
  1167. "only UDP and TCP are supported for output.\n");
  1168. err = AVERROR(EINVAL);
  1169. goto fail;
  1170. }
  1171. }
  1172. /* Construct the URI used in request; this is similar to s->filename,
  1173. * but with authentication credentials removed and RTSP specific options
  1174. * stripped out. */
  1175. ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,
  1176. host, port, "%s", path);
  1177. if (rt->control_transport == RTSP_MODE_TUNNEL) {
  1178. /* set up initial handshake for tunneling */
  1179. char httpname[1024];
  1180. char sessioncookie[17];
  1181. char headers[1024];
  1182. ff_url_join(httpname, sizeof(httpname), "http", auth, host, port, "%s", path);
  1183. snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",
  1184. av_get_random_seed(), av_get_random_seed());
  1185. /* GET requests */
  1186. if (url_alloc(&rt->rtsp_hd, httpname, URL_RDONLY) < 0) {
  1187. err = AVERROR(EIO);
  1188. goto fail;
  1189. }
  1190. /* generate GET headers */
  1191. snprintf(headers, sizeof(headers),
  1192. "x-sessioncookie: %s\r\n"
  1193. "Accept: application/x-rtsp-tunnelled\r\n"
  1194. "Pragma: no-cache\r\n"
  1195. "Cache-Control: no-cache\r\n",
  1196. sessioncookie);
  1197. ff_http_set_headers(rt->rtsp_hd, headers);
  1198. /* complete the connection */
  1199. if (url_connect(rt->rtsp_hd)) {
  1200. err = AVERROR(EIO);
  1201. goto fail;
  1202. }
  1203. /* POST requests */
  1204. if (url_alloc(&rt->rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {
  1205. err = AVERROR(EIO);
  1206. goto fail;
  1207. }
  1208. /* generate POST headers */
  1209. snprintf(headers, sizeof(headers),
  1210. "x-sessioncookie: %s\r\n"
  1211. "Content-Type: application/x-rtsp-tunnelled\r\n"
  1212. "Pragma: no-cache\r\n"
  1213. "Cache-Control: no-cache\r\n"
  1214. "Content-Length: 32767\r\n"
  1215. "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",
  1216. sessioncookie);
  1217. ff_http_set_headers(rt->rtsp_hd_out, headers);
  1218. ff_http_set_chunked_transfer_encoding(rt->rtsp_hd_out, 0);
  1219. /* Initialize the authentication state for the POST session. The HTTP
  1220. * protocol implementation doesn't properly handle multi-pass
  1221. * authentication for POST requests, since it would require one of
  1222. * the following:
  1223. * - implementing Expect: 100-continue, which many HTTP servers
  1224. * don't support anyway, even less the RTSP servers that do HTTP
  1225. * tunneling
  1226. * - sending the whole POST data until getting a 401 reply specifying
  1227. * what authentication method to use, then resending all that data
  1228. * - waiting for potential 401 replies directly after sending the
  1229. * POST header (waiting for some unspecified time)
  1230. * Therefore, we copy the full auth state, which works for both basic
  1231. * and digest. (For digest, we would have to synchronize the nonce
  1232. * count variable between the two sessions, if we'd do more requests
  1233. * with the original session, though.)
  1234. */
  1235. ff_http_init_auth_state(rt->rtsp_hd_out, rt->rtsp_hd);
  1236. /* complete the connection */
  1237. if (url_connect(rt->rtsp_hd_out)) {
  1238. err = AVERROR(EIO);
  1239. goto fail;
  1240. }
  1241. } else {
  1242. /* open the tcp connection */
  1243. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
  1244. if (url_open(&rt->rtsp_hd, tcpname, URL_RDWR) < 0) {
  1245. err = AVERROR(EIO);
  1246. goto fail;
  1247. }
  1248. rt->rtsp_hd_out = rt->rtsp_hd;
  1249. }
  1250. rt->seq = 0;
  1251. tcp_fd = url_get_file_handle(rt->rtsp_hd);
  1252. if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {
  1253. getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),
  1254. NULL, 0, NI_NUMERICHOST);
  1255. }
  1256. /* request options supported by the server; this also detects server
  1257. * type */
  1258. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1259. cmd[0] = 0;
  1260. if (rt->server_type == RTSP_SERVER_REAL)
  1261. av_strlcat(cmd,
  1262. /**
  1263. * The following entries are required for proper
  1264. * streaming from a Realmedia server. They are
  1265. * interdependent in some way although we currently
  1266. * don't quite understand how. Values were copied
  1267. * from mplayer SVN r23589.
  1268. * @param CompanyID is a 16-byte ID in base64
  1269. * @param ClientChallenge is a 16-byte ID in hex
  1270. */
  1271. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1272. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1273. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1274. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1275. sizeof(cmd));
  1276. ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);
  1277. if (reply->status_code != RTSP_STATUS_OK) {
  1278. err = AVERROR_INVALIDDATA;
  1279. goto fail;
  1280. }
  1281. /* detect server type if not standard-compliant RTP */
  1282. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1283. rt->server_type = RTSP_SERVER_REAL;
  1284. continue;
  1285. } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
  1286. rt->server_type = RTSP_SERVER_WMS;
  1287. } else if (rt->server_type == RTSP_SERVER_REAL)
  1288. strcpy(real_challenge, reply->real_challenge);
  1289. break;
  1290. }
  1291. if (s->iformat && CONFIG_RTSP_DEMUXER)
  1292. err = ff_rtsp_setup_input_streams(s, reply);
  1293. else if (CONFIG_RTSP_MUXER)
  1294. err = ff_rtsp_setup_output_streams(s, host);
  1295. if (err)
  1296. goto fail;
  1297. do {
  1298. int lower_transport = ff_log2_tab[lower_transport_mask &
  1299. ~(lower_transport_mask - 1)];
  1300. err = make_setup_request(s, host, port, lower_transport,
  1301. rt->server_type == RTSP_SERVER_REAL ?
  1302. real_challenge : NULL);
  1303. if (err < 0)
  1304. goto fail;
  1305. lower_transport_mask &= ~(1 << lower_transport);
  1306. if (lower_transport_mask == 0 && err == 1) {
  1307. err = FF_NETERROR(EPROTONOSUPPORT);
  1308. goto fail;
  1309. }
  1310. } while (err);
  1311. rt->state = RTSP_STATE_IDLE;
  1312. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1313. return 0;
  1314. fail:
  1315. ff_rtsp_close_streams(s);
  1316. ff_rtsp_close_connections(s);
  1317. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1318. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1319. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1320. reply->status_code,
  1321. s->filename);
  1322. goto redirect;
  1323. }
  1324. ff_network_close();
  1325. return err;
  1326. }
  1327. #endif /* CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER */
  1328. #if CONFIG_RTPDEC
  1329. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1330. uint8_t *buf, int buf_size, int64_t wait_end)
  1331. {
  1332. RTSPState *rt = s->priv_data;
  1333. RTSPStream *rtsp_st;
  1334. fd_set rfds;
  1335. int fd, fd_rtcp, fd_max, n, i, ret, tcp_fd, timeout_cnt = 0;
  1336. struct timeval tv;
  1337. for (;;) {
  1338. if (url_interrupt_cb())
  1339. return AVERROR(EINTR);
  1340. if (wait_end && wait_end - av_gettime() < 0)
  1341. return AVERROR(EAGAIN);
  1342. FD_ZERO(&rfds);
  1343. if (rt->rtsp_hd) {
  1344. tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
  1345. FD_SET(tcp_fd, &rfds);
  1346. } else {
  1347. fd_max = 0;
  1348. tcp_fd = -1;
  1349. }
  1350. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1351. rtsp_st = rt->rtsp_streams[i];
  1352. if (rtsp_st->rtp_handle) {
  1353. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1354. fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
  1355. if (FFMAX(fd, fd_rtcp) > fd_max)
  1356. fd_max = FFMAX(fd, fd_rtcp);
  1357. FD_SET(fd, &rfds);
  1358. FD_SET(fd_rtcp, &rfds);
  1359. }
  1360. }
  1361. tv.tv_sec = 0;
  1362. tv.tv_usec = SELECT_TIMEOUT_MS * 1000;
  1363. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1364. if (n > 0) {
  1365. timeout_cnt = 0;
  1366. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1367. rtsp_st = rt->rtsp_streams[i];
  1368. if (rtsp_st->rtp_handle) {
  1369. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1370. fd_rtcp = rtp_get_rtcp_file_handle(rtsp_st->rtp_handle);
  1371. if (FD_ISSET(fd_rtcp, &rfds) || FD_ISSET(fd, &rfds)) {
  1372. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1373. if (ret > 0) {
  1374. *prtsp_st = rtsp_st;
  1375. return ret;
  1376. }
  1377. }
  1378. }
  1379. }
  1380. #if CONFIG_RTSP_DEMUXER
  1381. if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
  1382. RTSPMessageHeader reply;
  1383. ret = ff_rtsp_read_reply(s, &reply, NULL, 0);
  1384. if (ret < 0)
  1385. return ret;
  1386. /* XXX: parse message */
  1387. if (rt->state != RTSP_STATE_STREAMING)
  1388. return 0;
  1389. }
  1390. #endif
  1391. } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {
  1392. return FF_NETERROR(ETIMEDOUT);
  1393. } else if (n < 0 && errno != EINTR)
  1394. return AVERROR(errno);
  1395. }
  1396. }
  1397. int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1398. {
  1399. RTSPState *rt = s->priv_data;
  1400. int ret, len;
  1401. RTSPStream *rtsp_st, *first_queue_st = NULL;
  1402. int64_t wait_end = 0;
  1403. if (rt->nb_byes == rt->nb_rtsp_streams)
  1404. return AVERROR_EOF;
  1405. /* get next frames from the same RTP packet */
  1406. if (rt->cur_transport_priv) {
  1407. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1408. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1409. } else
  1410. ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1411. if (ret == 0) {
  1412. rt->cur_transport_priv = NULL;
  1413. return 0;
  1414. } else if (ret == 1) {
  1415. return 0;
  1416. } else
  1417. rt->cur_transport_priv = NULL;
  1418. }
  1419. if (rt->transport == RTSP_TRANSPORT_RTP) {
  1420. int i;
  1421. int64_t first_queue_time = 0;
  1422. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1423. RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;
  1424. int64_t queue_time;
  1425. if (!rtpctx)
  1426. continue;
  1427. queue_time = ff_rtp_queued_packet_time(rtpctx);
  1428. if (queue_time && (queue_time - first_queue_time < 0 ||
  1429. !first_queue_time)) {
  1430. first_queue_time = queue_time;
  1431. first_queue_st = rt->rtsp_streams[i];
  1432. }
  1433. }
  1434. if (first_queue_time)
  1435. wait_end = first_queue_time + s->max_delay;
  1436. }
  1437. /* read next RTP packet */
  1438. redo:
  1439. if (!rt->recvbuf) {
  1440. rt->recvbuf = av_malloc(RECVBUF_SIZE);
  1441. if (!rt->recvbuf)
  1442. return AVERROR(ENOMEM);
  1443. }
  1444. switch(rt->lower_transport) {
  1445. default:
  1446. #if CONFIG_RTSP_DEMUXER
  1447. case RTSP_LOWER_TRANSPORT_TCP:
  1448. len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);
  1449. break;
  1450. #endif
  1451. case RTSP_LOWER_TRANSPORT_UDP:
  1452. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1453. len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);
  1454. if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1455. rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1456. break;
  1457. }
  1458. if (len == AVERROR(EAGAIN) && first_queue_st &&
  1459. rt->transport == RTSP_TRANSPORT_RTP) {
  1460. rtsp_st = first_queue_st;
  1461. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);
  1462. goto end;
  1463. }
  1464. if (len < 0)
  1465. return len;
  1466. if (len == 0)
  1467. return AVERROR_EOF;
  1468. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1469. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1470. } else {
  1471. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);
  1472. if (ret < 0) {
  1473. /* Either bad packet, or a RTCP packet. Check if the
  1474. * first_rtcp_ntp_time field was initialized. */
  1475. RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
  1476. if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {
  1477. /* first_rtcp_ntp_time has been initialized for this stream,
  1478. * copy the same value to all other uninitialized streams,
  1479. * in order to map their timestamp origin to the same ntp time
  1480. * as this one. */
  1481. int i;
  1482. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1483. RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;
  1484. if (rtpctx2 &&
  1485. rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE)
  1486. rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;
  1487. }
  1488. }
  1489. if (ret == -RTCP_BYE) {
  1490. rt->nb_byes++;
  1491. av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",
  1492. rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);
  1493. if (rt->nb_byes == rt->nb_rtsp_streams)
  1494. return AVERROR_EOF;
  1495. }
  1496. }
  1497. }
  1498. end:
  1499. if (ret < 0)
  1500. goto redo;
  1501. if (ret == 1)
  1502. /* more packets may follow, so we save the RTP context */
  1503. rt->cur_transport_priv = rtsp_st->transport_priv;
  1504. return ret;
  1505. }
  1506. #endif /* CONFIG_RTPDEC */
  1507. #if CONFIG_SDP_DEMUXER
  1508. static int sdp_probe(AVProbeData *p1)
  1509. {
  1510. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1511. /* we look for a line beginning "c=IN IP" */
  1512. while (p < p_end && *p != '\0') {
  1513. if (p + sizeof("c=IN IP") - 1 < p_end &&
  1514. av_strstart(p, "c=IN IP", NULL))
  1515. return AVPROBE_SCORE_MAX / 2;
  1516. while (p < p_end - 1 && *p != '\n') p++;
  1517. if (++p >= p_end)
  1518. break;
  1519. if (*p == '\r')
  1520. p++;
  1521. }
  1522. return 0;
  1523. }
  1524. static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1525. {
  1526. RTSPState *rt = s->priv_data;
  1527. RTSPStream *rtsp_st;
  1528. int size, i, err;
  1529. char *content;
  1530. char url[1024];
  1531. if (!ff_network_init())
  1532. return AVERROR(EIO);
  1533. /* read the whole sdp file */
  1534. /* XXX: better loading */
  1535. content = av_malloc(SDP_MAX_SIZE);
  1536. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1537. if (size <= 0) {
  1538. av_free(content);
  1539. return AVERROR_INVALIDDATA;
  1540. }
  1541. content[size] ='\0';
  1542. ff_sdp_parse(s, content);
  1543. av_free(content);
  1544. /* open each RTP stream */
  1545. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1546. char namebuf[50];
  1547. rtsp_st = rt->rtsp_streams[i];
  1548. getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),
  1549. namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);
  1550. ff_url_join(url, sizeof(url), "rtp", NULL,
  1551. namebuf, rtsp_st->sdp_port,
  1552. "?localport=%d&ttl=%d", rtsp_st->sdp_port,
  1553. rtsp_st->sdp_ttl);
  1554. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1555. err = AVERROR_INVALIDDATA;
  1556. goto fail;
  1557. }
  1558. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1559. goto fail;
  1560. }
  1561. return 0;
  1562. fail:
  1563. ff_rtsp_close_streams(s);
  1564. ff_network_close();
  1565. return err;
  1566. }
  1567. static int sdp_read_close(AVFormatContext *s)
  1568. {
  1569. ff_rtsp_close_streams(s);
  1570. ff_network_close();
  1571. return 0;
  1572. }
  1573. AVInputFormat sdp_demuxer = {
  1574. "sdp",
  1575. NULL_IF_CONFIG_SMALL("SDP"),
  1576. sizeof(RTSPState),
  1577. sdp_probe,
  1578. sdp_read_header,
  1579. ff_rtsp_fetch_packet,
  1580. sdp_read_close,
  1581. };
  1582. #endif /* CONFIG_SDP_DEMUXER */
  1583. #if CONFIG_RTP_DEMUXER
  1584. static int rtp_probe(AVProbeData *p)
  1585. {
  1586. if (av_strstart(p->filename, "rtp:", NULL))
  1587. return AVPROBE_SCORE_MAX;
  1588. return 0;
  1589. }
  1590. static int rtp_read_header(AVFormatContext *s,
  1591. AVFormatParameters *ap)
  1592. {
  1593. uint8_t recvbuf[1500];
  1594. char host[500], sdp[500];
  1595. int ret, port;
  1596. URLContext* in = NULL;
  1597. int payload_type;
  1598. AVCodecContext codec;
  1599. struct sockaddr_storage addr;
  1600. ByteIOContext pb;
  1601. socklen_t addrlen = sizeof(addr);
  1602. if (!ff_network_init())
  1603. return AVERROR(EIO);
  1604. ret = url_open(&in, s->filename, URL_RDONLY);
  1605. if (ret)
  1606. goto fail;
  1607. while (1) {
  1608. ret = url_read(in, recvbuf, sizeof(recvbuf));
  1609. if (ret == AVERROR(EAGAIN))
  1610. continue;
  1611. if (ret < 0)
  1612. goto fail;
  1613. if (ret < 12) {
  1614. av_log(s, AV_LOG_WARNING, "Received too short packet\n");
  1615. continue;
  1616. }
  1617. if ((recvbuf[0] & 0xc0) != 0x80) {
  1618. av_log(s, AV_LOG_WARNING, "Unsupported RTP version packet "
  1619. "received\n");
  1620. continue;
  1621. }
  1622. payload_type = recvbuf[1] & 0x7f;
  1623. break;
  1624. }
  1625. getsockname(url_get_file_handle(in), (struct sockaddr*) &addr, &addrlen);
  1626. url_close(in);
  1627. in = NULL;
  1628. memset(&codec, 0, sizeof(codec));
  1629. if (ff_rtp_get_codec_info(&codec, payload_type)) {
  1630. av_log(s, AV_LOG_ERROR, "Unable to receive RTP payload type %d "
  1631. "without an SDP file describing it\n",
  1632. payload_type);
  1633. goto fail;
  1634. }
  1635. if (codec.codec_type != AVMEDIA_TYPE_DATA) {
  1636. av_log(s, AV_LOG_WARNING, "Guessing on RTP content - if not received "
  1637. "properly you need an SDP file "
  1638. "describing it\n");
  1639. }
  1640. av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port,
  1641. NULL, 0, s->filename);
  1642. snprintf(sdp, sizeof(sdp),
  1643. "v=0\r\nc=IN IP%d %s\r\nm=%s %d RTP/AVP %d\r\n",
  1644. addr.ss_family == AF_INET ? 4 : 6, host,
  1645. codec.codec_type == AVMEDIA_TYPE_DATA ? "application" :
  1646. codec.codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio",
  1647. port, payload_type);
  1648. av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);
  1649. init_put_byte(&pb, sdp, strlen(sdp), 0, NULL, NULL, NULL, NULL);
  1650. s->pb = &pb;
  1651. /* sdp_read_header initializes this again */
  1652. ff_network_close();
  1653. ret = sdp_read_header(s, ap);
  1654. s->pb = NULL;
  1655. return ret;
  1656. fail:
  1657. if (in)
  1658. url_close(in);
  1659. ff_network_close();
  1660. return ret;
  1661. }
  1662. AVInputFormat rtp_demuxer = {
  1663. "rtp",
  1664. NULL_IF_CONFIG_SMALL("RTP input format"),
  1665. sizeof(RTSPState),
  1666. rtp_probe,
  1667. rtp_read_header,
  1668. ff_rtsp_fetch_packet,
  1669. sdp_read_close,
  1670. .flags = AVFMT_NOFILE,
  1671. };
  1672. #endif /* CONFIG_RTP_DEMUXER */