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.

1681 lines
52KB

  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 "rtp.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 (!strcmp(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_strlcpy(s->title, p, sizeof(s->title));
  343. break;
  344. case 'i':
  345. if (s->nb_streams == 0) {
  346. av_strlcpy(s->comment, p, sizeof(s->comment));
  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 {
  359. s1->skip_media = 1;
  360. return;
  361. }
  362. rtsp_st = av_mallocz(sizeof(RTSPStream));
  363. if (!rtsp_st)
  364. return;
  365. rtsp_st->stream_index = -1;
  366. dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);
  367. rtsp_st->sdp_ip = s1->default_ip;
  368. rtsp_st->sdp_ttl = s1->default_ttl;
  369. get_word(buf1, sizeof(buf1), &p); /* port */
  370. rtsp_st->sdp_port = atoi(buf1);
  371. get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */
  372. /* XXX: handle list of formats */
  373. get_word(buf1, sizeof(buf1), &p); /* format list */
  374. rtsp_st->sdp_payload_type = atoi(buf1);
  375. if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {
  376. /* no corresponding stream */
  377. } else {
  378. st = av_new_stream(s, 0);
  379. if (!st)
  380. return;
  381. st->priv_data = rtsp_st;
  382. rtsp_st->stream_index = st->index;
  383. st->codec->codec_type = codec_type;
  384. if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
  385. /* if standard payload type, we can find the codec right now */
  386. rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);
  387. }
  388. }
  389. /* put a default control url */
  390. av_strlcpy(rtsp_st->control_url, s->filename, sizeof(rtsp_st->control_url));
  391. break;
  392. case 'a':
  393. if (av_strstart(p, "control:", &p) && s->nb_streams > 0) {
  394. char proto[32];
  395. /* get the control url */
  396. st = s->streams[s->nb_streams - 1];
  397. rtsp_st = st->priv_data;
  398. /* XXX: may need to add full url resolution */
  399. url_split(proto, sizeof(proto), NULL, 0, NULL, 0, NULL, NULL, 0, p);
  400. if (proto[0] == '\0') {
  401. /* relative control URL */
  402. av_strlcat(rtsp_st->control_url, "/", sizeof(rtsp_st->control_url));
  403. av_strlcat(rtsp_st->control_url, p, sizeof(rtsp_st->control_url));
  404. } else {
  405. av_strlcpy(rtsp_st->control_url, p, sizeof(rtsp_st->control_url));
  406. }
  407. } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {
  408. /* NOTE: rtpmap is only supported AFTER the 'm=' tag */
  409. get_word(buf1, sizeof(buf1), &p);
  410. payload_type = atoi(buf1);
  411. st = s->streams[s->nb_streams - 1];
  412. rtsp_st = st->priv_data;
  413. sdp_parse_rtpmap(st->codec, rtsp_st, payload_type, p);
  414. } else if (av_strstart(p, "fmtp:", &p)) {
  415. /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */
  416. get_word(buf1, sizeof(buf1), &p);
  417. payload_type = atoi(buf1);
  418. for(i = 0; i < s->nb_streams;i++) {
  419. st = s->streams[i];
  420. rtsp_st = st->priv_data;
  421. if (rtsp_st->sdp_payload_type == payload_type) {
  422. if(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) {
  423. if(!rtsp_st->dynamic_handler->parse_sdp_a_line(s, i, rtsp_st->dynamic_protocol_context, buf)) {
  424. sdp_parse_fmtp(st, p);
  425. }
  426. } else {
  427. sdp_parse_fmtp(st, p);
  428. }
  429. }
  430. }
  431. } else if(av_strstart(p, "framesize:", &p)) {
  432. // let dynamic protocol handlers have a stab at the line.
  433. get_word(buf1, sizeof(buf1), &p);
  434. payload_type = atoi(buf1);
  435. for(i = 0; i < s->nb_streams;i++) {
  436. st = s->streams[i];
  437. rtsp_st = st->priv_data;
  438. if (rtsp_st->sdp_payload_type == payload_type) {
  439. if(rtsp_st->dynamic_handler && rtsp_st->dynamic_handler->parse_sdp_a_line) {
  440. rtsp_st->dynamic_handler->parse_sdp_a_line(s, i, rtsp_st->dynamic_protocol_context, buf);
  441. }
  442. }
  443. }
  444. } else if(av_strstart(p, "range:", &p)) {
  445. int64_t start, end;
  446. // this is so that seeking on a streamed file can work.
  447. rtsp_parse_range_npt(p, &start, &end);
  448. s->start_time= start;
  449. s->duration= (end==AV_NOPTS_VALUE)?AV_NOPTS_VALUE:end-start; // AV_NOPTS_VALUE means live broadcast (and can't seek)
  450. } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
  451. if (atoi(p) == 1)
  452. rt->transport = RTSP_TRANSPORT_RDT;
  453. } else if (s->nb_streams > 0) {
  454. if (rt->server_type == RTSP_SERVER_REAL)
  455. ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
  456. rtsp_st = s->streams[s->nb_streams - 1]->priv_data;
  457. if (rtsp_st->dynamic_handler &&
  458. rtsp_st->dynamic_handler->parse_sdp_a_line)
  459. rtsp_st->dynamic_handler->parse_sdp_a_line(s, s->nb_streams - 1,
  460. rtsp_st->dynamic_protocol_context, buf);
  461. }
  462. break;
  463. }
  464. }
  465. static int sdp_parse(AVFormatContext *s, const char *content)
  466. {
  467. const char *p;
  468. int letter;
  469. /* Some SDP lines, particularly for Realmedia or ASF RTSP streams,
  470. * contain long SDP lines containing complete ASF Headers (several
  471. * kB) or arrays of MDPR (RM stream descriptor) headers plus
  472. * "rulebooks" describing their properties. Therefore, the SDP line
  473. * buffer is large. */
  474. char buf[8192], *q;
  475. SDPParseState sdp_parse_state, *s1 = &sdp_parse_state;
  476. memset(s1, 0, sizeof(SDPParseState));
  477. p = content;
  478. for(;;) {
  479. skip_spaces(&p);
  480. letter = *p;
  481. if (letter == '\0')
  482. break;
  483. p++;
  484. if (*p != '=')
  485. goto next_line;
  486. p++;
  487. /* get the content */
  488. q = buf;
  489. while (*p != '\n' && *p != '\r' && *p != '\0') {
  490. if ((q - buf) < sizeof(buf) - 1)
  491. *q++ = *p;
  492. p++;
  493. }
  494. *q = '\0';
  495. sdp_parse_line(s, s1, letter, buf);
  496. next_line:
  497. while (*p != '\n' && *p != '\0')
  498. p++;
  499. if (*p == '\n')
  500. p++;
  501. }
  502. return 0;
  503. }
  504. static void rtsp_parse_range(int *min_ptr, int *max_ptr, const char **pp)
  505. {
  506. const char *p;
  507. int v;
  508. p = *pp;
  509. skip_spaces(&p);
  510. v = strtol(p, (char **)&p, 10);
  511. if (*p == '-') {
  512. p++;
  513. *min_ptr = v;
  514. v = strtol(p, (char **)&p, 10);
  515. *max_ptr = v;
  516. } else {
  517. *min_ptr = v;
  518. *max_ptr = v;
  519. }
  520. *pp = p;
  521. }
  522. /* XXX: only one transport specification is parsed */
  523. static void rtsp_parse_transport(RTSPHeader *reply, const char *p)
  524. {
  525. char transport_protocol[16];
  526. char profile[16];
  527. char lower_transport[16];
  528. char parameter[16];
  529. RTSPTransportField *th;
  530. char buf[256];
  531. reply->nb_transports = 0;
  532. for(;;) {
  533. skip_spaces(&p);
  534. if (*p == '\0')
  535. break;
  536. th = &reply->transports[reply->nb_transports];
  537. get_word_sep(transport_protocol, sizeof(transport_protocol),
  538. "/", &p);
  539. if (*p == '/')
  540. p++;
  541. if (!strcasecmp (transport_protocol, "rtp")) {
  542. get_word_sep(profile, sizeof(profile), "/;,", &p);
  543. lower_transport[0] = '\0';
  544. /* rtp/avp/<protocol> */
  545. if (*p == '/') {
  546. p++;
  547. get_word_sep(lower_transport, sizeof(lower_transport),
  548. ";,", &p);
  549. }
  550. th->transport = RTSP_TRANSPORT_RTP;
  551. } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||
  552. !strcasecmp (transport_protocol, "x-real-rdt")) {
  553. /* x-pn-tng/<protocol> */
  554. get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);
  555. profile[0] = '\0';
  556. th->transport = RTSP_TRANSPORT_RDT;
  557. }
  558. if (!strcasecmp(lower_transport, "TCP"))
  559. th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
  560. else
  561. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;
  562. if (*p == ';')
  563. p++;
  564. /* get each parameter */
  565. while (*p != '\0' && *p != ',') {
  566. get_word_sep(parameter, sizeof(parameter), "=;,", &p);
  567. if (!strcmp(parameter, "port")) {
  568. if (*p == '=') {
  569. p++;
  570. rtsp_parse_range(&th->port_min, &th->port_max, &p);
  571. }
  572. } else if (!strcmp(parameter, "client_port")) {
  573. if (*p == '=') {
  574. p++;
  575. rtsp_parse_range(&th->client_port_min,
  576. &th->client_port_max, &p);
  577. }
  578. } else if (!strcmp(parameter, "server_port")) {
  579. if (*p == '=') {
  580. p++;
  581. rtsp_parse_range(&th->server_port_min,
  582. &th->server_port_max, &p);
  583. }
  584. } else if (!strcmp(parameter, "interleaved")) {
  585. if (*p == '=') {
  586. p++;
  587. rtsp_parse_range(&th->interleaved_min,
  588. &th->interleaved_max, &p);
  589. }
  590. } else if (!strcmp(parameter, "multicast")) {
  591. if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)
  592. th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;
  593. } else if (!strcmp(parameter, "ttl")) {
  594. if (*p == '=') {
  595. p++;
  596. th->ttl = strtol(p, (char **)&p, 10);
  597. }
  598. } else if (!strcmp(parameter, "destination")) {
  599. struct in_addr ipaddr;
  600. if (*p == '=') {
  601. p++;
  602. get_word_sep(buf, sizeof(buf), ";,", &p);
  603. if (inet_aton(buf, &ipaddr))
  604. th->destination = ntohl(ipaddr.s_addr);
  605. }
  606. }
  607. while (*p != ';' && *p != '\0' && *p != ',')
  608. p++;
  609. if (*p == ';')
  610. p++;
  611. }
  612. if (*p == ',')
  613. p++;
  614. reply->nb_transports++;
  615. }
  616. }
  617. void rtsp_parse_line(RTSPHeader *reply, const char *buf)
  618. {
  619. const char *p;
  620. /* NOTE: we do case independent match for broken servers */
  621. p = buf;
  622. if (av_stristart(p, "Session:", &p)) {
  623. get_word_sep(reply->session_id, sizeof(reply->session_id), ";", &p);
  624. } else if (av_stristart(p, "Content-Length:", &p)) {
  625. reply->content_length = strtol(p, NULL, 10);
  626. } else if (av_stristart(p, "Transport:", &p)) {
  627. rtsp_parse_transport(reply, p);
  628. } else if (av_stristart(p, "CSeq:", &p)) {
  629. reply->seq = strtol(p, NULL, 10);
  630. } else if (av_stristart(p, "Range:", &p)) {
  631. rtsp_parse_range_npt(p, &reply->range_start, &reply->range_end);
  632. } else if (av_stristart(p, "RealChallenge1:", &p)) {
  633. skip_spaces(&p);
  634. av_strlcpy(reply->real_challenge, p, sizeof(reply->real_challenge));
  635. } else if (av_stristart(p, "Server:", &p)) {
  636. skip_spaces(&p);
  637. av_strlcpy(reply->server, p, sizeof(reply->server));
  638. }
  639. }
  640. static int url_readbuf(URLContext *h, unsigned char *buf, int size)
  641. {
  642. int ret, len;
  643. len = 0;
  644. while (len < size) {
  645. ret = url_read(h, buf+len, size-len);
  646. if (ret < 1)
  647. return ret;
  648. len += ret;
  649. }
  650. return len;
  651. }
  652. /* skip a RTP/TCP interleaved packet */
  653. static void rtsp_skip_packet(AVFormatContext *s)
  654. {
  655. RTSPState *rt = s->priv_data;
  656. int ret, len, len1;
  657. uint8_t buf[1024];
  658. ret = url_readbuf(rt->rtsp_hd, buf, 3);
  659. if (ret != 3)
  660. return;
  661. len = AV_RB16(buf + 1);
  662. #ifdef DEBUG
  663. printf("skipping RTP packet len=%d\n", len);
  664. #endif
  665. /* skip payload */
  666. while (len > 0) {
  667. len1 = len;
  668. if (len1 > sizeof(buf))
  669. len1 = sizeof(buf);
  670. ret = url_readbuf(rt->rtsp_hd, buf, len1);
  671. if (ret != len1)
  672. return;
  673. len -= len1;
  674. }
  675. }
  676. static void rtsp_send_cmd(AVFormatContext *s,
  677. const char *cmd, RTSPHeader *reply,
  678. unsigned char **content_ptr)
  679. {
  680. RTSPState *rt = s->priv_data;
  681. char buf[4096], buf1[1024], *q;
  682. unsigned char ch;
  683. const char *p;
  684. int content_length, line_count;
  685. unsigned char *content = NULL;
  686. memset(reply, 0, sizeof(RTSPHeader));
  687. rt->seq++;
  688. av_strlcpy(buf, cmd, sizeof(buf));
  689. snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
  690. av_strlcat(buf, buf1, sizeof(buf));
  691. if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
  692. snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
  693. av_strlcat(buf, buf1, sizeof(buf));
  694. }
  695. av_strlcat(buf, "\r\n", sizeof(buf));
  696. #ifdef DEBUG
  697. printf("Sending:\n%s--\n", buf);
  698. #endif
  699. url_write(rt->rtsp_hd, buf, strlen(buf));
  700. /* parse reply (XXX: use buffers) */
  701. line_count = 0;
  702. rt->last_reply[0] = '\0';
  703. for(;;) {
  704. q = buf;
  705. for(;;) {
  706. if (url_readbuf(rt->rtsp_hd, &ch, 1) != 1)
  707. break;
  708. if (ch == '\n')
  709. break;
  710. if (ch == '$') {
  711. /* XXX: only parse it if first char on line ? */
  712. rtsp_skip_packet(s);
  713. } else if (ch != '\r') {
  714. if ((q - buf) < sizeof(buf) - 1)
  715. *q++ = ch;
  716. }
  717. }
  718. *q = '\0';
  719. #ifdef DEBUG
  720. printf("line='%s'\n", buf);
  721. #endif
  722. /* test if last line */
  723. if (buf[0] == '\0')
  724. break;
  725. p = buf;
  726. if (line_count == 0) {
  727. /* get reply code */
  728. get_word(buf1, sizeof(buf1), &p);
  729. get_word(buf1, sizeof(buf1), &p);
  730. reply->status_code = atoi(buf1);
  731. } else {
  732. rtsp_parse_line(reply, p);
  733. av_strlcat(rt->last_reply, p, sizeof(rt->last_reply));
  734. av_strlcat(rt->last_reply, "\n", sizeof(rt->last_reply));
  735. }
  736. line_count++;
  737. }
  738. if (rt->session_id[0] == '\0' && reply->session_id[0] != '\0')
  739. av_strlcpy(rt->session_id, reply->session_id, sizeof(rt->session_id));
  740. content_length = reply->content_length;
  741. if (content_length > 0) {
  742. /* leave some room for a trailing '\0' (useful for simple parsing) */
  743. content = av_malloc(content_length + 1);
  744. (void)url_readbuf(rt->rtsp_hd, content, content_length);
  745. content[content_length] = '\0';
  746. }
  747. if (content_ptr)
  748. *content_ptr = content;
  749. else
  750. av_free(content);
  751. }
  752. /* close and free RTSP streams */
  753. static void rtsp_close_streams(RTSPState *rt)
  754. {
  755. int i;
  756. RTSPStream *rtsp_st;
  757. for(i=0;i<rt->nb_rtsp_streams;i++) {
  758. rtsp_st = rt->rtsp_streams[i];
  759. if (rtsp_st) {
  760. if (rtsp_st->tx_ctx) {
  761. if (rt->transport == RTSP_TRANSPORT_RDT)
  762. ff_rdt_parse_close(rtsp_st->tx_ctx);
  763. else
  764. rtp_parse_close(rtsp_st->tx_ctx);
  765. }
  766. if (rtsp_st->rtp_handle)
  767. url_close(rtsp_st->rtp_handle);
  768. if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)
  769. rtsp_st->dynamic_handler->close(rtsp_st->dynamic_protocol_context);
  770. }
  771. }
  772. av_free(rt->rtsp_streams);
  773. }
  774. static int
  775. rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)
  776. {
  777. RTSPState *rt = s->priv_data;
  778. AVStream *st = NULL;
  779. /* open the RTP context */
  780. if (rtsp_st->stream_index >= 0)
  781. st = s->streams[rtsp_st->stream_index];
  782. if (!st)
  783. s->ctx_flags |= AVFMTCTX_NOHEADER;
  784. if (rt->transport == RTSP_TRANSPORT_RDT)
  785. rtsp_st->tx_ctx = ff_rdt_parse_open(s, st->index,
  786. rtsp_st->dynamic_protocol_context,
  787. rtsp_st->dynamic_handler);
  788. else
  789. rtsp_st->tx_ctx = rtp_parse_open(s, st, rtsp_st->rtp_handle,
  790. rtsp_st->sdp_payload_type,
  791. &rtsp_st->rtp_payload_data);
  792. if (!rtsp_st->tx_ctx) {
  793. return AVERROR(ENOMEM);
  794. } else if (rt->transport != RTSP_TRANSPORT_RDT) {
  795. if(rtsp_st->dynamic_handler) {
  796. rtp_parse_set_dynamic_protocol(rtsp_st->tx_ctx,
  797. rtsp_st->dynamic_protocol_context,
  798. rtsp_st->dynamic_handler);
  799. }
  800. }
  801. return 0;
  802. }
  803. /**
  804. * @returns 0 on success, <0 on error, 1 if protocol is unavailable.
  805. */
  806. static int
  807. make_setup_request (AVFormatContext *s, const char *host, int port,
  808. int lower_transport, const char *real_challenge)
  809. {
  810. RTSPState *rt = s->priv_data;
  811. int j, i, err;
  812. RTSPStream *rtsp_st;
  813. RTSPHeader reply1, *reply = &reply1;
  814. char cmd[2048];
  815. const char *trans_pref;
  816. if (rt->transport == RTSP_TRANSPORT_RDT)
  817. trans_pref = "x-pn-tng";
  818. else
  819. trans_pref = "RTP/AVP";
  820. /* for each stream, make the setup request */
  821. /* XXX: we assume the same server is used for the control of each
  822. RTSP stream */
  823. for(j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
  824. char transport[2048];
  825. rtsp_st = rt->rtsp_streams[i];
  826. /* RTP/UDP */
  827. if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
  828. char buf[256];
  829. /* first try in specified port range */
  830. if (RTSP_RTP_PORT_MIN != 0) {
  831. while(j <= RTSP_RTP_PORT_MAX) {
  832. snprintf(buf, sizeof(buf), "rtp://%s?localport=%d", host, j);
  833. j += 2; /* we will use two port by rtp stream (rtp and rtcp) */
  834. if (url_open(&rtsp_st->rtp_handle, buf, URL_RDWR) == 0) {
  835. goto rtp_opened;
  836. }
  837. }
  838. }
  839. /* then try on any port
  840. ** if (url_open(&rtsp_st->rtp_handle, "rtp://", URL_RDONLY) < 0) {
  841. ** err = AVERROR_INVALIDDATA;
  842. ** goto fail;
  843. ** }
  844. */
  845. rtp_opened:
  846. port = rtp_get_local_port(rtsp_st->rtp_handle);
  847. snprintf(transport, sizeof(transport) - 1,
  848. "%s/UDP;", trans_pref);
  849. if (rt->server_type != RTSP_SERVER_REAL)
  850. av_strlcat(transport, "unicast;", sizeof(transport));
  851. av_strlcatf(transport, sizeof(transport),
  852. "client_port=%d", port);
  853. if (rt->transport == RTSP_TRANSPORT_RTP)
  854. av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
  855. }
  856. /* RTP/TCP */
  857. else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  858. snprintf(transport, sizeof(transport) - 1,
  859. "%s/TCP", trans_pref);
  860. }
  861. else if (lower_transport == RTSP_LOWER_TRANSPORT_UDP_MULTICAST) {
  862. snprintf(transport, sizeof(transport) - 1,
  863. "%s/UDP;multicast", trans_pref);
  864. }
  865. if (rt->server_type == RTSP_SERVER_REAL)
  866. av_strlcat(transport, ";mode=play", sizeof(transport));
  867. snprintf(cmd, sizeof(cmd),
  868. "SETUP %s RTSP/1.0\r\n"
  869. "Transport: %s\r\n",
  870. rtsp_st->control_url, transport);
  871. if (i == 0 && rt->server_type == RTSP_SERVER_REAL) {
  872. char real_res[41], real_csum[9];
  873. ff_rdt_calc_response_and_checksum(real_res, real_csum,
  874. real_challenge);
  875. av_strlcatf(cmd, sizeof(cmd),
  876. "If-Match: %s\r\n"
  877. "RealChallenge2: %s, sd=%s\r\n",
  878. rt->session_id, real_res, real_csum);
  879. }
  880. rtsp_send_cmd(s, cmd, reply, NULL);
  881. if (reply->status_code == 461 /* Unsupported protocol */ && i == 0) {
  882. err = 1;
  883. goto fail;
  884. } else if (reply->status_code != RTSP_STATUS_OK ||
  885. reply->nb_transports != 1) {
  886. err = AVERROR_INVALIDDATA;
  887. goto fail;
  888. }
  889. /* XXX: same protocol for all streams is required */
  890. if (i > 0) {
  891. if (reply->transports[0].lower_transport != rt->lower_transport ||
  892. reply->transports[0].transport != rt->transport) {
  893. err = AVERROR_INVALIDDATA;
  894. goto fail;
  895. }
  896. } else {
  897. rt->lower_transport = reply->transports[0].lower_transport;
  898. rt->transport = reply->transports[0].transport;
  899. }
  900. /* close RTP connection if not choosen */
  901. if (reply->transports[0].lower_transport != RTSP_LOWER_TRANSPORT_UDP &&
  902. (lower_transport == RTSP_LOWER_TRANSPORT_UDP)) {
  903. url_close(rtsp_st->rtp_handle);
  904. rtsp_st->rtp_handle = NULL;
  905. }
  906. switch(reply->transports[0].lower_transport) {
  907. case RTSP_LOWER_TRANSPORT_TCP:
  908. rtsp_st->interleaved_min = reply->transports[0].interleaved_min;
  909. rtsp_st->interleaved_max = reply->transports[0].interleaved_max;
  910. break;
  911. case RTSP_LOWER_TRANSPORT_UDP:
  912. {
  913. char url[1024];
  914. /* XXX: also use address if specified */
  915. snprintf(url, sizeof(url), "rtp://%s:%d",
  916. host, reply->transports[0].server_port_min);
  917. if (rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
  918. err = AVERROR_INVALIDDATA;
  919. goto fail;
  920. }
  921. }
  922. break;
  923. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  924. {
  925. char url[1024];
  926. struct in_addr in;
  927. in.s_addr = htonl(reply->transports[0].destination);
  928. snprintf(url, sizeof(url), "rtp://%s:%d?ttl=%d",
  929. inet_ntoa(in),
  930. reply->transports[0].port_min,
  931. reply->transports[0].ttl);
  932. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  933. err = AVERROR_INVALIDDATA;
  934. goto fail;
  935. }
  936. }
  937. break;
  938. }
  939. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  940. goto fail;
  941. }
  942. if (rt->server_type == RTSP_SERVER_REAL)
  943. rt->need_subscription = 1;
  944. return 0;
  945. fail:
  946. for (i=0; i<rt->nb_rtsp_streams; i++) {
  947. if (rt->rtsp_streams[i]->rtp_handle) {
  948. url_close(rt->rtsp_streams[i]->rtp_handle);
  949. rt->rtsp_streams[i]->rtp_handle = NULL;
  950. }
  951. }
  952. return err;
  953. }
  954. static int rtsp_read_header(AVFormatContext *s,
  955. AVFormatParameters *ap)
  956. {
  957. RTSPState *rt = s->priv_data;
  958. char host[1024], path[1024], tcpname[1024], cmd[2048], *option_list, *option;
  959. URLContext *rtsp_hd;
  960. int port, ret, err;
  961. RTSPHeader reply1, *reply = &reply1;
  962. unsigned char *content = NULL;
  963. int lower_transport_mask = 0;
  964. char real_challenge[64];
  965. /* extract hostname and port */
  966. url_split(NULL, 0, NULL, 0,
  967. host, sizeof(host), &port, path, sizeof(path), s->filename);
  968. if (port < 0)
  969. port = RTSP_DEFAULT_PORT;
  970. /* search for options */
  971. option_list = strchr(path, '?');
  972. if (option_list) {
  973. /* remove the options from the path */
  974. *option_list++ = 0;
  975. while(option_list) {
  976. /* move the option pointer */
  977. option = option_list;
  978. option_list = strchr(option_list, '&');
  979. if (option_list)
  980. *(option_list++) = 0;
  981. /* handle the options */
  982. if (strcmp(option, "udp") == 0)
  983. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP);
  984. else if (strcmp(option, "multicast") == 0)
  985. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  986. else if (strcmp(option, "tcp") == 0)
  987. lower_transport_mask = (1<< RTSP_LOWER_TRANSPORT_TCP);
  988. }
  989. }
  990. if (!lower_transport_mask)
  991. lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_LAST) - 1;
  992. /* open the tcp connexion */
  993. snprintf(tcpname, sizeof(tcpname), "tcp://%s:%d", host, port);
  994. if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0)
  995. return AVERROR(EIO);
  996. rt->rtsp_hd = rtsp_hd;
  997. rt->seq = 0;
  998. /* request options supported by the server; this also detects server type */
  999. for (rt->server_type = RTSP_SERVER_RTP;;) {
  1000. snprintf(cmd, sizeof(cmd),
  1001. "OPTIONS %s RTSP/1.0\r\n", s->filename);
  1002. if (rt->server_type == RTSP_SERVER_REAL)
  1003. av_strlcat(cmd,
  1004. /**
  1005. * The following entries are required for proper
  1006. * streaming from a Realmedia server. They are
  1007. * interdependent in some way although we currently
  1008. * don't quite understand how. Values were copied
  1009. * from mplayer SVN r23589.
  1010. * @param CompanyID is a 16-byte ID in base64
  1011. * @param ClientChallenge is a 16-byte ID in hex
  1012. */
  1013. "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"
  1014. "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"
  1015. "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"
  1016. "GUID: 00000000-0000-0000-0000-000000000000\r\n",
  1017. sizeof(cmd));
  1018. rtsp_send_cmd(s, cmd, reply, NULL);
  1019. if (reply->status_code != RTSP_STATUS_OK) {
  1020. err = AVERROR_INVALIDDATA;
  1021. goto fail;
  1022. }
  1023. /* detect server type if not standard-compliant RTP */
  1024. if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {
  1025. rt->server_type = RTSP_SERVER_REAL;
  1026. continue;
  1027. } else if (!strncasecmp(reply->server, "WMServer/", 9)) {
  1028. rt->server_type = RTSP_SERVER_WMS;
  1029. } else if (rt->server_type == RTSP_SERVER_REAL) {
  1030. strcpy(real_challenge, reply->real_challenge);
  1031. }
  1032. break;
  1033. }
  1034. /* describe the stream */
  1035. snprintf(cmd, sizeof(cmd),
  1036. "DESCRIBE %s RTSP/1.0\r\n"
  1037. "Accept: application/sdp\r\n",
  1038. s->filename);
  1039. if (rt->server_type == RTSP_SERVER_REAL) {
  1040. /**
  1041. * The Require: attribute is needed for proper streaming from
  1042. * Realmedia servers.
  1043. */
  1044. av_strlcat(cmd,
  1045. "Require: com.real.retain-entity-for-setup\r\n",
  1046. sizeof(cmd));
  1047. }
  1048. rtsp_send_cmd(s, cmd, reply, &content);
  1049. if (!content) {
  1050. err = AVERROR_INVALIDDATA;
  1051. goto fail;
  1052. }
  1053. if (reply->status_code != RTSP_STATUS_OK) {
  1054. err = AVERROR_INVALIDDATA;
  1055. goto fail;
  1056. }
  1057. /* now we got the SDP description, we parse it */
  1058. ret = sdp_parse(s, (const char *)content);
  1059. av_freep(&content);
  1060. if (ret < 0) {
  1061. err = AVERROR_INVALIDDATA;
  1062. goto fail;
  1063. }
  1064. do {
  1065. int lower_transport = ff_log2_tab[lower_transport_mask & ~(lower_transport_mask - 1)];
  1066. err = make_setup_request(s, host, port, lower_transport,
  1067. rt->server_type == RTSP_SERVER_REAL ?
  1068. real_challenge : NULL);
  1069. if (err < 0)
  1070. goto fail;
  1071. lower_transport_mask &= ~(1 << lower_transport);
  1072. if (lower_transport_mask == 0 && err == 1) {
  1073. err = AVERROR(FF_NETERROR(EPROTONOSUPPORT));
  1074. goto fail;
  1075. }
  1076. } while (err);
  1077. rt->state = RTSP_STATE_IDLE;
  1078. rt->seek_timestamp = 0; /* default is to start stream at position
  1079. zero */
  1080. if (ap->initial_pause) {
  1081. /* do not start immediately */
  1082. } else {
  1083. if (rtsp_read_play(s) < 0) {
  1084. err = AVERROR_INVALIDDATA;
  1085. goto fail;
  1086. }
  1087. }
  1088. return 0;
  1089. fail:
  1090. rtsp_close_streams(rt);
  1091. av_freep(&content);
  1092. url_close(rt->rtsp_hd);
  1093. return err;
  1094. }
  1095. static int tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1096. uint8_t *buf, int buf_size)
  1097. {
  1098. RTSPState *rt = s->priv_data;
  1099. int id, len, i, ret;
  1100. RTSPStream *rtsp_st;
  1101. #ifdef DEBUG_RTP_TCP
  1102. printf("tcp_read_packet:\n");
  1103. #endif
  1104. redo:
  1105. for(;;) {
  1106. ret = url_readbuf(rt->rtsp_hd, buf, 1);
  1107. #ifdef DEBUG_RTP_TCP
  1108. printf("ret=%d c=%02x [%c]\n", ret, buf[0], buf[0]);
  1109. #endif
  1110. if (ret != 1)
  1111. return -1;
  1112. if (buf[0] == '$')
  1113. break;
  1114. }
  1115. ret = url_readbuf(rt->rtsp_hd, buf, 3);
  1116. if (ret != 3)
  1117. return -1;
  1118. id = buf[0];
  1119. len = AV_RB16(buf + 1);
  1120. #ifdef DEBUG_RTP_TCP
  1121. printf("id=%d len=%d\n", id, len);
  1122. #endif
  1123. if (len > buf_size || len < 12)
  1124. goto redo;
  1125. /* get the data */
  1126. ret = url_readbuf(rt->rtsp_hd, buf, len);
  1127. if (ret != len)
  1128. return -1;
  1129. if (rt->transport == RTSP_TRANSPORT_RDT &&
  1130. ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0)
  1131. return -1;
  1132. /* find the matching stream */
  1133. for(i = 0; i < rt->nb_rtsp_streams; i++) {
  1134. rtsp_st = rt->rtsp_streams[i];
  1135. if (id >= rtsp_st->interleaved_min &&
  1136. id <= rtsp_st->interleaved_max)
  1137. goto found;
  1138. }
  1139. goto redo;
  1140. found:
  1141. *prtsp_st = rtsp_st;
  1142. return len;
  1143. }
  1144. static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
  1145. uint8_t *buf, int buf_size)
  1146. {
  1147. RTSPState *rt = s->priv_data;
  1148. RTSPStream *rtsp_st;
  1149. fd_set rfds;
  1150. int fd1, fd2, fd_max, n, i, ret;
  1151. struct timeval tv;
  1152. for(;;) {
  1153. if (url_interrupt_cb())
  1154. return AVERROR(EINTR);
  1155. FD_ZERO(&rfds);
  1156. fd_max = -1;
  1157. for(i = 0; i < rt->nb_rtsp_streams; i++) {
  1158. rtsp_st = rt->rtsp_streams[i];
  1159. /* currently, we cannot probe RTCP handle because of blocking restrictions */
  1160. rtp_get_file_handles(rtsp_st->rtp_handle, &fd1, &fd2);
  1161. if (fd1 > fd_max)
  1162. fd_max = fd1;
  1163. FD_SET(fd1, &rfds);
  1164. }
  1165. tv.tv_sec = 0;
  1166. tv.tv_usec = 100 * 1000;
  1167. n = select(fd_max + 1, &rfds, NULL, NULL, &tv);
  1168. if (n > 0) {
  1169. for(i = 0; i < rt->nb_rtsp_streams; i++) {
  1170. rtsp_st = rt->rtsp_streams[i];
  1171. rtp_get_file_handles(rtsp_st->rtp_handle, &fd1, &fd2);
  1172. if (FD_ISSET(fd1, &rfds)) {
  1173. ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
  1174. if (ret > 0) {
  1175. *prtsp_st = rtsp_st;
  1176. return ret;
  1177. }
  1178. }
  1179. }
  1180. }
  1181. }
  1182. }
  1183. static int rtsp_read_packet(AVFormatContext *s,
  1184. AVPacket *pkt)
  1185. {
  1186. RTSPState *rt = s->priv_data;
  1187. RTSPStream *rtsp_st;
  1188. int ret, len;
  1189. uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];
  1190. if (rt->server_type == RTSP_SERVER_REAL) {
  1191. int i;
  1192. RTSPHeader reply1, *reply = &reply1;
  1193. enum AVDiscard cache[MAX_STREAMS];
  1194. char cmd[1024];
  1195. for (i = 0; i < s->nb_streams; i++)
  1196. cache[i] = s->streams[i]->discard;
  1197. if (!rt->need_subscription) {
  1198. if (memcmp (cache, rt->real_setup_cache,
  1199. sizeof(enum AVDiscard) * s->nb_streams)) {
  1200. av_strlcatf(cmd, sizeof(cmd),
  1201. "SET_PARAMETER %s RTSP/1.0\r\n"
  1202. "Unsubscribe: %s\r\n",
  1203. s->filename, rt->last_subscription);
  1204. rtsp_send_cmd(s, cmd, reply, NULL);
  1205. if (reply->status_code != RTSP_STATUS_OK)
  1206. return AVERROR_INVALIDDATA;
  1207. rt->need_subscription = 1;
  1208. }
  1209. }
  1210. if (rt->need_subscription) {
  1211. int r, rule_nr, first = 1;
  1212. memcpy(rt->real_setup_cache, cache,
  1213. sizeof(enum AVDiscard) * s->nb_streams);
  1214. rt->last_subscription[0] = 0;
  1215. snprintf(cmd, sizeof(cmd),
  1216. "SET_PARAMETER %s RTSP/1.0\r\n"
  1217. "Subscribe: ",
  1218. s->filename);
  1219. for (i = 0; i < rt->nb_rtsp_streams; i++) {
  1220. rule_nr = 0;
  1221. for (r = 0; r < s->nb_streams; r++) {
  1222. if (s->streams[r]->priv_data == rt->rtsp_streams[i]) {
  1223. if (s->streams[r]->discard != AVDISCARD_ALL) {
  1224. if (!first)
  1225. av_strlcat(rt->last_subscription, ",",
  1226. sizeof(rt->last_subscription));
  1227. ff_rdt_subscribe_rule(
  1228. rt->last_subscription,
  1229. sizeof(rt->last_subscription), i, rule_nr);
  1230. first = 0;
  1231. }
  1232. rule_nr++;
  1233. }
  1234. }
  1235. }
  1236. av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
  1237. rtsp_send_cmd(s, cmd, reply, NULL);
  1238. if (reply->status_code != RTSP_STATUS_OK)
  1239. return AVERROR_INVALIDDATA;
  1240. rt->need_subscription = 0;
  1241. if (rt->state == RTSP_STATE_PLAYING)
  1242. rtsp_read_play (s);
  1243. }
  1244. }
  1245. /* get next frames from the same RTP packet */
  1246. if (rt->cur_tx) {
  1247. if (rt->transport == RTSP_TRANSPORT_RDT)
  1248. ret = ff_rdt_parse_packet(rt->cur_tx, pkt, NULL, 0);
  1249. else
  1250. ret = rtp_parse_packet(rt->cur_tx, pkt, NULL, 0);
  1251. if (ret == 0) {
  1252. rt->cur_tx = NULL;
  1253. return 0;
  1254. } else if (ret == 1) {
  1255. return 0;
  1256. } else {
  1257. rt->cur_tx = NULL;
  1258. }
  1259. }
  1260. /* read next RTP packet */
  1261. redo:
  1262. switch(rt->lower_transport) {
  1263. default:
  1264. case RTSP_LOWER_TRANSPORT_TCP:
  1265. len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1266. break;
  1267. case RTSP_LOWER_TRANSPORT_UDP:
  1268. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  1269. len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));
  1270. if (len >=0 && rtsp_st->tx_ctx && rt->transport == RTSP_TRANSPORT_RTP)
  1271. rtp_check_and_send_back_rr(rtsp_st->tx_ctx, len);
  1272. break;
  1273. }
  1274. if (len < 0)
  1275. return len;
  1276. if (rt->transport == RTSP_TRANSPORT_RDT)
  1277. ret = ff_rdt_parse_packet(rtsp_st->tx_ctx, pkt, buf, len);
  1278. else
  1279. ret = rtp_parse_packet(rtsp_st->tx_ctx, pkt, buf, len);
  1280. if (ret < 0)
  1281. goto redo;
  1282. if (ret == 1) {
  1283. /* more packets may follow, so we save the RTP context */
  1284. rt->cur_tx = rtsp_st->tx_ctx;
  1285. }
  1286. return 0;
  1287. }
  1288. static int rtsp_read_play(AVFormatContext *s)
  1289. {
  1290. RTSPState *rt = s->priv_data;
  1291. RTSPHeader reply1, *reply = &reply1;
  1292. char cmd[1024];
  1293. av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
  1294. if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1295. if (rt->state == RTSP_STATE_PAUSED) {
  1296. snprintf(cmd, sizeof(cmd),
  1297. "PLAY %s RTSP/1.0\r\n",
  1298. s->filename);
  1299. } else {
  1300. snprintf(cmd, sizeof(cmd),
  1301. "PLAY %s RTSP/1.0\r\n"
  1302. "Range: npt=%0.3f-\r\n",
  1303. s->filename,
  1304. (double)rt->seek_timestamp / AV_TIME_BASE);
  1305. }
  1306. rtsp_send_cmd(s, cmd, reply, NULL);
  1307. if (reply->status_code != RTSP_STATUS_OK) {
  1308. return -1;
  1309. }
  1310. }
  1311. rt->state = RTSP_STATE_PLAYING;
  1312. return 0;
  1313. }
  1314. /* pause the stream */
  1315. static int rtsp_read_pause(AVFormatContext *s)
  1316. {
  1317. RTSPState *rt = s->priv_data;
  1318. RTSPHeader reply1, *reply = &reply1;
  1319. char cmd[1024];
  1320. rt = s->priv_data;
  1321. if (rt->state != RTSP_STATE_PLAYING)
  1322. return 0;
  1323. else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
  1324. snprintf(cmd, sizeof(cmd),
  1325. "PAUSE %s RTSP/1.0\r\n",
  1326. s->filename);
  1327. rtsp_send_cmd(s, cmd, reply, NULL);
  1328. if (reply->status_code != RTSP_STATUS_OK) {
  1329. return -1;
  1330. }
  1331. }
  1332. rt->state = RTSP_STATE_PAUSED;
  1333. return 0;
  1334. }
  1335. static int rtsp_read_seek(AVFormatContext *s, int stream_index,
  1336. int64_t timestamp, int flags)
  1337. {
  1338. RTSPState *rt = s->priv_data;
  1339. rt->seek_timestamp = av_rescale_q(timestamp, s->streams[stream_index]->time_base, AV_TIME_BASE_Q);
  1340. switch(rt->state) {
  1341. default:
  1342. case RTSP_STATE_IDLE:
  1343. break;
  1344. case RTSP_STATE_PLAYING:
  1345. if (rtsp_read_play(s) != 0)
  1346. return -1;
  1347. break;
  1348. case RTSP_STATE_PAUSED:
  1349. rt->state = RTSP_STATE_IDLE;
  1350. break;
  1351. }
  1352. return 0;
  1353. }
  1354. static int rtsp_read_close(AVFormatContext *s)
  1355. {
  1356. RTSPState *rt = s->priv_data;
  1357. RTSPHeader reply1, *reply = &reply1;
  1358. char cmd[1024];
  1359. #if 0
  1360. /* NOTE: it is valid to flush the buffer here */
  1361. if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
  1362. url_fclose(&rt->rtsp_gb);
  1363. }
  1364. #endif
  1365. snprintf(cmd, sizeof(cmd),
  1366. "TEARDOWN %s RTSP/1.0\r\n",
  1367. s->filename);
  1368. rtsp_send_cmd(s, cmd, reply, NULL);
  1369. rtsp_close_streams(rt);
  1370. url_close(rt->rtsp_hd);
  1371. return 0;
  1372. }
  1373. #if CONFIG_RTSP_DEMUXER
  1374. AVInputFormat rtsp_demuxer = {
  1375. "rtsp",
  1376. NULL_IF_CONFIG_SMALL("RTSP input format"),
  1377. sizeof(RTSPState),
  1378. rtsp_probe,
  1379. rtsp_read_header,
  1380. rtsp_read_packet,
  1381. rtsp_read_close,
  1382. rtsp_read_seek,
  1383. .flags = AVFMT_NOFILE,
  1384. .read_play = rtsp_read_play,
  1385. .read_pause = rtsp_read_pause,
  1386. };
  1387. #endif
  1388. static int sdp_probe(AVProbeData *p1)
  1389. {
  1390. const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;
  1391. /* we look for a line beginning "c=IN IP4" */
  1392. while (p < p_end && *p != '\0') {
  1393. if (p + sizeof("c=IN IP4") - 1 < p_end && av_strstart(p, "c=IN IP4", NULL))
  1394. return AVPROBE_SCORE_MAX / 2;
  1395. while(p < p_end - 1 && *p != '\n') p++;
  1396. if (++p >= p_end)
  1397. break;
  1398. if (*p == '\r')
  1399. p++;
  1400. }
  1401. return 0;
  1402. }
  1403. #define SDP_MAX_SIZE 8192
  1404. static int sdp_read_header(AVFormatContext *s,
  1405. AVFormatParameters *ap)
  1406. {
  1407. RTSPState *rt = s->priv_data;
  1408. RTSPStream *rtsp_st;
  1409. int size, i, err;
  1410. char *content;
  1411. char url[1024];
  1412. /* read the whole sdp file */
  1413. /* XXX: better loading */
  1414. content = av_malloc(SDP_MAX_SIZE);
  1415. size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);
  1416. if (size <= 0) {
  1417. av_free(content);
  1418. return AVERROR_INVALIDDATA;
  1419. }
  1420. content[size] ='\0';
  1421. sdp_parse(s, content);
  1422. av_free(content);
  1423. /* open each RTP stream */
  1424. for(i=0;i<rt->nb_rtsp_streams;i++) {
  1425. rtsp_st = rt->rtsp_streams[i];
  1426. snprintf(url, sizeof(url), "rtp://%s:%d?localport=%d&ttl=%d",
  1427. inet_ntoa(rtsp_st->sdp_ip),
  1428. rtsp_st->sdp_port,
  1429. rtsp_st->sdp_port,
  1430. rtsp_st->sdp_ttl);
  1431. if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {
  1432. err = AVERROR_INVALIDDATA;
  1433. goto fail;
  1434. }
  1435. if ((err = rtsp_open_transport_ctx(s, rtsp_st)))
  1436. goto fail;
  1437. }
  1438. return 0;
  1439. fail:
  1440. rtsp_close_streams(rt);
  1441. return err;
  1442. }
  1443. static int sdp_read_packet(AVFormatContext *s,
  1444. AVPacket *pkt)
  1445. {
  1446. return rtsp_read_packet(s, pkt);
  1447. }
  1448. static int sdp_read_close(AVFormatContext *s)
  1449. {
  1450. RTSPState *rt = s->priv_data;
  1451. rtsp_close_streams(rt);
  1452. return 0;
  1453. }
  1454. #if CONFIG_SDP_DEMUXER
  1455. AVInputFormat sdp_demuxer = {
  1456. "sdp",
  1457. NULL_IF_CONFIG_SMALL("SDP"),
  1458. sizeof(RTSPState),
  1459. sdp_probe,
  1460. sdp_read_header,
  1461. sdp_read_packet,
  1462. sdp_read_close,
  1463. };
  1464. #endif
  1465. #if CONFIG_REDIR_DEMUXER
  1466. /* dummy redirector format (used directly in av_open_input_file now) */
  1467. static int redir_probe(AVProbeData *pd)
  1468. {
  1469. const char *p;
  1470. p = pd->buf;
  1471. while (redir_isspace(*p))
  1472. p++;
  1473. if (av_strstart(p, "http://", NULL) ||
  1474. av_strstart(p, "rtsp://", NULL))
  1475. return AVPROBE_SCORE_MAX;
  1476. return 0;
  1477. }
  1478. static int redir_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1479. {
  1480. char buf[4096], *q;
  1481. int c;
  1482. AVFormatContext *ic = NULL;
  1483. ByteIOContext *f = s->pb;
  1484. /* parse each URL and try to open it */
  1485. c = url_fgetc(f);
  1486. while (c != URL_EOF) {
  1487. /* skip spaces */
  1488. for(;;) {
  1489. if (!redir_isspace(c))
  1490. break;
  1491. c = url_fgetc(f);
  1492. }
  1493. if (c == URL_EOF)
  1494. break;
  1495. /* record url */
  1496. q = buf;
  1497. for(;;) {
  1498. if (c == URL_EOF || redir_isspace(c))
  1499. break;
  1500. if ((q - buf) < sizeof(buf) - 1)
  1501. *q++ = c;
  1502. c = url_fgetc(f);
  1503. }
  1504. *q = '\0';
  1505. //printf("URL='%s'\n", buf);
  1506. /* try to open the media file */
  1507. if (av_open_input_file(&ic, buf, NULL, 0, NULL) == 0)
  1508. break;
  1509. }
  1510. if (!ic)
  1511. return AVERROR(EIO);
  1512. *s = *ic;
  1513. url_fclose(f);
  1514. return 0;
  1515. }
  1516. AVInputFormat redir_demuxer = {
  1517. "redir",
  1518. NULL_IF_CONFIG_SMALL("Redirector format"),
  1519. 0,
  1520. redir_probe,
  1521. redir_read_header,
  1522. NULL,
  1523. NULL,
  1524. };
  1525. #endif