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.

1739 lines
55KB

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