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.

1828 lines
59KB

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