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.

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