rtsp.c 67 KB

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