rtsp.c 67 KB

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