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.

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