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.

1992 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 "avformat.h"
  25. #include <sys/time.h>
  26. #if HAVE_SYS_SELECT_H
  27. #include <sys/select.h>
  28. #endif
  29. #include <strings.h>
  30. #include "network.h"
  31. #include "rtsp.h"
  32. #include "rtpdec.h"
  33. #include "rdt.h"
  34. #include "rtpdec_asf.h"
  35. #include "rtpdec_vorbis.h"
  36. //#define DEBUG
  37. //#define DEBUG_RTP_TCP
  38. #if LIBAVFORMAT_VERSION_INT < (53 << 16)
  39. int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
  40. #endif
  41. #define SPACE_CHARS " \t\r\n"
  42. /* we use memchr() instead of strchr() here because strchr() will return
  43. * the terminating '\0' of SPACE_CHARS instead of NULL if c is '\0'. */
  44. #define redir_isspace(c) memchr(SPACE_CHARS, c, 4)
  45. static void skip_spaces(const char **pp)
  46. {
  47. const char *p;
  48. p = *pp;
  49. while (redir_isspace(*p))
  50. p++;
  51. *pp = p;
  52. }
  53. static void get_word_until_chars(char *buf, int buf_size,
  54. const char *sep, const char **pp)
  55. {
  56. const char *p;
  57. char *q;
  58. p = *pp;
  59. skip_spaces(&p);
  60. q = buf;
  61. while (!strchr(sep, *p) && *p != '\0') {
  62. if ((q - buf) < buf_size - 1)
  63. *q++ = *p;
  64. p++;
  65. }
  66. if (buf_size > 0)
  67. *q = '\0';
  68. *pp = p;
  69. }
  70. static void get_word_sep(char *buf, int buf_size, const char *sep,
  71. const char **pp)
  72. {
  73. if (**pp == '/') (*pp)++;
  74. get_word_until_chars(buf, buf_size, sep, pp);
  75. }
  76. static void get_word(char *buf, int buf_size, const char **pp)
  77. {
  78. get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
  79. }
  80. /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other params>] */
  81. static int sdp_parse_rtpmap(AVFormatContext *s,
  82. AVCodecContext *codec, RTSPStream *rtsp_st,
  83. int payload_type, const char *p)
  84. {
  85. char buf[256];
  86. int i;
  87. AVCodec *c;
  88. const char *c_name;
  89. /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and
  90. * see if we can handle this kind of payload.
  91. * The space should normally not be there but some Real streams or
  92. * particular servers ("RealServer Version 6.1.3.970", see issue 1658)
  93. * have a trailing space. */
  94. get_word_sep(buf, sizeof(buf), "/ ", &p);
  95. if (payload_type >= RTP_PT_PRIVATE) {
  96. RTPDynamicProtocolHandler *handler;
  97. for (handler = RTPFirstDynamicPayloadHandler;
  98. handler; handler = handler->next) {
  99. if (!strcasecmp(buf, handler->enc_name) &&
  100. codec->codec_type == handler->codec_type) {
  101. codec->codec_id = handler->codec_id;
  102. rtsp_st->dynamic_handler = handler;
  103. if (handler->open)
  104. rtsp_st->dynamic_protocol_context = handler->open();
  105. break;
  106. }
  107. }
  108. } else {
  109. /* We are in a standard case
  110. * (from http://www.iana.org/assignments/rtp-parameters). */
  111. /* search into AVRtpPayloadTypes[] */
  112. codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);
  113. }
  114. c = avcodec_find_decoder(codec->codec_id);
  115. if (c && c->name)
  116. c_name = c->name;
  117. else
  118. c_name = "(null)";
  119. get_word_sep(buf, sizeof(buf), "/", &p);
  120. i = atoi(buf);
  121. switch (codec->codec_type) {
  122. case CODEC_TYPE_AUDIO:
  123. av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);
  124. codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;
  125. codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;
  126. if (i > 0) {
  127. codec->sample_rate = i;
  128. get_word_sep(buf, sizeof(buf), "/", &p);
  129. i = atoi(buf);
  130. if (i > 0)
  131. codec->channels = i;
  132. // TODO: there is a bug here; if it is a mono stream, and
  133. // less than 22000Hz, faad upconverts to stereo and twice
  134. // the frequency. No problem, but the sample rate is being
  135. // set here by the sdp line. Patch on its way. (rdm)
  136. }
  137. av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",
  138. codec->sample_rate);
  139. av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",
  140. codec->channels);
  141. break;
  142. case CODEC_TYPE_VIDEO:
  143. av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
  144. break;
  145. default:
  146. break;
  147. }
  148. return 0;
  149. }
  150. /* return the length and optionally the data */
  151. static int hex_to_data(uint8_t *data, const char *p)
  152. {
  153. int c, len, v;
  154. len = 0;
  155. v = 1;
  156. for (;;) {
  157. skip_spaces(&p);
  158. if (*p == '\0')
  159. break;
  160. c = toupper((unsigned char) *p++);
  161. if (c >= '0' && c <= '9')
  162. c = c - '0';
  163. else if (c >= 'A' && c <= 'F')
  164. c = c - 'A' + 10;
  165. else
  166. break;
  167. v = (v << 4) | c;
  168. if (v & 0x100) {
  169. if (data)
  170. data[len] = v;
  171. len++;
  172. v = 1;
  173. }
  174. }
  175. return len;
  176. }
  177. static void sdp_parse_fmtp_config(AVCodecContext * codec, void *ctx,
  178. char *attr, char *value)
  179. {
  180. switch (codec->codec_id) {
  181. case CODEC_ID_MPEG4:
  182. case CODEC_ID_AAC:
  183. if (!strcmp(attr, "config")) {
  184. /* decode the hexa encoded parameter */
  185. int len = hex_to_data(NULL, value);
  186. if (codec->extradata)
  187. av_free(codec->extradata);
  188. codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
  189. if (!codec->extradata)
  190. return;
  191. codec->extradata_size = len;
  192. hex_to_data(codec->extradata, value);
  193. }
  194. break;
  195. case CODEC_ID_VORBIS:
  196. ff_vorbis_parse_fmtp_config(codec, ctx, attr, value);
  197. break;
  198. default:
  199. break;
  200. }
  201. return;
  202. }
  203. typedef struct {
  204. const char *str;
  205. uint16_t type;
  206. uint32_t offset;
  207. } AttrNameMap;
  208. /* All known fmtp parmeters and the corresping RTPAttrTypeEnum */
  209. #define ATTR_NAME_TYPE_INT 0
  210. #define ATTR_NAME_TYPE_STR 1
  211. static const AttrNameMap attr_names[]=
  212. {
  213. { "SizeLength", ATTR_NAME_TYPE_INT,
  214. offsetof(RTPPayloadData, sizelength) },
  215. { "IndexLength", ATTR_NAME_TYPE_INT,
  216. offsetof(RTPPayloadData, indexlength) },
  217. { "IndexDeltaLength", ATTR_NAME_TYPE_INT,
  218. offsetof(RTPPayloadData, indexdeltalength) },
  219. { "profile-level-id", ATTR_NAME_TYPE_INT,
  220. offsetof(RTPPayloadData, profile_level_id) },
  221. { "StreamType", ATTR_NAME_TYPE_INT,
  222. offsetof(RTPPayloadData, streamtype) },
  223. { "mode", ATTR_NAME_TYPE_STR,
  224. offsetof(RTPPayloadData, mode) },
  225. { NULL, -1, -1 },
  226. };
  227. /* parse the attribute line from the fmtp a line of an sdp resonse. This
  228. * is broken out as a function because it is used in rtp_h264.c, which is
  229. * forthcoming. */
  230. int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size,
  231. char *value, int value_size)
  232. {
  233. skip_spaces(p);
  234. if (**p) {
  235. get_word_sep(attr, attr_size, "=", p);
  236. if (**p == '=')
  237. (*p)++;
  238. get_word_sep(value, value_size, ";", p);
  239. if (**p == ';')
  240. (*p)++;
  241. return 1;
  242. }
  243. return 0;
  244. }
  245. /* parse a SDP line and save stream attributes */
  246. static void sdp_parse_fmtp(AVStream *st, const char *p)
  247. {
  248. char attr[256];
  249. /* Vorbis setup headers can be up to 12KB and are sent base64
  250. * encoded, giving a 12KB * (4/3) = 16KB FMTP line. */
  251. char value[16384];
  252. int i;
  253. RTSPStream *rtsp_st = st->priv_data;
  254. AVCodecContext *codec = st->codec;
  255. RTPPayloadData *rtp_payload_data = &rtsp_st->rtp_payload_data;
  256. /* loop on each attribute */
  257. while (ff_rtsp_next_attr_and_value(&p, attr, sizeof(attr),
  258. value, sizeof(value))) {
  259. /* grab the codec extra_data from the config parameter of the fmtp
  260. * line */
  261. sdp_parse_fmtp_config(codec, rtsp_st->dynamic_protocol_context,
  262. attr, value);
  263. /* Looking for a known attribute */
  264. for (i = 0; attr_names[i].str; ++i) {
  265. if (!strcasecmp(attr, attr_names[i].str)) {
  266. if (attr_names[i].type == ATTR_NAME_TYPE_INT) {
  267. *(int *)((char *)rtp_payload_data +
  268. attr_names[i].offset) = atoi(value);
  269. } else if (attr_names[i].type == ATTR_NAME_TYPE_STR)
  270. *(char **)((char *)rtp_payload_data +
  271. attr_names[i].offset) = av_strdup(value);
  272. }
  273. }
  274. }
  275. }
  276. /** Parse a string p in the form of Range:npt=xx-xx, and determine the start
  277. * and end time.
  278. * Used for seeking in the rtp stream.
  279. */
  280. static void rtsp_parse_range_npt(const char *p, int64_t *start, int64_t *end)
  281. {
  282. char buf[256];
  283. skip_spaces(&p);
  284. if (!av_stristart(p, "npt=", &p))
  285. return;
  286. *start = AV_NOPTS_VALUE;
  287. *end = AV_NOPTS_VALUE;
  288. get_word_sep(buf, sizeof(buf), "-", &p);
  289. *start = parse_date(buf, 1);
  290. if (*p == '-') {
  291. p++;
  292. get_word_sep(buf, sizeof(buf), "-", &p);
  293. *end = parse_date(buf, 1);
  294. }
  295. // av_log(NULL, AV_LOG_DEBUG, "Range Start: %lld\n", *start);
  296. // av_log(NULL, AV_LOG_DEBUG, "Range End: %lld\n", *end);
  297. }
  298. typedef struct SDPParseState {
  299. /* SDP only */
  300. struct in_addr default_ip;
  301. int default_ttl;
  302. int skip_media; ///< set if an unknown m= line occurs
  303. } SDPParseState;
  304. static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,
  305. int letter, const char *buf)
  306. {
  307. RTSPState *rt = s->priv_data;
  308. char buf1[64], st_type[64];
  309. const char *p;
  310. enum CodecType codec_type;
  311. int payload_type, i;
  312. AVStream *st;
  313. RTSPStream *rtsp_st;
  314. struct in_addr sdp_ip;
  315. int ttl;
  316. dprintf(s, "sdp: %c='%s'\n", letter, buf);
  317. p = buf;
  318. if (s1->skip_media && letter != 'm')
  319. return;
  320. switch (letter) {
  321. case 'c':
  322. get_word(buf1, sizeof(buf1), &p);
  323. if (strcmp(buf1, "IN") != 0)
  324. return;
  325. get_word(buf1, sizeof(buf1), &p);
  326. if (strcmp(buf1, "IP4") != 0)
  327. return;
  328. get_word_sep(buf1, sizeof(buf1), "/", &p);
  329. if (ff_inet_aton(buf1, &sdp_ip) == 0)
  330. return;
  331. ttl = 16;
  332. if (*p == '/') {
  333. p++;
  334. get_word_sep(buf1, sizeof(buf1), "/", &p);
  335. ttl = atoi(buf1);
  336. }
  337. if (s->nb_streams == 0) {
  338. s1->default_ip = sdp_ip;
  339. s1->default_ttl = ttl;
  340. } else {
  341. st = s->streams[s->nb_streams - 1];
  342. rtsp_st = st->priv_data;
  343. rtsp_st->sdp_ip = sdp_ip;
  344. rtsp_st->sdp_ttl = ttl;
  345. }
  346. break;
  347. case 's':
  348. av_metadata_set(&s->metadata, "title", p);
  349. break;
  350. case 'i':
  351. if (s->nb_streams == 0) {
  352. av_metadata_set(&s->metadata, "comment", p);
  353. break;
  354. }
  355. break;
  356. case 'm':
  357. /* new stream */
  358. s1->skip_media = 0;
  359. get_word(st_type, sizeof(st_type), &p);
  360. if (!strcmp(st_type, "audio")) {
  361. codec_type = CODEC_TYPE_AUDIO;
  362. } else if (!strcmp(st_type, "video")) {
  363. codec_type = CODEC_TYPE_VIDEO;
  364. } else if (!strcmp(st_type, "application")) {
  365. codec_type = CODEC_TYPE_DATA;
  366. } else {
  367. s1->skip_media = 1;
  368. return;
  369. }
  370. rtsp_st = av_mallocz(sizeof(RTSPStream));
  371. if (!rtsp_st)
  372. return;
  373. rtsp_st->stream_index = -1;
  374. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  375. rtsp_st->sdp_ip = s1->default_ip;
  376. rtsp_st->sdp_ttl = s1->default_ttl;
  377. get_word(buf1, sizeof(buf1), &p); /* port */
  378. rtsp_st->sdp_port = atoi(buf1);
  379. get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
  380. /* XXX: handle list of formats */
  381. get_word(buf1, sizeof(buf1), &p); /* format list */
  382. rtsp_st->sdp_payload_type = atoi(buf1);
  383. if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
  384. /* no corresponding stream */
  385. } else {
  386. st = av_new_stream(s, 0);
  387. if (!st)
  388. return;
  389. st->priv_data = rtsp_st;
  390. rtsp_st->stream_index = st->index;
  391. st->codec->codec_type = codec_type;
  392. if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
  393. /* if standard payload type, we can find the codec right now */
  394. ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
  395. }
  396. }
  397. /* put a default control url */
  398. av_strlcpy(rtsp_st->control_url, rt->control_uri,
  399. sizeof(rtsp_st->control_url));
  400. break;
  401. case 'a':
  402. if (av_strstart(p, "control:", &p)) {
  403. if (s->nb_streams == 0) {
  404. if (!strncmp(p, "rtsp://", 7))
  405. av_strlcpy(rt->control_uri, p,
  406. sizeof(rt->control_uri));
  407. } else {
  408. char proto[32];
  409. /* get the control url */
  410. st = s->streams[s->nb_streams - 1];
  411. rtsp_st = st->priv_data;
  412. /* XXX: may need to add full url resolution */
  413. ff_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,
  414. NULL, NULL, 0, p);
  415. if (proto[0] == '\0') {
  416. /* relative control URL */
  417. if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')
  418. av_strlcat(rtsp_st->control_url, "/",
  419. sizeof(rtsp_st->control_url));
  420. av_strlcat(rtsp_st->control_url, p,
  421. sizeof(rtsp_st->control_url));
  422. } else
  423. av_strlcpy(rtsp_st->control_url, p,
  424. sizeof(rtsp_st->control_url));
  425. }
  426. } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
  427. /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
  428. get_word(buf1, sizeof(buf1), &p);
  429. payload_type = atoi(buf1);
  430. st = s->streams[s->nb_streams - 1];
  431. rtsp_st = st->priv_data;
  432. sdp_parse_rtpmap(s, st->codec, rtsp_st, payload_type, p);
  433. } else if (av_strstart(p, "fmtp:", &p)) {
  434. /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
  435. get_word(buf1, sizeof(buf1), &p);
  436. payload_type = atoi(buf1);
  437. for (i = 0; i < s->nb_streams; i++) {
  438. st = s->streams[i];
  439. rtsp_st = st->priv_data;
  440. if (rtsp_st->sdp_payload_type == payload_type) {
  441. if (!(rtsp_st->dynamic_handler &&
  442. rtsp_st->dynamic_handler->parse_sdp_a_line &&
  443. rtsp_st->dynamic_handler->parse_sdp_a_line(s,
  444. i, rtsp_st->dynamic_protocol_context, buf)))
  445. sdp_parse_fmtp(st, p);
  446. }
  447. }
  448. } else if (av_strstart(p, "framesize:", &p)) {
  449. // let dynamic protocol handlers have a stab at the line.
  450. get_word(buf1, sizeof(buf1), &p);
  451. payload_type = atoi(buf1);
  452. for (i = 0; i < s->nb_streams; i++) {
  453. st = s->streams[i];
  454. rtsp_st = st->priv_data;
  455. if (rtsp_st->sdp_payload_type == payload_type &&
  456. rtsp_st->dynamic_handler &&
  457. rtsp_st->dynamic_handler->parse_sdp_a_line)
  458. rtsp_st->dynamic_handler->parse_sdp_a_line(s, i,
  459. rtsp_st->dynamic_protocol_context, buf);
  460. }
  461. } else if (av_strstart(p, "range:", &p)) {
  462. int64_t start, end;
  463. // this is so that seeking on a streamed file can work.
  464. rtsp_parse_range_npt(p, &start, &end);
  465. s->start_time = start;
  466. /* AV_NOPTS_VALUE means live broadcast (and can't seek) */
  467. s->duration = (end == AV_NOPTS_VALUE) ?
  468. AV_NOPTS_VALUE : end - start;
  469. } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
  470. if (atoi(p) == 1)
  471. rt->transport = RTSP_TRANSPORT_RDT;
  472. } else {
  473. if (rt->server_type == RTSP_SERVER_WMS)
  474. ff_wms_parse_sdp_a_line(s, p);
  475. if (s->nb_streams > 0) {
  476. if (rt->server_type == RTSP_SERVER_REAL)
  477. ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
  478. rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
  479. if (rtsp_st->dynamic_handler &&
  480. rtsp_st->dynamic_handler->parse_sdp_a_line)
  481. rtsp_st->dynamic_handler->parse_sdp_a_line(s,
  482. s->nb_streams - 1,
  483. rtsp_st->dynamic_protocol_context, buf);
  484. }
  485. }
  486. break;
  487. }
  488. }
  489. static int sdp_parse(AVFormatContext *s, const char *content)
  490. {
  491. const char *p;
  492. int letter;
  493. /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
  494. * contain long SDP lines containing complete ASF Headers (several
  495. * kB) or arrays of MDPR (RM stream descriptor) headers plus
  496. * "rulebooks" describing their properties. Therefore, the SDP line
  497. * buffer is large.
  498. *
  499. * The Vorbis FMTP line can be up to 16KB - see sdp_parse_fmtp. */
  500. char buf[16384], *q;
  501. SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
  502. memset(s1, 0, sizeof(SDPParseState));
  503. p = content;
  504. for (;;) {
  505. skip_spaces(&p);
  506. letter = *p;
  507. if (letter == '\0')
  508. break;
  509. p++;
  510. if (*p != '=')
  511. goto next_line;
  512. p++;
  513. /* get the content */
  514. q = buf;
  515. while (*p != '\n' && *p != '\r' && *p != '\0') {
  516. if ((q - buf) < sizeof(buf) - 1)
  517. *q++ = *p;
  518. p++;
  519. }
  520. *q = '\0';
  521. sdp_parse_line(s, s1, letter, buf);
  522. next_line:
  523. while (*p != '\n' && *p != '\0')
  524. p++;
  525. if (*p == '\n')
  526. p++;
  527. }
  528. return 0;
  529. }
  530. /* close and free RTSP streams */
  531. void ff_rtsp_close_streams(AVFormatContext *s)
  532. {
  533. RTSPState *rt = s->priv_data;
  534. int i;
  535. RTSPStream *rtsp_st;
  536. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  537. rtsp_st = rt->rtsp_streams[i];
  538. if (rtsp_st) {
  539. if (rtsp_st->transport_priv) {
  540. if (s->oformat) {
  541. AVFormatContext *rtpctx = rtsp_st->transport_priv;
  542. av_write_trailer(rtpctx);
  543. url_fclose(rtpctx->pb);
  544. av_metadata_free(&rtpctx->streams[0]->metadata);
  545. av_metadata_free(&rtpctx->metadata);
  546. av_free(rtpctx->streams[0]);
  547. av_free(rtpctx);
  548. } else if (rt->transport == RTSP_TRANSPORT_RDT)
  549. ff_rdt_parse_close(rtsp_st->transport_priv);
  550. else
  551. rtp_parse_close(rtsp_st->transport_priv);
  552. }
  553. if (rtsp_st->rtp_handle)
  554. url_close(rtsp_st->rtp_handle);
  555. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  556. rtsp_st->dynamic_handler->close(
  557. rtsp_st->dynamic_protocol_context);
  558. }
  559. }
  560. av_free(rt->rtsp_streams);
  561. if (rt->asf_ctx) {
  562. av_close_input_stream (rt->asf_ctx);
  563. rt->asf_ctx = NULL;
  564. }
  565. av_freep(&rt->auth_b64);
  566. }
  567. static void *rtsp_rtp_mux_open(AVFormatContext *s, AVStream *st, URLContext *handle) {
  568. AVFormatContext *rtpctx;
  569. int ret;
  570. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  571. if (!rtp_format)
  572. return NULL;
  573. /* Allocate an AVFormatContext for each output stream */
  574. rtpctx = avformat_alloc_context();
  575. if (!rtpctx)
  576. return NULL;
  577. rtpctx->oformat = rtp_format;
  578. if (!av_new_stream(rtpctx, 0)) {
  579. av_free(rtpctx);
  580. return NULL;
  581. }
  582. /* Copy the max delay setting; the rtp muxer reads this. */
  583. rtpctx->max_delay = s->max_delay;
  584. /* Copy other stream parameters. */
  585. rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;
  586. /* Remove the local codec, link to the original codec
  587. * context instead, to give the rtp muxer access to
  588. * codec parameters. */
  589. av_free(rtpctx->streams[0]->codec);
  590. rtpctx->streams[0]->codec = st->codec;
  591. url_fdopen(&rtpctx->pb, handle);
  592. ret = av_write_header(rtpctx);
  593. if (ret) {
  594. url_fclose(rtpctx->pb);
  595. av_free(rtpctx->streams[0]);
  596. av_free(rtpctx);
  597. return NULL;
  598. }
  599. /* Copy the RTP AVStream timebase back to the original AVStream */
  600. st->time_base = rtpctx->streams[0]->time_base;
  601. return rtpctx;
  602. }
  603. static int rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  604. {
  605. RTSPState *rt = s->priv_data;
  606. AVStream *st = NULL;
  607. /* open the RTP context */
  608. if (rtsp_st->stream_index >= 0)
  609. st = s->streams[rtsp_st->stream_index];
  610. if (!st)
  611. s->ctx_flags |= AVFMTCTX_NOHEADER;
  612. if (s->oformat) {
  613. rtsp_st->transport_priv = rtsp_rtp_mux_open(s, st, rtsp_st->rtp_handle);
  614. /* Ownage of rtp_handle is passed to the rtp mux context */
  615. rtsp_st->rtp_handle = NULL;
  616. } else if (rt->transport == RTSP_TRANSPORT_RDT)
  617. rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,
  618. rtsp_st->dynamic_protocol_context,
  619. rtsp_st->dynamic_handler);
  620. else
  621. rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,
  622. rtsp_st->sdp_payload_type,
  623. &rtsp_st->rtp_payload_data);
  624. if (!rtsp_st->transport_priv) {
  625. return AVERROR(ENOMEM);
  626. } else if (rt->transport != RTSP_TRANSPORT_RDT) {
  627. if (rtsp_st->dynamic_handler) {
  628. rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,
  629. rtsp_st->dynamic_protocol_context,
  630. rtsp_st->dynamic_handler);
  631. }
  632. }
  633. return 0;
  634. }
  635. #if CONFIG_RTSP_DEMUXER || CONFIG_RTSP_MUXER
  636. static int rtsp_probe(AVProbeData *p)
  637. {
  638. if (av_strstart(p->filename, "rtsp:", NULL))
  639. return AVPROBE_SCORE_MAX;
  640. return 0;
  641. }
  642. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  643. {
  644. const char *p;
  645. int v;
  646. p = *pp;
  647. skip_spaces(&p);
  648. v = strtol(p, (char **)&p, 10);
  649. if (*p == '-') {
  650. p++;
  651. *min_ptr = v;
  652. v = strtol(p, (char **)&p, 10);
  653. *max_ptr = v;
  654. } else {
  655. *min_ptr = v;
  656. *max_ptr = v;
  657. }
  658. *pp = p;
  659. }
  660. /* XXX: only one transport specification is parsed */
  661. static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)
  662. {
  663. char transport_protocol[16];
  664. char profile[16];
  665. char lower_transport[16];
  666. char parameter[16];
  667. RTSPTransportField *th;
  668. char buf[256];
  669. reply->nb_transports = 0;
  670. for (;;) {
  671. skip_spaces(&p);
  672. if (*p == '\0')
  673. break;
  674. th = &reply->transports[reply->nb_transports];
  675. get_word_sep(transport_protocol, sizeof(transport_protocol),
  676. "/", &p);
  677. if (!strcasecmp (transport_protocol, "rtp")) {
  678. get_word_sep(profile, sizeof(profile), "/;,", &p);
  679. lower_transport[0] = '\0';
  680. /* rtp/avp/<protocol> */
  681. if (*p == '/') {
  682. get_word_sep(lower_transport, sizeof(lower_transport),
  683. ";,", &p);
  684. }
  685. th->transport = RTSP_TRANSPORT_RTP;
  686. } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
  687. !strcasecmp (transport_protocol, "x-real-rdt")) {
  688. /* x-pn-tng/<protocol> */
  689. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  690. profile[0] = '\0';
  691. th->transport = RTSP_TRANSPORT_RDT;
  692. }
  693. if (!strcasecmp(lower_transport, "TCP"))
  694. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  695. else
  696. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  697. if (*p == ';')
  698. p++;
  699. /* get each parameter */
  700. while (*p != '\0' && *p != ',') {
  701. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  702. if (!strcmp(parameter, "port")) {
  703. if (*p == '=') {
  704. p++;
  705. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  706. }
  707. } else if (!strcmp(parameter, "client_port")) {
  708. if (*p == '=') {
  709. p++;
  710. rtsp_parse_range(&th->client_port_min,
  711. &th->client_port_max, &p);
  712. }
  713. } else if (!strcmp(parameter, "server_port")) {
  714. if (*p == '=') {
  715. p++;
  716. rtsp_parse_range(&th->server_port_min,
  717. &th->server_port_max, &p);
  718. }
  719. } else if (!strcmp(parameter, "interleaved")) {
  720. if (*p == '=') {
  721. p++;
  722. rtsp_parse_range(&th->interleaved_min,
  723. &th->interleaved_max, &p);
  724. }
  725. } else if (!strcmp(parameter, "multicast")) {
  726. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  727. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  728. } else if (!strcmp(parameter, "ttl")) {
  729. if (*p == '=') {
  730. p++;
  731. th->ttl = strtol(p, (char **)&p, 10);
  732. }
  733. } else if (!strcmp(parameter, "destination")) {
  734. struct in_addr ipaddr;
  735. if (*p == '=') {
  736. p++;
  737. get_word_sep(buf, sizeof(buf), ";,", &p);
  738. if (ff_inet_aton(buf, &ipaddr))
  739. th->destination = ntohl(ipaddr.s_addr);
  740. }
  741. }
  742. while (*p != ';' && *p != '\0' && *p != ',')
  743. p++;
  744. if (*p == ';')
  745. p++;
  746. }
  747. if (*p == ',')
  748. p++;
  749. reply->nb_transports++;
  750. }
  751. }
  752. void ff_rtsp_parse_line(RTSPMessageHeader *reply, const char *buf)
  753. {
  754. const char *p;
  755. /* NOTE: we do case independent match for broken servers */
  756. p = buf;
  757. if (av_stristart(p, "Session:", &p)) {
  758. int t;
  759. get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
  760. if (av_stristart(p, ";timeout=", &p) &&
  761. (t = strtol(p, NULL, 10)) > 0) {
  762. reply->timeout = t;
  763. }
  764. } else if (av_stristart(p, "Content-Length:", &p)) {
  765. reply->content_length = strtol(p, NULL, 10);
  766. } else if (av_stristart(p, "Transport:", &p)) {
  767. rtsp_parse_transport(reply, p);
  768. } else if (av_stristart(p, "CSeq:", &p)) {
  769. reply->seq = strtol(p, NULL, 10);
  770. } else if (av_stristart(p, "Range:", &p)) {
  771. rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
  772. } else if (av_stristart(p, "RealChallenge1:", &p)) {
  773. skip_spaces(&p);
  774. av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
  775. } else if (av_stristart(p, "Server:", &p)) {
  776. skip_spaces(&p);
  777. av_strlcpy(reply->server, p, sizeof(reply->server));
  778. } else if (av_stristart(p, "Notice:", &p) ||
  779. av_stristart(p, "X-Notice:", &p)) {
  780. reply->notice = strtol(p, NULL, 10);
  781. } else if (av_stristart(p, "Location:", &p)) {
  782. skip_spaces(&p);
  783. av_strlcpy(reply->location, p , sizeof(reply->location));
  784. }
  785. }
  786. /* skip a RTP/TCP interleaved packet */
  787. static void rtsp_skip_packet(AVFormatContext *s)
  788. {
  789. RTSPState *rt = s->priv_data;
  790. int ret, len, len1;
  791. uint8_t buf[1024];
  792. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  793. if (ret != 3)
  794. return;
  795. len = AV_RB16(buf + 1);
  796. dprintf(s, "skipping RTP packet len=%d\n", len);
  797. /* skip payload */
  798. while (len > 0) {
  799. len1 = len;
  800. if (len1 > sizeof(buf))
  801. len1 = sizeof(buf);
  802. ret = url_read_complete(rt->rtsp_hd, buf, len1);
  803. if (ret != len1)
  804. return;
  805. len -= len1;
  806. }
  807. }
  808. int ff_rtsp_read_reply(AVFormatContext *s, RTSPMessageHeader *reply,
  809. unsigned char **content_ptr,
  810. int return_on_interleaved_data)
  811. {
  812. RTSPState *rt = s->priv_data;
  813. char buf[4096], buf1[1024], *q;
  814. unsigned char ch;
  815. const char *p;
  816. int ret, content_length, line_count = 0;
  817. unsigned char *content = NULL;
  818. memset(reply, 0, sizeof(*reply));
  819. /* parse reply (XXX: use buffers) */
  820. rt->last_reply[0] = '\0';
  821. for (;;) {
  822. q = buf;
  823. for (;;) {
  824. ret = url_read_complete(rt->rtsp_hd, &ch, 1);
  825. #ifdef DEBUG_RTP_TCP
  826. dprintf(s, "ret=%d c=%02x [%c]\n", ret, ch, ch);
  827. #endif
  828. if (ret != 1)
  829. return -1;
  830. if (ch == '\n')
  831. break;
  832. if (ch == '$') {
  833. /* XXX: only parse it if first char on line ? */
  834. if (return_on_interleaved_data) {
  835. return 1;
  836. } else
  837. rtsp_skip_packet(s);
  838. } else if (ch != '\r') {
  839. if ((q - buf) < sizeof(buf) - 1)
  840. *q++ = ch;
  841. }
  842. }
  843. *q = '\0';
  844. dprintf(s, "line='%s'\n", buf);
  845. /* test if last line */
  846. if (buf[0] == '\0')
  847. break;
  848. p = buf;
  849. if (line_count == 0) {
  850. /* get reply code */
  851. get_word(buf1, sizeof(buf1), &p);
  852. get_word(buf1, sizeof(buf1), &p);
  853. reply->status_code = atoi(buf1);
  854. } else {
  855. ff_rtsp_parse_line(reply, p);
  856. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  857. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  858. }
  859. line_count++;
  860. }
  861. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  862. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  863. content_length = reply->content_length;
  864. if (content_length > 0) {
  865. /* leave some room for a trailing '\0' (useful for simple parsing) */
  866. content = av_malloc(content_length + 1);
  867. (void)url_read_complete(rt->rtsp_hd, content, content_length);
  868. content[content_length] = '\0';
  869. }
  870. if (content_ptr)
  871. *content_ptr = content;
  872. else
  873. av_free(content);
  874. /* EOS */
  875. if (reply->notice == 2101 /* End-of-Stream Reached */ ||
  876. reply->notice == 2104 /* Start-of-Stream Reached */ ||
  877. reply->notice == 2306 /* Continuous Feed Terminated */) {
  878. rt->state = RTSP_STATE_IDLE;
  879. } else if (reply->notice >= 4400 && reply->notice < 5500) {
  880. return AVERROR(EIO); /* data or server error */
  881. } else if (reply->notice == 2401 /* Ticket Expired */ ||
  882. (reply->notice >= 5500 && reply->notice < 5600) /* end of term */ )
  883. return AVERROR(EPERM);
  884. return 0;
  885. }
  886. void ff_rtsp_send_cmd_with_content_async(AVFormatContext *s,
  887. const char *cmd,
  888. const unsigned char *send_content,
  889. int send_content_length)
  890. {
  891. RTSPState *rt = s->priv_data;
  892. char buf[4096], buf1[1024];
  893. rt->seq++;
  894. av_strlcpy(buf, cmd, sizeof(buf));
  895. snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
  896. av_strlcat(buf, buf1, sizeof(buf));
  897. if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
  898. snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
  899. av_strlcat(buf, buf1, sizeof(buf));
  900. }
  901. if (rt->auth_b64)
  902. av_strlcatf(buf, sizeof(buf),
  903. "Authorization: Basic %s\r\n",
  904. rt->auth_b64);
  905. if (send_content_length > 0 && send_content)
  906. av_strlcatf(buf, sizeof(buf), "Content-Length: %d\r\n", send_content_length);
  907. av_strlcat(buf, "\r\n", sizeof(buf));
  908. dprintf(s, "Sending:\n%s--\n", buf);
  909. url_write(rt->rtsp_hd, buf, strlen(buf));
  910. if (send_content_length > 0 && send_content)
  911. url_write(rt->rtsp_hd, send_content, send_content_length);
  912. rt->last_cmd_time = av_gettime();
  913. }
  914. void ff_rtsp_send_cmd_async(AVFormatContext *s, const char *cmd)
  915. {
  916. ff_rtsp_send_cmd_with_content_async(s, cmd, NULL, 0);
  917. }
  918. void ff_rtsp_send_cmd(AVFormatContext *s,
  919. const char *cmd, RTSPMessageHeader *reply,
  920. unsigned char **content_ptr)
  921. {
  922. ff_rtsp_send_cmd_async(s, cmd);
  923. ff_rtsp_read_reply(s, reply, content_ptr, 0);
  924. }
  925. void ff_rtsp_send_cmd_with_content(AVFormatContext *s,
  926. const char *cmd,
  927. RTSPMessageHeader *reply,
  928. unsigned char **content_ptr,
  929. const unsigned char *send_content,
  930. int send_content_length)
  931. {
  932. ff_rtsp_send_cmd_with_content_async(s, cmd, send_content, send_content_length);
  933. ff_rtsp_read_reply(s, reply, content_ptr, 0);
  934. }
  935. /**
  936. * @returns 0 on success, <0 on error, 1 if protocol is unavailable.
  937. */
  938. static int make_setup_request(AVFormatContext *s, const char *host, int port,
  939. int lower_transport, const char *real_challenge)
  940. {
  941. RTSPState *rt = s->priv_data;
  942. int rtx, j, i, err, interleave = 0;
  943. RTSPStream *rtsp_st;
  944. RTSPMessageHeader reply1, *reply = &reply1;
  945. char cmd[2048];
  946. const char *trans_pref;
  947. if (rt->transport == RTSP_TRANSPORT_RDT)
  948. trans_pref = "x-pn-tng";
  949. else
  950. trans_pref = "RTP/AVP";
  951. /* default timeout: 1 minute */
  952. rt->timeout = 60;
  953. /* for each stream, make the setup request */
  954. /* XXX: we assume the same server is used for the control of each
  955. * RTSP stream */
  956. for (j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  957. char transport[2048];
  958. /**
  959. * WMS serves all UDP data over a single connection, the RTX, which
  960. * isn't necessarily the first in the SDP but has to be the first
  961. * to be set up, else the second/third SETUP will fail with a 461.
  962. */
  963. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  964. rt->server_type == RTSP_SERVER_WMS) {
  965. if (i == 0) {
  966. /* rtx first */
  967. for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
  968. int len = strlen(rt->rtsp_streams[rtx]->control_url);
  969. if (len >= 4 &&
  970. !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4,
  971. "/rtx"))
  972. break;
  973. }
  974. if (rtx == rt->nb_rtsp_streams)
  975. return -1; /* no RTX found */
  976. rtsp_st = rt->rtsp_streams[rtx];
  977. } else
  978. rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
  979. } else
  980. rtsp_st = rt->rtsp_streams[i];
  981. /* RTP/UDP */
  982. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  983. char buf[256];
  984. if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
  985. port = reply->transports[0].client_port_min;
  986. goto have_port;
  987. }
  988. /* first try in specified port range */
  989. if (RTSP_RTP_PORT_MIN != 0) {
  990. while (j <= RTSP_RTP_PORT_MAX) {
  991. ff_url_join(buf, sizeof(buf), "rtp", NULL, host, -1,
  992. "?localport=%d", j);
  993. /* we will use two ports per rtp stream (rtp and rtcp) */
  994. j += 2;
  995. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0)
  996. goto rtp_opened;
  997. }
  998. }
  999. #if 0
  1000. /* then try on any port */
  1001. if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  1002. err = AVERROR_INVALIDDATA;
  1003. goto fail;
  1004. }
  1005. #endif
  1006. rtp_opened:
  1007. port = rtp_get_local_port(rtsp_st->rtp_handle);
  1008. have_port:
  1009. snprintf(transport, sizeof(transport) - 1,
  1010. "%s/UDP;", trans_pref);
  1011. if (rt->server_type != RTSP_SERVER_REAL)
  1012. av_strlcat(transport, "unicast;", sizeof(transport));
  1013. av_strlcatf(transport, sizeof(transport),
  1014. "client_port=%d", port);
  1015. if (rt->transport == RTSP_TRANSPORT_RTP &&
  1016. !(rt->server_type == RTSP_SERVER_WMS && i > 0))
  1017. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  1018. }
  1019. /* RTP/TCP */
  1020. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1021. /** For WMS streams, the application streams are only used for
  1022. * UDP. When trying to set it up for TCP streams, the server
  1023. * will return an error. Therefore, we skip those streams. */
  1024. if (rt->server_type == RTSP_SERVER_WMS &&
  1025. s->streams[rtsp_st->stream_index]->codec->codec_type ==
  1026. CODEC_TYPE_DATA)
  1027. continue;
  1028. snprintf(transport, sizeof(transport) - 1,
  1029. "%s/TCP;", trans_pref);
  1030. if (rt->server_type == RTSP_SERVER_WMS)
  1031. av_strlcat(transport, "unicast;", sizeof(transport));
  1032. av_strlcatf(transport, sizeof(transport),
  1033. "interleaved=%d-%d",
  1034. interleave, interleave + 1);
  1035. interleave += 2;
  1036. }
  1037. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  1038. snprintf(transport, sizeof(transport) - 1,
  1039. "%s/UDP;multicast", trans_pref);
  1040. }
  1041. if (s->oformat) {
  1042. av_strlcat(transport, ";mode=receive", sizeof(transport));
  1043. } else if (rt->server_type == RTSP_SERVER_REAL ||
  1044. rt->server_type == RTSP_SERVER_WMS)
  1045. av_strlcat(transport, ";mode=play", sizeof(transport));
  1046. snprintf(cmd, sizeof(cmd),
  1047. "SETUP %s RTSP/1.0\r\n"
  1048. "Transport: %s\r\n",
  1049. rtsp_st->control_url, transport);
  1050. if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
  1051. char real_res[41], real_csum[9];
  1052. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  1053. real_challenge);
  1054. av_strlcatf(cmd, sizeof(cmd),
  1055. "If-Match: %s\r\n"
  1056. "RealChallenge2: %s, sd=%s\r\n",
  1057. rt->session_id, real_res, real_csum);
  1058. }
  1059. ff_rtsp_send_cmd(s, cmd, reply, NULL);
  1060. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  1061. err = 1;
  1062. goto fail;
  1063. } else if (reply->status_code != RTSP_STATUS_OK ||
  1064. reply->nb_transports != 1) {
  1065. err = AVERROR_INVALIDDATA;
  1066. goto fail;
  1067. }
  1068. /* XXX: same protocol for all streams is required */
  1069. if (i > 0) {
  1070. if (reply->transports[0].lower_transport != rt->lower_transport ||
  1071. reply->transports[0].transport != rt->transport) {
  1072. err = AVERROR_INVALIDDATA;
  1073. goto fail;
  1074. }
  1075. } else {
  1076. rt->lower_transport = reply->transports[0].lower_transport;
  1077. rt->transport = reply->transports[0].transport;
  1078. }
  1079. /* close RTP connection if not choosen */
  1080. if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
  1081. (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
  1082. url_close(rtsp_st->rtp_handle);
  1083. rtsp_st->rtp_handle = NULL;
  1084. }
  1085. switch(reply->transports[0].lower_transport) {
  1086. case RTSP_LOWER_TRANSPORT_TCP:
  1087. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  1088. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  1089. break;
  1090. case RTSP_LOWER_TRANSPORT_UDP: {
  1091. char url[1024];
  1092. /* XXX: also use address if specified */
  1093. ff_url_join(url, sizeof(url), "rtp", NULL, host,
  1094. reply->transports[0].server_port_min, NULL);
  1095. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
  1096. rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  1097. err = AVERROR_INVALIDDATA;
  1098. goto fail;
  1099. }
  1100. /* Try to initialize the connection state in a
  1101. * potential NAT router by sending dummy packets.
  1102. * RTP/RTCP dummy packets are used for RDT, too.
  1103. */
  1104. if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) && s->iformat)
  1105. rtp_send_punch_packets(rtsp_st->rtp_handle);
  1106. break;
  1107. }
  1108. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST: {
  1109. char url[1024];
  1110. struct in_addr in;
  1111. int port, ttl;
  1112. if (reply->transports[0].destination) {
  1113. in.s_addr = htonl(reply->transports[0].destination);
  1114. port = reply->transports[0].port_min;
  1115. ttl = reply->transports[0].ttl;
  1116. } else {
  1117. in = rtsp_st->sdp_ip;
  1118. port = rtsp_st->sdp_port;
  1119. ttl = rtsp_st->sdp_ttl;
  1120. }
  1121. ff_url_join(url, sizeof(url), "rtp", NULL, inet_ntoa(in),
  1122. port, "?ttl=%d", ttl);
  1123. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1124. err = AVERROR_INVALIDDATA;
  1125. goto fail;
  1126. }
  1127. break;
  1128. }
  1129. }
  1130. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1131. goto fail;
  1132. }
  1133. if (reply->timeout > 0)
  1134. rt->timeout = reply->timeout;
  1135. if (rt->server_type == RTSP_SERVER_REAL)
  1136. rt->need_subscription = 1;
  1137. return 0;
  1138. fail:
  1139. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1140. if (rt->rtsp_streams[i]->rtp_handle) {
  1141. url_close(rt->rtsp_streams[i]->rtp_handle);
  1142. rt->rtsp_streams[i]->rtp_handle = NULL;
  1143. }
  1144. }
  1145. return err;
  1146. }
  1147. static int rtsp_read_play(AVFormatContext *s)
  1148. {
  1149. RTSPState *rt = s->priv_data;
  1150. RTSPMessageHeader reply1, *reply = &reply1;
  1151. char cmd[1024];
  1152. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  1153. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1154. if (rt->state == RTSP_STATE_PAUSED) {
  1155. snprintf(cmd, sizeof(cmd),
  1156. "PLAY %s RTSP/1.0\r\n",
  1157. rt->control_uri);
  1158. } else {
  1159. snprintf(cmd, sizeof(cmd),
  1160. "PLAY %s RTSP/1.0\r\n"
  1161. "Range: npt=%0.3f-\r\n",
  1162. rt->control_uri,
  1163. (double)rt->seek_timestamp / AV_TIME_BASE);
  1164. }
  1165. ff_rtsp_send_cmd(s, cmd, reply, NULL);
  1166. if (reply->status_code != RTSP_STATUS_OK) {
  1167. return -1;
  1168. }
  1169. }
  1170. rt->state = RTSP_STATE_STREAMING;
  1171. return 0;
  1172. }
  1173. static int rtsp_setup_input_streams(AVFormatContext *s)
  1174. {
  1175. RTSPState *rt = s->priv_data;
  1176. RTSPMessageHeader reply1, *reply = &reply1;
  1177. char cmd[1024];
  1178. unsigned char *content = NULL;
  1179. int ret;
  1180. /* describe the stream */
  1181. snprintf(cmd, sizeof(cmd),
  1182. "DESCRIBE %s RTSP/1.0\r\n"
  1183. "Accept: application/sdp\r\n",
  1184. s->filename);
  1185. if (rt->server_type == RTSP_SERVER_REAL) {
  1186. /**
  1187. * The Require: attribute is needed for proper streaming from
  1188. * Realmedia servers.
  1189. */
  1190. av_strlcat(cmd,
  1191. "Require: com.real.retain-entity-for-setup\r\n",
  1192. sizeof(cmd));
  1193. }
  1194. ff_rtsp_send_cmd(s, cmd, reply, &content);
  1195. if (!content)
  1196. return AVERROR_INVALIDDATA;
  1197. if (reply->status_code != RTSP_STATUS_OK) {
  1198. av_freep(&content);
  1199. return AVERROR_INVALIDDATA;
  1200. }
  1201. /* now we got the SDP description, we parse it */
  1202. ret = sdp_parse(s, (const char *)content);
  1203. av_freep(&content);
  1204. if (ret < 0)
  1205. return AVERROR_INVALIDDATA;
  1206. return 0;
  1207. }
  1208. static int rtsp_setup_output_streams(AVFormatContext *s)
  1209. {
  1210. RTSPState *rt = s->priv_data;
  1211. RTSPMessageHeader reply1, *reply = &reply1;
  1212. char cmd[1024];
  1213. int i;
  1214. char *sdp;
  1215. /* Announce the stream */
  1216. snprintf(cmd, sizeof(cmd),
  1217. "ANNOUNCE %s RTSP/1.0\r\n"
  1218. "Content-Type: application/sdp\r\n",
  1219. s->filename);
  1220. sdp = av_mallocz(8192);
  1221. if (sdp == NULL)
  1222. return AVERROR(ENOMEM);
  1223. if (avf_sdp_create(&s, 1, sdp, 8192)) {
  1224. av_free(sdp);
  1225. return AVERROR_INVALIDDATA;
  1226. }
  1227. av_log(s, AV_LOG_INFO, "SDP:\n%s\n", sdp);
  1228. ff_rtsp_send_cmd_with_content(s, cmd, reply, NULL, sdp, strlen(sdp));
  1229. av_free(sdp);
  1230. if (reply->status_code != RTSP_STATUS_OK)
  1231. return AVERROR_INVALIDDATA;
  1232. /* Set up the RTSPStreams for each AVStream */
  1233. for (i = 0; i < s->nb_streams; i++) {
  1234. RTSPStream *rtsp_st;
  1235. AVStream *st = s->streams[i];
  1236. rtsp_st = av_mallocz(sizeof(RTSPStream));
  1237. if (!rtsp_st)
  1238. return AVERROR(ENOMEM);
  1239. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  1240. st->priv_data = rtsp_st;
  1241. rtsp_st->stream_index = i;
  1242. av_strlcpy(rtsp_st->control_url, s->filename, sizeof(rtsp_st->control_url));
  1243. /* Note, this must match the relative uri set in the sdp content */
  1244. av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),
  1245. "/streamid=%d", i);
  1246. }
  1247. return 0;
  1248. }
  1249. int ff_rtsp_connect(AVFormatContext *s)
  1250. {
  1251. RTSPState *rt = s->priv_data;
  1252. char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];
  1253. char *option_list, *option, *filename;
  1254. URLContext *rtsp_hd;
  1255. int port, err;
  1256. RTSPMessageHeader reply1, *reply = &reply1;
  1257. int lower_transport_mask = 0;
  1258. char real_challenge[64];
  1259. if (!ff_network_init())
  1260. return AVERROR(EIO);
  1261. redirect:
  1262. /* extract hostname and port */
  1263. ff_url_split(NULL, 0, auth, sizeof(auth),
  1264. host, sizeof(host), &port, path, sizeof(path), s->filename);
  1265. if (*auth) {
  1266. int auth_len = strlen(auth), b64_len = ((auth_len + 2) / 3) * 4 + 1;
  1267. if (!(rt->auth_b64 = av_malloc(b64_len)))
  1268. return AVERROR(ENOMEM);
  1269. if (!av_base64_encode(rt->auth_b64, b64_len, auth, auth_len)) {
  1270. err = AVERROR(EINVAL);
  1271. goto fail;
  1272. }
  1273. }
  1274. if (port < 0)
  1275. port = RTSP_DEFAULT_PORT;
  1276. /* search for options */
  1277. option_list = strchr(path, '?');
  1278. if (option_list) {
  1279. filename = strchr(s->filename, '?');
  1280. while (option_list) {
  1281. /* move the option pointer */
  1282. option = ++option_list;
  1283. option_list = strchr(option_list, '&');
  1284. if (option_list)
  1285. *option_list = 0;
  1286. /* handle the options */
  1287. if (!strcmp(option, "udp")) {
  1288. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP);
  1289. } else if (!strcmp(option, "multicast")) {
  1290. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  1291. } else if (!strcmp(option, "tcp")) {
  1292. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_TCP);
  1293. } else {
  1294. strcpy(++filename, option);
  1295. filename += strlen(option);
  1296. if (option_list) *filename = '&';
  1297. }
  1298. }
  1299. *filename = 0;
  1300. }
  1301. if (!lower_transport_mask)
  1302. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;
  1303. if (s->oformat) {
  1304. /* Only UDP output is supported at the moment. */
  1305. lower_transport_mask &= 1 << RTSP_LOWER_TRANSPORT_UDP;
  1306. if (!lower_transport_mask) {
  1307. av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "
  1308. "only UDP is supported for output.\n");
  1309. err = AVERROR(EINVAL);
  1310. goto fail;
  1311. }
  1312. }
  1313. /* open the tcp connexion */
  1314. ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);
  1315. if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0) {
  1316. err = AVERROR(EIO);
  1317. goto fail;
  1318. }
  1319. rt->rtsp_hd = rtsp_hd;
  1320. rt->seq = 0;
  1321. /* request options supported by the server; this also detects server
  1322. * type */
  1323. av_strlcpy(rt->control_uri, s->filename,
  1324. sizeof(rt->control_uri));
  1325. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1326. snprintf(cmd, sizeof(cmd),
  1327. "OPTIONS %s RTSP/1.0\r\n", s->filename);
  1328. if (rt->server_type == RTSP_SERVER_REAL)
  1329. av_strlcat(cmd,
  1330. /**
  1331. * The following entries are required for proper
  1332. * streaming from a Realmedia server. They are
  1333. * interdependent in some way although we currently
  1334. * don't quite understand how. Values were copied
  1335. * from mplayer SVN r23589.
  1336. * @param CompanyID is a 16-byte ID in base64
  1337. * @param ClientChallenge is a 16-byte ID in hex
  1338. */
  1339. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1340. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1341. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1342. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1343. sizeof(cmd));
  1344. ff_rtsp_send_cmd(s, cmd, reply, NULL);
  1345. if (reply->status_code != RTSP_STATUS_OK) {
  1346. err = AVERROR_INVALIDDATA;
  1347. goto fail;
  1348. }
  1349. /* detect server type if not standard-compliant RTP */
  1350. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1351. rt->server_type = RTSP_SERVER_REAL;
  1352. continue;
  1353. } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
  1354. rt->server_type = RTSP_SERVER_WMS;
  1355. } else if (rt->server_type == RTSP_SERVER_REAL)
  1356. strcpy(real_challenge, reply->real_challenge);
  1357. break;
  1358. }
  1359. if (s->iformat)
  1360. err = rtsp_setup_input_streams(s);
  1361. else
  1362. err = rtsp_setup_output_streams(s);
  1363. if (err)
  1364. goto fail;
  1365. do {
  1366. int lower_transport = ff_log2_tab[lower_transport_mask &
  1367. ~(lower_transport_mask - 1)];
  1368. err = make_setup_request(s, host, port, lower_transport,
  1369. rt->server_type == RTSP_SERVER_REAL ?
  1370. real_challenge : NULL);
  1371. if (err < 0)
  1372. goto fail;
  1373. lower_transport_mask &= ~(1 << lower_transport);
  1374. if (lower_transport_mask == 0 && err == 1) {
  1375. err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
  1376. goto fail;
  1377. }
  1378. } while (err);
  1379. rt->state = RTSP_STATE_IDLE;
  1380. rt->seek_timestamp = 0; /* default is to start stream at position zero */
  1381. return 0;
  1382. fail:
  1383. ff_rtsp_close_streams(s);
  1384. url_close(rt->rtsp_hd);
  1385. if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {
  1386. av_strlcpy(s->filename, reply->location, sizeof(s->filename));
  1387. av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",
  1388. reply->status_code,
  1389. s->filename);
  1390. goto redirect;
  1391. }
  1392. ff_network_close();
  1393. return err;
  1394. }
  1395. #endif
  1396. #if CONFIG_RTSP_DEMUXER
  1397. static int rtsp_read_header(AVFormatContext *s,
  1398. AVFormatParameters *ap)
  1399. {
  1400. RTSPState *rt = s->priv_data;
  1401. int ret;
  1402. ret = ff_rtsp_connect(s);
  1403. if (ret)
  1404. return ret;
  1405. if (ap->initial_pause) {
  1406. /* do not start immediately */
  1407. } else {
  1408. if (rtsp_read_play(s) < 0) {
  1409. ff_rtsp_close_streams(s);
  1410. url_close(rt->rtsp_hd);
  1411. return AVERROR_INVALIDDATA;
  1412. }
  1413. }
  1414. return 0;
  1415. }
  1416. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1417. uint8_t *buf, int buf_size)
  1418. {
  1419. RTSPState *rt = s->priv_data;
  1420. RTSPStream *rtsp_st;
  1421. fd_set rfds;
  1422. int fd, fd_max, n, i, ret, tcp_fd;
  1423. struct timeval tv;
  1424. for (;;) {
  1425. if (url_interrupt_cb())
  1426. return AVERROR(EINTR);
  1427. FD_ZERO(&rfds);
  1428. if (rt->rtsp_hd) {
  1429. tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
  1430. FD_SET(tcp_fd, &rfds);
  1431. } else {
  1432. fd_max = 0;
  1433. tcp_fd = -1;
  1434. }
  1435. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1436. rtsp_st = rt->rtsp_streams[i];
  1437. if (rtsp_st->rtp_handle) {
  1438. /* currently, we cannot probe RTCP handle because of
  1439. * blocking restrictions */
  1440. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1441. if (fd > fd_max)
  1442. fd_max = fd;
  1443. FD_SET(fd, &rfds);
  1444. }
  1445. }
  1446. tv.tv_sec = 0;
  1447. tv.tv_usec = 100 * 1000;
  1448. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1449. if (n > 0) {
  1450. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1451. rtsp_st = rt->rtsp_streams[i];
  1452. if (rtsp_st->rtp_handle) {
  1453. fd = url_get_file_handle(rtsp_st->rtp_handle);
  1454. if (FD_ISSET(fd, &rfds)) {
  1455. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1456. if (ret > 0) {
  1457. *prtsp_st = rtsp_st;
  1458. return ret;
  1459. }
  1460. }
  1461. }
  1462. }
  1463. #if CONFIG_RTSP_DEMUXER
  1464. if (tcp_fd != -1 && FD_ISSET(tcp_fd, &rfds)) {
  1465. RTSPMessageHeader reply;
  1466. ff_rtsp_read_reply(s, &reply, NULL, 0);
  1467. /* XXX: parse message */
  1468. if (rt->state != RTSP_STATE_STREAMING)
  1469. return 0;
  1470. }
  1471. #endif
  1472. }
  1473. }
  1474. }
  1475. static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1476. uint8_t *buf, int buf_size)
  1477. {
  1478. RTSPState *rt = s->priv_data;
  1479. int id, len, i, ret;
  1480. RTSPStream *rtsp_st;
  1481. #ifdef DEBUG_RTP_TCP
  1482. dprintf(s, "tcp_read_packet:\n");
  1483. #endif
  1484. redo:
  1485. for (;;) {
  1486. RTSPMessageHeader reply;
  1487. ret = ff_rtsp_read_reply(s, &reply, NULL, 1);
  1488. if (ret == -1)
  1489. return -1;
  1490. if (ret == 1) /* received '$' */
  1491. break;
  1492. /* XXX: parse message */
  1493. if (rt->state != RTSP_STATE_STREAMING)
  1494. return 0;
  1495. }
  1496. ret = url_read_complete(rt->rtsp_hd, buf, 3);
  1497. if (ret != 3)
  1498. return -1;
  1499. id = buf[0];
  1500. len = AV_RB16(buf + 1);
  1501. #ifdef DEBUG_RTP_TCP
  1502. dprintf(s, "id=%d len=%d\n", id, len);
  1503. #endif
  1504. if (len > buf_size || len < 12)
  1505. goto redo;
  1506. /* get the data */
  1507. ret = url_read_complete(rt->rtsp_hd, buf, len);
  1508. if (ret != len)
  1509. return -1;
  1510. if (rt->transport == RTSP_TRANSPORT_RDT &&
  1511. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  1512. return -1;
  1513. /* find the matching stream */
  1514. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1515. rtsp_st = rt->rtsp_streams[i];
  1516. if (id >= rtsp_st->interleaved_min &&
  1517. id <= rtsp_st->interleaved_max)
  1518. goto found;
  1519. }
  1520. goto redo;
  1521. found:
  1522. *prtsp_st = rtsp_st;
  1523. return len;
  1524. }
  1525. static int rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)
  1526. {
  1527. RTSPState *rt = s->priv_data;
  1528. int ret, len;
  1529. uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
  1530. RTSPStream *rtsp_st;
  1531. /* get next frames from the same RTP packet */
  1532. if (rt->cur_transport_priv) {
  1533. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1534. ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1535. } else
  1536. ret = rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);
  1537. if (ret == 0) {
  1538. rt->cur_transport_priv = NULL;
  1539. return 0;
  1540. } else if (ret == 1) {
  1541. return 0;
  1542. } else
  1543. rt->cur_transport_priv = NULL;
  1544. }
  1545. /* read next RTP packet */
  1546. redo:
  1547. switch(rt->lower_transport) {
  1548. default:
  1549. #if CONFIG_RTSP_DEMUXER
  1550. case RTSP_LOWER_TRANSPORT_TCP:
  1551. len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1552. break;
  1553. #endif
  1554. case RTSP_LOWER_TRANSPORT_UDP:
  1555. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1556. len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1557. if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)
  1558. rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);
  1559. break;
  1560. }
  1561. if (len < 0)
  1562. return len;
  1563. if (len == 0)
  1564. return AVERROR_EOF;
  1565. if (rt->transport == RTSP_TRANSPORT_RDT) {
  1566. ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
  1567. } else
  1568. ret = rtp_parse_packet(rtsp_st->transport_priv, pkt, buf, len);
  1569. if (ret < 0)
  1570. goto redo;
  1571. if (ret == 1)
  1572. /* more packets may follow, so we save the RTP context */
  1573. rt->cur_transport_priv = rtsp_st->transport_priv;
  1574. return ret;
  1575. }
  1576. static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
  1577. {
  1578. RTSPState *rt = s->priv_data;
  1579. int ret;
  1580. RTSPMessageHeader reply1, *reply = &reply1;
  1581. char cmd[1024];
  1582. if (rt->server_type == RTSP_SERVER_REAL) {
  1583. int i;
  1584. enum AVDiscard cache[MAX_STREAMS];
  1585. for (i = 0; i < s->nb_streams; i++)
  1586. cache[i] = s->streams[i]->discard;
  1587. if (!rt->need_subscription) {
  1588. if (memcmp (cache, rt->real_setup_cache,
  1589. sizeof(enum AVDiscard) * s->nb_streams)) {
  1590. snprintf(cmd, sizeof(cmd),
  1591. "SET_PARAMETER %s RTSP/1.0\r\n"
  1592. "Unsubscribe: %s\r\n",
  1593. rt->control_uri, rt->last_subscription);
  1594. ff_rtsp_send_cmd(s, cmd, reply, NULL);
  1595. if (reply->status_code != RTSP_STATUS_OK)
  1596. return AVERROR_INVALIDDATA;
  1597. rt->need_subscription = 1;
  1598. }
  1599. }
  1600. if (rt->need_subscription) {
  1601. int r, rule_nr, first = 1;
  1602. memcpy(rt->real_setup_cache, cache,
  1603. sizeof(enum AVDiscard) * s->nb_streams);
  1604. rt->last_subscription[0] = 0;
  1605. snprintf(cmd, sizeof(cmd),
  1606. "SET_PARAMETER %s RTSP/1.0\r\n"
  1607. "Subscribe: ",
  1608. rt->control_uri);
  1609. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1610. rule_nr = 0;
  1611. for (r = 0; r < s->nb_streams; r++) {
  1612. if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
  1613. if (s->streams[r]->discard != AVDISCARD_ALL) {
  1614. if (!first)
  1615. av_strlcat(rt->last_subscription, ",",
  1616. sizeof(rt->last_subscription));
  1617. ff_rdt_subscribe_rule(
  1618. rt->last_subscription,
  1619. sizeof(rt->last_subscription), i, rule_nr);
  1620. first = 0;
  1621. }
  1622. rule_nr++;
  1623. }
  1624. }
  1625. }
  1626. av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
  1627. ff_rtsp_send_cmd(s, cmd, reply, NULL);
  1628. if (reply->status_code != RTSP_STATUS_OK)
  1629. return AVERROR_INVALIDDATA;
  1630. rt->need_subscription = 0;
  1631. if (rt->state == RTSP_STATE_STREAMING)
  1632. rtsp_read_play (s);
  1633. }
  1634. }
  1635. ret = rtsp_fetch_packet(s, pkt);
  1636. if (ret < 0)
  1637. return ret;
  1638. /* send dummy request to keep TCP connection alive */
  1639. if ((rt->server_type == RTSP_SERVER_WMS ||
  1640. rt->server_type == RTSP_SERVER_REAL) &&
  1641. (av_gettime() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2) {
  1642. if (rt->server_type == RTSP_SERVER_WMS) {
  1643. snprintf(cmd, sizeof(cmd) - 1,
  1644. "GET_PARAMETER %s RTSP/1.0\r\n",
  1645. rt->control_uri);
  1646. ff_rtsp_send_cmd_async(s, cmd);
  1647. } else {
  1648. ff_rtsp_send_cmd_async(s, "OPTIONS * RTSP/1.0\r\n");
  1649. }
  1650. }
  1651. return 0;
  1652. }
  1653. /* pause the stream */
  1654. static int rtsp_read_pause(AVFormatContext *s)
  1655. {
  1656. RTSPState *rt = s->priv_data;
  1657. RTSPMessageHeader reply1, *reply = &reply1;
  1658. char cmd[1024];
  1659. rt = s->priv_data;
  1660. if (rt->state != RTSP_STATE_STREAMING)
  1661. return 0;
  1662. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1663. snprintf(cmd, sizeof(cmd),
  1664. "PAUSE %s RTSP/1.0\r\n",
  1665. rt->control_uri);
  1666. ff_rtsp_send_cmd(s, cmd, reply, NULL);
  1667. if (reply->status_code != RTSP_STATUS_OK) {
  1668. return -1;
  1669. }
  1670. }
  1671. rt->state = RTSP_STATE_PAUSED;
  1672. return 0;
  1673. }
  1674. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  1675. int64_t timestamp, int flags)
  1676. {
  1677. RTSPState *rt = s->priv_data;
  1678. rt->seek_timestamp = av_rescale_q(timestamp,
  1679. s->streams[stream_index]->time_base,
  1680. AV_TIME_BASE_Q);
  1681. switch(rt->state) {
  1682. default:
  1683. case RTSP_STATE_IDLE:
  1684. break;
  1685. case RTSP_STATE_STREAMING:
  1686. if (rtsp_read_pause(s) != 0)
  1687. return -1;
  1688. rt->state = RTSP_STATE_SEEKING;
  1689. if (rtsp_read_play(s) != 0)
  1690. return -1;
  1691. break;
  1692. case RTSP_STATE_PAUSED:
  1693. rt->state = RTSP_STATE_IDLE;
  1694. break;
  1695. }
  1696. return 0;
  1697. }
  1698. static int rtsp_read_close(AVFormatContext *s)
  1699. {
  1700. RTSPState *rt = s->priv_data;
  1701. char cmd[1024];
  1702. #if 0
  1703. /* NOTE: it is valid to flush the buffer here */
  1704. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1705. url_fclose(&rt->rtsp_gb);
  1706. }
  1707. #endif
  1708. snprintf(cmd, sizeof(cmd),
  1709. "TEARDOWN %s RTSP/1.0\r\n",
  1710. s->filename);
  1711. ff_rtsp_send_cmd_async(s, cmd);
  1712. ff_rtsp_close_streams(s);
  1713. url_close(rt->rtsp_hd);
  1714. ff_network_close();
  1715. return 0;
  1716. }
  1717. AVInputFormat rtsp_demuxer = {
  1718. "rtsp",
  1719. NULL_IF_CONFIG_SMALL("RTSP input format"),
  1720. sizeof(RTSPState),
  1721. rtsp_probe,
  1722. rtsp_read_header,
  1723. rtsp_read_packet,
  1724. rtsp_read_close,
  1725. rtsp_read_seek,
  1726. .flags = AVFMT_NOFILE,
  1727. .read_play = rtsp_read_play,
  1728. .read_pause = rtsp_read_pause,
  1729. };
  1730. #endif
  1731. static int sdp_probe(AVProbeData *p1)
  1732. {
  1733. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1734. /* we look for a line beginning "c=IN IP4" */
  1735. while (p < p_end && *p != '\0') {
  1736. if (p + sizeof("c=IN IP4") - 1 < p_end &&
  1737. av_strstart(p, "c=IN IP4", NULL))
  1738. return AVPROBE_SCORE_MAX / 2;
  1739. while (p < p_end - 1 && *p != '\n') p++;
  1740. if (++p >= p_end)
  1741. break;
  1742. if (*p == '\r')
  1743. p++;
  1744. }
  1745. return 0;
  1746. }
  1747. #define SDP_MAX_SIZE 8192
  1748. static int sdp_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1749. {
  1750. RTSPState *rt = s->priv_data;
  1751. RTSPStream *rtsp_st;
  1752. int size, i, err;
  1753. char *content;
  1754. char url[1024];
  1755. if (!ff_network_init())
  1756. return AVERROR(EIO);
  1757. /* read the whole sdp file */
  1758. /* XXX: better loading */
  1759. content = av_malloc(SDP_MAX_SIZE);
  1760. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1761. if (size <= 0) {
  1762. av_free(content);
  1763. return AVERROR_INVALIDDATA;
  1764. }
  1765. content[size] ='\0';
  1766. sdp_parse(s, content);
  1767. av_free(content);
  1768. /* open each RTP stream */
  1769. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1770. rtsp_st = rt->rtsp_streams[i];
  1771. ff_url_join(url, sizeof(url), "rtp", NULL,
  1772. inet_ntoa(rtsp_st->sdp_ip), rtsp_st->sdp_port,
  1773. "?localport=%d&ttl=%d", rtsp_st->sdp_port,
  1774. rtsp_st->sdp_ttl);
  1775. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1776. err = AVERROR_INVALIDDATA;
  1777. goto fail;
  1778. }
  1779. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1780. goto fail;
  1781. }
  1782. return 0;
  1783. fail:
  1784. ff_rtsp_close_streams(s);
  1785. ff_network_close();
  1786. return err;
  1787. }
  1788. static int sdp_read_close(AVFormatContext *s)
  1789. {
  1790. ff_rtsp_close_streams(s);
  1791. ff_network_close();
  1792. return 0;
  1793. }
  1794. AVInputFormat sdp_demuxer = {
  1795. "sdp",
  1796. NULL_IF_CONFIG_SMALL("SDP"),
  1797. sizeof(RTSPState),
  1798. sdp_probe,
  1799. sdp_read_header,
  1800. rtsp_fetch_packet,
  1801. sdp_read_close,
  1802. };